diff --git a/.github/workflows/extension.yml b/.github/workflows/extension.yml new file mode 100644 index 0000000..81dae63 --- /dev/null +++ b/.github/workflows/extension.yml @@ -0,0 +1,96 @@ +name: Extension package and release + +on: + pull_request: + push: + branches: [main] + workflow_dispatch: + inputs: + destination: + description: Publishing destination (artifact only does not publish) + required: true + type: choice + default: artifact + options: + - artifact + - open-vsx + - vscode-marketplace + - both + +permissions: + contents: read + +jobs: + package: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + - run: npm ci + - name: Compile, lint and test + run: npm test + - name: Package extension + run: | + mkdir -p dist + npx --no-install vsce package --out dist/ai-localizer.vsix + sha256sum dist/ai-localizer.vsix > dist/ai-localizer.vsix.sha256 + echo "Packaged venmail.ai-localizer $(node -p 'require("./package.json").version')" >> "$GITHUB_STEP_SUMMARY" + - name: Upload VSIX artifact + uses: actions/upload-artifact@v4 + with: + name: localizer-vsix + path: | + dist/ai-localizer.vsix + dist/ai-localizer.vsix.sha256 + if-no-files-found: error + + publish: + if: github.event_name == 'workflow_dispatch' && inputs.destination != 'artifact' + needs: package + runs-on: ubuntu-latest + concurrency: + group: extension-publish + cancel-in-progress: false + steps: + - name: Require the main branch + if: github.ref != 'refs/heads/main' + run: | + echo 'Publication is allowed only from main.' >&2 + exit 1 + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + - run: npm ci + - uses: actions/download-artifact@v4 + with: + name: localizer-vsix + path: dist + - name: Verify packaged artifact + run: sha256sum --check dist/ai-localizer.vsix.sha256 + - name: Check publishing credentials + env: + DESTINATION: ${{ inputs.destination }} + OVSX_PAT: ${{ secrets.OVSX_PAT }} + VSCE_PAT: ${{ secrets.VSCE_PAT }} + run: | + if [[ "$DESTINATION" == 'open-vsx' || "$DESTINATION" == 'both' ]]; then + [[ -n "$OVSX_PAT" ]] || { echo 'Missing OVSX_PAT secret.' >&2; exit 1; } + fi + if [[ "$DESTINATION" == 'vscode-marketplace' || "$DESTINATION" == 'both' ]]; then + [[ -n "$VSCE_PAT" ]] || { echo 'Missing VSCE_PAT secret.' >&2; exit 1; } + fi + - name: Publish to Open VSX + if: inputs.destination == 'open-vsx' || inputs.destination == 'both' + env: + OVSX_PAT: ${{ secrets.OVSX_PAT }} + run: npx --yes ovsx@1.4.0 publish dist/ai-localizer.vsix + - name: Publish to Visual Studio Marketplace + if: inputs.destination == 'vscode-marketplace' || inputs.destination == 'both' + env: + VSCE_PAT: ${{ secrets.VSCE_PAT }} + run: npx --no-install vsce publish --packagePath dist/ai-localizer.vsix diff --git a/dev.md b/dev.md index 7896268..cd90119 100644 --- a/dev.md +++ b/dev.md @@ -90,6 +90,32 @@ When you are preparing a new release: - Extension activates without errors. - i18n commands and IntelliSense behave as expected. +## GitHub Actions packaging and publishing + +The **Extension package and release** workflow builds and tests each pull +request and push to `main`. Download the `localizer-vsix` artifact from the +workflow run; it contains the VSIX and its SHA-256 checksum. + +To publish, first merge the release changes and increment `package.json`'s +version for every new release. In GitHub, open **Actions → Extension package and +release → Run workflow**, select `main`, and choose `open-vsx`, +`vscode-marketplace`, or `both`. Choose `artifact` to build without publishing. +The workflow publishes the exact VSIX produced by its tested package job. + +Configure repository Actions secrets before publishing: + +- `OVSX_PAT`: an Open VSX token belonging to a publisher authorized for the + `venmail` namespace. Complete any required namespace ownership and publisher + agreement steps on Open VSX. +- `VSCE_PAT`: an Azure DevOps personal access token authorized to publish under + the `venmail` Visual Studio Marketplace publisher. + +Both credentials are checked before either publication when `both` is chosen. +The registries publish independently: if the second publication fails, the +first may already be live. Resolve the error and rerun only the failed target. +Publishing is manual and restricted to `main`; ordinary PR and branch builds do +not publish. A marketplace will reject a version already published there. + --- ## Project Structure (High Level) diff --git a/package-lock.json b/package-lock.json index e036762..7e14f5f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,6 +12,7 @@ "packages/*" ], "dependencies": { + "@babel/parser": "^7.29.14", "magic-string": "^0.30.21", "node-fetch": "^2.7.0", "openai": "^4.0.0", @@ -242,12 +243,48 @@ "node": ">=6.9.0" } }, + "node_modules/@babel/helper-string-parser": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.14.tgz", + "integrity": "sha512-CXvKMFvM80ihI7Vox9jb+kQjnyjESQNPM+vB7U0Zz6TWuZA+Z/FL0QPMH300h33qJtIx+REeBhXqWOPW48TcAQ==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, "node_modules/@babel/helper-validator-identifier": { - "version": "7.28.5", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz", - "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==", - "dev": true, + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.14.tgz", + "integrity": "sha512-VL220vXuyO2z3rNIQwY7ftj9UwpqOt+33sH+sBWkOekbsSR2g7EEMnOx24ZlCH0xOA3DM/33SifVFGbnJD8r/w==", "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.14" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.14.tgz", + "integrity": "sha512-UjI/dKmwJwT9pOszJitq2G6EObZPnsZUfdCr92z2TlF3EZK9J3EdfOKUrCzHl6wFthbzwhzl1Soc/UIwxRiq6w==", + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.29.14", + "@babel/helper-validator-identifier": "^7.29.7" + }, "engines": { "node": ">=6.9.0" } @@ -7653,16 +7690,40 @@ "packages/cli": { "name": "@ai-localizer/cli", "version": "0.1.0", + "license": "Apache-2.0", "dependencies": { - "@ai-localizer/core": "*" + "@ai-localizer/core": "^0.1.0" }, "bin": { "ai-localize": "bin/ai-localize.js" + }, + "engines": { + "node": ">=18" } }, "packages/core": { "name": "@ai-localizer/core", - "version": "0.1.0" + "version": "0.1.0", + "license": "Apache-2.0", + "dependencies": { + "@babel/parser": "^7.29.14", + "magic-string": "^0.30.21", + "oxc-parser": "^0.89.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependenciesMeta": { + "@babel/generator": { + "optional": true + }, + "@babel/traverse": { + "optional": true + }, + "@babel/types": { + "optional": true + } + } } } } diff --git a/package.json b/package.json index f4543aa..c0e082a 100644 --- a/package.json +++ b/package.json @@ -459,7 +459,7 @@ "pretest": "npm run compile && npm run lint", "lint": "eslint src --ext ts", "package": "npm run test && vsce package", - "test": "vitest run", + "test": "vitest run && node --test tests/ReportedIssues.regression.test.cjs", "test:watch": "vitest", "i18n:extract": "node ./scripts/extract-i18n.js", "i18n:rewrite": "node ./scripts/replace-i18n.js", @@ -508,6 +508,7 @@ "vitest": "^1.2.2" }, "dependencies": { + "@babel/parser": "^7.29.14", "magic-string": "^0.30.21", "node-fetch": "^2.7.0", "openai": "^4.0.0", diff --git a/packages/cli/src/commands/init.js b/packages/cli/src/commands/init.js index 4562e8f..d96444f 100644 --- a/packages/cli/src/commands/init.js +++ b/packages/cli/src/commands/init.js @@ -63,6 +63,9 @@ async function run(parsed) { const srcRoot = String(parsed.flags['src-root'] || defaults.srcRoot); const localesDir = String(parsed.flags['locales-dir'] || defaults.localesDir); const layout = String(parsed.flags.layout || defaults.layout); + if (layout !== 'single' && layout !== 'grouped') { + throw new Error('Invalid --layout: expected single or grouped'); + } const newBlock = { sourceLocale, @@ -70,7 +73,7 @@ async function run(parsed) { locales: finalLocales, srcRoot, localesDir, - localeLayout: layout, + layout, }; const hasExisting = data.aiI18n && typeof data.aiI18n === 'object' && Object.keys(data.aiI18n).length > 0; diff --git a/packages/core/README.md b/packages/core/README.md index de05750..8d2bdc6 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -20,7 +20,9 @@ Most users should install the CLI. Install this package directly only if you wan npm install @ai-localizer/core ``` -Optional deps for legacy Babel-based JSX extraction fallback: `@babel/parser @babel/generator @babel/traverse @babel/types`. Default path uses `oxc-parser` (already bundled). +`@babel/parser` and `oxc-parser` are installed with the package. The legacy +Babel JSX backend additionally requires `@babel/generator`, `@babel/traverse` +and `@babel/types`. ## API @@ -72,6 +74,27 @@ The pipeline reads `package.json#aiI18n` (or `composer.json#extra.aiI18n` for La } ``` +### Vue setup scripts + +The default `replace` backend reuses a top-level `useI18n()` composer or its +`t` binding in `\n`; + assert.equal(findSfcBlocks(source, 'template').length, 1); + assert.equal(findSfcBlocks(source, 'script').length, 1); +}); + +test('#2 extracts and replaces component caption attributes in later slots', () => { + const input = ``; + assert(srcTexts(input).has('Add Category')); + const result = vueReplaced(input, [['text','Add Category','Commons.text.add_category']]).content; + assert.match(result, /:newrecordcaption="\$t\('Commons.text.add_category'\)"/); +}); + +test('#9 ternary mustache processes every literal independently and is idempotent', () => { + const input = ``; + const pairs = [ + ['text','Confirm Delete — cannot be undone','Pages.Form.text.confirm'], + ['text','Delete','Commons.text.delete'], + ]; + const first = vueReplaced(input, pairs); + assert.match(first.content, /\$t\("Pages.Form.text.confirm"\)/); + assert.match(first.content, /\$t\("Commons.text.delete"\)/); + assert.equal(vueReplaced(first.content,pairs).content,first.content); + const extracted = srcTexts(input); + assert(extracted.has('Confirm Delete — cannot be undone')); + assert(extracted.has('Delete')); +}); + +test('#9 both Required and None are extracted from a mustache ternary', () => { + const extracted = srcTexts(``); + assert(extracted.has('Required')); + assert(extracted.has('None')); +}); + +test('#11 ignores comment text, without ignoring real UI literals', () => { + const items = srcTexts(``); + assert(!items.has('Any Day')); + assert(!items.has('no override')); + assert(items.has('Could not save record')); +}); + +test('#7/#10 protect persisted select values and RBAC role constants', () => { + const items = srcTexts(``); + for(const text of ['Administrator','Sorting and Inventory','Office','other','weight']) { + assert(!items.has(text), `technical string unexpectedly registered: ${text}`); + } + assert(items.has('Other')); + assert(items.has('Weight')); +}); + +test('#12 scans both setup script and Options-API script', () => { + const input = `\n`; + const items = srcTexts(input); + assert(items.has('Submit your request')); + assert(items.has('Cannot perform this operation')); + const replaced = vueReplaced(input, [ + ['text','Submit your request','Pages.Form.text.submit'], + ['text','Cannot perform this operation','Pages.Form.text.cannot_perform'], + ]).content; + assert.match(replaced, /this\.\$t\("Pages.Form.text.cannot_perform"\)/); + assert.match(replaced, /t\("Pages.Form.text.submit"\)/); +}); + +test('Vue Options API uses the component translator without an unbound t call', () => { + const input = ``; + const result = vueReplaced(input, [['text','Cannot perform this operation','Pages.Form.text.cannot_perform']]); + assert.match(result.content, /this\.\$t\("Pages.Form.text.cannot_perform"\)/); + const vm = require('node:vm'); + const script = result.content.replace(/^`; + const result = vueReplaced(input, [['text', 'Save the file', 'Pages.Form.text.save']]).content; + assert.match(result, /\/\/ title: 'Save the file'/); + assert.match(result, /const title = 'Save the file'/); + assert.match(result, /function\(\)\{ return 'Save the file' \}/); + assert.match(result, /return this\.\$t\("Pages.Form.text.save"\)/); + assert.match(result, /roleName\(\) \{ return 'Save the file'; \}/); + assert.match(result, /bad: \(\) => \(\{title:'Save the file'\}\)/); +}); + +test('Vue setup does not use a translation binding before initialization', () => { + const input = ``; + const result = vueReplaced(input, [['text','Save the file','Pages.Form.text.save']]).content; + assert.match(result, /titleBefore = 'Save the file'/); + assert.match(result, /titleAfter = t\("Pages.Form.text.save"\)/); +}); + +test('Vue type-only imports do not count as runtime translation bindings', () => { + const input = ``; + const result = vueReplaced(input, [['text','Save the file','Pages.Form.text.save']]); + assert.equal(result.content, input); +}); + +test('Vue setup reuses an existing composer, including aliased hooks and bindings', () => { + const pairs = [['text','Save the file','Pages.Form.text.save']]; + for (const [setup, expected] of [ + ["import { useI18n as useLocale } from 'vue-i18n'; const composer = useLocale();", /title = composer\.t\(/], + ["const { t: translate } = useI18n();", /title = translate\(/], + ["const { locale, } = useI18n();", /title = __localizerT\(/], + ["const { locale, /* comment */ } = useI18n();", /title = __localizerT\(/], + ["const { t: translate = fallback } = useI18n();", /title = translate\(/], + ["const { locale, ...rest } = useI18n();", /title = __localizerT\(/], + ]) { + const input = ``; + const output = vueReplaced(input,pairs).content; + assert.match(output,expected); + require('@babel/parser').parse(output.slice(''.length), {sourceType:'module',plugins:['typescript']}); + assert.equal(vueReplaced(output,pairs).content,output); + } +}); + +test('Vue setup can opt into composition binding without identifier collisions', () => { + const input = ``; + const pairs = [['text','Save the file','Pages.Form.text.save']]; + const options = {vueSetupTranslation:'vue-i18n-composition'}; + const output = vueReplaced(input,pairs,options).content; + assert.match(output, /import \{ useI18n as __localizerUseI18n2 \} from 'vue-i18n'/); + assert.match(output, /const \{ t: __localizerT2 \} = __localizerUseI18n2\(\)/); + assert.match(output, /title = __localizerT2\("Pages.Form.text.save"\)/); + require('@babel/parser').parse(output.slice(output.indexOf('>')+1,output.indexOf('')), {sourceType:'module',plugins:['typescript']}); + assert.equal(vueReplaced(output,pairs,options).content,output); + assert.equal(vueReplaced(input,pairs).content,input); + assert.equal(vueReplaced(input,[],options).content,input); +}); + +test('default replace backend honors the Vue composition setup option', () => { + const dir=fixture(); + try { + const pkgPath=path.join(dir,'package.json'); + const pkg=JSON.parse(fs.readFileSync(pkgPath,'utf8')); + pkg.aiI18n.vueSetupTranslation='vue-i18n-composition'; + fs.writeFileSync(pkgPath, JSON.stringify(pkg)); + const file=path.join(dir,'resources','js','Form.vue'); + fs.writeFileSync(file, ``); + const locale=path.join(dir,'resources','js','i18n','auto','en.json'); + fs.writeFileSync(locale,JSON.stringify({Common:{text:{save:'Save the file'}}})); + runCoreScript(dir,'replace-i18n.js'); + const out=fs.readFileSync(file,'utf8'); + assert.match(out, /import \{ useI18n as __localizerUseI18n \} from 'vue-i18n'/); + assert.match(out, /title = __localizerT\("Common.text.save"\)/); + runCoreScript(dir,'replace-i18n.js'); + assert.equal(fs.readFileSync(file,'utf8'),out); + } finally { fs.rmSync(dir,{recursive:true,force:true}); } +}); + +test('Vue mustache comparison literals remain program values', () => { + const input = ``; + const result = vueReplaced(input, [['text','Pending','Commons.text.pending'], ['text','Completed','Commons.text.completed']]); + assert.match(result.content, /status === 'Pending'/); + assert.match(result.content, /\? \$t\("Commons.text.pending"\)/); +}); + +test('Vue mustache extraction and rewriting do not change comparison operands', () => { + const input = ``; + const pairs = [['text','Pending','Commons.text.pending'], ['text','Completed','Commons.text.completed']]; + const output = vueReplaced(input, pairs).content; + assert.match(output, /prefix \+ 'Pending'/); + assert.match(output, /\? \$t\("Commons.text.pending"\)/); + assert.equal((output.match(/Commons.text.pending/g) || []).length, 1); +}); + +test('Vue replacement leaves comments and nested code examples intact', () => { + const input = ``; + const result = vueReplaced(input, [['text', 'Save the file', 'Pages.Form.text.save']]).content; + assert.match(result, //); + assert.match(result, /
Save the file<\/span><\/pre>/);
+  assert.match(result, /

\{\{ \$t\('Pages.Form.text.save'\) \}\}<\/p>/); +}); + +test('Vue replacement does not treat attribute-like text as a tag attribute', () => { + const input = ``; + const result = vueReplaced(input, [['title', 'Save the file', 'Pages.Form.title.save']]).content; + assert.match(result, /See title="Save the file" in the instructions/); + assert.match(result, //); +}); + +test('Vue replacement does not emit invalid parameters for mixed interpolation', () => { + const input = ``; + const result = vueReplaced(input, [['text', 'Welcome {{ user.name }}', 'Pages.Form.text.welcome']]); + assert.equal(result.content, input); +}); + +test('Vue replacement respects > characters in quoted attributes', () => { + const input = ``; + const result = vueReplaced(input, [['text', 'Save the file', 'Pages.Form.text.save']]).content; + assert.match(result, /title="Score > Save the file"/); + assert.match(result, /">\{\{ \$t\('Pages.Form.text.save'\) \}\}<\/p>/); +}); + +test('Vue template replacement safely quotes translation keys in attributes', () => { + const key = `Pages.Form.text.s'ave"quoted`; + const input = ``; + const output = vueReplaced(input, [['title', 'Save the file', key]]).content; + const expression = output.match(/:title="([^"]+)"/)[1]; + const ast = require('@babel/parser').parseExpression(expression, {plugins:['estree']}); + assert.equal(ast.arguments[0].value, key); +}); + +test('#5 Blade extractor rejects pre/code content and inline fragments', () => { + const source = `

This page isn't set up yet

docker compose up -d
`+ + `

First APP_DEBUG=true then run:

`; + const texts = new Set(new BladeParser().parse(source).items.map(i=>i.text)); + assert(texts.has("This page isn't set up yet")); + assert(!texts.has('docker compose up -d')); + assert(!texts.has('then run:')); + assert(!texts.has('First')); +}); + +test('Blade extraction ignores nested content in protected blocks and HTML comments', () => { + const source = `
Example command text

Visible message

`; + const texts = new Set(new BladeParser().parse(source).items.map(i => i.text)); + assert(!texts.has('Example command text')); + assert(!texts.has('Hidden comment text')); + assert(texts.has('Visible message')); +}); + +test('Blade command filtering applies outside pre and preserves ordinary instructions', () => { + const source = `

docker compose up -d

npm install package

APP_DEBUG=true

Run npm install to continue.

Install the package now.

`; + const texts = new Set(new BladeParser().parse(source).items.map(i=>i.text)); + for (const command of ['docker compose up -d','npm install package','APP_DEBUG=true']) assert(!texts.has(command)); + assert(texts.has('Run npm install to continue.')); + assert(texts.has('Install the package now.')); +}); + +test('Blade rewrite preserves command-shaped text even if a locale key already exists', () => { + const dir=fixture(); + try { + const locales=path.join(dir,'resources','js','i18n','auto'); + fs.writeFileSync(path.join(locales,'en.json'), JSON.stringify({Reports:{Pallet:{text:{command:'docker compose up -d', instruction:'Run npm install to continue.'}}}})); + const view=path.join(dir,'resources','views','reports','pallet.blade.php'); + fs.writeFileSync(view,'

docker compose up -d

Run npm install to continue.

'); + runCoreScript(dir,'rewrite-i18n-blade.js'); + const out=fs.readFileSync(view,'utf8'); + assert.match(out, /

docker compose up -d<\/p>/); + assert.match(out, /Reports.Pallet.text.instruction/); + } finally { fs.rmSync(dir,{recursive:true,force:true}); } +}); + +test('Blade rewrite honors configured source locale and locale directory', () => { + const dir = fixture(); + try { + const localeDir = path.join(dir, 'translations'); + fs.mkdirSync(localeDir); + fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({aiI18n:{srcRoot:'resources/js',localesDir:'translations',sourceLocale:'pt',locales:['pt','en']}})); + fs.writeFileSync(path.join(localeDir, 'pt.json'), JSON.stringify({Commons:{text:{report:'Relatório geral'}}})); + const view = path.join(dir,'resources','views','reports','pallet.blade.php'); + fs.writeFileSync(view, 'Relatório geral'); + runCoreScript(dir,'rewrite-i18n-blade.js'); + assert.match(fs.readFileSync(view,'utf8'), /Commons.text.report/); + } finally { fs.rmSync(dir,{recursive:true,force:true}); } +}); + +test('#3/#4/#5 Blade rewrite uses Commons + text fallback and preserves protected content', () => { + const dir = fixture(); + try { + const locales = path.join(dir,'resources','js','i18n','auto'); + const base = { + Commons: { text: { pallet_report: 'Pallet Report' } }, + Errors: { TurnstileMisconfigured: { text: { this_page_isn_t: "This page isn't set up yet" } } }, + }; + fs.writeFileSync(path.join(locales,'en.json'), JSON.stringify(base)); + const p1 = path.join(dir,'resources','views','reports','pallet.blade.php'); + const p2 = path.join(dir,'resources','views','errors','turnstile_misconfigured.blade.php'); + fs.mkdirSync(path.dirname(p2),{recursive:true}); + fs.writeFileSync(p1,'Pallet Report'); + fs.writeFileSync(p2, `{{-- Never remove this comment --}}\n

This page isn't set up yet

\n
docker compose up -d
`); + runCoreScript(dir,'rewrite-i18n-blade.js'); + assert.match(fs.readFileSync(p1,'utf8'),/Commons.text.pallet_report/); + assert.match(fs.readFileSync(p2,'utf8'),/Errors.TurnstileMisconfigured.text.this_page_isn_t/); + assert.match(fs.readFileSync(p2,'utf8'),/Never remove this comment/); + assert.match(fs.readFileSync(p2,'utf8'),/
docker compose up -d<\/pre>/);
+  } finally {fs.rmSync(dir,{recursive:true,force:true});}
+});
+
+test('#6 accepts canonical layout and legacy localeLayout', () => {
+  const dir = fs.mkdtempSync(path.join(os.tmpdir(),'localizer-layout-'));
+  try {
+    const pkg = path.join(dir,'package.json');
+    fs.writeFileSync(pkg,JSON.stringify({aiI18n:{localeLayout:'grouped'}}));
+    assert.equal(getLocaleLayout(dir),'grouped');
+    fs.writeFileSync(pkg,JSON.stringify({aiI18n:{layout:'single',localeLayout:'grouped'}}));
+    assert.equal(getLocaleLayout(dir),'single');
+  } finally {fs.rmSync(dir,{recursive:true,force:true});}
+});
+
+test('#8 cleanup --apply preserves keys used in Blade and removes unused keys from both locales', () => {
+  const dir=fixture();
+  try {
+    const locales=path.join(dir,'resources','js','i18n','auto');
+    const data={Errors:{TurnstileMisconfigured:{text:{this_page_isn_t:"This page isn't set up yet",unused_text:'Unused string text'}}}};
+    for (const loc of ['en','fr'])fs.writeFileSync(path.join(locales,loc+'.json'),JSON.stringify(data));
+    const view=path.join(dir,'resources','views','reports','pallet.blade.php');
+    fs.writeFileSync(view,`

{{ __('Errors.TurnstileMisconfigured.text.this_page_isn_t') }}

`); + runCoreScript(dir,'cleanup-i18n-unused.js',['--apply']); + for (const loc of ['en','fr']) { + const obj=JSON.parse(fs.readFileSync(path.join(locales,loc+'.json'),'utf8')); + const keys=obj.Errors.TurnstileMisconfigured.text; + assert.equal(keys.this_page_isn_t,"This page isn't set up yet"); + assert.equal(keys.unused_text,undefined); + } + } finally {fs.rmSync(dir,{recursive:true,force:true});} +}); + +test('cleanup refuses deletion when translation keys are computed dynamically', () => { + const dir = fixture(); + try { + const locales = path.join(dir, 'resources', 'js', 'i18n', 'auto'); + const data = { Messages: { text: { pending: 'Pending', unused: 'Unused' } } }; + fs.writeFileSync(path.join(locales, 'en.json'), JSON.stringify(data)); + fs.writeFileSync(path.join(dir, 'resources', 'js', 'app.js'), "const msg = t('Messages.text.' + status);"); + const run = spawnSync(process.execPath, [path.join(__dirname,'..','packages','core','src','i18n','cleanup-i18n-unused.js'), '--apply'], { + env:{...process.env, AI_I18N_PROJECT_ROOT:dir},encoding:'utf8' + }); + assert.notEqual(run.status, 0); + assert.match(run.stderr, /dynamic translation calls/); + assert.deepEqual(JSON.parse(fs.readFileSync(path.join(locales,'en.json'),'utf8')),data); + } finally { fs.rmSync(dir,{recursive:true,force:true}); } +}); + +test('cleanup preserves children of referenced structured translation keys', () => { + const dir = fixture(); + try { + const locales = path.join(dir, 'resources', 'js', 'i18n', 'auto'); + const data = { menu: { first: 'First item', second: 'Second item' }, unused: 'Unused text' }; + fs.writeFileSync(path.join(locales,'en.json'), JSON.stringify(data)); + fs.writeFileSync(path.join(dir,'resources','js','app.js'), "const menu = t('menu', {returnObjects: true});"); + runCoreScript(dir,'cleanup-i18n-unused.js',['--apply']); + const after = JSON.parse(fs.readFileSync(path.join(locales,'en.json'),'utf8')); + assert.deepEqual(after.menu, data.menu); + assert.equal(after.unused, undefined); + } finally { fs.rmSync(dir,{recursive:true,force:true}); } +}); + +test('extract and replace work together on Vue slots and both script blocks', () => { + const dir = fixture(); + try { + const sourceDir = path.join(dir, 'resources', 'js', 'Pages'); + fs.mkdirSync(sourceDir, {recursive:true}); + const file = path.join(sourceDir, 'Form.vue'); + fs.writeFileSync(file, `\n\n`); + runCoreScript(dir, 'extract-i18n.js'); + runCoreScript(dir, 'replace-i18n.js'); + const result = fs.readFileSync(file, 'utf8'); + assert.match(result, /\$t\([^)]*order_overview/); + assert.match(result, /\$t\([^)]*required/); + assert.match(result, /\$t\([^)]*none/); + assert.match(result, /titleMessage = t\(/); + assert.match(result, /description:this\.\$t\(/); + const first = result; + runCoreScript(dir, 'replace-i18n.js'); + assert.equal(fs.readFileSync(file, 'utf8'), first); + } finally { fs.rmSync(dir,{recursive:true,force:true}); } +});