@intlayer/svelte-compiler 9.7.3 → 9.8.0-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.
|
@@ -3,6 +3,7 @@ const require_runtime = require("./_virtual/_rolldown/runtime.cjs");
|
|
|
3
3
|
let node_fs = require("node:fs");
|
|
4
4
|
let _babel_core = require("@babel/core");
|
|
5
5
|
let _intlayer_config_defaultValues = require("@intlayer/config/defaultValues");
|
|
6
|
+
let _intlayer_config_extract = require("@intlayer/config/extract");
|
|
6
7
|
let magic_string = require("magic-string");
|
|
7
8
|
magic_string = require_runtime.__toESM(magic_string);
|
|
8
9
|
let svelte_compiler = require("svelte/compiler");
|
|
@@ -63,6 +64,8 @@ const intlayerSvelteExtract = (code, filename, options = {}) => {
|
|
|
63
64
|
const { defaultLocale = _intlayer_config_defaultValues.DEFAULT_LOCALE, packageName = "svelte-intlayer", filesList, shouldExtract, onExtract, dictionaryKey: dictionaryKeyOption, attributesToExtract = [], extractDictionaryKeyFromPath, generateKey } = options;
|
|
64
65
|
if (!shouldProcessFile(filename, filesList)) return null;
|
|
65
66
|
if (!filename.endsWith(".svelte")) return null;
|
|
67
|
+
const ignoreDirectives = (0, _intlayer_config_extract.getExtractionIgnoreDirectives)(code);
|
|
68
|
+
if (ignoreDirectives.isFileIgnored) return null;
|
|
66
69
|
const magic = new magic_string.default(code);
|
|
67
70
|
const extractedContent = {};
|
|
68
71
|
const existingKeys = /* @__PURE__ */ new Set();
|
|
@@ -84,10 +87,17 @@ const intlayerSvelteExtract = (code, filename, options = {}) => {
|
|
|
84
87
|
const isTextNode = (node) => node.type === "Text" || node.type === 3;
|
|
85
88
|
const isAttributeNode = (node) => node.type === "Attribute" || node.type === 6;
|
|
86
89
|
const isExpressionTagNode = (node) => node.type === "MustacheTag" || node.type === 8 || node.type === "ExpressionTag";
|
|
87
|
-
|
|
90
|
+
/**
|
|
91
|
+
* Walks the markup; `isParentIgnored` is true when an ignore directive
|
|
92
|
+
* covers the opening tag of the enclosing element.
|
|
93
|
+
*/
|
|
94
|
+
const walkSvelte = (node, isParentIgnored = false) => {
|
|
95
|
+
const isNodeIgnored = ignoreDirectives.isOffsetIgnored(node.start);
|
|
96
|
+
const isChildIgnored = typeof node.name === "string" && !isAttributeNode(node) ? isNodeIgnored : isParentIgnored;
|
|
88
97
|
if (isTextNode(node)) {
|
|
89
98
|
const text = node.data ?? node.content ?? "";
|
|
90
|
-
|
|
99
|
+
const leadingWhitespaceLength = text.length - text.trimStart().length;
|
|
100
|
+
if (!(isParentIgnored || ignoreDirectives.isOffsetIgnored(node.start + leadingWhitespaceLength)) && shouldExtract?.(text) && generateKey) {
|
|
91
101
|
const key = generateKey(text, existingKeys);
|
|
92
102
|
existingKeys.add(key);
|
|
93
103
|
const ref = isDestructured ? key : `$${varName}.${key}`;
|
|
@@ -100,7 +110,7 @@ const intlayerSvelteExtract = (code, filename, options = {}) => {
|
|
|
100
110
|
});
|
|
101
111
|
}
|
|
102
112
|
} else if (isAttributeNode(node) && attributesToExtract.includes(node.name)) {
|
|
103
|
-
if (node.value && node.value.length === 1 && isTextNode(node.value[0])) {
|
|
113
|
+
if (!isParentIgnored && !isNodeIgnored && node.value && node.value.length === 1 && isTextNode(node.value[0])) {
|
|
104
114
|
const text = node.value[0].data ?? node.value[0].content ?? "";
|
|
105
115
|
if (shouldExtract?.(text) && generateKey) {
|
|
106
116
|
const key = generateKey(text, existingKeys);
|
|
@@ -117,7 +127,7 @@ const intlayerSvelteExtract = (code, filename, options = {}) => {
|
|
|
117
127
|
}
|
|
118
128
|
}
|
|
119
129
|
const children = node.children ?? node.fragment?.nodes ?? node.fragment?.children;
|
|
120
|
-
if (children?.some(isExpressionTagNode)) {
|
|
130
|
+
if (!isChildIgnored && children?.some(isExpressionTagNode)) {
|
|
121
131
|
const parts = [];
|
|
122
132
|
let hasSignificantText = false;
|
|
123
133
|
let isValid = true;
|
|
@@ -158,13 +168,13 @@ const intlayerSvelteExtract = (code, filename, options = {}) => {
|
|
|
158
168
|
key,
|
|
159
169
|
value: cleanString
|
|
160
170
|
});
|
|
161
|
-
|
|
171
|
+
node.attributes?.forEach((attribute) => walkSvelte(attribute, isNodeIgnored));
|
|
162
172
|
return;
|
|
163
173
|
}
|
|
164
174
|
}
|
|
165
175
|
}
|
|
166
|
-
|
|
167
|
-
|
|
176
|
+
children?.forEach((child) => walkSvelte(child, isChildIgnored));
|
|
177
|
+
node.attributes?.forEach((attribute) => walkSvelte(attribute, isNodeIgnored));
|
|
168
178
|
};
|
|
169
179
|
if (ast.html) walkSvelte(ast.html);
|
|
170
180
|
if (scriptMatch) {
|
|
@@ -192,6 +202,7 @@ const intlayerSvelteExtract = (code, filename, options = {}) => {
|
|
|
192
202
|
if (_babel_core.types.isIdentifier(callee) && callee.name === "require") return;
|
|
193
203
|
}
|
|
194
204
|
const text = path.node.value;
|
|
205
|
+
if (path.node.start != null && ignoreDirectives.isOffsetIgnored(offset + path.node.start)) return;
|
|
195
206
|
if (shouldExtract?.(text) && generateKey) {
|
|
196
207
|
const key = generateKey(text, existingKeys);
|
|
197
208
|
existingKeys.add(key);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"svelte-intlayer-extract.cjs","names":["babelParse","t","DEFAULT_LOCALE","MagicString","parse","readFileSync"],"sources":["../../src/svelte-intlayer-extract.ts"],"sourcesContent":["import { readFileSync, writeFileSync } from 'node:fs';\nimport { parseSync as babelParse, types as t, traverse } from '@babel/core';\nimport { DEFAULT_LOCALE } from '@intlayer/config/defaultValues';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport MagicString from 'magic-string';\nimport { parse } from 'svelte/compiler';\n\ntype ExistingCallInfo = {\n isDestructured: boolean;\n existingDestructuredKeys: string[];\n /** The variable name used to store the call result (e.g. `t` in `const t = useIntlayer(...)`) */\n variableName: string;\n /** Absolute position of `}` in the full file — only valid when `isDestructured` */\n closingBraceAbsolutePos: number;\n /** Absolute position of end of last property — only valid when `isDestructured` */\n lastPropAbsoluteEnd: number;\n} | null;\n\n/**\n * Detects whether a script block already contains a `useIntlayer` /\n * `getIntlayer` call and whether its result is destructured.\n */\nconst detectExistingIntlayerCall = (\n scriptText: string,\n absoluteOffset: number\n): ExistingCallInfo => {\n let info: ExistingCallInfo = null;\n\n try {\n const ast = babelParse(scriptText, {\n configFile: false,\n babelrc: false,\n parserOpts: { sourceType: 'module', plugins: ['typescript', 'jsx'] },\n });\n\n if (!ast) return null;\n\n traverse(ast, {\n CallExpression(path: any) {\n const callee = path.node.callee;\n\n if (\n !t.isIdentifier(callee) ||\n (callee.name !== 'useIntlayer' && callee.name !== 'getIntlayer')\n )\n return;\n\n const parent = path.parent;\n\n if (t.isVariableDeclarator(parent) && t.isObjectPattern(parent.id)) {\n const properties = parent.id.properties;\n const existingDestructuredKeys = properties\n .filter(\n (p: any): p is typeof t.objectProperty =>\n t.isObjectProperty(p) && t.isIdentifier(p.key)\n )\n .map((p: any) => (p.key as any).name as string);\n const lastProp = properties[properties.length - 1];\n\n info = {\n isDestructured: true,\n variableName: 'content',\n existingDestructuredKeys,\n closingBraceAbsolutePos: absoluteOffset + (parent.id.end! - 1),\n lastPropAbsoluteEnd: absoluteOffset + lastProp.end!,\n };\n } else {\n const variableName =\n t.isVariableDeclarator(parent) && t.isIdentifier(parent.id)\n ? parent.id.name\n : 'content';\n\n info = {\n isDestructured: false,\n variableName,\n existingDestructuredKeys: [],\n closingBraceAbsolutePos: -1,\n lastPropAbsoluteEnd: -1,\n };\n }\n\n path.stop();\n },\n });\n } catch {\n // Silently ignore parse failures — fall back to no-info\n }\n\n return info;\n};\n\nexport type ExtractedContent = Record<string, string>;\n\nexport type ExtractResult = {\n dictionaryKey: string;\n filePath: string;\n content: ExtractedContent;\n locale: Locale;\n};\n\nexport type ExtractPluginOptions = {\n defaultLocale?: Locale;\n packageName?: string;\n filesList?: string[];\n shouldExtract?: (text: string) => boolean;\n onExtract?: (result: ExtractResult) => void;\n dictionaryKey?: string;\n attributesToExtract?: readonly string[];\n extractDictionaryKeyFromPath?: (path: string) => string;\n generateKey?: (text: string, existingKeys: Set<string>) => string;\n};\n\ntype Replacement = {\n start: number;\n end: number;\n replacement: string;\n key: string;\n value: string;\n};\n\n/* ────────────────────────────────────────── helpers ─────────────────────── */\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 const normalizedFilename = filename.replace(/\\\\/g, '/');\n return filesList.some((f) => {\n const normalizedF = f.replace(/\\\\/g, '/');\n return normalizedF === normalizedFilename;\n });\n};\n\n/* ────────────────────────────────────────── plugin ──────────────────────── */\n\nexport const intlayerSvelteExtract = (\n code: string,\n filename: string,\n options: ExtractPluginOptions = {}\n): { code: string; map?: unknown; extracted: boolean } | null => {\n const {\n defaultLocale = DEFAULT_LOCALE,\n packageName = 'svelte-intlayer',\n filesList,\n shouldExtract,\n onExtract,\n dictionaryKey: dictionaryKeyOption,\n attributesToExtract = [],\n extractDictionaryKeyFromPath,\n generateKey,\n } = options;\n\n if (!shouldProcessFile(filename, filesList)) return null;\n if (!filename.endsWith('.svelte')) return null;\n\n const magic = new MagicString(code);\n const extractedContent: ExtractedContent = {};\n const existingKeys = new Set<string>();\n const dictionaryKey =\n dictionaryKeyOption ?? extractDictionaryKeyFromPath?.(filename) ?? '';\n const replacements: Replacement[] = [];\n\n // Extract and walk Script using Babel\n const scriptRegex = /<script[^>]*>([\\s\\S]*?)<\\/script>/;\n const scriptMatch = scriptRegex.exec(code);\n let hasScriptExtraction = false;\n const scriptContent = scriptMatch ? scriptMatch[1] : '';\n\n // Detect existing call BEFORE walking the template so the access pattern\n // (bare key vs. $content.key) can be chosen consistently.\n const existingCallInfo = scriptMatch\n ? detectExistingIntlayerCall(\n scriptContent,\n scriptMatch.index + scriptMatch[0].indexOf('>') + 1\n )\n : null;\n\n const isDestructured = existingCallInfo?.isDestructured ?? false;\n const varName = existingCallInfo?.variableName ?? 'content';\n\n let ast: any;\n try {\n ast = parse(code);\n } catch (e) {\n console.warn(\n `Svelte extraction: Failed to parse Svelte AST for ${filename}`,\n e\n );\n return null;\n }\n\n // Walk Svelte HTML AST.\n // Svelte 4 used numeric type constants; Svelte 5 uses string type names.\n // We check for both to remain compatible.\n const isTextNode = (node: any) => node.type === 'Text' || node.type === 3;\n const isAttributeNode = (node: any) =>\n node.type === 'Attribute' || node.type === 6;\n const isExpressionTagNode = (node: any): boolean =>\n node.type === 'MustacheTag' ||\n node.type === 8 || // Svelte 4 numeric\n node.type === 'ExpressionTag'; // Svelte 5\n\n const walkSvelte = (node: any) => {\n if (isTextNode(node)) {\n const text = node.data ?? node.content ?? '';\n if (shouldExtract?.(text) && generateKey) {\n const key = generateKey(text, existingKeys);\n existingKeys.add(key);\n // Destructured: each property is a plain value → `{key}`.\n // Otherwise use the reactive store subscription `{$content.key}`.\n const ref = isDestructured ? key : `$${varName}.${key}`;\n replacements.push({\n start: node.start,\n end: node.end,\n replacement: `{${ref}}`,\n key,\n value: text.replace(/\\s+/g, ' ').trim(),\n });\n }\n } else if (\n isAttributeNode(node) &&\n (attributesToExtract as readonly string[]).includes(node.name)\n ) {\n if (node.value && node.value.length === 1 && isTextNode(node.value[0])) {\n const text = node.value[0].data ?? node.value[0].content ?? '';\n if (shouldExtract?.(text) && generateKey) {\n const key = generateKey(text, existingKeys);\n existingKeys.add(key);\n const ref = isDestructured ? key : `$${varName}.${key}`;\n replacements.push({\n start: node.start,\n end: node.end,\n replacement: `${node.name}={${ref}}`,\n key,\n value: text.trim(),\n });\n }\n }\n }\n\n const children =\n node.children ?? node.fragment?.nodes ?? node.fragment?.children;\n\n // Try to handle mixed text + expression children as an insertion\n if (children?.some(isExpressionTagNode)) {\n const parts: {\n type: 'text' | 'var';\n value: string;\n originalExpr: string;\n }[] = [];\n let hasSignificantText = false;\n let isValid = true;\n\n for (const child of children) {\n if (isTextNode(child)) {\n const text = child.data ?? child.content ?? '';\n if (text.trim().length > 0) hasSignificantText = true;\n parts.push({ type: 'text', value: text, originalExpr: '' });\n } else if (isExpressionTagNode(child)) {\n // Source slice: skip the leading `{` and trailing `}`\n const exprCode = code.slice(child.start + 1, child.end - 1).trim();\n const varName = exprCode.includes('.')\n ? exprCode\n .split('.')\n .pop()!\n .replace(/[^\\w$]/g, '')\n : exprCode;\n parts.push({ type: 'var', value: varName, originalExpr: exprCode });\n } else {\n isValid = false;\n break;\n }\n }\n\n if (\n isValid &&\n hasSignificantText &&\n parts.some((p) => p.type === 'var')\n ) {\n let combined = '';\n for (const p of parts) {\n combined += p.type === 'var' ? `{{${p.value}}}` : p.value;\n }\n const cleanString = combined.replace(/\\s+/g, ' ').trim();\n\n if (shouldExtract?.(cleanString) && generateKey) {\n const key = generateKey(cleanString, existingKeys);\n existingKeys.add(key);\n const ref = isDestructured ? key : `$${varName}.${key}`;\n\n const uniqueVarPairs = [\n ...new Set(\n parts\n .filter((p) => p.type === 'var')\n .map((p) => `${p.value}: ${p.originalExpr}`)\n ),\n ];\n const varArgs = uniqueVarPairs.join(', ');\n const replacement = `{${ref}({ ${varArgs} })}`;\n\n const firstChild = children[0];\n const lastChild = children[children.length - 1];\n replacements.push({\n start: firstChild.start,\n end: lastChild.end,\n replacement,\n key,\n value: cleanString,\n });\n\n // Don't recurse into these children\n if (node.attributes) node.attributes.forEach(walkSvelte);\n return;\n }\n }\n }\n\n if (children) children.forEach(walkSvelte);\n if (node.attributes) node.attributes.forEach(walkSvelte);\n };\n\n if (ast.html) {\n walkSvelte(ast.html);\n }\n\n if (scriptMatch) {\n const openTagEndIndex = scriptMatch[0].indexOf('>') + 1;\n const offset = scriptMatch.index + openTagEndIndex;\n\n try {\n const babelAst = babelParse(scriptContent, {\n configFile: false,\n babelrc: false,\n parserOpts: {\n sourceType: 'module',\n plugins: ['typescript', 'jsx'],\n },\n });\n\n if (babelAst) {\n traverse(babelAst, {\n StringLiteral(path: any) {\n if (path.parentPath.isImportDeclaration()) return;\n if (path.parentPath.isExportDeclaration()) return;\n if (path.parentPath.isImportSpecifier()) return;\n if (path.parentPath.isObjectProperty() && path.key === 'key')\n return;\n\n if (path.parentPath.isCallExpression()) {\n const callee = path.parentPath.node.callee;\n if (\n t.isMemberExpression(callee) &&\n t.isIdentifier(callee.object) &&\n callee.object.name === 'console'\n )\n return;\n\n if (\n t.isIdentifier(callee) &&\n (callee.name === 'useIntlayer' || callee.name === 't')\n )\n return;\n\n if (callee.type === 'Import') return;\n if (t.isIdentifier(callee) && callee.name === 'require') return;\n }\n\n const text = path.node.value;\n if (shouldExtract?.(text) && generateKey) {\n const key = generateKey(text, existingKeys);\n existingKeys.add(key);\n hasScriptExtraction = true;\n\n if (path.node.start != null && path.node.end != null) {\n // Destructured: each property is a plain value → access directly.\n // Otherwise use `get(content).key` to read the Svelte store.\n const ref = isDestructured ? key : `get(${varName}).${key}`;\n replacements.push({\n start: offset + path.node.start,\n end: offset + path.node.end,\n replacement: ref,\n key,\n value: text.trim(),\n });\n }\n }\n },\n });\n }\n } catch (error) {\n console.warn(\n `Svelte extraction: Failed to parse script content for ${filename}`,\n error\n );\n }\n }\n\n // Abort if nothing was extracted\n if (replacements.length === 0) return null;\n\n // Apply Replacements in Reverse Order (prevents magic-string chunk errors)\n replacements.sort((a, b) => b.start - a.start);\n for (const { start, end, replacement, key, value } of replacements) {\n magic.overwrite(start, end, replacement);\n extractedContent[key] = value;\n }\n\n // When the existing call is destructured, inject only the missing keys into\n // the ObjectPattern — no new `content` variable is needed.\n if (\n existingCallInfo?.isDestructured &&\n existingCallInfo.closingBraceAbsolutePos >= 0\n ) {\n const missingKeys = Object.keys(extractedContent).filter(\n (k) => !existingCallInfo.existingDestructuredKeys.includes(k)\n );\n\n if (missingKeys.length > 0) {\n // Insert right after the last property so the space/newline before `}`\n // is naturally preserved: `{ a }` → `{ a, b }`.\n magic.appendLeft(\n existingCallInfo.lastPropAbsoluteEnd,\n `, ${missingKeys.join(', ')}`\n );\n }\n }\n\n // Inject necessary imports and setup\n const hasUseIntlayerImport =\n /import\\s*{[^}]*useIntlayer[^}]*}\\s*from\\s*['\"][^'\"]+['\"]/.test(\n scriptContent\n ) || /import\\s+useIntlayer\\s+from\\s*['\"][^'\"]+['\"]/.test(scriptContent);\n\n const hasGetImport =\n /import\\s*{[^}]*get[^}]*}\\s*from\\s*['\"]svelte\\/store['\"]/.test(\n scriptContent\n );\n\n // An existing call (destructured or not) means no new declaration is needed.\n const hasContentDeclaration =\n existingCallInfo !== null ||\n /const\\s+content\\s*=\\s*useIntlayer\\s*\\(/.test(scriptContent);\n\n const importStmt = hasUseIntlayerImport\n ? ''\n : `import { useIntlayer } from '${packageName}';`;\n const getImportStmt =\n hasScriptExtraction && !isDestructured && !hasGetImport\n ? `import { get } from 'svelte/store';`\n : '';\n const contentDecl = hasContentDeclaration\n ? ''\n : `const content = useIntlayer('${dictionaryKey}');`;\n\n const injectionParts = [importStmt, getImportStmt, contentDecl].filter(\n Boolean\n );\n\n if (injectionParts.length > 0) {\n const injection = `\\n ${injectionParts.join('\\n ')}\\n`;\n\n if (scriptMatch) {\n const scriptContentStart =\n scriptMatch.index + scriptMatch[0].indexOf('>') + 1;\n magic.appendLeft(scriptContentStart, injection);\n } else {\n magic.prepend(\n `<script>\\n ${importStmt}\\n ${hasScriptExtraction ? \"import { get } from 'svelte/store';\" : ''}\\n ${contentDecl}\\n</script>\\n\\n`\n );\n }\n }\n\n if (onExtract) {\n onExtract({\n dictionaryKey,\n filePath: filename,\n content: extractedContent,\n locale: defaultLocale,\n });\n }\n\n return {\n code: magic.toString(),\n map: magic.generateMap({ source: filename, includeContent: true }),\n extracted: true,\n };\n};\n\ntype Tools = {\n generateKey: (text: string, existingKeys: Set<string>) => string;\n shouldExtract: (text: string) => boolean;\n extractDictionaryKeyFromPath: (path: string) => string;\n attributesToExtract: readonly string[];\n extractTsContent: any;\n};\n\nexport const processSvelteFile = (\n filePath: string,\n _componentKey: string,\n packageName: string,\n tools: Tools,\n save: boolean = true,\n providedCode?: string\n): {\n extractedContent: Record<string, string>;\n code: string;\n map?: any;\n} | null => {\n const code = providedCode ?? readFileSync(filePath, 'utf-8');\n let extractedContent: Record<string, string> | null = null;\n\n const result = intlayerSvelteExtract(code, filePath, {\n packageName,\n dictionaryKey: _componentKey,\n shouldExtract: tools.shouldExtract,\n generateKey: tools.generateKey,\n extractDictionaryKeyFromPath: tools.extractDictionaryKeyFromPath,\n attributesToExtract: tools.attributesToExtract,\n onExtract: (extractResult) => {\n extractedContent = extractResult.content;\n },\n });\n\n if (!result) return null;\n\n if (save) {\n writeFileSync(filePath, result.code);\n }\n\n return {\n extractedContent: extractedContent!,\n code: result.code,\n map: result.map,\n };\n};\n"],"mappings":";;;;;;;;;;;;;;AAsBA,MAAM,8BACJ,YACA,mBACqB;CACrB,IAAI,OAAyB;CAE7B,IAAI;EACF,MAAM,UAAMA,uBAAW,YAAY;GACjC,YAAY;GACZ,SAAS;GACT,YAAY;IAAE,YAAY;IAAU,SAAS,CAAC,cAAc,KAAK;GAAE;EACrE,CAAC;EAED,IAAI,CAAC,KAAK,OAAO;EAEjB,0BAAS,KAAK,EACZ,eAAe,MAAW;GACxB,MAAM,SAAS,KAAK,KAAK;GAEzB,IACE,CAACC,kBAAE,aAAa,MAAM,KACrB,OAAO,SAAS,iBAAiB,OAAO,SAAS,eAElD;GAEF,MAAM,SAAS,KAAK;GAEpB,IAAIA,kBAAE,qBAAqB,MAAM,KAAKA,kBAAE,gBAAgB,OAAO,EAAE,GAAG;IAClE,MAAM,aAAa,OAAO,GAAG;IAC7B,MAAM,2BAA2B,WAC9B,QACE,MACCA,kBAAE,iBAAiB,CAAC,KAAKA,kBAAE,aAAa,EAAE,GAAG,CACjD,CAAC,CACA,KAAK,MAAY,EAAE,IAAY,IAAc;IAChD,MAAM,WAAW,WAAW,WAAW,SAAS;IAEhD,OAAO;KACL,gBAAgB;KAChB,cAAc;KACd;KACA,yBAAyB,kBAAkB,OAAO,GAAG,MAAO;KAC5D,qBAAqB,iBAAiB,SAAS;IACjD;G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Y;EAAe;CAAW,CAAC,CAAC,OAC9D,OACF;CAEA,IAAI,eAAe,SAAS,GAAG;EAC7B,MAAM,YAAY,OAAO,eAAe,KAAK,MAAM,EAAE;EAErD,IAAI,aAAa;GACf,MAAM,qBACJ,YAAY,QAAQ,YAAY,EAAE,CAAC,QAAQ,GAAG,IAAI;GACpD,MAAM,WAAW,oBAAoB,SAAS;EAChD,OACE,MAAM,QACJ,eAAe,WAAW,MAAM,sBAAsB,wCAAwC,GAAG,MAAM,YAAY,iBACrH;CAEJ;CAEA,IAAI,WACF,UAAU;EACR;EACA,UAAU;EACV,SAAS;EACT,QAAQ;CACV,CAAC;CAGH,OAAO;EACL,MAAM,MAAM,SAAS;EACrB,KAAK,MAAM,YAAY;GAAE,QAAQ;GAAU,gBAAgB;EAAK,CAAC;EACjE,WAAW;CACb;AACF;AAUA,MAAa,qBACX,UACA,eACA,aACA,OACA,OAAgB,MAChB,iBAKU;CACV,MAAM,OAAO,oBAAgBI,sBAAa,UAAU,OAAO;CAC3D,IAAI,mBAAkD;CAEtD,MAAM,SAAS,sBAAsB,MAAM,UAAU;EACnD;EACA,eAAe;EACf,eAAe,MAAM;EACrB,aAAa,MAAM;EACnB,8BAA8B,MAAM;EACpC,qBAAqB,MAAM;EAC3B,YAAY,kBAAkB;GAC5B,mBAAmB,cAAc;EACnC;CACF,CAAC;CAED,IAAI,CAAC,QAAQ,OAAO;CAEpB,IAAI,MACF,2BAAc,UAAU,OAAO,IAAI;CAGrC,OAAO;EACa;EAClB,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF"}
|
|
1
|
+
{"version":3,"file":"svelte-intlayer-extract.cjs","names":["babelParse","t","DEFAULT_LOCALE","getExtractionIgnoreDirectives","MagicString","parse","readFileSync"],"sources":["../../src/svelte-intlayer-extract.ts"],"sourcesContent":["import { readFileSync, writeFileSync } from 'node:fs';\nimport { parseSync as babelParse, types as t, traverse } from '@babel/core';\nimport { DEFAULT_LOCALE } from '@intlayer/config/defaultValues';\nimport { getExtractionIgnoreDirectives } from '@intlayer/config/extract';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport MagicString from 'magic-string';\nimport { parse } from 'svelte/compiler';\n\ntype ExistingCallInfo = {\n isDestructured: boolean;\n existingDestructuredKeys: string[];\n /** The variable name used to store the call result (e.g. `t` in `const t = useIntlayer(...)`) */\n variableName: string;\n /** Absolute position of `}` in the full file — only valid when `isDestructured` */\n closingBraceAbsolutePos: number;\n /** Absolute position of end of last property — only valid when `isDestructured` */\n lastPropAbsoluteEnd: number;\n} | null;\n\n/**\n * Detects whether a script block already contains a `useIntlayer` /\n * `getIntlayer` call and whether its result is destructured.\n */\nconst detectExistingIntlayerCall = (\n scriptText: string,\n absoluteOffset: number\n): ExistingCallInfo => {\n let info: ExistingCallInfo = null;\n\n try {\n const ast = babelParse(scriptText, {\n configFile: false,\n babelrc: false,\n parserOpts: { sourceType: 'module', plugins: ['typescript', 'jsx'] },\n });\n\n if (!ast) return null;\n\n traverse(ast, {\n CallExpression(path: any) {\n const callee = path.node.callee;\n\n if (\n !t.isIdentifier(callee) ||\n (callee.name !== 'useIntlayer' && callee.name !== 'getIntlayer')\n )\n return;\n\n const parent = path.parent;\n\n if (t.isVariableDeclarator(parent) && t.isObjectPattern(parent.id)) {\n const properties = parent.id.properties;\n const existingDestructuredKeys = properties\n .filter(\n (p: any): p is typeof t.objectProperty =>\n t.isObjectProperty(p) && t.isIdentifier(p.key)\n )\n .map((p: any) => (p.key as any).name as string);\n const lastProp = properties[properties.length - 1];\n\n info = {\n isDestructured: true,\n variableName: 'content',\n existingDestructuredKeys,\n closingBraceAbsolutePos: absoluteOffset + (parent.id.end! - 1),\n lastPropAbsoluteEnd: absoluteOffset + lastProp.end!,\n };\n } else {\n const variableName =\n t.isVariableDeclarator(parent) && t.isIdentifier(parent.id)\n ? parent.id.name\n : 'content';\n\n info = {\n isDestructured: false,\n variableName,\n existingDestructuredKeys: [],\n closingBraceAbsolutePos: -1,\n lastPropAbsoluteEnd: -1,\n };\n }\n\n path.stop();\n },\n });\n } catch {\n // Silently ignore parse failures — fall back to no-info\n }\n\n return info;\n};\n\nexport type ExtractedContent = Record<string, string>;\n\nexport type ExtractResult = {\n dictionaryKey: string;\n filePath: string;\n content: ExtractedContent;\n locale: Locale;\n};\n\nexport type ExtractPluginOptions = {\n defaultLocale?: Locale;\n packageName?: string;\n filesList?: string[];\n shouldExtract?: (text: string) => boolean;\n onExtract?: (result: ExtractResult) => void;\n dictionaryKey?: string;\n attributesToExtract?: readonly string[];\n extractDictionaryKeyFromPath?: (path: string) => string;\n generateKey?: (text: string, existingKeys: Set<string>) => string;\n};\n\ntype Replacement = {\n start: number;\n end: number;\n replacement: string;\n key: string;\n value: string;\n};\n\n/* ────────────────────────────────────────── helpers ─────────────────────── */\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 const normalizedFilename = filename.replace(/\\\\/g, '/');\n return filesList.some((f) => {\n const normalizedF = f.replace(/\\\\/g, '/');\n return normalizedF === normalizedFilename;\n });\n};\n\n/* ────────────────────────────────────────── plugin ──────────────────────── */\n\nexport const intlayerSvelteExtract = (\n code: string,\n filename: string,\n options: ExtractPluginOptions = {}\n): { code: string; map?: unknown; extracted: boolean } | null => {\n const {\n defaultLocale = DEFAULT_LOCALE,\n packageName = 'svelte-intlayer',\n filesList,\n shouldExtract,\n onExtract,\n dictionaryKey: dictionaryKeyOption,\n attributesToExtract = [],\n extractDictionaryKeyFromPath,\n generateKey,\n } = options;\n\n if (!shouldProcessFile(filename, filesList)) return null;\n if (!filename.endsWith('.svelte')) return null;\n\n const ignoreDirectives = getExtractionIgnoreDirectives(code);\n\n if (ignoreDirectives.isFileIgnored) return null;\n\n const magic = new MagicString(code);\n const extractedContent: ExtractedContent = {};\n const existingKeys = new Set<string>();\n const dictionaryKey =\n dictionaryKeyOption ?? extractDictionaryKeyFromPath?.(filename) ?? '';\n const replacements: Replacement[] = [];\n\n // Extract and walk Script using Babel\n const scriptRegex = /<script[^>]*>([\\s\\S]*?)<\\/script>/;\n const scriptMatch = scriptRegex.exec(code);\n let hasScriptExtraction = false;\n const scriptContent = scriptMatch ? scriptMatch[1] : '';\n\n // Detect existing call BEFORE walking the template so the access pattern\n // (bare key vs. $content.key) can be chosen consistently.\n const existingCallInfo = scriptMatch\n ? detectExistingIntlayerCall(\n scriptContent,\n scriptMatch.index + scriptMatch[0].indexOf('>') + 1\n )\n : null;\n\n const isDestructured = existingCallInfo?.isDestructured ?? false;\n const varName = existingCallInfo?.variableName ?? 'content';\n\n let ast: any;\n try {\n ast = parse(code);\n } catch (e) {\n console.warn(\n `Svelte extraction: Failed to parse Svelte AST for ${filename}`,\n e\n );\n return null;\n }\n\n // Walk Svelte HTML AST.\n // Svelte 4 used numeric type constants; Svelte 5 uses string type names.\n // We check for both to remain compatible.\n const isTextNode = (node: any) => node.type === 'Text' || node.type === 3;\n const isAttributeNode = (node: any) =>\n node.type === 'Attribute' || node.type === 6;\n const isExpressionTagNode = (node: any): boolean =>\n node.type === 'MustacheTag' ||\n node.type === 8 || // Svelte 4 numeric\n node.type === 'ExpressionTag'; // Svelte 5\n\n /**\n * Walks the markup; `isParentIgnored` is true when an ignore directive\n * covers the opening tag of the enclosing element.\n */\n const walkSvelte = (node: any, isParentIgnored = false) => {\n const isNodeIgnored = ignoreDirectives.isOffsetIgnored(node.start);\n // Only elements pass their ignored state down, not the root fragment or\n // logic blocks, which may start on an ignored line.\n const isElementNode =\n typeof node.name === 'string' && !isAttributeNode(node);\n const isChildIgnored = isElementNode ? isNodeIgnored : isParentIgnored;\n\n if (isTextNode(node)) {\n const text = node.data ?? node.content ?? '';\n const leadingWhitespaceLength = text.length - text.trimStart().length;\n const isTextIgnored =\n isParentIgnored ||\n ignoreDirectives.isOffsetIgnored(node.start + leadingWhitespaceLength);\n\n if (!isTextIgnored && shouldExtract?.(text) && generateKey) {\n const key = generateKey(text, existingKeys);\n existingKeys.add(key);\n // Destructured: each property is a plain value → `{key}`.\n // Otherwise use the reactive store subscription `{$content.key}`.\n const ref = isDestructured ? key : `$${varName}.${key}`;\n replacements.push({\n start: node.start,\n end: node.end,\n replacement: `{${ref}}`,\n key,\n value: text.replace(/\\s+/g, ' ').trim(),\n });\n }\n } else if (\n isAttributeNode(node) &&\n (attributesToExtract as readonly string[]).includes(node.name)\n ) {\n if (\n !isParentIgnored &&\n !isNodeIgnored &&\n node.value &&\n node.value.length === 1 &&\n isTextNode(node.value[0])\n ) {\n const text = node.value[0].data ?? node.value[0].content ?? '';\n if (shouldExtract?.(text) && generateKey) {\n const key = generateKey(text, existingKeys);\n existingKeys.add(key);\n const ref = isDestructured ? key : `$${varName}.${key}`;\n replacements.push({\n start: node.start,\n end: node.end,\n replacement: `${node.name}={${ref}}`,\n key,\n value: text.trim(),\n });\n }\n }\n }\n\n const children =\n node.children ?? node.fragment?.nodes ?? node.fragment?.children;\n\n // Try to handle mixed text + expression children as an insertion\n if (!isChildIgnored && children?.some(isExpressionTagNode)) {\n const parts: {\n type: 'text' | 'var';\n value: string;\n originalExpr: string;\n }[] = [];\n let hasSignificantText = false;\n let isValid = true;\n\n for (const child of children) {\n if (isTextNode(child)) {\n const text = child.data ?? child.content ?? '';\n if (text.trim().length > 0) hasSignificantText = true;\n parts.push({ type: 'text', value: text, originalExpr: '' });\n } else if (isExpressionTagNode(child)) {\n // Source slice: skip the leading `{` and trailing `}`\n const exprCode = code.slice(child.start + 1, child.end - 1).trim();\n const varName = exprCode.includes('.')\n ? exprCode\n .split('.')\n .pop()!\n .replace(/[^\\w$]/g, '')\n : exprCode;\n parts.push({ type: 'var', value: varName, originalExpr: exprCode });\n } else {\n isValid = false;\n break;\n }\n }\n\n if (\n isValid &&\n hasSignificantText &&\n parts.some((p) => p.type === 'var')\n ) {\n let combined = '';\n for (const p of parts) {\n combined += p.type === 'var' ? `{{${p.value}}}` : p.value;\n }\n const cleanString = combined.replace(/\\s+/g, ' ').trim();\n\n if (shouldExtract?.(cleanString) && generateKey) {\n const key = generateKey(cleanString, existingKeys);\n existingKeys.add(key);\n const ref = isDestructured ? key : `$${varName}.${key}`;\n\n const uniqueVarPairs = [\n ...new Set(\n parts\n .filter((p) => p.type === 'var')\n .map((p) => `${p.value}: ${p.originalExpr}`)\n ),\n ];\n const varArgs = uniqueVarPairs.join(', ');\n const replacement = `{${ref}({ ${varArgs} })}`;\n\n const firstChild = children[0];\n const lastChild = children[children.length - 1];\n replacements.push({\n start: firstChild.start,\n end: lastChild.end,\n replacement,\n key,\n value: cleanString,\n });\n\n // Don't recurse into these children\n node.attributes?.forEach((attribute: any) =>\n walkSvelte(attribute, isNodeIgnored)\n );\n return;\n }\n }\n }\n\n children?.forEach((child: any) => walkSvelte(child, isChildIgnored));\n node.attributes?.forEach((attribute: any) =>\n walkSvelte(attribute, isNodeIgnored)\n );\n };\n\n if (ast.html) {\n walkSvelte(ast.html);\n }\n\n if (scriptMatch) {\n const openTagEndIndex = scriptMatch[0].indexOf('>') + 1;\n const offset = scriptMatch.index + openTagEndIndex;\n\n try {\n const babelAst = babelParse(scriptContent, {\n configFile: false,\n babelrc: false,\n parserOpts: {\n sourceType: 'module',\n plugins: ['typescript', 'jsx'],\n },\n });\n\n if (babelAst) {\n traverse(babelAst, {\n StringLiteral(path: any) {\n if (path.parentPath.isImportDeclaration()) return;\n if (path.parentPath.isExportDeclaration()) return;\n if (path.parentPath.isImportSpecifier()) return;\n if (path.parentPath.isObjectProperty() && path.key === 'key')\n return;\n\n if (path.parentPath.isCallExpression()) {\n const callee = path.parentPath.node.callee;\n if (\n t.isMemberExpression(callee) &&\n t.isIdentifier(callee.object) &&\n callee.object.name === 'console'\n )\n return;\n\n if (\n t.isIdentifier(callee) &&\n (callee.name === 'useIntlayer' || callee.name === 't')\n )\n return;\n\n if (callee.type === 'Import') return;\n if (t.isIdentifier(callee) && callee.name === 'require') return;\n }\n\n const text = path.node.value;\n\n if (\n path.node.start != null &&\n ignoreDirectives.isOffsetIgnored(offset + path.node.start)\n )\n return;\n\n if (shouldExtract?.(text) && generateKey) {\n const key = generateKey(text, existingKeys);\n existingKeys.add(key);\n hasScriptExtraction = true;\n\n if (path.node.start != null && path.node.end != null) {\n // Destructured: each property is a plain value → access directly.\n // Otherwise use `get(content).key` to read the Svelte store.\n const ref = isDestructured ? key : `get(${varName}).${key}`;\n replacements.push({\n start: offset + path.node.start,\n end: offset + path.node.end,\n replacement: ref,\n key,\n value: text.trim(),\n });\n }\n }\n },\n });\n }\n } catch (error) {\n console.warn(\n `Svelte extraction: Failed to parse script content for ${filename}`,\n error\n );\n }\n }\n\n // Abort if nothing was extracted\n if (replacements.length === 0) return null;\n\n // Apply Replacements in Reverse Order (prevents magic-string chunk errors)\n replacements.sort((a, b) => b.start - a.start);\n for (const { start, end, replacement, key, value } of replacements) {\n magic.overwrite(start, end, replacement);\n extractedContent[key] = value;\n }\n\n // When the existing call is destructured, inject only the missing keys into\n // the ObjectPattern — no new `content` variable is needed.\n if (\n existingCallInfo?.isDestructured &&\n existingCallInfo.closingBraceAbsolutePos >= 0\n ) {\n const missingKeys = Object.keys(extractedContent).filter(\n (k) => !existingCallInfo.existingDestructuredKeys.includes(k)\n );\n\n if (missingKeys.length > 0) {\n // Insert right after the last property so the space/newline before `}`\n // is naturally preserved: `{ a }` → `{ a, b }`.\n magic.appendLeft(\n existingCallInfo.lastPropAbsoluteEnd,\n `, ${missingKeys.join(', ')}`\n );\n }\n }\n\n // Inject necessary imports and setup\n const hasUseIntlayerImport =\n /import\\s*{[^}]*useIntlayer[^}]*}\\s*from\\s*['\"][^'\"]+['\"]/.test(\n scriptContent\n ) || /import\\s+useIntlayer\\s+from\\s*['\"][^'\"]+['\"]/.test(scriptContent);\n\n const hasGetImport =\n /import\\s*{[^}]*get[^}]*}\\s*from\\s*['\"]svelte\\/store['\"]/.test(\n scriptContent\n );\n\n // An existing call (destructured or not) means no new declaration is needed.\n const hasContentDeclaration =\n existingCallInfo !== null ||\n /const\\s+content\\s*=\\s*useIntlayer\\s*\\(/.test(scriptContent);\n\n const importStmt = hasUseIntlayerImport\n ? ''\n : `import { useIntlayer } from '${packageName}';`;\n const getImportStmt =\n hasScriptExtraction && !isDestructured && !hasGetImport\n ? `import { get } from 'svelte/store';`\n : '';\n const contentDecl = hasContentDeclaration\n ? ''\n : `const content = useIntlayer('${dictionaryKey}');`;\n\n const injectionParts = [importStmt, getImportStmt, contentDecl].filter(\n Boolean\n );\n\n if (injectionParts.length > 0) {\n const injection = `\\n ${injectionParts.join('\\n ')}\\n`;\n\n if (scriptMatch) {\n const scriptContentStart =\n scriptMatch.index + scriptMatch[0].indexOf('>') + 1;\n magic.appendLeft(scriptContentStart, injection);\n } else {\n magic.prepend(\n `<script>\\n ${importStmt}\\n ${hasScriptExtraction ? \"import { get } from 'svelte/store';\" : ''}\\n ${contentDecl}\\n</script>\\n\\n`\n );\n }\n }\n\n if (onExtract) {\n onExtract({\n dictionaryKey,\n filePath: filename,\n content: extractedContent,\n locale: defaultLocale,\n });\n }\n\n return {\n code: magic.toString(),\n map: magic.generateMap({ source: filename, includeContent: true }),\n extracted: true,\n };\n};\n\ntype Tools = {\n generateKey: (text: string, existingKeys: Set<string>) => string;\n shouldExtract: (text: string) => boolean;\n extractDictionaryKeyFromPath: (path: string) => string;\n attributesToExtract: readonly string[];\n extractTsContent: any;\n};\n\nexport const processSvelteFile = (\n filePath: string,\n _componentKey: string,\n packageName: string,\n tools: Tools,\n save: boolean = true,\n providedCode?: string\n): {\n extractedContent: Record<string, string>;\n code: string;\n map?: any;\n} | null => {\n const code = providedCode ?? readFileSync(filePath, 'utf-8');\n let extractedContent: Record<string, string> | null = null;\n\n const result = intlayerSvelteExtract(code, filePath, {\n packageName,\n dictionaryKey: _componentKey,\n shouldExtract: tools.shouldExtract,\n generateKey: tools.generateKey,\n extractDictionaryKeyFromPath: tools.extractDictionaryKeyFromPath,\n attributesToExtract: tools.attributesToExtract,\n onExtract: (extractResult) => {\n extractedContent = extractResult.content;\n },\n });\n\n if (!result) return null;\n\n if (save) {\n writeFileSync(filePath, result.code);\n }\n\n return {\n extractedContent: extractedContent!,\n code: result.code,\n map: result.map,\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;AAuBA,MAAM,8BACJ,YACA,mBACqB;CACrB,IAAI,OAAyB;CAE7B,IAAI;EACF,MAAM,UAAMA,uBAAW,YAAY;GACjC,YAAY;GACZ,SAAS;GACT,YAAY;IAAE,YAAY;IAAU,SAAS,CAAC,cAAc,KAAK;GAAE;EACrE,CAAC;EAED,IAAI,CAAC,KAAK,OAAO;EAEjB,0BAAS,KAAK,EACZ,eAAe,MAAW;GACxB,MAAM,SAAS,KAAK,KAAK;GAEzB,IACE,CAACC,kBAAE,aAAa,MAAM,KACrB,OAAO,SAAS,iBAAiB,OAAO,SAAS,eAElD;GAEF,MAAM,SAAS,KAAK;GAEpB,IAAIA,kBAAE,qBAAqB,MAAM,KAAKA,kBAAE,gBAAgB,OAAO,EAAE,GAAG;IAClE,MAAM,aAAa,OAAO,GAAG;IAC7B,MAAM,2BAA2B,WAC9B,QACE,MACCA,kBAAE,iBAAiB,CAAC,KAAKA,kBAAE,aAAa,EAAE,GAAG,CACjD,CAAC,CACA,KAAK,MAAY,EAAE,IAAY,IAAc;IAChD,MAAM,WAAW,WAAW,WAAW,SAAS;IAEhD,OAAO;KACL,gBAAgB;KAChB,cAAc;KACd;KACA,yBAAyB,kBAAkB,OAAO,GAAG,MAAO;KAC5D,qBAAqB,iBAAiB,SAAS;IACjD;GACF,OAME,OAAO;IACL,gBAAgB;IAChB,cANAA,kBAAE,qBAAqB,MAAM,KAAKA,kBAAE,aAAa,OAAO,EAAE,IACtD,OAAO,GAAG,OACV;IAKJ,0BAA0B,CAAC;IAC3B,yBAAyB;IACzB,qBAAqB;GACvB;GAGF,KAAK,KAAK;EACZ,EACF,CAAC;CACH,QAAQ,CAER;CAEA,OAAO;AACT;AAiCA,MAAa,qBACX,UACA,cACY;CACZ,IAAI,CAAC,UAAU,OAA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seSync, traverse, types } from "@babel/core";
|
|
3
3
|
import { DEFAULT_LOCALE } from "@intlayer/config/defaultValues";
|
|
4
|
+
import { getExtractionIgnoreDirectives } from "@intlayer/config/extract";
|
|
4
5
|
import MagicString from "magic-string";
|
|
5
6
|
import { parse } from "svelte/compiler";
|
|
6
7
|
|
|
@@ -60,6 +61,8 @@ const intlayerSvelteExtract = (code, filename, options = {}) => {
|
|
|
60
61
|
const { defaultLocale = DEFAULT_LOCALE, packageName = "svelte-intlayer", filesList, shouldExtract, onExtract, dictionaryKey: dictionaryKeyOption, attributesToExtract = [], extractDictionaryKeyFromPath, generateKey } = options;
|
|
61
62
|
if (!shouldProcessFile(filename, filesList)) return null;
|
|
62
63
|
if (!filename.endsWith(".svelte")) return null;
|
|
64
|
+
const ignoreDirectives = getExtractionIgnoreDirectives(code);
|
|
65
|
+
if (ignoreDirectives.isFileIgnored) return null;
|
|
63
66
|
const magic = new MagicString(code);
|
|
64
67
|
const extractedContent = {};
|
|
65
68
|
const existingKeys = /* @__PURE__ */ new Set();
|
|
@@ -81,10 +84,17 @@ const intlayerSvelteExtract = (code, filename, options = {}) => {
|
|
|
81
84
|
const isTextNode = (node) => node.type === "Text" || node.type === 3;
|
|
82
85
|
const isAttributeNode = (node) => node.type === "Attribute" || node.type === 6;
|
|
83
86
|
const isExpressionTagNode = (node) => node.type === "MustacheTag" || node.type === 8 || node.type === "ExpressionTag";
|
|
84
|
-
|
|
87
|
+
/**
|
|
88
|
+
* Walks the markup; `isParentIgnored` is true when an ignore directive
|
|
89
|
+
* covers the opening tag of the enclosing element.
|
|
90
|
+
*/
|
|
91
|
+
const walkSvelte = (node, isParentIgnored = false) => {
|
|
92
|
+
const isNodeIgnored = ignoreDirectives.isOffsetIgnored(node.start);
|
|
93
|
+
const isChildIgnored = typeof node.name === "string" && !isAttributeNode(node) ? isNodeIgnored : isParentIgnored;
|
|
85
94
|
if (isTextNode(node)) {
|
|
86
95
|
const text = node.data ?? node.content ?? "";
|
|
87
|
-
|
|
96
|
+
const leadingWhitespaceLength = text.length - text.trimStart().length;
|
|
97
|
+
if (!(isParentIgnored || ignoreDirectives.isOffsetIgnored(node.start + leadingWhitespaceLength)) && shouldExtract?.(text) && generateKey) {
|
|
88
98
|
const key = generateKey(text, existingKeys);
|
|
89
99
|
existingKeys.add(key);
|
|
90
100
|
const ref = isDestructured ? key : `$${varName}.${key}`;
|
|
@@ -97,7 +107,7 @@ const intlayerSvelteExtract = (code, filename, options = {}) => {
|
|
|
97
107
|
});
|
|
98
108
|
}
|
|
99
109
|
} else if (isAttributeNode(node) && attributesToExtract.includes(node.name)) {
|
|
100
|
-
if (node.value && node.value.length === 1 && isTextNode(node.value[0])) {
|
|
110
|
+
if (!isParentIgnored && !isNodeIgnored && node.value && node.value.length === 1 && isTextNode(node.value[0])) {
|
|
101
111
|
const text = node.value[0].data ?? node.value[0].content ?? "";
|
|
102
112
|
if (shouldExtract?.(text) && generateKey) {
|
|
103
113
|
const key = generateKey(text, existingKeys);
|
|
@@ -114,7 +124,7 @@ const intlayerSvelteExtract = (code, filename, options = {}) => {
|
|
|
114
124
|
}
|
|
115
125
|
}
|
|
116
126
|
const children = node.children ?? node.fragment?.nodes ?? node.fragment?.children;
|
|
117
|
-
if (children?.some(isExpressionTagNode)) {
|
|
127
|
+
if (!isChildIgnored && children?.some(isExpressionTagNode)) {
|
|
118
128
|
const parts = [];
|
|
119
129
|
let hasSignificantText = false;
|
|
120
130
|
let isValid = true;
|
|
@@ -155,13 +165,13 @@ const intlayerSvelteExtract = (code, filename, options = {}) => {
|
|
|
155
165
|
key,
|
|
156
166
|
value: cleanString
|
|
157
167
|
});
|
|
158
|
-
|
|
168
|
+
node.attributes?.forEach((attribute) => walkSvelte(attribute, isNodeIgnored));
|
|
159
169
|
return;
|
|
160
170
|
}
|
|
161
171
|
}
|
|
162
172
|
}
|
|
163
|
-
|
|
164
|
-
|
|
173
|
+
children?.forEach((child) => walkSvelte(child, isChildIgnored));
|
|
174
|
+
node.attributes?.forEach((attribute) => walkSvelte(attribute, isNodeIgnored));
|
|
165
175
|
};
|
|
166
176
|
if (ast.html) walkSvelte(ast.html);
|
|
167
177
|
if (scriptMatch) {
|
|
@@ -189,6 +199,7 @@ const intlayerSvelteExtract = (code, filename, options = {}) => {
|
|
|
189
199
|
if (types.isIdentifier(callee) && callee.name === "require") return;
|
|
190
200
|
}
|
|
191
201
|
const text = path.node.value;
|
|
202
|
+
if (path.node.start != null && ignoreDirectives.isOffsetIgnored(offset + path.node.start)) return;
|
|
192
203
|
if (shouldExtract?.(text) && generateKey) {
|
|
193
204
|
const key = generateKey(text, existingKeys);
|
|
194
205
|
existingKeys.add(key);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"svelte-intlayer-extract.mjs","names":["babelParse","t"],"sources":["../../src/svelte-intlayer-extract.ts"],"sourcesContent":["import { readFileSync, writeFileSync } from 'node:fs';\nimport { parseSync as babelParse, types as t, traverse } from '@babel/core';\nimport { DEFAULT_LOCALE } from '@intlayer/config/defaultValues';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport MagicString from 'magic-string';\nimport { parse } from 'svelte/compiler';\n\ntype ExistingCallInfo = {\n isDestructured: boolean;\n existingDestructuredKeys: string[];\n /** The variable name used to store the call result (e.g. `t` in `const t = useIntlayer(...)`) */\n variableName: string;\n /** Absolute position of `}` in the full file — only valid when `isDestructured` */\n closingBraceAbsolutePos: number;\n /** Absolute position of end of last property — only valid when `isDestructured` */\n lastPropAbsoluteEnd: number;\n} | null;\n\n/**\n * Detects whether a script block already contains a `useIntlayer` /\n * `getIntlayer` call and whether its result is destructured.\n */\nconst detectExistingIntlayerCall = (\n scriptText: string,\n absoluteOffset: number\n): ExistingCallInfo => {\n let info: ExistingCallInfo = null;\n\n try {\n const ast = babelParse(scriptText, {\n configFile: false,\n babelrc: false,\n parserOpts: { sourceType: 'module', plugins: ['typescript', 'jsx'] },\n });\n\n if (!ast) return null;\n\n traverse(ast, {\n CallExpression(path: any) {\n const callee = path.node.callee;\n\n if (\n !t.isIdentifier(callee) ||\n (callee.name !== 'useIntlayer' && callee.name !== 'getIntlayer')\n )\n return;\n\n const parent = path.parent;\n\n if (t.isVariableDeclarator(parent) && t.isObjectPattern(parent.id)) {\n const properties = parent.id.properties;\n const existingDestructuredKeys = properties\n .filter(\n (p: any): p is typeof t.objectProperty =>\n t.isObjectProperty(p) && t.isIdentifier(p.key)\n )\n .map((p: any) => (p.key as any).name as string);\n const lastProp = properties[properties.length - 1];\n\n info = {\n isDestructured: true,\n variableName: 'content',\n existingDestructuredKeys,\n closingBraceAbsolutePos: absoluteOffset + (parent.id.end! - 1),\n lastPropAbsoluteEnd: absoluteOffset + lastProp.end!,\n };\n } else {\n const variableName =\n t.isVariableDeclarator(parent) && t.isIdentifier(parent.id)\n ? parent.id.name\n : 'content';\n\n info = {\n isDestructured: false,\n variableName,\n existingDestructuredKeys: [],\n closingBraceAbsolutePos: -1,\n lastPropAbsoluteEnd: -1,\n };\n }\n\n path.stop();\n },\n });\n } catch {\n // Silently ignore parse failures — fall back to no-info\n }\n\n return info;\n};\n\nexport type ExtractedContent = Record<string, string>;\n\nexport type ExtractResult = {\n dictionaryKey: string;\n filePath: string;\n content: ExtractedContent;\n locale: Locale;\n};\n\nexport type ExtractPluginOptions = {\n defaultLocale?: Locale;\n packageName?: string;\n filesList?: string[];\n shouldExtract?: (text: string) => boolean;\n onExtract?: (result: ExtractResult) => void;\n dictionaryKey?: string;\n attributesToExtract?: readonly string[];\n extractDictionaryKeyFromPath?: (path: string) => string;\n generateKey?: (text: string, existingKeys: Set<string>) => string;\n};\n\ntype Replacement = {\n start: number;\n end: number;\n replacement: string;\n key: string;\n value: string;\n};\n\n/* ────────────────────────────────────────── helpers ─────────────────────── */\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 const normalizedFilename = filename.replace(/\\\\/g, '/');\n return filesList.some((f) => {\n const normalizedF = f.replace(/\\\\/g, '/');\n return normalizedF === normalizedFilename;\n });\n};\n\n/* ────────────────────────────────────────── plugin ──────────────────────── */\n\nexport const intlayerSvelteExtract = (\n code: string,\n filename: string,\n options: ExtractPluginOptions = {}\n): { code: string; map?: unknown; extracted: boolean } | null => {\n const {\n defaultLocale = DEFAULT_LOCALE,\n packageName = 'svelte-intlayer',\n filesList,\n shouldExtract,\n onExtract,\n dictionaryKey: dictionaryKeyOption,\n attributesToExtract = [],\n extractDictionaryKeyFromPath,\n generateKey,\n } = options;\n\n if (!shouldProcessFile(filename, filesList)) return null;\n if (!filename.endsWith('.svelte')) return null;\n\n const magic = new MagicString(code);\n const extractedContent: ExtractedContent = {};\n const existingKeys = new Set<string>();\n const dictionaryKey =\n dictionaryKeyOption ?? extractDictionaryKeyFromPath?.(filename) ?? '';\n const replacements: Replacement[] = [];\n\n // Extract and walk Script using Babel\n const scriptRegex = /<script[^>]*>([\\s\\S]*?)<\\/script>/;\n const scriptMatch = scriptRegex.exec(code);\n let hasScriptExtraction = false;\n const scriptContent = scriptMatch ? scriptMatch[1] : '';\n\n // Detect existing call BEFORE walking the template so the access pattern\n // (bare key vs. $content.key) can be chosen consistently.\n const existingCallInfo = scriptMatch\n ? detectExistingIntlayerCall(\n scriptContent,\n scriptMatch.index + scriptMatch[0].indexOf('>') + 1\n )\n : null;\n\n const isDestructured = existingCallInfo?.isDestructured ?? false;\n const varName = existingCallInfo?.variableName ?? 'content';\n\n let ast: any;\n try {\n ast = parse(code);\n } catch (e) {\n console.warn(\n `Svelte extraction: Failed to parse Svelte AST for ${filename}`,\n e\n );\n return null;\n }\n\n // Walk Svelte HTML AST.\n // Svelte 4 used numeric type constants; Svelte 5 uses string type names.\n // We check for both to remain compatible.\n const isTextNode = (node: any) => node.type === 'Text' || node.type === 3;\n const isAttributeNode = (node: any) =>\n node.type === 'Attribute' || node.type === 6;\n const isExpressionTagNode = (node: any): boolean =>\n node.type === 'MustacheTag' ||\n node.type === 8 || // Svelte 4 numeric\n node.type === 'ExpressionTag'; // Svelte 5\n\n const walkSvelte = (node: any) => {\n if (isTextNode(node)) {\n const text = node.data ?? node.content ?? '';\n if (shouldExtract?.(text) && generateKey) {\n const key = generateKey(text, existingKeys);\n existingKeys.add(key);\n // Destructured: each property is a plain value → `{key}`.\n // Otherwise use the reactive store subscription `{$content.key}`.\n const ref = isDestructured ? key : `$${varName}.${key}`;\n replacements.push({\n start: node.start,\n end: node.end,\n replacement: `{${ref}}`,\n key,\n value: text.replace(/\\s+/g, ' ').trim(),\n });\n }\n } else if (\n isAttributeNode(node) &&\n (attributesToExtract as readonly string[]).includes(node.name)\n ) {\n if (node.value && node.value.length === 1 && isTextNode(node.value[0])) {\n const text = node.value[0].data ?? node.value[0].content ?? '';\n if (shouldExtract?.(text) && generateKey) {\n const key = generateKey(text, existingKeys);\n existingKeys.add(key);\n const ref = isDestructured ? key : `$${varName}.${key}`;\n replacements.push({\n start: node.start,\n end: node.end,\n replacement: `${node.name}={${ref}}`,\n key,\n value: text.trim(),\n });\n }\n }\n }\n\n const children =\n node.children ?? node.fragment?.nodes ?? node.fragment?.children;\n\n // Try to handle mixed text + expression children as an insertion\n if (children?.some(isExpressionTagNode)) {\n const parts: {\n type: 'text' | 'var';\n value: string;\n originalExpr: string;\n }[] = [];\n let hasSignificantText = false;\n let isValid = true;\n\n for (const child of children) {\n if (isTextNode(child)) {\n const text = child.data ?? child.content ?? '';\n if (text.trim().length > 0) hasSignificantText = true;\n parts.push({ type: 'text', value: text, originalExpr: '' });\n } else if (isExpressionTagNode(child)) {\n // Source slice: skip the leading `{` and trailing `}`\n const exprCode = code.slice(child.start + 1, child.end - 1).trim();\n const varName = exprCode.includes('.')\n ? exprCode\n .split('.')\n .pop()!\n .replace(/[^\\w$]/g, '')\n : exprCode;\n parts.push({ type: 'var', value: varName, originalExpr: exprCode });\n } else {\n isValid = false;\n break;\n }\n }\n\n if (\n isValid &&\n hasSignificantText &&\n parts.some((p) => p.type === 'var')\n ) {\n let combined = '';\n for (const p of parts) {\n combined += p.type === 'var' ? `{{${p.value}}}` : p.value;\n }\n const cleanString = combined.replace(/\\s+/g, ' ').trim();\n\n if (shouldExtract?.(cleanString) && generateKey) {\n const key = generateKey(cleanString, existingKeys);\n existingKeys.add(key);\n const ref = isDestructured ? key : `$${varName}.${key}`;\n\n const uniqueVarPairs = [\n ...new Set(\n parts\n .filter((p) => p.type === 'var')\n .map((p) => `${p.value}: ${p.originalExpr}`)\n ),\n ];\n const varArgs = uniqueVarPairs.join(', ');\n const replacement = `{${ref}({ ${varArgs} })}`;\n\n const firstChild = children[0];\n const lastChild = children[children.length - 1];\n replacements.push({\n start: firstChild.start,\n end: lastChild.end,\n replacement,\n key,\n value: cleanString,\n });\n\n // Don't recurse into these children\n if (node.attributes) node.attributes.forEach(walkSvelte);\n return;\n }\n }\n }\n\n if (children) children.forEach(walkSvelte);\n if (node.attributes) node.attributes.forEach(walkSvelte);\n };\n\n if (ast.html) {\n walkSvelte(ast.html);\n }\n\n if (scriptMatch) {\n const openTagEndIndex = scriptMatch[0].indexOf('>') + 1;\n const offset = scriptMatch.index + openTagEndIndex;\n\n try {\n const babelAst = babelParse(scriptContent, {\n configFile: false,\n babelrc: false,\n parserOpts: {\n sourceType: 'module',\n plugins: ['typescript', 'jsx'],\n },\n });\n\n if (babelAst) {\n traverse(babelAst, {\n StringLiteral(path: any) {\n if (path.parentPath.isImportDeclaration()) return;\n if (path.parentPath.isExportDeclaration()) return;\n if (path.parentPath.isImportSpecifier()) return;\n if (path.parentPath.isObjectProperty() && path.key === 'key')\n return;\n\n if (path.parentPath.isCallExpression()) {\n const callee = path.parentPath.node.callee;\n if (\n t.isMemberExpression(callee) &&\n t.isIdentifier(callee.object) &&\n callee.object.name === 'console'\n )\n return;\n\n if (\n t.isIdentifier(callee) &&\n (callee.name === 'useIntlayer' || callee.name === 't')\n )\n return;\n\n if (callee.type === 'Import') return;\n if (t.isIdentifier(callee) && callee.name === 'require') return;\n }\n\n const text = path.node.value;\n if (shouldExtract?.(text) && generateKey) {\n const key = generateKey(text, existingKeys);\n existingKeys.add(key);\n hasScriptExtraction = true;\n\n if (path.node.start != null && path.node.end != null) {\n // Destructured: each property is a plain value → access directly.\n // Otherwise use `get(content).key` to read the Svelte store.\n const ref = isDestructured ? key : `get(${varName}).${key}`;\n replacements.push({\n start: offset + path.node.start,\n end: offset + path.node.end,\n replacement: ref,\n key,\n value: text.trim(),\n });\n }\n }\n },\n });\n }\n } catch (error) {\n console.warn(\n `Svelte extraction: Failed to parse script content for ${filename}`,\n error\n );\n }\n }\n\n // Abort if nothing was extracted\n if (replacements.length === 0) return null;\n\n // Apply Replacements in Reverse Order (prevents magic-string chunk errors)\n replacements.sort((a, b) => b.start - a.start);\n for (const { start, end, replacement, key, value } of replacements) {\n magic.overwrite(start, end, replacement);\n extractedContent[key] = value;\n }\n\n // When the existing call is destructured, inject only the missing keys into\n // the ObjectPattern — no new `content` variable is needed.\n if (\n existingCallInfo?.isDestructured &&\n existingCallInfo.closingBraceAbsolutePos >= 0\n ) {\n const missingKeys = Object.keys(extractedContent).filter(\n (k) => !existingCallInfo.existingDestructuredKeys.includes(k)\n );\n\n if (missingKeys.length > 0) {\n // Insert right after the last property so the space/newline before `}`\n // is naturally preserved: `{ a }` → `{ a, b }`.\n magic.appendLeft(\n existingCallInfo.lastPropAbsoluteEnd,\n `, ${missingKeys.join(', ')}`\n );\n }\n }\n\n // Inject necessary imports and setup\n const hasUseIntlayerImport =\n /import\\s*{[^}]*useIntlayer[^}]*}\\s*from\\s*['\"][^'\"]+['\"]/.test(\n scriptContent\n ) || /import\\s+useIntlayer\\s+from\\s*['\"][^'\"]+['\"]/.test(scriptContent);\n\n const hasGetImport =\n /import\\s*{[^}]*get[^}]*}\\s*from\\s*['\"]svelte\\/store['\"]/.test(\n scriptContent\n );\n\n // An existing call (destructured or not) means no new declaration is needed.\n const hasContentDeclaration =\n existingCallInfo !== null ||\n /const\\s+content\\s*=\\s*useIntlayer\\s*\\(/.test(scriptContent);\n\n const importStmt = hasUseIntlayerImport\n ? ''\n : `import { useIntlayer } from '${packageName}';`;\n const getImportStmt =\n hasScriptExtraction && !isDestructured && !hasGetImport\n ? `import { get } from 'svelte/store';`\n : '';\n const contentDecl = hasContentDeclaration\n ? ''\n : `const content = useIntlayer('${dictionaryKey}');`;\n\n const injectionParts = [importStmt, getImportStmt, contentDecl].filter(\n Boolean\n );\n\n if (injectionParts.length > 0) {\n const injection = `\\n ${injectionParts.join('\\n ')}\\n`;\n\n if (scriptMatch) {\n const scriptContentStart =\n scriptMatch.index + scriptMatch[0].indexOf('>') + 1;\n magic.appendLeft(scriptContentStart, injection);\n } else {\n magic.prepend(\n `<script>\\n ${importStmt}\\n ${hasScriptExtraction ? \"import { get } from 'svelte/store';\" : ''}\\n ${contentDecl}\\n</script>\\n\\n`\n );\n }\n }\n\n if (onExtract) {\n onExtract({\n dictionaryKey,\n filePath: filename,\n content: extractedContent,\n locale: defaultLocale,\n });\n }\n\n return {\n code: magic.toString(),\n map: magic.generateMap({ source: filename, includeContent: true }),\n extracted: true,\n };\n};\n\ntype Tools = {\n generateKey: (text: string, existingKeys: Set<string>) => string;\n shouldExtract: (text: string) => boolean;\n extractDictionaryKeyFromPath: (path: string) => string;\n attributesToExtract: readonly string[];\n extractTsContent: any;\n};\n\nexport const processSvelteFile = (\n filePath: string,\n _componentKey: string,\n packageName: string,\n tools: Tools,\n save: boolean = true,\n providedCode?: string\n): {\n extractedContent: Record<string, string>;\n code: string;\n map?: any;\n} | null => {\n const code = providedCode ?? readFileSync(filePath, 'utf-8');\n let extractedContent: Record<string, string> | null = null;\n\n const result = intlayerSvelteExtract(code, filePath, {\n packageName,\n dictionaryKey: _componentKey,\n shouldExtract: tools.shouldExtract,\n generateKey: tools.generateKey,\n extractDictionaryKeyFromPath: tools.extractDictionaryKeyFromPath,\n attributesToExtract: tools.attributesToExtract,\n onExtract: (extractResult) => {\n extractedContent = extractResult.content;\n },\n });\n\n if (!result) return null;\n\n if (save) {\n writeFileSync(filePath, result.code);\n }\n\n return {\n extractedContent: extractedContent!,\n code: result.code,\n map: result.map,\n };\n};\n"],"mappings":";;;;;;;;;;;AAsBA,MAAM,8BACJ,YACA,mBACqB;CACrB,IAAI,OAAyB;CAE7B,IAAI;EACF,MAAM,MAAMA,UAAW,YAAY;GACjC,YAAY;GACZ,SAAS;GACT,YAAY;IAAE,YAAY;IAAU,SAAS,CAAC,cAAc,KAAK;GAAE;EACrE,CAAC;EAED,IAAI,CAAC,KAAK,OAAO;EAEjB,SAAS,KAAK,EACZ,eAAe,MAAW;GACxB,MAAM,SAAS,KAAK,KAAK;GAEzB,IACE,CAACC,MAAE,aAAa,MAAM,KACrB,OAAO,SAAS,iBAAiB,OAAO,SAAS,eAElD;GAEF,MAAM,SAAS,KAAK;GAEpB,IAAIA,MAAE,qBAAqB,MAAM,KAAKA,MAAE,gBAAgB,OAAO,EAAE,GAAG;IAClE,MAAM,aAAa,OAAO,GAAG;IAC7B,MAAM,2BAA2B,WAC9B,QACE,MACCA,MAAE,iBAAiB,CAAC,KAAKA,MAAE,aAAa,EAAE,GAAG,CACjD,CAAC,CACA,KAAK,MAAY,EAAE,IAAY,IAAc;IAChD,MAAM,WAAW,WAAW,WAAW,SAAS;IAEhD,OAAO;KACL,gBAAgB;KAChB,cAAc;KACd;KACA,yBAAyB,kBAAkB,OAAO,GAAG,MAAO;KAC5D,qBAAqB,iBAAiB,SAAS;IACjD;GACF,OAME,OAAO;IACL,gBAAgB;IAChB,cANAA,MAAE,qBAAqB,MAAM,KAAKA,MAAE,aAAa,OAAO,EAAE,IACtD,OAAO,GAAG,OACV;IAKJ,0BAA0B,CAAC;IAC3B,yBAAyB;IACzB,qBAAqB;GACvB;GAGF,KAAK,KAAK;EACZ,EACF,CAAC;CACH,QAAQ,CAER;CAEA,OAAO;AACT;AAiCA,MAAa,qBACX,UACA,cACY;CACZ,IAAI,CAAC,UAAU,OAAO;CACtB,IAAI,CAAC,aAAa,UAAU,WAAW,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R;EACA,UAAU;EACV,SAAS;EACT,QAAQ;CACV,CAAC;CAGH,OAAO;EACL,MAAM,MAAM,SAAS;EACrB,KAAK,MAAM,YAAY;GAAE,QAAQ;GAAU,gBAAgB;EAAK,CAAC;EACjE,WAAW;CACb;AACF;AAUA,MAAa,qBACX,UACA,eACA,aACA,OACA,OAAgB,MAChB,iBAKU;CACV,MAAM,OAAO,gBAAgB,aAAa,UAAU,OAAO;CAC3D,IAAI,mBAAkD;CAEtD,MAAM,SAAS,sBAAsB,MAAM,UAAU;EACnD;EACA,eAAe;EACf,eAAe,MAAM;EACrB,aAAa,MAAM;EACnB,8BAA8B,MAAM;EACpC,qBAAqB,MAAM;EAC3B,YAAY,kBAAkB;GAC5B,mBAAmB,cAAc;EACnC;CACF,CAAC;CAED,IAAI,CAAC,QAAQ,OAAO;CAEpB,IAAI,MACF,cAAc,UAAU,OAAO,IAAI;CAGrC,OAAO;EACa;EAClB,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF"}
|
|
1
|
+
{"version":3,"file":"svelte-intlayer-extract.mjs","names":["babelParse","t"],"sources":["../../src/svelte-intlayer-extract.ts"],"sourcesContent":["import { readFileSync, writeFileSync } from 'node:fs';\nimport { parseSync as babelParse, types as t, traverse } from '@babel/core';\nimport { DEFAULT_LOCALE } from '@intlayer/config/defaultValues';\nimport { getExtractionIgnoreDirectives } from '@intlayer/config/extract';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport MagicString from 'magic-string';\nimport { parse } from 'svelte/compiler';\n\ntype ExistingCallInfo = {\n isDestructured: boolean;\n existingDestructuredKeys: string[];\n /** The variable name used to store the call result (e.g. `t` in `const t = useIntlayer(...)`) */\n variableName: string;\n /** Absolute position of `}` in the full file — only valid when `isDestructured` */\n closingBraceAbsolutePos: number;\n /** Absolute position of end of last property — only valid when `isDestructured` */\n lastPropAbsoluteEnd: number;\n} | null;\n\n/**\n * Detects whether a script block already contains a `useIntlayer` /\n * `getIntlayer` call and whether its result is destructured.\n */\nconst detectExistingIntlayerCall = (\n scriptText: string,\n absoluteOffset: number\n): ExistingCallInfo => {\n let info: ExistingCallInfo = null;\n\n try {\n const ast = babelParse(scriptText, {\n configFile: false,\n babelrc: false,\n parserOpts: { sourceType: 'module', plugins: ['typescript', 'jsx'] },\n });\n\n if (!ast) return null;\n\n traverse(ast, {\n CallExpression(path: any) {\n const callee = path.node.callee;\n\n if (\n !t.isIdentifier(callee) ||\n (callee.name !== 'useIntlayer' && callee.name !== 'getIntlayer')\n )\n return;\n\n const parent = path.parent;\n\n if (t.isVariableDeclarator(parent) && t.isObjectPattern(parent.id)) {\n const properties = parent.id.properties;\n const existingDestructuredKeys = properties\n .filter(\n (p: any): p is typeof t.objectProperty =>\n t.isObjectProperty(p) && t.isIdentifier(p.key)\n )\n .map((p: any) => (p.key as any).name as string);\n const lastProp = properties[properties.length - 1];\n\n info = {\n isDestructured: true,\n variableName: 'content',\n existingDestructuredKeys,\n closingBraceAbsolutePos: absoluteOffset + (parent.id.end! - 1),\n lastPropAbsoluteEnd: absoluteOffset + lastProp.end!,\n };\n } else {\n const variableName =\n t.isVariableDeclarator(parent) && t.isIdentifier(parent.id)\n ? parent.id.name\n : 'content';\n\n info = {\n isDestructured: false,\n variableName,\n existingDestructuredKeys: [],\n closingBraceAbsolutePos: -1,\n lastPropAbsoluteEnd: -1,\n };\n }\n\n path.stop();\n },\n });\n } catch {\n // Silently ignore parse failures — fall back to no-info\n }\n\n return info;\n};\n\nexport type ExtractedContent = Record<string, string>;\n\nexport type ExtractResult = {\n dictionaryKey: string;\n filePath: string;\n content: ExtractedContent;\n locale: Locale;\n};\n\nexport type ExtractPluginOptions = {\n defaultLocale?: Locale;\n packageName?: string;\n filesList?: string[];\n shouldExtract?: (text: string) => boolean;\n onExtract?: (result: ExtractResult) => void;\n dictionaryKey?: string;\n attributesToExtract?: readonly string[];\n extractDictionaryKeyFromPath?: (path: string) => string;\n generateKey?: (text: string, existingKeys: Set<string>) => string;\n};\n\ntype Replacement = {\n start: number;\n end: number;\n replacement: string;\n key: string;\n value: string;\n};\n\n/* ────────────────────────────────────────── helpers ─────────────────────── */\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 const normalizedFilename = filename.replace(/\\\\/g, '/');\n return filesList.some((f) => {\n const normalizedF = f.replace(/\\\\/g, '/');\n return normalizedF === normalizedFilename;\n });\n};\n\n/* ────────────────────────────────────────── plugin ──────────────────────── */\n\nexport const intlayerSvelteExtract = (\n code: string,\n filename: string,\n options: ExtractPluginOptions = {}\n): { code: string; map?: unknown; extracted: boolean } | null => {\n const {\n defaultLocale = DEFAULT_LOCALE,\n packageName = 'svelte-intlayer',\n filesList,\n shouldExtract,\n onExtract,\n dictionaryKey: dictionaryKeyOption,\n attributesToExtract = [],\n extractDictionaryKeyFromPath,\n generateKey,\n } = options;\n\n if (!shouldProcessFile(filename, filesList)) return null;\n if (!filename.endsWith('.svelte')) return null;\n\n const ignoreDirectives = getExtractionIgnoreDirectives(code);\n\n if (ignoreDirectives.isFileIgnored) return null;\n\n const magic = new MagicString(code);\n const extractedContent: ExtractedContent = {};\n const existingKeys = new Set<string>();\n const dictionaryKey =\n dictionaryKeyOption ?? extractDictionaryKeyFromPath?.(filename) ?? '';\n const replacements: Replacement[] = [];\n\n // Extract and walk Script using Babel\n const scriptRegex = /<script[^>]*>([\\s\\S]*?)<\\/script>/;\n const scriptMatch = scriptRegex.exec(code);\n let hasScriptExtraction = false;\n const scriptContent = scriptMatch ? scriptMatch[1] : '';\n\n // Detect existing call BEFORE walking the template so the access pattern\n // (bare key vs. $content.key) can be chosen consistently.\n const existingCallInfo = scriptMatch\n ? detectExistingIntlayerCall(\n scriptContent,\n scriptMatch.index + scriptMatch[0].indexOf('>') + 1\n )\n : null;\n\n const isDestructured = existingCallInfo?.isDestructured ?? false;\n const varName = existingCallInfo?.variableName ?? 'content';\n\n let ast: any;\n try {\n ast = parse(code);\n } catch (e) {\n console.warn(\n `Svelte extraction: Failed to parse Svelte AST for ${filename}`,\n e\n );\n return null;\n }\n\n // Walk Svelte HTML AST.\n // Svelte 4 used numeric type constants; Svelte 5 uses string type names.\n // We check for both to remain compatible.\n const isTextNode = (node: any) => node.type === 'Text' || node.type === 3;\n const isAttributeNode = (node: any) =>\n node.type === 'Attribute' || node.type === 6;\n const isExpressionTagNode = (node: any): boolean =>\n node.type === 'MustacheTag' ||\n node.type === 8 || // Svelte 4 numeric\n node.type === 'ExpressionTag'; // Svelte 5\n\n /**\n * Walks the markup; `isParentIgnored` is true when an ignore directive\n * covers the opening tag of the enclosing element.\n */\n const walkSvelte = (node: any, isParentIgnored = false) => {\n const isNodeIgnored = ignoreDirectives.isOffsetIgnored(node.start);\n // Only elements pass their ignored state down, not the root fragment or\n // logic blocks, which may start on an ignored line.\n const isElementNode =\n typeof node.name === 'string' && !isAttributeNode(node);\n const isChildIgnored = isElementNode ? isNodeIgnored : isParentIgnored;\n\n if (isTextNode(node)) {\n const text = node.data ?? node.content ?? '';\n const leadingWhitespaceLength = text.length - text.trimStart().length;\n const isTextIgnored =\n isParentIgnored ||\n ignoreDirectives.isOffsetIgnored(node.start + leadingWhitespaceLength);\n\n if (!isTextIgnored && shouldExtract?.(text) && generateKey) {\n const key = generateKey(text, existingKeys);\n existingKeys.add(key);\n // Destructured: each property is a plain value → `{key}`.\n // Otherwise use the reactive store subscription `{$content.key}`.\n const ref = isDestructured ? key : `$${varName}.${key}`;\n replacements.push({\n start: node.start,\n end: node.end,\n replacement: `{${ref}}`,\n key,\n value: text.replace(/\\s+/g, ' ').trim(),\n });\n }\n } else if (\n isAttributeNode(node) &&\n (attributesToExtract as readonly string[]).includes(node.name)\n ) {\n if (\n !isParentIgnored &&\n !isNodeIgnored &&\n node.value &&\n node.value.length === 1 &&\n isTextNode(node.value[0])\n ) {\n const text = node.value[0].data ?? node.value[0].content ?? '';\n if (shouldExtract?.(text) && generateKey) {\n const key = generateKey(text, existingKeys);\n existingKeys.add(key);\n const ref = isDestructured ? key : `$${varName}.${key}`;\n replacements.push({\n start: node.start,\n end: node.end,\n replacement: `${node.name}={${ref}}`,\n key,\n value: text.trim(),\n });\n }\n }\n }\n\n const children =\n node.children ?? node.fragment?.nodes ?? node.fragment?.children;\n\n // Try to handle mixed text + expression children as an insertion\n if (!isChildIgnored && children?.some(isExpressionTagNode)) {\n const parts: {\n type: 'text' | 'var';\n value: string;\n originalExpr: string;\n }[] = [];\n let hasSignificantText = false;\n let isValid = true;\n\n for (const child of children) {\n if (isTextNode(child)) {\n const text = child.data ?? child.content ?? '';\n if (text.trim().length > 0) hasSignificantText = true;\n parts.push({ type: 'text', value: text, originalExpr: '' });\n } else if (isExpressionTagNode(child)) {\n // Source slice: skip the leading `{` and trailing `}`\n const exprCode = code.slice(child.start + 1, child.end - 1).trim();\n const varName = exprCode.includes('.')\n ? exprCode\n .split('.')\n .pop()!\n .replace(/[^\\w$]/g, '')\n : exprCode;\n parts.push({ type: 'var', value: varName, originalExpr: exprCode });\n } else {\n isValid = false;\n break;\n }\n }\n\n if (\n isValid &&\n hasSignificantText &&\n parts.some((p) => p.type === 'var')\n ) {\n let combined = '';\n for (const p of parts) {\n combined += p.type === 'var' ? `{{${p.value}}}` : p.value;\n }\n const cleanString = combined.replace(/\\s+/g, ' ').trim();\n\n if (shouldExtract?.(cleanString) && generateKey) {\n const key = generateKey(cleanString, existingKeys);\n existingKeys.add(key);\n const ref = isDestructured ? key : `$${varName}.${key}`;\n\n const uniqueVarPairs = [\n ...new Set(\n parts\n .filter((p) => p.type === 'var')\n .map((p) => `${p.value}: ${p.originalExpr}`)\n ),\n ];\n const varArgs = uniqueVarPairs.join(', ');\n const replacement = `{${ref}({ ${varArgs} })}`;\n\n const firstChild = children[0];\n const lastChild = children[children.length - 1];\n replacements.push({\n start: firstChild.start,\n end: lastChild.end,\n replacement,\n key,\n value: cleanString,\n });\n\n // Don't recurse into these children\n node.attributes?.forEach((attribute: any) =>\n walkSvelte(attribute, isNodeIgnored)\n );\n return;\n }\n }\n }\n\n children?.forEach((child: any) => walkSvelte(child, isChildIgnored));\n node.attributes?.forEach((attribute: any) =>\n walkSvelte(attribute, isNodeIgnored)\n );\n };\n\n if (ast.html) {\n walkSvelte(ast.html);\n }\n\n if (scriptMatch) {\n const openTagEndIndex = scriptMatch[0].indexOf('>') + 1;\n const offset = scriptMatch.index + openTagEndIndex;\n\n try {\n const babelAst = babelParse(scriptContent, {\n configFile: false,\n babelrc: false,\n parserOpts: {\n sourceType: 'module',\n plugins: ['typescript', 'jsx'],\n },\n });\n\n if (babelAst) {\n traverse(babelAst, {\n StringLiteral(path: any) {\n if (path.parentPath.isImportDeclaration()) return;\n if (path.parentPath.isExportDeclaration()) return;\n if (path.parentPath.isImportSpecifier()) return;\n if (path.parentPath.isObjectProperty() && path.key === 'key')\n return;\n\n if (path.parentPath.isCallExpression()) {\n const callee = path.parentPath.node.callee;\n if (\n t.isMemberExpression(callee) &&\n t.isIdentifier(callee.object) &&\n callee.object.name === 'console'\n )\n return;\n\n if (\n t.isIdentifier(callee) &&\n (callee.name === 'useIntlayer' || callee.name === 't')\n )\n return;\n\n if (callee.type === 'Import') return;\n if (t.isIdentifier(callee) && callee.name === 'require') return;\n }\n\n const text = path.node.value;\n\n if (\n path.node.start != null &&\n ignoreDirectives.isOffsetIgnored(offset + path.node.start)\n )\n return;\n\n if (shouldExtract?.(text) && generateKey) {\n const key = generateKey(text, existingKeys);\n existingKeys.add(key);\n hasScriptExtraction = true;\n\n if (path.node.start != null && path.node.end != null) {\n // Destructured: each property is a plain value → access directly.\n // Otherwise use `get(content).key` to read the Svelte store.\n const ref = isDestructured ? key : `get(${varName}).${key}`;\n replacements.push({\n start: offset + path.node.start,\n end: offset + path.node.end,\n replacement: ref,\n key,\n value: text.trim(),\n });\n }\n }\n },\n });\n }\n } catch (error) {\n console.warn(\n `Svelte extraction: Failed to parse script content for ${filename}`,\n error\n );\n }\n }\n\n // Abort if nothing was extracted\n if (replacements.length === 0) return null;\n\n // Apply Replacements in Reverse Order (prevents magic-string chunk errors)\n replacements.sort((a, b) => b.start - a.start);\n for (const { start, end, replacement, key, value } of replacements) {\n magic.overwrite(start, end, replacement);\n extractedContent[key] = value;\n }\n\n // When the existing call is destructured, inject only the missing keys into\n // the ObjectPattern — no new `content` variable is needed.\n if (\n existingCallInfo?.isDestructured &&\n existingCallInfo.closingBraceAbsolutePos >= 0\n ) {\n const missingKeys = Object.keys(extractedContent).filter(\n (k) => !existingCallInfo.existingDestructuredKeys.includes(k)\n );\n\n if (missingKeys.length > 0) {\n // Insert right after the last property so the space/newline before `}`\n // is naturally preserved: `{ a }` → `{ a, b }`.\n magic.appendLeft(\n existingCallInfo.lastPropAbsoluteEnd,\n `, ${missingKeys.join(', ')}`\n );\n }\n }\n\n // Inject necessary imports and setup\n const hasUseIntlayerImport =\n /import\\s*{[^}]*useIntlayer[^}]*}\\s*from\\s*['\"][^'\"]+['\"]/.test(\n scriptContent\n ) || /import\\s+useIntlayer\\s+from\\s*['\"][^'\"]+['\"]/.test(scriptContent);\n\n const hasGetImport =\n /import\\s*{[^}]*get[^}]*}\\s*from\\s*['\"]svelte\\/store['\"]/.test(\n scriptContent\n );\n\n // An existing call (destructured or not) means no new declaration is needed.\n const hasContentDeclaration =\n existingCallInfo !== null ||\n /const\\s+content\\s*=\\s*useIntlayer\\s*\\(/.test(scriptContent);\n\n const importStmt = hasUseIntlayerImport\n ? ''\n : `import { useIntlayer } from '${packageName}';`;\n const getImportStmt =\n hasScriptExtraction && !isDestructured && !hasGetImport\n ? `import { get } from 'svelte/store';`\n : '';\n const contentDecl = hasContentDeclaration\n ? ''\n : `const content = useIntlayer('${dictionaryKey}');`;\n\n const injectionParts = [importStmt, getImportStmt, contentDecl].filter(\n Boolean\n );\n\n if (injectionParts.length > 0) {\n const injection = `\\n ${injectionParts.join('\\n ')}\\n`;\n\n if (scriptMatch) {\n const scriptContentStart =\n scriptMatch.index + scriptMatch[0].indexOf('>') + 1;\n magic.appendLeft(scriptContentStart, injection);\n } else {\n magic.prepend(\n `<script>\\n ${importStmt}\\n ${hasScriptExtraction ? \"import { get } from 'svelte/store';\" : ''}\\n ${contentDecl}\\n</script>\\n\\n`\n );\n }\n }\n\n if (onExtract) {\n onExtract({\n dictionaryKey,\n filePath: filename,\n content: extractedContent,\n locale: defaultLocale,\n });\n }\n\n return {\n code: magic.toString(),\n map: magic.generateMap({ source: filename, includeContent: true }),\n extracted: true,\n };\n};\n\ntype Tools = {\n generateKey: (text: string, existingKeys: Set<string>) => string;\n shouldExtract: (text: string) => boolean;\n extractDictionaryKeyFromPath: (path: string) => string;\n attributesToExtract: readonly string[];\n extractTsContent: any;\n};\n\nexport const processSvelteFile = (\n filePath: string,\n _componentKey: string,\n packageName: string,\n tools: Tools,\n save: boolean = true,\n providedCode?: string\n): {\n extractedContent: Record<string, string>;\n code: string;\n map?: any;\n} | null => {\n const code = providedCode ?? readFileSync(filePath, 'utf-8');\n let extractedContent: Record<string, string> | null = null;\n\n const result = intlayerSvelteExtract(code, filePath, {\n packageName,\n dictionaryKey: _componentKey,\n shouldExtract: tools.shouldExtract,\n generateKey: tools.generateKey,\n extractDictionaryKeyFromPath: tools.extractDictionaryKeyFromPath,\n attributesToExtract: tools.attributesToExtract,\n onExtract: (extractResult) => {\n extractedContent = extractResult.content;\n },\n });\n\n if (!result) return null;\n\n if (save) {\n writeFileSync(filePath, result.code);\n }\n\n return {\n extractedContent: extractedContent!,\n code: result.code,\n map: result.map,\n };\n};\n"],"mappings":";;;;;;;;;;;;AAuBA,MAAM,8BACJ,YACA,mBACqB;CACrB,IAAI,OAAyB;CAE7B,IAAI;EACF,MAAM,MAAMA,UAAW,YAAY;GACjC,YAAY;GACZ,SAAS;GACT,YAAY;IAAE,YAAY;IAAU,SAAS,CAAC,cAAc,KAAK;GAAE;EACrE,CAAC;EAED,IAAI,CAAC,KAAK,OAAO;EAEjB,SAAS,KAAK,EACZ,eAAe,MAAW;GACxB,MAAM,SAAS,KA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AAe,WAAW,MAAM,sBAAsB,wCAAwC,GAAG,MAAM,YAAY,iBACrH;CAEJ;CAEA,IAAI,WACF,UAAU;EACR;EACA,UAAU;EACV,SAAS;EACT,QAAQ;CACV,CAAC;CAGH,OAAO;EACL,MAAM,MAAM,SAAS;EACrB,KAAK,MAAM,YAAY;GAAE,QAAQ;GAAU,gBAAgB;EAAK,CAAC;EACjE,WAAW;CACb;AACF;AAUA,MAAa,qBACX,UACA,eACA,aACA,OACA,OAAgB,MAChB,iBAKU;CACV,MAAM,OAAO,gBAAgB,aAAa,UAAU,OAAO;CAC3D,IAAI,mBAAkD;CAEtD,MAAM,SAAS,sBAAsB,MAAM,UAAU;EACnD;EACA,eAAe;EACf,eAAe,MAAM;EACrB,aAAa,MAAM;EACnB,8BAA8B,MAAM;EACpC,qBAAqB,MAAM;EAC3B,YAAY,kBAAkB;GAC5B,mBAAmB,cAAc;EACnC;CACF,CAAC;CAED,IAAI,CAAC,QAAQ,OAAO;CAEpB,IAAI,MACF,cAAc,UAAU,OAAO,IAAI;CAGrC,OAAO;EACa;EAClB,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"svelte-intlayer-extract.d.ts","names":[],"sources":["../../src/svelte-intlayer-extract.ts"],"mappings":";
|
|
1
|
+
{"version":3,"file":"svelte-intlayer-extract.d.ts","names":[],"sources":["../../src/svelte-intlayer-extract.ts"],"mappings":";YA4FY,mBAAmB;YAEnB;EACV;EACA;EACA,SAAS;EACT,QAAQ;;YAGE;EACV,gBAAgB;EAChB;EACA;EACA,iBAAiB;EACjB,aAAa,QAAQ;EACrB;EACA;EACA,gCAAgC;EAChC,eAAe,cAAc,cAAc;;qBAahC,oBAAiB,8BACA;qBAejB,wBAAqB,cACpB,kBACI,UACP;EACN;EAAc;EAAe;;KAkY7B;EACH,cAAc,cAAc,cAAc;EAC1C,gBAAgB;EAChB,+BAA+B;EAC/B;EACA;;qBAGW,oBAAiB,kBACZ,uBACK,qBACF,OACZ,OAAK,gBACC;EAGb,kBAAkB;EAClB;EACA"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@intlayer/svelte-compiler",
|
|
3
|
-
"version": "9.
|
|
3
|
+
"version": "9.8.0-canary.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Vite-compatible compiler plugin for Svelte with Intlayer, providing HMR support, file transformation, and optimized dictionary loading for Svelte applications.",
|
|
6
6
|
"keywords": [
|
|
@@ -79,13 +79,13 @@
|
|
|
79
79
|
},
|
|
80
80
|
"dependencies": {
|
|
81
81
|
"@babel/core": "8.1.0",
|
|
82
|
-
"@intlayer/types": "9.
|
|
82
|
+
"@intlayer/types": "9.8.0-canary.0",
|
|
83
83
|
"fast-glob": "3.3.3",
|
|
84
84
|
"magic-string": "1.4.5"
|
|
85
85
|
},
|
|
86
86
|
"devDependencies": {
|
|
87
|
-
"@intlayer/config": "9.
|
|
88
|
-
"@intlayer/types": "9.
|
|
87
|
+
"@intlayer/config": "9.8.0-canary.0",
|
|
88
|
+
"@intlayer/types": "9.8.0-canary.0",
|
|
89
89
|
"@types/babel__core": "7.20.5",
|
|
90
90
|
"@types/babel__generator": "7.27.0",
|
|
91
91
|
"@types/babel__traverse": "7.28.0",
|