Skip to content

perf: format - #7950

Merged
wangdan-fit2cloud merged 1 commit into
v3from
pr@v3@feat_locals
Nov 16, 2026
Merged

wangdan-fit2cloud merged 1 commit into
v3from
pr@v3@feat_locals

Conversation

@shaohuzhang1

Copy link
Copy Markdown
Contributor

No description provided.

@wangdan-fit2cloud
wangdan-fit2cloud merged commit c20c69a into v3 Nov 16, 2026
6 of 8 checks passed
@wangdan-fit2cloud
wangdan-fit2cloud deleted the pr@v3@feat_locals branch November 16, 2026 11:28
},
}
},
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review of the ESLint rule (import grouping/sorting)

Bugs / Correctness issues

  1. specifiers.filter((s) => !types.includes(s)) is O(n²) — Array.prototype.includes on types is linear. For imports this is negligible, but new Set(types) or a simple specifier.importKind !== 'type' predicate is cleaner. More importantly, in an inline mixed import (e.g. import { A, type B } from 'x'), splitting into two import lines changes semantics only mildly — but the split path runs when node.importKind !== 'type', and the resulting value statement keeps all non-type specifiers. That's fine, but the emitted renderImport(node, values, false, …) reuses code.getText(node.source) and slices trailing text from node.source.range[1] to node.range[1]. If the original had a semicolon after the source (no assertions), that works; if it had import attributes / assertions (assert { type: 'json' }) they are preserved by the slice — good. However the same slice is applied to both the type sub-import and the value sub-import, so an attribute clause would end up duplicated onto the type import (which is illegal). Worth guarding.

  2. inlineTypesOnly detection vs. types filter inconsistency. In check, you decide "all specifiers are type" per-node with node.importKind === 'type' || specifier.importKind === 'type'. In Program, inlineTypesOnly uses node.type === 'ImportDeclaration' while elsewhere you consistently test node.type === 'ImportDeclaration'. Then later again if (node.type === 'ImportDeclaration' && …). Minor redundancy, not a bug. But the comment says such imports are kept in place to preserve side effects — yet groupOf for a pure import type node returns group 1 regardless of whether the source is external/relative. So a import type from ./local will be sorted among other type imports before runtime imports. That matches most conventions; just confirm intent.

  3. length > 150 magic number. The comment says it mirrors .prettierrc.json printWidth, but 150 is hard-coded. If prettier config changes, this silently diverges. Better to read it once (or at least define a named constant const PRINT_WIDTH = 150).

  4. Length calculation is approximate. prefix.length + [...bindings, singleLine].join(', ').length + code.getText(node.source).length + 6 — the + 6 accounts for ' from ' and ';'? ' from ' is 6 chars, yes, plus possibly a trailing ; on another line. This approximation ignores the trailing slice (attributes, comments). For typical cases it's fine; for correctness, compute against the fully rendered string instead:

    const candidate = `${prefix}${[...bindings, singleLine].join(', ')} from ${code.getText(node.source)}${tail}`

    and check candidate.length > PRINT_WIDTH.

  5. compare(left.imported.name ?? left.imported.value, …) doesn't handle ImportNamespaceSpecifier/ImportDefaultSpecifier in named — those never appear there because of the filter, so it's fine, but left.imported may be undefined for import { type Foo } where the middle AST differs across parsers (ImportSpecifier.imported is always present, so OK). Still, ?? '' fallback would be safer.

  6. source regexes assume @/ and /src/ without an anchor. For instance some-lib/src/api/foo (a published package with a src folder reused verbatim) would land in group 3. Rare but possible. Consider anchoring one segment less aggressively or documenting.

  7. path.resolve(...).replaceAll('\\', '/') — path.resolve requires filename to be absolute; context.filename is, so fine. But resolving aliases like @/api/enums cannot go through path.resolve (it produces nonsense paths). The subsequent regex still matches the literal @/api/enums, so behavior is unaffected — but the resolved value is misleading. Split alias handling from relative handling for clarity.

  8. leadingComment check uses comment.loc.end.line >= node.loc.start.line - 1. That treats a comment on the previous line as attached even if separated by a blank line (blank line should de-attach). Also, comments have already been used to reset the block via gap.trim() — if there's a comment in the gap, gap.trim() is non-empty, so leadingComment is effectively redundant there except for the case where the comment sits between the import and the previous statement with no other text. Simplify: rely on gap.trim().

  9. trailingComment for the block boundary. On a trailing same-line comment you check(block) and block = [], then push nothing — meaning the current node starts a fresh block but is never pushed. Next iteration, previous is undefined, so gap is '', treating the next import as adjacent. This can produce wrong grouping across the commented import. Should be:

    if (trailingComment) { check(block); block = []; continue-ish }
    else block.push(node)

    As written, after a trailing-comment import, the following import becomes the start of a new block spanning from that import onwards — which loses the commented import entirely from ordering. Whether intended (freeze position) or not, document it.

  10. range = [nodes[0].range[0], nodes.at(-1).range[1]] — this replaces the whole span including inter-import blank lines. Since entries.map(text).join('\n') emits no blank lines, deliberate blank-line groupings between imports are destroyed. Most format-preserving rules re-emit with one blank line between groups. Confirm this is desired; otherwise you're fighting Prettier/dev expectations.

  11. node.specifiers.length guard — bare import 'x.css' resets the block. Good, but a side-effect import between otherwise-sortable imports means the sort is never re-established after it. Consider starting a fresh block after it (push nothing, then continue — but previous must be undefined so the gap check restarts). Currently that's exactly what happens because block=[]; fine.

  12. Type-only default imports: import type Foo from 'x' — defaults includes Foo, but the specifier's importKind is 'value' on the specifier itself (parser moves it to node level). Fine. But import { type A } where entire list is type triggers inlineTypesOnly, skipping sort — intentional but silently skips these; add a comment.

  13. Missing importKind === 'typeof' handling (TS pre-verbatim syntax). Low risk under modern TS.

  14. Repeated calls to code.getText(specifier) / code.getText(node.source) within loops — cheap but renderImport recomputes code.getText(node.source) twice. Store once.

  15. type in meta is 'layout'. Valid, but import ordering is usually 'suggestion'; both work. For meta.messages, adding an English message alongside is optional — enterprise lint configs often require i18n consistency; the Chinese message is consistent here.

  16. No docs field in meta. Add at least { description } for tooling/introspection.

  17. Schema empty array — fine, but if printWidth were made configurable, schema would need updating.

  18. The fix only reports on nodes[0]. If a fix fails repeatedly ESLint disables autofix for the file. Fine, but multiple report entries per problematic block would give clearer errors. Optional.

