@intlayer/chokidar 8.3.0-canary.0 → 8.3.0-canary.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. package/dist/cjs/loadDictionaries/loadDictionaries.cjs +1 -1
  2. package/dist/cjs/loadDictionaries/loadDictionaries.cjs.map +1 -1
  3. package/dist/cjs/loadDictionaries/loadLocalDictionaries.cjs +1 -1
  4. package/dist/cjs/loadDictionaries/loadLocalDictionaries.cjs.map +1 -1
  5. package/dist/cjs/loadDictionaries/logTypeScriptErrors.cjs +1 -1
  6. package/dist/cjs/loadDictionaries/logTypeScriptErrors.cjs.map +1 -1
  7. package/dist/cjs/prepareIntlayer.cjs +1 -1
  8. package/dist/cjs/prepareIntlayer.cjs.map +1 -1
  9. package/dist/cjs/writeContentDeclaration/transformJSONFile.cjs +2 -1
  10. package/dist/cjs/writeContentDeclaration/transformJSONFile.cjs.map +1 -1
  11. package/dist/cjs/writeContentDeclaration/writeContentDeclaration.cjs +1 -1
  12. package/dist/cjs/writeContentDeclaration/writeContentDeclaration.cjs.map +1 -1
  13. package/dist/esm/loadDictionaries/loadDictionaries.mjs +1 -1
  14. package/dist/esm/loadDictionaries/loadDictionaries.mjs.map +1 -1
  15. package/dist/esm/loadDictionaries/loadLocalDictionaries.mjs +1 -1
  16. package/dist/esm/loadDictionaries/loadLocalDictionaries.mjs.map +1 -1
  17. package/dist/esm/loadDictionaries/logTypeScriptErrors.mjs +1 -1
  18. package/dist/esm/loadDictionaries/logTypeScriptErrors.mjs.map +1 -1
  19. package/dist/esm/prepareIntlayer.mjs +1 -1
  20. package/dist/esm/prepareIntlayer.mjs.map +1 -1
  21. package/dist/esm/writeContentDeclaration/transformJSONFile.mjs +2 -1
  22. package/dist/esm/writeContentDeclaration/transformJSONFile.mjs.map +1 -1
  23. package/dist/esm/writeContentDeclaration/writeContentDeclaration.mjs +1 -1
  24. package/dist/esm/writeContentDeclaration/writeContentDeclaration.mjs.map +1 -1
  25. package/dist/types/writeContentDeclaration/transformJSONFile.d.ts.map +1 -1
  26. package/package.json +10 -10
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../_virtual/_rolldown/runtime.cjs`);const e=require(`../filterInvalidDictionaries.cjs`),t=require(`./loadContentDeclaration.cjs`),n=require(`../formatDictionary.cjs`),r=require(`./loadRemoteDictionaries.cjs`),i=require(`./log.cjs`);let a=require(`@intlayer/config/logger`),o=[];const s=new i.DictionariesLogger,c=e=>{let t=[...o];for(let n of e){let e=t.findIndex(e=>e.dictionaryKey===n.dictionaryKey&&e.type===n.type);e>=0?t[e]=n:t.push(n)}return o=t,s.update(e),t},l=e=>{switch(e){case`built`:case`imported`:case`fetched`:return`✔`;case`error`:return`✖`;default:return`⏲`}},u=e=>{switch(e){case`built`:case`imported`:case`fetched`:return a.ANSIColors.GREEN;case`error`:return a.ANSIColors.RED;default:return a.ANSIColors.BLUE}},d=e=>{if(e.log.mode!==`verbose`)return;let t=(0,a.getAppLogger)(e),n=new Map;for(let e of o){let t=n.get(e.dictionaryKey)??{};e.type===`local`&&(t.local=e.status),e.type===`remote`&&(t.remote=e.status),n.set(e.dictionaryKey,t)}let r=Array.from(n.keys()).sort((e,t)=>e.localeCompare(t)),i=0;for(let e of r){let t=n.get(e);if(t.local){let e=`[local: ${l(t.local)} ${t.local}]`;e.length>i&&(i=e.length)}}for(let e of r){let o=n.get(e),s=[];if(o.local){let e=(0,a.colorize)(`${l(o.local)} ${o.local}`,u(o.local)),t=`${a.ANSIColors.GREY}[`+(0,a.colorize)(`local: `,a.ANSIColors.GREY)+e+`${a.ANSIColors.GREY}]${a.ANSIColors.RESET}`,n=`[local: ${l(o.local)} ${o.local}]`,r=Math.max(0,i-n.length);s.push(t+` `.repeat(r))}else s.push(` `.repeat(i));if(o.remote){let e=(0,a.colorize)(`${l(o.remote)} ${o.remote}`,u(o.remote));s.push(`${a.ANSIColors.GREY}[`+(0,a.colorize)(`distant: `,a.ANSIColors.GREY)+e+`${a.ANSIColors.GREY}]${a.ANSIColors.RESET}`)}t(` - ${(0,a.colon)((0,a.colorizeKey)(e),{colSize:r})} ${s.join(` `)}`)}},f=async(i,o)=>{let{plugins:l}=o,u=Date.now();(0,a.getAppLogger)(o)(`Dictionaries:`,{isVerbose:!0});let f=(l??[]).filter(e=>e.loadDictionaries).map(async e=>{try{return await e.loadDictionaries?.({configuration:o})??[]}catch(e){return s.setPluginError(e),[]}}),p=await Promise.all(f).then(e=>e.flat()).then(t=>e.filterInvalidDictionaries(t,o)).then(e=>n.formatDictionaries(e));s.setPluginTotal(p.length),s.setPluginDone(p.length);let m=Date.now(),h=await t.loadContentDeclarations(Array.isArray(i)?i:[i],o,c).then(t=>e.filterInvalidDictionaries(t,o)).then(e=>n.formatDictionaries(e)),g=Date.now();c(h.map(e=>({dictionaryKey:e.key,type:`local`,status:`built`})));let _=!!(o.editor.clientId&&o.editor.clientSecret);_&&s.setExpectRemote(!0);let v=[];_&&(v=await r.loadRemoteDictionaries(o,c,{onStartRemoteCheck:()=>s.startRemoteCheck(),onStopRemoteCheck:()=>s.stopRemoteCheck(),onError:e=>s.setRemoteError(e)}).then(t=>e.filterInvalidDictionaries(t,o)).then(e=>n.formatDictionaries(e)));let y=Date.now();return s.finish(),d(o),{localDictionaries:h,remoteDictionaries:v,pluginDictionaries:p,time:{localDictionaries:g-m,remoteDictionaries:y-g,pluginDictionaries:m-u}}};exports.loadDictionaries=f;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../_virtual/_rolldown/runtime.cjs`);const e=require(`../filterInvalidDictionaries.cjs`),t=require(`./loadContentDeclaration.cjs`),n=require(`../formatDictionary.cjs`),r=require(`./loadRemoteDictionaries.cjs`),i=require(`./log.cjs`);let a=require(`@intlayer/config/logger`),o=[];const s=new i.DictionariesLogger,c=e=>{let t=[...o];for(let n of e){let e=t.findIndex(e=>e.dictionaryKey===n.dictionaryKey&&e.type===n.type);e>=0?t[e]=n:t.push(n)}return o=t,s.update(e),t},l=e=>{switch(e){case`built`:case`imported`:case`fetched`:return`✔`;case`error`:return`✖`;default:return`⏲`}},u=e=>{switch(e){case`built`:case`imported`:case`fetched`:return a.ANSIColors.GREEN;case`error`:return a.ANSIColors.RED;default:return a.ANSIColors.BLUE}},d=e=>{if(e.log.mode!==`verbose`)return;let t=(0,a.getAppLogger)(e),n=new Map;for(let e of o){let t=n.get(e.dictionaryKey)??{};e.type===`local`&&(t.local=e.status),e.type===`remote`&&(t.remote=e.status),n.set(e.dictionaryKey,t)}let r=Array.from(n.keys()).sort((e,t)=>e.localeCompare(t)),i=0;for(let e of r){let t=n.get(e);if(t.local){let e=`[local: ${l(t.local)} ${t.local}]`;e.length>i&&(i=e.length)}}for(let e of r){let o=n.get(e),s=[];if(o.local){let e=(0,a.colorize)(`${l(o.local)} ${o.local}`,u(o.local)),t=`${a.ANSIColors.GREY}[`+(0,a.colorize)(`local: `,a.ANSIColors.GREY)+e+`${a.ANSIColors.GREY}]${a.ANSIColors.RESET}`,n=`[local: ${l(o.local)} ${o.local}]`,r=Math.max(0,i-n.length);s.push(t+` `.repeat(r))}else s.push(` `.repeat(i));if(o.remote){let e=(0,a.colorize)(`${l(o.remote)} ${o.remote}`,u(o.remote));s.push(`${a.ANSIColors.GREY}[`+(0,a.colorize)(`distant: `,a.ANSIColors.GREY)+e+`${a.ANSIColors.GREY}]${a.ANSIColors.RESET}`)}t(` - ${(0,a.colon)((0,a.colorizeKey)(e),{colSize:r})} ${s.join(` `)}`)}},f=async(i,o)=>{let{plugins:l}=o,u=Date.now();(0,a.getAppLogger)(o)(`Dictionaries:`,{isVerbose:!0});let f=(await Promise.all(l??[])).filter(e=>e.loadDictionaries).map(async e=>{try{return await e.loadDictionaries?.({configuration:o})??[]}catch(e){return s.setPluginError(e),[]}}),p=await Promise.all(f).then(e=>e.flat()).then(t=>e.filterInvalidDictionaries(t,o)).then(e=>n.formatDictionaries(e));s.setPluginTotal(p.length),s.setPluginDone(p.length);let m=Date.now(),h=await t.loadContentDeclarations(Array.isArray(i)?i:[i],o,c).then(t=>e.filterInvalidDictionaries(t,o)).then(e=>n.formatDictionaries(e)),g=Date.now();c(h.map(e=>({dictionaryKey:e.key,type:`local`,status:`built`})));let _=!!(o.editor.clientId&&o.editor.clientSecret);_&&s.setExpectRemote(!0);let v=[];_&&(v=await r.loadRemoteDictionaries(o,c,{onStartRemoteCheck:()=>s.startRemoteCheck(),onStopRemoteCheck:()=>s.stopRemoteCheck(),onError:e=>s.setRemoteError(e)}).then(t=>e.filterInvalidDictionaries(t,o)).then(e=>n.formatDictionaries(e)));let y=Date.now();return s.finish(),d(o),{localDictionaries:h,remoteDictionaries:v,pluginDictionaries:p,time:{localDictionaries:g-m,remoteDictionaries:y-g,pluginDictionaries:m-u}}};exports.loadDictionaries=f;
2
2
  //# sourceMappingURL=loadDictionaries.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"loadDictionaries.cjs","names":["DictionariesLogger","ANSIColors","filterInvalidDictionaries","formatDictionaries","loadContentDeclarations","loadRemoteDictionaries"],"sources":["../../../src/loadDictionaries/loadDictionaries.ts"],"sourcesContent":["import {\n ANSIColors,\n colon,\n colorize,\n colorizeKey,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { filterInvalidDictionaries } from '../filterInvalidDictionaries';\nimport { formatDictionaries } from '../formatDictionary';\nimport { loadContentDeclarations } from './loadContentDeclaration';\nimport { loadRemoteDictionaries } from './loadRemoteDictionaries';\nimport { DictionariesLogger } from './log';\n\nexport type DictionariesStatus = {\n dictionaryKey: string;\n type: 'local' | 'remote';\n status:\n | 'pending' // Key found but not fetched yet\n | 'fetching' // If dictionary fetch is in progress\n | 'fetched' // If dictionary fetch succeeded\n | 'error' // If dictionary fetch failed\n | 'imported' // If dictionary already fetched and still up to date\n | 'found' // If dictionary key is found but promise is not resolved yet (ex: fetching distant content)\n | 'building' // If dictionary is being built\n | 'built'; // If dictionary is built;\n error?: string;\n};\n\nlet loadDictionariesStatus: DictionariesStatus[] = [];\nconst logger = new DictionariesLogger();\n\nconst setLoadDictionariesStatus = (statuses: DictionariesStatus[]) => {\n const updated: DictionariesStatus[] = [...loadDictionariesStatus];\n\n for (const incoming of statuses) {\n const index = updated.findIndex(\n (s) =>\n s.dictionaryKey === incoming.dictionaryKey && s.type === incoming.type\n );\n if (index >= 0) {\n updated[index] = incoming;\n } else {\n updated.push(incoming);\n }\n }\n\n loadDictionariesStatus = updated;\n logger.update(statuses);\n\n return updated;\n};\n\ntype StatusRecord = {\n local?: DictionariesStatus['status'];\n remote?: DictionariesStatus['status'];\n};\n\nconst iconFor = (status: DictionariesStatus['status']) => {\n switch (status) {\n case 'built':\n case 'imported':\n case 'fetched':\n return '✔';\n case 'error':\n return '✖';\n default:\n return '⏲';\n }\n};\n\nconst colorFor = (status: DictionariesStatus['status']) => {\n switch (status) {\n case 'built':\n case 'imported':\n case 'fetched':\n return ANSIColors.GREEN;\n case 'error':\n return ANSIColors.RED;\n default:\n return ANSIColors.BLUE;\n }\n};\n\nconst printSummary = (configuration: IntlayerConfig) => {\n if (configuration.log.mode !== 'verbose') return;\n\n const appLogger = getAppLogger(configuration);\n\n // Aggregate by dictionary key\n const byKey = new Map<string, StatusRecord>();\n for (const status of loadDictionariesStatus) {\n const rec = byKey.get(status.dictionaryKey) ?? {};\n if (status.type === 'local') rec.local = status.status;\n if (status.type === 'remote') rec.remote = status.status;\n byKey.set(status.dictionaryKey, rec);\n }\n\n const keys = Array.from(byKey.keys()).sort((a, b) => a.localeCompare(b));\n\n // Compute the max visible length of the local label to align distant labels\n let maxLocalLabelLen = 0;\n for (const key of keys) {\n const rec = byKey.get(key)!;\n if (rec.local) {\n const visibleLocal = `[local: ${iconFor(rec.local)} ${rec.local}]`;\n if (visibleLocal.length > maxLocalLabelLen) {\n maxLocalLabelLen = visibleLocal.length;\n }\n }\n }\n\n for (const key of keys) {\n const rec = byKey.get(key)!;\n const labels: string[] = [];\n\n if (rec.local) {\n const inner = colorize(\n `${iconFor(rec.local)} ${rec.local}`,\n colorFor(rec.local)\n );\n const coloredLocal =\n `${ANSIColors.GREY}[` +\n colorize('local: ', ANSIColors.GREY) +\n inner +\n `${ANSIColors.GREY}]${ANSIColors.RESET}`;\n\n // Pad to align distant label across rows\n const visibleLocal = `[local: ${iconFor(rec.local)} ${rec.local}]`;\n const pad = Math.max(0, maxLocalLabelLen - visibleLocal.length);\n labels.push(coloredLocal + ' '.repeat(pad));\n } else {\n // If no local label, insert spaces to keep distant aligned\n labels.push(' '.repeat(maxLocalLabelLen));\n }\n\n if (rec.remote) {\n const inner = colorize(\n `${iconFor(rec.remote)} ${rec.remote}`,\n colorFor(rec.remote)\n );\n labels.push(\n `${ANSIColors.GREY}[` +\n colorize('distant: ', ANSIColors.GREY) +\n inner +\n `${ANSIColors.GREY}]${ANSIColors.RESET}`\n );\n }\n\n appLogger(\n ` - ${colon(colorizeKey(key), { colSize: keys })} ${labels.join(' ')}`\n );\n }\n};\n\nexport const loadDictionaries = async (\n contentDeclarationsPaths: string[] | string,\n configuration: IntlayerConfig\n): Promise<{\n localDictionaries: Dictionary[];\n remoteDictionaries: Dictionary[];\n pluginDictionaries: Dictionary[];\n time: {\n localDictionaries: number;\n remoteDictionaries: number;\n pluginDictionaries: number;\n };\n}> => {\n const { plugins } = configuration;\n const loadDictionariesStartTime = Date.now();\n const appLogger = getAppLogger(configuration);\n\n appLogger('Dictionaries:', { isVerbose: true });\n\n // Load additional dictionaries via plugins (e.g., ICU JSON ingestion)\n const pluginsWithLoadDictionaries = (plugins ?? []).filter(\n (plugin) => plugin.loadDictionaries\n );\n\n const loadPluginDictionariesPromise = pluginsWithLoadDictionaries.map(\n async (plugin) => {\n try {\n const res = await plugin.loadDictionaries?.({\n configuration,\n });\n\n return (res as Dictionary[] | undefined) ?? [];\n } catch (error) {\n logger.setPluginError(error as Error);\n\n return [];\n }\n }\n );\n\n const pluginDictionaries: Dictionary[] = await Promise.all(\n loadPluginDictionariesPromise as Promise<Dictionary[]>[]\n )\n .then((dictionaries) => dictionaries.flat())\n .then((dictionaries) =>\n filterInvalidDictionaries(dictionaries, configuration)\n )\n .then((dictionaries) => formatDictionaries(dictionaries));\n\n logger.setPluginTotal(pluginDictionaries.length);\n logger.setPluginDone(pluginDictionaries.length);\n\n const pluginDictionariesTime = Date.now();\n\n const files = Array.isArray(contentDeclarationsPaths)\n ? contentDeclarationsPaths\n : [contentDeclarationsPaths];\n\n const localDictionaries: Dictionary[] = await loadContentDeclarations(\n files,\n configuration,\n setLoadDictionariesStatus\n )\n .then((dictionaries) =>\n filterInvalidDictionaries(dictionaries, configuration)\n )\n .then((dictionaries) => formatDictionaries(dictionaries));\n\n const localDictionariesTime = Date.now();\n\n const localDictionariesStatus = localDictionaries.map(\n (dictionary) =>\n ({\n dictionaryKey: dictionary.key,\n type: 'local',\n status: 'built',\n }) as const\n );\n\n setLoadDictionariesStatus(localDictionariesStatus);\n\n const hasRemoteDictionaries = Boolean(\n configuration.editor.clientId && configuration.editor.clientSecret\n );\n\n if (hasRemoteDictionaries) {\n // We expect to fetch remote dictionaries soon; suppress a transient local-only render\n logger.setExpectRemote(true);\n }\n\n let remoteDictionaries: Dictionary[] = [];\n\n if (hasRemoteDictionaries) {\n remoteDictionaries = await loadRemoteDictionaries(\n configuration,\n setLoadDictionariesStatus,\n {\n onStartRemoteCheck: () => logger.startRemoteCheck(),\n onStopRemoteCheck: () => logger.stopRemoteCheck(),\n onError: (e) => logger.setRemoteError(e),\n }\n )\n .then((dictionaries) =>\n filterInvalidDictionaries(dictionaries, configuration)\n )\n .then((dictionaries) => formatDictionaries(dictionaries));\n }\n\n const remoteDictionariesTime = Date.now();\n\n // Stop spinner and show final progress line(s)\n logger.finish();\n\n printSummary(configuration);\n\n return {\n localDictionaries,\n remoteDictionaries,\n pluginDictionaries,\n time: {\n localDictionaries: localDictionariesTime - pluginDictionariesTime,\n remoteDictionaries: remoteDictionariesTime - localDictionariesTime,\n pluginDictionaries: pluginDictionariesTime - loadDictionariesStartTime,\n },\n };\n};\n"],"mappings":"6VA8BI,EAA+C,EAAE,CACrD,MAAM,EAAS,IAAIA,EAAAA,mBAEb,EAA6B,GAAmC,CACpE,IAAM,EAAgC,CAAC,GAAG,EAAuB,CAEjE,IAAK,IAAM,KAAY,EAAU,CAC/B,IAAM,EAAQ,EAAQ,UACnB,GACC,EAAE,gBAAkB,EAAS,eAAiB,EAAE,OAAS,EAAS,KACrE,CACG,GAAS,EACX,EAAQ,GAAS,EAEjB,EAAQ,KAAK,EAAS,CAO1B,MAHA,GAAyB,EACzB,EAAO,OAAO,EAAS,CAEhB,GAQH,EAAW,GAAyC,CACxD,OAAQ,EAAR,CACE,IAAK,QACL,IAAK,WACL,IAAK,UACH,MAAO,IACT,IAAK,QACH,MAAO,IACT,QACE,MAAO,MAIP,EAAY,GAAyC,CACzD,OAAQ,EAAR,CACE,IAAK,QACL,IAAK,WACL,IAAK,UACH,OAAOC,EAAAA,WAAW,MACpB,IAAK,QACH,OAAOA,EAAAA,WAAW,IACpB,QACE,OAAOA,EAAAA,WAAW,OAIlB,EAAgB,GAAkC,CACtD,GAAI,EAAc,IAAI,OAAS,UAAW,OAE1C,IAAM,GAAA,EAAA,EAAA,cAAyB,EAAc,CAGvC,EAAQ,IAAI,IAClB,IAAK,IAAM,KAAU,EAAwB,CAC3C,IAAM,EAAM,EAAM,IAAI,EAAO,cAAc,EAAI,EAAE,CAC7C,EAAO,OAAS,UAAS,EAAI,MAAQ,EAAO,QAC5C,EAAO,OAAS,WAAU,EAAI,OAAS,EAAO,QAClD,EAAM,IAAI,EAAO,cAAe,EAAI,CAGtC,IAAM,EAAO,MAAM,KAAK,EAAM,MAAM,CAAC,CAAC,MAAM,EAAG,IAAM,EAAE,cAAc,EAAE,CAAC,CAGpE,EAAmB,EACvB,IAAK,IAAM,KAAO,EAAM,CACtB,IAAM,EAAM,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AAC,EAG7D,IAAM,EAAyB,KAAK,KAAK,CAOzC,OAJA,EAAO,QAAQ,CAEf,EAAa,EAAc,CAEpB,CACL,oBACA,qBACA,qBACA,KAAM,CACJ,kBAAmB,EAAwB,EAC3C,mBAAoB,EAAyB,EAC7C,mBAAoB,EAAyB,EAC9C,CACF"}
1
+ {"version":3,"file":"loadDictionaries.cjs","names":["DictionariesLogger","ANSIColors","filterInvalidDictionaries","formatDictionaries","loadContentDeclarations","loadRemoteDictionaries"],"sources":["../../../src/loadDictionaries/loadDictionaries.ts"],"sourcesContent":["import {\n ANSIColors,\n colon,\n colorize,\n colorizeKey,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { filterInvalidDictionaries } from '../filterInvalidDictionaries';\nimport { formatDictionaries } from '../formatDictionary';\nimport { loadContentDeclarations } from './loadContentDeclaration';\nimport { loadRemoteDictionaries } from './loadRemoteDictionaries';\nimport { DictionariesLogger } from './log';\n\nexport type DictionariesStatus = {\n dictionaryKey: string;\n type: 'local' | 'remote';\n status:\n | 'pending' // Key found but not fetched yet\n | 'fetching' // If dictionary fetch is in progress\n | 'fetched' // If dictionary fetch succeeded\n | 'error' // If dictionary fetch failed\n | 'imported' // If dictionary already fetched and still up to date\n | 'found' // If dictionary key is found but promise is not resolved yet (ex: fetching distant content)\n | 'building' // If dictionary is being built\n | 'built'; // If dictionary is built;\n error?: string;\n};\n\nlet loadDictionariesStatus: DictionariesStatus[] = [];\nconst logger = new DictionariesLogger();\n\nconst setLoadDictionariesStatus = (statuses: DictionariesStatus[]) => {\n const updated: DictionariesStatus[] = [...loadDictionariesStatus];\n\n for (const incoming of statuses) {\n const index = updated.findIndex(\n (s) =>\n s.dictionaryKey === incoming.dictionaryKey && s.type === incoming.type\n );\n if (index >= 0) {\n updated[index] = incoming;\n } else {\n updated.push(incoming);\n }\n }\n\n loadDictionariesStatus = updated;\n logger.update(statuses);\n\n return updated;\n};\n\ntype StatusRecord = {\n local?: DictionariesStatus['status'];\n remote?: DictionariesStatus['status'];\n};\n\nconst iconFor = (status: DictionariesStatus['status']) => {\n switch (status) {\n case 'built':\n case 'imported':\n case 'fetched':\n return '✔';\n case 'error':\n return '✖';\n default:\n return '⏲';\n }\n};\n\nconst colorFor = (status: DictionariesStatus['status']) => {\n switch (status) {\n case 'built':\n case 'imported':\n case 'fetched':\n return ANSIColors.GREEN;\n case 'error':\n return ANSIColors.RED;\n default:\n return ANSIColors.BLUE;\n }\n};\n\nconst printSummary = (configuration: IntlayerConfig) => {\n if (configuration.log.mode !== 'verbose') return;\n\n const appLogger = getAppLogger(configuration);\n\n // Aggregate by dictionary key\n const byKey = new Map<string, StatusRecord>();\n for (const status of loadDictionariesStatus) {\n const rec = byKey.get(status.dictionaryKey) ?? {};\n if (status.type === 'local') rec.local = status.status;\n if (status.type === 'remote') rec.remote = status.status;\n byKey.set(status.dictionaryKey, rec);\n }\n\n const keys = Array.from(byKey.keys()).sort((a, b) => a.localeCompare(b));\n\n // Compute the max visible length of the local label to align distant labels\n let maxLocalLabelLen = 0;\n for (const key of keys) {\n const rec = byKey.get(key)!;\n if (rec.local) {\n const visibleLocal = `[local: ${iconFor(rec.local)} ${rec.local}]`;\n if (visibleLocal.length > maxLocalLabelLen) {\n maxLocalLabelLen = visibleLocal.length;\n }\n }\n }\n\n for (const key of keys) {\n const rec = byKey.get(key)!;\n const labels: string[] = [];\n\n if (rec.local) {\n const inner = colorize(\n `${iconFor(rec.local)} ${rec.local}`,\n colorFor(rec.local)\n );\n const coloredLocal =\n `${ANSIColors.GREY}[` +\n colorize('local: ', ANSIColors.GREY) +\n inner +\n `${ANSIColors.GREY}]${ANSIColors.RESET}`;\n\n // Pad to align distant label across rows\n const visibleLocal = `[local: ${iconFor(rec.local)} ${rec.local}]`;\n const pad = Math.max(0, maxLocalLabelLen - visibleLocal.length);\n labels.push(coloredLocal + ' '.repeat(pad));\n } else {\n // If no local label, insert spaces to keep distant aligned\n labels.push(' '.repeat(maxLocalLabelLen));\n }\n\n if (rec.remote) {\n const inner = colorize(\n `${iconFor(rec.remote)} ${rec.remote}`,\n colorFor(rec.remote)\n );\n labels.push(\n `${ANSIColors.GREY}[` +\n colorize('distant: ', ANSIColors.GREY) +\n inner +\n `${ANSIColors.GREY}]${ANSIColors.RESET}`\n );\n }\n\n appLogger(\n ` - ${colon(colorizeKey(key), { colSize: keys })} ${labels.join(' ')}`\n );\n }\n};\n\nexport const loadDictionaries = async (\n contentDeclarationsPaths: string[] | string,\n configuration: IntlayerConfig\n): Promise<{\n localDictionaries: Dictionary[];\n remoteDictionaries: Dictionary[];\n pluginDictionaries: Dictionary[];\n time: {\n localDictionaries: number;\n remoteDictionaries: number;\n pluginDictionaries: number;\n };\n}> => {\n const { plugins } = configuration;\n const loadDictionariesStartTime = Date.now();\n const appLogger = getAppLogger(configuration);\n\n appLogger('Dictionaries:', { isVerbose: true });\n\n // Load additional dictionaries via plugins (e.g., ICU JSON ingestion)\n const resolvedPlugins = await Promise.all(plugins ?? []);\n\n const pluginsWithLoadDictionaries = resolvedPlugins.filter(\n (plugin) => plugin.loadDictionaries\n );\n\n const loadPluginDictionariesPromise = pluginsWithLoadDictionaries.map(\n async (plugin) => {\n try {\n const res = await plugin.loadDictionaries?.({\n configuration,\n });\n\n return (res as Dictionary[] | undefined) ?? [];\n } catch (error) {\n logger.setPluginError(error as Error);\n\n return [];\n }\n }\n );\n\n const pluginDictionaries: Dictionary[] = await Promise.all(\n loadPluginDictionariesPromise as Promise<Dictionary[]>[]\n )\n .then((dictionaries) => dictionaries.flat())\n .then((dictionaries) =>\n filterInvalidDictionaries(dictionaries, configuration)\n )\n .then((dictionaries) => formatDictionaries(dictionaries));\n\n logger.setPluginTotal(pluginDictionaries.length);\n logger.setPluginDone(pluginDictionaries.length);\n\n const pluginDictionariesTime = Date.now();\n\n const files = Array.isArray(contentDeclarationsPaths)\n ? contentDeclarationsPaths\n : [contentDeclarationsPaths];\n\n const localDictionaries: Dictionary[] = await loadContentDeclarations(\n files,\n configuration,\n setLoadDictionariesStatus\n )\n .then((dictionaries) =>\n filterInvalidDictionaries(dictionaries, configuration)\n )\n .then((dictionaries) => formatDictionaries(dictionaries));\n\n const localDictionariesTime = Date.now();\n\n const localDictionariesStatus = localDictionaries.map(\n (dictionary) =>\n ({\n dictionaryKey: dictionary.key,\n type: 'local',\n status: 'built',\n }) as const\n );\n\n setLoadDictionariesStatus(localDictionariesStatus);\n\n const hasRemoteDictionaries = Boolean(\n configuration.editor.clientId && configuration.editor.clientSecret\n );\n\n if (hasRemoteDictionaries) {\n // We expect to fetch remote dictionaries soon; suppress a transient local-only render\n logger.setExpectRemote(true);\n }\n\n let remoteDictionaries: Dictionary[] = [];\n\n if (hasRemoteDictionaries) {\n remoteDictionaries = await loadRemoteDictionaries(\n configuration,\n setLoadDictionariesStatus,\n {\n onStartRemoteCheck: () => logger.startRemoteCheck(),\n onStopRemoteCheck: () => logger.stopRemoteCheck(),\n onError: (e) => logger.setRemoteError(e),\n }\n )\n .then((dictionaries) =>\n filterInvalidDictionaries(dictionaries, configuration)\n )\n .then((dictionaries) => formatDictionaries(dictionaries));\n }\n\n const remoteDictionariesTime = Date.now();\n\n // Stop spinner and show final progress line(s)\n logger.finish();\n\n printSummary(configuration);\n\n return {\n localDictionaries,\n remoteDictionaries,\n pluginDictionaries,\n time: {\n localDictionaries: localDictionariesTime - pluginDictionariesTime,\n remoteDictionaries: remoteDictionariesTime - localDictionariesTime,\n pluginDictionaries: pluginDictionariesTime - loadDictionariesStartTime,\n },\n };\n};\n"],"mappings":"6VA8BI,EAA+C,EAAE,CACrD,MAAM,EAAS,IAAIA,EAAAA,mBAEb,EAA6B,GAAmC,CACpE,IAAM,EAAgC,CAAC,GAAG,EAAuB,CAEjE,IAAK,IAAM,KAAY,EAAU,CAC/B,IAAM,EAAQ,EAAQ,UACnB,GACC,EAAE,gBAAkB,EAAS,eAAiB,EAAE,OAAS,EAAS,K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,EACD,CACE,KAAM,GAAiB,EAAa,MAAM,CAAC,CAC3C,KAAM,GACLC,EAAAA,0BAA0B,EAAc,EAAc,CACvD,CACA,KAAM,GAAiBC,EAAAA,mBAAmB,EAAa,CAAC,CAE3D,EAAO,eAAe,EAAmB,OAAO,CAChD,EAAO,cAAc,EAAmB,OAAO,CAE/C,IAAM,EAAyB,KAAK,KAAK,CAMnC,EAAkC,MAAMC,EAAAA,wBAJhC,MAAM,QAAQ,EAAyB,CACjD,EACA,CAAC,EAAyB,CAI5B,EACA,EACD,CACE,KAAM,GACLF,EAAAA,0BAA0B,EAAc,EAAc,CACvD,CACA,KAAM,GAAiBC,EAAAA,mBAAmB,EAAa,CAAC,CAErD,EAAwB,KAAK,KAAK,CAWxC,EATgC,EAAkB,IAC/C,IACE,CACC,cAAe,EAAW,IAC1B,KAAM,QACN,OAAQ,QACT,EACJ,CAEiD,CAElD,IAAM,EAAwB,GAC5B,EAAc,OAAO,UAAY,EAAc,OAAO,cAGpD,GAEF,EAAO,gBAAgB,GAAK,CAG9B,IAAI,EAAmC,EAAE,CAErC,IACF,EAAqB,MAAME,EAAAA,uBACzB,EACA,EACA,CACE,uBAA0B,EAAO,kBAAkB,CACnD,sBAAyB,EAAO,iBAAiB,CACjD,QAAU,GAAM,EAAO,eAAe,EAAE,CACzC,CACF,CACE,KAAM,GACLH,EAAAA,0BAA0B,EAAc,EAAc,CACvD,CACA,KAAM,GAAiBC,EAAAA,mBAAmB,EAAa,CAAC,EAG7D,IAAM,EAAyB,KAAK,KAAK,CAOzC,OAJA,EAAO,QAAQ,CAEf,EAAa,EAAc,CAEpB,CACL,oBACA,qBACA,qBACA,KAAM,CACJ,kBAAmB,EAAwB,EAC3C,mBAAoB,EAAyB,EAC7C,mBAAoB,EAAyB,EAC9C,CACF"}
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../_virtual/_rolldown/runtime.cjs`);const e=require(`./loadContentDeclaration.cjs`);let t=require(`node:fs/promises`),n=require(`node:path`);const r=async(r,i)=>{let{content:a,system:o}=i,{baseDir:s}=a,{dictionariesDir:c}=o;typeof r==`string`&&(r=[r]),await(0,t.mkdir)((0,n.resolve)(c),{recursive:!0});let l=[];for await(let t of r){let r=await e.loadContentDeclarations([t],i),a=(0,n.relative)(s,t),o={...r[0],filePath:a};l.push(o)}return l};exports.loadLocalDictionaries=r;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../_virtual/_rolldown/runtime.cjs`);const e=require(`./loadContentDeclaration.cjs`);let t=require(`node:fs/promises`),n=require(`node:path`);const r=async(r,i)=>{let{system:a}=i,{dictionariesDir:o,baseDir:s}=a;typeof r==`string`&&(r=[r]),await(0,t.mkdir)((0,n.resolve)(o),{recursive:!0});let c=[];for await(let t of r){let r=await e.loadContentDeclarations([t],i),a=(0,n.relative)(s,t),o={...r[0],filePath:a};c.push(o)}return c};exports.loadLocalDictionaries=r;
2
2
  //# sourceMappingURL=loadLocalDictionaries.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"loadLocalDictionaries.cjs","names":["loadContentDeclarations"],"sources":["../../../src/loadDictionaries/loadLocalDictionaries.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport { relative, resolve } from 'node:path';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { loadContentDeclarations } from './loadContentDeclaration';\n\nexport const loadLocalDictionaries = async (\n contentDeclarationsPaths: string[] | string,\n configuration: IntlayerConfig\n): Promise<Dictionary[]> => {\n const { content, system } = configuration;\n const { baseDir } = content;\n const { dictionariesDir } = system;\n\n if (typeof contentDeclarationsPaths === 'string') {\n contentDeclarationsPaths = [contentDeclarationsPaths];\n }\n\n // Create the dictionaries folder if it doesn't exist\n await mkdir(resolve(dictionariesDir), { recursive: true });\n\n const result: Dictionary[] = [];\n\n for await (const contentDeclarationPath of contentDeclarationsPaths) {\n const dictionary = await loadContentDeclarations(\n [contentDeclarationPath],\n configuration\n );\n\n const relativeFilePath = relative(baseDir, contentDeclarationPath);\n\n const dictionaryWithPath: Dictionary = {\n ...dictionary[0],\n filePath: relativeFilePath,\n };\n\n result.push(dictionaryWithPath);\n }\n\n return result;\n};\n"],"mappings":"yNAMA,MAAa,EAAwB,MACnC,EACA,IAC0B,CAC1B,GAAM,CAAE,UAAS,UAAW,EACtB,CAAE,WAAY,EACd,CAAE,mBAAoB,EAExB,OAAO,GAA6B,WACtC,EAA2B,CAAC,EAAyB,EAIvD,MAAA,EAAA,EAAA,QAAA,EAAA,EAAA,SAAoB,EAAgB,CAAE,CAAE,UAAW,GAAM,CAAC,CAE1D,IAAM,EAAuB,EAAE,CAE/B,UAAW,IAAM,KAA0B,EAA0B,CACnE,IAAM,EAAa,MAAMA,EAAAA,wBACvB,CAAC,EAAuB,CACxB,EACD,CAEK,GAAA,EAAA,EAAA,UAA4B,EAAS,EAAuB,CAE5D,EAAiC,CACrC,GAAG,EAAW,GACd,SAAU,EACX,CAED,EAAO,KAAK,EAAmB,CAGjC,OAAO"}
1
+ {"version":3,"file":"loadLocalDictionaries.cjs","names":["loadContentDeclarations"],"sources":["../../../src/loadDictionaries/loadLocalDictionaries.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport { relative, resolve } from 'node:path';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { loadContentDeclarations } from './loadContentDeclaration';\n\nexport const loadLocalDictionaries = async (\n contentDeclarationsPaths: string[] | string,\n configuration: IntlayerConfig\n): Promise<Dictionary[]> => {\n const { system } = configuration;\n const { dictionariesDir, baseDir } = system;\n\n if (typeof contentDeclarationsPaths === 'string') {\n contentDeclarationsPaths = [contentDeclarationsPaths];\n }\n\n // Create the dictionaries folder if it doesn't exist\n await mkdir(resolve(dictionariesDir), { recursive: true });\n\n const result: Dictionary[] = [];\n\n for await (const contentDeclarationPath of contentDeclarationsPaths) {\n const dictionary = await loadContentDeclarations(\n [contentDeclarationPath],\n configuration\n );\n\n const relativeFilePath = relative(baseDir, contentDeclarationPath);\n\n const dictionaryWithPath: Dictionary = {\n ...dictionary[0],\n filePath: relativeFilePath,\n };\n\n result.push(dictionaryWithPath);\n }\n\n return result;\n};\n"],"mappings":"yNAMA,MAAa,EAAwB,MACnC,EACA,IAC0B,CAC1B,GAAM,CAAE,UAAW,EACb,CAAE,kBAAiB,WAAY,EAEjC,OAAO,GAA6B,WACtC,EAA2B,CAAC,EAAyB,EAIvD,MAAA,EAAA,EAAA,QAAA,EAAA,EAAA,SAAoB,EAAgB,CAAE,CAAE,UAAW,GAAM,CAAC,CAE1D,IAAM,EAAuB,EAAE,CAE/B,UAAW,IAAM,KAA0B,EAA0B,CACnE,IAAM,EAAa,MAAMA,EAAAA,wBACvB,CAAC,EAAuB,CACxB,EACD,CAEK,GAAA,EAAA,EAAA,UAA4B,EAAS,EAAuB,CAE5D,EAAiC,CACrC,GAAG,EAAW,GACd,SAAU,EACX,CAED,EAAO,KAAK,EAAmB,CAGjC,OAAO"}
@@ -1,3 +1,3 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../_virtual/_rolldown/runtime.cjs`);let e=require(`node:path`),t=require(`@intlayer/config/logger`);const n=async(n,r)=>{let i=(0,t.getAppLogger)(r),a=n.filter(t=>{let n=(0,e.extname)(t);return[`.ts`,`.tsx`,`.js`,`.jsx`,`.cjs`,`.mjs`,`.json`].includes(n)});if(a.length===0)return;let o;try{o=(await import(`typescript`)).default||await import(`typescript`)}catch{return}let s=o.findConfigFile(r.content?.baseDir??process.cwd(),o.sys.fileExists,`tsconfig.json`),c={noEmit:!0,allowJs:!0,resolveJsonModule:!0};if(s){let t=o.sys.readFile(s);if(t){let n=o.parseConfigFileTextToJson(s,t);if(!n.error){let{incremental:t,tsBuildInfoFile:r,...i}=o.parseJsonConfigFileContent(n.config,o.sys,(0,e.dirname)(s)).options;c={...c,...i,noEmit:!0}}}}let l=o.createProgram(a,c);a.forEach(e=>{let t=l.getSourceFile(e);t&&o.getPreEmitDiagnostics(l,t).forEach(e=>{let t=o.flattenDiagnosticMessageText(e.messageText,`
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../_virtual/_rolldown/runtime.cjs`);let e=require(`node:path`),t=require(`@intlayer/config/logger`);const n=async(n,r)=>{let i=(0,t.getAppLogger)(r),a=n.filter(t=>{let n=(0,e.extname)(t);return[`.ts`,`.tsx`,`.js`,`.jsx`,`.cjs`,`.mjs`,`.json`].includes(n)});if(a.length===0)return;let o;try{o=(await import(`typescript`)).default||await import(`typescript`)}catch{return}let s=o.findConfigFile(r.system?.baseDir??process.cwd(),o.sys.fileExists,`tsconfig.json`),c={noEmit:!0,allowJs:!0,resolveJsonModule:!0};if(s){let t=o.sys.readFile(s);if(t){let n=o.parseConfigFileTextToJson(s,t);if(!n.error){let{incremental:t,tsBuildInfoFile:r,...i}=o.parseJsonConfigFileContent(n.config,o.sys,(0,e.dirname)(s)).options;c={...c,...i,noEmit:!0}}}}let l=o.createProgram(a,c);a.forEach(e=>{let t=l.getSourceFile(e);t&&o.getPreEmitDiagnostics(l,t).forEach(e=>{let t=o.flattenDiagnosticMessageText(e.messageText,`
2
2
  `);if(e.file&&e.start!==void 0){let{line:n,character:r}=e.file.getLineAndCharacterOfPosition(e.start);i(`TS Error in ${e.file.fileName} (${n+1},${r+1}): ${t}`,{level:`warn`})}})})};exports.logTypeScriptErrors=n;
3
3
  //# sourceMappingURL=logTypeScriptErrors.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"logTypeScriptErrors.cjs","names":[],"sources":["../../../src/loadDictionaries/logTypeScriptErrors.ts"],"sourcesContent":["import { dirname, extname } from 'node:path';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport type { IntlayerConfig } from '@intlayer/types/config';\n\nexport const logTypeScriptErrors = async (\n filePaths: string[],\n configuration: IntlayerConfig\n) => {\n const appLogger = getAppLogger(configuration);\n\n const filesToCheck = filePaths.filter((path) => {\n const ext = extname(path);\n\n return ['.ts', '.tsx', '.js', '.jsx', '.cjs', '.mjs', '.json'].includes(\n ext\n );\n });\n\n if (filesToCheck.length === 0) return;\n\n let ts: typeof import('typescript');\n\n try {\n ts = (await import('typescript')).default || (await import('typescript'));\n } catch {\n // TypeScript not installed, skip type checking\n\n return;\n }\n\n const configFileName = ts.findConfigFile(\n configuration.content?.baseDir ?? process.cwd(),\n ts.sys.fileExists,\n 'tsconfig.json'\n );\n\n let compilerOptions: any = {\n noEmit: true,\n\n allowJs: true,\n\n resolveJsonModule: true,\n };\n\n if (configFileName) {\n const configFileText = ts.sys.readFile(configFileName);\n\n if (configFileText) {\n const configJson = ts.parseConfigFileTextToJson(\n configFileName,\n\n configFileText\n );\n\n if (!configJson.error) {\n const parsedConfig = ts.parseJsonConfigFileContent(\n configJson.config,\n\n ts.sys,\n\n dirname(configFileName)\n );\n\n const { incremental, tsBuildInfoFile, ...restOptions } =\n parsedConfig.options;\n\n compilerOptions = { ...compilerOptions, ...restOptions, noEmit: true };\n }\n }\n }\n\n const program = ts.createProgram(filesToCheck, compilerOptions);\n\n filesToCheck.forEach((filePath) => {\n const sourceFile = program.getSourceFile(filePath);\n\n if (!sourceFile) return;\n\n const diagnostics = ts.getPreEmitDiagnostics(program, sourceFile);\n\n diagnostics.forEach((diagnostic) => {\n const message = ts.flattenDiagnosticMessageText(\n diagnostic.messageText,\n\n '\\n'\n );\n\n if (diagnostic.file && diagnostic.start !== undefined) {\n const { line, character } =\n diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);\n\n appLogger(\n `TS Error in ${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`,\n\n { level: 'warn' }\n );\n }\n });\n });\n};\n"],"mappings":"gLAIA,MAAa,EAAsB,MACjC,EACA,IACG,CACH,IAAM,GAAA,EAAA,EAAA,cAAyB,EAAc,CAEvC,EAAe,EAAU,OAAQ,GAAS,CAC9C,IAAM,GAAA,EAAA,EAAA,SA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import { dirname, extname } from 'node:path';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport type { IntlayerConfig } from '@intlayer/types/config';\n\nexport const logTypeScriptErrors = async (\n filePaths: string[],\n configuration: IntlayerConfig\n) => {\n const appLogger = getAppLogger(configuration);\n\n const filesToCheck = filePaths.filter((path) => {\n const ext = extname(path);\n\n return ['.ts', '.tsx', '.js', '.jsx', '.cjs', '.mjs', '.json'].includes(\n ext\n );\n });\n\n if (filesToCheck.length === 0) return;\n\n let ts: typeof import('typescript');\n\n try {\n ts = (await import('typescript')).default || (await import('typescript'));\n } catch {\n // TypeScript not installed, skip type checking\n\n return;\n }\n\n const configFileName = ts.findConfigFile(\n configuration.system?.baseDir ?? process.cwd(),\n ts.sys.fileExists,\n 'tsconfig.json'\n );\n\n let compilerOptions: any = {\n noEmit: true,\n\n allowJs: true,\n\n resolveJsonModule: true,\n };\n\n if (configFileName) {\n const configFileText = ts.sys.readFile(configFileName);\n\n if (configFileText) {\n const configJson = ts.parseConfigFileTextToJson(\n configFileName,\n\n configFileText\n );\n\n if (!configJson.error) {\n const parsedConfig = ts.parseJsonConfigFileContent(\n configJson.config,\n\n ts.sys,\n\n dirname(configFileName)\n );\n\n const { incremental, tsBuildInfoFile, ...restOptions } =\n parsedConfig.options;\n\n compilerOptions = { ...compilerOptions, ...restOptions, noEmit: true };\n }\n }\n }\n\n const program = ts.createProgram(filesToCheck, compilerOptions);\n\n filesToCheck.forEach((filePath) => {\n const sourceFile = program.getSourceFile(filePath);\n\n if (!sourceFile) return;\n\n const diagnostics = ts.getPreEmitDiagnostics(program, sourceFile);\n\n diagnostics.forEach((diagnostic) => {\n const message = ts.flattenDiagnosticMessageText(\n diagnostic.messageText,\n\n '\\n'\n );\n\n if (diagnostic.file && diagnostic.start !== undefined) {\n const { line, character } =\n diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);\n\n appLogger(\n `TS Error in ${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`,\n\n { level: 'warn' }\n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,EAAO,EAAE,GAAG,EAAY,EAAE,KAAK,IAE3E,CAAE,MAAO,OAAQ,CAClB,GAEH,EACF"}
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./_virtual/_rolldown/runtime.cjs`),t=require(`./createDictionaryEntryPoint/createDictionaryEntryPoint.cjs`),n=require(`./buildIntlayerDictionary/buildIntlayerDictionary.cjs`),r=require(`./utils/runOnce.cjs`),i=require(`./createType/createModuleAugmentation.cjs`),a=require(`./createType/createType.cjs`),o=require(`./listDictionariesPath.cjs`),s=require(`./loadDictionaries/loadDictionaries.cjs`),c=require(`./buildIntlayerDictionary/writeRemoteDictionary.cjs`),l=require(`./cleanOutputDir.cjs`),u=require(`./writeConfiguration/index.cjs`);let d=require(`node:fs/promises`),f=require(`node:path`),p=require(`@intlayer/config/logger`),m=require(`@intlayer/config/utils`),h=require(`@intlayer/config/package.json`);h=e.__toESM(h);const g={clean:!1,format:[`cjs`,`esm`],cacheTimeoutMs:1e3*60*60},_=async(e,_)=>{let v=(0,p.getAppLogger)(e),y=(0,f.join)(e.system.cacheDir,`intlayer-prepared.lock`),b=(0,m.cacheDisk)(e,[`intlayer-version`]),x=await b.get(),S=!!(x&&x===h.default.version),C=await u.isCachedConfigurationUpToDate(e),w=await o.listDictionariesWithStats(e),T=!1;try{let e=await(0,d.stat)(y);T=w.some(t=>t.stats.mtime.getTime()>e.mtime.getTime())}catch{}let E=e.plugins?.some(e=>!!e.loadDictionaries),{clean:D,format:O,forceRun:k,onIsCached:A,cacheTimeoutMs:j}={...g,forceRun:!S||!C||T||E,..._??{}};await r.runOnce(y,async()=>{(D||!S)&&await l.cleanOutputDir(e),await b.set(h.default.version);let r=Date.now();v([`Preparing Intlayer`,(0,p.colorize)(`(v${h.default.version})`,p.ANSIColors.GREY_DARK)]),await u.writeConfiguration(e);let o=Date.now();v([`Configuration written`,(0,p.colorize)(`(${o-r}ms)`,p.ANSIColors.GREY_DARK)],{isVerbose:!0});let d=await s.loadDictionaries(w.map(e=>e.path),e),f=Date.now();v([`Content loaded`,(0,p.colorize)([d.remoteDictionaries.length+d.pluginDictionaries.length>0?[`(Total: ${f-o}ms`,d.localDictionaries.length>0?` - Local: ${d.time.localDictionaries}ms`:``,d.remoteDictionaries.length>0?` - Remote: ${d.time.remoteDictionaries}ms`:``,d.pluginDictionaries.length>0?` - Plugin: ${d.time.pluginDictionaries}ms`:``,`)`].join(``):`(${f-o}ms)`].join(``),p.ANSIColors.GREY_DARK)],{isVerbose:!0});let m=await n.buildDictionary([...d.localDictionaries,...d.remoteDictionaries,...d.pluginDictionaries],e,O,!1);await c.writeRemoteDictionary(d.remoteDictionaries,e),await a.createTypes(Object.values(m?.mergedDictionaries??{}).map(e=>e.dictionary),e),await t.createDictionaryEntryPoint(e);let g=Date.now();v([`Dictionaries built`,(0,p.colorize)(`(${g-r}ms)`,p.ANSIColors.GREY_DARK)]),await i.createModuleAugmentation(e),v([`Module augmentation built`,(0,p.colorize)(`(${Date.now()-g}ms)`,p.ANSIColors.GREY_DARK)],{isVerbose:!0});for await(let t of e.plugins??[]){let{unmergedDictionaries:n,mergedDictionaries:r}=m;await t.afterBuild?.({dictionaries:{unmergedDictionaries:n,mergedDictionaries:r},configuration:e})}v([`Done`,(0,p.colorize)(`${Date.now()-r}ms`,p.ANSIColors.GREEN)],{level:`info`,isVerbose:!0})},{forceRun:k,onIsCached:A,cacheTimeoutMs:j})};exports.prepareIntlayer=_;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./_virtual/_rolldown/runtime.cjs`),t=require(`./createDictionaryEntryPoint/createDictionaryEntryPoint.cjs`),n=require(`./buildIntlayerDictionary/buildIntlayerDictionary.cjs`),r=require(`./utils/runOnce.cjs`),i=require(`./createType/createModuleAugmentation.cjs`),a=require(`./createType/createType.cjs`),o=require(`./listDictionariesPath.cjs`),s=require(`./loadDictionaries/loadDictionaries.cjs`),c=require(`./buildIntlayerDictionary/writeRemoteDictionary.cjs`),l=require(`./cleanOutputDir.cjs`),u=require(`./writeConfiguration/index.cjs`);let d=require(`node:fs/promises`),f=require(`node:path`),p=require(`@intlayer/config/logger`),m=require(`@intlayer/config/utils`),h=require(`@intlayer/config/package.json`);h=e.__toESM(h);const g={clean:!1,format:[`cjs`,`esm`],cacheTimeoutMs:1e3*60*60},_=async(e,_)=>{let v=(0,p.getAppLogger)(e),y=(0,f.join)(e.system.cacheDir,`intlayer-prepared.lock`),b=(0,m.cacheDisk)(e,[`intlayer-version`]),x=await b.get(),S=!!(x&&x===h.default.version),C=await u.isCachedConfigurationUpToDate(e),w=await o.listDictionariesWithStats(e),T=!1;try{let e=await(0,d.stat)(y);T=w.some(t=>t.stats.mtime.getTime()>e.mtime.getTime())}catch{}let E=(await Promise.all(e.plugins??[])).some(e=>!!e.loadDictionaries),{clean:D,format:O,forceRun:k,onIsCached:A,cacheTimeoutMs:j}={...g,forceRun:!S||!C||T||E,..._??{}};await r.runOnce(y,async()=>{(D||!S)&&await l.cleanOutputDir(e),await b.set(h.default.version);let r=Date.now();v([`Preparing Intlayer`,(0,p.colorize)(`(v${h.default.version})`,p.ANSIColors.GREY_DARK)]),await u.writeConfiguration(e);let o=Date.now();v([`Configuration written`,(0,p.colorize)(`(${o-r}ms)`,p.ANSIColors.GREY_DARK)],{isVerbose:!0});let d=await s.loadDictionaries(w.map(e=>e.path),e),f=Date.now();v([`Content loaded`,(0,p.colorize)([d.remoteDictionaries.length+d.pluginDictionaries.length>0?[`(Total: ${f-o}ms`,d.localDictionaries.length>0?` - Local: ${d.time.localDictionaries}ms`:``,d.remoteDictionaries.length>0?` - Remote: ${d.time.remoteDictionaries}ms`:``,d.pluginDictionaries.length>0?` - Plugin: ${d.time.pluginDictionaries}ms`:``,`)`].join(``):`(${f-o}ms)`].join(``),p.ANSIColors.GREY_DARK)],{isVerbose:!0});let m=await n.buildDictionary([...d.localDictionaries,...d.remoteDictionaries,...d.pluginDictionaries],e,O,!1);await c.writeRemoteDictionary(d.remoteDictionaries,e),await a.createTypes(Object.values(m?.mergedDictionaries??{}).map(e=>e.dictionary),e),await t.createDictionaryEntryPoint(e);let g=Date.now();v([`Dictionaries built`,(0,p.colorize)(`(${g-r}ms)`,p.ANSIColors.GREY_DARK)]),await i.createModuleAugmentation(e),v([`Module augmentation built`,(0,p.colorize)(`(${Date.now()-g}ms)`,p.ANSIColors.GREY_DARK)],{isVerbose:!0});for await(let t of e.plugins??[]){let{unmergedDictionaries:n,mergedDictionaries:r}=m;await t.afterBuild?.({dictionaries:{unmergedDictionaries:n,mergedDictionaries:r},configuration:e})}v([`Done`,(0,p.colorize)(`${Date.now()-r}ms`,p.ANSIColors.GREEN)],{level:`info`,isVerbose:!0})},{forceRun:k,onIsCached:A,cacheTimeoutMs:j})};exports.prepareIntlayer=_;
2
2
  //# sourceMappingURL=prepareIntlayer.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"prepareIntlayer.cjs","names":["packageJson","isCachedConfigurationUpToDate","listDictionariesWithStats","runOnce","cleanOutputDir","ANSIColors","writeConfiguration","loadDictionaries","buildDictionary","writeRemoteDictionary","createTypes","createDictionaryEntryPoint","createModuleAugmentation"],"sources":["../../src/prepareIntlayer.ts"],"sourcesContent":["import { stat } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { ANSIColors, colorize, getAppLogger } from '@intlayer/config/logger';\nimport packageJson from '@intlayer/config/package.json' with { type: 'json' };\nimport { cacheDisk } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { buildDictionary } from './buildIntlayerDictionary/buildIntlayerDictionary';\nimport { writeRemoteDictionary } from './buildIntlayerDictionary/writeRemoteDictionary';\nimport { cleanOutputDir } from './cleanOutputDir';\nimport { createDictionaryEntryPoint } from './createDictionaryEntryPoint/createDictionaryEntryPoint';\nimport { createModuleAugmentation, createTypes } from './createType/index';\nimport { listDictionariesWithStats } from './listDictionariesPath';\nimport { loadDictionaries } from './loadDictionaries/loadDictionaries';\nimport { runOnce } from './utils/runOnce';\nimport {\n isCachedConfigurationUpToDate,\n writeConfiguration,\n} from './writeConfiguration';\n\ntype PrepareIntlayerOptions = {\n clean?: boolean;\n format?: ('cjs' | 'esm')[];\n forceRun?: boolean;\n cacheTimeoutMs?: number;\n onIsCached?: () => void | Promise<void>;\n};\n\nconst DEFAULT_PREPARE_INTLAYER_OPTIONS = {\n clean: false,\n format: ['cjs', 'esm'],\n cacheTimeoutMs: 1000 * 60 * 60, // 1 hour\n} satisfies PrepareIntlayerOptions;\n\nexport const prepareIntlayer = async (\n configuration: IntlayerConfig,\n options?: PrepareIntlayerOptions\n) => {\n const appLogger = getAppLogger(configuration);\n\n const sentinelPath = join(\n configuration.system.cacheDir,\n 'intlayer-prepared.lock'\n );\n // Clean output dir if the intlayer version has changed\n const versionCache = cacheDisk(configuration, ['intlayer-version']);\n const intlayerCacheVersion = await versionCache.get();\n const isCorrectVersion = Boolean(\n intlayerCacheVersion && intlayerCacheVersion === packageJson.version\n );\n\n const isConfigSimilar = await isCachedConfigurationUpToDate(configuration);\n\n // Check if any dictionary has been changed to force a new rebuild\n const dictionariesWithStats = await listDictionariesWithStats(configuration);\n let isDictionaryChanged = false;\n try {\n // Try catch as sentinel file may not exist yet\n const sentinelStats = await stat(sentinelPath);\n isDictionaryChanged = dictionariesWithStats.some(\n (dictionary) =>\n dictionary.stats.mtime.getTime() > sentinelStats.mtime.getTime()\n );\n } catch {}\n\n const hasPluginLoadDictionaries = configuration.plugins?.some((plugin) =>\n Boolean(plugin.loadDictionaries)\n ); // Disable cache if any plugin because it can have custom behavior\n\n const { clean, format, forceRun, onIsCached, cacheTimeoutMs } = {\n ...DEFAULT_PREPARE_INTLAYER_OPTIONS,\n forceRun:\n !isCorrectVersion ||\n !isConfigSimilar ||\n isDictionaryChanged ||\n hasPluginLoadDictionaries,\n ...(options ?? {}),\n };\n\n // Skip preparation if it has already been done recently\n await runOnce(\n sentinelPath,\n async () => {\n // comment because of issue with next and webpack\n // await checkVersionsConsistency(configuration);\n\n if (clean || !isCorrectVersion) {\n await cleanOutputDir(configuration);\n }\n\n await versionCache.set(packageJson.version);\n\n const preparationStartMs = Date.now();\n\n appLogger([\n 'Preparing Intlayer',\n colorize(`(v${packageJson.version})`, ANSIColors.GREY_DARK),\n ]);\n\n await writeConfiguration(configuration);\n\n const configurationWrittenTime = Date.now();\n\n appLogger(\n [\n 'Configuration written',\n colorize(\n `(${configurationWrittenTime - preparationStartMs}ms)`,\n ANSIColors.GREY_DARK\n ),\n ],\n {\n isVerbose: true,\n }\n );\n\n const contentDeclarationPaths = dictionariesWithStats.map(\n (dictionary) => dictionary.path\n );\n\n const dictionaries = await loadDictionaries(\n contentDeclarationPaths,\n configuration\n );\n\n const dictionariesLoadedTime = Date.now();\n\n appLogger(\n [\n 'Content loaded',\n colorize(\n [\n dictionaries.remoteDictionaries.length +\n dictionaries.pluginDictionaries.length >\n 0\n ? [\n `(Total: ${dictionariesLoadedTime - configurationWrittenTime}ms`,\n dictionaries.localDictionaries.length > 0\n ? ` - Local: ${dictionaries.time.localDictionaries}ms`\n : '',\n dictionaries.remoteDictionaries.length > 0\n ? ` - Remote: ${dictionaries.time.remoteDictionaries}ms`\n : '',\n dictionaries.pluginDictionaries.length > 0\n ? ` - Plugin: ${dictionaries.time.pluginDictionaries}ms`\n : '',\n `)`,\n ].join('')\n : `(${dictionariesLoadedTime - configurationWrittenTime}ms)`,\n ].join(''),\n ANSIColors.GREY_DARK\n ),\n ],\n {\n isVerbose: true,\n }\n );\n\n // Build local dictionaries\n const dictionariesOutput = await buildDictionary(\n [\n ...dictionaries.localDictionaries,\n ...dictionaries.remoteDictionaries,\n ...dictionaries.pluginDictionaries,\n ],\n configuration,\n format,\n false\n );\n\n // Write remote dictionaries\n // Used as cache for next fetch\n await writeRemoteDictionary(\n dictionaries.remoteDictionaries,\n configuration\n );\n\n const dictionariesToBuild = Object.values(\n dictionariesOutput?.mergedDictionaries ?? {}\n ).map((dictionary) => dictionary.dictionary);\n\n await createTypes(dictionariesToBuild, configuration);\n\n await createDictionaryEntryPoint(configuration);\n\n const dictionariesBuiltTime = Date.now();\n\n appLogger([\n 'Dictionaries built',\n colorize(\n `(${dictionariesBuiltTime - preparationStartMs}ms)`,\n ANSIColors.GREY_DARK\n ),\n ]);\n\n await createModuleAugmentation(configuration);\n\n const moduleAugmentationBuiltTime = Date.now();\n\n appLogger(\n [\n 'Module augmentation built',\n colorize(\n `(${moduleAugmentationBuiltTime - dictionariesBuiltTime}ms)`,\n ANSIColors.GREY_DARK\n ),\n ],\n {\n isVerbose: true,\n }\n );\n\n // Plugin transformation\n // Allow plugins to post-process the final build output (e.g., write back ICU JSON)\n for await (const plugin of configuration.plugins ?? []) {\n const { unmergedDictionaries, mergedDictionaries } = dictionariesOutput;\n\n await plugin.afterBuild?.({\n dictionaries: {\n unmergedDictionaries,\n mergedDictionaries,\n },\n configuration,\n });\n }\n\n const preparationElapsedMs = Date.now() - preparationStartMs;\n appLogger(\n [`Done`, colorize(`${preparationElapsedMs}ms`, ANSIColors.GREEN)],\n {\n level: 'info',\n isVerbose: true,\n }\n );\n },\n {\n forceRun,\n onIsCached,\n cacheTimeoutMs,\n }\n );\n};\n"],"mappings":"4yBA2BA,MAAM,EAAmC,CACvC,MAAO,GACP,OAAQ,CAAC,MAAO,MAAM,CACtB,eAAgB,IAAO,GAAK,GAC7B,CAEY,EAAkB,MAC7B,EACA,IACG,CACH,IAAM,GAAA,EAAA,EAAA,cAAyB,EAAc,CAEvC,GAAA,EAAA,EAAA,MACJ,EAAc,OAAO,SACrB,yBACD,CAEK,GAAA,EAAA,EAAA,WAAyB,EAAe,CAAC,mBAAmB,CAAC,CAC7D,EAAuB,MAAM,EAAa,KAAK,CAC/C,EAAmB,GACvB,GAAwB,IAAyBA,EAAAA,QAAY,SAGzD,EAAkB,MAAMC,EAAAA,8BAA8B,EAAc,CAGpE,EAAwB,MAAMC,EAAAA,0BAA0B,EAAc,CACxE,EAAsB,GAC1B,GAAI,CAEF,IAAM,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CACV,IAAI,EAAyB,EAAyB,KAC3D,CAAC,KAAK,GAAG,CACVF,EAAAA,WAAW,UACZ,CACF,CACD,CACE,UAAW,GACZ,CACF,CAGD,IAAM,EAAqB,MAAMG,EAAAA,gBAC/B,CACE,GAAG,EAAa,kBAChB,GAAG,EAAa,mBAChB,GAAG,EAAa,mBACjB,CACD,EACA,EACA,GACD,CAID,MAAMC,EAAAA,sBACJ,EAAa,mBACb,EACD,CAMD,MAAMC,EAAAA,YAJsB,OAAO,OACjC,GAAoB,oBAAsB,EAAE,CAC7C,CAAC,IAAK,GAAe,EAAW,WAAW,CAEL,EAAc,CAErD,MAAMC,EAAAA,2BAA2B,EAAc,CAE/C,IAAM,EAAwB,KAAK,KAAK,CAExC,EAAU,CACR,sBAAA,EAAA,EAAA,UAEE,IAAI,EAAwB,EAAmB,KAC/CN,EAAAA,WAAW,UACZ,CACF,CAAC,CAEF,MAAMO,EAAAA,yBAAyB,EAAc,CAI7C,EACE,CACE,6BAAA,EAAA,EAAA,UAEE,IAN8B,KAAK,KAAK,CAMN,EAAsB,KACxDP,EAAAA,WAAW,UACZ,CACF,CACD,CACE,UAAW,GACZ,CACF,CAID,UAAW,IAAM,KAAU,EAAc,SAAW,EAAE,CAAE,CACtD,GAAM,CAAE,uBAAsB,sBAAuB,EAErD,MAAM,EAAO,aAAa,CACxB,aAAc,CACZ,uBACA,qBACD,CACD,gBACD,CAAC,CAIJ,EACE,CAAC,QAAA,EAAA,EAAA,UAAiB,GAFS,KAAK,KAAK,CAAG,EAEE,IAAKA,EAAAA,WAAW,MAAM,CAAC,CACjE,CACE,MAAO,OACP,UAAW,GACZ,CACF,EAEH,CACE,WACA,aACA,iBACD,CACF"}
1
+ {"version":3,"file":"prepareIntlayer.cjs","names":["packageJson","isCachedConfigurationUpToDate","listDictionariesWithStats","runOnce","cleanOutputDir","ANSIColors","writeConfiguration","loadDictionaries","buildDictionary","writeRemoteDictionary","createTypes","createDictionaryEntryPoint","createModuleAugmentation"],"sources":["../../src/prepareIntlayer.ts"],"sourcesContent":["import { stat } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { ANSIColors, colorize, getAppLogger } from '@intlayer/config/logger';\nimport packageJson from '@intlayer/config/package.json' with { type: 'json' };\nimport { cacheDisk } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { buildDictionary } from './buildIntlayerDictionary/buildIntlayerDictionary';\nimport { writeRemoteDictionary } from './buildIntlayerDictionary/writeRemoteDictionary';\nimport { cleanOutputDir } from './cleanOutputDir';\nimport { createDictionaryEntryPoint } from './createDictionaryEntryPoint/createDictionaryEntryPoint';\nimport { createModuleAugmentation, createTypes } from './createType/index';\nimport { listDictionariesWithStats } from './listDictionariesPath';\nimport { loadDictionaries } from './loadDictionaries/loadDictionaries';\nimport { runOnce } from './utils/runOnce';\nimport {\n isCachedConfigurationUpToDate,\n writeConfiguration,\n} from './writeConfiguration';\n\ntype PrepareIntlayerOptions = {\n clean?: boolean;\n format?: ('cjs' | 'esm')[];\n forceRun?: boolean;\n cacheTimeoutMs?: number;\n onIsCached?: () => void | Promise<void>;\n};\n\nconst DEFAULT_PREPARE_INTLAYER_OPTIONS = {\n clean: false,\n format: ['cjs', 'esm'],\n cacheTimeoutMs: 1000 * 60 * 60, // 1 hour\n} satisfies PrepareIntlayerOptions;\n\nexport const prepareIntlayer = async (\n configuration: IntlayerConfig,\n options?: PrepareIntlayerOptions\n) => {\n const appLogger = getAppLogger(configuration);\n\n const sentinelPath = join(\n configuration.system.cacheDir,\n 'intlayer-prepared.lock'\n );\n // Clean output dir if the intlayer version has changed\n const versionCache = cacheDisk(configuration, ['intlayer-version']);\n const intlayerCacheVersion = await versionCache.get();\n const isCorrectVersion = Boolean(\n intlayerCacheVersion && intlayerCacheVersion === packageJson.version\n );\n\n const isConfigSimilar = await isCachedConfigurationUpToDate(configuration);\n\n // Check if any dictionary has been changed to force a new rebuild\n const dictionariesWithStats = await listDictionariesWithStats(configuration);\n let isDictionaryChanged = false;\n try {\n // Try catch as sentinel file may not exist yet\n const sentinelStats = await stat(sentinelPath);\n isDictionaryChanged = dictionariesWithStats.some(\n (dictionary) =>\n dictionary.stats.mtime.getTime() > sentinelStats.mtime.getTime()\n );\n } catch {}\n\n const resolvedPlugins = await Promise.all(configuration.plugins ?? []);\n const hasPluginLoadDictionaries = resolvedPlugins.some((plugin) =>\n Boolean(plugin.loadDictionaries)\n ); // Disable cache if any plugin because it can have custom behavior\n\n const { clean, format, forceRun, onIsCached, cacheTimeoutMs } = {\n ...DEFAULT_PREPARE_INTLAYER_OPTIONS,\n forceRun:\n !isCorrectVersion ||\n !isConfigSimilar ||\n isDictionaryChanged ||\n hasPluginLoadDictionaries,\n ...(options ?? {}),\n };\n\n // Skip preparation if it has already been done recently\n await runOnce(\n sentinelPath,\n async () => {\n // comment because of issue with next and webpack\n // await checkVersionsConsistency(configuration);\n\n if (clean || !isCorrectVersion) {\n await cleanOutputDir(configuration);\n }\n\n await versionCache.set(packageJson.version);\n\n const preparationStartMs = Date.now();\n\n appLogger([\n 'Preparing Intlayer',\n colorize(`(v${packageJson.version})`, ANSIColors.GREY_DARK),\n ]);\n\n await writeConfiguration(configuration);\n\n const configurationWrittenTime = Date.now();\n\n appLogger(\n [\n 'Configuration written',\n colorize(\n `(${configurationWrittenTime - preparationStartMs}ms)`,\n ANSIColors.GREY_DARK\n ),\n ],\n {\n isVerbose: true,\n }\n );\n\n const contentDeclarationPaths = dictionariesWithStats.map(\n (dictionary) => dictionary.path\n );\n\n const dictionaries = await loadDictionaries(\n contentDeclarationPaths,\n configuration\n );\n\n const dictionariesLoadedTime = Date.now();\n\n appLogger(\n [\n 'Content loaded',\n colorize(\n [\n dictionaries.remoteDictionaries.length +\n dictionaries.pluginDictionaries.length >\n 0\n ? [\n `(Total: ${dictionariesLoadedTime - configurationWrittenTime}ms`,\n dictionaries.localDictionaries.length > 0\n ? ` - Local: ${dictionaries.time.localDictionaries}ms`\n : '',\n dictionaries.remoteDictionaries.length > 0\n ? ` - Remote: ${dictionaries.time.remoteDictionaries}ms`\n : '',\n dictionaries.pluginDictionaries.length > 0\n ? ` - Plugin: ${dictionaries.time.pluginDictionaries}ms`\n : '',\n `)`,\n ].join('')\n : `(${dictionariesLoadedTime - configurationWrittenTime}ms)`,\n ].join(''),\n ANSIColors.GREY_DARK\n ),\n ],\n {\n isVerbose: true,\n }\n );\n\n // Build local dictionaries\n const dictionariesOutput = await buildDictionary(\n [\n ...dictionaries.localDictionaries,\n ...dictionaries.remoteDictionaries,\n ...dictionaries.pluginDictionaries,\n ],\n configuration,\n format,\n false\n );\n\n // Write remote dictionaries\n // Used as cache for next fetch\n await writeRemoteDictionary(\n dictionaries.remoteDictionaries,\n configuration\n );\n\n const dictionariesToBuild = Object.values(\n dictionariesOutput?.mergedDictionaries ?? {}\n ).map((dictionary) => dictionary.dictionary);\n\n await createTypes(dictionariesToBuild, configuration);\n\n await createDictionaryEntryPoint(configuration);\n\n const dictionariesBuiltTime = Date.now();\n\n appLogger([\n 'Dictionaries built',\n colorize(\n `(${dictionariesBuiltTime - preparationStartMs}ms)`,\n ANSIColors.GREY_DARK\n ),\n ]);\n\n await createModuleAugmentation(configuration);\n\n const moduleAugmentationBuiltTime = Date.now();\n\n appLogger(\n [\n 'Module augmentation built',\n colorize(\n `(${moduleAugmentationBuiltTime - dictionariesBuiltTime}ms)`,\n ANSIColors.GREY_DARK\n ),\n ],\n {\n isVerbose: true,\n }\n );\n\n // Plugin transformation\n // Allow plugins to post-process the final build output (e.g., write back ICU JSON)\n for await (const plugin of configuration.plugins ?? []) {\n const { unmergedDictionaries, mergedDictionaries } = dictionariesOutput;\n\n await plugin.afterBuild?.({\n dictionaries: {\n unmergedDictionaries,\n mergedDictionaries,\n },\n configuration,\n });\n }\n\n const preparationElapsedMs = Date.now() - preparationStartMs;\n appLogger(\n [`Done`, colorize(`${preparationElapsedMs}ms`, ANSIColors.GREEN)],\n {\n level: 'info',\n isVerbose: true,\n }\n );\n },\n {\n forceRun,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AsB,KACxDP,EAAAA,WAAW,UACZ,CACF,CACD,CACE,UAAW,GACZ,CACF,CAID,UAAW,IAAM,KAAU,EAAc,SAAW,EAAE,CAAE,CACtD,GAAM,CAAE,uBAAsB,sBAAuB,EAErD,MAAM,EAAO,aAAa,CACxB,aAAc,CACZ,uBACA,qBACD,CACD,gBACD,CAAC,CAIJ,EACE,CAAC,QAAA,EAAA,EAAA,UAAiB,GAFS,KAAK,KAAK,CAAG,EAEE,IAAKA,EAAAA,WAAW,MAAM,CAAC,CACjE,CACE,MAAO,OACP,UAAW,GACZ,CACF,EAEH,CACE,WACA,aACA,iBACD,CACF"}
@@ -1,2 +1,3 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../_virtual/_rolldown/runtime.cjs`);let t=require(`recast`);t=e.__toESM(t);let n=require(`recast/parsers/babel.js`);n=e.__toESM(n);const r=t.types.builders,i=t.types.namedTypes,a=e=>typeof e==`object`&&!!e&&!Array.isArray(e),o=(e,t)=>e.properties.find(e=>!!((i.Property.check(e)||i.ObjectProperty.check(e))&&(i.Identifier.check(e.key)&&e.key.name===t||i.StringLiteral.check(e.key)&&e.key.value===t||i.Literal.check(e.key)&&e.key.value===t))),s=e=>e===null?r.literal(null):typeof e==`string`||typeof e==`number`||typeof e==`boolean`?r.literal(e):Array.isArray(e)?r.arrayExpression(e.map(e=>s(e))):a(e)?r.objectExpression(Object.entries(e).filter(([,e])=>e!==void 0).map(([e,t])=>r.property(`init`,r.stringLiteral(e),s(t)))):r.literal(null),c=(e,t)=>{for(let[n,l]of Object.entries(t)){if(l===void 0)continue;let t=o(e,n);if(a(l))if(t&&i.ObjectExpression.check(t.value))c(t.value,l);else{let i=s(l);t?t.value=i:e.properties.push(r.property(`init`,r.stringLiteral(n),i))}else{let i=s(l);t?t.value=i:e.properties.push(r.property(`init`,r.stringLiteral(n),i))}}},l=(e,r,a)=>{let o=`const _config = ${e.trim()||`{}`};`,s;try{s=t.parse(o,{parser:n})}catch{return JSON.stringify(a?r.content:r,null,2)}let l=s.program.body[0],u;if(i.VariableDeclaration.check(l)&&l.declarations.length>0&&i.VariableDeclarator.check(l.declarations[0])&&i.ObjectExpression.check(l.declarations[0].init)&&(u=l.declarations[0].init),a){let e=[`id`,`locale`,`filled`,`fill`,`title`,`description`,`tags`,`version`,`priority`,`contentAutoTransformation`,`$schema`];u.properties=u.properties.filter(t=>{if(i.Property.check(t)||i.ObjectProperty.check(t)){let n=``;return i.Identifier.check(t.key)?n=t.key.name:i.StringLiteral.check(t.key)?n=t.key.value:i.Literal.check(t.key)&&(n=String(t.key.value)),![`key`,`content`,...e].includes(n)}return!0})}return c(u,a?r.content:r),t.print(u,{tabWidth:2,quote:`double`,trailingComma:!1}).code};exports.transformJSONFile=l;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../_virtual/_rolldown/runtime.cjs`);let t=require(`recast`);t=e.__toESM(t);const n=t.types.builders,r=t.types.namedTypes,i=e=>typeof e==`object`&&!!e&&!Array.isArray(e),a=(e,t)=>t===null?r.Literal.check(e)&&e.value===null:typeof t==`string`||typeof t==`number`||typeof t==`boolean`?(r.Literal.check(e)||r.StringLiteral.check(e)||r.NumericLiteral.check(e)||r.BooleanLiteral.check(e))&&e.value===t:!1,o=(e,t)=>e.properties.find(e=>!!((r.Property.check(e)||r.ObjectProperty.check(e))&&(r.Identifier.check(e.key)&&e.key.name===t||r.StringLiteral.check(e.key)&&e.key.value===t||r.Literal.check(e.key)&&e.key.value===t))),s=e=>e===null?n.literal(null):typeof e==`string`||typeof e==`number`||typeof e==`boolean`?n.literal(e):Array.isArray(e)?n.arrayExpression(e.map(e=>s(e))):i(e)?n.objectExpression(Object.entries(e).filter(([,e])=>e!==void 0).map(([e,t])=>n.property(`init`,n.stringLiteral(e),s(t)))):n.literal(null),c=(e,t)=>{for(let[l,u]of Object.entries(t)){if(u===void 0)continue;let t=o(e,l);t?.comments&&t.comments.forEach(e=>{(e.type===`Line`||e.type===`CommentLine`)&&(e.type=e.type===`Line`?`Block`:`CommentBlock`,e.value=`__INLINE_LINE__${e.value}`,e.leading=!1,e.trailing=!0)}),i(u)?t&&r.ObjectExpression.check(t.value)?c(t.value,u):t?r.Literal.check(t.value)&&t.value.value===u||(t.value=s(u)):e.properties.push(n.property(`init`,n.stringLiteral(l),s(u))):t?a(t.value,u)||(t.value=s(u)):e.properties.push(n.property(`init`,n.stringLiteral(l),s(u)))}},l=(e,n,i)=>{let a=`const _config = ${e.trim()||`{}`};`,o;try{o=t.parse(a)}catch{return JSON.stringify(i?n.content:n,null,2)}let s=o.program.body[0],l;if(r.VariableDeclaration.check(s)&&s.declarations.length>0&&r.VariableDeclarator.check(s.declarations[0])&&r.ObjectExpression.check(s.declarations[0].init)&&(l=s.declarations[0].init),i){let e=[`id`,`locale`,`filled`,`fill`,`title`,`description`,`tags`,`version`,`priority`,`contentAutoTransformation`,`$schema`];for(let t=l.properties.length-1;t>=0;t--){let n=l.properties[t];if(r.Property.check(n)||r.ObjectProperty.check(n)){let i=``;r.Identifier.check(n.key)?i=n.key.name:r.StringLiteral.check(n.key)?i=n.key.value:r.Literal.check(n.key)&&(i=String(n.key.value)),[`key`,`content`,...e].includes(i)&&l.properties.splice(t,1)}}}c(l,i?n.content:n);let u=t.print(o,{tabWidth:2,quote:`double`,trailingComma:!1}).code,d=u.indexOf(`{`),f=u.lastIndexOf(`}`),p=u.substring(d,f+1);return p=p.replace(/\s*\/\*__INLINE_LINE__(.*?)\*\/(\s*,?)/g,`$2 //$1`),p=p.replace(/\n[ \t]*\n/g,`
2
+ `),p};exports.transformJSONFile=l;
2
3
  //# sourceMappingURL=transformJSONFile.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"transformJSONFile.cjs","names":["babelParser"],"sources":["../../../src/writeContentDeclaration/transformJSONFile.ts"],"sourcesContent":["import type { Dictionary } from '@intlayer/types/dictionary';\nimport * as recast from 'recast';\nimport * as babelParser from 'recast/parsers/babel.js';\n\nconst b = recast.types.builders;\nconst n = recast.types.namedTypes;\n\n/**\n * Checks if a value is a plain object (and not null/array)\n */\nconst isPlainObject = (value: unknown): value is Record<string, unknown> => {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n};\n\n/**\n * Robustly finds a property in a recast ObjectExpression.\n * Handles quoted (\"key\") or unquoted (key) properties.\n */\nconst getMatchingProperty = (node: any, key: string) => {\n return node.properties.find((prop: any) => {\n if (n.Property.check(prop) || n.ObjectProperty.check(prop)) {\n if (n.Identifier.check(prop.key) && prop.key.name === key) return true;\n if (n.StringLiteral.check(prop.key) && prop.key.value === key)\n return true;\n if (n.Literal.check(prop.key) && prop.key.value === key) return true;\n }\n return false;\n });\n};\n\n/**\n * Recursively builds a clean recast AST node from a plain JS value.\n * Because these nodes lack `loc` tracking, recast is forced to pretty-print them.\n */\nconst buildASTNode = (val: unknown): any => {\n if (val === null) return b.literal(null);\n\n if (\n typeof val === 'string' ||\n typeof val === 'number' ||\n typeof val === 'boolean'\n ) {\n return b.literal(val);\n }\n\n if (Array.isArray(val)) {\n return b.arrayExpression(val.map((item) => buildASTNode(item)));\n }\n\n if (isPlainObject(val)) {\n return b.objectExpression(\n Object.entries(val)\n .filter(([, v]) => v !== undefined)\n .map(([k, v]) =>\n b.property('init', b.stringLiteral(k), buildASTNode(v))\n )\n );\n }\n\n return b.literal(null); // Fallback\n};\n\n/**\n * Recursively updates the AST object literal with new data.\n */\nconst updateObjectLiteral = (node: any, data: Record<string, any>) => {\n for (const [key, val] of Object.entries(data)) {\n if (val === undefined) continue;\n\n const existingProp = getMatchingProperty(node, key);\n\n if (isPlainObject(val)) {\n if (existingProp && n.ObjectExpression.check(existingProp.value)) {\n updateObjectLiteral(existingProp.value, val);\n } else {\n const valueNode = buildASTNode(val);\n if (existingProp) {\n existingProp.value = valueNode;\n } else {\n node.properties.push(\n b.property('init', b.stringLiteral(key), valueNode)\n );\n }\n }\n } else {\n const valueNode = buildASTNode(val);\n if (existingProp) {\n existingProp.value = valueNode;\n } else {\n node.properties.push(\n b.property('init', b.stringLiteral(key), valueNode)\n );\n }\n }\n }\n};\n\nexport const transformJSONFile = (\n fileContent: string,\n dictionary: Dictionary,\n noMetadata?: boolean\n): string => {\n // Wrap content to create valid syntax for the parser\n const wrappedContent = `const _config = ${fileContent.trim() || '{}'};`;\n\n let ast: ReturnType<typeof recast.parse>;\n try {\n ast = recast.parse(wrappedContent, {\n parser: babelParser,\n });\n } catch {\n // Fallback if parsing failed\n return JSON.stringify(\n noMetadata ? dictionary.content : dictionary,\n null,\n 2\n );\n }\n\n // Navigate the AST to locate the object literal initialized to `_config`\n const declaration = ast.program.body[0];\n let objectLiteral: any;\n\n if (\n n.VariableDeclaration.check(declaration) &&\n declaration.declarations.length > 0 &&\n n.VariableDeclarator.check(declaration.declarations[0]) &&\n n.ObjectExpression.check(declaration.declarations[0].init)\n ) {\n objectLiteral = declaration.declarations[0].init;\n }\n\n if (noMetadata) {\n // Remove key, content and metadata properties if they exist\n const metadataProperties = [\n 'id',\n 'locale',\n 'filled',\n 'fill',\n 'title',\n 'description',\n 'tags',\n 'version',\n 'priority',\n 'contentAutoTransformation',\n '$schema',\n ];\n\n objectLiteral.properties = objectLiteral.properties.filter((prop: any) => {\n if (n.Property.check(prop) || n.ObjectProperty.check(prop)) {\n let propName = '';\n if (n.Identifier.check(prop.key)) propName = prop.key.name;\n else if (n.StringLiteral.check(prop.key)) propName = prop.key.value;\n else if (n.Literal.check(prop.key)) propName = String(prop.key.value);\n\n return !['key', 'content', ...metadataProperties].includes(propName);\n }\n return true;\n });\n }\n\n // Update the AST in place\n updateObjectLiteral(\n objectLiteral,\n noMetadata ? (dictionary.content as Record<string, any>) : dictionary\n );\n\n // Print only the target object literal node\n return recast.print(objectLiteral, {\n tabWidth: 2,\n quote: 'double',\n trailingComma: false,\n }).code;\n};\n"],"mappings":"uNAIA,MAAM,EAAI,EAAO,MAAM,SACjB,EAAI,EAAO,MAAM,WAKjB,EAAiB,GACd,OAAO,GAAU,YAAY,GAAkB,C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SONFile.ts"],"sourcesContent":["import type { Dictionary } from '@intlayer/types/dictionary';\nimport * as recast from 'recast';\n\nconst b = recast.types.builders;\nconst n = recast.types.namedTypes;\n\n/**\n * Checks if a value is a plain object (and not null/array)\n */\nconst isPlainObject = (value: unknown): value is Record<string, unknown> => {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n};\n\n/**\n * Checks if a recast AST node value matches the incoming primitive value.\n */\nconst isPrimitiveEqual = (astNode: any, val: unknown): boolean => {\n if (val === null) {\n return n.Literal.check(astNode) && astNode.value === null;\n }\n if (\n typeof val === 'string' ||\n typeof val === 'number' ||\n typeof val === 'boolean'\n ) {\n return (\n (n.Literal.check(astNode) ||\n n.StringLiteral.check(astNode) ||\n n.NumericLiteral.check(astNode) ||\n n.BooleanLiteral.check(astNode)) &&\n astNode.value === val\n );\n }\n return false;\n};\n\n/**\n * Robustly finds a property in a recast ObjectExpression.\n * Handles quoted (\"key\") or unquoted (key) properties.\n */\nconst getMatchingProperty = (node: any, key: string) => {\n return node.properties.find((prop: any) => {\n if (n.Property.check(prop) || n.ObjectProperty.check(prop)) {\n if (n.Identifier.check(prop.key) && prop.key.name === key) return true;\n if (n.StringLiteral.check(prop.key) && prop.key.value === key)\n return true;\n if (n.Literal.check(prop.key) && prop.key.value === key) return true;\n }\n return false;\n });\n};\n\n/**\n * Recursively builds a clean recast AST node from a plain JS value.\n * Because these nodes lack `loc` tracking, recast is forced to pretty-print them.\n */\nconst buildASTNode = (val: unknown): any => {\n if (val === null) return b.literal(null);\n\n if (\n typeof val === 'string' ||\n typeof val === 'number' ||\n typeof val === 'boolean'\n ) {\n return b.literal(val);\n }\n\n if (Array.isArray(val)) {\n return b.arrayExpression(val.map((item) => buildASTNode(item)));\n }\n\n if (isPlainObject(val)) {\n return b.objectExpression(\n Object.entries(val)\n .filter(([, v]) => v !== undefined)\n .map(([k, v]) =>\n b.property('init', b.stringLiteral(k), buildASTNode(v))\n )\n );\n }\n\n return b.literal(null); // Fallback\n};\n\n/**\n * Recursively updates the AST object literal with new data.\n */\nconst updateObjectLiteral = (node: any, data: Record<string, any>) => {\n for (const [key, val] of Object.entries(data)) {\n if (val === undefined) {\n continue;\n }\n\n const existingProp = getMatchingProperty(node, key);\n\n if (existingProp?.comments) {\n existingProp.comments.forEach((c: any) => {\n if (c.type === 'Line' || c.type === 'CommentLine') {\n // Convert to block comment and tag it to force Recast to print it inline\n c.type = c.type === 'Line' ? 'Block' : 'CommentBlock';\n c.value = `__INLINE_LINE__${c.value}`;\n c.leading = false;\n c.trailing = true;\n }\n });\n }\n\n if (isPlainObject(val)) {\n if (existingProp && n.ObjectExpression.check(existingProp.value)) {\n updateObjectLiteral(existingProp.value, val);\n } else {\n if (existingProp) {\n // Prevent AST invalidation if the primitive value is identical\n const isIdentical =\n n.Literal.check(existingProp.value) &&\n existingProp.value.value === val;\n\n if (!isIdentical) {\n existingProp.value = buildASTNode(val);\n }\n } else {\n node.properties.push(\n b.property('init', b.stringLiteral(key), buildASTNode(val))\n );\n }\n }\n } else {\n // Handle primitives and arrays\n if (existingProp) {\n // Skip assignment if the primitive value is identical\n if (!isPrimitiveEqual(existingProp.value, val)) {\n existingProp.value = buildASTNode(val);\n }\n } else {\n node.properties.push(\n b.property('init', b.stringLiteral(key), buildASTNode(val))\n );\n }\n }\n }\n};\n\nexport const transformJSONFile = (\n fileContent: string,\n dictionary: Dictionary,\n noMetadata?: boolean\n): string => {\n // Wrap content to create valid syntax for the parser\n const wrappedContent = `const _config = ${fileContent.trim() || '{}'};`;\n\n let ast: ReturnType<typeof recast.parse>;\n try {\n ast = recast.parse(wrappedContent);\n } catch {\n // Fallback if parsing failed\n return JSON.stringify(\n noMetadata ? dictionary.content : dictionary,\n null,\n 2\n );\n }\n\n // Navigate the AST to locate the object literal initialized to `_config`\n const declaration = ast.program.body[0];\n let objectLiteral: any;\n\n if (\n n.VariableDeclaration.check(declaration) &&\n declaration.declarations.length > 0 &&\n n.VariableDeclarator.check(declaration.declarations[0]) &&\n n.ObjectExpression.check(declaration.declarations[0].init)\n ) {\n objectLiteral = declaration.declarations[0].init;\n }\n\n if (noMetadata) {\n const metadataProperties = [\n 'id',\n 'locale',\n 'filled',\n 'fill',\n 'title',\n 'description',\n 'tags',\n 'version',\n 'priority',\n 'contentAutoTransformation',\n '$schema',\n ];\n\n // Mutate the array backwards instead of using .filter() to prevent layout invalidation\n for (let i = objectLiteral.properties.length - 1; i >= 0; i--) {\n const prop = objectLiteral.properties[i];\n if (n.Property.check(prop) || n.ObjectProperty.check(prop)) {\n let propName = '';\n if (n.Identifier.check(prop.key)) propName = prop.key.name;\n else if (n.StringLiteral.check(prop.key)) propName = prop.key.value;\n else if (n.Literal.check(prop.key)) propName = String(prop.key.value);\n\n if (['key', 'content', ...metadataProperties].includes(propName)) {\n objectLiteral.properties.splice(i, 1);\n }\n }\n }\n }\n\n // Update the AST in place\n updateObjectLiteral(\n objectLiteral,\n noMetadata ? (dictionary.content as Record<string, any>) : dictionary\n );\n\n // Print the full AST to utilize the global token stream for inline comments\n const printedCode = recast.print(ast, {\n tabWidth: 2,\n quote: 'double',\n trailingComma: false,\n }).code;\n\n // Extract the target object literal cleanly\n const startIndex = printedCode.indexOf('{');\n const endIndex = printedCode.lastIndexOf('}');\n let finalOutput = printedCode.substring(startIndex, endIndex + 1);\n\n // Revert the tagged block comment back to an inline line comment and fix comma placement\n finalOutput = finalOutput.replace(\n /\\s*\\/\\*__INLINE_LINE__(.*?)\\*\\/(\\s*,?)/g,\n '$2 //$1'\n );\n\n // Collapse empty lines injected by Recast around commented properties\n finalOutput = finalOutput.replace(/\\n[ \\t]*\\n/g, '\\n');\n\n return finalOutput;\n};\n"],"mappings":"+JAGA,MAAM,EAAI,EAAO,MAAM,SACjB,EAAI,EAAO,MAAM,WAKjB,EAAiB,GACd,OAAO,GAAU,YAAY,GAAkB,CAAC,MAAM,QAAQ,EAAM,CAMvE,GAAoB,EAAc,IAClC,IAAQ,KACH,EAAE,QAAQ,MAAM,EAAQ,EAAI,EA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CAC1D,IAAI,EAAW,GACX,EAAE,WAAW,MAAM,EAAK,IAAI,CAAE,EAAW,EAAK,IAAI,KAC7C,EAAE,cAAc,MAAM,EAAK,IAAI,CAAE,EAAW,EAAK,IAAI,MACrD,EAAE,QAAQ,MAAM,EAAK,IAAI,GAAE,EAAW,OAAO,EAAK,IAAI,MAAM,EAEjE,CAAC,MAAO,UAAW,GAAG,EAAmB,CAAC,SAAS,EAAS,EAC9D,EAAc,WAAW,OAAO,EAAG,EAAE,GAO7C,EACE,EACA,EAAc,EAAW,QAAkC,EAC5D,CAGD,IAAM,EAAc,EAAO,MAAM,EAAK,CACpC,SAAU,EACV,MAAO,SACP,cAAe,GAChB,CAAC,CAAC,KAGG,EAAa,EAAY,QAAQ,IAAI,CACrC,EAAW,EAAY,YAAY,IAAI,CACzC,EAAc,EAAY,UAAU,EAAY,EAAW,EAAE,CAWjE,MARA,GAAc,EAAY,QACxB,0CACA,UACD,CAGD,EAAc,EAAY,QAAQ,cAAe;EAAK,CAE/C"}
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../_virtual/_rolldown/runtime.cjs`);const e=require(`../utils/getFormatFromExtension.cjs`),t=require(`../detectFormatCommand.cjs`),n=require(`./processContentDeclarationContent.cjs`),r=require(`./transformJSONFile.cjs`),i=require(`./writeJSFile.cjs`);let a=require(`node:fs/promises`),o=require(`node:path`),s=require(`@intlayer/config/client`),c=require(`@intlayer/unmerged-dictionaries-entry`),l=require(`node:fs`),u=require(`@intlayer/core/plugins`),d=require(`node:child_process`),f=require(`node:util`);const p=async(t,r,i)=>{let a=await n.processContentDeclarationContent(t),s=a.content;t.locale?s=(0,u.getPerLocaleDictionary)(a,t.locale).content:i&&(s=(0,u.getFilteredLocalesDictionary)(a,i).content);let c={...t,content:s};for await(let e of r.plugins??[])if(e.formatOutput){let t=await e.formatOutput?.({dictionary:c,configuration:r});t&&(c=t)}if(!(c.content&&c.key))return c;let l={key:t.key,id:t.id,title:t.title,description:t.description,tags:t.tags,locale:t.locale,fill:t.fill,filled:t.filled,priority:t.priority,importMode:t.importMode,version:t.version,content:s};return e.getFormatFromExtension(t.filePath?(0,o.extname)(t.filePath):`.json`)===`json`&&c.content&&c.key&&(l={$schema:`https://intlayer.org/schema.json`,...l}),l},m={newDictionariesPath:`intlayer-dictionaries`},h=async(e,t,n)=>{let{system:r,compiler:i}=t,{baseDir:a}=r,l=i?.noMetadata??s.DefaultValues.Compiler.COMPILER_NO_METADATA,{newDictionariesPath:u,localeList:d}={...m,...n},h=(0,o.join)(a,u),_=(0,c.getUnmergedDictionaries)(t)[e.key]?.find(t=>t.localId===e.localId),v=await p(e,t,d);if(_?.filePath){let n=(0,f.isDeepStrictEqual)(_,e),r=(0,o.resolve)(t.system.baseDir,_.filePath);return n?{status:`up-to-date`,path:r}:(await g(r,v,t,l),{status:`updated`,path:r})}if(e.filePath){let n=(0,o.resolve)(t.system.baseDir,e.filePath);return await g(n,v,t,l),{status:`created`,path:n}}let y=(0,o.join)(h,`${e.key}.content.json`);return await g(y,v,t,l),{status:`imported`,path:y}},g=async(e,n,s,c)=>{await(0,a.mkdir)((0,o.dirname)(e),{recursive:!0});let u=(0,o.extname)(e);if(!s.content.fileExtensions.map(e=>e.startsWith(`.`)?e:`.${e}`).some(t=>e.endsWith(t)))throw Error(`Invalid file extension: ${u}, file: ${e}`);if(u===`.json`){let r=JSON.stringify(c?n.content:n,null,2),i=s.system?.tempDir;i&&await(0,a.mkdir)(i,{recursive:!0});let l=`${(0,o.basename)(e)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`,u=i?(0,o.join)(i,l):`${e}.${l}`;try{await(0,a.writeFile)(u,`${r}\n`),await(0,a.rename)(u,e)}catch(e){try{await(0,a.rm)(u,{force:!0})}catch{}throw e}let f=t.detectFormatCommand(s);if(f)try{(0,d.execSync)(f.replace(`{{file}}`,e),{stdio:`inherit`,cwd:s.system.baseDir})}catch(e){console.error(e)}return}if([`.jsonc`,`.json5`].includes(u)){let i=`{}`;if((0,l.existsSync)(e))try{i=await(0,a.readFile)(e,`utf-8`)}catch{}let u=r.transformJSONFile(i,n,c),f=s.system?.tempDir;f&&await(0,a.mkdir)(f,{recursive:!0});let p=`${(0,o.basename)(e)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`,m=f?(0,o.join)(f,p):`${e}.${p}`;try{await(0,a.writeFile)(m,u,`utf-8`),await(0,a.rename)(m,e)}catch(e){try{await(0,a.rm)(m,{force:!0})}catch{}throw e}let h=t.detectFormatCommand(s);if(h)try{(0,d.execSync)(h.replace(`{{file}}`,e),{stdio:`inherit`,cwd:s.system.baseDir})}catch(e){console.error(e)}return}await i.writeJSFile(e,n,s,c);try{await(0,a.rm)((0,o.join)(s.system.cacheDir,`intlayer-prepared.lock`),{recursive:!0})}catch{}};exports.writeContentDeclaration=h;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`}),require(`../_virtual/_rolldown/runtime.cjs`);const e=require(`../utils/getFormatFromExtension.cjs`),t=require(`../detectFormatCommand.cjs`),n=require(`./processContentDeclarationContent.cjs`),r=require(`./transformJSONFile.cjs`),i=require(`./writeJSFile.cjs`);let a=require(`node:fs/promises`),o=require(`node:path`),s=require(`@intlayer/config/client`),c=require(`@intlayer/unmerged-dictionaries-entry`),l=require(`node:fs`),u=require(`@intlayer/core/plugins`),d=require(`node:child_process`),f=require(`node:util`);const p=async(t,r,i)=>{let a=await n.processContentDeclarationContent(t),s=a.content;t.locale?s=(0,u.getPerLocaleDictionary)(a,t.locale).content:i&&(s=(0,u.getFilteredLocalesDictionary)(a,i).content);let c={...t,content:s};for await(let e of r.plugins??[])if(e.formatOutput){let t=await e.formatOutput?.({dictionary:c,configuration:r});t&&(c=t)}if(!(c.content&&c.key))return c;let l={key:t.key,id:t.id,title:t.title,description:t.description,tags:t.tags,locale:t.locale,fill:t.fill,filled:t.filled,priority:t.priority,importMode:t.importMode,version:t.version,content:s};return e.getFormatFromExtension(t.filePath?(0,o.extname)(t.filePath):`.json`)===`json`&&c.content&&c.key&&(l={$schema:`https://intlayer.org/schema.json`,...l}),l},m={newDictionariesPath:`intlayer-dictionaries`},h=async(e,t,n)=>{let{system:r,compiler:i}=t,{baseDir:a}=r,l=i?.noMetadata??s.DefaultValues.Compiler.COMPILER_NO_METADATA,{newDictionariesPath:u,localeList:d}={...m,...n},h=(0,o.join)(a,u),_=(0,c.getUnmergedDictionaries)(t)[e.key]?.find(t=>t.localId===e.localId),v=await p(e,t,d);if(_?.filePath){let n=(0,f.isDeepStrictEqual)(_,e),r=(0,o.resolve)(t.system.baseDir,_.filePath);return n?{status:`up-to-date`,path:r}:(await g(r,v,t,l),{status:`updated`,path:r})}if(e.filePath){let n=(0,o.resolve)(t.system.baseDir,e.filePath);return await g(n,v,t,l),{status:`created`,path:n}}let y=(0,o.join)(h,`${e.key}.content.json`);return await g(y,v,t,l),{status:`imported`,path:y}},g=async(e,n,s,c)=>{await(0,a.mkdir)((0,o.dirname)(e),{recursive:!0});let u=(0,o.extname)(e);if([`.json`,`.jsonc`,`.json5`].includes(u)){let i=`{}`;if((0,l.existsSync)(e))try{i=await(0,a.readFile)(e,`utf-8`)}catch{}let u=r.transformJSONFile(i,n,c),f=s.system?.tempDir;f&&await(0,a.mkdir)(f,{recursive:!0});let p=`${(0,o.basename)(e)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`,m=f?(0,o.join)(f,p):`${e}.${p}`;try{await(0,a.writeFile)(m,u,`utf-8`),await(0,a.rename)(m,e)}catch(e){try{await(0,a.rm)(m,{force:!0})}catch{}throw e}let h=t.detectFormatCommand(s);if(h)try{(0,d.execSync)(h.replace(`{{file}}`,e),{stdio:`inherit`,cwd:s.system.baseDir})}catch(e){console.error(e)}return}await i.writeJSFile(e,n,s,c);try{await(0,a.rm)((0,o.join)(s.system.cacheDir,`intlayer-prepared.lock`),{recursive:!0})}catch{}};exports.writeContentDeclaration=h;
2
2
  //# sourceMappingURL=writeContentDeclaration.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"writeContentDeclaration.cjs","names":["processContentDeclarationContent","getFormatFromExtension","DefaultValues","detectFormatCommand","transformJSONFile","writeJSFile"],"sources":["../../../src/writeContentDeclaration/writeContentDeclaration.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';\nimport { basename, dirname, extname, join, resolve } from 'node:path';\nimport { isDeepStrictEqual } from 'node:util';\nimport { DefaultValues } from '@intlayer/config/client';\nimport {\n getFilteredLocalesDictionary,\n getPerLocaleDictionary,\n} from '@intlayer/core/plugins';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\nimport { detectFormatCommand } from '../detectFormatCommand';\nimport {\n type Extension,\n getFormatFromExtension,\n} from '../utils/getFormatFromExtension';\nimport type { DictionaryStatus } from './dictionaryStatus';\nimport { processContentDeclarationContent } from './processContentDeclarationContent';\nimport { transformJSONFile } from './transformJSONFile';\nimport { writeJSFile } from './writeJSFile';\n\nconst formatContentDeclaration = async (\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n localeList?: LocalesValues[]\n) => {\n /**\n * Clean Markdown, Insertion, File, etc. node metadata\n */\n const processedDictionary =\n await processContentDeclarationContent(dictionary);\n\n let content = processedDictionary.content;\n\n /**\n * Filter locales content\n */\n\n if (dictionary.locale) {\n content = getPerLocaleDictionary(\n processedDictionary,\n dictionary.locale\n ).content;\n } else if (localeList) {\n content = getFilteredLocalesDictionary(\n processedDictionary,\n localeList\n ).content;\n }\n\n let pluginFormatResult: any = {\n ...dictionary,\n content,\n } satisfies Dictionary;\n\n /**\n * Format the dictionary with the plugins\n */\n\n for await (const plugin of configuration.plugins ?? []) {\n if (plugin.formatOutput) {\n const formattedResult = await plugin.formatOutput?.({\n dictionary: pluginFormatResult,\n configuration,\n });\n\n if (formattedResult) {\n pluginFormatResult = formattedResult;\n }\n }\n }\n\n const isDictionaryFormat =\n pluginFormatResult.content && pluginFormatResult.key;\n\n if (!isDictionaryFormat) return pluginFormatResult;\n\n let result: Dictionary = {\n key: dictionary.key,\n id: dictionary.id,\n title: dictionary.title,\n description: dictionary.description,\n tags: dictionary.tags,\n locale: dictionary.locale,\n fill: dictionary.fill,\n filled: dictionary.filled,\n priority: dictionary.priority,\n importMode: dictionary.importMode,\n version: dictionary.version,\n content,\n };\n\n /**\n * Add $schema to JSON dictionaries\n */\n const extension = (\n dictionary.filePath ? extname(dictionary.filePath) : '.json'\n ) as Extension;\n const format = getFormatFromExtension(extension);\n\n if (\n format === 'json' &&\n pluginFormatResult.content &&\n pluginFormatResult.key\n ) {\n result = {\n $schema: 'https://intlayer.org/schema.json',\n ...result,\n };\n }\n\n return result;\n};\n\ntype WriteContentDeclarationOptions = {\n newDictionariesPath?: string;\n localeList?: LocalesValues[];\n fallbackLocale?: Locale;\n};\n\nconst defaultOptions = {\n newDictionariesPath: 'intlayer-dictionaries',\n} satisfies WriteContentDeclarationOptions;\n\nexport const writeContentDeclaration = async (\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n options?: WriteContentDeclarationOptions\n): Promise<{ status: DictionaryStatus; path: string }> => {\n const { system, compiler } = configuration;\n const { baseDir } = system;\n\n const noMetadata =\n compiler?.noMetadata ?? DefaultValues.Compiler.COMPILER_NO_METADATA;\n const { newDictionariesPath, localeList } = {\n ...defaultOptions,\n ...options,\n };\n\n const newDictionaryLocationPath = join(baseDir, newDictionariesPath);\n\n const unmergedDictionariesRecord = getUnmergedDictionaries(configuration);\n const unmergedDictionaries = unmergedDictionariesRecord[\n dictionary.key\n ] as Dictionary[];\n\n const existingDictionary = unmergedDictionaries?.find(\n (el) => el.localId === dictionary.localId\n );\n\n const formattedContentDeclaration = await formatContentDeclaration(\n dictionary,\n configuration,\n localeList\n );\n\n if (existingDictionary?.filePath) {\n // Compare existing dictionary content with new dictionary content\n const isSameContent = isDeepStrictEqual(existingDictionary, dictionary);\n\n const filePath = resolve(\n configuration.system.baseDir,\n existingDictionary.filePath\n );\n\n // Up to date, nothing to do\n if (isSameContent) {\n return {\n status: 'up-to-date',\n path: filePath,\n };\n }\n\n await writeFileWithDirectories(\n filePath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return { status: 'updated', path: filePath };\n }\n\n if (dictionary.filePath) {\n const filePath = resolve(configuration.system.baseDir, dictionary.filePath);\n\n await writeFileWithDirectories(\n filePath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return { status: 'created', path: filePath };\n }\n\n // No existing dictionary, write to new location\n const contentDeclarationPath = join(\n newDictionaryLocationPath,\n `${dictionary.key}.content.json`\n );\n\n await writeFileWithDirectories(\n contentDeclarationPath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return {\n status: 'imported',\n path: contentDeclarationPath,\n };\n};\n\nconst writeFileWithDirectories = async (\n absoluteFilePath: string,\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n noMetadata?: boolean\n): Promise<void> => {\n // Extract the directory from the file path\n const dir = dirname(absoluteFilePath);\n\n // Create the directory recursively\n await mkdir(dir, { recursive: true });\n\n const extension = extname(absoluteFilePath);\n const acceptedExtensions = configuration.content.fileExtensions.map((ext) =>\n ext.startsWith('.') ? ext : `.${ext}`\n );\n\n const hasAcceptedExtension = acceptedExtensions.some((ext) =>\n absoluteFilePath.endsWith(ext)\n );\n\n if (!hasAcceptedExtension) {\n throw new Error(\n `Invalid file extension: ${extension}, file: ${absoluteFilePath}`\n );\n }\n\n if (extension === '.json') {\n const jsonDictionary = JSON.stringify(\n noMetadata ? dictionary.content : dictionary,\n null,\n 2\n );\n\n // Write the file\n const tempDir = configuration.system?.tempDir;\n if (tempDir) {\n await mkdir(tempDir, { recursive: true });\n }\n\n const tempFileName = `${basename(absoluteFilePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${absoluteFilePath}.${tempFileName}`;\n try {\n await writeFile(tempPath, `${jsonDictionary}\\n`); // Add a new line at the end of the file to avoid formatting issues with VSCode\n await rename(tempPath, absoluteFilePath);\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {\n // Ignore\n }\n throw error;\n }\n\n const formatCommand = detectFormatCommand(configuration);\n\n if (formatCommand) {\n try {\n execSync(formatCommand.replace('{{file}}', absoluteFilePath), {\n stdio: 'inherit',\n cwd: configuration.system.baseDir,\n });\n } catch (error) {\n console.error(error);\n }\n }\n\n return;\n }\n\n // Handle JSONC, and JSON5 via the AST transformer\n if (['.jsonc', '.json5'].includes(extension)) {\n let fileContent = '{}';\n\n if (existsSync(absoluteFilePath)) {\n try {\n fileContent = await readFile(absoluteFilePath, 'utf-8');\n } catch {\n // ignore read errors, start with empty object\n }\n }\n\n const transformedContent = transformJSONFile(\n fileContent,\n dictionary,\n noMetadata\n );\n\n // We use standard writeFile because transformedContent is already a string\n const tempDir = configuration.system?.tempDir;\n if (tempDir) {\n await mkdir(tempDir, { recursive: true });\n }\n\n const tempFileName = `${basename(absoluteFilePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${absoluteFilePath}.${tempFileName}`;\n try {\n await writeFile(tempPath, transformedContent, 'utf-8');\n await rename(tempPath, absoluteFilePath);\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {\n // Ignore\n }\n throw error;\n }\n\n const formatCommand = detectFormatCommand(configuration);\n\n if (formatCommand) {\n try {\n execSync(formatCommand.replace('{{file}}', absoluteFilePath), {\n stdio: 'inherit',\n cwd: configuration.system.baseDir,\n });\n } catch (error) {\n console.error(error);\n }\n }\n\n return;\n }\n\n await writeJSFile(absoluteFilePath, dictionary, configuration, noMetadata);\n\n // remove the cache as content has changed\n // Will force a new preparation of the intlayer on next build\n try {\n const sentinelPath = join(\n configuration.system.cacheDir,\n 'intlayer-prepared.lock'\n );\n await rm(sentinelPath, { recursive: true });\n } catch {}\n};\n"],"mappings":"wkBAyBA,MAAM,EAA2B,MAC/B,EACA,EACA,IACG,CAIH,IAAM,EACJ,MAAMA,EAAAA,iCAAiC,EAAW,CAEhD,EAAU,EAAoB,QAM9B,EAAW,OACb,GAAA,EAAA,EAAA,wBACE,EACA,EAAW,OACZ,CAAC,QACO,IACT,GAAA,EAAA,EAAA,8BACE,EACA,EACD,CAAC,SAGJ,IAAI,EAA0B,CAC5B,GAAG,EACH,UACD,CAMD,UAAW,IAAM,KAAU,EAAc,SAAW,EAAE,CACpD,GAAI,EAAO,aAAc,CACvB,IAAM,EAAkB,MAAM,EAAO,eAAe,CAClD,WAAY,EACZ,gBACD,CAAC,CAEE,IACF,EAAqB,GAQ3B,GAAI,EAFF,EAAmB,SAAW,EAAmB,KAE1B,OAAO,EAEhC,IAAI,EAAqB,CACvB,IAAK,EAAW,IAChB,GAAI,EAAW,GACf,MAAO,EAAW,MAClB,YAAa,EAAW,YACxB,KAAM,EAAW,KACjB,OAAQ,EAAW,OACnB,KAAM,EAAW,KACjB,OAAQ,EAAW,OACnB,SAAU,EAAW,SACrB,WAAY,EAAW,WACvB,QAAS,EAAW,QACpB,UACD,CAqBD,OAbeC,EAAAA,uBAFb,EAAW,UAAA,EAAA,EAAA,SAAmB,EAAW,SAAS,CAAG,QAEP,GAGnC,QACX,EAAmB,SACnB,EAAmB,MAEnB,EAAS,CACP,QAAS,mCACT,GAAG,EACJ,EAGI,GASH,EAAiB,CACrB,oBAAqB,wBACtB,CAEY,EAA0B,MACrC,EACA,EACA,IACwD,CACxD,GAAM,CAAE,SAAQ,YAAa,EACvB,CAAE,WAAY,EAEd,EACJ,GAAU,YAAcC,EAAAA,cAAc,SAAS,qBAC3C,CAAE,sBAAqB,cAAe,CAC1C,GAAG,EACH,GAAG,EACJ,CAEK,GAA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GAAI,CACF,MAAA,EAAA,EAAA,WAAgB,EAAU,EAAoB,QAAQ,CACtD,MAAA,EAAA,EAAA,QAAa,EAAU,EAAiB,OACjC,EAAO,CACd,GAAI,CACF,MAAA,EAAA,EAAA,IAAS,EAAU,CAAE,MAAO,GAAM,CAAC,MAC7B,EAGR,MAAM,EAGR,IAAM,EAAgBD,EAAAA,oBAAoB,EAAc,CAExD,GAAI,EACF,GAAI,EACF,EAAA,EAAA,UAAS,EAAc,QAAQ,WAAY,EAAiB,CAAE,CAC5D,MAAO,UACP,IAAK,EAAc,OAAO,QAC3B,CAAC,OACK,EAAO,CACd,QAAQ,MAAM,EAAM,CAIxB,OAGF,MAAME,EAAAA,YAAY,EAAkB,EAAY,EAAe,EAAW,CAI1E,GAAI,CAKF,MAAA,EAAA,EAAA,KAAA,EAAA,EAAA,MAHE,EAAc,OAAO,SACrB,yBACD,CACsB,CAAE,UAAW,GAAM,CAAC,MACrC"}
1
+ {"version":3,"file":"writeContentDeclaration.cjs","names":["processContentDeclarationContent","getFormatFromExtension","DefaultValues","transformJSONFile","detectFormatCommand","writeJSFile"],"sources":["../../../src/writeContentDeclaration/writeContentDeclaration.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';\nimport { basename, dirname, extname, join, resolve } from 'node:path';\nimport { isDeepStrictEqual } from 'node:util';\nimport { DefaultValues } from '@intlayer/config/client';\nimport {\n getFilteredLocalesDictionary,\n getPerLocaleDictionary,\n} from '@intlayer/core/plugins';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\nimport { detectFormatCommand } from '../detectFormatCommand';\nimport {\n type Extension,\n getFormatFromExtension,\n} from '../utils/getFormatFromExtension';\nimport type { DictionaryStatus } from './dictionaryStatus';\nimport { processContentDeclarationContent } from './processContentDeclarationContent';\nimport { transformJSONFile } from './transformJSONFile';\nimport { writeJSFile } from './writeJSFile';\n\nconst formatContentDeclaration = async (\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n localeList?: LocalesValues[]\n) => {\n /**\n * Clean Markdown, Insertion, File, etc. node metadata\n */\n const processedDictionary =\n await processContentDeclarationContent(dictionary);\n\n let content = processedDictionary.content;\n\n /**\n * Filter locales content\n */\n\n if (dictionary.locale) {\n content = getPerLocaleDictionary(\n processedDictionary,\n dictionary.locale\n ).content;\n } else if (localeList) {\n content = getFilteredLocalesDictionary(\n processedDictionary,\n localeList\n ).content;\n }\n\n let pluginFormatResult: any = {\n ...dictionary,\n content,\n } satisfies Dictionary;\n\n /**\n * Format the dictionary with the plugins\n */\n\n for await (const plugin of configuration.plugins ?? []) {\n if (plugin.formatOutput) {\n const formattedResult = await plugin.formatOutput?.({\n dictionary: pluginFormatResult,\n configuration,\n });\n\n if (formattedResult) {\n pluginFormatResult = formattedResult;\n }\n }\n }\n\n const isDictionaryFormat =\n pluginFormatResult.content && pluginFormatResult.key;\n\n if (!isDictionaryFormat) return pluginFormatResult;\n\n let result: Dictionary = {\n key: dictionary.key,\n id: dictionary.id,\n title: dictionary.title,\n description: dictionary.description,\n tags: dictionary.tags,\n locale: dictionary.locale,\n fill: dictionary.fill,\n filled: dictionary.filled,\n priority: dictionary.priority,\n importMode: dictionary.importMode,\n version: dictionary.version,\n content,\n };\n\n /**\n * Add $schema to JSON dictionaries\n */\n const extension = (\n dictionary.filePath ? extname(dictionary.filePath) : '.json'\n ) as Extension;\n const format = getFormatFromExtension(extension);\n\n if (\n format === 'json' &&\n pluginFormatResult.content &&\n pluginFormatResult.key\n ) {\n result = {\n $schema: 'https://intlayer.org/schema.json',\n ...result,\n };\n }\n\n return result;\n};\n\ntype WriteContentDeclarationOptions = {\n newDictionariesPath?: string;\n localeList?: LocalesValues[];\n fallbackLocale?: Locale;\n};\n\nconst defaultOptions = {\n newDictionariesPath: 'intlayer-dictionaries',\n} satisfies WriteContentDeclarationOptions;\n\nexport const writeContentDeclaration = async (\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n options?: WriteContentDeclarationOptions\n): Promise<{ status: DictionaryStatus; path: string }> => {\n const { system, compiler } = configuration;\n const { baseDir } = system;\n\n const noMetadata =\n compiler?.noMetadata ?? DefaultValues.Compiler.COMPILER_NO_METADATA;\n const { newDictionariesPath, localeList } = {\n ...defaultOptions,\n ...options,\n };\n\n const newDictionaryLocationPath = join(baseDir, newDictionariesPath);\n\n const unmergedDictionariesRecord = getUnmergedDictionaries(configuration);\n const unmergedDictionaries = unmergedDictionariesRecord[\n dictionary.key\n ] as Dictionary[];\n\n const existingDictionary = unmergedDictionaries?.find(\n (el) => el.localId === dictionary.localId\n );\n\n const formattedContentDeclaration = await formatContentDeclaration(\n dictionary,\n configuration,\n localeList\n );\n\n if (existingDictionary?.filePath) {\n // Compare existing dictionary content with new dictionary content\n const isSameContent = isDeepStrictEqual(existingDictionary, dictionary);\n\n const filePath = resolve(\n configuration.system.baseDir,\n existingDictionary.filePath\n );\n\n // Up to date, nothing to do\n if (isSameContent) {\n return {\n status: 'up-to-date',\n path: filePath,\n };\n }\n\n await writeFileWithDirectories(\n filePath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return { status: 'updated', path: filePath };\n }\n\n if (dictionary.filePath) {\n const filePath = resolve(configuration.system.baseDir, dictionary.filePath);\n\n await writeFileWithDirectories(\n filePath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return { status: 'created', path: filePath };\n }\n\n // No existing dictionary, write to new location\n const contentDeclarationPath = join(\n newDictionaryLocationPath,\n `${dictionary.key}.content.json`\n );\n\n await writeFileWithDirectories(\n contentDeclarationPath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return {\n status: 'imported',\n path: contentDeclarationPath,\n };\n};\n\nconst writeFileWithDirectories = async (\n absoluteFilePath: string,\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n noMetadata?: boolean\n): Promise<void> => {\n // Extract the directory from the file path\n const dir = dirname(absoluteFilePath);\n\n // Create the directory recursively\n await mkdir(dir, { recursive: true });\n\n const extension = extname(absoluteFilePath);\n\n // Handle JSON, JSONC, and JSON5 via the AST transformer\n if (['.json', '.jsonc', '.json5'].includes(extension)) {\n let fileContent = '{}';\n\n if (existsSync(absoluteFilePath)) {\n try {\n fileContent = await readFile(absoluteFilePath, 'utf-8');\n } catch {\n // ignore read errors, start with empty object\n }\n }\n\n const transformedContent = transformJSONFile(\n fileContent,\n dictionary,\n noMetadata\n );\n\n // We use standard writeFile because transformedContent is already a string\n const tempDir = configuration.system?.tempDir;\n if (tempDir) {\n await mkdir(tempDir, { recursive: true });\n }\n\n const tempFileName = `${basename(absoluteFilePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${absoluteFilePath}.${tempFileName}`;\n try {\n await writeFile(tempPath, transformedContent, 'utf-8');\n await rename(tempPath, absoluteFilePath);\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {\n // Ignore\n }\n throw error;\n }\n\n const formatCommand = detectFormatCommand(configuration);\n\n if (formatCommand) {\n try {\n execSync(formatCommand.replace('{{file}}', absoluteFilePath), {\n stdio: 'inherit',\n cwd: configuration.system.baseDir,\n });\n } catch (error) {\n console.error(error);\n }\n }\n\n return;\n }\n\n await writeJSFile(absoluteFilePath, dictionary, configuration, noMetadata);\n\n // remove the cache as content has changed\n // Will force a new preparation of the intlayer on next build\n try {\n const sentinelPath = join(\n configuration.system.cacheDir,\n 'intlayer-prepared.lock'\n );\n await rm(sentinelPath, { recursive: true });\n } catch {}\n};\n"],"mappings":"wkBAyBA,MAAM,EAA2B,MAC/B,EACA,EACA,IACG,CAIH,IAAM,EACJ,MAAMA,EAAAA,iCAAiC,EAAW,CAEhD,EAAU,EAAoB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I,CACF,MAAA,EAAA,EAAA,WAAgB,EAAU,EAAoB,QAAQ,CACtD,MAAA,EAAA,EAAA,QAAa,EAAU,EAAiB,OACjC,EAAO,CACd,GAAI,CACF,MAAA,EAAA,EAAA,IAAS,EAAU,CAAE,MAAO,GAAM,CAAC,MAC7B,EAGR,MAAM,EAGR,IAAM,EAAgBC,EAAAA,oBAAoB,EAAc,CAExD,GAAI,EACF,GAAI,EACF,EAAA,EAAA,UAAS,EAAc,QAAQ,WAAY,EAAiB,CAAE,CAC5D,MAAO,UACP,IAAK,EAAc,OAAO,QAC3B,CAAC,OACK,EAAO,CACd,QAAQ,MAAM,EAAM,CAIxB,OAGF,MAAMC,EAAAA,YAAY,EAAkB,EAAY,EAAe,EAAW,CAI1E,GAAI,CAKF,MAAA,EAAA,EAAA,KAAA,EAAA,EAAA,MAHE,EAAc,OAAO,SACrB,yBACD,CACsB,CAAE,UAAW,GAAM,CAAC,MACrC"}
@@ -1,2 +1,2 @@
1
- import{filterInvalidDictionaries as e}from"../filterInvalidDictionaries.mjs";import{loadContentDeclarations as t}from"./loadContentDeclaration.mjs";import{formatDictionaries as n}from"../formatDictionary.mjs";import{loadRemoteDictionaries as r}from"./loadRemoteDictionaries.mjs";import{DictionariesLogger as i}from"./log.mjs";import{ANSIColors as a,colon as o,colorize as s,colorizeKey as c,getAppLogger as l}from"@intlayer/config/logger";let u=[];const d=new i,f=e=>{let t=[...u];for(let n of e){let e=t.findIndex(e=>e.dictionaryKey===n.dictionaryKey&&e.type===n.type);e>=0?t[e]=n:t.push(n)}return u=t,d.update(e),t},p=e=>{switch(e){case`built`:case`imported`:case`fetched`:return`✔`;case`error`:return`✖`;default:return`⏲`}},m=e=>{switch(e){case`built`:case`imported`:case`fetched`:return a.GREEN;case`error`:return a.RED;default:return a.BLUE}},h=e=>{if(e.log.mode!==`verbose`)return;let t=l(e),n=new Map;for(let e of u){let t=n.get(e.dictionaryKey)??{};e.type===`local`&&(t.local=e.status),e.type===`remote`&&(t.remote=e.status),n.set(e.dictionaryKey,t)}let r=Array.from(n.keys()).sort((e,t)=>e.localeCompare(t)),i=0;for(let e of r){let t=n.get(e);if(t.local){let e=`[local: ${p(t.local)} ${t.local}]`;e.length>i&&(i=e.length)}}for(let e of r){let l=n.get(e),u=[];if(l.local){let e=s(`${p(l.local)} ${l.local}`,m(l.local)),t=`${a.GREY}[`+s(`local: `,a.GREY)+e+`${a.GREY}]${a.RESET}`,n=`[local: ${p(l.local)} ${l.local}]`,r=Math.max(0,i-n.length);u.push(t+` `.repeat(r))}else u.push(` `.repeat(i));if(l.remote){let e=s(`${p(l.remote)} ${l.remote}`,m(l.remote));u.push(`${a.GREY}[`+s(`distant: `,a.GREY)+e+`${a.GREY}]${a.RESET}`)}t(` - ${o(c(e),{colSize:r})} ${u.join(` `)}`)}},g=async(i,a)=>{let{plugins:o}=a,s=Date.now();l(a)(`Dictionaries:`,{isVerbose:!0});let c=(o??[]).filter(e=>e.loadDictionaries).map(async e=>{try{return await e.loadDictionaries?.({configuration:a})??[]}catch(e){return d.setPluginError(e),[]}}),u=await Promise.all(c).then(e=>e.flat()).then(t=>e(t,a)).then(e=>n(e));d.setPluginTotal(u.length),d.setPluginDone(u.length);let p=Date.now(),m=await t(Array.isArray(i)?i:[i],a,f).then(t=>e(t,a)).then(e=>n(e)),g=Date.now();f(m.map(e=>({dictionaryKey:e.key,type:`local`,status:`built`})));let _=!!(a.editor.clientId&&a.editor.clientSecret);_&&d.setExpectRemote(!0);let v=[];_&&(v=await r(a,f,{onStartRemoteCheck:()=>d.startRemoteCheck(),onStopRemoteCheck:()=>d.stopRemoteCheck(),onError:e=>d.setRemoteError(e)}).then(t=>e(t,a)).then(e=>n(e)));let y=Date.now();return d.finish(),h(a),{localDictionaries:m,remoteDictionaries:v,pluginDictionaries:u,time:{localDictionaries:g-p,remoteDictionaries:y-g,pluginDictionaries:p-s}}};export{g as loadDictionaries};
1
+ import{filterInvalidDictionaries as e}from"../filterInvalidDictionaries.mjs";import{loadContentDeclarations as t}from"./loadContentDeclaration.mjs";import{formatDictionaries as n}from"../formatDictionary.mjs";import{loadRemoteDictionaries as r}from"./loadRemoteDictionaries.mjs";import{DictionariesLogger as i}from"./log.mjs";import{ANSIColors as a,colon as o,colorize as s,colorizeKey as c,getAppLogger as l}from"@intlayer/config/logger";let u=[];const d=new i,f=e=>{let t=[...u];for(let n of e){let e=t.findIndex(e=>e.dictionaryKey===n.dictionaryKey&&e.type===n.type);e>=0?t[e]=n:t.push(n)}return u=t,d.update(e),t},p=e=>{switch(e){case`built`:case`imported`:case`fetched`:return`✔`;case`error`:return`✖`;default:return`⏲`}},m=e=>{switch(e){case`built`:case`imported`:case`fetched`:return a.GREEN;case`error`:return a.RED;default:return a.BLUE}},h=e=>{if(e.log.mode!==`verbose`)return;let t=l(e),n=new Map;for(let e of u){let t=n.get(e.dictionaryKey)??{};e.type===`local`&&(t.local=e.status),e.type===`remote`&&(t.remote=e.status),n.set(e.dictionaryKey,t)}let r=Array.from(n.keys()).sort((e,t)=>e.localeCompare(t)),i=0;for(let e of r){let t=n.get(e);if(t.local){let e=`[local: ${p(t.local)} ${t.local}]`;e.length>i&&(i=e.length)}}for(let e of r){let l=n.get(e),u=[];if(l.local){let e=s(`${p(l.local)} ${l.local}`,m(l.local)),t=`${a.GREY}[`+s(`local: `,a.GREY)+e+`${a.GREY}]${a.RESET}`,n=`[local: ${p(l.local)} ${l.local}]`,r=Math.max(0,i-n.length);u.push(t+` `.repeat(r))}else u.push(` `.repeat(i));if(l.remote){let e=s(`${p(l.remote)} ${l.remote}`,m(l.remote));u.push(`${a.GREY}[`+s(`distant: `,a.GREY)+e+`${a.GREY}]${a.RESET}`)}t(` - ${o(c(e),{colSize:r})} ${u.join(` `)}`)}},g=async(i,a)=>{let{plugins:o}=a,s=Date.now();l(a)(`Dictionaries:`,{isVerbose:!0});let c=(await Promise.all(o??[])).filter(e=>e.loadDictionaries).map(async e=>{try{return await e.loadDictionaries?.({configuration:a})??[]}catch(e){return d.setPluginError(e),[]}}),u=await Promise.all(c).then(e=>e.flat()).then(t=>e(t,a)).then(e=>n(e));d.setPluginTotal(u.length),d.setPluginDone(u.length);let p=Date.now(),m=await t(Array.isArray(i)?i:[i],a,f).then(t=>e(t,a)).then(e=>n(e)),g=Date.now();f(m.map(e=>({dictionaryKey:e.key,type:`local`,status:`built`})));let _=!!(a.editor.clientId&&a.editor.clientSecret);_&&d.setExpectRemote(!0);let v=[];_&&(v=await r(a,f,{onStartRemoteCheck:()=>d.startRemoteCheck(),onStopRemoteCheck:()=>d.stopRemoteCheck(),onError:e=>d.setRemoteError(e)}).then(t=>e(t,a)).then(e=>n(e)));let y=Date.now();return d.finish(),h(a),{localDictionaries:m,remoteDictionaries:v,pluginDictionaries:u,time:{localDictionaries:g-p,remoteDictionaries:y-g,pluginDictionaries:p-s}}};export{g as loadDictionaries};
2
2
  //# sourceMappingURL=loadDictionaries.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"loadDictionaries.mjs","names":["logger"],"sources":["../../../src/loadDictionaries/loadDictionaries.ts"],"sourcesContent":["import {\n ANSIColors,\n colon,\n colorize,\n colorizeKey,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { filterInvalidDictionaries } from '../filterInvalidDictionaries';\nimport { formatDictionaries } from '../formatDictionary';\nimport { loadContentDeclarations } from './loadContentDeclaration';\nimport { loadRemoteDictionaries } from './loadRemoteDictionaries';\nimport { DictionariesLogger } from './log';\n\nexport type DictionariesStatus = {\n dictionaryKey: string;\n type: 'local' | 'remote';\n status:\n | 'pending' // Key found but not fetched yet\n | 'fetching' // If dictionary fetch is in progress\n | 'fetched' // If dictionary fetch succeeded\n | 'error' // If dictionary fetch failed\n | 'imported' // If dictionary already fetched and still up to date\n | 'found' // If dictionary key is found but promise is not resolved yet (ex: fetching distant content)\n | 'building' // If dictionary is being built\n | 'built'; // If dictionary is built;\n error?: string;\n};\n\nlet loadDictionariesStatus: DictionariesStatus[] = [];\nconst logger = new DictionariesLogger();\n\nconst setLoadDictionariesStatus = (statuses: DictionariesStatus[]) => {\n const updated: DictionariesStatus[] = [...loadDictionariesStatus];\n\n for (const incoming of statuses) {\n const index = updated.findIndex(\n (s) =>\n s.dictionaryKey === incoming.dictionaryKey && s.type === incoming.type\n );\n if (index >= 0) {\n updated[index] = incoming;\n } else {\n updated.push(incoming);\n }\n }\n\n loadDictionariesStatus = updated;\n logger.update(statuses);\n\n return updated;\n};\n\ntype StatusRecord = {\n local?: DictionariesStatus['status'];\n remote?: DictionariesStatus['status'];\n};\n\nconst iconFor = (status: DictionariesStatus['status']) => {\n switch (status) {\n case 'built':\n case 'imported':\n case 'fetched':\n return '✔';\n case 'error':\n return '✖';\n default:\n return '⏲';\n }\n};\n\nconst colorFor = (status: DictionariesStatus['status']) => {\n switch (status) {\n case 'built':\n case 'imported':\n case 'fetched':\n return ANSIColors.GREEN;\n case 'error':\n return ANSIColors.RED;\n default:\n return ANSIColors.BLUE;\n }\n};\n\nconst printSummary = (configuration: IntlayerConfig) => {\n if (configuration.log.mode !== 'verbose') return;\n\n const appLogger = getAppLogger(configuration);\n\n // Aggregate by dictionary key\n const byKey = new Map<string, StatusRecord>();\n for (const status of loadDictionariesStatus) {\n const rec = byKey.get(status.dictionaryKey) ?? {};\n if (status.type === 'local') rec.local = status.status;\n if (status.type === 'remote') rec.remote = status.status;\n byKey.set(status.dictionaryKey, rec);\n }\n\n const keys = Array.from(byKey.keys()).sort((a, b) => a.localeCompare(b));\n\n // Compute the max visible length of the local label to align distant labels\n let maxLocalLabelLen = 0;\n for (const key of keys) {\n const rec = byKey.get(key)!;\n if (rec.local) {\n const visibleLocal = `[local: ${iconFor(rec.local)} ${rec.local}]`;\n if (visibleLocal.length > maxLocalLabelLen) {\n maxLocalLabelLen = visibleLocal.length;\n }\n }\n }\n\n for (const key of keys) {\n const rec = byKey.get(key)!;\n const labels: string[] = [];\n\n if (rec.local) {\n const inner = colorize(\n `${iconFor(rec.local)} ${rec.local}`,\n colorFor(rec.local)\n );\n const coloredLocal =\n `${ANSIColors.GREY}[` +\n colorize('local: ', ANSIColors.GREY) +\n inner +\n `${ANSIColors.GREY}]${ANSIColors.RESET}`;\n\n // Pad to align distant label across rows\n const visibleLocal = `[local: ${iconFor(rec.local)} ${rec.local}]`;\n const pad = Math.max(0, maxLocalLabelLen - visibleLocal.length);\n labels.push(coloredLocal + ' '.repeat(pad));\n } else {\n // If no local label, insert spaces to keep distant aligned\n labels.push(' '.repeat(maxLocalLabelLen));\n }\n\n if (rec.remote) {\n const inner = colorize(\n `${iconFor(rec.remote)} ${rec.remote}`,\n colorFor(rec.remote)\n );\n labels.push(\n `${ANSIColors.GREY}[` +\n colorize('distant: ', ANSIColors.GREY) +\n inner +\n `${ANSIColors.GREY}]${ANSIColors.RESET}`\n );\n }\n\n appLogger(\n ` - ${colon(colorizeKey(key), { colSize: keys })} ${labels.join(' ')}`\n );\n }\n};\n\nexport const loadDictionaries = async (\n contentDeclarationsPaths: string[] | string,\n configuration: IntlayerConfig\n): Promise<{\n localDictionaries: Dictionary[];\n remoteDictionaries: Dictionary[];\n pluginDictionaries: Dictionary[];\n time: {\n localDictionaries: number;\n remoteDictionaries: number;\n pluginDictionaries: number;\n };\n}> => {\n const { plugins } = configuration;\n const loadDictionariesStartTime = Date.now();\n const appLogger = getAppLogger(configuration);\n\n appLogger('Dictionaries:', { isVerbose: true });\n\n // Load additional dictionaries via plugins (e.g., ICU JSON ingestion)\n const pluginsWithLoadDictionaries = (plugins ?? []).filter(\n (plugin) => plugin.loadDictionaries\n );\n\n const loadPluginDictionariesPromise = pluginsWithLoadDictionaries.map(\n async (plugin) => {\n try {\n const res = await plugin.loadDictionaries?.({\n configuration,\n });\n\n return (res as Dictionary[] | undefined) ?? [];\n } catch (error) {\n logger.setPluginError(error as Error);\n\n return [];\n }\n }\n );\n\n const pluginDictionaries: Dictionary[] = await Promise.all(\n loadPluginDictionariesPromise as Promise<Dictionary[]>[]\n )\n .then((dictionaries) => dictionaries.flat())\n .then((dictionaries) =>\n filterInvalidDictionaries(dictionaries, configuration)\n )\n .then((dictionaries) => formatDictionaries(dictionaries));\n\n logger.setPluginTotal(pluginDictionaries.length);\n logger.setPluginDone(pluginDictionaries.length);\n\n const pluginDictionariesTime = Date.now();\n\n const files = Array.isArray(contentDeclarationsPaths)\n ? contentDeclarationsPaths\n : [contentDeclarationsPaths];\n\n const localDictionaries: Dictionary[] = await loadContentDeclarations(\n files,\n configuration,\n setLoadDictionariesStatus\n )\n .then((dictionaries) =>\n filterInvalidDictionaries(dictionaries, configuration)\n )\n .then((dictionaries) => formatDictionaries(dictionaries));\n\n const localDictionariesTime = Date.now();\n\n const localDictionariesStatus = localDictionaries.map(\n (dictionary) =>\n ({\n dictionaryKey: dictionary.key,\n type: 'local',\n status: 'built',\n }) as const\n );\n\n setLoadDictionariesStatus(localDictionariesStatus);\n\n const hasRemoteDictionaries = Boolean(\n configuration.editor.clientId && configuration.editor.clientSecret\n );\n\n if (hasRemoteDictionaries) {\n // We expect to fetch remote dictionaries soon; suppress a transient local-only render\n logger.setExpectRemote(true);\n }\n\n let remoteDictionaries: Dictionary[] = [];\n\n if (hasRemoteDictionaries) {\n remoteDictionaries = await loadRemoteDictionaries(\n configuration,\n setLoadDictionariesStatus,\n {\n onStartRemoteCheck: () => logger.startRemoteCheck(),\n onStopRemoteCheck: () => logger.stopRemoteCheck(),\n onError: (e) => logger.setRemoteError(e),\n }\n )\n .then((dictionaries) =>\n filterInvalidDictionaries(dictionaries, configuration)\n )\n .then((dictionaries) => formatDictionaries(dictionaries));\n }\n\n const remoteDictionariesTime = Date.now();\n\n // Stop spinner and show final progress line(s)\n logger.finish();\n\n printSummary(configuration);\n\n return {\n localDictionaries,\n remoteDictionaries,\n pluginDictionaries,\n time: {\n localDictionaries: localDictionariesTime - pluginDictionariesTime,\n remoteDictionaries: remoteDictionariesTime - localDictionariesTime,\n pluginDictionaries: plugin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,eAAe,EAAe,CAE9B,EAAE,GAGd,CAEK,EAAmC,MAAM,QAAQ,IACrD,EACD,CACE,KAAM,GAAiB,EAAa,MAAM,CAAC,CAC3C,KAAM,GACL,EAA0B,EAAc,EAAc,CACvD,CACA,KAAM,GAAiB,EAAmB,EAAa,CAAC,CAE3D,EAAO,eAAe,EAAmB,OAAO,CAChD,EAAO,cAAc,EAAmB,OAAO,CAE/C,IAAM,EAAyB,KAAK,KAAK,CAMnC,EAAkC,MAAM,EAJhC,MAAM,QAAQ,EAAyB,CACjD,EACA,CAAC,EAAyB,CAI5B,EACA,EACD,CACE,KAAM,GACL,EAA0B,EAAc,EAAc,CACvD,CACA,KAAM,GAAiB,EAAmB,EAAa,CAAC,CAErD,EAAwB,KAAK,KAAK,CAWxC,EATgC,EAAkB,IAC/C,IACE,CACC,cAAe,EAAW,IAC1B,KAAM,QACN,OAAQ,QACT,EACJ,CAEiD,CAElD,IAAM,EAAwB,GAC5B,EAAc,OAAO,UAAY,EAAc,OAAO,cAGpD,GAEF,EAAO,gBAAgB,GAAK,CAG9B,IAAI,EAAmC,EAAE,CAErC,IACF,EAAqB,MAAM,EACzB,EACA,EACA,CACE,uBAA0BA,EAAO,kBAAkB,CACnD,sBAAyBA,EAAO,iBAAiB,CACjD,QAAU,GAAMA,EAAO,eAAe,EAAE,CACzC,CACF,CACE,KAAM,GACL,EAA0B,EAAc,EAAc,CACvD,CACA,KAAM,GAAiB,EAAmB,EAAa,CAAC,EAG7D,IAAM,EAAyB,KAAK,KAAK,CAOzC,OAJA,EAAO,QAAQ,CAEf,EAAa,EAAc,CAEpB,CACL,oBACA,qBACA,qBACA,KAAM,CACJ,kBAAmB,EAAwB,EAC3C,mBAAoB,EAAyB,EAC7C,mBAAoB,EAAyB,EAC9C,CACF"}
