vite-intlayer 9.8.0-canary.0 → 9.8.0
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.
- package/dist/esm/IntlayerCompilerPlugin.mjs +30 -4
- package/dist/esm/IntlayerCompilerPlugin.mjs.map +1 -1
- package/dist/esm/index.mjs +2 -2
- package/dist/types/IntlayerCompilerPlugin.d.ts +10 -0
- package/dist/types/IntlayerCompilerPlugin.d.ts.map +1 -1
- package/dist/types/index.d.ts +2 -2
- package/package.json +9 -9
|
@@ -10,6 +10,31 @@ import { getConfiguration } from "@intlayer/config/node";
|
|
|
10
10
|
// src/IntlayerCompilerPlugin.ts
|
|
11
11
|
const COMPILER_PLUGIN_NAME = "vite-intlayer-compiler";
|
|
12
12
|
/**
|
|
13
|
+
* Query parameters marking a module that is not the component source itself:
|
|
14
|
+
* Vite asset imports (`?raw`, `?url`, `?worker`…) and Vue / Svelte / Astro
|
|
15
|
+
* sub-blocks, which are compiled from the already transformed parent file.
|
|
16
|
+
*/
|
|
17
|
+
const NON_SOURCE_QUERY_REGEX = /(?:^|&)(?:raw|url|inline|worker|sharedworker|import|direct|vue|svelte|astro)(?:&|=|$)/;
|
|
18
|
+
/**
|
|
19
|
+
* Splits a Vite module id into its file path and query. Returns `undefined`
|
|
20
|
+
* for ids that must not be compiled. Other queries (e.g. TanStack Router
|
|
21
|
+
* `?tsr-split=component`) are virtual modules rebuilt from the original
|
|
22
|
+
* source, so they are compiled like the file itself.
|
|
23
|
+
*/
|
|
24
|
+
const getCompilableModule = (moduleId) => {
|
|
25
|
+
const queryIndex = moduleId.indexOf("?");
|
|
26
|
+
if (queryIndex === -1) return {
|
|
27
|
+
filePath: moduleId,
|
|
28
|
+
isVirtualModule: false
|
|
29
|
+
};
|
|
30
|
+
const query = moduleId.slice(queryIndex + 1);
|
|
31
|
+
if (NON_SOURCE_QUERY_REGEX.test(query)) return void 0;
|
|
32
|
+
return {
|
|
33
|
+
filePath: moduleId.slice(0, queryIndex),
|
|
34
|
+
isVirtualModule: true
|
|
35
|
+
};
|
|
36
|
+
};
|
|
37
|
+
/**
|
|
13
38
|
* Create an IntlayerCompiler - A Vite-compatible compiler plugin for Intlayer
|
|
14
39
|
*
|
|
15
40
|
* This autonomous compiler handles:
|
|
@@ -182,8 +207,9 @@ const intlayerCompiler = (options) => {
|
|
|
182
207
|
const transformHandler = async (code, id) => {
|
|
183
208
|
if (!guard.isPrimary) return;
|
|
184
209
|
if (!compilerConfig.enabled) return;
|
|
185
|
-
|
|
186
|
-
|
|
210
|
+
const compilableModule = getCompilableModule(id);
|
|
211
|
+
if (!compilableModule) return;
|
|
212
|
+
const filename = compilableModule.filePath;
|
|
187
213
|
if (!filesList.includes(normalizePath(filename))) return;
|
|
188
214
|
logger(`${colorize("Compiler:", ANSIColors.GREY_DARK)} Transforming ${colorizePath(relative(projectRoot, filename))}`, {
|
|
189
215
|
level: "info",
|
|
@@ -194,7 +220,7 @@ const intlayerCompiler = (options) => {
|
|
|
194
220
|
const result = await extractContent(filename, packageName, {
|
|
195
221
|
configuration: config,
|
|
196
222
|
code,
|
|
197
|
-
declarationOnly: !config.compiler.saveComponents,
|
|
223
|
+
declarationOnly: compilableModule.isVirtualModule || !config.compiler.saveComponents,
|
|
198
224
|
onExtract: async ({ key, content }) => {
|
|
199
225
|
await handleExtractedContent({
|
|
200
226
|
dictionaryKey: key,
|
|
@@ -233,5 +259,5 @@ const intlayerCompiler = (options) => {
|
|
|
233
259
|
return plugin;
|
|
234
260
|
};
|
|
235
261
|
|
|
236
|
-
export { intlayerCompiler };
|
|
262
|
+
export { getCompilableModule, intlayerCompiler };
|
|
237
263
|
//# sourceMappingURL=IntlayerCompilerPlugin.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"IntlayerCompilerPlugin.mjs","names":[],"sources":["../../src/IntlayerCompilerPlugin.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { dirname, relative } from 'node:path';\nimport {\n type CompilerMode,\n detectPackageName,\n type ExtractPluginOptions,\n type ExtractResult,\n extractContent,\n getExtractPluginOptions,\n writeContentHelper,\n} from '@intlayer/babel';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport {\n colorize,\n colorizeKey,\n colorizeNumber,\n colorizePath,\n getAppLogger,\n x,\n} from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport { normalizePath } from '@intlayer/config/utils';\nimport type { CompilerConfig, IntlayerConfig } from '@intlayer/types/config';\nimport type { HmrContext, Plugin, PluginOption } from 'vite';\nimport { createPrimaryInstanceGuard } from './dedupePlugin';\n\nconst COMPILER_PLUGIN_NAME = 'vite-intlayer-compiler';\n\n/**\n * Options for initializing the compiler\n */\nexport type IntlayerCompilerOptions = {\n /**\n * Configuration options for getting the intlayer configuration\n */\n configOptions?: GetConfigurationOptions;\n\n /**\n * Custom compiler configuration to override defaults\n */\n compilerConfig?: Partial<CompilerConfig>;\n};\n\n/**\n * Create an IntlayerCompiler - A Vite-compatible compiler plugin for Intlayer\n *\n * This autonomous compiler handles:\n * - Configuration loading and management\n * - Hot Module Replacement (HMR) for content changes\n * - File transformation with content extraction\n * - Dictionary persistence and building\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { defineConfig } from 'vite';\n * import { intlayerCompiler } from 'vite-intlayer';\n *\n * export default defineConfig({\n * plugins: [intlayerCompiler()],\n * });\n * ```\n *\n * @deprecated Since Intlayer v9, the compiler is bundled directly into the `intlayer()` plugin and activates automatically once `compiler.enabled` is set with a `compiler.output` path. Registering `intlayerCompiler()` separately as shown below is now optional. See the [v9 release notes](https://github.com/aymericzip/intlayer/blob/main/docs/docs/en/releases/v9.md).\n */\nexport const intlayerCompiler = (\n options?: IntlayerCompilerOptions\n): PluginOption => {\n let config: IntlayerConfig;\n let compilerConfig: ExtractPluginOptions;\n let logger: ReturnType<typeof getAppLogger>;\n let projectRoot = '';\n let filesList: string[] = [];\n\n // Ensures the compiler runs its side effects only once, even when it is\n // registered both via `intlayer()` (which now bundles it) and a manual\n // `intlayerCompiler()` call.\n const guard = createPrimaryInstanceGuard(COMPILER_PLUGIN_NAME);\n\n // Promise to track dictionary writing (for synchronization)\n let pendingDictionaryWrite: Promise<void> | null = null;\n\n // Track recently processed files to prevent infinite loops\n // Key: file path, Value: timestamp of last processing\n const recentlyProcessedFiles = new Map<string, number>();\n // Track recently written dictionaries to prevent duplicate writes\n // Key: dictionary key, Value: hash of content that was written\n const recentDictionaryContent = new Map<string, string>();\n // Debounce window in milliseconds - skip re-processing files within this window\n const DEBOUNCE_MS = 500;\n\n /**\n * Check if a file was recently processed (within debounce window)\n * and should be skipped to prevent infinite loops\n */\n const wasRecentlyProcessed = (filePath: string): boolean => {\n const lastProcessed = recentlyProcessedFiles.get(filePath);\n if (!lastProcessed) return false;\n\n const now = Date.now();\n return now - lastProcessed < DEBOUNCE_MS;\n };\n\n /**\n * Mark a file as recently processed\n */\n const markAsProcessed = (filePath: string): void => {\n recentlyProcessedFiles.set(filePath, Date.now());\n\n // Clean up old entries to prevent memory leaks\n const now = Date.now();\n for (const [path, timestamp] of recentlyProcessedFiles.entries()) {\n if (now - timestamp > DEBOUNCE_MS * 2) {\n recentlyProcessedFiles.delete(path);\n }\n }\n };\n\n /**\n * Create a simple hash of content for comparison\n * Used to detect if dictionary content has actually changed\n */\n const hashContent = (content: Record<string, string>): string =>\n JSON.stringify(\n Object.keys(content)\n .sort()\n .map((key) => [key, content[key]])\n );\n\n /**\n * Check if dictionary content has changed since last write\n */\n const hasDictionaryContentChanged = (\n dictionaryKey: string,\n content: Record<string, string>\n ): boolean => {\n const newHash = hashContent(content);\n const previousHash = recentDictionaryContent.get(dictionaryKey);\n\n if (previousHash === newHash) {\n return false;\n }\n\n // Update the stored hash\n recentDictionaryContent.set(dictionaryKey, newHash);\n return true;\n };\n\n /**\n * Build the list of files to transform based on configuration patterns\n */\n const buildFilesListFn = async (): Promise<void> => {\n // Normalize to POSIX so comparisons match on Windows.\n filesList = (compilerConfig.filesList ?? []).map(normalizePath);\n };\n\n /**\n * Initialize the compiler with the given mode\n */\n const init = async (compilerMode: CompilerMode): Promise<void> => {\n config = getConfiguration(options?.configOptions);\n\n compilerConfig = getExtractPluginOptions(config, compilerMode);\n\n logger = getAppLogger(config);\n\n // Build files list for transformation\n await buildFilesListFn();\n };\n\n /**\n * Vite hook: configResolved\n * Called when Vite config is resolved\n */\n const configResolved = async (viteConfig: {\n env?: { DEV?: boolean };\n root: string;\n plugins?: readonly { name: string }[];\n }): Promise<void> => {\n // Decide whether this is the primary instance before doing any work.\n guard.resolve({ plugins: viteConfig.plugins ?? [] });\n if (!guard.isPrimary) return;\n\n const compilerMode: CompilerMode = viteConfig.env?.DEV ? 'dev' : 'build';\n projectRoot = viteConfig.root;\n\n await init(compilerMode);\n };\n\n /**\n * Build start hook - no longer needs to prepare dictionaries\n * The compiler is now autonomous and extracts content inline\n */\n const buildStart = async (): Promise<void> => {\n if (!guard.isPrimary) return;\n\n // Bootstrap dictionaries and types before build starts\n // This ensures existing dictionaries are available for resolution\n try {\n logger('Intlayer compiler initialized', {\n level: 'info',\n });\n } catch (error) {\n logger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Failed to prepare Intlayer: ${error}`,\n {\n level: 'error',\n }\n );\n }\n };\n\n /**\n * Build end hook - wait for any pending dictionary writes\n */\n const buildEnd = async (): Promise<void> => {\n // Wait for any pending dictionary writes to complete\n if (pendingDictionaryWrite) {\n await pendingDictionaryWrite;\n }\n };\n\n /**\n * Vite hook: handleHotUpdate\n * Handles HMR for content files - invalidates cache and triggers re-transform\n */\n const handleHotUpdate = async ({\n file,\n server,\n modules,\n }: HmrContext): Promise<void> => {\n if (!guard.isPrimary) return undefined;\n\n // Check if this is a file we should transform (compare as POSIX paths).\n const normalizedFile = normalizePath(file);\n const isTransformableFile = filesList.some(\n (fileEl) => fileEl === normalizedFile\n );\n\n if (isTransformableFile) {\n // Check if this file was recently processed to prevent infinite loops\n // When a component is transformed, it writes a dictionary, which triggers HMR,\n // which would re-transform the component - this debounce prevents that loop\n if (wasRecentlyProcessed(file)) {\n logger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Skipping re-transform of ${colorizePath(relative(projectRoot, file))} (recently processed)`,\n {\n level: 'info',\n isVerbose: true,\n }\n );\n return undefined;\n }\n\n // Mark file as being processed before transformation\n markAsProcessed(file);\n\n // Invalidate all affected modules to ensure re-transform\n for (const mod of modules) {\n server.moduleGraph.invalidateModule(mod);\n }\n\n // Force re-transform by reading and processing the file\n // This ensures content extraction happens on every file change\n try {\n const code = await readFile(file, 'utf-8');\n\n // Trigger the transform manually to extract content\n await transformHandler(code, file);\n } catch (error) {\n logger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Failed to re-transform ${file}: ${error}`,\n {\n level: 'error',\n }\n );\n }\n\n // Trigger full reload for content changes\n server.ws.send({ type: 'full-reload' });\n }\n };\n\n /**\n * Write and build one or more dictionaries based on extracted content.\n * Leverages shared logic from @intlayer/babel.\n */\n const writeAndBuildDictionary = async (\n result: ExtractResult\n ): Promise<void> => {\n const { dictionaryKey, content, filePath: sourceFilePath } = result;\n\n // Skip if content hasn't changed - prevents infinite loops during HMR\n if (!hasDictionaryContentChanged(dictionaryKey, content)) {\n logger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Skipping dictionary ${colorizeKey(dictionaryKey)} (content unchanged)`,\n {\n level: 'info',\n isVerbose: true,\n }\n );\n return;\n }\n\n try {\n await writeContentHelper(content, dictionaryKey, sourceFilePath!, config);\n } catch (error) {\n logger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Failed to write/build dictionary for ${colorizeKey(dictionaryKey)}: ${error}`,\n {\n level: 'error',\n }\n );\n }\n };\n\n /**\n * Callback for when content is extracted from a file\n * Immediately writes and builds the dictionary\n */\n const handleExtractedContent = async (\n result: ExtractResult\n ): Promise<void> => {\n const contentKeys = Object.keys(result.content);\n\n logger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Extracted ${colorizeNumber(contentKeys.length)} content keys from ${colorizePath(relative(projectRoot, result.filePath))}`,\n {\n level: 'info',\n }\n );\n\n // Chain the write operation to ensure sequential writes\n pendingDictionaryWrite = (pendingDictionaryWrite ?? Promise.resolve())\n .then(() => writeAndBuildDictionary(result))\n .catch((error) => {\n logger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Error in dictionary write chain: ${error}`,\n {\n level: 'error',\n }\n );\n });\n\n return pendingDictionaryWrite;\n };\n\n /**\n * Transform a file using the appropriate extraction plugin based on file type.\n * Delegates to `extractContent` from `@intlayer/babel` which handles\n * JS/TS/JSX/TSX/Vue/Svelte/Astro extraction and transformation.\n */\n const transformHandler = async (code: string, id: string) => {\n // Skip duplicate instances so dictionaries are not written twice.\n if (!guard.isPrimary) {\n return undefined;\n }\n\n // Only transform if compiler is enabled\n if (!compilerConfig.enabled) {\n return undefined;\n }\n\n // Skip virtual modules (query strings indicate compiled/virtual modules)\n // e.g., App.svelte?svelte&type=style, Component.vue?vue&type=script\n if (id.includes('?')) {\n return undefined;\n }\n\n const filename = id;\n\n // Compare as POSIX paths; filename stays raw for extraction below.\n if (!filesList.includes(normalizePath(filename))) {\n return undefined;\n }\n\n logger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Transforming ${colorizePath(relative(projectRoot, filename))}`,\n {\n level: 'info',\n isVerbose: true,\n }\n );\n\n try {\n const packageName = detectPackageName(dirname(filename));\n\n const result = await extractContent(filename, packageName, {\n configuration: config,\n code,\n // Keep the transformation in memory unless `saveComponents` is enabled.\n declarationOnly: !config.compiler.saveComponents,\n // Dictionary writing is handled by handleExtractedContent below.\n onExtract: async ({ key, content }) => {\n await handleExtractedContent({\n dictionaryKey: key,\n content,\n filePath: filename,\n locale: config.internationalization.defaultLocale,\n });\n },\n });\n\n // Wait for the dictionary to be written before returning\n // This ensures the dictionary exists before any subsequent processing\n if (pendingDictionaryWrite) {\n await pendingDictionaryWrite;\n }\n\n if (result?.transformedCode) {\n return {\n code: result.transformedCode,\n };\n }\n } catch (error) {\n logger(\n [\n `Failed to transform ${colorizePath(relative(projectRoot, filename))}:`,\n error,\n ],\n {\n level: 'error',\n }\n );\n }\n\n return undefined;\n };\n\n const plugin: Plugin = {\n name: COMPILER_PLUGIN_NAME,\n enforce: 'pre',\n configResolved,\n buildStart,\n buildEnd,\n handleHotUpdate,\n transform: transformHandler,\n apply: (_viteConfig, env) => {\n // Initialize config if not already done\n if (!config) {\n config = getConfiguration(options?.configOptions);\n }\n if (!logger) {\n logger = getAppLogger(config);\n }\n\n if (!config.compiler.output) {\n logger(\n `${x} No output configuration found. Add a ${colorize('compiler.output', ANSIColors.BLUE)} in your configuration.`,\n {\n level: 'error',\n }\n );\n\n return false;\n }\n\n if (!compilerConfig) {\n compilerConfig = getExtractPluginOptions(config, env.command);\n }\n\n return compilerConfig.enabled;\n },\n };\n\n // Register the plugin object so the dedupe guard can identify the primary\n // instance by reference during `configResolved`.\n guard.setPlugin(plugin);\n\n return plugin;\n};\n"],"mappings":";;;;;;;;;;AA6BA,MAAM,uBAAuB;;;;;;;;;;;;;;;;;;;;;;;AAuC7B,MAAa,oBACX,YACiB;CACjB,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI,cAAc;CAClB,IAAI,YAAsB,CAAC;CAK3B,MAAM,QAAQ,2BAA2B,oBAAoB;CAG7D,IAAI,yBAA+C;CAInD,MAAM,yCAAyB,IAAI,IAAoB;CAGvD,MAAM,0CAA0B,IAAI,IAAoB;CAExD,MAAM,cAAc;;;;;CAMpB,MAAM,wBAAwB,aAA8B;EAC1D,MAAM,gBAAgB,uBAAuB,IAAI,QAAQ;EACzD,IAAI,CAAC,eAAe,OAAO;EAG3B,OADY,KAAK,IACR,IAAI,gBAAgB;CAC/B;;;;CAKA,MAAM,mBAAmB,aAA2B;EAClD,uBAAuB,IAAI,UAAU,KAAK,IAAI,CAAC;EAG/C,MAAM,MAAM,KAAK,IAAI;EACrB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AAC,QACH,SAAS,iBAAiB,SAAS,aAAa;GAElD,IAAI,CAAC,QACH,SAAS,aAAa,MAAM;GAG9B,IAAI,CAAC,OAAO,SAAS,QAAQ;IAC3B,OACE,GAAG,EAAE,wCAAwC,SAAS,mBAAmB,WAAW,IAAI,EAAE,0BAC1F,EACE,OAAO,QACT,CACF;IAEA,OAAO;GACT;GAEA,IAAI,CAAC,gBACH,iBAAiB,wBAAwB,QAAQ,IAAI,OAAO;GAG9D,OAAO,eAAe;EACxB;CACF;CAIA,MAAM,UAAU,MAAM;CAEtB,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"IntlayerCompilerPlugin.mjs","names":[],"sources":["../../src/IntlayerCompilerPlugin.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { dirname, relative } from 'node:path';\nimport {\n type CompilerMode,\n detectPackageName,\n type ExtractPluginOptions,\n type ExtractResult,\n extractContent,\n getExtractPluginOptions,\n writeContentHelper,\n} from '@intlayer/babel';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport {\n colorize,\n colorizeKey,\n colorizeNumber,\n colorizePath,\n getAppLogger,\n x,\n} from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport { normalizePath } from '@intlayer/config/utils';\nimport type { CompilerConfig, IntlayerConfig } from '@intlayer/types/config';\nimport type { HmrContext, Plugin, PluginOption } from 'vite';\nimport { createPrimaryInstanceGuard } from './dedupePlugin';\n\nconst COMPILER_PLUGIN_NAME = 'vite-intlayer-compiler';\n\n/**\n * Query parameters marking a module that is not the component source itself:\n * Vite asset imports (`?raw`, `?url`, `?worker`…) and Vue / Svelte / Astro\n * sub-blocks, which are compiled from the already transformed parent file.\n */\nconst NON_SOURCE_QUERY_REGEX =\n /(?:^|&)(?:raw|url|inline|worker|sharedworker|import|direct|vue|svelte|astro)(?:&|=|$)/;\n\n/**\n * Splits a Vite module id into its file path and query. Returns `undefined`\n * for ids that must not be compiled. Other queries (e.g. TanStack Router\n * `?tsr-split=component`) are virtual modules rebuilt from the original\n * source, so they are compiled like the file itself.\n */\nexport const getCompilableModule = (\n moduleId: string\n): { filePath: string; isVirtualModule: boolean } | undefined => {\n const queryIndex = moduleId.indexOf('?');\n\n if (queryIndex === -1) return { filePath: moduleId, isVirtualModule: false };\n\n const query = moduleId.slice(queryIndex + 1);\n\n if (NON_SOURCE_QUERY_REGEX.test(query)) return undefined;\n\n return { filePath: moduleId.slice(0, queryIndex), isVirtualModule: true };\n};\n\n/**\n * Options for initializing the compiler\n */\nexport type IntlayerCompilerOptions = {\n /**\n * Configuration options for getting the intlayer configuration\n */\n configOptions?: GetConfigurationOptions;\n\n /**\n * Custom compiler configuration to override defaults\n */\n compilerConfig?: Partial<CompilerConfig>;\n};\n\n/**\n * Create an IntlayerCompiler - A Vite-compatible compiler plugin for Intlayer\n *\n * This autonomous compiler handles:\n * - Configuration loading and management\n * - Hot Module Replacement (HMR) for content changes\n * - File transformation with content extraction\n * - Dictionary persistence and building\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { defineConfig } from 'vite';\n * import { intlayerCompiler } from 'vite-intlayer';\n *\n * export default defineConfig({\n * plugins: [intlayerCompiler()],\n * });\n * ```\n *\n * @deprecated Since Intlayer v9, the compiler is bundled directly into the `intlayer()` plugin and activates automatically once `compiler.enabled` is set with a `compiler.output` path. Registering `intlayerCompiler()` separately as shown below is now optional. See the [v9 release notes](https://github.com/aymericzip/intlayer/blob/main/docs/docs/en/releases/v9.md).\n */\nexport const intlayerCompiler = (\n options?: IntlayerCompilerOptions\n): PluginOption => {\n let config: IntlayerConfig;\n let compilerConfig: ExtractPluginOptions;\n let logger: ReturnType<typeof getAppLogger>;\n let projectRoot = '';\n let filesList: string[] = [];\n\n // Ensures the compiler runs its side effects only once, even when it is\n // registered both via `intlayer()` (which now bundles it) and a manual\n // `intlayerCompiler()` call.\n const guard = createPrimaryInstanceGuard(COMPILER_PLUGIN_NAME);\n\n // Promise to track dictionary writing (for synchronization)\n let pendingDictionaryWrite: Promise<void> | null = null;\n\n // Track recently processed files to prevent infinite loops\n // Key: file path, Value: timestamp of last processing\n const recentlyProcessedFiles = new Map<string, number>();\n // Track recently written dictionaries to prevent duplicate writes\n // Key: dictionary key, Value: hash of content that was written\n const recentDictionaryContent = new Map<string, string>();\n // Debounce window in milliseconds - skip re-processing files within this window\n const DEBOUNCE_MS = 500;\n\n /**\n * Check if a file was recently processed (within debounce window)\n * and should be skipped to prevent infinite loops\n */\n const wasRecentlyProcessed = (filePath: string): boolean => {\n const lastProcessed = recentlyProcessedFiles.get(filePath);\n if (!lastProcessed) return false;\n\n const now = Date.now();\n return now - lastProcessed < DEBOUNCE_MS;\n };\n\n /**\n * Mark a file as recently processed\n */\n const markAsProcessed = (filePath: string): void => {\n recentlyProcessedFiles.set(filePath, Date.now());\n\n // Clean up old entries to prevent memory leaks\n const now = Date.now();\n for (const [path, timestamp] of recentlyProcessedFiles.entries()) {\n if (now - timestamp > DEBOUNCE_MS * 2) {\n recentlyProcessedFiles.delete(path);\n }\n }\n };\n\n /**\n * Create a simple hash of content for comparison\n * Used to detect if dictionary content has actually changed\n */\n const hashContent = (content: Record<string, string>): string =>\n JSON.stringify(\n Object.keys(content)\n .sort()\n .map((key) => [key, content[key]])\n );\n\n /**\n * Check if dictionary content has changed since last write\n */\n const hasDictionaryContentChanged = (\n dictionaryKey: string,\n content: Record<string, string>\n ): boolean => {\n const newHash = hashContent(content);\n const previousHash = recentDictionaryContent.get(dictionaryKey);\n\n if (previousHash === newHash) {\n return false;\n }\n\n // Update the stored hash\n recentDictionaryContent.set(dictionaryKey, newHash);\n return true;\n };\n\n /**\n * Build the list of files to transform based on configuration patterns\n */\n const buildFilesListFn = async (): Promise<void> => {\n // Normalize to POSIX so comparisons match on Windows.\n filesList = (compilerConfig.filesList ?? []).map(normalizePath);\n };\n\n /**\n * Initialize the compiler with the given mode\n */\n const init = async (compilerMode: CompilerMode): Promise<void> => {\n config = getConfiguration(options?.configOptions);\n\n compilerConfig = getExtractPluginOptions(config, compilerMode);\n\n logger = getAppLogger(config);\n\n // Build files list for transformation\n await buildFilesListFn();\n };\n\n /**\n * Vite hook: configResolved\n * Called when Vite config is resolved\n */\n const configResolved = async (viteConfig: {\n env?: { DEV?: boolean };\n root: string;\n plugins?: readonly { name: string }[];\n }): Promise<void> => {\n // Decide whether this is the primary instance before doing any work.\n guard.resolve({ plugins: viteConfig.plugins ?? [] });\n if (!guard.isPrimary) return;\n\n const compilerMode: CompilerMode = viteConfig.env?.DEV ? 'dev' : 'build';\n projectRoot = viteConfig.root;\n\n await init(compilerMode);\n };\n\n /**\n * Build start hook - no longer needs to prepare dictionaries\n * The compiler is now autonomous and extracts content inline\n */\n const buildStart = async (): Promise<void> => {\n if (!guard.isPrimary) return;\n\n // Bootstrap dictionaries and types before build starts\n // This ensures existing dictionaries are available for resolution\n try {\n logger('Intlayer compiler initialized', {\n level: 'info',\n });\n } catch (error) {\n logger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Failed to prepare Intlayer: ${error}`,\n {\n level: 'error',\n }\n );\n }\n };\n\n /**\n * Build end hook - wait for any pending dictionary writes\n */\n const buildEnd = async (): Promise<void> => {\n // Wait for any pending dictionary writes to complete\n if (pendingDictionaryWrite) {\n await pendingDictionaryWrite;\n }\n };\n\n /**\n * Vite hook: handleHotUpdate\n * Handles HMR for content files - invalidates cache and triggers re-transform\n */\n const handleHotUpdate = async ({\n file,\n server,\n modules,\n }: HmrContext): Promise<void> => {\n if (!guard.isPrimary) return undefined;\n\n // Check if this is a file we should transform (compare as POSIX paths).\n const normalizedFile = normalizePath(file);\n const isTransformableFile = filesList.some(\n (fileEl) => fileEl === normalizedFile\n );\n\n if (isTransformableFile) {\n // Check if this file was recently processed to prevent infinite loops\n // When a component is transformed, it writes a dictionary, which triggers HMR,\n // which would re-transform the component - this debounce prevents that loop\n if (wasRecentlyProcessed(file)) {\n logger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Skipping re-transform of ${colorizePath(relative(projectRoot, file))} (recently processed)`,\n {\n level: 'info',\n isVerbose: true,\n }\n );\n return undefined;\n }\n\n // Mark file as being processed before transformation\n markAsProcessed(file);\n\n // Invalidate all affected modules to ensure re-transform\n for (const mod of modules) {\n server.moduleGraph.invalidateModule(mod);\n }\n\n // Force re-transform by reading and processing the file\n // This ensures content extraction happens on every file change\n try {\n const code = await readFile(file, 'utf-8');\n\n // Trigger the transform manually to extract content\n await transformHandler(code, file);\n } catch (error) {\n logger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Failed to re-transform ${file}: ${error}`,\n {\n level: 'error',\n }\n );\n }\n\n // Trigger full reload for content changes\n server.ws.send({ type: 'full-reload' });\n }\n };\n\n /**\n * Write and build one or more dictionaries based on extracted content.\n * Leverages shared logic from @intlayer/babel.\n */\n const writeAndBuildDictionary = async (\n result: ExtractResult\n ): Promise<void> => {\n const { dictionaryKey, content, filePath: sourceFilePath } = result;\n\n // Skip if content hasn't changed - prevents infinite loops during HMR\n if (!hasDictionaryContentChanged(dictionaryKey, content)) {\n logger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Skipping dictionary ${colorizeKey(dictionaryKey)} (content unchanged)`,\n {\n level: 'info',\n isVerbose: true,\n }\n );\n return;\n }\n\n try {\n await writeContentHelper(content, dictionaryKey, sourceFilePath!, config);\n } catch (error) {\n logger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Failed to write/build dictionary for ${colorizeKey(dictionaryKey)}: ${error}`,\n {\n level: 'error',\n }\n );\n }\n };\n\n /**\n * Callback for when content is extracted from a file\n * Immediately writes and builds the dictionary\n */\n const handleExtractedContent = async (\n result: ExtractResult\n ): Promise<void> => {\n const contentKeys = Object.keys(result.content);\n\n logger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Extracted ${colorizeNumber(contentKeys.length)} content keys from ${colorizePath(relative(projectRoot, result.filePath))}`,\n {\n level: 'info',\n }\n );\n\n // Chain the write operation to ensure sequential writes\n pendingDictionaryWrite = (pendingDictionaryWrite ?? Promise.resolve())\n .then(() => writeAndBuildDictionary(result))\n .catch((error) => {\n logger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Error in dictionary write chain: ${error}`,\n {\n level: 'error',\n }\n );\n });\n\n return pendingDictionaryWrite;\n };\n\n /**\n * Transform a file using the appropriate extraction plugin based on file type.\n * Delegates to `extractContent` from `@intlayer/babel` which handles\n * JS/TS/JSX/TSX/Vue/Svelte/Astro extraction and transformation.\n */\n const transformHandler = async (code: string, id: string) => {\n // Skip duplicate instances so dictionaries are not written twice.\n if (!guard.isPrimary) {\n return undefined;\n }\n\n // Only transform if compiler is enabled\n if (!compilerConfig.enabled) {\n return undefined;\n }\n\n const compilableModule = getCompilableModule(id);\n\n if (!compilableModule) {\n return undefined;\n }\n\n // Query-free path, so the dictionary key and `componentFilePath` match\n // the ones of the plain file.\n const filename = compilableModule.filePath;\n\n // Compare as POSIX paths; filename stays raw for extraction below.\n if (!filesList.includes(normalizePath(filename))) {\n return undefined;\n }\n\n logger(\n `${colorize('Compiler:', ANSIColors.GREY_DARK)} Transforming ${colorizePath(relative(projectRoot, filename))}`,\n {\n level: 'info',\n isVerbose: true,\n }\n );\n\n try {\n const packageName = detectPackageName(dirname(filename));\n\n const result = await extractContent(filename, packageName, {\n configuration: config,\n code,\n // Keep the transformation in memory unless `saveComponents` is enabled.\n // A virtual module holds only part of the file, never write it back.\n declarationOnly:\n compilableModule.isVirtualModule || !config.compiler.saveComponents,\n // Dictionary writing is handled by handleExtractedContent below.\n onExtract: async ({ key, content }) => {\n await handleExtractedContent({\n dictionaryKey: key,\n content,\n filePath: filename,\n locale: config.internationalization.defaultLocale,\n });\n },\n });\n\n // Wait for the dictionary to be written before returning\n // This ensures the dictionary exists before any subsequent processing\n if (pendingDictionaryWrite) {\n await pendingDictionaryWrite;\n }\n\n if (result?.transformedCode) {\n return {\n code: result.transformedCode,\n };\n }\n } catch (error) {\n logger(\n [\n `Failed to transform ${colorizePath(relative(projectRoot, filename))}:`,\n error,\n ],\n {\n level: 'error',\n }\n );\n }\n\n return undefined;\n };\n\n const plugin: Plugin = {\n name: COMPILER_PLUGIN_NAME,\n enforce: 'pre',\n configResolved,\n buildStart,\n buildEnd,\n handleHotUpdate,\n transform: transformHandler,\n apply: (_viteConfig, env) => {\n // Initialize config if not already done\n if (!config) {\n config = getConfiguration(options?.configOptions);\n }\n if (!logger) {\n logger = getAppLogger(config);\n }\n\n if (!config.compiler.output) {\n logger(\n `${x} No output configuration found. Add a ${colorize('compiler.output', ANSIColors.BLUE)} in your configuration.`,\n {\n level: 'error',\n }\n );\n\n return false;\n }\n\n if (!compilerConfig) {\n compilerConfig = getExtractPluginOptions(config, env.command);\n }\n\n return compilerConfig.enabled;\n },\n };\n\n // Register the plugin object so the dedupe guard can identify the primary\n // instance by reference during `configResolved`.\n guard.setPlugin(plugin);\n\n return plugin;\n};\n"],"mappings":";;;;;;;;;;AA6BA,MAAM,uBAAuB;;;;;;AAO7B,MAAM,yBACJ;;;;;;;AAQF,MAAa,uBACX,aAC+D;CAC/D,MAAM,aAAa,SAAS,QAAQ,GAAG;CAEvC,IAAI,eAAe,IAAI,OAAO;EAAE,UAAU;EAAU,iBAAiB;CAAM;CAE3E,MAAM,QAAQ,SAAS,MAAM,aAAa,CAAC;CAE3C,IAAI,uBAAuB,KAAK,KAAK,GAAG,OAAO;CAE/C,OAAO;EAAE,UAAU,SAAS,MAAM,GAAG,UAAU;EAAG,iBAAiB;CAAK;AAC1E;;;;;;;;;;;;;;;;;;;;;;;AAuCA,MAAa,oBACX,YACiB;CACjB,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI,cAAc;CAClB,IAAI,YAAsB,CAAC;CAK3B,MAAM,QAAQ,2BAA2B,oBAAoB;CAG7D,IAAI,yBAA+C;CAInD,MAAM,yCAAyB,IAAI,IAAoB;CAGvD,MAAM,0CAA0B,IAAI,IAAoB;CAExD,MAAM,cAAc;;;;;CAMpB,MAAM,wBAA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R,IAAI,QAAQ,iBACV,OAAO,EACL,MAAM,OAAO,gBACf;EAEJ,SAAS,OAAO;GACd,OACE,CACE,uBAAuB,aAAa,SAAS,aAAa,QAAQ,CAAC,EAAE,IACrE,KACF,GACA,EACE,OAAO,QACT,CACF;EACF;CAGF;CAEA,MAAM,SAAiB;EACrB,MAAM;EACN,SAAS;EACT;EACA;EACA;EACA;EACA,WAAW;EACX,QAAQ,aAAa,QAAQ;GAE3B,IAAI,CAAC,QACH,SAAS,iBAAiB,SAAS,aAAa;GAElD,IAAI,CAAC,QACH,SAAS,aAAa,MAAM;GAG9B,IAAI,CAAC,OAAO,SAAS,QAAQ;IAC3B,OACE,GAAG,EAAE,wCAAwC,SAAS,mBAAmB,WAAW,IAAI,EAAE,0BAC1F,EACE,OAAO,QACT,CACF;IAEA,OAAO;GACT;GAEA,IAAI,CAAC,gBACH,iBAAiB,wBAAwB,QAAQ,IAAI,OAAO;GAG9D,OAAO,eAAe;EACxB;CACF;CAIA,MAAM,UAAU,MAAM;CAEtB,OAAO;AACT"}
|
package/dist/esm/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { intlayerCompiler } from "./IntlayerCompilerPlugin.mjs";
|
|
1
|
+
import { getCompilableModule, intlayerCompiler } from "./IntlayerCompilerPlugin.mjs";
|
|
2
2
|
import { createDictionaryModuleParser, intlayerChunk, resolveBoundaries, toBoundaryName } from "./intlayerChunkPlugin.mjs";
|
|
3
3
|
import { DICTIONARY_ENTRY_HMR_FOOTER, findDictionaryConsumers, intlayerDictionaryHmr } from "./intlayerDictionaryHmrPlugin.mjs";
|
|
4
4
|
import { intlayerMinify } from "./intlayerMinifyPlugin.mjs";
|
|
@@ -8,4 +8,4 @@ import { intlayerPreload } from "./intlayerPreloadPlugin.mjs";
|
|
|
8
8
|
import { createIntlayerProxyHandler, createRedirectOnlyMiddleware, intLayerMiddlewarePlugin, intlayerMiddleware, intlayerProxy, resolveNitroHandlerPath } from "./intlayerProxyPlugin.mjs";
|
|
9
9
|
import { intlayerPrune } from "./intlayerPrunePlugin.mjs";
|
|
10
10
|
|
|
11
|
-
export { DICTIONARY_ENTRY_HMR_FOOTER, INTLAYER_NO_EXTERNAL_PATTERN, createDictionaryModuleParser, createIntlayerProxyHandler, createRedirectOnlyMiddleware, findDictionaryConsumers, intLayerMiddlewarePlugin, intLayerPlugin, intlayer, intlayerChunk, intlayerCompiler, intlayerDictionaryHmr, intlayerMiddleware, intlayerMinify, intlayerOptimize, intlayerPlugin, intlayerPreload, intlayerProxy, intlayerPrune, resolveBoundaries, resolveNitroHandlerPath, toBoundaryName };
|
|
11
|
+
export { DICTIONARY_ENTRY_HMR_FOOTER, INTLAYER_NO_EXTERNAL_PATTERN, createDictionaryModuleParser, createIntlayerProxyHandler, createRedirectOnlyMiddleware, findDictionaryConsumers, getCompilableModule, intLayerMiddlewarePlugin, intLayerPlugin, intlayer, intlayerChunk, intlayerCompiler, intlayerDictionaryHmr, intlayerMiddleware, intlayerMinify, intlayerOptimize, intlayerPlugin, intlayerPreload, intlayerProxy, intlayerPrune, resolveBoundaries, resolveNitroHandlerPath, toBoundaryName };
|
|
@@ -1,6 +1,16 @@
|
|
|
1
1
|
import { CompilerConfig } from "@intlayer/types/config";
|
|
2
2
|
import { PluginOption } from "vite";
|
|
3
3
|
import { GetConfigurationOptions } from "@intlayer/config/node";
|
|
4
|
+
/**
|
|
5
|
+
* Splits a Vite module id into its file path and query. Returns `undefined`
|
|
6
|
+
* for ids that must not be compiled. Other queries (e.g. TanStack Router
|
|
7
|
+
* `?tsr-split=component`) are virtual modules rebuilt from the original
|
|
8
|
+
* source, so they are compiled like the file itself.
|
|
9
|
+
*/
|
|
10
|
+
export declare const getCompilableModule: (moduleId: string) => {
|
|
11
|
+
filePath: string;
|
|
12
|
+
isVirtualModule: boolean;
|
|
13
|
+
} | undefined;
|
|
4
14
|
/**
|
|
5
15
|
* Options for initializing the compiler
|
|
6
16
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"IntlayerCompilerPlugin.d.ts","names":[],"sources":["../../src/IntlayerCompilerPlugin.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"IntlayerCompilerPlugin.d.ts","names":[],"sources":["../../src/IntlayerCompilerPlugin.ts"],"mappings":";;;;;;;;;qBA6Ca,sBAAmB;EAE3B;EAAkB;;;;;YAeX;;;;EAIV,gBAAgB;;;;EAKhB,iBAAiB,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;qBAyBd,mBAAgB,UACjB,4BACT"}
|
package/dist/types/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { IntlayerCompilerOptions, intlayerCompiler } from "./IntlayerCompilerPlugin.js";
|
|
1
|
+
import { IntlayerCompilerOptions, getCompilableModule, intlayerCompiler } from "./IntlayerCompilerPlugin.js";
|
|
2
2
|
import { ChunkingContext, DictionaryModule, ModuleGraphNode, createDictionaryModuleParser, intlayerChunk, resolveBoundaries, toBoundaryName } from "./intlayerChunkPlugin.js";
|
|
3
3
|
import { DICTIONARY_ENTRY_HMR_FOOTER, findDictionaryConsumers, intlayerDictionaryHmr } from "./intlayerDictionaryHmrPlugin.js";
|
|
4
4
|
import { intlayerMinify } from "./intlayerMinifyPlugin.js";
|
|
@@ -7,4 +7,4 @@ import { INTLAYER_NO_EXTERNAL_PATTERN, IntlayerPluginOptions, intLayerPlugin, in
|
|
|
7
7
|
import { intlayerPreload } from "./intlayerPreloadPlugin.js";
|
|
8
8
|
import { IntlayerProxyPluginOptions, createIntlayerProxyHandler, createRedirectOnlyMiddleware, intLayerMiddlewarePlugin, intlayerMiddleware, intlayerProxy, resolveNitroHandlerPath } from "./intlayerProxyPlugin.js";
|
|
9
9
|
import { intlayerPrune } from "./intlayerPrunePlugin.js";
|
|
10
|
-
export { ChunkingContext, DICTIONARY_ENTRY_HMR_FOOTER, DictionaryModule, INTLAYER_NO_EXTERNAL_PATTERN, IntlayerCompilerOptions, IntlayerPluginOptions, IntlayerProxyPluginOptions, ModuleGraphNode, createDictionaryModuleParser, createIntlayerProxyHandler, createRedirectOnlyMiddleware, findDictionaryConsumers, intLayerMiddlewarePlugin, intLayerPlugin, intlayer, intlayerChunk, intlayerCompiler, intlayerDictionaryHmr, intlayerMiddleware, intlayerMinify, intlayerOptimize, intlayerPlugin, intlayerPreload, intlayerProxy, intlayerPrune, resolveBoundaries, resolveNitroHandlerPath, toBoundaryName };
|
|
10
|
+
export { ChunkingContext, DICTIONARY_ENTRY_HMR_FOOTER, DictionaryModule, INTLAYER_NO_EXTERNAL_PATTERN, IntlayerCompilerOptions, IntlayerPluginOptions, IntlayerProxyPluginOptions, ModuleGraphNode, createDictionaryModuleParser, createIntlayerProxyHandler, createRedirectOnlyMiddleware, findDictionaryConsumers, getCompilableModule, intLayerMiddlewarePlugin, intLayerPlugin, intlayer, intlayerChunk, intlayerCompiler, intlayerDictionaryHmr, intlayerMiddleware, intlayerMinify, intlayerOptimize, intlayerPlugin, intlayerPreload, intlayerProxy, intlayerPrune, resolveBoundaries, resolveNitroHandlerPath, toBoundaryName };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "vite-intlayer",
|
|
3
|
-
"version": "9.8.0
|
|
3
|
+
"version": "9.8.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "A Vite plugin for seamless internationalization (i18n), providing locale detection, redirection, and environment-based configuration",
|
|
6
6
|
"keywords": [
|
|
@@ -87,12 +87,12 @@
|
|
|
87
87
|
"typecheck": "tsc --noEmit --project tsconfig.types.json"
|
|
88
88
|
},
|
|
89
89
|
"dependencies": {
|
|
90
|
-
"@intlayer/babel": "9.8.0
|
|
91
|
-
"@intlayer/config": "9.8.0
|
|
92
|
-
"@intlayer/core": "9.8.0
|
|
93
|
-
"@intlayer/dictionaries-entry": "9.8.0
|
|
94
|
-
"@intlayer/engine": "9.8.0
|
|
95
|
-
"@intlayer/types": "9.8.0
|
|
90
|
+
"@intlayer/babel": "9.8.0",
|
|
91
|
+
"@intlayer/config": "9.8.0",
|
|
92
|
+
"@intlayer/core": "9.8.0",
|
|
93
|
+
"@intlayer/dictionaries-entry": "9.8.0",
|
|
94
|
+
"@intlayer/engine": "9.8.0",
|
|
95
|
+
"@intlayer/types": "9.8.0"
|
|
96
96
|
},
|
|
97
97
|
"devDependencies": {
|
|
98
98
|
"@types/node": "^26",
|
|
@@ -106,8 +106,8 @@
|
|
|
106
106
|
},
|
|
107
107
|
"peerDependencies": {
|
|
108
108
|
"@babel/core": ">=6.0.0",
|
|
109
|
-
"@intlayer/svelte-compiler": "9.8.0
|
|
110
|
-
"@intlayer/vue-compiler": "9.8.0
|
|
109
|
+
"@intlayer/svelte-compiler": "9.8.0",
|
|
110
|
+
"@intlayer/vue-compiler": "9.8.0",
|
|
111
111
|
"h3": ">=1.0.0",
|
|
112
112
|
"vite": ">=4.0.0"
|
|
113
113
|
},
|