Style / minor

  • flatMap producing arrays of objects is fine; readability could be improved by extracting the "split into type/value pair" logic.
  • Comment mentions perm but the sorting regex targets /^@\/permission/. Consistency: rename comment to match, e.g. "permission".
  • frameworks.indexOf(source) inside sort → memoize with a Map for clarity (trivial perf).
  • _entry.text joins with '\n' while original may use \r\n on Windows (code.text is raw). Consider normalizing or joining with the detected EOL from the first node's line break.

Summary of recommended fixes (priority order)

Priority Item
High #9 – block reset after trailing comment drops the node
High #10 – confirm blank-line preservation strategy
High #1 – don't duplicate import attributes to the synthetic type import
Medium #4/#3 – compute length from rendered string; extract PRINT_WIDTH
Medium #8 – simplify double leading-comment checks (blank-line aware)
Low #6 – anchor src/api regex not to match third-party paths
Low Cleanups: named constants, docs, memoized framework rank, remove redundant node.type === 'ImportDeclaration' guards

Overall the rule logic is solid and defensively guards execution order — the main real risks are the trailing-comment block reset and the loss of intentional blank-line grouping.

import { createPortalConversation } from './index'
const applicationSelectorRef = ref<InstanceType<typeof SelectApplicationDrawer>>()
const bundle = createPortalConversation({ openApplicationSelector: () => applicationSelectorRef.value?.open() })

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here's my review of the diff:

Issues

1. Missing file extensions in some imports (inconsistency)

import { MESSAGE_INPUT_KEY } from '../../components/message-input/index'

This is inconsistent with '../index.ts' used later. Mixed extension usage (.ts vs none) can cause resolution differences between bundlers/TS configs, and can break if moduleResolution changes.

2. Import ordering looks auto-sorted but may violate project conventions

The new order (notably placing VIEW_TYPE, createDeviceType) looks like it came from an alphabetical sorter. If the repo uses ESLint import/order with grouping rules, verify this matches the configured groups (external → internal → relative). The sorting also mixes .vue imports with key imports — confirm this is intentional.

3. ./index imported last among relatives (potentially circular)