1
+ {"version":3,"file":"loadDictionaries.mjs","names":["logger"],"sources":["../../../src/loadDictionaries/loadDictionaries.ts"],"sourcesContent":["import {\n ANSIColors,\n colon,\n colorize,\n colorizeKey,\n getAppLogger,\n} from '@intlayer/config/logger';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { filterInvalidDictionaries } from '../filterInvalidDictionaries';\nimport { formatDictionaries } from '../formatDictionary';\nimport { loadContentDeclarations } from './loadContentDeclaration';\nimport { loadRemoteDictionaries } from './loadRemoteDictionaries';\nimport { DictionariesLogger } from './log';\n\nexport type DictionariesStatus = {\n dictionaryKey: string;\n type: 'local' | 'remote';\n status:\n | 'pending' // Key found but not fetched yet\n | 'fetching' // If dictionary fetch is in progress\n | 'fetched' // If dictionary fetch succeeded\n | 'error' // If dictionary fetch failed\n | 'imported' // If dictionary already fetched and still up to date\n | 'found' // If dictionary key is found but promise is not resolved yet (ex: fetching distant content)\n | 'building' // If dictionary is being built\n | 'built'; // If dictionary is built;\n error?: string;\n};\n\nlet loadDictionariesStatus: DictionariesStatus[] = [];\nconst logger = new DictionariesLogger();\n\nconst setLoadDictionariesStatus = (statuses: DictionariesStatus[]) => {\n const updated: DictionariesStatus[] = [...loadDictionariesStatus];\n\n for (const incoming of statuses) {\n const index = updated.findIndex(\n (s) =>\n s.dictionaryKey === incoming.dictionaryKey && s.type === incoming.type\n );\n if (index >= 0) {\n updated[index] = incoming;\n } else {\n updated.push(incoming);\n }\n }\n\n loadDictionariesStatus = updated;\n logger.update(statuses);\n\n return updated;\n};\n\ntype StatusRecord = {\n local?: DictionariesStatus['status'];\n remote?: DictionariesStatus['status'];\n};\n\nconst iconFor = (status: DictionariesStatus['status']) => {\n switch (status) {\n case 'built':\n case 'imported':\n case 'fetched':\n return '✔';\n case 'error':\n return '✖';\n default:\n return '⏲';\n }\n};\n\nconst colorFor = (status: DictionariesStatus['status']) => {\n switch (status) {\n case 'built':\n case 'imported':\n case 'fetched':\n return ANSIColors.GREEN;\n case 'error':\n return ANSIColors.RED;\n default:\n return ANSIColors.BLUE;\n }\n};\n\nconst printSummary = (configuration: IntlayerConfig) => {\n if (configuration.log.mode !== 'verbose') return;\n\n const appLogger = getAppLogger(configuration);\n\n // Aggregate by dictionary key\n const byKey = new Map<string, StatusRecord>();\n for (const status of loadDictionariesStatus) {\n const rec = byKey.get(status.dictionaryKey) ?? {};\n if (status.type === 'local') rec.local = status.status;\n if (status.type === 'remote') rec.remote = status.status;\n byKey.set(status.dictionaryKey, rec);\n }\n\n const keys = Array.from(byKey.keys()).sort((a, b) => a.localeCompare(b));\n\n // Compute the max visible length of the local label to align distant labels\n let maxLocalLabelLen = 0;\n for (const key of keys) {\n const rec = byKey.get(key)!;\n if (rec.local) {\n const visibleLocal = `[local: ${iconFor(rec.local)} ${rec.local}]`;\n if (visibleLocal.length > maxLocalLabelLen) {\n maxLocalLabelLen = visibleLocal.length;\n }\n }\n }\n\n for (const key of keys) {\n const rec = byKey.get(key)!;\n const labels: string[] = [];\n\n if (rec.local) {\n const inner = colorize(\n `${iconFor(rec.local)} ${rec.local}`,\n colorFor(rec.local)\n );\n const coloredLocal =\n `${ANSIColors.GREY}[` +\n colorize('local: ', ANSIColors.GREY) +\n inner +\n `${ANSIColors.GREY}]${ANSIColors.RESET}`;\n\n // Pad to align distant label across rows\n const visibleLocal = `[local: ${iconFor(rec.local)} ${rec.local}]`;\n const pad = Math.max(0, maxLocalLabelLen - visibleLocal.length);\n labels.push(coloredLocal + ' '.repeat(pad));\n } else {\n // If no local label, insert spaces to keep distant aligned\n labels.push(' '.repeat(maxLocalLabelLen));\n }\n\n if (rec.remote) {\n const inner = colorize(\n `${iconFor(rec.remote)} ${rec.remote}`,\n colorFor(rec.remote)\n );\n labels.push(\n `${ANSIColors.GREY}[` +\n colorize('distant: ', ANSIColors.GREY) +\n inner +\n `${ANSIColors.GREY}]${ANSIColors.RESET}`\n );\n }\n\n appLogger(\n ` - ${colon(colorizeKey(key), { colSize: keys })} ${labels.join(' ')}`\n );\n }\n};\n\nexport const loadDictionaries = async (\n contentDeclarationsPaths: string[] | string,\n configuration: IntlayerConfig\n): Promise<{\n localDictionaries: Dictionary[];\n remoteDictionaries: Dictionary[];\n pluginDictionaries: Dictionary[];\n time: {\n localDictionaries: number;\n remoteDictionaries: number;\n pluginDictionaries: number;\n };\n}> => {\n const { plugins } = configuration;\n const loadDictionariesStartTime = Date.now();\n const appLogger = getAppLogger(configuration);\n\n appLogger('Dictionaries:', { isVerbose: true });\n\n // Load additional dictionaries via plugins (e.g., ICU JSON ingestion)\n const resolvedPlugins = await Promise.all(plugins ?? []);\n\n const pluginsWithLoadDictionaries = resolvedPlugins.filter(\n (plugin) => plugin.loadDictionaries\n );\n\n const loadPluginDictionariesPromise = pluginsWithLoadDictionaries.map(\n async (plugin) => {\n try {\n const res = await plugin.loadDictionaries?.({\n configuration,\n });\n\n return (res as Dictionary[] | undefined) ?? [];\n } catch (error) {\n logger.setPluginError(error as Error);\n\n return [];\n }\n }\n );\n\n const pluginDictionaries: Dictionary[] = await Promise.all(\n loadPluginDictionariesPromise as Promise<Dictionary[]>[]\n )\n .then((dictionaries) => dictionaries.flat())\n .then((dictionaries) =>\n filterInvalidDictionaries(dictionaries, configuration)\n )\n .then((dictionaries) => formatDictionaries(dictionaries));\n\n logger.setPluginTotal(pluginDictionaries.length);\n logger.setPluginDone(pluginDictionaries.length);\n\n const pluginDictionariesTime = Date.now();\n\n const files = Array.isArray(contentDeclarationsPaths)\n ? contentDeclarationsPaths\n : [contentDeclarationsPaths];\n\n const localDictionaries: Dictionary[] = await loadContentDeclarations(\n files,\n configuration,\n setLoadDictionariesStatus\n )\n .then((dictionaries) =>\n filterInvalidDictionaries(dictionaries, configuration)\n )\n .then((dictionaries) => formatDictionaries(dictionaries));\n\n const localDictionariesTime = Date.now();\n\n const localDictionariesStatus = localDictionaries.map(\n (dictionary) =>\n ({\n dictionaryKey: dictionary.key,\n type: 'local',\n status: 'built',\n }) as const\n );\n\n setLoadDictionariesStatus(localDictionariesStatus);\n\n const hasRemoteDictionaries = Boolean(\n configuration.editor.clientId && configuration.editor.clientSecret\n );\n\n if (hasRemoteDictionaries) {\n // We expect to fetch remote dictionaries soon; suppress a transient local-only render\n logger.setExpectRemote(true);\n }\n\n let remoteDictionaries: Dictionary[] = [];\n\n if (hasRemoteDictionaries) {\n remoteDictionaries = await loadRemoteDictionaries(\n configuration,\n setLoadDictionariesStatus,\n {\n onStartRemoteCheck: () => logger.startRemoteCheck(),\n onStopRemoteCheck: () => logger.stopRemoteCheck(),\n onError: (e) => logger.setRemoteError(e),\n }\n )\n .then((dictionaries) =>\n filterInvalidDictionaries(dictionaries, configuration)\n )\n .then((dictionaries) => formatDictionaries(dictionaries));\n }\n\n const remoteDictionariesTime = Date.now();\n\n // Stop spinner and show final progress line(s)\n logger.finish();\n\n printSummary(configuration);\n\n return {\n localDictionaries,\n remoteDictionaries,\n pluginDictionaries,\n time: {\n localDictionaries: localDictionariesTime - pluginDictionariesTime,\n remoteDictionaries: remoteDictionariesTime - localDictionariesTime,\n pluginDictionaries: pluginDictionariesTime - loadDictionariesStartTime,\n },\n };\n};\n"],"mappings":"ubA8BA,IAAI,EAA+C,EAAE,CACrD,MAAMA,EAAS,IAAI,EAEb,EAA6B,GAAmC,CACpE,IAAM,EAAgC,CAAC,GAAG,EAAuB,CAEjE,IAAK,IAAM,KAAY,EAAU,CAC/B,IAAM,EAAQ,EAAQ,UACnB,GACC,EAAE,gBAAkB,EAAS,eAAiB,EAAE,OAAS,EAAS,KACrE,CACG,GAAS,EACX,EAAQ,GAAS,EAEjB,EAAQ,KAAK,EAAS,CAO1B,MAHA,GAAyB,EACzB,EAAO,OAAO,EAAS,CAEhB,GAQH,EAAW,GAAyC,CACxD,OAAQ,EAAR,CACE,IAAK,QACL,IAAK,WACL,IAAK,UACH,MAAO,IACT,IAAK,QACH,MAAO,IACT,QACE,MAAO,MAIP,EAAY,GAAyC,CACzD,OAAQ,EAAR,CACE,IAAK,QACL,IAAK,WACL,IAAK,UACH,OAAO,EAAW,MACpB,IAAK,QACH,OAAO,EAAW,IACpB,QACE,OAAO,EAAW,OAIlB,EAAgB,GAAkC,CACt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AgB,GAAK,CAG9B,IAAI,EAAmC,EAAE,CAErC,IACF,EAAqB,MAAM,EACzB,EACA,EACA,CACE,uBAA0BA,EAAO,kBAAkB,CACnD,sBAAyBA,EAAO,iBAAiB,CACjD,QAAU,GAAMA,EAAO,eAAe,EAAE,CACzC,CACF,CACE,KAAM,GACL,EAA0B,EAAc,EAAc,CACvD,CACA,KAAM,GAAiB,EAAmB,EAAa,CAAC,EAG7D,IAAM,EAAyB,KAAK,KAAK,CAOzC,OAJA,EAAO,QAAQ,CAEf,EAAa,EAAc,CAEpB,CACL,oBACA,qBACA,qBACA,KAAM,CACJ,kBAAmB,EAAwB,EAC3C,mBAAoB,EAAyB,EAC7C,mBAAoB,EAAyB,EAC9C,CACF"}
@@ -1,2 +1,2 @@
1
- import{loadContentDeclarations as e}from"./loadContentDeclaration.mjs";import{mkdir as t}from"node:fs/promises";import{relative as n,resolve as r}from"node:path";const i=async(i,a)=>{let{content:o,system:s}=a,{baseDir:c}=o,{dictionariesDir:l}=s;typeof i==`string`&&(i=[i]),await t(r(l),{recursive:!0});let u=[];for await(let t of i){let r=await e([t],a),i=n(c,t),o={...r[0],filePath:i};u.push(o)}return u};export{i as loadLocalDictionaries};
1
+ import{loadContentDeclarations as e}from"./loadContentDeclaration.mjs";import{mkdir as t}from"node:fs/promises";import{relative as n,resolve as r}from"node:path";const i=async(i,a)=>{let{system:o}=a,{dictionariesDir:s,baseDir:c}=o;typeof i==`string`&&(i=[i]),await t(r(s),{recursive:!0});let l=[];for await(let t of i){let r=await e([t],a),i=n(c,t),o={...r[0],filePath:i};l.push(o)}return l};export{i as loadLocalDictionaries};
2
2
  //# sourceMappingURL=loadLocalDictionaries.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"loadLocalDictionaries.mjs","names":[],"sources":["../../../src/loadDictionaries/loadLocalDictionaries.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport { relative, resolve } from 'node:path';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { loadContentDeclarations } from './loadContentDeclaration';\n\nexport const loadLocalDictionaries = async (\n contentDeclarationsPaths: string[] | string,\n configuration: IntlayerConfig\n): Promise<Dictionary[]> => {\n const { content, system } = configuration;\n const { baseDir } = content;\n const { dictionariesDir } = system;\n\n if (typeof contentDeclarationsPaths === 'string') {\n contentDeclarationsPaths = [contentDeclarationsPaths];\n }\n\n // Create the dictionaries folder if it doesn't exist\n await mkdir(resolve(dictionariesDir), { recursive: true });\n\n const result: Dictionary[] = [];\n\n for await (const contentDeclarationPath of contentDeclarationsPaths) {\n const dictionary = await loadContentDeclarations(\n [contentDeclarationPath],\n configuration\n );\n\n const relativeFilePath = relative(baseDir, contentDeclarationPath);\n\n const dictionaryWithPath: Dictionary = {\n ...dictionary[0],\n filePath: relativeFilePath,\n };\n\n result.push(dictionaryWithPath);\n }\n\n return result;\n};\n"],"mappings":"kKAMA,MAAa,EAAwB,MACnC,EACA,IAC0B,CAC1B,GAAM,CAAE,UAAS,UAAW,EACtB,CAAE,WAAY,EACd,CAAE,mBAAoB,EAExB,OAAO,GAA6B,WACtC,EAA2B,CAAC,EAAyB,EAIvD,MAAM,EAAM,EAAQ,EAAgB,CAAE,CAAE,UAAW,GAAM,CAAC,CAE1D,IAAM,EAAuB,EAAE,CAE/B,UAAW,IAAM,KAA0B,EAA0B,CACnE,IAAM,EAAa,MAAM,EACvB,CAAC,EAAuB,CACxB,EACD,CAEK,EAAmB,EAAS,EAAS,EAAuB,CAE5D,EAAiC,CACrC,GAAG,EAAW,GACd,SAAU,EACX,CAED,EAAO,KAAK,EAAmB,CAGjC,OAAO"}
