@intlayer/vue-compiler 7.3.2-canary.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.
@@ -0,0 +1,174 @@
1
+ const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
2
+ let node_path = require("node:path");
3
+
4
+ //#region src/vue-intlayer-extract.ts
5
+ /**
6
+ * Attributes that should be extracted for localization
7
+ */
8
+ const ATTRIBUTES_TO_EXTRACT = [
9
+ "title",
10
+ "placeholder",
11
+ "alt",
12
+ "aria-label",
13
+ "label"
14
+ ];
15
+ /**
16
+ * Default function to determine if a string should be extracted
17
+ */
18
+ const defaultShouldExtract = (text) => {
19
+ const trimmed = text.trim();
20
+ if (!trimmed) return false;
21
+ if (!trimmed.includes(" ")) return false;
22
+ if (!/^[A-Z]/.test(trimmed)) return false;
23
+ if (trimmed.startsWith("{") || trimmed.startsWith("v-")) return false;
24
+ return true;
25
+ };
26
+ /**
27
+ * Generate a unique key from text
28
+ */
29
+ const generateKey = (text, existingKeys) => {
30
+ let key = text.replace(/\s+/g, " ").replace(/_+/g, " ").replace(/-+/g, " ").replace(/[^a-zA-Z0-9 ]/g, "").trim().split(" ").filter(Boolean).slice(0, 5).map((word, index) => index === 0 ? word.toLowerCase() : word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join("");
31
+ if (!key) key = "content";
32
+ if (existingKeys.has(key)) {
33
+ let i = 1;
34
+ while (existingKeys.has(`${key}${i}`)) i++;
35
+ key = `${key}${i}`;
36
+ }
37
+ return key;
38
+ };
39
+ /**
40
+ * Extract dictionary key from file path
41
+ */
42
+ const extractDictionaryKeyFromPath = (filePath) => {
43
+ let baseName = (0, node_path.basename)(filePath, (0, node_path.extname)(filePath));
44
+ if (baseName === "index") baseName = (0, node_path.basename)((0, node_path.dirname)(filePath));
45
+ return `comp-${baseName.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/[\s_]+/g, "-").toLowerCase()}`;
46
+ };
47
+ /**
48
+ * Check if a file should be processed based on filesList
49
+ */
50
+ const shouldProcessFile = (filename, filesList) => {
51
+ if (!filename) return false;
52
+ if (!filesList || filesList.length === 0) return true;
53
+ const normalizedFilename = filename.replace(/\\/g, "/");
54
+ return filesList.some((f) => {
55
+ return f.replace(/\\/g, "/") === normalizedFilename;
56
+ });
57
+ };
58
+ const NODE_TYPES = {
59
+ TEXT: 2,
60
+ ELEMENT: 1,
61
+ ATTRIBUTE: 6
62
+ };
63
+ /**
64
+ * Vue extraction plugin that extracts content and transforms Vue SFC to use useIntlayer.
65
+ *
66
+ * This plugin:
67
+ * 1. Scans Vue SFC files for extractable text (template text, attributes)
68
+ * 2. Auto-injects useIntlayer import and composable call
69
+ * 3. Reports extracted content via onExtract callback (for the compiler to write dictionaries)
70
+ * 4. Replaces extractable strings with content references
71
+ *
72
+ * ## Input
73
+ * ```vue
74
+ * <template>
75
+ * <div>Hello World</div>
76
+ * </template>
77
+ * ```
78
+ *
79
+ * ## Output
80
+ * ```vue
81
+ * <script setup>
82
+ * import { useIntlayer } from 'vue-intlayer';
83
+ * const content = useIntlayer('hello-world');
84
+ * <\/script>
85
+ * <template>
86
+ * <div>{{ content.helloWorld }}</div>
87
+ * </template>
88
+ * ```
89
+ */
90
+ const intlayerVueExtract = async (code, filename, options = {}) => {
91
+ const { defaultLocale = "en", packageName = "vue-intlayer", filesList, shouldExtract = defaultShouldExtract, onExtract } = options;
92
+ if (!shouldProcessFile(filename, filesList)) return null;
93
+ if (!filename.endsWith(".vue")) return null;
94
+ let parseVue;
95
+ let MagicString;
96
+ try {
97
+ parseVue = (await import("@vue/compiler-sfc")).parse;
98
+ } catch {
99
+ console.warn("Vue extraction: @vue/compiler-sfc not found. Install it to enable Vue content extraction.");
100
+ return null;
101
+ }
102
+ try {
103
+ MagicString = (await import("magic-string")).default;
104
+ } catch {
105
+ console.warn("Vue extraction: magic-string not found. Install it to enable Vue content extraction.");
106
+ return null;
107
+ }
108
+ const sfc = parseVue(code);
109
+ const magic = new MagicString(code);
110
+ const extractedContent = {};
111
+ const existingKeys = /* @__PURE__ */ new Set();
112
+ const dictionaryKey = extractDictionaryKeyFromPath(filename);
113
+ if (sfc.descriptor.template) {
114
+ const walkVueAst = (node) => {
115
+ if (node.type === NODE_TYPES.TEXT) {
116
+ const text = node.content ?? "";
117
+ if (shouldExtract(text)) {
118
+ const key = generateKey(text, existingKeys);
119
+ existingKeys.add(key);
120
+ extractedContent[key] = text.replace(/\s+/g, " ").trim();
121
+ magic.overwrite(node.loc.start.offset, node.loc.end.offset, `{{ content.${key} }}`);
122
+ }
123
+ } else if (node.type === NODE_TYPES.ELEMENT) node.props?.forEach((prop) => {
124
+ if (prop.type === NODE_TYPES.ATTRIBUTE && ATTRIBUTES_TO_EXTRACT.includes(prop.name) && prop.value) {
125
+ const text = prop.value.content;
126
+ if (shouldExtract(text)) {
127
+ const key = generateKey(text, existingKeys);
128
+ existingKeys.add(key);
129
+ extractedContent[key] = text.trim();
130
+ magic.overwrite(prop.loc.start.offset, prop.loc.end.offset, `:${prop.name}="content.${key}.value"`);
131
+ }
132
+ }
133
+ });
134
+ if (node.children) node.children.forEach(walkVueAst);
135
+ };
136
+ walkVueAst(sfc.descriptor.template.ast);
137
+ }
138
+ if (Object.keys(extractedContent).length === 0) return null;
139
+ const scriptContent = sfc.descriptor.scriptSetup?.content ?? sfc.descriptor.script?.content ?? "";
140
+ const hasUseIntlayerImport = /import\s*{[^}]*useIntlayer[^}]*}\s*from\s*['"][^'"]+['"]/.test(scriptContent) || /import\s+useIntlayer\s+from\s*['"][^'"]+['"]/.test(scriptContent);
141
+ const hasContentDeclaration = /const\s+content\s*=\s*useIntlayer\s*\(/.test(scriptContent);
142
+ if (hasUseIntlayerImport && hasContentDeclaration) return null;
143
+ const importStmt = hasUseIntlayerImport ? "" : `import { useIntlayer } from '${packageName}';`;
144
+ const contentDecl = hasContentDeclaration ? "" : `const content = useIntlayer('${dictionaryKey}');`;
145
+ const injectionParts = [importStmt, contentDecl].filter(Boolean);
146
+ if (injectionParts.length === 0) return null;
147
+ const injection = `\n${injectionParts.join("\n")}\n`;
148
+ if (sfc.descriptor.scriptSetup) magic.appendLeft(sfc.descriptor.scriptSetup.loc.start.offset, injection);
149
+ else if (sfc.descriptor.script) magic.appendLeft(sfc.descriptor.script.loc.start.offset, injection);
150
+ else magic.prepend(`<script setup>\n${importStmt}\n${contentDecl}\n<\/script>\n`);
151
+ if (onExtract) onExtract({
152
+ dictionaryKey,
153
+ filePath: filename,
154
+ content: { ...extractedContent },
155
+ locale: defaultLocale
156
+ });
157
+ return {
158
+ code: magic.toString(),
159
+ map: magic.generateMap({
160
+ source: filename,
161
+ includeContent: true
162
+ }),
163
+ extracted: true
164
+ };
165
+ };
166
+
167
+ //#endregion
168
+ exports.ATTRIBUTES_TO_EXTRACT = ATTRIBUTES_TO_EXTRACT;
169
+ exports.defaultShouldExtract = defaultShouldExtract;
170
+ exports.extractDictionaryKeyFromPath = extractDictionaryKeyFromPath;
171
+ exports.generateKey = generateKey;
172
+ exports.intlayerVueExtract = intlayerVueExtract;
173
+ exports.shouldProcessFile = shouldProcessFile;
174
+ //# sourceMappingURL=vue-intlayer-extract.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vue-intlayer-extract.cjs","names":["parseVue: (code: string) => VueParseResult","MagicString: new (code: string) => MagicStringType","extractedContent: ExtractedContent"],"sources":["../../src/vue-intlayer-extract.ts"],"sourcesContent":["import { basename, dirname, extname } from 'node:path';\n\n/* ────────────────────────────────────────── constants ───────────────────── */\n\n/**\n * Attributes that should be extracted for localization\n */\nexport const ATTRIBUTES_TO_EXTRACT = [\n 'title',\n 'placeholder',\n 'alt',\n 'aria-label',\n 'label',\n];\n\n/* ────────────────────────────────────────── types ───────────────────────── */\n\nexport type ExtractedContent = Record<string, string>;\n\n/**\n * Extracted content result from a file transformation\n */\nexport type ExtractResult = {\n /** Dictionary key derived from the file path */\n dictionaryKey: string;\n /** File path that was processed */\n filePath: string;\n /** Extracted content key-value pairs */\n content: ExtractedContent;\n /** Default locale used */\n locale: string;\n};\n\n/**\n * Options for extraction plugins\n */\nexport type ExtractPluginOptions = {\n /**\n * The default locale for the extracted content\n * @default 'en'\n */\n defaultLocale?: string;\n /**\n * The package to import useIntlayer from\n * @default 'vue-intlayer'\n */\n packageName?: string;\n /**\n * Files list to traverse. If provided, only files in this list will be processed.\n */\n filesList?: string[];\n /**\n * Custom function to determine if a string should be extracted\n */\n shouldExtract?: (text: string) => boolean;\n /**\n * Callback function called when content is extracted from a file.\n * This allows the compiler to capture the extracted content and write it to files.\n * The dictionary will be updated: new keys added, unused keys removed.\n */\n onExtract?: (result: ExtractResult) => void;\n};\n\n/* ────────────────────────────────────────── helpers ─────────────────────── */\n\n/**\n * Default function to determine if a string should be extracted\n */\nexport const defaultShouldExtract = (text: string): boolean => {\n const trimmed = text.trim();\n if (!trimmed) return false;\n // Must contain at least one space (likely a sentence/phrase)\n if (!trimmed.includes(' ')) return false;\n // Must start with a capital letter\n if (!/^[A-Z]/.test(trimmed)) return false;\n // Filter out template logic identifiers\n if (trimmed.startsWith('{') || trimmed.startsWith('v-')) return false;\n return true;\n};\n\n/**\n * Generate a unique key from text\n */\nexport const generateKey = (\n text: string,\n existingKeys: Set<string>\n): string => {\n const maxWords = 5;\n let key = text\n .replace(/\\s+/g, ' ')\n .replace(/_+/g, ' ')\n .replace(/-+/g, ' ')\n .replace(/[^a-zA-Z0-9 ]/g, '')\n .trim()\n .split(' ')\n .filter(Boolean)\n .slice(0, maxWords)\n .map((word, index) =>\n index === 0\n ? word.toLowerCase()\n : word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()\n )\n .join('');\n\n if (!key) key = 'content';\n if (existingKeys.has(key)) {\n let i = 1;\n while (existingKeys.has(`${key}${i}`)) i++;\n key = `${key}${i}`;\n }\n return key;\n};\n\n/**\n * Extract dictionary key from file path\n */\nexport const extractDictionaryKeyFromPath = (filePath: string): string => {\n const ext = extname(filePath);\n let baseName = basename(filePath, ext);\n\n if (baseName === 'index') {\n baseName = basename(dirname(filePath));\n }\n\n // Convert to kebab-case\n const key = baseName\n .replace(/([a-z])([A-Z])/g, '$1-$2')\n .replace(/[\\s_]+/g, '-')\n .toLowerCase();\n\n return `comp-${key}`;\n};\n\n/**\n * Check if a file should be processed based on filesList\n */\nexport const shouldProcessFile = (\n filename: string | undefined,\n filesList?: string[]\n): boolean => {\n if (!filename) return false;\n if (!filesList || filesList.length === 0) return true;\n\n // Normalize paths for comparison (handle potential path separator issues)\n const normalizedFilename = filename.replace(/\\\\/g, '/');\n return filesList.some((f) => {\n const normalizedF = f.replace(/\\\\/g, '/');\n return normalizedF === normalizedFilename;\n });\n};\n\n/* ────────────────────────────────────────── Vue types ───────────────────── */\n\ntype VueParseResult = {\n descriptor: {\n template?: {\n ast: VueAstNode;\n loc: { start: { offset: number }; end: { offset: number } };\n };\n script?: {\n content: string;\n loc: { start: { offset: number }; end: { offset: number } };\n };\n scriptSetup?: {\n content: string;\n loc: { start: { offset: number }; end: { offset: number } };\n };\n };\n};\n\ntype VueAstNode = {\n type: number;\n content?: string;\n children?: VueAstNode[];\n props?: VueAstProp[];\n loc: { start: { offset: number }; end: { offset: number } };\n};\n\ntype VueAstProp = {\n type: number;\n name: string;\n value?: { content: string };\n loc: { start: { offset: number }; end: { offset: number } };\n};\n\n// Vue AST NodeTypes\nconst NODE_TYPES = {\n TEXT: 2,\n ELEMENT: 1,\n ATTRIBUTE: 6,\n};\n\n// MagicString type for dynamic import\ntype MagicStringType = {\n overwrite: (start: number, end: number, content: string) => void;\n appendLeft: (index: number, content: string) => void;\n prepend: (content: string) => void;\n toString: () => string;\n generateMap: (options: {\n source: string;\n includeContent: boolean;\n }) => unknown;\n};\n\n/* ────────────────────────────────────────── plugin ──────────────────────── */\n\n/**\n * Vue extraction plugin that extracts content and transforms Vue SFC to use useIntlayer.\n *\n * This plugin:\n * 1. Scans Vue SFC files for extractable text (template text, attributes)\n * 2. Auto-injects useIntlayer import and composable call\n * 3. Reports extracted content via onExtract callback (for the compiler to write dictionaries)\n * 4. Replaces extractable strings with content references\n *\n * ## Input\n * ```vue\n * <template>\n * <div>Hello World</div>\n * </template>\n * ```\n *\n * ## Output\n * ```vue\n * <script setup>\n * import { useIntlayer } from 'vue-intlayer';\n * const content = useIntlayer('hello-world');\n * </script>\n * <template>\n * <div>{{ content.helloWorld }}</div>\n * </template>\n * ```\n */\nexport const intlayerVueExtract = async (\n code: string,\n filename: string,\n options: ExtractPluginOptions = {}\n): Promise<{ code: string; map?: unknown; extracted: boolean } | null> => {\n const {\n defaultLocale = 'en',\n packageName = 'vue-intlayer',\n filesList,\n shouldExtract = defaultShouldExtract,\n onExtract,\n } = options;\n\n // Check if file should be processed\n if (!shouldProcessFile(filename, filesList)) {\n return null;\n }\n\n // Skip non-Vue files\n if (!filename.endsWith('.vue')) {\n return null;\n }\n\n // Dynamic imports for dependencies (peer dependencies)\n let parseVue: (code: string) => VueParseResult;\n let MagicString: new (code: string) => MagicStringType;\n\n try {\n const vueSfc = await import('@vue/compiler-sfc');\n // Type assertion needed because Vue's SFCParseResult uses `null` for optional properties\n // while our VueParseResult uses `undefined` (optional). This is safe since we check\n // for truthy values before accessing template/script properties.\n parseVue = vueSfc.parse as unknown as (code: string) => VueParseResult;\n } catch {\n console.warn(\n 'Vue extraction: @vue/compiler-sfc not found. Install it to enable Vue content extraction.'\n );\n return null;\n }\n\n try {\n const magicStringModule = await import('magic-string');\n MagicString = magicStringModule.default;\n } catch {\n console.warn(\n 'Vue extraction: magic-string not found. Install it to enable Vue content extraction.'\n );\n return null;\n }\n\n const sfc = parseVue(code);\n const magic = new MagicString(code);\n\n const extractedContent: ExtractedContent = {};\n const existingKeys = new Set<string>();\n const dictionaryKey = extractDictionaryKeyFromPath(filename);\n\n // Walk the template AST\n if (sfc.descriptor.template) {\n const walkVueAst = (node: VueAstNode) => {\n if (node.type === NODE_TYPES.TEXT) {\n // Text node\n const text = node.content ?? '';\n if (shouldExtract(text)) {\n const key = generateKey(text, existingKeys);\n existingKeys.add(key);\n extractedContent[key] = text.replace(/\\s+/g, ' ').trim();\n magic.overwrite(\n node.loc.start.offset,\n node.loc.end.offset,\n `{{ content.${key} }}`\n );\n }\n } else if (node.type === NODE_TYPES.ELEMENT) {\n // Element node - check attributes\n node.props?.forEach((prop) => {\n if (\n prop.type === NODE_TYPES.ATTRIBUTE &&\n ATTRIBUTES_TO_EXTRACT.includes(prop.name) &&\n prop.value\n ) {\n const text = prop.value.content;\n if (shouldExtract(text)) {\n const key = generateKey(text, existingKeys);\n existingKeys.add(key);\n extractedContent[key] = text.trim();\n magic.overwrite(\n prop.loc.start.offset,\n prop.loc.end.offset,\n `:${prop.name}=\"content.${key}.value\"`\n );\n }\n }\n });\n }\n\n // Recurse into children\n if (node.children) {\n node.children.forEach(walkVueAst);\n }\n };\n\n walkVueAst(sfc.descriptor.template.ast);\n }\n\n // If nothing was extracted, return null\n if (Object.keys(extractedContent).length === 0) {\n return null;\n }\n\n // Get script content for checking existing imports/declarations\n const scriptContent =\n sfc.descriptor.scriptSetup?.content ?? sfc.descriptor.script?.content ?? '';\n\n // Check if useIntlayer is already imported\n const hasUseIntlayerImport =\n /import\\s*{[^}]*useIntlayer[^}]*}\\s*from\\s*['\"][^'\"]+['\"]/.test(\n scriptContent\n ) || /import\\s+useIntlayer\\s+from\\s*['\"][^'\"]+['\"]/.test(scriptContent);\n\n // Check if content variable is already declared with useIntlayer\n const hasContentDeclaration = /const\\s+content\\s*=\\s*useIntlayer\\s*\\(/.test(\n scriptContent\n );\n\n // Skip injection if already using useIntlayer\n if (hasUseIntlayerImport && hasContentDeclaration) {\n return null;\n }\n\n // Prepare injection statements (only what's missing)\n const importStmt = hasUseIntlayerImport\n ? ''\n : `import { useIntlayer } from '${packageName}';`;\n const contentDecl = hasContentDeclaration\n ? ''\n : `const content = useIntlayer('${dictionaryKey}');`;\n\n // Build injection string\n const injectionParts = [importStmt, contentDecl].filter(Boolean);\n if (injectionParts.length === 0) {\n return null;\n }\n const injection = `\\n${injectionParts.join('\\n')}\\n`;\n\n if (sfc.descriptor.scriptSetup) {\n // Insert at the beginning of script setup content\n magic.appendLeft(sfc.descriptor.scriptSetup.loc.start.offset, injection);\n } else if (sfc.descriptor.script) {\n // Insert at the beginning of script content\n magic.appendLeft(sfc.descriptor.script.loc.start.offset, injection);\n } else {\n // No script block, create one\n magic.prepend(`<script setup>\\n${importStmt}\\n${contentDecl}\\n</script>\\n`);\n }\n\n // Call the onExtract callback with extracted content\n if (onExtract) {\n const result: ExtractResult = {\n dictionaryKey,\n filePath: filename,\n content: { ...extractedContent },\n locale: defaultLocale,\n };\n onExtract(result);\n }\n\n return {\n code: magic.toString(),\n map: magic.generateMap({ source: filename, includeContent: true }),\n extracted: true,\n };\n};\n"],"mappings":";;;;;;;AAOA,MAAa,wBAAwB;CACnC;CACA;CACA;CACA;CACA;CACD;;;;AAuDD,MAAa,wBAAwB,SAA0B;CAC7D,MAAM,UAAU,KAAK,MAAM;AAC3B,KAAI,CAAC,QAAS,QAAO;AAErB,KAAI,CAAC,QAAQ,SAAS,IAAI,CAAE,QAAO;AAEnC,KAAI,CAAC,SAAS,KAAK,QAAQ,CAAE,QAAO;AAEpC,KAAI,QAAQ,WAAW,IAAI,IAAI,QAAQ,WAAW,KAAK,CAAE,QAAO;AAChE,QAAO;;;;;AAMT,MAAa,eACX,MACA,iBACW;CAEX,IAAI,MAAM,KACP,QAAQ,QAAQ,IAAI,CACpB,QAAQ,OAAO,IAAI,CACnB,QAAQ,OAAO,IAAI,CACnB,QAAQ,kBAAkB,GAAG,CAC7B,MAAM,CACN,MAAM,IAAI,CACV,OAAO,QAAQ,CACf,MAAM,GATQ,EASI,CAClB,KAAK,MAAM,UACV,UAAU,IACN,KAAK,aAAa,GAClB,KAAK,OAAO,EAAE,CAAC,aAAa,GAAG,KAAK,MAAM,EAAE,CAAC,aAAa,CAC/D,CACA,KAAK,GAAG;AAEX,KAAI,CAAC,IAAK,OAAM;AAChB,KAAI,aAAa,IA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B,CAAC,YAAY,YAAY,CAAC,OAAO,QAAQ;AAChE,KAAI,eAAe,WAAW,EAC5B,QAAO;CAET,MAAM,YAAY,KAAK,eAAe,KAAK,KAAK,CAAC;AAEjD,KAAI,IAAI,WAAW,YAEjB,OAAM,WAAW,IAAI,WAAW,YAAY,IAAI,MAAM,QAAQ,UAAU;UAC/D,IAAI,WAAW,OAExB,OAAM,WAAW,IAAI,WAAW,OAAO,IAAI,MAAM,QAAQ,UAAU;KAGnE,OAAM,QAAQ,mBAAmB,WAAW,IAAI,YAAY,gBAAe;AAI7E,KAAI,UAOF,WAN8B;EAC5B;EACA,UAAU;EACV,SAAS,EAAE,GAAG,kBAAkB;EAChC,QAAQ;EACT,CACgB;AAGnB,QAAO;EACL,MAAM,MAAM,UAAU;EACtB,KAAK,MAAM,YAAY;GAAE,QAAQ;GAAU,gBAAgB;GAAM,CAAC;EAClE,WAAW;EACZ"}
@@ -0,0 +1,241 @@
1
+ import { createRequire } from "node:module";
2
+ import { join, relative } from "node:path";
3
+ import { intlayerOptimizeBabelPlugin } from "@intlayer/babel";
4
+ import { prepareIntlayer, watch } from "@intlayer/chokidar";
5
+ import { getAppLogger, getConfiguration } from "@intlayer/config";
6
+ import fg from "fast-glob";
7
+
8
+ //#region src/VueIntlayerCompiler.ts
9
+ /**
10
+ * Create a VueIntlayerCompiler - A Vite-compatible compiler plugin for Vue with Intlayer
11
+ *
12
+ * Handles Vue Single File Components (SFC) with special handling for:
13
+ * - Script blocks in .vue files
14
+ * - TypeScript in Vue files
15
+ * - Vue-specific transformations
16
+ *
17
+ * @example
18
+ * ```ts
19
+ * // vite.config.ts
20
+ * import { defineConfig } from 'vite';
21
+ * import vue from '@vitejs/plugin-vue';
22
+ * import { vueIntlayerCompiler } from '@intlayer/vue-compiler';
23
+ *
24
+ * export default defineConfig({
25
+ * plugins: [vue(), vueIntlayerCompiler()],
26
+ * });
27
+ * ```
28
+ */
29
+ const createVueIntlayerCompiler = (options) => {
30
+ let config;
31
+ let logger;
32
+ let projectRoot = "";
33
+ let mode = "dev";
34
+ let hmrVersion = -1;
35
+ const lastSourceTriggeredWrite = 0;
36
+ let filesList = [];
37
+ let babel = null;
38
+ let liveSyncKeys = [];
39
+ const configOptions = options?.configOptions;
40
+ const customCompilerConfig = options?.compilerConfig;
41
+ /**
42
+ * Build the list of files to transform based on configuration patterns
43
+ * Includes Vue-specific patterns
44
+ */
45
+ const buildFilesList = async () => {
46
+ const { traversePattern } = config.build;
47
+ const { baseDir, mainDir } = config.content;
48
+ const transformPattern = customCompilerConfig?.transformPattern ?? traversePattern;
49
+ const excludePattern = customCompilerConfig?.excludePattern ?? ["**/node_modules/**"];
50
+ const patterns = Array.isArray(transformPattern) ? transformPattern : [transformPattern];
51
+ const vuePatterns = patterns.map((p) => {
52
+ if (p.includes(".vue") || p.includes("{")) return p;
53
+ return p.replace(/\{([^}]+)\}/, (_, exts) => `{${exts},vue}`);
54
+ });
55
+ const excludePatterns = Array.isArray(excludePattern) ? excludePattern : [excludePattern];
56
+ const filesListPattern = fg.sync([...new Set([...patterns, ...vuePatterns])], {
57
+ cwd: baseDir,
58
+ ignore: excludePatterns
59
+ }).map((file) => join(baseDir, file));
60
+ const dictionariesEntryPath = join(mainDir, "dictionaries.mjs");
61
+ const unmergedDictionariesEntryPath = join(mainDir, "unmerged_dictionaries.mjs");
62
+ filesList = [
63
+ ...filesListPattern,
64
+ dictionariesEntryPath,
65
+ unmergedDictionariesEntryPath
66
+ ];
67
+ };
68
+ /**
69
+ * Load dictionary keys that have live sync enabled
70
+ */
71
+ const loadLiveSyncKeys = async () => {
72
+ try {
73
+ const { getDictionaries } = await import("@intlayer/dictionaries-entry");
74
+ const dictionaries = getDictionaries();
75
+ liveSyncKeys = Object.values(dictionaries).filter((dictionary) => dictionary.live).map((dictionary) => dictionary.key);
76
+ } catch {
77
+ liveSyncKeys = [];
78
+ }
79
+ };
80
+ /**
81
+ * Initialize the compiler with the given mode
82
+ */
83
+ const init = async (compilerMode) => {
84
+ mode = compilerMode;
85
+ config = getConfiguration(configOptions);
86
+ logger = getAppLogger(config);
87
+ try {
88
+ babel = createRequire(import.meta.url)("@babel/core");
89
+ } catch {
90
+ logger("Failed to load @babel/core. Transformation will be disabled.", { level: "warn" });
91
+ }
92
+ await buildFilesList();
93
+ await loadLiveSyncKeys();
94
+ };
95
+ /**
96
+ * Vite hook: configResolved
97
+ */
98
+ const configResolved = async (viteConfig) => {
99
+ const compilerMode = viteConfig.env?.DEV ? "dev" : "build";
100
+ projectRoot = viteConfig.root;
101
+ await init(compilerMode);
102
+ };
103
+ /**
104
+ * Prepare intlayer dictionaries and types
105
+ */
106
+ const buildStart = async () => {
107
+ const isBuild = mode === "build";
108
+ await prepareIntlayer(config, {
109
+ clean: isBuild,
110
+ cacheTimeoutMs: isBuild ? 1e3 * 30 : 1e3 * 60 * 60
111
+ });
112
+ };
113
+ /**
114
+ * Configure the dev server with file watching
115
+ */
116
+ const configureServer = async () => {
117
+ if (config.content.watch) watch({ configuration: config });
118
+ };
119
+ /**
120
+ * Handle HMR for content changes
121
+ */
122
+ const handleHotUpdate = async (ctx) => {
123
+ const { file, server } = ctx;
124
+ if (!config.content.watchedFilesPatternWithPath.some((pattern) => {
125
+ return new RegExp(pattern.replace(/\*\*/g, ".*").replace(/\*/g, "[^/]*")).test(file);
126
+ })) {
127
+ const dictionariesDir = config.content.dictionariesDir;
128
+ if (file.startsWith(dictionariesDir)) return [];
129
+ hmrVersion++;
130
+ return;
131
+ }
132
+ if (!(performance.now() - lastSourceTriggeredWrite < 1e3)) {
133
+ server.ws.send({ type: "full-reload" });
134
+ return [];
135
+ }
136
+ };
137
+ /**
138
+ * Transform handler with Vue-specific handling
139
+ */
140
+ const transformHandler = async (code, id, _options) => {
141
+ if (!babel) return null;
142
+ const { optimize, importMode } = config.build;
143
+ if (!optimize && mode !== "build") return null;
144
+ const { dictionariesDir, dynamicDictionariesDir, unmergedDictionariesDir, fetchDictionariesDir, mainDir } = config.content;
145
+ /**
146
+ * Handle Vue SFC virtual modules
147
+ * Transform paths like:
148
+ * - .../Component.vue?vue&type=script&setup=true&lang.ts
149
+ * Into:
150
+ * - .../Component.vue
151
+ */
152
+ const filename = id.split("?", 1)[0];
153
+ const checkFilename = id.includes("?vue&type=script") ? filename : filename;
154
+ if (!filesList.includes(checkFilename)) {
155
+ const baseVueFile = filename.endsWith(".vue") ? filename : null;
156
+ if (!baseVueFile || !filesList.some((f) => f === baseVueFile || f.startsWith(baseVueFile))) return null;
157
+ }
158
+ const dictionariesEntryPath = join(mainDir, "dictionaries.mjs");
159
+ const unmergedDictionariesEntryPath = join(mainDir, "unmerged_dictionaries.mjs");
160
+ const dynamicDictionariesEntryPath = join(mainDir, "dynamic_dictionaries.mjs");
161
+ try {
162
+ const result = babel.transformSync(code, {
163
+ filename,
164
+ plugins: [[intlayerOptimizeBabelPlugin, {
165
+ dictionariesDir,
166
+ dictionariesEntryPath,
167
+ unmergedDictionariesEntryPath,
168
+ unmergedDictionariesDir,
169
+ dynamicDictionariesDir,
170
+ dynamicDictionariesEntryPath,
171
+ fetchDictionariesDir,
172
+ importMode,
173
+ filesList,
174
+ replaceDictionaryEntry: true,
175
+ liveSyncKeys
176
+ }]],
177
+ parserOpts: {
178
+ sourceType: "module",
179
+ allowImportExportEverywhere: true,
180
+ plugins: [
181
+ "typescript",
182
+ "jsx",
183
+ "decorators-legacy",
184
+ "classProperties",
185
+ "objectRestSpread",
186
+ "asyncGenerators",
187
+ "functionBind",
188
+ "exportDefaultFrom",
189
+ "exportNamespaceFrom",
190
+ "dynamicImport",
191
+ "nullishCoalescingOperator",
192
+ "optionalChaining"
193
+ ]
194
+ }
195
+ });
196
+ if (result?.code) return {
197
+ code: result.code,
198
+ map: result.map
199
+ };
200
+ } catch (error) {
201
+ logger(`Failed to transform Vue file ${relative(projectRoot, filename)}: ${error}`, { level: "error" });
202
+ }
203
+ return null;
204
+ };
205
+ /**
206
+ * Apply hook for determining when plugin should be active
207
+ */
208
+ const apply = (_config, env) => {
209
+ const { optimize } = config?.build ?? {};
210
+ const isEnabled = customCompilerConfig?.enabled ?? true;
211
+ const isBuild = env.command === "build";
212
+ return isEnabled && (isBuild ? optimize ?? true : optimize ?? false);
213
+ };
214
+ return {
215
+ name: "vue-intlayer-compiler",
216
+ enforce: "post",
217
+ configResolved,
218
+ buildStart,
219
+ configureServer,
220
+ handleHotUpdate,
221
+ transform: {
222
+ order: "post",
223
+ handler: transformHandler
224
+ },
225
+ apply: (_viteConfig, env) => {
226
+ if (!config) config = getConfiguration(configOptions);
227
+ return apply(_viteConfig, env);
228
+ }
229
+ };
230
+ };
231
+ /**
232
+ * Factory function for creating a Vite plugin
233
+ */
234
+ const vueIntlayerCompiler = (options) => {
235
+ return createVueIntlayerCompiler(options);
236
+ };
237
+ const VueIntlayerCompiler = createVueIntlayerCompiler;
238
+
239
+ //#endregion
240
+ export { VueIntlayerCompiler, createVueIntlayerCompiler, vueIntlayerCompiler };
241
+ //# sourceMappingURL=VueIntlayerCompiler.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"VueIntlayerCompiler.mjs","names":["config: IntlayerConfig","logger: ReturnType<typeof getAppLogger>","mode: CompilerMode","filesList: string[]","babel: typeof import('@babel/core') | null","liveSyncKeys: string[]","compilerMode: CompilerMode"],"sources":["../../src/VueIntlayerCompiler.ts"],"sourcesContent":["import { createRequire } from 'node:module';\nimport { join, relative } from 'node:path';\nimport { intlayerOptimizeBabelPlugin } from '@intlayer/babel';\nimport { watch as chokidarWatch, prepareIntlayer } from '@intlayer/chokidar';\nimport {\n type GetConfigurationOptions,\n getAppLogger,\n getConfiguration,\n} from '@intlayer/config';\nimport type { CompilerConfig, IntlayerConfig } from '@intlayer/types';\nimport fg from 'fast-glob';\n\n/**\n * Mode of the compiler\n */\nexport type CompilerMode = 'dev' | 'build';\n\n/**\n * Context for hot update handling\n */\nexport type HotUpdateContext = {\n file: string;\n server: {\n ws: { send: (message: { type: string }) => void };\n moduleGraph: {\n getModulesByFile: (file: string) => Set<unknown> | null | undefined;\n invalidateModule: (\n module: unknown,\n seen: Set<unknown>,\n timestamp: number,\n isHmr: boolean\n ) => void;\n };\n };\n timestamp: number;\n};\n\n/**\n * Transform result from the compiler\n */\nexport type TransformResult = {\n code?: string;\n map?: unknown;\n} | null;\n\n/**\n * Options for initializing the Vue compiler\n */\nexport type VueIntlayerCompilerOptions = {\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 * Vite plugin object returned by the compiler\n */\nexport type VueIntlayerVitePlugin = {\n name: string;\n enforce: 'pre' | 'post';\n configResolved: (config: {\n env?: { DEV?: boolean };\n root: string;\n }) => Promise<void>;\n buildStart: () => Promise<void>;\n configureServer: () => Promise<void>;\n handleHotUpdate: (ctx: HotUpdateContext) => Promise<unknown[] | undefined>;\n transform: {\n order: 'pre' | 'post';\n handler: (\n code: string,\n id: string,\n options?: { ssr?: boolean }\n ) => Promise<TransformResult>;\n };\n apply: (config: unknown, env: { command: string }) => boolean;\n};\n\n/**\n * Create a VueIntlayerCompiler - A Vite-compatible compiler plugin for Vue with Intlayer\n *\n * Handles Vue Single File Components (SFC) with special handling for:\n * - Script blocks in .vue files\n * - TypeScript in Vue files\n * - Vue-specific transformations\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { defineConfig } from 'vite';\n * import vue from '@vitejs/plugin-vue';\n * import { vueIntlayerCompiler } from '@intlayer/vue-compiler';\n *\n * export default defineConfig({\n * plugins: [vue(), vueIntlayerCompiler()],\n * });\n * ```\n */\nexport const createVueIntlayerCompiler = (\n options?: VueIntlayerCompilerOptions\n): VueIntlayerVitePlugin => {\n // Private state\n let config: IntlayerConfig;\n let logger: ReturnType<typeof getAppLogger>;\n let projectRoot = '';\n let mode: CompilerMode = 'dev';\n let hmrVersion = -1;\n const lastSourceTriggeredWrite = 0;\n let filesList: string[] = [];\n // @ts-expect-error - @babel/core is a peer dependency\n let babel: typeof import('@babel/core') | null = null;\n let liveSyncKeys: string[] = [];\n\n const configOptions = options?.configOptions;\n const customCompilerConfig = options?.compilerConfig;\n\n /**\n * Build the list of files to transform based on configuration patterns\n * Includes Vue-specific patterns\n */\n const buildFilesList = async (): Promise<void> => {\n const { traversePattern } = config.build;\n const { baseDir, mainDir } = config.content;\n\n const transformPattern =\n customCompilerConfig?.transformPattern ?? traversePattern;\n const excludePattern = customCompilerConfig?.excludePattern ?? [\n '**/node_modules/**',\n ];\n\n // Add Vue file patterns\n const patterns = Array.isArray(transformPattern)\n ? transformPattern\n : [transformPattern];\n const vuePatterns = patterns.map((p) => {\n // Ensure Vue files are included\n if (p.includes('.vue') || p.includes('{')) {\n return p;\n }\n // Add .vue extension to patterns\n return p.replace(/\\{([^}]+)\\}/, (_, exts) => `{${exts},vue}`);\n });\n\n const excludePatterns = Array.isArray(excludePattern)\n ? excludePattern\n : [excludePattern];\n\n const filesListPattern = fg\n .sync([...new Set([...patterns, ...vuePatterns])], {\n cwd: baseDir,\n ignore: excludePatterns,\n })\n .map((file) => join(baseDir, file));\n\n const dictionariesEntryPath = join(mainDir, 'dictionaries.mjs');\n const unmergedDictionariesEntryPath = join(\n mainDir,\n 'unmerged_dictionaries.mjs'\n );\n\n filesList = [\n ...filesListPattern,\n dictionariesEntryPath,\n unmergedDictionariesEntryPath,\n ];\n };\n\n /**\n * Load dictionary keys that have live sync enabled\n */\n const loadLiveSyncKeys = async (): Promise<void> => {\n try {\n const { getDictionaries } = await import('@intlayer/dictionaries-entry');\n const dictionaries = getDictionaries() as Record<\n string,\n { live?: boolean; key: string }\n >;\n liveSyncKeys = Object.values(dictionaries)\n .filter((dictionary) => dictionary.live)\n .map((dictionary) => dictionary.key);\n } catch {\n liveSyncKeys = [];\n }\n };\n\n /**\n * Initialize the compiler with the given mode\n */\n const init = async (compilerMode: CompilerMode): Promise<void> => {\n mode = compilerMode;\n config = getConfiguration(configOptions);\n logger = getAppLogger(config);\n\n // Load Babel dynamically\n try {\n const localRequire = createRequire(import.meta.url);\n babel = localRequire('@babel/core');\n } catch {\n logger('Failed to load @babel/core. Transformation will be disabled.', {\n level: 'warn',\n });\n }\n\n // Build files list for transformation\n await buildFilesList();\n\n // Load live sync keys\n await loadLiveSyncKeys();\n };\n\n /**\n * Vite hook: configResolved\n */\n const configResolved = async (viteConfig: {\n env?: { DEV?: boolean };\n root: string;\n }): Promise<void> => {\n const compilerMode: CompilerMode = viteConfig.env?.DEV ? 'dev' : 'build';\n projectRoot = viteConfig.root;\n await init(compilerMode);\n };\n\n /**\n * Prepare intlayer dictionaries and types\n */\n const buildStart = async (): Promise<void> => {\n const isBuild = mode === 'build';\n\n await prepareIntlayer(config, {\n clean: isBuild,\n cacheTimeoutMs: isBuild ? 1000 * 30 : 1000 * 60 * 60,\n });\n };\n\n /**\n * Configure the dev server with file watching\n */\n const configureServer = async (): Promise<void> => {\n if (config.content.watch) {\n chokidarWatch({ configuration: config });\n }\n };\n\n /**\n * Handle HMR for content changes\n */\n const handleHotUpdate = async (\n ctx: HotUpdateContext\n ): Promise<unknown[] | undefined> => {\n const { file, server } = ctx;\n\n // Check if this is a content declaration file\n const isContentFile = config.content.watchedFilesPatternWithPath.some(\n (pattern: string) => {\n const regex = new RegExp(\n pattern.replace(/\\*\\*/g, '.*').replace(/\\*/g, '[^/]*')\n );\n return regex.test(file);\n }\n );\n\n if (!isContentFile) {\n const dictionariesDir = config.content.dictionariesDir;\n if (file.startsWith(dictionariesDir)) {\n return [];\n }\n hmrVersion++;\n return undefined;\n }\n\n const sourceTriggered = performance.now() - lastSourceTriggeredWrite < 1000;\n\n if (!sourceTriggered) {\n server.ws.send({ type: 'full-reload' });\n return [];\n }\n\n return undefined;\n };\n\n /**\n * Transform handler with Vue-specific handling\n */\n const transformHandler = async (\n code: string,\n id: string,\n _options?: { ssr?: boolean }\n ): Promise<TransformResult> => {\n if (!babel) {\n return null;\n }\n\n const { optimize, importMode } = config.build;\n\n if (!optimize && mode !== 'build') {\n return null;\n }\n\n const {\n dictionariesDir,\n dynamicDictionariesDir,\n unmergedDictionariesDir,\n fetchDictionariesDir,\n mainDir,\n } = config.content;\n\n /**\n * Handle Vue SFC virtual modules\n * Transform paths like:\n * - .../Component.vue?vue&type=script&setup=true&lang.ts\n * Into:\n * - .../Component.vue\n */\n const filename = id.split('?', 1)[0];\n\n // Check if this file should be transformed\n // For Vue files, also check the base .vue file\n const isVueVirtualModule = id.includes('?vue&type=script');\n const checkFilename = isVueVirtualModule ? filename : filename;\n\n if (!filesList.includes(checkFilename)) {\n // Also check without the virtual module query\n const baseVueFile = filename.endsWith('.vue') ? filename : null;\n if (\n !baseVueFile ||\n !filesList.some((f) => f === baseVueFile || f.startsWith(baseVueFile))\n ) {\n return null;\n }\n }\n\n const dictionariesEntryPath = join(mainDir, 'dictionaries.mjs');\n const unmergedDictionariesEntryPath = join(\n mainDir,\n 'unmerged_dictionaries.mjs'\n );\n const dynamicDictionariesEntryPath = join(\n mainDir,\n 'dynamic_dictionaries.mjs'\n );\n\n try {\n const result = babel.transformSync(code, {\n filename,\n plugins: [\n [\n intlayerOptimizeBabelPlugin,\n {\n dictionariesDir,\n dictionariesEntryPath,\n unmergedDictionariesEntryPath,\n unmergedDictionariesDir,\n dynamicDictionariesDir,\n dynamicDictionariesEntryPath,\n fetchDictionariesDir,\n importMode,\n filesList,\n replaceDictionaryEntry: true,\n liveSyncKeys,\n },\n ],\n ],\n parserOpts: {\n sourceType: 'module',\n allowImportExportEverywhere: true,\n plugins: [\n 'typescript',\n 'jsx',\n 'decorators-legacy',\n 'classProperties',\n 'objectRestSpread',\n 'asyncGenerators',\n 'functionBind',\n 'exportDefaultFrom',\n 'exportNamespaceFrom',\n 'dynamicImport',\n 'nullishCoalescingOperator',\n 'optionalChaining',\n ],\n },\n });\n\n if (result?.code) {\n return {\n code: result.code,\n map: result.map,\n };\n }\n } catch (error) {\n logger(\n `Failed to transform Vue file ${relative(projectRoot, filename)}: ${error}`,\n {\n level: 'error',\n }\n );\n }\n\n return null;\n };\n\n /**\n * Apply hook for determining when plugin should be active\n */\n const apply = (_config: unknown, env: { command: string }): boolean => {\n const { optimize } = config?.build ?? {};\n const isEnabled = customCompilerConfig?.enabled ?? true;\n const isBuild = env.command === 'build';\n\n return isEnabled && (isBuild ? (optimize ?? true) : (optimize ?? false));\n };\n\n return {\n name: 'vue-intlayer-compiler',\n enforce: 'post', // Run after Vue plugin\n configResolved,\n buildStart,\n configureServer,\n handleHotUpdate,\n transform: {\n order: 'post', // Run after Vue plugin transformation\n handler: transformHandler,\n },\n apply: (_viteConfig: unknown, env: { command: string }) => {\n if (!config) {\n config = getConfiguration(configOptions);\n }\n return apply(_viteConfig, env);\n },\n };\n};\n\n/**\n * Factory function for creating a Vite plugin\n */\nexport const vueIntlayerCompiler = (\n options?: VueIntlayerCompilerOptions\n): VueIntlayerVitePlugin => {\n return createVueIntlayerCompiler(options);\n};\n\n// Legacy export for backwards compatibility\nexport const VueIntlayerCompiler = createVueIntlayerCompiler;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwGA,MAAa,6BACX,YAC0B;CAE1B,IAAIA;CACJ,IAAIC;CACJ,IAAI,cAAc;CAClB,IAAIC,OAAqB;CACzB,IAAI,aAAa;CACjB,MAAM,2BAA2B;CACjC,IAAIC,YAAsB,EAAE;CAE5B,IAAIC,QAA6C;CACjD,IAAIC,eAAyB,EAAE;CAE/B,MAAM,gBAAgB,SAAS;CAC/B,MAAM,uBAAuB,SAAS;;;;;CAMtC,MAAM,iBAAiB,YAA2B;EAChD,MAAM,EAAE,oBAAoB,OAAO;EACnC,MAAM,EAAE,SAAS,YAAY,OAAO;EAEpC,MAAM,mBACJ,sBAAsB,oBAAoB;EAC5C,MAAM,iBAAiB,sBAAsB,kBAAkB,CAC7D,qBACD;EAGD,MAAM,WAAW,MAAM,QAAQ,iBAAiB,GAC5C,mBACA,CAAC,iBAAiB;EACtB,MAAM,cAAc,SAAS,KAAK,MA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S,MAAM,cAAc,MAAM;IACvC;IACA,SAAS,CACP,CACE,6BACA;KACE;KACA;KACA;KACA;KACA;KACA;KACA;KACA;KACA;KACA,wBAAwB;KACxB;KACD,CACF,CACF;IACD,YAAY;KACV,YAAY;KACZ,6BAA6B;KAC7B,SAAS;MACP;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACA;MACD;KACF;IACF,CAAC;AAEF,OAAI,QAAQ,KACV,QAAO;IACL,MAAM,OAAO;IACb,KAAK,OAAO;IACb;WAEI,OAAO;AACd,UACE,gCAAgC,SAAS,aAAa,SAAS,CAAC,IAAI,SACpE,EACE,OAAO,SACR,CACF;;AAGH,SAAO;;;;;CAMT,MAAM,SAAS,SAAkB,QAAsC;EACrE,MAAM,EAAE,aAAa,QAAQ,SAAS,EAAE;EACxC,MAAM,YAAY,sBAAsB,WAAW;EACnD,MAAM,UAAU,IAAI,YAAY;AAEhC,SAAO,cAAc,UAAW,YAAY,OAAS,YAAY;;AAGnE,QAAO;EACL,MAAM;EACN,SAAS;EACT;EACA;EACA;EACA;EACA,WAAW;GACT,OAAO;GACP,SAAS;GACV;EACD,QAAQ,aAAsB,QAA6B;AACzD,OAAI,CAAC,OACH,UAAS,iBAAiB,cAAc;AAE1C,UAAO,MAAM,aAAa,IAAI;;EAEjC;;;;;AAMH,MAAa,uBACX,YAC0B;AAC1B,QAAO,0BAA0B,QAAQ;;AAI3C,MAAa,sBAAsB"}
@@ -0,0 +1,4 @@
1
+ import { VueIntlayerCompiler, createVueIntlayerCompiler, vueIntlayerCompiler } from "./VueIntlayerCompiler.mjs";
2
+ import { ATTRIBUTES_TO_EXTRACT, defaultShouldExtract, extractDictionaryKeyFromPath, generateKey, intlayerVueExtract, shouldProcessFile } from "./vue-intlayer-extract.mjs";
3
+
4
+ export { ATTRIBUTES_TO_EXTRACT, VueIntlayerCompiler, createVueIntlayerCompiler, defaultShouldExtract, extractDictionaryKeyFromPath, generateKey, intlayerVueExtract, shouldProcessFile, vueIntlayerCompiler };
@@ -0,0 +1,168 @@
1
+ import { basename, dirname, extname } from "node:path";
2
+
3
+ //#region src/vue-intlayer-extract.ts
4
+ /**
5
+ * Attributes that should be extracted for localization
6
+ */
7
+ const ATTRIBUTES_TO_EXTRACT = [
8
+ "title",
9
+ "placeholder",
10
+ "alt",
11
+ "aria-label",
12
+ "label"
13
+ ];
14
+ /**
15
+ * Default function to determine if a string should be extracted
16
+ */
17
+ const defaultShouldExtract = (text) => {
18
+ const trimmed = text.trim();
19
+ if (!trimmed) return false;
20
+ if (!trimmed.includes(" ")) return false;
21
+ if (!/^[A-Z]/.test(trimmed)) return false;
22
+ if (trimmed.startsWith("{") || trimmed.startsWith("v-")) return false;
23
+ return true;
24
+ };
25
+ /**
26
+ * Generate a unique key from text
27
+ */
28
+ const generateKey = (text, existingKeys) => {
29
+ let key = text.replace(/\s+/g, " ").replace(/_+/g, " ").replace(/-+/g, " ").replace(/[^a-zA-Z0-9 ]/g, "").trim().split(" ").filter(Boolean).slice(0, 5).map((word, index) => index === 0 ? word.toLowerCase() : word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join("");
30
+ if (!key) key = "content";
31
+ if (existingKeys.has(key)) {
32
+ let i = 1;
33
+ while (existingKeys.has(`${key}${i}`)) i++;
34
+ key = `${key}${i}`;
35
+ }
36
+ return key;
37
+ };
38
+ /**
39
+ * Extract dictionary key from file path
40
+ */
41
+ const extractDictionaryKeyFromPath = (filePath) => {
42
+ let baseName = basename(filePath, extname(filePath));
43
+ if (baseName === "index") baseName = basename(dirname(filePath));
44
+ return `comp-${baseName.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/[\s_]+/g, "-").toLowerCase()}`;
45
+ };
46
+ /**
47
+ * Check if a file should be processed based on filesList
48
+ */
49
+ const shouldProcessFile = (filename, filesList) => {
50
+ if (!filename) return false;
51
+ if (!filesList || filesList.length === 0) return true;
52
+ const normalizedFilename = filename.replace(/\\/g, "/");
53
+ return filesList.some((f) => {
54
+ return f.replace(/\\/g, "/") === normalizedFilename;
55
+ });
56
+ };
57
+ const NODE_TYPES = {
58
+ TEXT: 2,
59
+ ELEMENT: 1,
60
+ ATTRIBUTE: 6
61
+ };
62
+ /**
63
+ * Vue extraction plugin that extracts content and transforms Vue SFC to use useIntlayer.
64
+ *
65
+ * This plugin:
66
+ * 1. Scans Vue SFC files for extractable text (template text, attributes)
67
+ * 2. Auto-injects useIntlayer import and composable call
68
+ * 3. Reports extracted content via onExtract callback (for the compiler to write dictionaries)
69
+ * 4. Replaces extractable strings with content references
70
+ *
71
+ * ## Input
72
+ * ```vue
73
+ * <template>
74
+ * <div>Hello World</div>
75
+ * </template>
76
+ * ```
77
+ *
78
+ * ## Output
79
+ * ```vue
80
+ * <script setup>
81
+ * import { useIntlayer } from 'vue-intlayer';
82
+ * const content = useIntlayer('hello-world');
83
+ * <\/script>
84
+ * <template>
85
+ * <div>{{ content.helloWorld }}</div>
86
+ * </template>
87
+ * ```
88
+ */
89
+ const intlayerVueExtract = async (code, filename, options = {}) => {
90
+ const { defaultLocale = "en", packageName = "vue-intlayer", filesList, shouldExtract = defaultShouldExtract, onExtract } = options;
91
+ if (!shouldProcessFile(filename, filesList)) return null;
92
+ if (!filename.endsWith(".vue")) return null;
93
+ let parseVue;
94
+ let MagicString;
95
+ try {
96
+ parseVue = (await import("@vue/compiler-sfc")).parse;
97
+ } catch {
98
+ console.warn("Vue extraction: @vue/compiler-sfc not found. Install it to enable Vue content extraction.");
99
+ return null;
100
+ }
101
+ try {
102
+ MagicString = (await import("magic-string")).default;
103
+ } catch {
104
+ console.warn("Vue extraction: magic-string not found. Install it to enable Vue content extraction.");
105
+ return null;
106
+ }
107
+ const sfc = parseVue(code);
108
+ const magic = new MagicString(code);
109
+ const extractedContent = {};
110
+ const existingKeys = /* @__PURE__ */ new Set();
111
+ const dictionaryKey = extractDictionaryKeyFromPath(filename);
112
+ if (sfc.descriptor.template) {
113
+ const walkVueAst = (node) => {
114
+ if (node.type === NODE_TYPES.TEXT) {
115
+ const text = node.content ?? "";
116
+ if (shouldExtract(text)) {
117
+ const key = generateKey(text, existingKeys);
118
+ existingKeys.add(key);
119
+ extractedContent[key] = text.replace(/\s+/g, " ").trim();
120
+ magic.overwrite(node.loc.start.offset, node.loc.end.offset, `{{ content.${key} }}`);
121
+ }
122
+ } else if (node.type === NODE_TYPES.ELEMENT) node.props?.forEach((prop) => {
123
+ if (prop.type === NODE_TYPES.ATTRIBUTE && ATTRIBUTES_TO_EXTRACT.includes(prop.name) && prop.value) {
124
+ const text = prop.value.content;
125
+ if (shouldExtract(text)) {
126
+ const key = generateKey(text, existingKeys);
127
+ existingKeys.add(key);
128
+ extractedContent[key] = text.trim();
129
+ magic.overwrite(prop.loc.start.offset, prop.loc.end.offset, `:${prop.name}="content.${key}.value"`);
130
+ }
131
+ }
132
+ });
133
+ if (node.children) node.children.forEach(walkVueAst);
134
+ };
135
+ walkVueAst(sfc.descriptor.template.ast);
136
+ }
137
+ if (Object.keys(extractedContent).length === 0) return null;
138
+ const scriptContent = sfc.descriptor.scriptSetup?.content ?? sfc.descriptor.script?.content ?? "";
139
+ const hasUseIntlayerImport = /import\s*{[^}]*useIntlayer[^}]*}\s*from\s*['"][^'"]+['"]/.test(scriptContent) || /import\s+useIntlayer\s+from\s*['"][^'"]+['"]/.test(scriptContent);
140
+ const hasContentDeclaration = /const\s+content\s*=\s*useIntlayer\s*\(/.test(scriptContent);
141
+ if (hasUseIntlayerImport && hasContentDeclaration) return null;
142
+ const importStmt = hasUseIntlayerImport ? "" : `import { useIntlayer } from '${packageName}';`;
143
+ const contentDecl = hasContentDeclaration ? "" : `const content = useIntlayer('${dictionaryKey}');`;
144
+ const injectionParts = [importStmt, contentDecl].filter(Boolean);
145
+ if (injectionParts.length === 0) return null;
146
+ const injection = `\n${injectionParts.join("\n")}\n`;
147
+ if (sfc.descriptor.scriptSetup) magic.appendLeft(sfc.descriptor.scriptSetup.loc.start.offset, injection);
148
+ else if (sfc.descriptor.script) magic.appendLeft(sfc.descriptor.script.loc.start.offset, injection);
149
+ else magic.prepend(`<script setup>\n${importStmt}\n${contentDecl}\n<\/script>\n`);
150
+ if (onExtract) onExtract({
151
+ dictionaryKey,
152
+ filePath: filename,
153
+ content: { ...extractedContent },
154
+ locale: defaultLocale
155
+ });
156
+ return {
157
+ code: magic.toString(),
158
+ map: magic.generateMap({
159
+ source: filename,
160
+ includeContent: true
161
+ }),
162
+ extracted: true
163
+ };
164
+ };
165
+
166
+ //#endregion
167
+ export { ATTRIBUTES_TO_EXTRACT, defaultShouldExtract, extractDictionaryKeyFromPath, generateKey, intlayerVueExtract, shouldProcessFile };
168
+ //# sourceMappingURL=vue-intlayer-extract.mjs.map