import { createPortalConversation } from './index'

Importing ./index (the same folder's barrel) after other module-level imports, especially when those modules may themselves import from ./index, risks circular dependencies. This was present before the change, but the reordering didn't address it. Consider importing createPortalConversation directly from its defining file rather than the barrel.

4. InstanceType<typeof ...> without generic discipline

const applicationSelectorRef = ref<InstanceType<typeof SelectApplicationDrawer>>()

Also pre-existing, but since SelectApplicationDrawer.vue uses <script setup>, InstanceType inference depends on defineExpose. Verify the open method is actually exposed; otherwise TS won't error but runtime ?.open() will silently no-op.

5. Unused / missing context (cannot fully validate from diff only)

  • onMounted, onBeforeUnmount, watch, provide are imported but their usage isn't shown — ensure all remain used after reordering (dead imports often accumulate through refactors).
  • FILE_SOURCE_TYPE, AxiosProgressEvent similarly need verification.

Optimization suggestions

  1. Standardize import resolution: pick one convention (either always include .ts/.vue, or never for barrels) and enforce via ESLint.
  2. Replace ./index barrier import with a direct path to avoid circular-dependency risk.
  3. Add explicit type to the ref if defineExpose isn't guaranteed:
    interface ApplicationSelectorExposed { open: () => void }
    const applicationSelectorRef = ref<ApplicationSelectorExposed>()
  4. Run eslint --fix + tsc --noEmit after this purely-reordering change — pure import reorders occasionally surface latent circular deps that previously resolved by accident of order.
  5. Consider unplugin-auto-import or path aliases for the deeply nested ../../ paths (already using @/api/...); mixing @/ and deep relatives reduces readability.

Summary

No functional logic changed — this is a pure import reorder, which is low-risk. The main things to verify: (a) extension consistency, (b) no newly-surfaced circular dependency via ./index, and (c) no accidentally unused imports. Otherwise the change is safe to merge.

import { isSystemResource } from '@/utils/resource-context'

/**
* debug 模式:装配各组件 store。adapter 走 admin(带 applicationId)。

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review of the diff

1. Import reordering (the main change)

The diff mostly reorders imports. This is fine but a few notes:

  • Ordering is inconsistent. Imports aren't sorted alphabetically or by group (types first, then local, then external). If your project has an ESLint import/order rule, this ordering may fail lint. Either let the linter auto-fix or adopt a consistent convention:

    1. Vue core / third-party
    2. @/ aliases
    3. relative imports
    4. type-only imports (or interleaved—pick one scheme).
  • type Ref moved out of the vue import into a standalone import type { Ref } from 'vue'. This is fine and even slightly preferred if you use verbatimModuleSyntax / explicit type imports, but be aware it's now two separate statements against the same module. A common style is:

    import { computed, type Ref } from 'vue'

    Both work; just keep it consistent across files.

  • Mixed import type styles: some are inline (import { computed, type Ref } originally), some are dedicated (import type { ConversationApiAdapter }). Since you're moving to dedicated import type, apply it uniformly (the original in-file Ref was inconsistent with the ConversationApiAdapter style — so the change actually improves consistency here).

2. No functional changes

No logic is altered in the visible hunk — good. Confirm the rest of the file (not shown) isn't affected.

3. Potential optimizations / issues to verify

These aren't in the hunk but worth checking given the imports:

  • Static vs dynamic imports: WorkspaceConversationApi, SystemResourceConversationApi, FileApi, and createConversationListStore / createMessageListStore are all statically imported. If isSystemResource gates which API is used, consider lazy import() for the unused branch to avoid loading both admin workspace and system-resource API modules on every page load. Minor bundle-size win.

  • Tree-shaking: import type changes are tree-safe, but ensure no value is accidentally referenced from type-only imports elsewhere (e.g., using FILE_SOURCE_TYPE as a value vs. type — it's an enum, so it must remain a value import; confirm it isn't a const enum that gets inlined differently).

  • useRoute retained but check usage: If useRoute was kept while other imports were pruned, verify it's still used; otherwise remove it.

  • Duplicate @/api/types encoding: ApplicationDetail is type-only, which is correct.

Summary

The change is safe (import reorganization only). Main recommendations:

  1. Enforce/normalize import ordering via lint to prevent future churn.
  2. Pick one import type convention and apply it everywhere.
  3. Consider lazy-loading the mutually-exclusive API adapters to reduce initial bundle size.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants