@kimesh/auto-import 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":["parseSFC","logger","logger","RegistryBuilder","OxcExportScanner"],"sources":["../src/scanner/reference-detector.ts","../src/script/injector.ts","../src/types/generator.ts","../src/script/plugin.ts","../src/template/resolver.ts","../src/template/plugin.ts","../src/vite/plugin.ts","../src/index.ts"],"sourcesContent":["/**\n * @kimesh/auto-import - Unresolved Reference Detector\n *\n * Detects unresolved identifiers in source code using OXC AST analysis.\n * These are the identifiers that need auto-importing.\n */\n\nimport { parseSync, type Program } from 'oxc-parser';\nimport { parse as parseSFC } from '@vue/compiler-sfc';\nimport type { UnresolvedReference } from '../types';\n\n/**\n * Global identifiers that should not be auto-imported\n */\nconst GLOBALS = new Set([\n // JavaScript globals\n 'undefined', 'null', 'true', 'false', 'NaN', 'Infinity',\n 'Object', 'Array', 'String', 'Number', 'Boolean', 'Symbol', 'BigInt',\n 'Function', 'Date', 'RegExp', 'Error', 'TypeError', 'SyntaxError',\n 'RangeError', 'ReferenceError', 'EvalError', 'URIError',\n 'Map', 'Set', 'WeakMap', 'WeakSet', 'Promise', 'Proxy', 'Reflect',\n 'JSON', 'Math', 'console', 'window', 'document', 'globalThis',\n 'setTimeout', 'setInterval', 'clearTimeout', 'clearInterval',\n 'fetch', 'Request', 'Response', 'Headers', 'URL', 'URLSearchParams',\n 'FormData', 'Blob', 'File', 'FileReader', 'ArrayBuffer', 'DataView',\n 'Int8Array', 'Uint8Array', 'Uint8ClampedArray', 'Int16Array', 'Uint16Array',\n 'Int32Array', 'Uint32Array', 'Float32Array', 'Float64Array', 'BigInt64Array',\n 'BigUint64Array', 'TextEncoder', 'TextDecoder',\n 'alert', 'confirm', 'prompt', 'open', 'close', 'print',\n 'localStorage', 'sessionStorage', 'navigator', 'location', 'history',\n 'performance', 'crypto', 'indexedDB', 'caches',\n 'requestAnimationFrame', 'cancelAnimationFrame',\n 'MutationObserver', 'ResizeObserver', 'IntersectionObserver',\n 'CustomEvent', 'Event', 'EventTarget', 'AbortController', 'AbortSignal',\n 'structuredClone', 'atob', 'btoa', 'encodeURI', 'decodeURI',\n 'encodeURIComponent', 'decodeURIComponent', 'escape', 'unescape',\n 'isFinite', 'isNaN', 'parseFloat', 'parseInt', 'eval',\n\n // Node.js globals (for SSR)\n 'process', 'Buffer', 'global', '__dirname', '__filename',\n 'require', 'module', 'exports',\n\n // TypeScript utilities\n 'Partial', 'Required', 'Readonly', 'Record', 'Pick', 'Omit',\n 'Exclude', 'Extract', 'NonNullable', 'Parameters', 'ReturnType',\n 'InstanceType', 'ThisType', 'Awaited', 'Uppercase', 'Lowercase',\n 'Capitalize', 'Uncapitalize',\n\n // Vue script setup compiler macros\n 'defineProps', 'defineEmits', 'defineExpose', 'defineOptions',\n 'defineSlots', 'defineModel', 'withDefaults',\n]);\n\n/**\n * Reference detector using scope analysis\n */\nexport class ReferenceDetector {\n /**\n * Detect unresolved references in TypeScript/JavaScript code\n */\n detectInScript(code: string, filePath: string): UnresolvedReference[] {\n try {\n const result = parseSync(filePath, code, {\n sourceType: 'module',\n });\n\n if (result.errors.length > 0) {\n return [];\n }\n\n return this.detectInAST(result.program);\n } catch {\n return [];\n }\n }\n\n /**\n * Detect unresolved references in Vue SFC\n */\n detectInVue(code: string, filePath: string): UnresolvedReference[] {\n try {\n const { descriptor, errors } = parseSFC(code, { filename: filePath });\n\n if (errors.length > 0) {\n return [];\n }\n\n const refs: UnresolvedReference[] = [];\n\n // Check <script setup>\n if (descriptor.scriptSetup) {\n const scriptRefs = this.detectInScript(\n descriptor.scriptSetup.content,\n filePath + '.setup.ts'\n );\n refs.push(...scriptRefs);\n }\n\n // Check regular <script>\n if (descriptor.script) {\n const scriptRefs = this.detectInScript(\n descriptor.script.content,\n filePath + '.ts'\n );\n refs.push(...scriptRefs);\n }\n\n // Note: Template references would need separate handling\n // as they use different resolution rules\n\n return refs;\n } catch {\n return [];\n }\n }\n\n /**\n * Detect unresolved references in parsed AST\n */\n private detectInAST(program: Program): UnresolvedReference[] {\n const declarations = new Set<string>();\n const references: UnresolvedReference[] = [];\n\n // First pass: collect all declarations\n this.collectDeclarations(program, declarations);\n\n // Second pass: find unresolved references\n this.findUnresolvedReferences(program, declarations, references);\n\n return references;\n }\n\n /**\n * Collect all declared identifiers in the scope\n */\n private collectDeclarations(node: any, declarations: Set<string>): void {\n if (!node || typeof node !== 'object') return;\n\n switch (node.type) {\n // Variable declarations\n case 'VariableDeclaration':\n for (const decl of node.declarations || []) {\n this.collectPatternNames(decl.id, declarations);\n }\n break;\n\n // Function declarations\n case 'FunctionDeclaration':\n if (node.id?.name) {\n declarations.add(node.id.name);\n }\n // Collect parameters\n for (const param of node.params || []) {\n this.collectPatternNames(param, declarations);\n }\n break;\n\n // Arrow/function expressions with assigned name\n case 'VariableDeclarator':\n this.collectPatternNames(node.id, declarations);\n break;\n\n // Class declarations\n case 'ClassDeclaration':\n if (node.id?.name) {\n declarations.add(node.id.name);\n }\n break;\n\n // Import declarations\n case 'ImportDeclaration':\n for (const spec of node.specifiers || []) {\n if (spec.local?.name) {\n declarations.add(spec.local.name);\n }\n }\n break;\n\n // Type declarations\n case 'TSInterfaceDeclaration':\n case 'TSTypeAliasDeclaration':\n case 'TSEnumDeclaration':\n if (node.id?.name) {\n declarations.add(node.id.name);\n }\n break;\n\n // Catch clause parameter\n case 'CatchClause':\n if (node.param) {\n this.collectPatternNames(node.param, declarations);\n }\n break;\n\n // For-in/of declarations\n case 'ForInStatement':\n case 'ForOfStatement':\n if (node.left?.type === 'VariableDeclaration') {\n this.collectDeclarations(node.left, declarations);\n }\n break;\n }\n\n // Recurse into children\n for (const key of Object.keys(node)) {\n if (key === 'type' || key === 'start' || key === 'end') continue;\n\n const child = node[key];\n if (Array.isArray(child)) {\n for (const item of child) {\n this.collectDeclarations(item, declarations);\n }\n } else if (child && typeof child === 'object') {\n this.collectDeclarations(child, declarations);\n }\n }\n }\n\n /**\n * Collect names from binding patterns\n */\n private collectPatternNames(pattern: any, names: Set<string>): void {\n if (!pattern) return;\n\n switch (pattern.type) {\n case 'Identifier':\n names.add(pattern.name);\n break;\n\n case 'ObjectPattern':\n for (const prop of pattern.properties || []) {\n if (prop.type === 'RestElement') {\n this.collectPatternNames(prop.argument, names);\n } else {\n this.collectPatternNames(prop.value || prop.key, names);\n }\n }\n break;\n\n case 'ArrayPattern':\n for (const element of pattern.elements || []) {\n if (element) {\n this.collectPatternNames(element, names);\n }\n }\n break;\n\n case 'RestElement':\n this.collectPatternNames(pattern.argument, names);\n break;\n\n case 'AssignmentPattern':\n this.collectPatternNames(pattern.left, names);\n break;\n }\n }\n\n /**\n * Find references to undeclared identifiers\n */\n private findUnresolvedReferences(\n node: any,\n declarations: Set<string>,\n references: UnresolvedReference[]\n ): void {\n if (!node || typeof node !== 'object') return;\n\n // Check for identifier references\n if (node.type === 'Identifier' && node.name) {\n const name = node.name;\n\n // Skip if it's a declaration, global, or property access\n if (\n !declarations.has(name) &&\n !GLOBALS.has(name) &&\n !this.isPropertyAccess(node) &&\n !this.isPropertyKey(node) &&\n !this.isLabelReference(node)\n ) {\n // Check if it's a type reference\n const isType = this.isTypeContext(node);\n\n // Avoid duplicates\n const existing = references.find(\n (r) => r.name === name && r.start === node.start\n );\n if (!existing) {\n references.push({\n name,\n start: node.start,\n end: node.end,\n isType,\n });\n }\n }\n }\n\n // Recurse into children (skip certain properties)\n for (const key of Object.keys(node)) {\n if (this.shouldSkipProperty(key)) continue;\n\n const child = node[key];\n if (Array.isArray(child)) {\n for (const item of child) {\n this.findUnresolvedReferences(item, declarations, references);\n }\n } else if (child && typeof child === 'object') {\n this.findUnresolvedReferences(child, declarations, references);\n }\n }\n }\n\n /**\n * Check if identifier is a property access (obj.prop)\n */\n private isPropertyAccess(node: any): boolean {\n const parent = node._parent;\n return (\n parent?.type === 'MemberExpression' &&\n parent.property === node &&\n !parent.computed\n );\n }\n\n /**\n * Check if identifier is a property key ({ key: value })\n */\n private isPropertyKey(node: any): boolean {\n const parent = node._parent;\n return (\n parent?.type === 'Property' &&\n parent.key === node &&\n !parent.computed\n );\n }\n\n /**\n * Check if identifier is a label reference\n */\n private isLabelReference(node: any): boolean {\n const parent = node._parent;\n return (\n parent?.type === 'LabeledStatement' ||\n parent?.type === 'BreakStatement' ||\n parent?.type === 'ContinueStatement'\n );\n }\n\n /**\n * Check if identifier is in type context\n */\n private isTypeContext(node: any): boolean {\n const parent = node._parent;\n return (\n parent?.type === 'TSTypeReference' ||\n parent?.type === 'TSQualifiedName' ||\n parent?.type === 'TSTypeQuery' ||\n parent?.type === 'TSImportType'\n );\n }\n\n /**\n * Properties to skip when recursing\n */\n private shouldSkipProperty(key: string): boolean {\n return (\n key === 'type' ||\n key === 'start' ||\n key === 'end' ||\n key === '_parent' ||\n key === 'loc' ||\n key === 'range'\n );\n }\n}\n","/**\n * @kimesh/auto-import - Script Import Injector\n *\n * Handles injecting import statements into script code.\n */\n\nimport MagicString from \"magic-string\";\nimport type { ImportEntry } from \"../types\";\n\nexport interface InjectionResult {\n code: string;\n map: ReturnType<MagicString[\"generateMap\"]>;\n count: number;\n}\n\nexport class ImportInjector {\n inject(\n code: string,\n imports: ImportEntry[],\n isVue: boolean\n ): InjectionResult | null {\n if (imports.length === 0) return null;\n\n const s = new MagicString(code);\n const importStatements = this.generateImportStatements(imports);\n const insertPoint = this.findImportInsertionPoint(code, isVue);\n s.appendLeft(insertPoint, \"\\n\" + importStatements + \"\\n\");\n\n return {\n code: s.toString(),\n map: s.generateMap({ hires: true }),\n count: imports.length,\n };\n }\n\n generateImportStatements(imports: ImportEntry[]): string {\n const groups = this.groupImportsBySource(imports);\n const statements: string[] = [];\n\n for (const [source, entries] of groups) {\n const { defaultImports, namedImports, typeImports } =\n this.categorizeImports(entries);\n\n const parts: string[] = [];\n if (defaultImports.length > 0) parts.push(defaultImports[0]);\n if (namedImports.length > 0) parts.push(`{ ${namedImports.join(\", \")} }`);\n\n if (parts.length > 0) {\n statements.push(`import ${parts.join(\", \")} from '${source}';`);\n }\n\n if (typeImports.length > 0) {\n statements.push(\n `import type { ${typeImports.join(\", \")} } from '${source}';`\n );\n }\n }\n\n return statements.join(\"\\n\");\n }\n\n private groupImportsBySource(imports: ImportEntry[]): Map<string, ImportEntry[]> {\n const groups = new Map<string, ImportEntry[]>();\n for (const entry of imports) {\n const existing = groups.get(entry.from) ?? [];\n existing.push(entry);\n groups.set(entry.from, existing);\n }\n return groups;\n }\n\n private categorizeImports(entries: ImportEntry[]): {\n defaultImports: string[];\n namedImports: string[];\n typeImports: string[];\n } {\n const defaultImports: string[] = [];\n const namedImports: string[] = [];\n const typeImports: string[] = [];\n\n for (const entry of entries) {\n const importName = entry.as ? `${entry.name} as ${entry.as}` : entry.name;\n\n if (entry.isDefault) {\n defaultImports.push(entry.as ?? entry.name);\n } else if (entry.isType) {\n typeImports.push(importName);\n } else {\n namedImports.push(importName);\n }\n }\n\n return { defaultImports, namedImports, typeImports };\n }\n\n findImportInsertionPoint(code: string, isVue: boolean): number {\n if (isVue) {\n return this.findVueScriptInsertionPoint(code);\n }\n return this.findJsInsertionPoint(code);\n }\n\n private findVueScriptInsertionPoint(code: string): number {\n const scriptMatch = code.match(/<script(\\s+[^>]*)?>|<script\\s+setup[^>]*>/i);\n if (!scriptMatch || scriptMatch.index === undefined) return 0;\n\n const insertPoint = scriptMatch.index + scriptMatch[0].length;\n const afterScript = code.slice(insertPoint);\n const importMatch = afterScript.match(/^(\\s*\\n?\\s*import\\s+.*?['\"].*?['\"];?\\s*)+/);\n\n return importMatch ? insertPoint + importMatch[0].length : insertPoint;\n }\n\n private findJsInsertionPoint(code: string): number {\n const importRegex = /^import\\s+.*?['\"].*?['\"];?\\s*$/gm;\n let lastImportEnd = 0;\n let match;\n\n while ((match = importRegex.exec(code)) !== null) {\n lastImportEnd = match.index + match[0].length;\n }\n\n if (lastImportEnd > 0) return lastImportEnd;\n\n const useStrictMatch = code.match(/^(['\"]use strict['\"];?\\s*)/);\n if (useStrictMatch) return useStrictMatch[0].length;\n\n const shebangMatch = code.match(/^#!.*\\n/);\n if (shebangMatch) return shebangMatch[0].length;\n\n return 0;\n }\n\n extractExistingImports(code: string, isVue: boolean): Set<string> {\n const imported = new Set<string>();\n\n const scriptContent = isVue ? this.extractVueScriptContent(code) : code;\n if (!scriptContent) return imported;\n\n const importRegex =\n /import\\s+(?:type\\s+)?(?:(\\w+)\\s*,?\\s*)?(?:\\{([^}]*)\\})?\\s*from\\s*['\"][^'\"]+['\"]/g;\n\n let match;\n while ((match = importRegex.exec(scriptContent)) !== null) {\n if (match[1]) imported.add(match[1]);\n\n if (match[2]) {\n for (const name of match[2].split(\",\")) {\n const trimmed = name.trim();\n if (!trimmed) continue;\n\n const asMatch = trimmed.match(/(\\w+)\\s+as\\s+(\\w+)/);\n imported.add(asMatch ? asMatch[2] : trimmed);\n }\n }\n }\n\n return imported;\n }\n\n private extractVueScriptContent(code: string): string | null {\n const scriptMatch = code.match(/<script[^>]*>([\\s\\S]*?)<\\/script>/gi);\n if (!scriptMatch) return null;\n\n return scriptMatch\n .map((m) => {\n const content = m.match(/<script[^>]*>([\\s\\S]*?)<\\/script>/i);\n return content ? content[1] : \"\";\n })\n .join(\"\\n\");\n }\n}\n","/**\n * @kimesh/auto-import - Type Declaration Generator\n *\n * Generates .d.ts files for auto-imported modules.\n */\n\nimport * as fs from \"node:fs\";\nimport * as path from \"pathe\";\nimport { consola } from \"consola\";\nimport type { ImportRegistry, ImportEntry } from \"../types\";\n\nconst logger = consola.withTag(\"kimesh:auto-import:types\");\n\nexport async function generateDtsFiles(\n registry: ImportRegistry,\n outputDir: string\n): Promise<void> {\n fs.mkdirSync(outputDir, { recursive: true });\n\n writeFile(outputDir, \"auto-imports.d.ts\", generateAutoImportsDts(registry));\n\n const presetComponents = generatePresetComponentsDts(registry);\n if (presetComponents) {\n writeFile(outputDir, \"kimesh-components.d.ts\", presetComponents);\n }\n\n writeFile(outputDir, \".eslintrc-auto-import.json\", generateEslintGlobals(registry));\n}\n\nfunction writeFile(outputDir: string, filename: string, content: string): void {\n const filePath = path.join(outputDir, filename);\n fs.writeFileSync(filePath, content, \"utf-8\");\n logger.debug(`Generated: ${filePath}`);\n}\n\nfunction generateAutoImportsDts(registry: ImportRegistry): string {\n const header = [\n \"/* eslint-disable */\",\n \"/* prettier-ignore */\",\n \"// @ts-nocheck\",\n \"// noinspection JSUnusedGlobalSymbols\",\n \"\",\n \"// Auto-generated by @kimesh/auto-import\",\n \"// DO NOT EDIT - changes will be overwritten\",\n \"\",\n \"export {}\",\n \"\",\n \"declare global {\",\n ];\n\n const groups = groupImportsBySource(registry.imports, [\n \"composable\",\n \"utility\",\n \"preset\",\n \"store\",\n ]);\n\n const body: string[] = [];\n for (const [source, entries] of groups) {\n body.push(` // ${source}`);\n for (const entry of entries) {\n body.push(formatGlobalDeclaration(entry));\n }\n body.push(\"\");\n }\n\n return [...header, ...body, \"}\"].join(\"\\n\");\n}\n\nfunction formatGlobalDeclaration(entry: ImportEntry): string {\n const comment = entry.layer !== \"app\" ? ` // from ${entry.layer}` : \"\";\n\n if (entry.isType) {\n return ` type ${entry.name} = import('${entry.from}').${entry.name}${comment}`;\n }\n if (entry.isDefault) {\n return ` const ${entry.name}: typeof import('${entry.from}').default${comment}`;\n }\n return ` const ${entry.name}: typeof import('${entry.from}').${entry.name}${comment}`;\n}\n\nfunction generateEslintGlobals(registry: ImportRegistry): string {\n const globals: Record<string, \"readonly\"> = {};\n\n for (const [name, entry] of registry.imports) {\n if (!entry.isType) {\n globals[name] = \"readonly\";\n }\n }\n\n return JSON.stringify({ globals }, null, 2);\n}\n\nconst EXCLUDED_TYPE_NAMES = new Set([\n // Vue types\n 'Ref', 'ComputedRef', 'UnwrapRef', 'ShallowRef', 'WritableComputedRef',\n 'ToRefs', 'PropType', 'Component', 'ComponentPublicInstance', 'VNode',\n // Vue Router types\n 'RouteLocationNormalized', 'RouteLocationNormalizedLoaded', 'RouteRecordRaw',\n 'NavigationGuard', 'NavigationFailure', 'Router', 'RouteLocation',\n 'LocationQuery', 'RouteParams',\n]);\n\nfunction generatePresetComponentsDts(registry: ImportRegistry): string | null {\n const presetComponents = [...registry.components.entries()]\n .filter(([name, entry]) =>\n entry.type === \"preset\" &&\n /^[A-Z][a-zA-Z0-9]*$/.test(name) &&\n !entry.isType &&\n !EXCLUDED_TYPE_NAMES.has(name)\n )\n .sort((a, b) => a[0].localeCompare(b[0]));\n\n if (presetComponents.length === 0) return null;\n\n const header = [\n \"/* eslint-disable */\",\n \"// @ts-nocheck\",\n \"// Generated by @kimesh/auto-import\",\n \"// Preset components for Vue templates\",\n \"// biome-ignore lint: disable\",\n \"export {}\",\n \"\",\n \"/* prettier-ignore */\",\n \"declare module 'vue' {\",\n \" export interface GlobalComponents {\",\n ];\n\n const componentDeclarations = presetComponents.map(([name, entry]) => {\n const importPath = entry.isDefault\n ? `typeof import('${entry.from}').default`\n : `typeof import('${entry.from}')['${entry.name}']`;\n return ` ${name}: ${importPath}`;\n });\n\n return [...header, ...componentDeclarations, \" }\", \"}\"].join(\"\\n\");\n}\n\nfunction groupImportsBySource(\n imports: Map<string, ImportEntry>,\n types: string[]\n): Map<string, ImportEntry[]> {\n const groups = new Map<string, ImportEntry[]>();\n\n for (const [, entry] of imports) {\n if (!types.includes(entry.type)) continue;\n\n const existing = groups.get(entry.from) ?? [];\n existing.push(entry);\n groups.set(entry.from, existing);\n }\n\n for (const entries of groups.values()) {\n entries.sort((a, b) => {\n if (a.isType !== b.isType) return a.isType ? 1 : -1;\n return a.name.localeCompare(b.name);\n });\n }\n\n return groups;\n}\n\nexport function generateSourceDts(source: string, entries: ImportEntry[]): string {\n const lines: string[] = [\n \"// Auto-generated by @kimesh/auto-import\",\n \"\",\n `// Exports from: ${source}`,\n \"\",\n ];\n\n const defaultExports = entries.filter((e) => e.isDefault);\n const namedExports = entries.filter((e) => !e.isDefault && !e.isType);\n const typeExports = entries.filter((e) => e.isType);\n\n if (defaultExports.length > 0) {\n lines.push(`export { default as ${defaultExports[0].name} } from '${source}'`);\n }\n\n if (namedExports.length > 0) {\n const names = namedExports.map((e) => (e.as ? `${e.name} as ${e.as}` : e.name));\n lines.push(`export { ${names.join(\", \")} } from '${source}'`);\n }\n\n if (typeExports.length > 0) {\n const names = typeExports.map((e) => (e.as ? `${e.name} as ${e.as}` : e.name));\n lines.push(`export type { ${names.join(\", \")} } from '${source}'`);\n }\n\n return lines.join(\"\\n\");\n}\n","/**\n * @kimesh/auto-import - Script Transform Plugin\n *\n * Vite plugin for script-level auto-import.\n * Handles auto-importing composables, utilities, and presets in <script> blocks.\n */\n\nimport type { Plugin, ResolvedConfig, ViteDevServer } from \"vite\";\nimport * as fs from \"node:fs\";\nimport * as path from \"pathe\";\nimport { consola } from \"consola\";\nimport { ReferenceDetector } from \"./detector\";\nimport { ImportInjector } from \"./injector\";\nimport { RegistryBuilder } from \"../registry/builder\";\nimport { collectExistingDirectories } from \"../registry/utils\";\nimport { generateDtsFiles } from \"../types/generator\";\nimport type {\n AutoImportPluginOptions,\n ImportRegistry,\n ImportEntry,\n LayerAutoImportSource,\n ResolvedLayerInfo,\n} from \"../types\";\n\nconst logger = consola.withTag(\"kimesh:auto-import:script\");\n\nconst DEFAULT_INCLUDE = [/\\.[jt]sx?$/, /\\.vue$/, /\\.vue\\?vue/];\nconst DEFAULT_EXCLUDE = [/node_modules/, /\\.d\\.ts$/];\n\nexport interface ScriptPluginOptions extends AutoImportPluginOptions {\n onRegistryUpdate?: (registry: ImportRegistry) => void;\n}\n\nexport interface ScriptPluginState {\n registry: ImportRegistry | null;\n config: ResolvedConfig | null;\n isBuilding: boolean;\n}\n\nfunction debounce<T extends (...args: unknown[]) => void>(\n fn: T,\n ms: number\n): T {\n let timeoutId: ReturnType<typeof setTimeout> | null = null;\n return ((...args: unknown[]) => {\n if (timeoutId) clearTimeout(timeoutId);\n timeoutId = setTimeout(() => fn(...args), ms);\n }) as T;\n}\n\nexport function createScriptPlugin(options: ScriptPluginOptions): Plugin {\n const {\n sources: staticSources,\n getSources,\n layers: staticLayers = [],\n getLayers,\n include = DEFAULT_INCLUDE,\n exclude = DEFAULT_EXCLUDE,\n dts = \".kimesh\",\n debug = false,\n onRegistryUpdate,\n } = options;\n\n const builder = new RegistryBuilder();\n const detector = new ReferenceDetector();\n const injector = new ImportInjector();\n let registry: ImportRegistry | null = null;\n let config: ResolvedConfig;\n let isBuilding = false;\n let resolvedSources: typeof staticSources = undefined;\n\n function resolveSources(): LayerAutoImportSource[] {\n if (resolvedSources !== undefined) {\n return resolvedSources;\n }\n resolvedSources = getSources ? getSources() : (staticSources ?? []);\n return resolvedSources;\n }\n\n function resolveLayers(): ResolvedLayerInfo[] {\n return getLayers ? getLayers() : staticLayers;\n }\n\n function getRegistry(): ImportRegistry | null {\n return registry;\n }\n\n function resolveDtsDir(): string {\n return path.isAbsolute(dts as string)\n ? (dts as string)\n : path.join(config.root, dts as string);\n }\n\n async function generateDtsForLayers(reg: ImportRegistry): Promise<void> {\n if (dts === false) return;\n\n const hostDtsDir = resolveDtsDir();\n await generateDtsFiles(reg, hostDtsDir);\n logger.debug(`Generated type declarations in ${hostDtsDir}`);\n\n const resolvedLayerList = resolveLayers();\n for (const layer of resolvedLayerList) {\n if (layer.isApp) continue;\n\n // Resolve real path (handle symlinks in node_modules)\n let layerRoot = layer.path;\n try {\n layerRoot = fs.realpathSync(layer.path);\n } catch {\n // Ignore if path doesn't exist\n }\n\n const layerKimeshDir = path.join(layerRoot, \".kimesh\");\n try {\n fs.mkdirSync(layerKimeshDir, { recursive: true });\n await generateDtsFiles(reg, layerKimeshDir);\n logger.debug(`Generated type declarations for layer: ${layer.name} at ${layerKimeshDir}`);\n } catch (err) {\n logger.warn(`Failed to generate .d.ts for layer ${layer.name}: ${err}`);\n }\n }\n }\n\n async function buildAndLogRegistry(): Promise<void> {\n const startTime = performance.now();\n const sources = resolveSources();\n registry = await builder.build(sources);\n const elapsed = performance.now() - startTime;\n\n logger.info(\n `Script auto-import registry built in ${elapsed.toFixed(1)}ms`\n );\n logger.info(\n ` ${registry.stats.composablesCount} composables, ` +\n `${registry.stats.utilitiesCount} utilities, ` +\n `${registry.stats.presetsCount} preset imports`\n );\n\n if (registry.conflicts.length > 0) {\n logger.warn(` ${registry.conflicts.length} conflicts detected`);\n }\n\n await generateDtsForLayers(registry);\n\n onRegistryUpdate?.(registry);\n }\n\n const plugin = {\n name: \"kimesh:auto-import:script\",\n enforce: \"pre\" as const,\n getRegistry,\n\n configResolved(resolvedConfig) {\n config = resolvedConfig;\n isBuilding = config.command === \"build\";\n },\n\n async buildStart() {\n await buildAndLogRegistry();\n },\n\n configureServer(server: ViteDevServer) {\n if (isBuilding) return;\n\n const sources = resolveSources();\n const watchDirs = getWatchDirs(sources);\n\n if (watchDirs.length === 0) {\n logger.debug(\"No directories to watch for auto-import\");\n return;\n }\n\n logger.debug(\n `Watching ${watchDirs.length} directories for auto-import changes`\n );\n\n const rebuildRegistry = async (): Promise<void> => {\n const startTime = performance.now();\n builder.clearCache();\n\n const sources = resolveSources();\n registry = await builder.build(sources);\n const elapsed = performance.now() - startTime;\n\n logger.info(`Auto-import registry rebuilt in ${elapsed.toFixed(1)}ms`);\n logger.info(\n ` ${registry.stats.componentsCount} components, ` +\n `${registry.stats.composablesCount} composables, ` +\n `${registry.stats.utilitiesCount} utilities`\n );\n\n await generateDtsForLayers(registry);\n\n onRegistryUpdate?.(registry);\n };\n\n const debouncedRebuild = debounce(rebuildRegistry, 300);\n\n const isWatchedFile = (file: string): boolean => {\n const ext = path.extname(file);\n const validExtensions = [\".ts\", \".js\", \".tsx\", \".jsx\", \".mts\", \".mjs\", \".vue\"];\n if (!validExtensions.includes(ext)) return false;\n return watchDirs.some((dir) => file.startsWith(dir));\n };\n\n server.watcher.on(\"add\", (file) => {\n if (!isWatchedFile(file)) return;\n logger.debug(`New file detected: ${path.relative(config.root, file)}`);\n debouncedRebuild();\n });\n\n server.watcher.on(\"unlink\", (file) => {\n if (!isWatchedFile(file)) return;\n logger.debug(`File deleted: ${path.relative(config.root, file)}`);\n debouncedRebuild();\n });\n\n server.watcher.on(\"change\", (file) => {\n if (!isWatchedFile(file)) return;\n logger.debug(`File changed: ${path.relative(config.root, file)}`);\n builder.invalidate(file);\n debouncedRebuild();\n });\n },\n\n transform(code, id) {\n if (!registry) return null;\n if (!shouldTransform(id, include, exclude)) return null;\n\n const startTime = performance.now();\n const isVue = id.endsWith(\".vue\") || id.includes(\".vue?\");\n const refs = isVue\n ? detector.detectInVue(code, id)\n : detector.detectInScript(code, id);\n\n if (refs.length === 0) return null;\n\n const existingImports = injector.extractExistingImports(code, isVue);\n const imports: ImportEntry[] = [];\n const matched = new Set<string>();\n\n for (const ref of refs) {\n if (matched.has(ref.name)) continue;\n if (existingImports.has(ref.name)) continue;\n\n const entry = registry.imports.get(ref.name);\n if (!entry) continue;\n if (ref.isType && !entry.isType) continue;\n\n if (registry.components.has(ref.name)) {\n if (debug) {\n logger.debug(`Skipping component ${ref.name} for template plugin`);\n }\n continue;\n }\n\n imports.push(entry);\n matched.add(ref.name);\n }\n\n if (imports.length === 0) return null;\n\n const result = injector.inject(code, imports, isVue);\n if (!result) return null;\n\n const elapsed = performance.now() - startTime;\n\n if (debug) {\n logger.debug(\n `[${elapsed.toFixed(1)}ms] ${id}: injected ${imports.length} imports`\n );\n }\n\n return {\n code: result.code,\n map: result.map,\n };\n },\n\n handleHotUpdate({ file }) {\n const relativePath = path.relative(config.root, file);\n const sources = resolveSources();\n\n for (const source of sources) {\n if (file.startsWith(source.layerPath)) {\n logger.debug(`HMR update: ${relativePath}`);\n break;\n }\n }\n },\n } satisfies Plugin & { getRegistry: () => ImportRegistry | null };\n\n return plugin;\n}\n\nfunction getWatchDirs(sources: LayerAutoImportSource[]): string[] {\n const dirs: string[] = [];\n\n for (const source of sources) {\n const { layerPath, config: sourceConfig } = source;\n const dirConfigs = [\n sourceConfig.components?.dirs ?? [\"components\"],\n sourceConfig.composables?.dirs ?? [\"composables\"],\n sourceConfig.utils?.dirs ?? [\"utils\"],\n sourceConfig.stores?.dirs ?? [\"stores\"],\n ];\n\n for (const configDirs of dirConfigs) {\n dirs.push(...collectExistingDirectories(layerPath, configDirs));\n }\n }\n\n return [...new Set(dirs)];\n}\n\nfunction matchesPattern(id: string, pattern: string | RegExp): boolean {\n if (typeof pattern === \"string\") {\n return id.includes(pattern);\n }\n return pattern.test(id);\n}\n\nfunction shouldTransform(\n id: string,\n include: Array<string | RegExp>,\n exclude: Array<string | RegExp>\n): boolean {\n if (exclude.some((pattern) => matchesPattern(id, pattern))) {\n return false;\n }\n return include.some((pattern) => matchesPattern(id, pattern));\n}\n\nexport default createScriptPlugin;\n","/**\n * @kimesh/auto-import - Kimesh Component Resolver\n *\n * Custom resolver for unplugin-vue-components that uses\n * the Kimesh import registry to resolve components.\n */\n\nimport type { ComponentResolver } from \"unplugin-vue-components\";\nimport { consola } from \"consola\";\nimport type { ImportRegistry, ImportEntry } from \"../types\";\n\nconst logger = consola.withTag(\"kimesh:auto-import:template:resolver\");\n\nexport interface KimeshResolverOptions {\n getRegistry: () => ImportRegistry | null;\n debug?: boolean;\n}\n\nfunction looksLikeComponent(name: string): boolean {\n return /^[A-Z][a-zA-Z0-9]*$/.test(name);\n}\n\nfunction createResolvedComponent(entry: ImportEntry, name: string) {\n return {\n name: entry.isDefault ? \"default\" : entry.name,\n from: entry.from,\n as: name,\n };\n}\n\nexport function createKimeshResolver(\n options: KimeshResolverOptions\n): ComponentResolver {\n const { getRegistry, debug = false } = options;\n\n return {\n type: \"component\",\n resolve: (name: string) => {\n const registry = getRegistry();\n if (!registry) {\n if (debug) logger.debug(`Registry not ready, skipping ${name}`);\n return undefined;\n }\n\n if (debug) {\n logger.debug(`Resolving component: ${name}`);\n logger.debug(` Components map size: ${registry.components.size}`);\n logger.debug(` Imports map size: ${registry.imports.size}`);\n }\n\n const componentEntry = registry.components.get(name);\n if (componentEntry) {\n if (debug) {\n logger.debug(\n `Resolved component ${name} from ${componentEntry.from} (layer: ${componentEntry.layer})`\n );\n }\n return createResolvedComponent(componentEntry, name);\n }\n\n const importEntry = registry.imports.get(name);\n if (!importEntry) {\n if (debug) logger.debug(`${name} not found in imports map`);\n return undefined;\n }\n\n if (debug) logger.debug(`Found ${name} in imports, type: ${importEntry.type}`);\n\n const isResolvable =\n importEntry.type === \"component\" ||\n (importEntry.type === \"preset\" && looksLikeComponent(name));\n\n if (isResolvable) {\n if (debug) {\n logger.debug(\n `Resolved component ${name} from ${importEntry.from} (layer: ${importEntry.layer})`\n );\n }\n return {\n name: importEntry.isDefault ? \"default\" : name,\n from: importEntry.from,\n as: name,\n };\n }\n\n return undefined;\n },\n };\n}\n\nexport default createKimeshResolver;\n","/**\n * @kimesh/auto-import - Template Auto-Import Plugin\n *\n * Vite plugin for template-level component auto-import.\n * Wraps unplugin-vue-components with Kimesh's custom resolver.\n */\n\nimport type { Plugin } from \"vite\";\nimport Components from \"unplugin-vue-components/vite\";\nimport MagicString from \"magic-string\";\nimport * as path from \"pathe\";\nimport { createKimeshResolver } from \"./resolver\";\nimport type { ImportRegistry } from \"../types\";\n\nexport interface TemplatePluginOptions {\n getRegistry: () => ImportRegistry | null;\n dts?: string | false;\n debug?: boolean;\n}\n\nfunction resolveDtsPath(dts: string | false | undefined): string | boolean {\n if (dts === false) return false;\n if (typeof dts === \"string\") return path.join(dts, \"components.d.ts\");\n return true;\n}\n\nexport function createTemplatePlugin(options: TemplatePluginOptions): Plugin {\n const { getRegistry, dts, debug = false } = options;\n\n const basePlugin = Components({\n resolvers: [createKimeshResolver({ getRegistry, debug })],\n dirs: [],\n dts: resolveDtsPath(dts),\n include: [/\\.vue$/, /\\.vue\\?vue/],\n exclude: [/[\\\\/]node_modules[\\\\/]/],\n deep: true,\n directoryAsNamespace: false,\n collapseSamePrefixes: true,\n version: 3,\n });\n\n const plugin = basePlugin as unknown as Plugin;\n plugin.name = \"kimesh:auto-import:template\";\n\n const api = (basePlugin as any).api as {\n findComponent: (name: string, filename?: string) => Promise<any>;\n stringifyImport: (info: any) => string;\n };\n\n const originalTransform = plugin.transform;\n if (originalTransform) {\n plugin.transform = async function (\n code: string,\n id: string,\n transformOptions: any\n ) {\n const DISABLE_COMMENT = \"/* unplugin-vue-components disabled */\";\n\n if (!code.includes(DISABLE_COMMENT)) {\n return (originalTransform as Function).call(\n this,\n code,\n id,\n transformOptions\n );\n }\n\n const registry = getRegistry();\n if (!registry) return null;\n\n const unresolvedMatches = [\n ...code.matchAll(/_?resolveComponent\\d*\\(\"(.+?)\"\\)/g),\n ];\n if (unresolvedMatches.length === 0) return null;\n\n const existingVars = [...code.matchAll(/__unplugin_components_(\\d+)/g)];\n let nextVarIndex =\n existingVars.length > 0\n ? Math.max(...existingVars.map((m) => parseInt(m[1], 10))) + 1\n : 0;\n\n const s = new MagicString(code);\n const imports: string[] = [];\n const resolved = new Set<string>();\n\n for (const match of unresolvedMatches) {\n const fullMatch = match[0];\n const componentName = match[1];\n\n if (resolved.has(componentName)) continue;\n if (componentName.startsWith(\"_\")) continue;\n\n const entry = resolveComponentEntry(registry, componentName);\n if (!entry) continue;\n\n const varName = `__unplugin_components_${nextVarIndex++}`;\n const importName = entry.isDefault ? \"default\" : entry.name;\n imports.push(\n `import { ${importName} as ${varName} } from \"${entry.from}\";`\n );\n\n replaceAllOccurrences(s, code, fullMatch, varName);\n resolved.add(componentName);\n\n if (api && typeof api.findComponent === \"function\") {\n try {\n await api.findComponent(componentName, id);\n } catch {\n // Ignore errors from API registration\n }\n }\n }\n\n if (imports.length === 0) return null;\n\n s.prepend(imports.join(\"\\n\") + \"\\n\");\n\n return {\n code: s.toString(),\n map: s.generateMap({ source: id, includeContent: true }),\n };\n };\n }\n\n return plugin;\n}\n\nfunction resolveComponentEntry(\n registry: ImportRegistry,\n componentName: string\n): import(\"../types\").ImportEntry | undefined {\n const entry = registry.components.get(componentName);\n if (entry) return entry;\n\n const importEntry = registry.imports.get(componentName);\n if (\n importEntry &&\n importEntry.type === \"preset\" &&\n /^[A-Z][a-zA-Z0-9]*$/.test(componentName)\n ) {\n return importEntry;\n }\n\n return undefined;\n}\n\nfunction replaceAllOccurrences(\n s: MagicString,\n code: string,\n search: string,\n replacement: string\n): void {\n let searchIndex = 0;\n while (true) {\n const idx = code.indexOf(search, searchIndex);\n if (idx === -1) break;\n s.overwrite(idx, idx + search.length, replacement);\n searchIndex = idx + search.length;\n }\n}\n\nexport default createTemplatePlugin;\n","/**\n * @kimesh/auto-import - Unified Vite Plugin\n *\n * Main entry point that combines script and template auto-import plugins.\n * Both plugins share the same import registry for consistent resolution.\n */\n\nimport type { PluginOption } from \"vite\";\nimport { createScriptPlugin } from \"../script/plugin\";\nimport { createTemplatePlugin } from \"../template/plugin\";\nimport type { AutoImportPluginOptions, ImportRegistry } from \"../types\";\n\nfunction resolveDtsDirectory(dts: string | false | undefined): string | false {\n if (dts === false) return false;\n if (typeof dts === \"string\") return dts;\n return \".kimesh\";\n}\n\nexport function autoImportPlugin(\n options: AutoImportPluginOptions\n): PluginOption[] {\n const { dts = \".kimesh\", debug = false } = options;\n\n let sharedRegistry: ImportRegistry | null = null;\n\n const scriptPlugin = createScriptPlugin({\n ...options,\n onRegistryUpdate: (registry) => {\n sharedRegistry = registry;\n },\n });\n\n const templatePlugin = createTemplatePlugin({\n getRegistry: () => sharedRegistry,\n dts: resolveDtsDirectory(dts),\n debug,\n });\n\n return [scriptPlugin, templatePlugin];\n}\n\nexport const kimeshAutoImport = autoImportPlugin;\n\nexport default autoImportPlugin;\n","/**\n * @kimesh/auto-import\n *\n * OXC-powered auto-import system for Kimesh framework with layer support.\n *\n * Features:\n * - High-performance export scanning using OXC parser\n * - Layer-aware import resolution with priority-based conflict handling\n * - Automatic type declaration generation\n * - Built-in presets for Vue, Vue Router, TanStack Query, and Pinia\n * - Clear separation between script and template auto-import\n *\n * Architecture:\n * - `script/` - Handles composables, utilities, presets in <script> blocks\n * - `template/` - Handles components in <template> via unplugin-vue-components\n * - `registry/` - Shared import registry with conflict resolution\n * - `types/` - Type declaration generation\n * - `vite/` - Unified plugin entry point\n *\n * @packageDocumentation\n */\n\n// Type exports\nexport type {\n // Core types\n ImportEntry,\n ImportRegistry,\n ConflictReport,\n ExportInfo,\n ScanResult,\n UnresolvedReference,\n TransformResult,\n\n // Configuration types\n ImportPreset,\n AutoImportConfig,\n LayerAutoImportSource,\n AutoImportPluginOptions,\n ResolvedLayerInfo,\n} from \"./types\";\n\n// Scanner (legacy location, prefer script/ imports)\nexport { OxcExportScanner } from \"./scanner/oxc-scanner\";\nexport { ReferenceDetector } from \"./scanner/reference-detector\";\n\n// Registry\nexport { RegistryBuilder } from \"./registry/builder\";\nexport { ConflictResolver } from \"./registry/conflict-resolver\";\n\n// Script module exports\nexport {\n createScriptPlugin,\n ImportInjector,\n type ScriptPluginOptions,\n type InjectionResult,\n} from \"./script\";\n\n// Template module exports\nexport {\n createTemplatePlugin,\n createKimeshResolver,\n type TemplatePluginOptions,\n type KimeshResolverOptions,\n} from \"./template\";\n\n// Presets\nexport {\n vuePreset,\n vueRouterPreset,\n tanstackQueryPreset,\n piniaPreset,\n kimeshPreset,\n builtinPresets,\n normalizePreset,\n resolvePresets,\n} from \"./presets\";\n\n// Type generation\nexport { generateDtsFiles, generateSourceDts } from \"./types/generator\";\n\n// Vite plugins (unified entry)\nexport {\n autoImportPlugin,\n kimeshAutoImport,\n default as default,\n} from \"./vite/plugin\";\n\n// Backward compatibility: export createComponentsPlugin from vite/components\nexport { createComponentsPlugin } from \"./vite/components\";\n\n/**\n * Build import registry from sources (convenience function)\n */\nexport async function buildImportRegistry(\n sources: import(\"./types\").LayerAutoImportSource[]\n) {\n const { RegistryBuilder } = await import(\"./registry/builder\");\n const builder = new RegistryBuilder();\n return builder.build(sources);\n}\n\n/**\n * Scan exports from a file (convenience function)\n */\nexport async function scanExports(filePath: string) {\n const { OxcExportScanner } = await import(\"./scanner/oxc-scanner\");\n const scanner = new OxcExportScanner();\n return scanner.scanFile(filePath);\n}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,eAAsB,YAAY,UAAkB;CAClD,MAAM,EAAE,yCAAqB,MAAM,OAAO;AAE1C,QADgB,IAAIC,oBAAkB,CACvB,SAAS,SAAS"}
@@ -0,0 +1,195 @@
1
+ import { parseSync } from "oxc-parser";
2
+ import { parse } from "@vue/compiler-sfc";
3
+ import * as fs from "node:fs";
4
+ import * as path from "pathe";
5
+ import { createHash } from "node:crypto";
6
+ import { consola } from "consola";
7
+
8
+ //#region src/scanner/oxc-scanner.ts
9
+ /**
10
+ * @kimesh/auto-import - OXC Export Scanner
11
+ *
12
+ * High-performance export scanning using OXC parser.
13
+ */
14
+ const logger = consola.withTag("kimesh:auto-import:scanner");
15
+ var OxcExportScanner = class {
16
+ cache = {
17
+ version: "1.0",
18
+ entries: /* @__PURE__ */ new Map()
19
+ };
20
+ async scanFile(filePath) {
21
+ const startTime = performance.now();
22
+ let content;
23
+ try {
24
+ content = fs.readFileSync(filePath, "utf-8");
25
+ } catch {
26
+ logger.warn(`Could not read file: ${filePath}`);
27
+ return {
28
+ filePath,
29
+ fileHash: "",
30
+ exports: [],
31
+ parseTime: performance.now() - startTime
32
+ };
33
+ }
34
+ const fileHash = this.hashContent(content);
35
+ const cached = this.cache.entries.get(filePath);
36
+ if (cached && cached.hash === fileHash) return cached.result;
37
+ const result = {
38
+ filePath,
39
+ fileHash,
40
+ exports: filePath.endsWith(".vue") ? this.scanVueFile(content, filePath) : this.scanTsFile(content, filePath),
41
+ parseTime: performance.now() - startTime
42
+ };
43
+ this.cache.entries.set(filePath, {
44
+ hash: fileHash,
45
+ result
46
+ });
47
+ return result;
48
+ }
49
+ async scanFiles(filePaths) {
50
+ const startTime = performance.now();
51
+ const results = await Promise.all(filePaths.map((fp) => this.scanFile(fp)));
52
+ const totalTime = performance.now() - startTime;
53
+ logger.debug(`Scanned ${filePaths.length} files in ${totalTime.toFixed(1)}ms (${(totalTime / filePaths.length).toFixed(2)}ms/file avg)`);
54
+ return results;
55
+ }
56
+ scanTsFile(content, filePath) {
57
+ try {
58
+ const result = parseSync(filePath, content, { sourceType: "module" });
59
+ if (result.errors.length > 0) {
60
+ logger.debug(`Parse errors in ${filePath}: ${result.errors.length} errors`);
61
+ return [];
62
+ }
63
+ return this.extractExports(result.program);
64
+ } catch (error) {
65
+ logger.debug(`Failed to parse ${filePath}: ${error}`);
66
+ return [];
67
+ }
68
+ }
69
+ scanVueFile(content, filePath) {
70
+ try {
71
+ const { descriptor, errors } = parse(content, { filename: filePath });
72
+ if (errors.length > 0) {
73
+ logger.debug(`SFC parse errors in ${filePath}: ${errors.length} errors`);
74
+ return [];
75
+ }
76
+ const exports = [{
77
+ name: this.componentNameFromPath(filePath),
78
+ isDefault: true,
79
+ isType: false,
80
+ start: 0,
81
+ end: 0
82
+ }];
83
+ if (descriptor.script) {
84
+ const namedExports = this.scanTsFile(descriptor.script.content, filePath).filter((e) => !e.isDefault);
85
+ exports.push(...namedExports);
86
+ }
87
+ if (descriptor.scriptSetup) {
88
+ const exposeExports = this.extractDefineExposeExports(descriptor.scriptSetup.content, filePath);
89
+ exports.push(...exposeExports);
90
+ }
91
+ return exports;
92
+ } catch (error) {
93
+ logger.debug(`Failed to parse Vue file ${filePath}: ${error}`);
94
+ return [];
95
+ }
96
+ }
97
+ extractExports(program) {
98
+ const exports = [];
99
+ for (const node of program.body) if (node.type === "ExportNamedDeclaration") this.extractNamedExports(node, exports);
100
+ else if (node.type === "ExportDefaultDeclaration") this.extractDefaultExport(node, exports);
101
+ return exports;
102
+ }
103
+ extractNamedExports(node, exports) {
104
+ if (node.declaration) {
105
+ const names = this.extractDeclarationNames(node.declaration);
106
+ for (const name of names) exports.push({
107
+ name,
108
+ isDefault: false,
109
+ isType: node.exportKind === "type",
110
+ start: node.start,
111
+ end: node.end
112
+ });
113
+ }
114
+ if (node.specifiers) for (const spec of node.specifiers) {
115
+ const exportedName = spec.exported?.name || spec.local?.name;
116
+ if (exportedName) exports.push({
117
+ name: exportedName,
118
+ isDefault: false,
119
+ isType: spec.exportKind === "type",
120
+ start: spec.start,
121
+ end: spec.end
122
+ });
123
+ }
124
+ }
125
+ extractDefaultExport(node, exports) {
126
+ const name = node.declaration?.id?.name ?? "default";
127
+ exports.push({
128
+ name,
129
+ isDefault: true,
130
+ isType: false,
131
+ start: node.start,
132
+ end: node.end
133
+ });
134
+ }
135
+ extractDeclarationNames(declaration) {
136
+ const names = [];
137
+ if (declaration.type === "VariableDeclaration") {
138
+ for (const decl of declaration.declarations) if (decl.id.type === "Identifier") names.push(decl.id.name);
139
+ else if (decl.id.type === "ObjectPattern") {
140
+ for (const prop of decl.id.properties) if (prop.value?.name) names.push(prop.value.name);
141
+ }
142
+ } else if (declaration.id?.name) names.push(declaration.id.name);
143
+ return names;
144
+ }
145
+ extractDefineExposeExports(content, filePath) {
146
+ const exports = [];
147
+ try {
148
+ const result = parseSync(filePath + ".setup.ts", content, { sourceType: "module" });
149
+ this.walkAST(result.program, (node) => {
150
+ if (node.type === "CallExpression" && node.callee?.type === "Identifier" && node.callee.name === "defineExpose" && node.arguments?.[0]?.type === "ObjectExpression") {
151
+ for (const prop of node.arguments[0].properties) if (prop.key?.name) exports.push({
152
+ name: prop.key.name,
153
+ isDefault: false,
154
+ isType: false,
155
+ start: prop.start,
156
+ end: prop.end
157
+ });
158
+ }
159
+ });
160
+ } catch {}
161
+ return exports;
162
+ }
163
+ walkAST(node, visitor) {
164
+ if (!node || typeof node !== "object") return;
165
+ visitor(node);
166
+ for (const key of Object.keys(node)) {
167
+ const child = node[key];
168
+ if (Array.isArray(child)) for (const item of child) this.walkAST(item, visitor);
169
+ else if (child && typeof child === "object") this.walkAST(child, visitor);
170
+ }
171
+ }
172
+ componentNameFromPath(filePath) {
173
+ const basename = path.basename(filePath, path.extname(filePath));
174
+ return basename === "index" ? path.basename(path.dirname(filePath)) : basename;
175
+ }
176
+ hashContent(content) {
177
+ return createHash("md5").update(content).digest("hex").slice(0, 8);
178
+ }
179
+ invalidate(filePath) {
180
+ this.cache.entries.delete(filePath);
181
+ }
182
+ clearCache() {
183
+ this.cache.entries.clear();
184
+ }
185
+ getCacheStats() {
186
+ return {
187
+ size: this.cache.entries.size,
188
+ version: this.cache.version
189
+ };
190
+ }
191
+ };
192
+
193
+ //#endregion
194
+ export { OxcExportScanner as t };
195
+ //# sourceMappingURL=oxc-scanner-DrjjlY9k.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oxc-scanner-DrjjlY9k.mjs","names":["parseSFC"],"sources":["../src/scanner/oxc-scanner.ts"],"sourcesContent":["/**\n * @kimesh/auto-import - OXC Export Scanner\n *\n * High-performance export scanning using OXC parser.\n */\n\nimport { parseSync, type Program } from 'oxc-parser';\nimport { parse as parseSFC } from '@vue/compiler-sfc';\nimport * as fs from 'node:fs';\nimport * as path from 'pathe';\nimport { createHash } from 'node:crypto';\nimport { consola } from 'consola';\nimport type { ExportInfo, ScanResult } from '../types';\n\nconst logger = consola.withTag('kimesh:auto-import:scanner');\n\ninterface ScanCache {\n version: string;\n entries: Map<string, { hash: string; result: ScanResult }>;\n}\n\nexport class OxcExportScanner {\n private cache: ScanCache = { version: '1.0', entries: new Map() };\n\n async scanFile(filePath: string): Promise<ScanResult> {\n const startTime = performance.now();\n\n let content: string;\n try {\n content = fs.readFileSync(filePath, 'utf-8');\n } catch {\n logger.warn(`Could not read file: ${filePath}`);\n return {\n filePath,\n fileHash: '',\n exports: [],\n parseTime: performance.now() - startTime,\n };\n }\n\n const fileHash = this.hashContent(content);\n const cached = this.cache.entries.get(filePath);\n if (cached && cached.hash === fileHash) {\n return cached.result;\n }\n\n const exports = filePath.endsWith('.vue')\n ? this.scanVueFile(content, filePath)\n : this.scanTsFile(content, filePath);\n\n const result: ScanResult = {\n filePath,\n fileHash,\n exports,\n parseTime: performance.now() - startTime,\n };\n\n this.cache.entries.set(filePath, { hash: fileHash, result });\n return result;\n }\n\n async scanFiles(filePaths: string[]): Promise<ScanResult[]> {\n const startTime = performance.now();\n const results = await Promise.all(filePaths.map((fp) => this.scanFile(fp)));\n const totalTime = performance.now() - startTime;\n\n logger.debug(\n `Scanned ${filePaths.length} files in ${totalTime.toFixed(1)}ms ` +\n `(${(totalTime / filePaths.length).toFixed(2)}ms/file avg)`\n );\n\n return results;\n }\n\n private scanTsFile(content: string, filePath: string): ExportInfo[] {\n try {\n const result = parseSync(filePath, content, { sourceType: 'module' });\n\n if (result.errors.length > 0) {\n logger.debug(`Parse errors in ${filePath}: ${result.errors.length} errors`);\n return [];\n }\n\n return this.extractExports(result.program);\n } catch (error) {\n logger.debug(`Failed to parse ${filePath}: ${error}`);\n return [];\n }\n }\n\n private scanVueFile(content: string, filePath: string): ExportInfo[] {\n try {\n const { descriptor, errors } = parseSFC(content, { filename: filePath });\n\n if (errors.length > 0) {\n logger.debug(`SFC parse errors in ${filePath}: ${errors.length} errors`);\n return [];\n }\n\n const componentName = this.componentNameFromPath(filePath);\n const exports: ExportInfo[] = [\n { name: componentName, isDefault: true, isType: false, start: 0, end: 0 },\n ];\n\n if (descriptor.script) {\n const scriptExports = this.scanTsFile(descriptor.script.content, filePath);\n const namedExports = scriptExports.filter((e) => !e.isDefault);\n exports.push(...namedExports);\n }\n\n if (descriptor.scriptSetup) {\n const exposeExports = this.extractDefineExposeExports(\n descriptor.scriptSetup.content,\n filePath\n );\n exports.push(...exposeExports);\n }\n\n return exports;\n } catch (error) {\n logger.debug(`Failed to parse Vue file ${filePath}: ${error}`);\n return [];\n }\n }\n\n private extractExports(program: Program): ExportInfo[] {\n const exports: ExportInfo[] = [];\n\n for (const node of program.body) {\n if (node.type === 'ExportNamedDeclaration') {\n this.extractNamedExports(node, exports);\n } else if (node.type === 'ExportDefaultDeclaration') {\n this.extractDefaultExport(node, exports);\n }\n }\n\n return exports;\n }\n\n private extractNamedExports(node: any, exports: ExportInfo[]): void {\n if (node.declaration) {\n const names = this.extractDeclarationNames(node.declaration);\n for (const name of names) {\n exports.push({\n name,\n isDefault: false,\n isType: node.exportKind === 'type',\n start: node.start,\n end: node.end,\n });\n }\n }\n\n if (node.specifiers) {\n for (const spec of node.specifiers) {\n const exportedName = spec.exported?.name || spec.local?.name;\n if (exportedName) {\n exports.push({\n name: exportedName,\n isDefault: false,\n isType: spec.exportKind === 'type',\n start: spec.start,\n end: spec.end,\n });\n }\n }\n }\n }\n\n private extractDefaultExport(node: any, exports: ExportInfo[]): void {\n const name = node.declaration?.id?.name ?? 'default';\n exports.push({\n name,\n isDefault: true,\n isType: false,\n start: node.start,\n end: node.end,\n });\n }\n\n private extractDeclarationNames(declaration: any): string[] {\n const names: string[] = [];\n\n if (declaration.type === 'VariableDeclaration') {\n for (const decl of declaration.declarations) {\n if (decl.id.type === 'Identifier') {\n names.push(decl.id.name);\n } else if (decl.id.type === 'ObjectPattern') {\n for (const prop of decl.id.properties) {\n if (prop.value?.name) {\n names.push(prop.value.name);\n }\n }\n }\n }\n } else if (declaration.id?.name) {\n names.push(declaration.id.name);\n }\n\n return names;\n }\n\n private extractDefineExposeExports(content: string, filePath: string): ExportInfo[] {\n const exports: ExportInfo[] = [];\n\n try {\n const result = parseSync(filePath + '.setup.ts', content, { sourceType: 'module' });\n\n this.walkAST(result.program, (node: any) => {\n if (\n node.type === 'CallExpression' &&\n node.callee?.type === 'Identifier' &&\n node.callee.name === 'defineExpose' &&\n node.arguments?.[0]?.type === 'ObjectExpression'\n ) {\n for (const prop of node.arguments[0].properties) {\n if (prop.key?.name) {\n exports.push({\n name: prop.key.name,\n isDefault: false,\n isType: false,\n start: prop.start,\n end: prop.end,\n });\n }\n }\n }\n });\n } catch {\n // Ignore parse errors for expose extraction\n }\n\n return exports;\n }\n\n private walkAST(node: any, visitor: (node: any) => void): void {\n if (!node || typeof node !== 'object') return;\n\n visitor(node);\n\n for (const key of Object.keys(node)) {\n const child = node[key];\n if (Array.isArray(child)) {\n for (const item of child) {\n this.walkAST(item, visitor);\n }\n } else if (child && typeof child === 'object') {\n this.walkAST(child, visitor);\n }\n }\n }\n\n private componentNameFromPath(filePath: string): string {\n const basename = path.basename(filePath, path.extname(filePath));\n return basename === 'index' ? path.basename(path.dirname(filePath)) : basename;\n }\n\n private hashContent(content: string): string {\n return createHash('md5').update(content).digest('hex').slice(0, 8);\n }\n\n invalidate(filePath: string): void {\n this.cache.entries.delete(filePath);\n }\n\n clearCache(): void {\n this.cache.entries.clear();\n }\n\n getCacheStats(): { size: number; version: string } {\n return { size: this.cache.entries.size, version: this.cache.version };\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAcA,MAAM,SAAS,QAAQ,QAAQ,6BAA6B;AAO5D,IAAa,mBAAb,MAA8B;CAC5B,AAAQ,QAAmB;EAAE,SAAS;EAAO,yBAAS,IAAI,KAAK;EAAE;CAEjE,MAAM,SAAS,UAAuC;EACpD,MAAM,YAAY,YAAY,KAAK;EAEnC,IAAI;AACJ,MAAI;AACF,aAAU,GAAG,aAAa,UAAU,QAAQ;UACtC;AACN,UAAO,KAAK,wBAAwB,WAAW;AAC/C,UAAO;IACL;IACA,UAAU;IACV,SAAS,EAAE;IACX,WAAW,YAAY,KAAK,GAAG;IAChC;;EAGH,MAAM,WAAW,KAAK,YAAY,QAAQ;EAC1C,MAAM,SAAS,KAAK,MAAM,QAAQ,IAAI,SAAS;AAC/C,MAAI,UAAU,OAAO,SAAS,SAC5B,QAAO,OAAO;EAOhB,MAAM,SAAqB;GACzB;GACA;GACA,SAPc,SAAS,SAAS,OAAO,GACrC,KAAK,YAAY,SAAS,SAAS,GACnC,KAAK,WAAW,SAAS,SAAS;GAMpC,WAAW,YAAY,KAAK,GAAG;GAChC;AAED,OAAK,MAAM,QAAQ,IAAI,UAAU;GAAE,MAAM;GAAU;GAAQ,CAAC;AAC5D,SAAO;;CAGT,MAAM,UAAU,WAA4C;EAC1D,MAAM,YAAY,YAAY,KAAK;EACnC,MAAM,UAAU,MAAM,QAAQ,IAAI,UAAU,KAAK,OAAO,KAAK,SAAS,GAAG,CAAC,CAAC;EAC3E,MAAM,YAAY,YAAY,KAAK,GAAG;AAEtC,SAAO,MACL,WAAW,UAAU,OAAO,Y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jjlY9k.mjs";
2
+
3
+ export { OxcExportScanner };
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@kimesh/auto-import",
3
+ "version": "0.0.1",
4
+ "description": "OXC-powered auto-import system for Kimesh framework with layer support",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./dist/index.d.mts",
9
+ "import": "./dist/index.mjs"
10
+ }
11
+ },
12
+ "main": "./dist/index.mjs",
13
+ "types": "./dist/index.d.mts",
14
+ "files": [
15
+ "dist"
16
+ ],
17
+ "scripts": {
18
+ "build": "tsdown",
19
+ "dev": "tsdown --watch",
20
+ "typecheck": "tsc --noEmit",
21
+ "test": "vitest"
22
+ },
23
+ "dependencies": {
24
+ "oxc-parser": "^0.108.0",
25
+ "@vue/compiler-sfc": "^3.5.26",
26
+ "magic-string": "^0.30.21",
27
+ "pathe": "^2.0.3",
28
+ "consola": "^3.4.2",
29
+ "unplugin-vue-components": "^28.7.0"
30
+ },
31
+ "devDependencies": {
32
+ "@types/node": "^25.0.8",
33
+ "typescript": "^5.9.3",
34
+ "tsdown": "^0.20.0-beta.3",
35
+ "vitest": "^4.0.17",
36
+ "vite": "^8.0.0-beta.8"
37
+ },
38
+ "peerDependencies": {
39
+ "vite": "^8.0.0-beta.8"
40
+ }
41
+ }