1
+ {"version":3,"file":"loadLocalDictionaries.mjs","names":[],"sources":["../../../src/loadDictionaries/loadLocalDictionaries.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport { relative, resolve } from 'node:path';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport { loadContentDeclarations } from './loadContentDeclaration';\n\nexport const loadLocalDictionaries = async (\n contentDeclarationsPaths: string[] | string,\n configuration: IntlayerConfig\n): Promise<Dictionary[]> => {\n const { system } = configuration;\n const { dictionariesDir, baseDir } = system;\n\n if (typeof contentDeclarationsPaths === 'string') {\n contentDeclarationsPaths = [contentDeclarationsPaths];\n }\n\n // Create the dictionaries folder if it doesn't exist\n await mkdir(resolve(dictionariesDir), { recursive: true });\n\n const result: Dictionary[] = [];\n\n for await (const contentDeclarationPath of contentDeclarationsPaths) {\n const dictionary = await loadContentDeclarations(\n [contentDeclarationPath],\n configuration\n );\n\n const relativeFilePath = relative(baseDir, contentDeclarationPath);\n\n const dictionaryWithPath: Dictionary = {\n ...dictionary[0],\n filePath: relativeFilePath,\n };\n\n result.push(dictionaryWithPath);\n }\n\n return result;\n};\n"],"mappings":"kKAMA,MAAa,EAAwB,MACnC,EACA,IAC0B,CAC1B,GAAM,CAAE,UAAW,EACb,CAAE,kBAAiB,WAAY,EAEjC,OAAO,GAA6B,WACtC,EAA2B,CAAC,EAAyB,EAIvD,MAAM,EAAM,EAAQ,EAAgB,CAAE,CAAE,UAAW,GAAM,CAAC,CAE1D,IAAM,EAAuB,EAAE,CAE/B,UAAW,IAAM,KAA0B,EAA0B,CACnE,IAAM,EAAa,MAAM,EACvB,CAAC,EAAuB,CACxB,EACD,CAEK,EAAmB,EAAS,EAAS,EAAuB,CAE5D,EAAiC,CACrC,GAAG,EAAW,GACd,SAAU,EACX,CAED,EAAO,KAAK,EAAmB,CAGjC,OAAO"}
@@ -1,3 +1,3 @@
1
- import{dirname as e,extname as t}from"node:path";import{getAppLogger as n}from"@intlayer/config/logger";const r=async(r,i)=>{let a=n(i),o=r.filter(e=>{let n=t(e);return[`.ts`,`.tsx`,`.js`,`.jsx`,`.cjs`,`.mjs`,`.json`].includes(n)});if(o.length===0)return;let s;try{s=(await import(`typescript`)).default||await import(`typescript`)}catch{return}let c=s.findConfigFile(i.content?.baseDir??process.cwd(),s.sys.fileExists,`tsconfig.json`),l={noEmit:!0,allowJs:!0,resolveJsonModule:!0};if(c){let t=s.sys.readFile(c);if(t){let n=s.parseConfigFileTextToJson(c,t);if(!n.error){let{incremental:t,tsBuildInfoFile:r,...i}=s.parseJsonConfigFileContent(n.config,s.sys,e(c)).options;l={...l,...i,noEmit:!0}}}}let u=s.createProgram(o,l);o.forEach(e=>{let t=u.getSourceFile(e);t&&s.getPreEmitDiagnostics(u,t).forEach(e=>{let t=s.flattenDiagnosticMessageText(e.messageText,`
1
+ import{dirname as e,extname as t}from"node:path";import{getAppLogger as n}from"@intlayer/config/logger";const r=async(r,i)=>{let a=n(i),o=r.filter(e=>{let n=t(e);return[`.ts`,`.tsx`,`.js`,`.jsx`,`.cjs`,`.mjs`,`.json`].includes(n)});if(o.length===0)return;let s;try{s=(await import(`typescript`)).default||await import(`typescript`)}catch{return}let c=s.findConfigFile(i.system?.baseDir??process.cwd(),s.sys.fileExists,`tsconfig.json`),l={noEmit:!0,allowJs:!0,resolveJsonModule:!0};if(c){let t=s.sys.readFile(c);if(t){let n=s.parseConfigFileTextToJson(c,t);if(!n.error){let{incremental:t,tsBuildInfoFile:r,...i}=s.parseJsonConfigFileContent(n.config,s.sys,e(c)).options;l={...l,...i,noEmit:!0}}}}let u=s.createProgram(o,l);o.forEach(e=>{let t=u.getSourceFile(e);t&&s.getPreEmitDiagnostics(u,t).forEach(e=>{let t=s.flattenDiagnosticMessageText(e.messageText,`
2
2
  `);if(e.file&&e.start!==void 0){let{line:n,character:r}=e.file.getLineAndCharacterOfPosition(e.start);a(`TS Error in ${e.file.fileName} (${n+1},${r+1}): ${t}`,{level:`warn`})}})})};export{r as logTypeScriptErrors};
3
3
  //# sourceMappingURL=logTypeScriptErrors.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"logTypeScriptErrors.mjs","names":[],"sources":["../../../src/loadDictionaries/logTypeScriptErrors.ts"],"sourcesContent":["import { dirname, extname } from 'node:path';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport type { IntlayerConfig } from '@intlayer/types/config';\n\nexport const logTypeScriptErrors = async (\n filePaths: string[],\n configuration: IntlayerConfig\n) => {\n const appLogger = getAppLogger(configuration);\n\n const filesToCheck = filePaths.filter((path) => {\n const ext = extname(path);\n\n return ['.ts', '.tsx', '.js', '.jsx', '.cjs', '.mjs', '.json'].includes(\n ext\n );\n });\n\n if (filesToCheck.length === 0) return;\n\n let ts: typeof import('typescript');\n\n try {\n ts = (await import('typescript')).default || (await import('typescript'));\n } catch {\n // TypeScript not installed, skip type checking\n\n return;\n }\n\n const configFileName = ts.findConfigFile(\n configuration.content?.baseDir ?? process.cwd(),\n ts.sys.fileExists,\n 'tsconfig.json'\n );\n\n let compilerOptions: any = {\n noEmit: true,\n\n allowJs: true,\n\n resolveJsonModule: true,\n };\n\n if (configFileName) {\n const configFileText = ts.sys.readFile(configFileName);\n\n if (configFileText) {\n const configJson = ts.parseConfigFileTextToJson(\n configFileName,\n\n configFileText\n );\n\n if (!configJson.error) {\n const parsedConfig = ts.parseJsonConfigFileContent(\n configJson.config,\n\n ts.sys,\n\n dirname(configFileName)\n );\n\n const { incremental, tsBuildInfoFile, ...restOptions } =\n parsedConfig.options;\n\n compilerOptions = { ...compilerOptions, ...restOptions, noEmit: true };\n }\n }\n }\n\n const program = ts.createProgram(filesToCheck, compilerOptions);\n\n filesToCheck.forEach((filePath) => {\n const sourceFile = program.getSourceFile(filePath);\n\n if (!sourceFile) return;\n\n const diagnostics = ts.getPreEmitDiagnostics(program, sourceFile);\n\n diagnostics.forEach((diagnostic) => {\n const message = ts.flattenDiagnosticMessageText(\n diagnostic.messageText,\n\n '\\n'\n );\n\n if (diagnostic.file && diagnostic.start !== undefined) {\n const { line, character } =\n diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);\n\n appLogger(\n `TS Error in ${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`,\n\n { level: 'warn' }\n );\n }\n });\n });\n};\n"],"mappings":"wGAIA,MA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H,EACF"}
1
+ {"version":3,"file":"logTypeScriptErrors.mjs","names":[],"sources":["../../../src/loadDictionaries/logTypeScriptErrors.ts"],"sourcesContent":["import { dirname, extname } from 'node:path';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport type { IntlayerConfig } from '@intlayer/types/config';\n\nexport const logTypeScriptErrors = async (\n filePaths: string[],\n configuration: IntlayerConfig\n) => {\n const appLogger = getAppLogger(configuration);\n\n const filesToCheck = filePaths.filter((path) => {\n const ext = extname(path);\n\n return ['.ts', '.tsx', '.js', '.jsx', '.cjs', '.mjs', '.json'].includes(\n ext\n );\n });\n\n if (filesToCheck.length === 0) return;\n\n let ts: typeof import('typescript');\n\n try {\n ts = (await import('typescript')).default || (await import('typescript'));\n } catch {\n // TypeScript not installed, skip type checking\n\n return;\n }\n\n const configFileName = ts.findConfigFile(\n configuration.system?.baseDir ?? process.cwd(),\n ts.sys.fileExists,\n 'tsconfig.json'\n );\n\n let compilerOptions: any = {\n noEmit: true,\n\n allowJs: true,\n\n resolveJsonModule: true,\n };\n\n if (configFileName) {\n const configFileText = ts.sys.readFile(configFileName);\n\n if (configFileText) {\n const configJson = ts.parseConfigFileTextToJson(\n configFileName,\n\n configFileText\n );\n\n if (!configJson.error) {\n const parsedConfig = ts.parseJsonConfigFileContent(\n configJson.config,\n\n ts.sys,\n\n dirname(configFileName)\n );\n\n const { incremental, tsBuildInfoFile, ...restOptions } =\n parsedConfig.options;\n\n compilerOptions = { ...compilerOptions, ...restOptions, noEmit: true };\n }\n }\n }\n\n const program = ts.createProgram(filesToCheck, compilerOptions);\n\n filesToCheck.forEach((filePath) => {\n const sourceFile = program.getSourceFile(filePath);\n\n if (!sourceFile) return;\n\n const diagnostics = ts.getPreEmitDiagnostics(program, sourceFile);\n\n diagnostics.forEach((diagnostic) => {\n const message = ts.flattenDiagnosticMessageText(\n diagnostic.messageText,\n\n '\\n'\n );\n\n if (diagnostic.file && diagnostic.start !== undefined) {\n const { line, character } =\n diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);\n\n appLogger(\n `TS Error in ${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`,\n\n { level: 'warn' }\n );\n }\n });\n });\n};\n"],"mappings":"wGAIA,MAAa,EAAsB,MACjC,EACA,IACG,CACH,IAAM,EAAY,EAAa,EAAc,CAEvC,EAAe,EAAU,OAAQ,GAAS,CAC9C,IAAM,EAAM,EAAQ,EAAK,CAEzB,MAAO,CAAC,MAAO,OAAQ,MAAO,OAAQ,OAAQ,OAAQ,QAAQ,CAAC,SAC7D,EACD,EACD,CAEF,GAAI,EAAa,SAAW,EAAG,OAE/B,IAAI,EAEJ,GAAI,CACF,GAAM,MAAM,OAAO,eAAe,SAAY,MAAM,OAAO,mBACrD,CAGN,OAGF,IAAM,EAAiB,EAAG,eACxB,EAAc,QAAQ,SAAW,QAAQ,KAAK,CAC9C,EAAG,IAAI,WACP,gBACD,CAEG,EAAuB,CACzB,OAAQ,GAER,QAAS,GAET,kBAAmB,GACpB,CAED,GAAI,EAAgB,CAClB,IAAM,EAAiB,EAAG,IAAI,SAAS,EAAe,CAEtD,GAAI,EAAgB,CAClB,IAAM,EAAa,EAAG,0BACpB,EAEA,EACD,CAED,GAAI,CAAC,EAAW,MAAO,CASrB,GAAM,CAAE,cAAa,kBAAiB,GAAG,GARpB,EAAG,2BACtB,EAAW,OAEX,EAAG,IAEH,EAAQ,EAAe,CACxB,CAGc,QAEf,EAAkB,CAAE,GAAG,EAAiB,GAAG,EAAa,OAAQ,GAAM,GAK5E,IAAM,EAAU,EAAG,cAAc,EAAc,EAAgB,CAE/D,EAAa,QAAS,GAAa,CACjC,IAAM,EAAa,EAAQ,cAAc,EAAS,CAE7C,GAEe,EAAG,sBAAsB,EAAS,EAAW,CAErD,QAAS,GAAe,CAClC,IAAM,EAAU,EAAG,6BACjB,EAAW,YAEX;EACD,CAED,GAAI,EAAW,MAAQ,EAAW,QAAU,IAAA,GAAW,CACrD,GAAM,CAAE,OAAM,aACZ,EAAW,KAAK,8BAA8B,EAAW,MAAM,CAEjE,EACE,eAAe,EAAW,KAAK,SAAS,IAAI,EAAO,EAAE,GAAG,EAAY,EAAE,KAAK,IAE3E,CAAE,MAAO,OAAQ,CAClB,GAEH,EACF"}
@@ -1,2 +1,2 @@
1
- import{createDictionaryEntryPoint as e}from"./createDictionaryEntryPoint/createDictionaryEntryPoint.mjs";import{buildDictionary as t}from"./buildIntlayerDictionary/buildIntlayerDictionary.mjs";import{runOnce as n}from"./utils/runOnce.mjs";import{createModuleAugmentation as r}from"./createType/createModuleAugmentation.mjs";import{createTypes as i}from"./createType/createType.mjs";import{listDictionariesWithStats as a}from"./listDictionariesPath.mjs";import{loadDictionaries as o}from"./loadDictionaries/loadDictionaries.mjs";import{writeRemoteDictionary as s}from"./buildIntlayerDictionary/writeRemoteDictionary.mjs";import{cleanOutputDir as c}from"./cleanOutputDir.mjs";import{isCachedConfigurationUpToDate as l,writeConfiguration as u}from"./writeConfiguration/index.mjs";import{stat as d}from"node:fs/promises";import{join as f}from"node:path";import{ANSIColors as p,colorize as m,getAppLogger as h}from"@intlayer/config/logger";import{cacheDisk as g}from"@intlayer/config/utils";import _ from"@intlayer/config/package.json"with{type:"json"};const v={clean:!1,format:[`cjs`,`esm`],cacheTimeoutMs:1e3*60*60},y=async(y,b)=>{let x=h(y),S=f(y.system.cacheDir,`intlayer-prepared.lock`),C=g(y,[`intlayer-version`]),w=await C.get(),T=!!(w&&w===_.version),E=await l(y),D=await a(y),O=!1;try{let e=await d(S);O=D.some(t=>t.stats.mtime.getTime()>e.mtime.getTime())}catch{}let k=y.plugins?.some(e=>!!e.loadDictionaries),{clean:A,format:j,forceRun:M,onIsCached:N,cacheTimeoutMs:P}={...v,forceRun:!T||!E||O||k,...b??{}};await n(S,async()=>{(A||!T)&&await c(y),await C.set(_.version);let n=Date.now();x([`Preparing Intlayer`,m(`(v${_.version})`,p.GREY_DARK)]),await u(y);let a=Date.now();x([`Configuration written`,m(`(${a-n}ms)`,p.GREY_DARK)],{isVerbose:!0});let l=await o(D.map(e=>e.path),y),d=Date.now();x([`Content loaded`,m([l.remoteDictionaries.length+l.pluginDictionaries.length>0?[`(Total: ${d-a}ms`,l.localDictionaries.length>0?` - Local: ${l.time.localDictionaries}ms`:``,l.remoteDictionaries.length>0?` - Remote: ${l.time.remoteDictionaries}ms`:``,l.pluginDictionaries.length>0?` - Plugin: ${l.time.pluginDictionaries}ms`:``,`)`].join(``):`(${d-a}ms)`].join(``),p.GREY_DARK)],{isVerbose:!0});let f=await t([...l.localDictionaries,...l.remoteDictionaries,...l.pluginDictionaries],y,j,!1);await s(l.remoteDictionaries,y),await i(Object.values(f?.mergedDictionaries??{}).map(e=>e.dictionary),y),await e(y);let h=Date.now();x([`Dictionaries built`,m(`(${h-n}ms)`,p.GREY_DARK)]),await r(y),x([`Module augmentation built`,m(`(${Date.now()-h}ms)`,p.GREY_DARK)],{isVerbose:!0});for await(let e of y.plugins??[]){let{unmergedDictionaries:t,mergedDictionaries:n}=f;await e.afterBuild?.({dictionaries:{unmergedDictionaries:t,mergedDictionaries:n},configuration:y})}x([`Done`,m(`${Date.now()-n}ms`,p.GREEN)],{level:`info`,isVerbose:!0})},{forceRun:M,onIsCached:N,cacheTimeoutMs:P})};export{y as prepareIntlayer};
1
+ import{createDictionaryEntryPoint as e}from"./createDictionaryEntryPoint/createDictionaryEntryPoint.mjs";import{buildDictionary as t}from"./buildIntlayerDictionary/buildIntlayerDictionary.mjs";import{runOnce as n}from"./utils/runOnce.mjs";import{createModuleAugmentation as r}from"./createType/createModuleAugmentation.mjs";import{createTypes as i}from"./createType/createType.mjs";import{listDictionariesWithStats as a}from"./listDictionariesPath.mjs";import{loadDictionaries as o}from"./loadDictionaries/loadDictionaries.mjs";import{writeRemoteDictionary as s}from"./buildIntlayerDictionary/writeRemoteDictionary.mjs";import{cleanOutputDir as c}from"./cleanOutputDir.mjs";import{isCachedConfigurationUpToDate as l,writeConfiguration as u}from"./writeConfiguration/index.mjs";import{stat as d}from"node:fs/promises";import{join as f}from"node:path";import{ANSIColors as p,colorize as m,getAppLogger as h}from"@intlayer/config/logger";import{cacheDisk as g}from"@intlayer/config/utils";import _ from"@intlayer/config/package.json"with{type:"json"};const v={clean:!1,format:[`cjs`,`esm`],cacheTimeoutMs:1e3*60*60},y=async(y,b)=>{let x=h(y),S=f(y.system.cacheDir,`intlayer-prepared.lock`),C=g(y,[`intlayer-version`]),w=await C.get(),T=!!(w&&w===_.version),E=await l(y),D=await a(y),O=!1;try{let e=await d(S);O=D.some(t=>t.stats.mtime.getTime()>e.mtime.getTime())}catch{}let k=(await Promise.all(y.plugins??[])).some(e=>!!e.loadDictionaries),{clean:A,format:j,forceRun:M,onIsCached:N,cacheTimeoutMs:P}={...v,forceRun:!T||!E||O||k,...b??{}};await n(S,async()=>{(A||!T)&&await c(y),await C.set(_.version);let n=Date.now();x([`Preparing Intlayer`,m(`(v${_.version})`,p.GREY_DARK)]),await u(y);let a=Date.now();x([`Configuration written`,m(`(${a-n}ms)`,p.GREY_DARK)],{isVerbose:!0});let l=await o(D.map(e=>e.path),y),d=Date.now();x([`Content loaded`,m([l.remoteDictionaries.length+l.pluginDictionaries.length>0?[`(Total: ${d-a}ms`,l.localDictionaries.length>0?` - Local: ${l.time.localDictionaries}ms`:``,l.remoteDictionaries.length>0?` - Remote: ${l.time.remoteDictionaries}ms`:``,l.pluginDictionaries.length>0?` - Plugin: ${l.time.pluginDictionaries}ms`:``,`)`].join(``):`(${d-a}ms)`].join(``),p.GREY_DARK)],{isVerbose:!0});let f=await t([...l.localDictionaries,...l.remoteDictionaries,...l.pluginDictionaries],y,j,!1);await s(l.remoteDictionaries,y),await i(Object.values(f?.mergedDictionaries??{}).map(e=>e.dictionary),y),await e(y);let h=Date.now();x([`Dictionaries built`,m(`(${h-n}ms)`,p.GREY_DARK)]),await r(y),x([`Module augmentation built`,m(`(${Date.now()-h}ms)`,p.GREY_DARK)],{isVerbose:!0});for await(let e of y.plugins??[]){let{unmergedDictionaries:t,mergedDictionaries:n}=f;await e.afterBuild?.({dictionaries:{unmergedDictionaries:t,mergedDictionaries:n},configuration:y})}x([`Done`,m(`${Date.now()-n}ms`,p.GREEN)],{level:`info`,isVerbose:!0})},{forceRun:M,onIsCached:N,cacheTimeoutMs:P})};export{y as prepareIntlayer};
2
2
  //# sourceMappingURL=prepareIntlayer.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"prepareIntlayer.mjs","names":[],"sources":["../../src/prepareIntlayer.ts"],"sourcesContent":["import { stat } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { ANSIColors, colorize, getAppLogger } from '@intlayer/config/logger';\nimport packageJson from '@intlayer/config/package.json' with { type: 'json' };\nimport { cacheDisk } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { buildDictionary } from './buildIntlayerDictionary/buildIntlayerDictionary';\nimport { writeRemoteDictionary } from './buildIntlayerDictionary/writeRemoteDictionary';\nimport { cleanOutputDir } from './cleanOutputDir';\nimport { createDictionaryEntryPoint } from './createDictionaryEntryPoint/createDictionaryEntryPoint';\nimport { createModuleAugmentation, createTypes } from './createType/index';\nimport { listDictionariesWithStats } from './listDictionariesPath';\nimport { loadDictionaries } from './loadDictionaries/loadDictionaries';\nimport { runOnce } from './utils/runOnce';\nimport {\n isCachedConfigurationUpToDate,\n writeConfiguration,\n} from './writeConfiguration';\n\ntype PrepareIntlayerOptions = {\n clean?: boolean;\n format?: ('cjs' | 'esm')[];\n forceRun?: boolean;\n cacheTimeoutMs?: number;\n onIsCached?: () => void | Promise<void>;\n};\n\nconst DEFAULT_PREPARE_INTLAYER_OPTIONS = {\n clean: false,\n format: ['cjs', 'esm'],\n cacheTimeoutMs: 1000 * 60 * 60, // 1 hour\n} satisfies PrepareIntlayerOptions;\n\nexport const prepareIntlayer = async (\n configuration: IntlayerConfig,\n options?: PrepareIntlayerOptions\n) => {\n const appLogger = getAppLogger(configuration);\n\n const sentinelPath = join(\n configuration.system.cacheDir,\n 'intlayer-prepared.lock'\n );\n // Clean output dir if the intlayer version has changed\n const versionCache = cacheDisk(configuration, ['intlayer-version']);\n const intlayerCacheVersion = await versionCache.get();\n const isCorrectVersion = Boolean(\n intlayerCacheVersion && intlayerCacheVersion === packageJson.version\n );\n\n const isConfigSimilar = await isCachedConfigurationUpToDate(configuration);\n\n // Check if any dictionary has been changed to force a new rebuild\n const dictionariesWithStats = await listDictionariesWithStats(configuration);\n let isDictionaryChanged = false;\n try {\n // Try catch as sentinel file may not exist yet\n const sentinelStats = await stat(sentinelPath);\n isDictionaryChanged = dictionariesWithStats.some(\n (dictionary) =>\n dictionary.stats.mtime.getTime() > sentinelStats.mtime.getTime()\n );\n } catch {}\n\n const hasPluginLoadDictionaries = configuration.plugins?.some((plugin) =>\n Boolean(plugin.loadDictionaries)\n ); // Disable cache if any plugin because it can have custom behavior\n\n const { clean, format, forceRun, onIsCached, cacheTimeoutMs } = {\n ...DEFAULT_PREPARE_INTLAYER_OPTIONS,\n forceRun:\n !isCorrectVersion ||\n !isConfigSimilar ||\n isDictionaryChanged ||\n hasPluginLoadDictionaries,\n ...(options ?? {}),\n };\n\n // Skip preparation if it has already been done recently\n await runOnce(\n sentinelPath,\n async () => {\n // comment because of issue with next and webpack\n // await checkVersionsConsistency(configuration);\n\n if (clean || !isCorrectVersion) {\n await cleanOutputDir(configuration);\n }\n\n await versionCache.set(packageJson.version);\n\n const preparationStartMs = Date.now();\n\n appLogger([\n 'Preparing Intlayer',\n colorize(`(v${packageJson.version})`, ANSIColors.GREY_DARK),\n ]);\n\n await writeConfiguration(configuration);\n\n const configurationWrittenTime = Date.now();\n\n appLogger(\n [\n 'Configuration written',\n colorize(\n `(${configurationWrittenTime - preparationStartMs}ms)`,\n ANSIColors.GREY_DARK\n ),\n ],\n {\n isVerbose: true,\n }\n );\n\n const contentDeclarationPaths = dictionariesWithStats.map(\n (dictionary) => dictionary.path\n );\n\n const dictionaries = await loadDictionaries(\n contentDeclarationPaths,\n configuration\n );\n\n const dictionariesLoadedTime = Date.now();\n\n appLogger(\n [\n 'Content loaded',\n colorize(\n [\n dictionaries.remoteDictionaries.length +\n dictionaries.pluginDictionaries.length >\n 0\n ? [\n `(Total: ${dictionariesLoadedTime - configurationWrittenTime}ms`,\n dictionaries.localDictionaries.length > 0\n ? ` - Local: ${dictionaries.time.localDictionaries}ms`\n : '',\n dictionaries.remoteDictionaries.length > 0\n ? ` - Remote: ${dictionaries.time.remoteDictionaries}ms`\n : '',\n dictionaries.pluginDictionaries.length > 0\n ? ` - Plugin: ${dictionaries.time.pluginDictionaries}ms`\n : '',\n `)`,\n ].join('')\n : `(${dictionariesLoadedTime - configurationWrittenTime}ms)`,\n ].join(''),\n ANSIColors.GREY_DARK\n ),\n ],\n {\n isVerbose: true,\n }\n );\n\n // Build local dictionaries\n const dictionariesOutput = await buildDictionary(\n [\n ...dictionaries.localDictionaries,\n ...dictionaries.remoteDictionaries,\n ...dictionaries.pluginDictionaries,\n ],\n configuration,\n format,\n false\n );\n\n // Write remote dictionaries\n // Used as cache for next fetch\n await writeRemoteDictionary(\n dictionaries.remoteDictionaries,\n configuration\n );\n\n const dictionariesToBuild = Object.values(\n dictionariesOutput?.mergedDictionaries ?? {}\n ).map((dictionary) => dictionary.dictionary);\n\n await createTypes(dictionariesToBuild, configuration);\n\n await createDictionaryEntryPoint(configuration);\n\n const dictionariesBuiltTime = Date.now();\n\n appLogger([\n 'Dictionaries built',\n colorize(\n `(${dictionariesBuiltTime - preparationStartMs}ms)`,\n ANSIColors.GREY_DARK\n ),\n ]);\n\n await createModuleAugmentation(configuration);\n\n const moduleAugmentationBuiltTime = Date.now();\n\n appLogger(\n [\n 'Module augmentation built',\n colorize(\n `(${moduleAugmentationBuiltTime - dictionariesBuiltTime}ms)`,\n ANSIColors.GREY_DARK\n ),\n ],\n {\n isVerbose: true,\n }\n );\n\n // Plugin transformation\n // Allow plugins to post-process the final build output (e.g., write back ICU JSON)\n for await (const plugin of configuration.plugins ?? []) {\n const { unmergedDictionaries, mergedDictionaries } = dictionariesOutput;\n\n await plugin.afterBuild?.({\n dictionaries: {\n unmergedDictionaries,\n mergedDictionaries,\n },\n configuration,\n });\n }\n\n const preparationElapsedMs = Date.now() - preparationStartMs;\n appLogger(\n [`Done`, colorize(`${preparationElapsedMs}ms`, ANSIColors.GREEN)],\n {\n level: 'info',\n isVerbose: true,\n }\n );\n },\n {\n forceRun,\n onIsCached,\n cacheTimeoutMs,\n }\n );\n};\n"],"mappings":"whCA2BA,MAAM,EAAmC,CACvC,MAAO,GACP,OAAQ,CAAC,MAAO,MAAM,CACtB,eAAgB,IAAO,GAAK,GAC7B,CAEY,EAAkB,MAC7B,EACA,IACG,CACH,IAAM,EAAY,EAAa,EAAc,CAEvC,EAAe,EACnB,EAAc,OAAO,SACrB,yBACD,CAEK,EAAe,EAAU,EAAe,CAAC,mBAAmB,CAAC,CAC7D,EAAuB,MAAM,EAAa,KAAK,CAC/C,EAAmB,GACvB,GAAwB,IAAyB,EAAY,SAGzD,EAAkB,MAAM,EAA8B,EAAc,CAGpE,EAAwB,MAAM,EAA0B,EAAc,CACxE,EAAsB,GAC1B,GAAI,CAEF,IAAM,EAAgB,MAAM,EAAK,EAAa,CAC9C,EAAsB,EAAsB,KACzC,GACC,EAAW,MAAM,MAAM,SAAS,CAAG,EAAc,MAAM,SAAS,CACnE,MACK,EAER,IAAM,EAA4B,EAAc,SAAS,KAAM,GAC7D,EAAQ,EAAO,iBAChB,CAEK,CAAE,QAAO,SAAQ,WAAU,aAAY,kBAAmB,CAC9D,GAAG,EACH,SACE,CAAC,GACD,CAAC,GACD,GACA,EACF,GAAI,GAAW,EAAE,CAClB,CAGD,MAAM,EACJ,EACA,SAAY,EAIN,GAAS,CAAC,IACZ,MAAM,EAAe,EAAc,CAGrC,MAAM,EAAa,IAAI,EAAY,QAAQ,CAE3C,IAAM,EAAqB,KAAK,KAAK,CAErC,EAAU,CACR,qBACA,EAAS,KAAK,EAAY,QAAQ,GAAI,EAAW,UAAU,CAC5D,CA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Ac,SAAW,EAAE,CAAE,CACtD,GAAM,CAAE,uBAAsB,sBAAuB,EAErD,MAAM,EAAO,aAAa,CACxB,aAAc,CACZ,uBACA,qBACD,CACD,gBACD,CAAC,CAIJ,EACE,CAAC,OAAQ,EAAS,GAFS,KAAK,KAAK,CAAG,EAEE,IAAK,EAAW,MAAM,CAAC,CACjE,CACE,MAAO,OACP,UAAW,GACZ,CACF,EAEH,CACE,WACA,aACA,iBACD,CACF"}
1
+ {"version":3,"file":"prepareIntlayer.mjs","names":[],"sources":["../../src/prepareIntlayer.ts"],"sourcesContent":["import { stat } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { ANSIColors, colorize, getAppLogger } from '@intlayer/config/logger';\nimport packageJson from '@intlayer/config/package.json' with { type: 'json' };\nimport { cacheDisk } from '@intlayer/config/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { buildDictionary } from './buildIntlayerDictionary/buildIntlayerDictionary';\nimport { writeRemoteDictionary } from './buildIntlayerDictionary/writeRemoteDictionary';\nimport { cleanOutputDir } from './cleanOutputDir';\nimport { createDictionaryEntryPoint } from './createDictionaryEntryPoint/createDictionaryEntryPoint';\nimport { createModuleAugmentation, createTypes } from './createType/index';\nimport { listDictionariesWithStats } from './listDictionariesPath';\nimport { loadDictionaries } from './loadDictionaries/loadDictionaries';\nimport { runOnce } from './utils/runOnce';\nimport {\n isCachedConfigurationUpToDate,\n writeConfiguration,\n} from './writeConfiguration';\n\ntype PrepareIntlayerOptions = {\n clean?: boolean;\n format?: ('cjs' | 'esm')[];\n forceRun?: boolean;\n cacheTimeoutMs?: number;\n onIsCached?: () => void | Promise<void>;\n};\n\nconst DEFAULT_PREPARE_INTLAYER_OPTIONS = {\n clean: false,\n format: ['cjs', 'esm'],\n cacheTimeoutMs: 1000 * 60 * 60, // 1 hour\n} satisfies PrepareIntlayerOptions;\n\nexport const prepareIntlayer = async (\n configuration: IntlayerConfig,\n options?: PrepareIntlayerOptions\n) => {\n const appLogger = getAppLogger(configuration);\n\n const sentinelPath = join(\n configuration.system.cacheDir,\n 'intlayer-prepared.lock'\n );\n // Clean output dir if the intlayer version has changed\n const versionCache = cacheDisk(configuration, ['intlayer-version']);\n const intlayerCacheVersion = await versionCache.get();\n const isCorrectVersion = Boolean(\n intlayerCacheVersion && intlayerCacheVersion === packageJson.version\n );\n\n const isConfigSimilar = await isCachedConfigurationUpToDate(configuration);\n\n // Check if any dictionary has been changed to force a new rebuild\n const dictionariesWithStats = await listDictionariesWithStats(configuration);\n let isDictionaryChanged = false;\n try {\n // Try catch as sentinel file may not exist yet\n const sentinelStats = await stat(sentinelPath);\n isDictionaryChanged = dictionariesWithStats.some(\n (dictionary) =>\n dictionary.stats.mtime.getTime() > sentinelStats.mtime.getTime()\n );\n } catch {}\n\n const resolvedPlugins = await Promise.all(configuration.plugins ?? []);\n const hasPluginLoadDictionaries = resolvedPlugins.some((plugin) =>\n Boolean(plugin.loadDictionaries)\n ); // Disable cache if any plugin because it can have custom behavior\n\n const { clean, format, forceRun, onIsCached, cacheTimeoutMs } = {\n ...DEFAULT_PREPARE_INTLAYER_OPTIONS,\n forceRun:\n !isCorrectVersion ||\n !isConfigSimilar ||\n isDictionaryChanged ||\n hasPluginLoadDictionaries,\n ...(options ?? {}),\n };\n\n // Skip preparation if it has already been done recently\n await runOnce(\n sentinelPath,\n async () => {\n // comment because of issue with next and webpack\n // await checkVersionsConsistency(configuration);\n\n if (clean || !isCorrectVersion) {\n await cleanOutputDir(configuration);\n }\n\n await versionCache.set(packageJson.version);\n\n const preparationStartMs = Date.now();\n\n appLogger([\n 'Preparing Intlayer',\n colorize(`(v${packageJson.version})`, ANSIColors.GREY_DARK),\n ]);\n\n await writeConfiguration(configuration);\n\n const configurationWrittenTime = Date.now();\n\n appLogger(\n [\n 'Configuration written',\n colorize(\n `(${configurationWrittenTime - preparationStartMs}ms)`,\n ANSIColors.GREY_DARK\n ),\n ],\n {\n isVerbose: true,\n }\n );\n\n const contentDeclarationPaths = dictionariesWithStats.map(\n (dictionary) => dictionary.path\n );\n\n const dictionaries = await loadDictionaries(\n contentDeclarationPaths,\n configuration\n );\n\n const dictionariesLoadedTime = Date.now();\n\n appLogger(\n [\n 'Content loaded',\n colorize(\n [\n dictionaries.remoteDictionaries.length +\n dictionaries.pluginDictionaries.length >\n 0\n ? [\n `(Total: ${dictionariesLoadedTime - configurationWrittenTime}ms`,\n dictionaries.localDictionaries.length > 0\n ? ` - Local: ${dictionaries.time.localDictionaries}ms`\n : '',\n dictionaries.remoteDictionaries.length > 0\n ? ` - Remote: ${dictionaries.time.remoteDictionaries}ms`\n : '',\n dictionaries.pluginDictionaries.length > 0\n ? ` - Plugin: ${dictionaries.time.pluginDictionaries}ms`\n : '',\n `)`,\n ].join('')\n : `(${dictionariesLoadedTime - configurationWrittenTime}ms)`,\n ].join(''),\n ANSIColors.GREY_DARK\n ),\n ],\n {\n isVerbose: true,\n }\n );\n\n // Build local dictionaries\n const dictionariesOutput = await buildDictionary(\n [\n ...dictionaries.localDictionaries,\n ...dictionaries.remoteDictionaries,\n ...dictionaries.pluginDictionaries,\n ],\n configuration,\n format,\n false\n );\n\n // Write remote dictionaries\n // Used as cache for next fetch\n await writeRemoteDictionary(\n dictionaries.remoteDictionaries,\n configuration\n );\n\n const dictionariesToBuild = Object.values(\n dictionariesOutput?.mergedDictionaries ?? {}\n ).map((dictionary) => dictionary.dictionary);\n\n await createTypes(dictionariesToBuild, configuration);\n\n await createDictionaryEntryPoint(configuration);\n\n const dictionariesBuiltTime = Date.now();\n\n appLogger([\n 'Dictionaries built',\n colorize(\n `(${dictionariesBuiltTime - preparationStartMs}ms)`,\n ANSIColors.GREY_DARK\n ),\n ]);\n\n await createModuleAugmentation(configuration);\n\n const moduleAugmentationBuiltTime = Date.now();\n\n appLogger(\n [\n 'Module augmentation built',\n colorize(\n `(${moduleAugmentationBuiltTime - dictionariesBuiltTime}ms)`,\n ANSIColors.GREY_DARK\n ),\n ],\n {\n isVerbose: true,\n }\n );\n\n // Plugin transformation\n // Allow plugins to post-process the final build output (e.g., write back ICU JSON)\n for await (const plugin of configuration.plugins ?? []) {\n const { unmergedDictionaries, mergedDictionaries } = dictionariesOutput;\n\n await plugin.afterBuild?.({\n dictionaries: {\n unmergedDictionaries,\n mergedDictionaries,\n },\n configuration,\n });\n }\n\n const preparationElapsedMs = Date.now() - preparationStartMs;\n appLogger(\n [`Done`, colorize(`${preparationElapsedMs}ms`, ANSIColors.GREEN)],\n {\n level: 'info',\n isVerbose: true,\n }\n );\n },\n {\n forceRun,\n onIsCached,\n cacheTimeoutMs,\n }\n );\n};\n"],"mappings":"whCA2BA,MAAM,EAAmC,CACvC,MAAO,GACP,OAAQ,CAAC,MAAO,MAAM,CACtB,eAAgB,IAAO,GAAK,GAC7B,CAEY,EAAkB,MAC7B,EACA,IACG,CACH,IAAM,EAAY,EAAa,EAAc,CAEvC,EAAe,EACnB,EAAc,OAAO,SACrB,yBACD,CAEK,EAAe,EAAU,EAAe,CAAC,mBAAmB,CAAC,CAC7D,EAAuB,MAAM,EAAa,KAAK,CAC/C,EAAmB,GACvB,GAAwB,IAAyB,EAAY,SAGzD,EAAkB,MAAM,EAA8B,EAAc,CAGpE,EAAwB,MAAM,EAA0B,EAAc,CACxE,EAAsB,GAC1B,GAAI,CAEF,IAAM,EAAgB,MAAM,EAAK,EAAa,CAC9C,EAAsB,EAAsB,KACzC,GACC,EAAW,MAAM,MAAM,SAAS,CAAG,EAAc,MAAM,SAAS,CACnE,MACK,EAGR,IAAM,GADkB,MAAM,QAAQ,IAAI,EAAc,SAAW,EAAE,CAAC,EACpB,KAAM,GACtD,EAAQ,EAAO,iBAChB,CAEK,CAAE,QAAO,SAAQ,WAAU,aAAY,kBAAmB,CAC9D,GAAG,EACH,SACE,CAAC,GACD,CAAC,GACD,GACA,EACF,GAAI,GAAW,EAAE,CAClB,CAGD,MAAM,EACJ,EACA,SAAY,EAIN,GAAS,CAAC,IACZ,MAAM,EAAe,EAAc,CAGrC,MAAM,EAAa,IA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E,CACE,4BACA,EACE,IAN8B,KAAK,KAAK,CAMN,EAAsB,KACxD,EAAW,UACZ,CACF,CACD,CACE,UAAW,GACZ,CACF,CAID,UAAW,IAAM,KAAU,EAAc,SAAW,EAAE,CAAE,CACtD,GAAM,CAAE,uBAAsB,sBAAuB,EAErD,MAAM,EAAO,aAAa,CACxB,aAAc,CACZ,uBACA,qBACD,CACD,gBACD,CAAC,CAIJ,EACE,CAAC,OAAQ,EAAS,GAFS,KAAK,KAAK,CAAG,EAEE,IAAK,EAAW,MAAM,CAAC,CACjE,CACE,MAAO,OACP,UAAW,GACZ,CACF,EAEH,CACE,WACA,aACA,iBACD,CACF"}
@@ -1,2 +1,3 @@
1
- import*as e from"recast";import*as t from"recast/parsers/babel.js";const n=e.types.builders,r=e.types.namedTypes,i=e=>typeof e==`object`&&!!e&&!Array.isArray(e),a=(e,t)=>e.properties.find(e=>!!((r.Property.check(e)||r.ObjectProperty.check(e))&&(r.Identifier.check(e.key)&&e.key.name===t||r.StringLiteral.check(e.key)&&e.key.value===t||r.Literal.check(e.key)&&e.key.value===t))),o=e=>e===null?n.literal(null):typeof e==`string`||typeof e==`number`||typeof e==`boolean`?n.literal(e):Array.isArray(e)?n.arrayExpression(e.map(e=>o(e))):i(e)?n.objectExpression(Object.entries(e).filter(([,e])=>e!==void 0).map(([e,t])=>n.property(`init`,n.stringLiteral(e),o(t)))):n.literal(null),s=(e,t)=>{for(let[c,l]of Object.entries(t)){if(l===void 0)continue;let t=a(e,c);if(i(l))if(t&&r.ObjectExpression.check(t.value))s(t.value,l);else{let r=o(l);t?t.value=r:e.properties.push(n.property(`init`,n.stringLiteral(c),r))}else{let r=o(l);t?t.value=r:e.properties.push(n.property(`init`,n.stringLiteral(c),r))}}},c=(n,i,a)=>{let o=`const _config = ${n.trim()||`{}`};`,c;try{c=e.parse(o,{parser:t})}catch{return JSON.stringify(a?i.content:i,null,2)}let l=c.program.body[0],u;if(r.VariableDeclaration.check(l)&&l.declarations.length>0&&r.VariableDeclarator.check(l.declarations[0])&&r.ObjectExpression.check(l.declarations[0].init)&&(u=l.declarations[0].init),a){let e=[`id`,`locale`,`filled`,`fill`,`title`,`description`,`tags`,`version`,`priority`,`contentAutoTransformation`,`$schema`];u.properties=u.properties.filter(t=>{if(r.Property.check(t)||r.ObjectProperty.check(t)){let n=``;return r.Identifier.check(t.key)?n=t.key.name:r.StringLiteral.check(t.key)?n=t.key.value:r.Literal.check(t.key)&&(n=String(t.key.value)),![`key`,`content`,...e].includes(n)}return!0})}return s(u,a?i.content:i),e.print(u,{tabWidth:2,quote:`double`,trailingComma:!1}).code};export{c as transformJSONFile};
1
+ import*as e from"recast";const t=e.types.builders,n=e.types.namedTypes,r=e=>typeof e==`object`&&!!e&&!Array.isArray(e),i=(e,t)=>t===null?n.Literal.check(e)&&e.value===null:typeof t==`string`||typeof t==`number`||typeof t==`boolean`?(n.Literal.check(e)||n.StringLiteral.check(e)||n.NumericLiteral.check(e)||n.BooleanLiteral.check(e))&&e.value===t:!1,a=(e,t)=>e.properties.find(e=>!!((n.Property.check(e)||n.ObjectProperty.check(e))&&(n.Identifier.check(e.key)&&e.key.name===t||n.StringLiteral.check(e.key)&&e.key.value===t||n.Literal.check(e.key)&&e.key.value===t))),o=e=>e===null?t.literal(null):typeof e==`string`||typeof e==`number`||typeof e==`boolean`?t.literal(e):Array.isArray(e)?t.arrayExpression(e.map(e=>o(e))):r(e)?t.objectExpression(Object.entries(e).filter(([,e])=>e!==void 0).map(([e,n])=>t.property(`init`,t.stringLiteral(e),o(n)))):t.literal(null),s=(e,c)=>{for(let[l,u]of Object.entries(c)){if(u===void 0)continue;let c=a(e,l);c?.comments&&c.comments.forEach(e=>{(e.type===`Line`||e.type===`CommentLine`)&&(e.type=e.type===`Line`?`Block`:`CommentBlock`,e.value=`__INLINE_LINE__${e.value}`,e.leading=!1,e.trailing=!0)}),r(u)?c&&n.ObjectExpression.check(c.value)?s(c.value,u):c?n.Literal.check(c.value)&&c.value.value===u||(c.value=o(u)):e.properties.push(t.property(`init`,t.stringLiteral(l),o(u))):c?i(c.value,u)||(c.value=o(u)):e.properties.push(t.property(`init`,t.stringLiteral(l),o(u)))}},c=(t,r,i)=>{let a=`const _config = ${t.trim()||`{}`};`,o;try{o=e.parse(a)}catch{return JSON.stringify(i?r.content:r,null,2)}let c=o.program.body[0],l;if(n.VariableDeclaration.check(c)&&c.declarations.length>0&&n.VariableDeclarator.check(c.declarations[0])&&n.ObjectExpression.check(c.declarations[0].init)&&(l=c.declarations[0].init),i){let e=[`id`,`locale`,`filled`,`fill`,`title`,`description`,`tags`,`version`,`priority`,`contentAutoTransformation`,`$schema`];for(let t=l.properties.length-1;t>=0;t--){let r=l.properties[t];if(n.Property.check(r)||n.ObjectProperty.check(r)){let i=``;n.Identifier.check(r.key)?i=r.key.name:n.StringLiteral.check(r.key)?i=r.key.value:n.Literal.check(r.key)&&(i=String(r.key.value)),[`key`,`content`,...e].includes(i)&&l.properties.splice(t,1)}}}s(l,i?r.content:r);let u=e.print(o,{tabWidth:2,quote:`double`,trailingComma:!1}).code,d=u.indexOf(`{`),f=u.lastIndexOf(`}`),p=u.substring(d,f+1);return p=p.replace(/\s*\/\*__INLINE_LINE__(.*?)\*\/(\s*,?)/g,`$2 //$1`),p=p.replace(/\n[ \t]*\n/g,`
2
+ `),p};export{c as transformJSONFile};
2
3
  //# sourceMappingURL=transformJSONFile.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"transformJSONFile.mjs","names":[],"sources":["../../../src/writeContentDeclaration/transformJSONFile.ts"],"sourcesContent":["import type { Dictionary } from '@intlayer/types/dictionary';\nimport * as recast from 'recast';\nimport * as babelParser from 'recast/parsers/babel.js';\n\nconst b = recast.types.builders;\nconst n = recast.types.namedTypes;\n\n/**\n * Checks if a value is a plain object (and not null/array)\n */\nconst isPlainObject = (value: unknown): value is Record<string, unknown> => {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n};\n\n/**\n * Robustly finds a property in a recast ObjectExpression.\n * Handles quoted (\"key\") or unquoted (key) properties.\n */\nconst getMatchingProperty = (node: any, key: string) => {\n return node.properties.find((prop: any) => {\n if (n.Property.check(prop) || n.ObjectProperty.check(prop)) {\n if (n.Identifier.check(prop.key) && prop.key.name === key) return true;\n if (n.StringLiteral.check(prop.key) && prop.key.value === key)\n return true;\n if (n.Literal.check(prop.key) && prop.key.value === key) return true;\n }\n return false;\n });\n};\n\n/**\n * Recursively builds a clean recast AST node from a plain JS value.\n * Because these nodes lack `loc` tracking, recast is forced to pretty-print them.\n */\nconst buildASTNode = (val: unknown): any => {\n if (val === null) return b.literal(null);\n\n if (\n typeof val === 'string' ||\n typeof val === 'number' ||\n typeof val === 'boolean'\n ) {\n return b.literal(val);\n }\n\n if (Array.isArray(val)) {\n return b.arrayExpression(val.map((item) => buildASTNode(item)));\n }\n\n if (isPlainObject(val)) {\n return b.objectExpression(\n Object.entries(val)\n .filter(([, v]) => v !== undefined)\n .map(([k, v]) =>\n b.property('init', b.stringLiteral(k), buildASTNode(v))\n )\n );\n }\n\n return b.literal(null); // Fallback\n};\n\n/**\n * Recursively updates the AST object literal with new data.\n */\nconst updateObjectLiteral = (node: any, data: Record<string, any>) => {\n for (const [key, val] of Object.entries(data)) {\n if (val === undefined) continue;\n\n const existingProp = getMatchingProperty(node, key);\n\n if (isPlainObject(val)) {\n if (existingProp && n.ObjectExpression.check(existingProp.value)) {\n updateObjectLiteral(existingProp.value, val);\n } else {\n const valueNode = buildASTNode(val);\n if (existingProp) {\n existingProp.value = valueNode;\n } else {\n node.properties.push(\n b.property('init', b.stringLiteral(key), valueNode)\n );\n }\n }\n } else {\n const valueNode = buildASTNode(val);\n if (existingProp) {\n existingProp.value = valueNode;\n } else {\n node.properties.push(\n b.property('init', b.stringLiteral(key), valueNode)\n );\n }\n }\n }\n};\n\nexport const transformJSONFile = (\n fileContent: string,\n dictionary: Dictionary,\n noMetadata?: boolean\n): string => {\n // Wrap content to create valid syntax for the parser\n const wrappedContent = `const _config = ${fileContent.trim() || '{}'};`;\n\n let ast: ReturnType<typeof recast.parse>;\n try {\n ast = recast.parse(wrappedContent, {\n parser: babelParser,\n });\n } catch {\n // Fallback if parsing failed\n return JSON.stringify(\n noMetadata ? dictionary.content : dictionary,\n null,\n 2\n );\n }\n\n // Navigate the AST to locate the object literal initialized to `_config`\n const declaration = ast.program.body[0];\n let objectLiteral: any;\n\n if (\n n.VariableDeclaration.check(declaration) &&\n declaration.declarations.length > 0 &&\n n.VariableDeclarator.check(declaration.declarations[0]) &&\n n.ObjectExpression.check(declaration.declarations[0].init)\n ) {\n objectLiteral = declaration.declarations[0].init;\n }\n\n if (noMetadata) {\n // Remove key, content and metadata properties if they exist\n const metadataProperties = [\n 'id',\n 'locale',\n 'filled',\n 'fill',\n 'title',\n 'description',\n 'tags',\n 'version',\n 'priority',\n 'contentAutoTransformation',\n '$schema',\n ];\n\n objectLiteral.properties = objectLiteral.properties.filter((prop: any) => {\n if (n.Property.check(prop) || n.ObjectProperty.check(prop)) {\n let propName = '';\n if (n.Identifier.check(prop.key)) propName = prop.key.name;\n else if (n.StringLiteral.check(prop.key)) propName = prop.key.value;\n else if (n.Literal.check(prop.key)) propName = String(prop.key.value);\n\n return !['key', 'content', ...metadataProperties].includes(propName);\n }\n return true;\n });\n }\n\n // Update the AST in place\n updateObjectLiteral(\n objectLiteral,\n noMetadata ? (dictionary.content as Record<string, any>) : dictionary\n );\n\n // Print only the target object literal node\n return recast.print(objectLiteral, {\n tabWidth: 2,\n quote: 'double',\n trailingComma: false,\n }).code;\n};\n"],"mappings":"mEAIA,MAAM,EAAI,EAAO,MAAM,SACjB,EAAI,EAAO,MAAM,WAKjB,EAAiB,GACd,OAAO,GAAU,YAAY,GAAkB,CAAC,MAAM,QAAQ,EAAM,CAOvE,GAAuB,EAAW,IAC/B,EAAK,WAAW,KAAM,GAC3B,IAAI,EAAE,SAAS,MAAM,EAAK,EAAI,EAAE,eAAe,MAAM,EAAK,IACpD,EAAE,WAAW,MAAM,EAAK,IAAI,E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ACJ,GAAI,CACF,EAAM,EAAO,MAAM,EAAgB,CACjC,OAAQ,EACT,CAAC,MACI,CAEN,OAAO,KAAK,UACV,EAAa,EAAW,QAAU,EAClC,KACA,EACD,CAIH,IAAM,EAAc,EAAI,QAAQ,KAAK,GACjC,EAWJ,GARE,EAAE,oBAAoB,MAAM,EAAY,EACxC,EAAY,aAAa,OAAS,GAClC,EAAE,mBAAmB,MAAM,EAAY,aAAa,GAAG,EACvD,EAAE,iBAAiB,MAAM,EAAY,aAAa,GAAG,KAAK,GAE1D,EAAgB,EAAY,aAAa,GAAG,MAG1C,EAAY,CAEd,IAAM,EAAqB,CACzB,KACA,SACA,SACA,OACA,QACA,cACA,OACA,UACA,WACA,4BACA,UACD,CAED,EAAc,WAAa,EAAc,WAAW,OAAQ,GAAc,CACxE,GAAI,EAAE,SAAS,MAAM,EAAK,EAAI,EAAE,eAAe,MAAM,EAAK,CAAE,CAC1D,IAAI,EAAW,GAKf,OAJI,EAAE,WAAW,MAAM,EAAK,IAAI,CAAE,EAAW,EAAK,IAAI,KAC7C,EAAE,cAAc,MAAM,EAAK,IAAI,CAAE,EAAW,EAAK,IAAI,MACrD,EAAE,QAAQ,MAAM,EAAK,IAAI,GAAE,EAAW,OAAO,EAAK,IAAI,MAAM,EAE9D,CAAC,CAAC,MAAO,UAAW,GAAG,EAAmB,CAAC,SAAS,EAAS,CAEtE,MAAO,IACP,CAUJ,OANA,EACE,EACA,EAAc,EAAW,QAAkC,EAC5D,CAGM,EAAO,MAAM,EAAe,CACjC,SAAU,EACV,MAAO,SACP,cAAe,GAChB,CAAC,CAAC"}
1
+ {"version":3,"file":"transformJSONFile.mjs","names":[],"sources":["../../../src/writeContentDeclaration/transformJSONFile.ts"],"sourcesContent":["import type { Dictionary } from '@intlayer/types/dictionary';\nimport * as recast from 'recast';\n\nconst b = recast.types.builders;\nconst n = recast.types.namedTypes;\n\n/**\n * Checks if a value is a plain object (and not null/array)\n */\nconst isPlainObject = (value: unknown): value is Record<string, unknown> => {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n};\n\n/**\n * Checks if a recast AST node value matches the incoming primitive value.\n */\nconst isPrimitiveEqual = (astNode: any, val: unknown): boolean => {\n if (val === null) {\n return n.Literal.check(astNode) && astNode.value === null;\n }\n if (\n typeof val === 'string' ||\n typeof val === 'number' ||\n typeof val === 'boolean'\n ) {\n return (\n (n.Literal.check(astNode) ||\n n.StringLiteral.check(astNode) ||\n n.NumericLiteral.check(astNode) ||\n n.BooleanLiteral.check(astNode)) &&\n astNode.value === val\n );\n }\n return false;\n};\n\n/**\n * Robustly finds a property in a recast ObjectExpression.\n * Handles quoted (\"key\") or unquoted (key) properties.\n */\nconst getMatchingProperty = (node: any, key: string) => {\n return node.properties.find((prop: any) => {\n if (n.Property.check(prop) || n.ObjectProperty.check(prop)) {\n if (n.Identifier.check(prop.key) && prop.key.name === key) return true;\n if (n.StringLiteral.check(prop.key) && prop.key.value === key)\n return true;\n if (n.Literal.check(prop.key) && prop.key.value === key) return true;\n }\n return false;\n });\n};\n\n/**\n * Recursively builds a clean recast AST node from a plain JS value.\n * Because these nodes lack `loc` tracking, recast is forced to pretty-print them.\n */\nconst buildASTNode = (val: unknown): any => {\n if (val === null) return b.literal(null);\n\n if (\n typeof val === 'string' ||\n typeof val === 'number' ||\n typeof val === 'boolean'\n ) {\n return b.literal(val);\n }\n\n if (Array.isArray(val)) {\n return b.arrayExpression(val.map((item) => buildASTNode(item)));\n }\n\n if (isPlainObject(val)) {\n return b.objectExpression(\n Object.entries(val)\n .filter(([, v]) => v !== undefined)\n .map(([k, v]) =>\n b.property('init', b.stringLiteral(k), buildASTNode(v))\n )\n );\n }\n\n return b.literal(null); // Fallback\n};\n\n/**\n * Recursively updates the AST object literal with new data.\n */\nconst updateObjectLiteral = (node: any, data: Record<string, any>) => {\n for (const [key, val] of Object.entries(data)) {\n if (val === undefined) {\n continue;\n }\n\n const existingProp = getMatchingProperty(node, key);\n\n if (existingProp?.comments) {\n existingProp.comments.forEach((c: any) => {\n if (c.type === 'Line' || c.type === 'CommentLine') {\n // Convert to block comment and tag it to force Recast to print it inline\n c.type = c.type === 'Line' ? 'Block' : 'CommentBlock';\n c.value = `__INLINE_LINE__${c.value}`;\n c.leading = false;\n c.trailing = true;\n }\n });\n }\n\n if (isPlainObject(val)) {\n if (existingProp && n.ObjectExpression.check(existingProp.value)) {\n updateObjectLiteral(existingProp.value, val);\n } else {\n if (existingProp) {\n // Prevent AST invalidation if the primitive value is identical\n const isIdentical =\n n.Literal.check(existingProp.value) &&\n existingProp.value.value === val;\n\n if (!isIdentical) {\n existingProp.value = buildASTNode(val);\n }\n } else {\n node.properties.push(\n b.property('init', b.stringLiteral(key), buildASTNode(val))\n );\n }\n }\n } else {\n // Handle primitives and arrays\n if (existingProp) {\n // Skip assignment if the primitive value is identical\n if (!isPrimitiveEqual(existingProp.value, val)) {\n existingProp.value = buildASTNode(val);\n }\n } else {\n node.properties.push(\n b.property('init', b.stringLiteral(key), buildASTNode(val))\n );\n }\n }\n }\n};\n\nexport const transformJSONFile = (\n fileContent: string,\n dictionary: Dictionary,\n noMetadata?: boolean\n): string => {\n // Wrap content to create valid syntax for the parser\n const wrappedContent = `const _config = ${fileContent.trim() || '{}'};`;\n\n let ast: ReturnType<typeof recast.parse>;\n try {\n ast = recast.parse(wrappedContent);\n } catch {\n // Fallback if parsing failed\n return JSON.stringify(\n noMetadata ? dictionary.content : dictionary,\n null,\n 2\n );\n }\n\n // Navigate the AST to locate the object literal initialized to `_config`\n const declaration = ast.program.body[0];\n let objectLiteral: any;\n\n if (\n n.VariableDeclaration.check(declaration) &&\n declaration.declarations.length > 0 &&\n n.VariableDeclarator.check(declaration.declarations[0]) &&\n n.ObjectExpression.check(declaration.declarations[0].init)\n ) {\n objectLiteral = declaration.declarations[0].init;\n }\n\n if (noMetadata) {\n const metadataProperties = [\n 'id',\n 'locale',\n 'filled',\n 'fill',\n 'title',\n 'description',\n 'tags',\n 'version',\n 'priority',\n 'contentAutoTransformation',\n '$schema',\n ];\n\n // Mutate the array backwards instead of using .filter() to prevent layout invalidation\n for (let i = objectLiteral.properties.length - 1; i >= 0; i--) {\n const prop = objectLiteral.properties[i];\n if (n.Property.check(prop) || n.ObjectProperty.check(prop)) {\n let propName = '';\n if (n.Identifier.check(prop.key)) propName = prop.key.name;\n else if (n.StringLiteral.check(prop.key)) propName = prop.key.value;\n else if (n.Literal.check(prop.key)) propName = String(prop.key.value);\n\n if (['key', 'content', ...metadataProperties].includes(propName)) {\n objectLiteral.properties.splice(i, 1);\n }\n }\n }\n }\n\n // Update the AST in place\n updateObjectLiteral(\n objectLiteral,\n noMetadata ? (dictionary.content as Record<string, any>) : dictionary\n );\n\n // Print the full AST to utilize the global token stream for inline comments\n const printedCode = recast.print(ast, {\n tabWidth: 2,\n quote: 'double',\n trailingComma: false,\n }).code;\n\n // Extract the target object literal cleanly\n const startIndex = printedCode.indexOf('{');\n const endIndex = printedCode.lastIndexOf('}');\n let finalOutput = printedCode.substring(startIndex, endIndex + 1);\n\n // Revert the tagged block comment back to an inline line comment and fix comma placement\n finalOutput = finalOutput.replace(\n /\\s*\\/\\*__INLINE_LINE__(.*?)\\*\\/(\\s*,?)/g,\n '$2 //$1'\n );\n\n // Collapse empty lines injected by Recast around commented properties\n finalOutput = finalOutput.replace(/\\n[ \\t]*\\n/g, '\\n');\n\n return finalOutput;\n};\n"],"mappings":"yBAGA,MAAM,EAAI,EAAO,MAAM,SACjB,EAAI,EAAO,MAAM,WAKjB,EAAiB,GACd,OAAO,GAAU,YAAY,GAAkB,CAAC,MAAM,QAAQ,EAAM,CAMvE,GAAoB,EAAc,IAClC,IAAQ,KACH,EAAE,QAAQ,MAAM,EAAQ,EAAI,EAAQ,QAAU,KAGrD,OAAO,GAAQ,UACf,OAAO,GAAQ,UACf,OAAO,GAAQ,WAGZ,EAAE,QAAQ,MAAM,EAAQ,EACvB,EAAE,cAAc,MAAM,EAAQ,EAC9B,EAAE,eAAe,MAAM,EAAQ,EAC/B,EA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I,GAAE,EAAW,OAAO,EAAK,IAAI,MAAM,EAEjE,CAAC,MAAO,UAAW,GAAG,EAAmB,CAAC,SAAS,EAAS,EAC9D,EAAc,WAAW,OAAO,EAAG,EAAE,GAO7C,EACE,EACA,EAAc,EAAW,QAAkC,EAC5D,CAGD,IAAM,EAAc,EAAO,MAAM,EAAK,CACpC,SAAU,EACV,MAAO,SACP,cAAe,GAChB,CAAC,CAAC,KAGG,EAAa,EAAY,QAAQ,IAAI,CACrC,EAAW,EAAY,YAAY,IAAI,CACzC,EAAc,EAAY,UAAU,EAAY,EAAW,EAAE,CAWjE,MARA,GAAc,EAAY,QACxB,0CACA,UACD,CAGD,EAAc,EAAY,QAAQ,cAAe;EAAK,CAE/C"}
@@ -1,2 +1,2 @@
1
- import{getFormatFromExtension as e}from"../utils/getFormatFromExtension.mjs";import{detectFormatCommand as t}from"../detectFormatCommand.mjs";import{processContentDeclarationContent as n}from"./processContentDeclarationContent.mjs";import{transformJSONFile as r}from"./transformJSONFile.mjs";import{writeJSFile as i}from"./writeJSFile.mjs";import{mkdir as a,readFile as o,rename as s,rm as c,writeFile as l}from"node:fs/promises";import{basename as u,dirname as d,extname as f,join as p,resolve as m}from"node:path";import{DefaultValues as h}from"@intlayer/config/client";import{getUnmergedDictionaries as g}from"@intlayer/unmerged-dictionaries-entry";import{existsSync as _}from"node:fs";import{getFilteredLocalesDictionary as v,getPerLocaleDictionary as y}from"@intlayer/core/plugins";import{execSync as b}from"node:child_process";import{isDeepStrictEqual as x}from"node:util";const S=async(t,r,i)=>{let a=await n(t),o=a.content;t.locale?o=y(a,t.locale).content:i&&(o=v(a,i).content);let s={...t,content:o};for await(let e of r.plugins??[])if(e.formatOutput){let t=await e.formatOutput?.({dictionary:s,configuration:r});t&&(s=t)}if(!(s.content&&s.key))return s;let c={key:t.key,id:t.id,title:t.title,description:t.description,tags:t.tags,locale:t.locale,fill:t.fill,filled:t.filled,priority:t.priority,importMode:t.importMode,version:t.version,content:o};return e(t.filePath?f(t.filePath):`.json`)===`json`&&s.content&&s.key&&(c={$schema:`https://intlayer.org/schema.json`,...c}),c},C={newDictionariesPath:`intlayer-dictionaries`},w=async(e,t,n)=>{let{system:r,compiler:i}=t,{baseDir:a}=r,o=i?.noMetadata??h.Compiler.COMPILER_NO_METADATA,{newDictionariesPath:s,localeList:c}={...C,...n},l=p(a,s),u=g(t)[e.key]?.find(t=>t.localId===e.localId),d=await S(e,t,c);if(u?.filePath){let n=x(u,e),r=m(t.system.baseDir,u.filePath);return n?{status:`up-to-date`,path:r}:(await T(r,d,t,o),{status:`updated`,path:r})}if(e.filePath){let n=m(t.system.baseDir,e.filePath);return await T(n,d,t,o),{status:`created`,path:n}}let f=p(l,`${e.key}.content.json`);return await T(f,d,t,o),{status:`imported`,path:f}},T=async(e,n,m,h)=>{await a(d(e),{recursive:!0});let g=f(e);if(!m.content.fileExtensions.map(e=>e.startsWith(`.`)?e:`.${e}`).some(t=>e.endsWith(t)))throw Error(`Invalid file extension: ${g}, file: ${e}`);if(g===`.json`){let r=JSON.stringify(h?n.content:n,null,2),i=m.system?.tempDir;i&&await a(i,{recursive:!0});let o=`${u(e)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`,d=i?p(i,o):`${e}.${o}`;try{await l(d,`${r}\n`),await s(d,e)}catch(e){try{await c(d,{force:!0})}catch{}throw e}let f=t(m);if(f)try{b(f.replace(`{{file}}`,e),{stdio:`inherit`,cwd:m.system.baseDir})}catch(e){console.error(e)}return}if([`.jsonc`,`.json5`].includes(g)){let i=`{}`;if(_(e))try{i=await o(e,`utf-8`)}catch{}let d=r(i,n,h),f=m.system?.tempDir;f&&await a(f,{recursive:!0});let g=`${u(e)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`,v=f?p(f,g):`${e}.${g}`;try{await l(v,d,`utf-8`),await s(v,e)}catch(e){try{await c(v,{force:!0})}catch{}throw e}let y=t(m);if(y)try{b(y.replace(`{{file}}`,e),{stdio:`inherit`,cwd:m.system.baseDir})}catch(e){console.error(e)}return}await i(e,n,m,h);try{await c(p(m.system.cacheDir,`intlayer-prepared.lock`),{recursive:!0})}catch{}};export{w as writeContentDeclaration};
1
+ import{getFormatFromExtension as e}from"../utils/getFormatFromExtension.mjs";import{detectFormatCommand as t}from"../detectFormatCommand.mjs";import{processContentDeclarationContent as n}from"./processContentDeclarationContent.mjs";import{transformJSONFile as r}from"./transformJSONFile.mjs";import{writeJSFile as i}from"./writeJSFile.mjs";import{mkdir as a,readFile as o,rename as s,rm as c,writeFile as l}from"node:fs/promises";import{basename as u,dirname as d,extname as f,join as p,resolve as m}from"node:path";import{DefaultValues as h}from"@intlayer/config/client";import{getUnmergedDictionaries as g}from"@intlayer/unmerged-dictionaries-entry";import{existsSync as _}from"node:fs";import{getFilteredLocalesDictionary as v,getPerLocaleDictionary as y}from"@intlayer/core/plugins";import{execSync as b}from"node:child_process";import{isDeepStrictEqual as x}from"node:util";const S=async(t,r,i)=>{let a=await n(t),o=a.content;t.locale?o=y(a,t.locale).content:i&&(o=v(a,i).content);let s={...t,content:o};for await(let e of r.plugins??[])if(e.formatOutput){let t=await e.formatOutput?.({dictionary:s,configuration:r});t&&(s=t)}if(!(s.content&&s.key))return s;let c={key:t.key,id:t.id,title:t.title,description:t.description,tags:t.tags,locale:t.locale,fill:t.fill,filled:t.filled,priority:t.priority,importMode:t.importMode,version:t.version,content:o};return e(t.filePath?f(t.filePath):`.json`)===`json`&&s.content&&s.key&&(c={$schema:`https://intlayer.org/schema.json`,...c}),c},C={newDictionariesPath:`intlayer-dictionaries`},w=async(e,t,n)=>{let{system:r,compiler:i}=t,{baseDir:a}=r,o=i?.noMetadata??h.Compiler.COMPILER_NO_METADATA,{newDictionariesPath:s,localeList:c}={...C,...n},l=p(a,s),u=g(t)[e.key]?.find(t=>t.localId===e.localId),d=await S(e,t,c);if(u?.filePath){let n=x(u,e),r=m(t.system.baseDir,u.filePath);return n?{status:`up-to-date`,path:r}:(await T(r,d,t,o),{status:`updated`,path:r})}if(e.filePath){let n=m(t.system.baseDir,e.filePath);return await T(n,d,t,o),{status:`created`,path:n}}let f=p(l,`${e.key}.content.json`);return await T(f,d,t,o),{status:`imported`,path:f}},T=async(e,n,m,h)=>{await a(d(e),{recursive:!0});let g=f(e);if([`.json`,`.jsonc`,`.json5`].includes(g)){let i=`{}`;if(_(e))try{i=await o(e,`utf-8`)}catch{}let d=r(i,n,h),f=m.system?.tempDir;f&&await a(f,{recursive:!0});let g=`${u(e)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`,v=f?p(f,g):`${e}.${g}`;try{await l(v,d,`utf-8`),await s(v,e)}catch(e){try{await c(v,{force:!0})}catch{}throw e}let y=t(m);if(y)try{b(y.replace(`{{file}}`,e),{stdio:`inherit`,cwd:m.system.baseDir})}catch(e){console.error(e)}return}await i(e,n,m,h);try{await c(p(m.system.cacheDir,`intlayer-prepared.lock`),{recursive:!0})}catch{}};export{w as writeContentDeclaration};
2
2
  //# sourceMappingURL=writeContentDeclaration.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"writeContentDeclaration.mjs","names":[],"sources":["../../../src/writeContentDeclaration/writeContentDeclaration.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';\nimport { basename, dirname, extname, join, resolve } from 'node:path';\nimport { isDeepStrictEqual } from 'node:util';\nimport { DefaultValues } from '@intlayer/config/client';\nimport {\n getFilteredLocalesDictionary,\n getPerLocaleDictionary,\n} from '@intlayer/core/plugins';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\nimport { detectFormatCommand } from '../detectFormatCommand';\nimport {\n type Extension,\n getFormatFromExtension,\n} from '../utils/getFormatFromExtension';\nimport type { DictionaryStatus } from './dictionaryStatus';\nimport { processContentDeclarationContent } from './processContentDeclarationContent';\nimport { transformJSONFile } from './transformJSONFile';\nimport { writeJSFile } from './writeJSFile';\n\nconst formatContentDeclaration = async (\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n localeList?: LocalesValues[]\n) => {\n /**\n * Clean Markdown, Insertion, File, etc. node metadata\n */\n const processedDictionary =\n await processContentDeclarationContent(dictionary);\n\n let content = processedDictionary.content;\n\n /**\n * Filter locales content\n */\n\n if (dictionary.locale) {\n content = getPerLocaleDictionary(\n processedDictionary,\n dictionary.locale\n ).content;\n } else if (localeList) {\n content = getFilteredLocalesDictionary(\n processedDictionary,\n localeList\n ).content;\n }\n\n let pluginFormatResult: any = {\n ...dictionary,\n content,\n } satisfies Dictionary;\n\n /**\n * Format the dictionary with the plugins\n */\n\n for await (const plugin of configuration.plugins ?? []) {\n if (plugin.formatOutput) {\n const formattedResult = await plugin.formatOutput?.({\n dictionary: pluginFormatResult,\n configuration,\n });\n\n if (formattedResult) {\n pluginFormatResult = formattedResult;\n }\n }\n }\n\n const isDictionaryFormat =\n pluginFormatResult.content && pluginFormatResult.key;\n\n if (!isDictionaryFormat) return pluginFormatResult;\n\n let result: Dictionary = {\n key: dictionary.key,\n id: dictionary.id,\n title: dictionary.title,\n description: dictionary.description,\n tags: dictionary.tags,\n locale: dictionary.locale,\n fill: dictionary.fill,\n filled: dictionary.filled,\n priority: dictionary.priority,\n importMode: dictionary.importMode,\n version: dictionary.version,\n content,\n };\n\n /**\n * Add $schema to JSON dictionaries\n */\n const extension = (\n dictionary.filePath ? extname(dictionary.filePath) : '.json'\n ) as Extension;\n const format = getFormatFromExtension(extension);\n\n if (\n format === 'json' &&\n pluginFormatResult.content &&\n pluginFormatResult.key\n ) {\n result = {\n $schema: 'https://intlayer.org/schema.json',\n ...result,\n };\n }\n\n return result;\n};\n\ntype WriteContentDeclarationOptions = {\n newDictionariesPath?: string;\n localeList?: LocalesValues[];\n fallbackLocale?: Locale;\n};\n\nconst defaultOptions = {\n newDictionariesPath: 'intlayer-dictionaries',\n} satisfies WriteContentDeclarationOptions;\n\nexport const writeContentDeclaration = async (\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n options?: WriteContentDeclarationOptions\n): Promise<{ status: DictionaryStatus; path: string }> => {\n const { system, compiler } = configuration;\n const { baseDir } = system;\n\n const noMetadata =\n compiler?.noMetadata ?? DefaultValues.Compiler.COMPILER_NO_METADATA;\n const { newDictionariesPath, localeList } = {\n ...defaultOptions,\n ...options,\n };\n\n const newDictionaryLocationPath = join(baseDir, newDictionariesPath);\n\n const unmergedDictionariesRecord = getUnmergedDictionaries(configuration);\n const unmergedDictionaries = unmergedDictionariesRecord[\n dictionary.key\n ] as Dictionary[];\n\n const existingDictionary = unmergedDictionaries?.find(\n (el) => el.localId === dictionary.localId\n );\n\n const formattedContentDeclaration = await formatContentDeclaration(\n dictionary,\n configuration,\n localeList\n );\n\n if (existingDictionary?.filePath) {\n // Compare existing dictionary content with new dictionary content\n const isSameContent = isDeepStrictEqual(existingDictionary, dictionary);\n\n const filePath = resolve(\n configuration.system.baseDir,\n existingDictionary.filePath\n );\n\n // Up to date, nothing to do\n if (isSameContent) {\n return {\n status: 'up-to-date',\n path: filePath,\n };\n }\n\n await writeFileWithDirectories(\n filePath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return { status: 'updated', path: filePath };\n }\n\n if (dictionary.filePath) {\n const filePath = resolve(configuration.system.baseDir, dictionary.filePath);\n\n await writeFileWithDirectories(\n filePath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return { status: 'created', path: filePath };\n }\n\n // No existing dictionary, write to new location\n const contentDeclarationPath = join(\n newDictionaryLocationPath,\n `${dictionary.key}.content.json`\n );\n\n await writeFileWithDirectories(\n contentDeclarationPath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return {\n status: 'imported',\n path: contentDeclarationPath,\n };\n};\n\nconst writeFileWithDirectories = async (\n absoluteFilePath: string,\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n noMetadata?: boolean\n): Promise<void> => {\n // Extract the directory from the file path\n const dir = dirname(absoluteFilePath);\n\n // Create the directory recursively\n await mkdir(dir, { recursive: true });\n\n const extension = extname(absoluteFilePath);\n const acceptedExtensions = configuration.content.fileExtensions.map((ext) =>\n ext.startsWith('.') ? ext : `.${ext}`\n );\n\n const hasAcceptedExtension = acceptedExtensions.some((ext) =>\n absoluteFilePath.endsWith(ext)\n );\n\n if (!hasAcceptedExtension) {\n throw new Error(\n `Invalid file extension: ${extension}, file: ${absoluteFilePath}`\n );\n }\n\n if (extension === '.json') {\n const jsonDictionary = JSON.stringify(\n noMetadata ? dictionary.content : dictionary,\n null,\n 2\n );\n\n // Write the file\n const tempDir = configuration.system?.tempDir;\n if (tempDir) {\n await mkdir(tempDir, { recursive: true });\n }\n\n const tempFileName = `${basename(absoluteFilePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${absoluteFilePath}.${tempFileName}`;\n try {\n await writeFile(tempPath, `${jsonDictionary}\\n`); // Add a new line at the end of the file to avoid formatting issues with VSCode\n await rename(tempPath, absoluteFilePath);\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {\n // Ignore\n }\n throw error;\n }\n\n const formatCommand = detectFormatCommand(configuration);\n\n if (formatCommand) {\n try {\n execSync(formatCommand.replace('{{file}}', absoluteFilePath), {\n stdio: 'inherit',\n cwd: configuration.system.baseDir,\n });\n } catch (error) {\n console.error(error);\n }\n }\n\n return;\n }\n\n // Handle JSONC, and JSON5 via the AST transformer\n if (['.jsonc', '.json5'].includes(extension)) {\n let fileContent = '{}';\n\n if (existsSync(absoluteFilePath)) {\n try {\n fileContent = await readFile(absoluteFilePath, 'utf-8');\n } catch {\n // ignore read errors, start with empty object\n }\n }\n\n const transformedContent = transformJSONFile(\n fileContent,\n dictionary,\n noMetadata\n );\n\n // We use standard writeFile because transformedContent is already a string\n const tempDir = configuration.system?.tempDir;\n if (tempDir) {\n await mkdir(tempDir, { recursive: true });\n }\n\n const tempFileName = `${basename(absoluteFilePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${absoluteFilePath}.${tempFileName}`;\n try {\n await writeFile(tempPath, transformedContent, 'utf-8');\n await rename(tempPath, absoluteFilePath);\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {\n // Ignore\n }\n throw error;\n }\n\n const formatCommand = detectFormatCommand(configuration);\n\n if (formatCommand) {\n try {\n execSync(formatCommand.replace('{{file}}', absoluteFilePath), {\n stdio: 'inherit',\n cwd: configuration.system.baseDir,\n });\n } catch (error) {\n console.error(error);\n }\n }\n\n return;\n }\n\n await writeJSFile(absoluteFilePath, dictionary, configuration, noMetadata);\n\n // remove the cache as content has changed\n // Will force a new preparation of the intlayer on next build\n try {\n const sentinelPath = join(\n configuration.system.cacheDir,\n 'intlayer-prepared.lock'\n );\n await rm(sentinelPath, { recursive: true });\n } catch {}\n};\n"],"mappings":"+2BAyBA,MAAM,EAA2B,MAC/B,EACA,EACA,IACG,CAIH,IAAM,EACJ,MAAM,EAAiC,EAAW,CAEhD,EAAU,EAAoB,QAM9B,EAAW,OACb,EAAU,EACR,EACA,EAAW,OACZ,CAAC,QACO,IACT,EAAU,EACR,EACA,EACD,CAAC,SAGJ,IAAI,EAA0B,CAC5B,GAAG,EACH,UACD,CAMD,UAAW,IAAM,KAAU,EAAc,SAAW,EAAE,CACpD,GAAI,EAAO,aAAc,CACvB,IAAM,EAAkB,MAAM,EAAO,eAAe,CAClD,WAAY,EACZ,gBACD,CAAC,CAEE,IACF,EAAqB,GAQ3B,GAAI,EAFF,EAAmB,SAAW,EAAmB,KAE1B,OAAO,EAEhC,IAAI,EAAqB,CACvB,IAAK,EAAW,IAChB,GAAI,EAAW,GACf,MAAO,EAAW,MAClB,YAAa,EAAW,YACxB,KAAM,EA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AE,UAAW,GAAM,CAAC,CAG3C,IAAM,EAAe,GAAG,EAAS,EAAiB,CAAC,GAAG,KAAK,KAAK,CAAC,GAAG,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,MAAM,EAAE,CAAC,MAClG,EAAW,EACb,EAAK,EAAS,EAAa,CAC3B,GAAG,EAAiB,GAAG,IAC3B,GAAI,CACF,MAAM,EAAU,EAAU,EAAoB,QAAQ,CACtD,MAAM,EAAO,EAAU,EAAiB,OACjC,EAAO,CACd,GAAI,CACF,MAAM,EAAG,EAAU,CAAE,MAAO,GAAM,CAAC,MAC7B,EAGR,MAAM,EAGR,IAAM,EAAgB,EAAoB,EAAc,CAExD,GAAI,EACF,GAAI,CACF,EAAS,EAAc,QAAQ,WAAY,EAAiB,CAAE,CAC5D,MAAO,UACP,IAAK,EAAc,OAAO,QAC3B,CAAC,OACK,EAAO,CACd,QAAQ,MAAM,EAAM,CAIxB,OAGF,MAAM,EAAY,EAAkB,EAAY,EAAe,EAAW,CAI1E,GAAI,CAKF,MAAM,EAJe,EACnB,EAAc,OAAO,SACrB,yBACD,CACsB,CAAE,UAAW,GAAM,CAAC,MACrC"}
1
+ {"version":3,"file":"writeContentDeclaration.mjs","names":[],"sources":["../../../src/writeContentDeclaration/writeContentDeclaration.ts"],"sourcesContent":["import { execSync } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';\nimport { basename, dirname, extname, join, resolve } from 'node:path';\nimport { isDeepStrictEqual } from 'node:util';\nimport { DefaultValues } from '@intlayer/config/client';\nimport {\n getFilteredLocalesDictionary,\n getPerLocaleDictionary,\n} from '@intlayer/core/plugins';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { getUnmergedDictionaries } from '@intlayer/unmerged-dictionaries-entry';\nimport { detectFormatCommand } from '../detectFormatCommand';\nimport {\n type Extension,\n getFormatFromExtension,\n} from '../utils/getFormatFromExtension';\nimport type { DictionaryStatus } from './dictionaryStatus';\nimport { processContentDeclarationContent } from './processContentDeclarationContent';\nimport { transformJSONFile } from './transformJSONFile';\nimport { writeJSFile } from './writeJSFile';\n\nconst formatContentDeclaration = async (\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n localeList?: LocalesValues[]\n) => {\n /**\n * Clean Markdown, Insertion, File, etc. node metadata\n */\n const processedDictionary =\n await processContentDeclarationContent(dictionary);\n\n let content = processedDictionary.content;\n\n /**\n * Filter locales content\n */\n\n if (dictionary.locale) {\n content = getPerLocaleDictionary(\n processedDictionary,\n dictionary.locale\n ).content;\n } else if (localeList) {\n content = getFilteredLocalesDictionary(\n processedDictionary,\n localeList\n ).content;\n }\n\n let pluginFormatResult: any = {\n ...dictionary,\n content,\n } satisfies Dictionary;\n\n /**\n * Format the dictionary with the plugins\n */\n\n for await (const plugin of configuration.plugins ?? []) {\n if (plugin.formatOutput) {\n const formattedResult = await plugin.formatOutput?.({\n dictionary: pluginFormatResult,\n configuration,\n });\n\n if (formattedResult) {\n pluginFormatResult = formattedResult;\n }\n }\n }\n\n const isDictionaryFormat =\n pluginFormatResult.content && pluginFormatResult.key;\n\n if (!isDictionaryFormat) return pluginFormatResult;\n\n let result: Dictionary = {\n key: dictionary.key,\n id: dictionary.id,\n title: dictionary.title,\n description: dictionary.description,\n tags: dictionary.tags,\n locale: dictionary.locale,\n fill: dictionary.fill,\n filled: dictionary.filled,\n priority: dictionary.priority,\n importMode: dictionary.importMode,\n version: dictionary.version,\n content,\n };\n\n /**\n * Add $schema to JSON dictionaries\n */\n const extension = (\n dictionary.filePath ? extname(dictionary.filePath) : '.json'\n ) as Extension;\n const format = getFormatFromExtension(extension);\n\n if (\n format === 'json' &&\n pluginFormatResult.content &&\n pluginFormatResult.key\n ) {\n result = {\n $schema: 'https://intlayer.org/schema.json',\n ...result,\n };\n }\n\n return result;\n};\n\ntype WriteContentDeclarationOptions = {\n newDictionariesPath?: string;\n localeList?: LocalesValues[];\n fallbackLocale?: Locale;\n};\n\nconst defaultOptions = {\n newDictionariesPath: 'intlayer-dictionaries',\n} satisfies WriteContentDeclarationOptions;\n\nexport const writeContentDeclaration = async (\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n options?: WriteContentDeclarationOptions\n): Promise<{ status: DictionaryStatus; path: string }> => {\n const { system, compiler } = configuration;\n const { baseDir } = system;\n\n const noMetadata =\n compiler?.noMetadata ?? DefaultValues.Compiler.COMPILER_NO_METADATA;\n const { newDictionariesPath, localeList } = {\n ...defaultOptions,\n ...options,\n };\n\n const newDictionaryLocationPath = join(baseDir, newDictionariesPath);\n\n const unmergedDictionariesRecord = getUnmergedDictionaries(configuration);\n const unmergedDictionaries = unmergedDictionariesRecord[\n dictionary.key\n ] as Dictionary[];\n\n const existingDictionary = unmergedDictionaries?.find(\n (el) => el.localId === dictionary.localId\n );\n\n const formattedContentDeclaration = await formatContentDeclaration(\n dictionary,\n configuration,\n localeList\n );\n\n if (existingDictionary?.filePath) {\n // Compare existing dictionary content with new dictionary content\n const isSameContent = isDeepStrictEqual(existingDictionary, dictionary);\n\n const filePath = resolve(\n configuration.system.baseDir,\n existingDictionary.filePath\n );\n\n // Up to date, nothing to do\n if (isSameContent) {\n return {\n status: 'up-to-date',\n path: filePath,\n };\n }\n\n await writeFileWithDirectories(\n filePath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return { status: 'updated', path: filePath };\n }\n\n if (dictionary.filePath) {\n const filePath = resolve(configuration.system.baseDir, dictionary.filePath);\n\n await writeFileWithDirectories(\n filePath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return { status: 'created', path: filePath };\n }\n\n // No existing dictionary, write to new location\n const contentDeclarationPath = join(\n newDictionaryLocationPath,\n `${dictionary.key}.content.json`\n );\n\n await writeFileWithDirectories(\n contentDeclarationPath,\n formattedContentDeclaration,\n configuration,\n noMetadata\n );\n\n return {\n status: 'imported',\n path: contentDeclarationPath,\n };\n};\n\nconst writeFileWithDirectories = async (\n absoluteFilePath: string,\n dictionary: Dictionary,\n configuration: IntlayerConfig,\n noMetadata?: boolean\n): Promise<void> => {\n // Extract the directory from the file path\n const dir = dirname(absoluteFilePath);\n\n // Create the directory recursively\n await mkdir(dir, { recursive: true });\n\n const extension = extname(absoluteFilePath);\n\n // Handle JSON, JSONC, and JSON5 via the AST transformer\n if (['.json', '.jsonc', '.json5'].includes(extension)) {\n let fileContent = '{}';\n\n if (existsSync(absoluteFilePath)) {\n try {\n fileContent = await readFile(absoluteFilePath, 'utf-8');\n } catch {\n // ignore read errors, start with empty object\n }\n }\n\n const transformedContent = transformJSONFile(\n fileContent,\n dictionary,\n noMetadata\n );\n\n // We use standard writeFile because transformedContent is already a string\n const tempDir = configuration.system?.tempDir;\n if (tempDir) {\n await mkdir(tempDir, { recursive: true });\n }\n\n const tempFileName = `${basename(absoluteFilePath)}.${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;\n const tempPath = tempDir\n ? join(tempDir, tempFileName)\n : `${absoluteFilePath}.${tempFileName}`;\n try {\n await writeFile(tempPath, transformedContent, 'utf-8');\n await rename(tempPath, absoluteFilePath);\n } catch (error) {\n try {\n await rm(tempPath, { force: true });\n } catch {\n // Ignore\n }\n throw error;\n }\n\n const formatCommand = detectFormatCommand(configuration);\n\n if (formatCommand) {\n try {\n execSync(formatCommand.replace('{{file}}', absoluteFilePath), {\n stdio: 'inherit',\n cwd: configuration.system.baseDir,\n });\n } catch (error) {\n console.error(error);\n }\n }\n\n return;\n }\n\n await writeJSFile(absoluteFilePath, dictionary, configuration, noMetadata);\n\n // remove the cache as content has changed\n // Will force a new preparation of the intlayer on next build\n try {\n const sentinelPath = join(\n configuration.system.cacheDir,\n 'intlayer-prepared.lock'\n );\n await rm(sentinelPath, { recursive: true });\n } catch {}\n};\n"],"mappings":"+2BAyBA,MAAM,EAA2B,MAC/B,EACA,EACA,IACG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AgB,EAAoB,EAAc,CAExD,GAAI,EACF,GAAI,CACF,EAAS,EAAc,QAAQ,WAAY,EAAiB,CAAE,CAC5D,MAAO,UACP,IAAK,EAAc,OAAO,QAC3B,CAAC,OACK,EAAO,CACd,QAAQ,MAAM,EAAM,CAIxB,OAGF,MAAM,EAAY,EAAkB,EAAY,EAAe,EAAW,CAI1E,GAAI,CAKF,MAAM,EAJe,EACnB,EAAc,OAAO,SACrB,yBACD,CACsB,CAAE,UAAW,GAAM,CAAC,MACrC"}
@@ -1 +1 @@
1
- {"version":3,"file":"transformJSONFile.d.ts","names":[],"sources":["../../../src/writeContentDeclaration/transformJSONFile.ts"],"mappings":";;;cAiGa,iBAAA,GACX,WAAA,UACA,UAAA,EAAY,UAAA,EACZ,UAAA"}
1
+ {"version":3,"file":"transformJSONFile.d.ts","names":[],"sources":["../../../src/writeContentDeclaration/transformJSONFile.ts"],"mappings":";;;cA8Ia,iBAAA,GACX,WAAA,UACA,UAAA,EAAY,UAAA,EACZ,UAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@intlayer/chokidar",
3
- "version": "8.3.0-canary.0",
3
+ "version": "8.3.0-canary.1",
4
4
  "private": false,
5
5
  "description": "Uses chokidar to scan and build Intlayer declaration files into dictionaries based on Intlayer configuration.",
6
6
  "keywords": [
@@ -102,13 +102,13 @@
102
102
  },
103
103
  "dependencies": {
104
104
  "@babel/parser": "7.29.0",
105
- "@intlayer/api": "8.3.0-canary.0",
106
- "@intlayer/config": "8.3.0-canary.0",
107
- "@intlayer/core": "8.3.0-canary.0",
108
- "@intlayer/dictionaries-entry": "8.3.0-canary.0",
109
- "@intlayer/remote-dictionaries-entry": "8.3.0-canary.0",
110
- "@intlayer/types": "8.3.0-canary.0",
111
- "@intlayer/unmerged-dictionaries-entry": "8.3.0-canary.0",
105
+ "@intlayer/api": "8.3.0-canary.1",
106
+ "@intlayer/config": "8.3.0-canary.1",
107
+ "@intlayer/core": "8.3.0-canary.1",
108
+ "@intlayer/dictionaries-entry": "8.3.0-canary.1",
109
+ "@intlayer/remote-dictionaries-entry": "8.3.0-canary.1",
110
+ "@intlayer/types": "8.3.0-canary.1",
111
+ "@intlayer/unmerged-dictionaries-entry": "8.3.0-canary.1",
112
112
  "chokidar": "3.6.0",
113
113
  "defu": "6.1.4",
114
114
  "fast-glob": "3.3.3",
@@ -117,12 +117,12 @@
117
117
  "zod-to-ts": "2.0.0"
118
118
  },
119
119
  "devDependencies": {
120
- "@types/node": "25.3.5",
120
+ "@types/node": "25.4.0",
121
121
  "@utils/ts-config": "1.0.4",
122
122
  "@utils/ts-config-types": "1.0.4",
123
123
  "@utils/tsdown-config": "1.0.4",
124
124
  "rimraf": "6.1.3",
125
- "tsdown": "0.21.1",
125
+ "tsdown": "0.21.2",
126
126
  "typescript": "5.9.3",
127
127
  "vitest": "4.0.18",
128
128
  "zod": "4.3.6"