@intlayer/config 9.5.10 → 9.5.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/callers/compat/ngxTranslate.cjs +43 -0
- package/dist/cjs/callers/compat/ngxTranslate.cjs.map +1 -0
- package/dist/cjs/callers/compat/nuxtjsI18n.cjs +33 -0
- package/dist/cjs/callers/compat/nuxtjsI18n.cjs.map +1 -0
- package/dist/cjs/callers/compat/svelteI18n.cjs +42 -0
- package/dist/cjs/callers/compat/svelteI18n.cjs.map +1 -0
- package/dist/cjs/callers/index.cjs +11 -1
- package/dist/cjs/callers/index.cjs.map +1 -1
- package/dist/cjs/callers/transform.cjs +12 -0
- package/dist/cjs/callers/transform.cjs.map +1 -1
- package/dist/cjs/client.cjs +1 -0
- package/dist/cjs/configFile/buildBrowserConfiguration.cjs +15 -4
- package/dist/cjs/configFile/buildBrowserConfiguration.cjs.map +1 -1
- package/dist/cjs/configFile/buildConfigurationFields.cjs +1 -1
- package/dist/cjs/configFile/buildConfigurationFields.cjs.map +1 -1
- package/dist/cjs/loadEnvFile.cjs.map +1 -1
- package/dist/esm/callers/compat/ngxTranslate.mjs +42 -0
- package/dist/esm/callers/compat/ngxTranslate.mjs.map +1 -0
- package/dist/esm/callers/compat/nuxtjsI18n.mjs +32 -0
- package/dist/esm/callers/compat/nuxtjsI18n.mjs.map +1 -0
- package/dist/esm/callers/compat/svelteI18n.mjs +41 -0
- package/dist/esm/callers/compat/svelteI18n.mjs.map +1 -0
- package/dist/esm/callers/index.mjs +9 -3
- package/dist/esm/callers/index.mjs.map +1 -1
- package/dist/esm/callers/transform.mjs +12 -1
- package/dist/esm/callers/transform.mjs.map +1 -1
- package/dist/esm/client.mjs +2 -2
- package/dist/esm/configFile/buildBrowserConfiguration.mjs +15 -5
- package/dist/esm/configFile/buildBrowserConfiguration.mjs.map +1 -1
- package/dist/esm/configFile/buildConfigurationFields.mjs +2 -2
- package/dist/esm/configFile/buildConfigurationFields.mjs.map +1 -1
- package/dist/esm/loadEnvFile.mjs +2 -2
- package/dist/esm/loadEnvFile.mjs.map +1 -1
- package/dist/types/callers/compat/ngxTranslate.d.ts +5 -0
- package/dist/types/callers/compat/ngxTranslate.d.ts.map +1 -0
- package/dist/types/callers/compat/nuxtjsI18n.d.ts +14 -0
- package/dist/types/callers/compat/nuxtjsI18n.d.ts.map +1 -0
- package/dist/types/callers/compat/svelteI18n.d.ts +5 -0
- package/dist/types/callers/compat/svelteI18n.d.ts.map +1 -0
- package/dist/types/callers/index.d.ts +5 -2
- package/dist/types/callers/index.d.ts.map +1 -1
- package/dist/types/callers/transform.d.ts +11 -0
- package/dist/types/callers/transform.d.ts.map +1 -1
- package/dist/types/client.d.ts +2 -2
- package/dist/types/configFile/buildBrowserConfiguration.d.ts +10 -0
- package/dist/types/configFile/buildBrowserConfiguration.d.ts.map +1 -1
- package/dist/types/configFile/buildConfigurationFields.d.ts.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loadEnvFile.cjs","names":["existsSync","statSync"],"sources":["../../src/loadEnvFile.ts"],"sourcesContent":["import { existsSync, statSync } from 'node:fs';\nimport dotenv from 'dotenv';\n\nconst DEFAULT_ENV = process.env.NODE_ENV ?? 'development';\n\nexport type LoadEnvFileOptions = {\n env?: string;\n envFile?: string;\n};\n\nexport const getEnvFilePath = (\n env: string = process.env.NODE_ENV ?? 'development',\n envFile?: string\n): string | undefined => {\n const envFiles = envFile\n ? [envFile]\n : [`.env.${env}.local`, `.env.${env}`, '.env.local', '.env'];\n\n return envFiles.find(existsSync); // Returns the first existing env file\n};\n\ntype EnvFileCacheEntry = {\n /** The env file that was resolved and parsed (undefined if none exists). */\n envFilePath: string | undefined;\n /** Fingerprint of the parsed file, used to detect edits. */\n mtimeMs: number;\n size: number;\n /** The parsed env variables. */\n parsedEnv: Record<string, string>;\n};\n\n/**\n * Cache of parsed env files keyed by `cwd|env|envFile`. Loading content\n * declarations calls `loadEnvFile` once per file; without this every call pays\n * up to 4 `existsSync` probes plus a dotenv read+parse. A cached hit is\n * validated with a single `stat` so edits to the env file are still picked up.\n */\nconst envFileCache = new Map<string, EnvFileCacheEntry>();\n\nconst parseEnvFile = (envFilePath: string): Record<string, string> => {\n const parsedEnv: Record<string, string> = {};\n\n dotenv.config({\n path: envFilePath,\n processEnv: parsedEnv,\n quiet: true,\n });\n\n return parsedEnv;\n};\n\nexport const loadEnvFile = (\n options?: Partial<LoadEnvFileOptions>\n): Record<string, string> => {\n const env = options?.env ?? DEFAULT_ENV;\n\n // Env file candidates are resolved relative to the working directory\n const cacheKey = `${process.cwd()}|${env}|${options?.envFile ?? ''}`;\n\n const cachedEntry = envFileCache.get(cacheKey);\n\n if (cachedEntry) {\n if (cachedEntry.envFilePath === undefined) {\n // No env file existed. Re-probe cheaply in case one was created since.\n const envFilePath = getEnvFilePath(env, options?.envFile);\n if (!envFilePath) return cachedEntry.parsedEnv;\n } else {\n try {\n const stats = statSync(cachedEntry.envFilePath);\n if (\n stats.mtimeMs === cachedEntry.mtimeMs &&\n stats.size === cachedEntry.size\n ) {\n return cachedEntry.parsedEnv;\n }\n } catch {\n // File was removed — fall through and re-resolve\n }\n }\n }\n\n const envFilePath = getEnvFilePath(env, options?.envFile);\n\n if (!envFilePath) {\n envFileCache.set(cacheKey, {\n envFilePath: undefined,\n mtimeMs: 0,\n size: 0,\n parsedEnv: {},\n });\n return {};\n }\n\n const parsedEnv = parseEnvFile(envFilePath);\n\n try {\n const stats = statSync(envFilePath);\n envFileCache.set(cacheKey, {\n envFilePath,\n mtimeMs: stats.mtimeMs,\n size: stats.size,\n parsedEnv,\n });\n } catch {\n // Race: file removed between parse and stat — skip caching this round\n }\n\n return parsedEnv; // Return the parsed env object\n};\n"],"mappings":";;;;;;;AAGA,MAAM,
|
|
1
|
+
{"version":3,"file":"loadEnvFile.cjs","names":["existsSync","statSync"],"sources":["../../src/loadEnvFile.ts"],"sourcesContent":["import { existsSync, statSync } from 'node:fs';\nimport dotenv from 'dotenv';\n\nconst DEFAULT_ENV = process.env.NODE_ENV ?? 'development';\n\nexport type LoadEnvFileOptions = {\n env?: string;\n envFile?: string;\n};\n\nexport const getEnvFilePath = (\n env: string = process.env.NODE_ENV ?? 'development',\n envFile?: string\n): string | undefined => {\n const envFiles = envFile\n ? [envFile]\n : [`.env.${env}.local`, `.env.${env}`, '.env.local', '.env'];\n\n return envFiles.find(existsSync); // Returns the first existing env file\n};\n\ntype EnvFileCacheEntry = {\n /** The env file that was resolved and parsed (undefined if none exists). */\n envFilePath: string | undefined;\n /** Fingerprint of the parsed file, used to detect edits. */\n mtimeMs: number;\n size: number;\n /** The parsed env variables. */\n parsedEnv: Record<string, string>;\n};\n\n/**\n * Cache of parsed env files keyed by `cwd|env|envFile`. Loading content\n * declarations calls `loadEnvFile` once per file; without this every call pays\n * up to 4 `existsSync` probes plus a dotenv read+parse. A cached hit is\n * validated with a single `stat` so edits to the env file are still picked up.\n */\nconst envFileCache = new Map<string, EnvFileCacheEntry>();\n\nconst parseEnvFile = (envFilePath: string): Record<string, string> => {\n const parsedEnv: Record<string, string> = {};\n\n dotenv.config({\n path: envFilePath,\n processEnv: parsedEnv,\n quiet: true,\n });\n\n return parsedEnv;\n};\n\nexport const loadEnvFile = (\n options?: Partial<LoadEnvFileOptions>\n): Record<string, string> => {\n const env = options?.env ?? DEFAULT_ENV;\n\n // Env file candidates are resolved relative to the working directory\n const cacheKey = `${process.cwd()}|${env}|${options?.envFile ?? ''}`;\n\n const cachedEntry = envFileCache.get(cacheKey);\n\n if (cachedEntry) {\n if (cachedEntry.envFilePath === undefined) {\n // No env file existed. Re-probe cheaply in case one was created since.\n const envFilePath = getEnvFilePath(env, options?.envFile);\n if (!envFilePath) return cachedEntry.parsedEnv;\n } else {\n try {\n const stats = statSync(cachedEntry.envFilePath);\n if (\n stats.mtimeMs === cachedEntry.mtimeMs &&\n stats.size === cachedEntry.size\n ) {\n return cachedEntry.parsedEnv;\n }\n } catch {\n // File was removed — fall through and re-resolve\n }\n }\n }\n\n const envFilePath = getEnvFilePath(env, options?.envFile);\n\n if (!envFilePath) {\n envFileCache.set(cacheKey, {\n envFilePath: undefined,\n mtimeMs: 0,\n size: 0,\n parsedEnv: {},\n });\n return {};\n }\n\n const parsedEnv = parseEnvFile(envFilePath);\n\n try {\n const stats = statSync(envFilePath);\n envFileCache.set(cacheKey, {\n envFilePath,\n mtimeMs: stats.mtimeMs,\n size: stats.size,\n parsedEnv,\n });\n } catch {\n // Race: file removed between parse and stat — skip caching this round\n }\n\n return parsedEnv; // Return the parsed env object\n};\n"],"mappings":";;;;;;;AAGA,MAAM,sCAAsC;AAO5C,MAAa,kBACX,8BAAsC,eACtC,YACuB;CAKvB,QAJiB,UACb,CAAC,OAAO,IACR;EAAC,QAAQ,IAAI;EAAS,QAAQ;EAAO;EAAc;CAAM,EAE9C,CAAC,KAAKA,kBAAU;AACjC;;;;;;;AAkBA,MAAM,+BAAe,IAAI,IAA+B;AAExD,MAAM,gBAAgB,gBAAgD;CACpE,MAAM,YAAoC,CAAC;CAE3C,eAAO,OAAO;EACZ,MAAM;EACN,YAAY;EACZ,OAAO;CACT,CAAC;CAED,OAAO;AACT;AAEA,MAAa,eACX,YAC2B;CAC3B,MAAM,MAAM,SAAS,OAAO;CAG5B,MAAM,WAAW,GAAG,QAAQ,IAAI,EAAE,GAAG,IAAI,GAAG,SAAS,WAAW;CAEhE,MAAM,cAAc,aAAa,IAAI,QAAQ;CAE7C,IAAI,aAAa;EACf,IAAI,YAAY,gBAAgB,QAG9B;OAAI,CADgB,eAAe,KAAK,SAAS,OAClC,GAAG,OAAO,YAAY;EAAS,OAE9C,IAAI;GACF,MAAM,YAAQC,kBAAS,YAAY,WAAW;GAC9C,IACE,MAAM,YAAY,YAAY,WAC9B,MAAM,SAAS,YAAY,MAE3B,OAAO,YAAY;EAEvB,QAAQ,CAER;CAEJ;CAEA,MAAM,cAAc,eAAe,KAAK,SAAS,OAAO;CAExD,IAAI,CAAC,aAAa;EAChB,aAAa,IAAI,UAAU;GACzB,aAAa;GACb,SAAS;GACT,MAAM;GACN,WAAW,CAAC;EACd,CAAC;EACD,OAAO,CAAC;CACV;CAEA,MAAM,YAAY,aAAa,WAAW;CAE1C,IAAI;EACF,MAAM,YAAQA,kBAAS,WAAW;EAClC,aAAa,IAAI,UAAU;GACzB;GACA,SAAS,MAAM;GACf,MAAM,MAAM;GACZ;EACF,CAAC;CACH,QAAQ,CAER;CAEA,OAAO;AACT"}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
//#region src/callers/compat/ngxTranslate.ts
|
|
2
|
+
/**
|
|
3
|
+
* @ngx-translate/core — `@intlayer/ngx-translate` compat adapter.
|
|
4
|
+
*
|
|
5
|
+
* ngx-translate keys are namespace-less dotted paths (`'HOME.TITLE'`), so the
|
|
6
|
+
* dictionary is the key's first dot-segment and the rest is the field path.
|
|
7
|
+
*
|
|
8
|
+
* Covered call shapes:
|
|
9
|
+
* - `translate('home.title')` — standalone signal helper
|
|
10
|
+
* - `this.translate.instant('home.title')` / `.get(…)` / `.stream(…)` /
|
|
11
|
+
* `.translate(…)` — `TranslateService` methods
|
|
12
|
+
*
|
|
13
|
+
* The `| translate` pipe and `[translate]` directive live in Angular templates
|
|
14
|
+
* that no JS analyser sees; the adapter's bundler plugin therefore widens these
|
|
15
|
+
* descriptors to `translationFunction: 'all'` for field pruning, while editors
|
|
16
|
+
* keep the precise `'self'` resolution below.
|
|
17
|
+
*
|
|
18
|
+
* No caller carries a build-time replacement: `TranslateService` is resolved
|
|
19
|
+
* through Angular DI, not an import rename.
|
|
20
|
+
*
|
|
21
|
+
* Mirrors `compat-comming/ngx-translate/src/plugin/index.ts`.
|
|
22
|
+
*/
|
|
23
|
+
const NGX_TRANSLATE_IMPORT_SOURCES = ["@ngx-translate/core", "@intlayer/ngx-translate"];
|
|
24
|
+
const createKeyCaller = (callerName, matchAsMethod) => ({
|
|
25
|
+
callerName,
|
|
26
|
+
library: "@ngx-translate/core",
|
|
27
|
+
importSources: NGX_TRANSLATE_IMPORT_SOURCES,
|
|
28
|
+
requiresImport: true,
|
|
29
|
+
matchAsMethod,
|
|
30
|
+
namespaceSources: [{ from: "path-first-segment" }],
|
|
31
|
+
translationFunction: "self"
|
|
32
|
+
});
|
|
33
|
+
const NGX_TRANSLATE_CALLERS = [
|
|
34
|
+
createKeyCaller("translate", true),
|
|
35
|
+
createKeyCaller("instant", true),
|
|
36
|
+
createKeyCaller("get", true),
|
|
37
|
+
createKeyCaller("stream", true)
|
|
38
|
+
];
|
|
39
|
+
|
|
40
|
+
//#endregion
|
|
41
|
+
export { NGX_TRANSLATE_CALLERS };
|
|
42
|
+
//# sourceMappingURL=ngxTranslate.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ngxTranslate.mjs","names":[],"sources":["../../../../src/callers/compat/ngxTranslate.ts"],"sourcesContent":["import type { CallerDescriptor } from '../types';\n\n/**\n * @ngx-translate/core — `@intlayer/ngx-translate` compat adapter.\n *\n * ngx-translate keys are namespace-less dotted paths (`'HOME.TITLE'`), so the\n * dictionary is the key's first dot-segment and the rest is the field path.\n *\n * Covered call shapes:\n * - `translate('home.title')` — standalone signal helper\n * - `this.translate.instant('home.title')` / `.get(…)` / `.stream(…)` /\n * `.translate(…)` — `TranslateService` methods\n *\n * The `| translate` pipe and `[translate]` directive live in Angular templates\n * that no JS analyser sees; the adapter's bundler plugin therefore widens these\n * descriptors to `translationFunction: 'all'` for field pruning, while editors\n * keep the precise `'self'` resolution below.\n *\n * No caller carries a build-time replacement: `TranslateService` is resolved\n * through Angular DI, not an import rename.\n *\n * Mirrors `compat-comming/ngx-translate/src/plugin/index.ts`.\n */\nconst NGX_TRANSLATE_IMPORT_SOURCES = [\n '@ngx-translate/core',\n '@intlayer/ngx-translate',\n];\n\nconst createKeyCaller = (\n callerName: string,\n matchAsMethod: boolean\n): CallerDescriptor => ({\n callerName,\n library: '@ngx-translate/core',\n importSources: NGX_TRANSLATE_IMPORT_SOURCES,\n // `get`, `instant`, `translate` are generic names — only files importing\n // ngx-translate participate.\n requiresImport: true,\n matchAsMethod,\n namespaceSources: [{ from: 'path-first-segment' }],\n translationFunction: 'self',\n});\n\nexport const NGX_TRANSLATE_CALLERS: CallerDescriptor[] = [\n createKeyCaller('translate', true),\n createKeyCaller('instant', true),\n createKeyCaller('get', true),\n createKeyCaller('stream', true),\n];\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAuBA,MAAM,+BAA+B,CACnC,uBACA,yBACF;AAEA,MAAM,mBACJ,YACA,mBACsB;CACtB;CACA,SAAS;CACT,eAAe;CAGf,gBAAgB;CAChB;CACA,kBAAkB,CAAC,EAAE,MAAM,qBAAqB,CAAC;CACjD,qBAAqB;AACvB;AAEA,MAAa,wBAA4C;CACvD,gBAAgB,aAAa,IAAI;CACjC,gBAAgB,WAAW,IAAI;CAC/B,gBAAgB,OAAO,IAAI;CAC3B,gBAAgB,UAAU,IAAI;AAChC"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
//#region src/callers/compat/nuxtjsI18n.ts
|
|
2
|
+
/**
|
|
3
|
+
* @nuxtjs/i18n — `@intlayer/nuxtjs-i18n` compat adapter.
|
|
4
|
+
*
|
|
5
|
+
* `useI18n()` is vue-i18n's composer (plus Nuxt routing helpers), imported
|
|
6
|
+
* explicitly from `#i18n` or auto-imported by the Nuxt module from the
|
|
7
|
+
* adapter's runtime entry.
|
|
8
|
+
*
|
|
9
|
+
* Mirrors `compat-comming/nuxtjs-i18n/src/module.ts`.
|
|
10
|
+
*/
|
|
11
|
+
const NUXTJS_I18N_CALLERS = [{
|
|
12
|
+
callerName: "useI18n",
|
|
13
|
+
library: "@nuxtjs/i18n",
|
|
14
|
+
importSources: [
|
|
15
|
+
"#i18n",
|
|
16
|
+
"#imports",
|
|
17
|
+
"@intlayer/nuxtjs-i18n/runtime"
|
|
18
|
+
],
|
|
19
|
+
namespaceSources: [{
|
|
20
|
+
from: "option",
|
|
21
|
+
argumentIndex: 0,
|
|
22
|
+
property: "namespace"
|
|
23
|
+
}],
|
|
24
|
+
translationFunction: "destructured-t",
|
|
25
|
+
allowRootScope: true,
|
|
26
|
+
staticReplacement: "useDictionary",
|
|
27
|
+
dynamicReplacement: "useDictionaryDynamic"
|
|
28
|
+
}];
|
|
29
|
+
|
|
30
|
+
//#endregion
|
|
31
|
+
export { NUXTJS_I18N_CALLERS };
|
|
32
|
+
//# sourceMappingURL=nuxtjsI18n.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"nuxtjsI18n.mjs","names":[],"sources":["../../../../src/callers/compat/nuxtjsI18n.ts"],"sourcesContent":["import type { CallerDescriptor } from '../types';\n\n/**\n * @nuxtjs/i18n — `@intlayer/nuxtjs-i18n` compat adapter.\n *\n * `useI18n()` is vue-i18n's composer (plus Nuxt routing helpers), imported\n * explicitly from `#i18n` or auto-imported by the Nuxt module from the\n * adapter's runtime entry.\n *\n * Mirrors `compat-comming/nuxtjs-i18n/src/module.ts`.\n */\nexport const NUXTJS_I18N_CALLERS: CallerDescriptor[] = [\n {\n callerName: 'useI18n',\n library: '@nuxtjs/i18n',\n // Every module listed here must also export the two replacements below:\n // `#i18n` aliases the runtime entry, and the Nuxt module registers\n // `useDictionary` / `useDictionaryDynamic` as `#imports` auto-imports.\n importSources: ['#i18n', '#imports', '@intlayer/nuxtjs-i18n/runtime'],\n // `const { t } = useI18n({ namespace: 'ns' })` — intlayer extension of\n // vue-i18n's options object, shared with `@intlayer/vue-i18n`.\n namespaceSources: [\n { from: 'option', argumentIndex: 0, property: 'namespace' },\n ],\n translationFunction: 'destructured-t',\n // Bare `useI18n()` resolves the first key segment as the dictionary.\n allowRootScope: true,\n staticReplacement: 'useDictionary',\n dynamicReplacement: 'useDictionaryDynamic',\n },\n];\n"],"mappings":";;;;;;;;;;AAWA,MAAa,sBAA0C,CACrD;CACE,YAAY;CACZ,SAAS;CAIT,eAAe;EAAC;EAAS;EAAY;CAA+B;CAGpE,kBAAkB,CAChB;EAAE,MAAM;EAAU,eAAe;EAAG,UAAU;CAAY,CAC5D;CACA,qBAAqB;CAErB,gBAAgB;CAChB,mBAAmB;CACnB,oBAAoB;AACtB,CACF"}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
//#region src/callers/compat/svelteI18n.ts
|
|
2
|
+
/**
|
|
3
|
+
* svelte-i18n — `@intlayer/svelte-i18n` compat adapter.
|
|
4
|
+
*
|
|
5
|
+
* svelte-i18n is a single-catalog library: `$_('home.title')` names both the
|
|
6
|
+
* dictionary (`home`) and the field (`title`), so every caller reads its
|
|
7
|
+
* dictionary from the id's first dot-segment.
|
|
8
|
+
*
|
|
9
|
+
* `_` / `t` / `format` are Svelte *stores* consumed through auto-subscription
|
|
10
|
+
* (`$_(…)`), never called directly. None of them carries a build-time
|
|
11
|
+
* replacement: re-pointing the store import at a dictionary-accepting helper
|
|
12
|
+
* would break every `$_` subscription in the file. Call sites keep resolving
|
|
13
|
+
* through the runtime dictionary registry.
|
|
14
|
+
*
|
|
15
|
+
* `_` and `t` are generic names, so matching requires an import from a
|
|
16
|
+
* svelte-i18n module.
|
|
17
|
+
*
|
|
18
|
+
* Mirrors `compat-comming/svelte-i18n/src/plugin/index.ts`.
|
|
19
|
+
*/
|
|
20
|
+
const SVELTE_I18N_IMPORT_SOURCES = ["svelte-i18n", "@intlayer/svelte-i18n"];
|
|
21
|
+
const createMessageStoreCaller = (callerName) => ({
|
|
22
|
+
callerName,
|
|
23
|
+
library: "svelte-i18n",
|
|
24
|
+
importSources: SVELTE_I18N_IMPORT_SOURCES,
|
|
25
|
+
requiresImport: true,
|
|
26
|
+
namespaceSources: [{ from: "path-first-segment" }],
|
|
27
|
+
translationFunction: "self"
|
|
28
|
+
});
|
|
29
|
+
const SVELTE_I18N_CALLERS = [
|
|
30
|
+
createMessageStoreCaller("_"),
|
|
31
|
+
createMessageStoreCaller("t"),
|
|
32
|
+
createMessageStoreCaller("format"),
|
|
33
|
+
{
|
|
34
|
+
...createMessageStoreCaller("json"),
|
|
35
|
+
translationFunction: "all"
|
|
36
|
+
}
|
|
37
|
+
];
|
|
38
|
+
|
|
39
|
+
//#endregion
|
|
40
|
+
export { SVELTE_I18N_CALLERS };
|
|
41
|
+
//# sourceMappingURL=svelteI18n.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"svelteI18n.mjs","names":[],"sources":["../../../../src/callers/compat/svelteI18n.ts"],"sourcesContent":["import type { CallerDescriptor } from '../types';\n\n/**\n * svelte-i18n — `@intlayer/svelte-i18n` compat adapter.\n *\n * svelte-i18n is a single-catalog library: `$_('home.title')` names both the\n * dictionary (`home`) and the field (`title`), so every caller reads its\n * dictionary from the id's first dot-segment.\n *\n * `_` / `t` / `format` are Svelte *stores* consumed through auto-subscription\n * (`$_(…)`), never called directly. None of them carries a build-time\n * replacement: re-pointing the store import at a dictionary-accepting helper\n * would break every `$_` subscription in the file. Call sites keep resolving\n * through the runtime dictionary registry.\n *\n * `_` and `t` are generic names, so matching requires an import from a\n * svelte-i18n module.\n *\n * Mirrors `compat-comming/svelte-i18n/src/plugin/index.ts`.\n */\nconst SVELTE_I18N_IMPORT_SOURCES = ['svelte-i18n', '@intlayer/svelte-i18n'];\n\nconst createMessageStoreCaller = (callerName: string): CallerDescriptor => ({\n callerName,\n library: 'svelte-i18n',\n importSources: SVELTE_I18N_IMPORT_SOURCES,\n requiresImport: true,\n // `$_('home.title')` / `$_({ id: 'home.title' })`\n namespaceSources: [{ from: 'path-first-segment' }],\n translationFunction: 'self',\n});\n\nexport const SVELTE_I18N_CALLERS: CallerDescriptor[] = [\n createMessageStoreCaller('_'),\n createMessageStoreCaller('t'),\n createMessageStoreCaller('format'),\n // `$json('home.nav')` returns a whole subtree: every field may be read.\n {\n ...createMessageStoreCaller('json'),\n translationFunction: 'all',\n },\n];\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAoBA,MAAM,6BAA6B,CAAC,eAAe,uBAAuB;AAE1E,MAAM,4BAA4B,gBAA0C;CAC1E;CACA,SAAS;CACT,eAAe;CACf,gBAAgB;CAEhB,kBAAkB,CAAC,EAAE,MAAM,qBAAqB,CAAC;CACjD,qBAAqB;AACvB;AAEA,MAAa,sBAA0C;CACrD,yBAAyB,GAAG;CAC5B,yBAAyB,GAAG;CAC5B,yBAAyB,QAAQ;CAEjC;EACE,GAAG,yBAAyB,MAAM;EAClC,qBAAqB;CACvB;AACF"}
|
|
@@ -2,11 +2,14 @@ import { BASE_CALLERS } from "./base.mjs";
|
|
|
2
2
|
import { I18NEXT_CALLERS } from "./compat/i18next.mjs";
|
|
3
3
|
import { LINGUI_CALLERS } from "./compat/lingui.mjs";
|
|
4
4
|
import { NEXT_INTL_CALLERS } from "./compat/nextIntl.mjs";
|
|
5
|
+
import { NGX_TRANSLATE_CALLERS } from "./compat/ngxTranslate.mjs";
|
|
6
|
+
import { NUXTJS_I18N_CALLERS } from "./compat/nuxtjsI18n.mjs";
|
|
5
7
|
import { REACT_I18NEXT_CALLERS } from "./compat/reactI18next.mjs";
|
|
6
8
|
import { REACT_INTL_CALLERS } from "./compat/reactIntl.mjs";
|
|
9
|
+
import { SVELTE_I18N_CALLERS } from "./compat/svelteI18n.mjs";
|
|
7
10
|
import { USE_INTL_CALLERS } from "./compat/useIntl.mjs";
|
|
8
11
|
import { VUE_I18N_CALLERS } from "./compat/vueI18n.mjs";
|
|
9
|
-
import { getRewritableCallers, isRewritableCaller, toSwcExtraCallers } from "./transform.mjs";
|
|
12
|
+
import { getRewritableCallers, isRewritableCaller, requiresDictionaryRegistry, toSwcExtraCallers } from "./transform.mjs";
|
|
10
13
|
|
|
11
14
|
//#region src/callers/index.ts
|
|
12
15
|
/**
|
|
@@ -22,7 +25,10 @@ const COMPAT_CALLERS = [
|
|
|
22
25
|
...USE_INTL_CALLERS,
|
|
23
26
|
...REACT_INTL_CALLERS,
|
|
24
27
|
...LINGUI_CALLERS,
|
|
25
|
-
...VUE_I18N_CALLERS
|
|
28
|
+
...VUE_I18N_CALLERS,
|
|
29
|
+
...SVELTE_I18N_CALLERS,
|
|
30
|
+
...NUXTJS_I18N_CALLERS,
|
|
31
|
+
...NGX_TRANSLATE_CALLERS
|
|
26
32
|
];
|
|
27
33
|
/** Base + compat callers — the full registry the matchers run against. */
|
|
28
34
|
const ALL_CALLERS = [...BASE_CALLERS, ...COMPAT_CALLERS];
|
|
@@ -68,5 +74,5 @@ const isCallerActive = (descriptor, fileImportSources) => {
|
|
|
68
74
|
};
|
|
69
75
|
|
|
70
76
|
//#endregion
|
|
71
|
-
export { ALL_CALLERS, BASE_CALLERS, CALLERS_BY_NAME, COMPAT_CALLERS, I18NEXT_CALLERS, LINGUI_CALLERS, NEXT_INTL_CALLERS, REACT_I18NEXT_CALLERS, REACT_INTL_CALLERS, USE_INTL_CALLERS, VUE_I18N_CALLERS, getPositionalKeyCallerNames, getRewritableCallers, isCallerActive, isRewritableCaller, toSwcExtraCallers };
|
|
77
|
+
export { ALL_CALLERS, BASE_CALLERS, CALLERS_BY_NAME, COMPAT_CALLERS, I18NEXT_CALLERS, LINGUI_CALLERS, NEXT_INTL_CALLERS, NGX_TRANSLATE_CALLERS, NUXTJS_I18N_CALLERS, REACT_I18NEXT_CALLERS, REACT_INTL_CALLERS, SVELTE_I18N_CALLERS, USE_INTL_CALLERS, VUE_I18N_CALLERS, getPositionalKeyCallerNames, getRewritableCallers, isCallerActive, isRewritableCaller, requiresDictionaryRegistry, toSwcExtraCallers };
|
|
72
78
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/callers/index.ts"],"sourcesContent":["import { BASE_CALLERS } from './base';\nimport { I18NEXT_CALLERS } from './compat/i18next';\nimport { LINGUI_CALLERS } from './compat/lingui';\nimport { NEXT_INTL_CALLERS } from './compat/nextIntl';\nimport { REACT_I18NEXT_CALLERS } from './compat/reactI18next';\nimport { REACT_INTL_CALLERS } from './compat/reactIntl';\nimport { USE_INTL_CALLERS } from './compat/useIntl';\nimport { VUE_I18N_CALLERS } from './compat/vueI18n';\nimport type { CallerDescriptor } from './types';\n\nexport { BASE_CALLERS } from './base';\nexport { I18NEXT_CALLERS } from './compat/i18next';\nexport { LINGUI_CALLERS } from './compat/lingui';\nexport { NEXT_INTL_CALLERS } from './compat/nextIntl';\nexport { REACT_I18NEXT_CALLERS } from './compat/reactI18next';\nexport { REACT_INTL_CALLERS } from './compat/reactIntl';\nexport { USE_INTL_CALLERS } from './compat/useIntl';\nexport { VUE_I18N_CALLERS } from './compat/vueI18n';\nexport {\n getRewritableCallers,\n isRewritableCaller,\n type SwcExtraCallerConfig,\n toSwcExtraCallers,\n} from './transform';\nexport type {\n CallerDescriptor,\n CallerResultShape,\n CallerValueSource,\n} from './types';\n\n/**\n * Compat-adapter callers, grouped in one list. Each compat package's bundler\n * plugin injects its own slice (e.g. `REACT_I18NEXT_CALLERS`) into the build\n * pipeline; this aggregate exists for consumers that need every syntax at\n * once, such as the LSP.\n */\nexport const COMPAT_CALLERS: CallerDescriptor[] = [\n ...I18NEXT_CALLERS,\n ...REACT_I18NEXT_CALLERS,\n ...NEXT_INTL_CALLERS,\n ...USE_INTL_CALLERS,\n ...REACT_INTL_CALLERS,\n ...LINGUI_CALLERS,\n ...VUE_I18N_CALLERS,\n];\n\n/** Base + compat callers — the full registry the matchers run against. */\nexport const ALL_CALLERS: CallerDescriptor[] = [\n ...BASE_CALLERS,\n ...COMPAT_CALLERS,\n];\n\n/**\n * Descriptors indexed by caller name. A name can map to several descriptors\n * (e.g. `Trans` exists in both react-i18next and lingui with different\n * attributes); matchers try them in registry order.\n */\nexport const CALLERS_BY_NAME: Map<string, CallerDescriptor[]> = (() => {\n const byName = new Map<string, CallerDescriptor[]>();\n\n for (const descriptor of ALL_CALLERS) {\n const existing = byName.get(descriptor.callerName);\n\n if (existing) {\n existing.push(descriptor);\n } else {\n byName.set(descriptor.callerName, [descriptor]);\n }\n }\n\n return byName;\n})();\n\n/**\n * Caller names whose dictionary key can appear as a positional string literal\n * argument (`caller('key', …)` / `caller(locale, 'key', …)`). Used to build\n * text-search regexes over project source files (find-references) and the\n * completion trigger pattern. Callers whose key never appears positionally\n * (fixed namespace, options object, JSX-only) are excluded on purpose.\n */\nexport const getPositionalKeyCallerNames = (): string[] => {\n const names = new Set<string>();\n\n for (const descriptor of ALL_CALLERS) {\n const hasPositionalNamespace = descriptor.namespaceSources.some(\n (source) => source.from === 'argument'\n );\n\n if (hasPositionalNamespace) names.add(descriptor.callerName);\n }\n\n return [...names];\n};\n\n/**\n * Returns `true` when the descriptor may participate in matching for a file\n * importing from `importSources`. Descriptors flagged `requiresImport` only\n * activate when the file imports from one of their declared modules;\n * everything else is always active (results are still validated against the\n * project's dictionaries downstream).\n *\n * @param descriptor - The caller descriptor to gate.\n * @param fileImportSources - Module specifiers imported by the analysed file.\n */\nexport const isCallerActive = (\n descriptor: CallerDescriptor,\n fileImportSources: ReadonlySet<string>\n): boolean => {\n if (!descriptor.requiresImport) return true;\n\n return descriptor.importSources.some((source) =>\n fileImportSources.has(source)\n );\n};\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/callers/index.ts"],"sourcesContent":["import { BASE_CALLERS } from './base';\nimport { I18NEXT_CALLERS } from './compat/i18next';\nimport { LINGUI_CALLERS } from './compat/lingui';\nimport { NEXT_INTL_CALLERS } from './compat/nextIntl';\nimport { NGX_TRANSLATE_CALLERS } from './compat/ngxTranslate';\nimport { NUXTJS_I18N_CALLERS } from './compat/nuxtjsI18n';\nimport { REACT_I18NEXT_CALLERS } from './compat/reactI18next';\nimport { REACT_INTL_CALLERS } from './compat/reactIntl';\nimport { SVELTE_I18N_CALLERS } from './compat/svelteI18n';\nimport { USE_INTL_CALLERS } from './compat/useIntl';\nimport { VUE_I18N_CALLERS } from './compat/vueI18n';\nimport type { CallerDescriptor } from './types';\n\nexport { BASE_CALLERS } from './base';\nexport { I18NEXT_CALLERS } from './compat/i18next';\nexport { LINGUI_CALLERS } from './compat/lingui';\nexport { NEXT_INTL_CALLERS } from './compat/nextIntl';\nexport { NGX_TRANSLATE_CALLERS } from './compat/ngxTranslate';\nexport { NUXTJS_I18N_CALLERS } from './compat/nuxtjsI18n';\nexport { REACT_I18NEXT_CALLERS } from './compat/reactI18next';\nexport { REACT_INTL_CALLERS } from './compat/reactIntl';\nexport { SVELTE_I18N_CALLERS } from './compat/svelteI18n';\nexport { USE_INTL_CALLERS } from './compat/useIntl';\nexport { VUE_I18N_CALLERS } from './compat/vueI18n';\nexport {\n getRewritableCallers,\n isRewritableCaller,\n requiresDictionaryRegistry,\n type SwcExtraCallerConfig,\n toSwcExtraCallers,\n} from './transform';\nexport type {\n CallerDescriptor,\n CallerResultShape,\n CallerValueSource,\n} from './types';\n\n/**\n * Compat-adapter callers, grouped in one list. Each compat package's bundler\n * plugin injects its own slice (e.g. `REACT_I18NEXT_CALLERS`) into the build\n * pipeline; this aggregate exists for consumers that need every syntax at\n * once, such as the LSP.\n */\nexport const COMPAT_CALLERS: CallerDescriptor[] = [\n ...I18NEXT_CALLERS,\n ...REACT_I18NEXT_CALLERS,\n ...NEXT_INTL_CALLERS,\n ...USE_INTL_CALLERS,\n ...REACT_INTL_CALLERS,\n ...LINGUI_CALLERS,\n ...VUE_I18N_CALLERS,\n ...SVELTE_I18N_CALLERS,\n ...NUXTJS_I18N_CALLERS,\n ...NGX_TRANSLATE_CALLERS,\n];\n\n/** Base + compat callers — the full registry the matchers run against. */\nexport const ALL_CALLERS: CallerDescriptor[] = [\n ...BASE_CALLERS,\n ...COMPAT_CALLERS,\n];\n\n/**\n * Descriptors indexed by caller name. A name can map to several descriptors\n * (e.g. `Trans` exists in both react-i18next and lingui with different\n * attributes); matchers try them in registry order.\n */\nexport const CALLERS_BY_NAME: Map<string, CallerDescriptor[]> = (() => {\n const byName = new Map<string, CallerDescriptor[]>();\n\n for (const descriptor of ALL_CALLERS) {\n const existing = byName.get(descriptor.callerName);\n\n if (existing) {\n existing.push(descriptor);\n } else {\n byName.set(descriptor.callerName, [descriptor]);\n }\n }\n\n return byName;\n})();\n\n/**\n * Caller names whose dictionary key can appear as a positional string literal\n * argument (`caller('key', …)` / `caller(locale, 'key', …)`). Used to build\n * text-search regexes over project source files (find-references) and the\n * completion trigger pattern. Callers whose key never appears positionally\n * (fixed namespace, options object, JSX-only) are excluded on purpose.\n */\nexport const getPositionalKeyCallerNames = (): string[] => {\n const names = new Set<string>();\n\n for (const descriptor of ALL_CALLERS) {\n const hasPositionalNamespace = descriptor.namespaceSources.some(\n (source) => source.from === 'argument'\n );\n\n if (hasPositionalNamespace) names.add(descriptor.callerName);\n }\n\n return [...names];\n};\n\n/**\n * Returns `true` when the descriptor may participate in matching for a file\n * importing from `importSources`. Descriptors flagged `requiresImport` only\n * activate when the file imports from one of their declared modules;\n * everything else is always active (results are still validated against the\n * project's dictionaries downstream).\n *\n * @param descriptor - The caller descriptor to gate.\n * @param fileImportSources - Module specifiers imported by the analysed file.\n */\nexport const isCallerActive = (\n descriptor: CallerDescriptor,\n fileImportSources: ReadonlySet<string>\n): boolean => {\n if (!descriptor.requiresImport) return true;\n\n return descriptor.importSources.some((source) =>\n fileImportSources.has(source)\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA2CA,MAAa,iBAAqC;CAChD,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;CACH,GAAG;AACL;;AAGA,MAAa,cAAkC,CAC7C,GAAG,cACH,GAAG,cACL;;;;;;AAOA,MAAa,yBAA0D;CACrE,MAAM,yBAAS,IAAI,IAAgC;CAEnD,KAAK,MAAM,cAAc,aAAa;EACpC,MAAM,WAAW,OAAO,IAAI,WAAW,UAAU;EAEjD,IAAI,UACF,SAAS,KAAK,UAAU;OAExB,OAAO,IAAI,WAAW,YAAY,CAAC,UAAU,CAAC;CAElD;CAEA,OAAO;AACT,EAAC,CAAE;;;;;;;;AASH,MAAa,oCAA8C;CACzD,MAAM,wBAAQ,IAAI,IAAY;CAE9B,KAAK,MAAM,cAAc,aAKvB,IAJ+B,WAAW,iBAAiB,MACxD,WAAW,OAAO,SAAS,UAGL,GAAG,MAAM,IAAI,WAAW,UAAU;CAG7D,OAAO,CAAC,GAAG,KAAK;AAClB;;;;;;;;;;;AAYA,MAAa,kBACX,YACA,sBACY;CACZ,IAAI,CAAC,WAAW,gBAAgB,OAAO;CAEvC,OAAO,WAAW,cAAc,MAAM,WACpC,kBAAkB,IAAI,MAAM,CAC9B;AACF"}
|
|
@@ -11,6 +11,17 @@
|
|
|
11
11
|
*/
|
|
12
12
|
const isRewritableCaller = (descriptor) => descriptor.staticReplacement !== void 0 && descriptor.dynamicReplacement !== void 0 && descriptor.matchAsMethod !== true;
|
|
13
13
|
/**
|
|
14
|
+
* Whether a registry slice leaves call sites that resolve through the runtime
|
|
15
|
+
* dictionary registry (`@intlayer/dictionaries-entry`) in an optimized build.
|
|
16
|
+
*
|
|
17
|
+
* That is the case for callers the optimize pass never rewrites (message-id
|
|
18
|
+
* callers such as svelte-i18n's `$_` or ngx-translate's `instant`) and for
|
|
19
|
+
* root-scope callers (a bare `useI18n()`), whose dictionary is only known
|
|
20
|
+
* from each key at runtime. The build must then keep the registry instead of
|
|
21
|
+
* replacing it with an empty map.
|
|
22
|
+
*/
|
|
23
|
+
const requiresDictionaryRegistry = (descriptors) => descriptors.some((descriptor) => !isRewritableCaller(descriptor) || descriptor.allowRootScope === true);
|
|
24
|
+
/**
|
|
14
25
|
* Returns the callers of a registry slice that the optimize pass can rewrite
|
|
15
26
|
* at build time. See {@link isRewritableCaller}.
|
|
16
27
|
*/
|
|
@@ -47,5 +58,5 @@ const toSwcExtraCallers = (descriptors) => getRewritableCallers(descriptors).fla
|
|
|
47
58
|
});
|
|
48
59
|
|
|
49
60
|
//#endregion
|
|
50
|
-
export { getRewritableCallers, isRewritableCaller, toSwcExtraCallers };
|
|
61
|
+
export { getRewritableCallers, isRewritableCaller, requiresDictionaryRegistry, toSwcExtraCallers };
|
|
51
62
|
//# sourceMappingURL=transform.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transform.mjs","names":[],"sources":["../../../src/callers/transform.ts"],"sourcesContent":["import type { CallerDescriptor, CallerValueSource } from './types';\n\n/**\n * Wire format of an extra caller forwarded to the `@intlayer/swc` plugin.\n *\n * Field names mirror the serde attributes of `ExtraCallerConfig` in\n * `packages/@intlayer/swc/src/lib.rs` — both sides must stay in sync.\n */\nexport type SwcExtraCallerConfig = {\n /** The function name the user calls, e.g. `\"useTranslation\"`. */\n callerName: string;\n /** Module specifiers exporting the function (original + `@intlayer/*`). */\n importSources: string[];\n /**\n * Zero-based index of the positional argument holding the namespace string.\n * Omitted for fixed/option namespace callers.\n */\n namespaceArgIndex?: number;\n /**\n * Compile-time constant namespace — the dictionary ident is inserted as a\n * new first argument (lingui's `useLingui()`).\n */\n fixedNamespace?: string;\n /**\n * Namespace read from a property of an options-object argument — the\n * dictionary ident is inserted as a new first argument and the property is\n * rewritten to the key-prefix remainder (vue-i18n's `useI18n({ namespace })`).\n */\n namespaceOption?: { argumentIndex: number; property: string };\n /** Replacement function name for static import mode, e.g. `\"useDictionary\"`. */\n staticReplacement: string;\n /** Replacement function name for dynamic/fetch mode, e.g. `\"useDictionaryDynamic\"`. */\n dynamicReplacement: string;\n};\n\n/**\n * Whether the optimize pass can rewrite this caller's call sites at build time.\n *\n * Requires both replacement names and a call shape reachable through an import\n * specifier rename: a plain imported function, or a JSX component whose\n * element receives the dictionary as a prop (lingui's `<Trans>`).\n * Method-matched callers (`i18n.getFixedT`, `intl.formatMessage`) are\n * excluded — their call sites keep resolving through the runtime dictionary\n * registry.\n */\nexport const isRewritableCaller = (descriptor: CallerDescriptor): boolean =>\n descriptor.staticReplacement !== undefined &&\n descriptor.dynamicReplacement !== undefined &&\n descriptor.matchAsMethod !== true;\n\n/**\n * Returns the callers of a registry slice that the optimize pass can rewrite\n * at build time. See {@link isRewritableCaller}.\n */\nexport const getRewritableCallers = (\n descriptors: CallerDescriptor[]\n): CallerDescriptor[] => descriptors.filter(isRewritableCaller);\n\nconst findSource = <F extends CallerValueSource['from']>(\n sources: CallerValueSource[],\n from: F\n): Extract<CallerValueSource, { from: F }> | undefined =>\n sources.find(\n (source): source is Extract<CallerValueSource, { from: F }> =>\n source.from === from\n );\n\n/**\n * Serialises the rewritable callers of a registry slice into the\n * `@intlayer/swc` plugin wire format (`extraCallers` option).\n *\n * A caller with no statically readable namespace source is dropped: the plugin\n * binds a dictionary from an argument, an option property or a fixed value\n * only, so forwarding it would emit a descriptor no call site can match.\n *\n * @param descriptors - Registry slice, e.g. `REACT_I18NEXT_CALLERS`.\n * @returns Configs ready to pass as the plugin's `extraCallers` option.\n */\nexport const toSwcExtraCallers = (\n descriptors: CallerDescriptor[]\n): SwcExtraCallerConfig[] =>\n getRewritableCallers(descriptors).flatMap((descriptor) => {\n const argumentSource = findSource(descriptor.namespaceSources, 'argument');\n const optionSource = findSource(descriptor.namespaceSources, 'option');\n const fixedSource = findSource(descriptor.namespaceSources, 'fixed');\n\n if (!argumentSource && !optionSource && !fixedSource) return [];\n\n return [\n {\n callerName: descriptor.callerName,\n importSources: descriptor.importSources,\n ...(argumentSource ? { namespaceArgIndex: argumentSource.index } : {}),\n ...(fixedSource ? { fixedNamespace: fixedSource.value } : {}),\n ...(optionSource\n ? {\n namespaceOption: {\n argumentIndex: optionSource.argumentIndex,\n property: optionSource.property,\n },\n }\n : {}),\n staticReplacement: descriptor.staticReplacement!,\n dynamicReplacement: descriptor.dynamicReplacement!,\n },\n ];\n });\n"],"mappings":";;;;;;;;;;;AA6CA,MAAa,sBAAsB,eACjC,WAAW,sBAAsB,UACjC,WAAW,uBAAuB,UAClC,WAAW,kBAAkB
|
|
1
|
+
{"version":3,"file":"transform.mjs","names":[],"sources":["../../../src/callers/transform.ts"],"sourcesContent":["import type { CallerDescriptor, CallerValueSource } from './types';\n\n/**\n * Wire format of an extra caller forwarded to the `@intlayer/swc` plugin.\n *\n * Field names mirror the serde attributes of `ExtraCallerConfig` in\n * `packages/@intlayer/swc/src/lib.rs` — both sides must stay in sync.\n */\nexport type SwcExtraCallerConfig = {\n /** The function name the user calls, e.g. `\"useTranslation\"`. */\n callerName: string;\n /** Module specifiers exporting the function (original + `@intlayer/*`). */\n importSources: string[];\n /**\n * Zero-based index of the positional argument holding the namespace string.\n * Omitted for fixed/option namespace callers.\n */\n namespaceArgIndex?: number;\n /**\n * Compile-time constant namespace — the dictionary ident is inserted as a\n * new first argument (lingui's `useLingui()`).\n */\n fixedNamespace?: string;\n /**\n * Namespace read from a property of an options-object argument — the\n * dictionary ident is inserted as a new first argument and the property is\n * rewritten to the key-prefix remainder (vue-i18n's `useI18n({ namespace })`).\n */\n namespaceOption?: { argumentIndex: number; property: string };\n /** Replacement function name for static import mode, e.g. `\"useDictionary\"`. */\n staticReplacement: string;\n /** Replacement function name for dynamic/fetch mode, e.g. `\"useDictionaryDynamic\"`. */\n dynamicReplacement: string;\n};\n\n/**\n * Whether the optimize pass can rewrite this caller's call sites at build time.\n *\n * Requires both replacement names and a call shape reachable through an import\n * specifier rename: a plain imported function, or a JSX component whose\n * element receives the dictionary as a prop (lingui's `<Trans>`).\n * Method-matched callers (`i18n.getFixedT`, `intl.formatMessage`) are\n * excluded — their call sites keep resolving through the runtime dictionary\n * registry.\n */\nexport const isRewritableCaller = (descriptor: CallerDescriptor): boolean =>\n descriptor.staticReplacement !== undefined &&\n descriptor.dynamicReplacement !== undefined &&\n descriptor.matchAsMethod !== true;\n\n/**\n * Whether a registry slice leaves call sites that resolve through the runtime\n * dictionary registry (`@intlayer/dictionaries-entry`) in an optimized build.\n *\n * That is the case for callers the optimize pass never rewrites (message-id\n * callers such as svelte-i18n's `$_` or ngx-translate's `instant`) and for\n * root-scope callers (a bare `useI18n()`), whose dictionary is only known\n * from each key at runtime. The build must then keep the registry instead of\n * replacing it with an empty map.\n */\nexport const requiresDictionaryRegistry = (\n descriptors: readonly CallerDescriptor[]\n): boolean =>\n descriptors.some(\n (descriptor) =>\n !isRewritableCaller(descriptor) || descriptor.allowRootScope === true\n );\n\n/**\n * Returns the callers of a registry slice that the optimize pass can rewrite\n * at build time. See {@link isRewritableCaller}.\n */\nexport const getRewritableCallers = (\n descriptors: CallerDescriptor[]\n): CallerDescriptor[] => descriptors.filter(isRewritableCaller);\n\nconst findSource = <F extends CallerValueSource['from']>(\n sources: CallerValueSource[],\n from: F\n): Extract<CallerValueSource, { from: F }> | undefined =>\n sources.find(\n (source): source is Extract<CallerValueSource, { from: F }> =>\n source.from === from\n );\n\n/**\n * Serialises the rewritable callers of a registry slice into the\n * `@intlayer/swc` plugin wire format (`extraCallers` option).\n *\n * A caller with no statically readable namespace source is dropped: the plugin\n * binds a dictionary from an argument, an option property or a fixed value\n * only, so forwarding it would emit a descriptor no call site can match.\n *\n * @param descriptors - Registry slice, e.g. `REACT_I18NEXT_CALLERS`.\n * @returns Configs ready to pass as the plugin's `extraCallers` option.\n */\nexport const toSwcExtraCallers = (\n descriptors: CallerDescriptor[]\n): SwcExtraCallerConfig[] =>\n getRewritableCallers(descriptors).flatMap((descriptor) => {\n const argumentSource = findSource(descriptor.namespaceSources, 'argument');\n const optionSource = findSource(descriptor.namespaceSources, 'option');\n const fixedSource = findSource(descriptor.namespaceSources, 'fixed');\n\n if (!argumentSource && !optionSource && !fixedSource) return [];\n\n return [\n {\n callerName: descriptor.callerName,\n importSources: descriptor.importSources,\n ...(argumentSource ? { namespaceArgIndex: argumentSource.index } : {}),\n ...(fixedSource ? { fixedNamespace: fixedSource.value } : {}),\n ...(optionSource\n ? {\n namespaceOption: {\n argumentIndex: optionSource.argumentIndex,\n property: optionSource.property,\n },\n }\n : {}),\n staticReplacement: descriptor.staticReplacement!,\n dynamicReplacement: descriptor.dynamicReplacement!,\n },\n ];\n });\n"],"mappings":";;;;;;;;;;;AA6CA,MAAa,sBAAsB,eACjC,WAAW,sBAAsB,UACjC,WAAW,uBAAuB,UAClC,WAAW,kBAAkB;;;;;;;;;;;AAY/B,MAAa,8BACX,gBAEA,YAAY,MACT,eACC,CAAC,mBAAmB,UAAU,KAAK,WAAW,mBAAmB,IACrE;;;;;AAMF,MAAa,wBACX,gBACuB,YAAY,OAAO,kBAAkB;AAE9D,MAAM,cACJ,SACA,SAEA,QAAQ,MACL,WACC,OAAO,SAAS,IACpB;;;;;;;;;;;;AAaF,MAAa,qBACX,gBAEA,qBAAqB,WAAW,CAAC,CAAC,SAAS,eAAe;CACxD,MAAM,iBAAiB,WAAW,WAAW,kBAAkB,UAAU;CACzE,MAAM,eAAe,WAAW,WAAW,kBAAkB,QAAQ;CACrE,MAAM,cAAc,WAAW,WAAW,kBAAkB,OAAO;CAEnE,IAAI,CAAC,kBAAkB,CAAC,gBAAgB,CAAC,aAAa,OAAO,CAAC;CAE9D,OAAO,CACL;EACE,YAAY,WAAW;EACvB,eAAe,WAAW;EAC1B,GAAI,iBAAiB,EAAE,mBAAmB,eAAe,MAAM,IAAI,CAAC;EACpE,GAAI,cAAc,EAAE,gBAAgB,YAAY,MAAM,IAAI,CAAC;EAC3D,GAAI,eACA,EACE,iBAAiB;GACf,eAAe,aAAa;GAC5B,UAAU,aAAa;EACzB,EACF,IACA,CAAC;EACL,mBAAmB,WAAW;EAC9B,oBAAoB,WAAW;CACjC,CACF;AACF,CAAC"}
|
package/dist/esm/client.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { buildAnalyticsFields, buildBrowserConfiguration, buildEditorFields, buildInternationalizationFields, buildLogFields, buildRoutingFields, extractBrowserConfiguration } from "./configFile/buildBrowserConfiguration.mjs";
|
|
1
|
+
import { bindLogFunction, buildAnalyticsFields, buildBrowserConfiguration, buildEditorFields, buildInternationalizationFields, buildLogFields, buildRoutingFields, extractBrowserConfiguration } from "./configFile/buildBrowserConfiguration.mjs";
|
|
2
2
|
import { extractErrorMessage } from "./utils/extractErrorMessage.mjs";
|
|
3
3
|
import { logStack } from "./utils/logStack.mjs";
|
|
4
4
|
import { normalizePath } from "./utils/normalizePath.mjs";
|
|
@@ -8,4 +8,4 @@ import { camelCaseToSentence } from "./utils/stringFormatter/camelCaseToSentence
|
|
|
8
8
|
import { kebabCaseToCamelCase } from "./utils/stringFormatter/kebabCaseToCamelCase.mjs";
|
|
9
9
|
import { toLowerCamelCase } from "./utils/stringFormatter/toLowerCamelCase.mjs";
|
|
10
10
|
|
|
11
|
-
export { buildAnalyticsFields, buildBrowserConfiguration, buildEditorFields, buildInternationalizationFields, buildLogFields, buildRoutingFields, camelCaseToKebabCase, camelCaseToSentence, extractBrowserConfiguration, extractErrorMessage, kebabCaseToCamelCase, logStack, normalizePath, setIntlayerIdentifier, toLowerCamelCase };
|
|
11
|
+
export { bindLogFunction, buildAnalyticsFields, buildBrowserConfiguration, buildEditorFields, buildInternationalizationFields, buildLogFields, buildRoutingFields, camelCaseToKebabCase, camelCaseToSentence, extractBrowserConfiguration, extractErrorMessage, kebabCaseToCamelCase, logStack, normalizePath, setIntlayerIdentifier, toLowerCamelCase };
|
|
@@ -316,6 +316,16 @@ const buildAnalyticsFields = (customConfiguration, isPackageInstalled = true) =>
|
|
|
316
316
|
sampleRate: customConfiguration?.sampleRate ?? 1
|
|
317
317
|
});
|
|
318
318
|
/**
|
|
319
|
+
* Binds a custom log function to its owner, so logger instances whose methods
|
|
320
|
+
* read their state from `this` (e.g. pino, used as `fastify.log`) keep working
|
|
321
|
+
* once the method is detached and called on its own.
|
|
322
|
+
*
|
|
323
|
+
* @param logFunctions - The object holding the custom log functions.
|
|
324
|
+
* @param level - The log function to bind.
|
|
325
|
+
* @returns The bound function, or `undefined` when not provided.
|
|
326
|
+
*/
|
|
327
|
+
const bindLogFunction = (logFunctions, level) => logFunctions?.[level]?.bind(logFunctions);
|
|
328
|
+
/**
|
|
319
329
|
* Build the log section of the Intlayer configuration.
|
|
320
330
|
*
|
|
321
331
|
* @param customConfiguration - Partial user-supplied log config.
|
|
@@ -344,10 +354,10 @@ const buildLogFields = (customConfiguration, logFunctions) => ({
|
|
|
344
354
|
/**
|
|
345
355
|
* Functions to log
|
|
346
356
|
*/
|
|
347
|
-
error: logFunctions
|
|
348
|
-
log: logFunctions
|
|
349
|
-
info: logFunctions
|
|
350
|
-
warn: logFunctions
|
|
357
|
+
error: bindLogFunction(logFunctions, "error"),
|
|
358
|
+
log: bindLogFunction(logFunctions, "log"),
|
|
359
|
+
info: bindLogFunction(logFunctions, "info"),
|
|
360
|
+
warn: bindLogFunction(logFunctions, "warn")
|
|
351
361
|
});
|
|
352
362
|
/**
|
|
353
363
|
* Build a browser-safe {@link BrowserIntlayerConfig} from a raw user config.
|
|
@@ -427,5 +437,5 @@ const extractBrowserConfiguration = (config) => {
|
|
|
427
437
|
};
|
|
428
438
|
|
|
429
439
|
//#endregion
|
|
430
|
-
export { buildAnalyticsFields, buildBrowserConfiguration, buildEditorFields, buildInternationalizationFields, buildLogFields, buildRoutingFields, extractBrowserConfiguration };
|
|
440
|
+
export { bindLogFunction, buildAnalyticsFields, buildBrowserConfiguration, buildEditorFields, buildInternationalizationFields, buildLogFields, buildRoutingFields, extractBrowserConfiguration };
|
|
431
441
|
//# sourceMappingURL=buildBrowserConfiguration.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"buildBrowserConfiguration.mjs","names":[],"sources":["../../../src/configFile/buildBrowserConfiguration.ts"],"sourcesContent":["import type {\n AnalyticsConfig,\n CustomIntlayerConfig,\n CustomRoutingConfig,\n EditorConfig,\n InternationalizationConfig,\n IntlayerConfig,\n LogConfig,\n LogFunctions,\n RoutingConfig,\n} from '@intlayer/types/config';\nimport {\n ANALYTICS_ENABLED,\n ANALYTICS_FLUSH_INTERVAL,\n ANALYTICS_SAMPLE_RATE,\n} from '../defaultValues/analytics';\nimport {\n APPLICATION_URL,\n BACKEND_URL,\n CMS_URL,\n DICTIONARY_PRIORITY_STRATEGY,\n EDITOR_URL,\n IS_ENABLED,\n LIVE_SYNC,\n LIVE_SYNC_PORT,\n PORT,\n} from '../defaultValues/editor';\nimport {\n DEFAULT_LOCALE,\n LOCALES,\n REQUIRED_LOCALES,\n STRICT_MODE,\n} from '../defaultValues/internationalization';\nimport { MODE, PREFIX } from '../defaultValues/log';\nimport {\n BASE_PATH,\n ENABLE_PROXY,\n ROUTING_MODE,\n STORAGE,\n} from '../defaultValues/routing';\nimport { getStorageAttributes } from '../utils/getStorageAttributes';\n\n// ---------------------------------------------------------------------------\n// Type\n// ---------------------------------------------------------------------------\n\n/**\n * Browser-safe subset of {@link IntlayerConfig}.\n *\n * Excludes server-only fields (`system`, `content`, `build`, `compiler`,\n * `dictionary`, `ai`) and the `editor.clientSecret`, which must never be\n * shipped to the browser.\n *\n * `editor.clientId` is kept: it is the **public** project key, used by\n * `@intlayer/analytics` to identify the project when exchanging it for a\n * short-lived ingest token. It grants nothing on its own — every credentialed\n * backend call needs the secret, which only ever exists server-side.\n */\nexport type BrowserIntlayerConfig = {\n internationalization: Pick<\n InternationalizationConfig,\n 'locales' | 'defaultLocale'\n >;\n routing: RoutingConfig;\n editor: Omit<EditorConfig, 'clientSecret'>;\n analytics: AnalyticsConfig;\n log: Pick<LogConfig, 'mode' | 'prefix'>;\n};\n\ndeclare global {\n interface Window {\n /** Browser-safe Intlayer configuration injected by a build plugin or `installIntlayer`. */\n INTLAYER_CONFIG?: BrowserIntlayerConfig;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Shared field builders (browser-safe — no Node.js APIs)\n//\n// These functions are re-used by both `buildBrowserConfiguration` (browser)\n// and `buildConfigurationFields` (server) to avoid duplication.\n// ---------------------------------------------------------------------------\n\n/**\n * Build the internationalization section of the Intlayer configuration.\n *\n * @param customConfiguration - Partial user-supplied internationalization config.\n * @returns A fully-defaulted {@link InternationalizationConfig}.\n */\nexport const buildInternationalizationFields = (\n customConfiguration?: Partial<InternationalizationConfig>\n): InternationalizationConfig => ({\n /**\n * Locales available in the application\n *\n * Default: ['en']\n *\n */\n locales: customConfiguration?.locales ?? LOCALES,\n\n /**\n * Locales required by TypeScript to ensure strong implementations of internationalized content using typescript.\n *\n * Default: []\n *\n * If empty, all locales are required in `strict` mode.\n *\n * Ensure required locales are also defined in the `locales` field.\n */\n requiredLocales:\n customConfiguration?.requiredLocales ??\n customConfiguration?.locales ??\n REQUIRED_LOCALES,\n\n /**\n * Ensure strong implementations of internationalized content using typescript.\n * - If set to \"strict\", the translation `t` function will require each declared locales to be defined. If one locale is missing, or if a locale is not declared in your config, it will throw an error.\n * - If set to \"inclusive\", the translation `t` function will require each declared locales to be defined. If one locale is missing, it will throw a warning. But will accept if a locale is not declared in your config, but exist.\n * - If set to \"loose\", the translation `t` function will accept any existing locale.\n *\n * Default: \"inclusive\"\n */\n strictMode: customConfiguration?.strictMode ?? STRICT_MODE,\n\n /**\n * Default locale of the application for fallback\n *\n * Default: 'en'\n */\n defaultLocale: customConfiguration?.defaultLocale ?? DEFAULT_LOCALE,\n});\n\n/**\n * Build the routing section of the Intlayer configuration.\n *\n * @param customConfiguration - Partial user-supplied routing config.\n * @returns A fully-defaulted {@link RoutingConfig}.\n */\nexport const buildRoutingFields = (\n customConfiguration?: Partial<CustomRoutingConfig>\n): RoutingConfig => {\n const storage = customConfiguration?.storage ?? STORAGE;\n\n return {\n /**\n * URL routing mode for locale handling\n *\n * Controls how locales are represented in application URLs:\n * - 'prefix-no-default': Prefix all locales except the default locale (default)\n * - en → /dashboard\n * - fr → /fr/dashboard\n *\n * - 'prefix-all': Prefix all locales including the default locale\n * - en → /en/dashboard\n * - fr → /fr/dashboard\n *\n * - 'search-params': Use search parameters for locale handling\n * - en → /dashboard?locale=en\n * - fr → /fr/dashboard?locale=fr\n *\n * - 'no-prefix': No locale prefixing in URLs\n * - en → /dashboard\n * - fr → /dashboard\n *\n * Default: 'prefix-no-default'\n */\n mode: customConfiguration?.mode ?? ROUTING_MODE,\n\n /**\n * Enables the Intlayer locale-routing proxy (middleware).\n *\n * When enabled, the build-tool integration (e.g. the `intlayer()` Vite plugin)\n * automatically wires the locale-detection / redirect / rewrite middleware in\n * development, preview, and production SSR.\n *\n * - `undefined` (auto, default): the proxy runs, but development and preview\n * servers ignore the stored locale (cookie / header) as a redirect source.\n * - `true`: full proxy behaviour in every environment.\n * - `false`: no locale routing; the proxy is not registered.\n *\n * Default: undefined (auto)\n */\n enableProxy: customConfiguration?.enableProxy ?? ENABLE_PROXY,\n\n /**\n * Configuration for storing the locale in the client (localStorage or sessionStorage)\n *\n * If false, the locale will not be stored by the middleware.\n * If true, the locale storage will consider all default values. (cookie and header)\n *\n * Default: ['cookie', 'header']\n *\n */\n storage: getStorageAttributes(storage),\n\n /**\n * Base path of the application URL\n *\n * Default: ''\n *\n * Example:\n * - If the application is hosted at https://example.com/my-app\n * - The base path is '/my-app'\n * - The URL will be https://example.com/my-app/en\n * - If the base path is not set, the URL will be https://example.com/en\n */\n basePath: customConfiguration?.basePath ?? BASE_PATH,\n\n /**\n * Custom URL rewriting rules that override the default routing mode for specific paths.\n * Allows you to define locale-specific paths that differ from the standard routing behavior.\n * Supports dynamic route parameters using `[param]` syntax.\n *\n * Default: undefined\n *\n * Example:\n * ```typescript\n * rewrite: {\n * \"/about\": {\n * en: \"/about\",\n * fr: \"/a-propos\",\n * },\n * \"/product/[slug]\": {\n * en: \"/product/[slug]\",\n * fr: \"/produit/[slug]\",\n * },\n * }\n * ```\n *\n * Note:\n * - The rewrite rules take precedence over the default `mode` behavior.\n * - If a path matches a rewrite rule, the localized path from the rewrite configuration will be used.\n * - Dynamic route parameters are supported using bracket notation (e.g., `[slug]`, `[id]`).\n * - Works with both Next.js and Vite applications.\n */\n rewrite: customConfiguration?.rewrite,\n\n /**\n * Maps locales to specific domain hostnames for domain-based routing.\n *\n * Default: undefined\n */\n domains: customConfiguration?.domains,\n };\n};\n\n/**\n * Build the editor section of the Intlayer configuration.\n *\n * Returns the **full** {@link EditorConfig} including sensitive fields\n * (`clientId`, `clientSecret`). The browser-safe {@link BrowserIntlayerConfig}\n * omits those fields when exposing config to the client.\n *\n * `clientId` / `clientSecret` are never inferred from the environment: the\n * configuration file is the single source of truth. A project that wants to\n * authenticate from its `.env` file must wire the variables explicitly, e.g.\n * `clientId: process.env.INTLAYER_CLIENT_ID`. Commenting those lines out is\n * therefore enough to disable every credentialed behaviour (remote dictionary\n * fetching, CMS access) even when the variables remain defined in the\n * environment.\n *\n * @param customConfiguration - Partial user-supplied editor config.\n * @returns A fully-defaulted {@link EditorConfig}.\n */\nexport const buildEditorFields = (\n customConfiguration?: Partial<EditorConfig>\n): EditorConfig => {\n const liveSyncPort = customConfiguration?.liveSyncPort ?? LIVE_SYNC_PORT;\n return {\n /**\n * URL of the application. Used to restrict the origin of the editor for security reasons.\n *\n * > '*' means that the editor is accessible from any origin\n *\n * Default: '*'\n */\n applicationURL: customConfiguration?.applicationURL || APPLICATION_URL,\n\n /**\n * URL of the editor server. Used to restrict the origin of the editor for security reasons.\n *\n * > '*' means that the editor is accessible from any origin\n *\n * Default: '*'\n */\n editorURL: customConfiguration?.editorURL || EDITOR_URL,\n\n /**\n * URL of the CMS server. Used to restrict the origin of the editor for security reasons.\n */\n cmsURL: customConfiguration?.cmsURL || CMS_URL,\n\n /**\n * URL of the editor server\n *\n * Default: 'https://back.intlayer.org'\n */\n backendURL: customConfiguration?.backendURL || BACKEND_URL,\n\n /** Port of the editor server\n *\n * Default: 8000\n */\n port: customConfiguration?.port ?? PORT,\n\n /**\n * Indicates if the application interact with the visual editor\n *\n * Default: false;\n *\n * If true, the editor will be able to interact with the application.\n * If false, the editor will not be able to interact with the application.\n * In any case, the editor can only be enabled by the visual editor.\n * Disabling the editor for specific environments is a way to enforce the security.\n *\n * Usage:\n * ```js\n * {\n * // Other configurations\n * editor: {\n * enabled: process.env.NODE_ENV !== 'production',\n * }\n * };\n * ```\n */\n enabled: customConfiguration?.enabled ?? IS_ENABLED,\n\n /**\n * clientId and clientSecret allow the intlayer packages to authenticate with the backend using oAuth2 authentication.\n * An access token is use to authenticate the user related to the project.\n * To get an access token, go to https://app.intlayer.org/project and create an account.\n *\n * Default: undefined\n *\n * > Important: The clientId and clientSecret should be kept secret and not shared publicly. Please ensure to keep them in a secure location, such as environment variables.\n */\n clientId: customConfiguration?.clientId,\n\n /**\n * clientId and clientSecret allow the intlayer packages to authenticate with the backend using oAuth2 authentication.\n * An access token is use to authenticate the user related to the project.\n * To get an access token, go to https://app.intlayer.org/project and create an account.\n *\n * Default: undefined\n *\n * > Important: The clientId and clientSecret should be kept secret and not shared publicly. Please ensure to keep them in a secure location, such as environment variables.\n */\n clientSecret: customConfiguration?.clientSecret,\n\n /**\n * Strategy for prioritizing dictionaries. If a dictionary is both present online and locally, the content will be merge.\n * However, is a field is defined in both dictionary, this setting determines which fields takes the priority over the other.\n *\n * Default: 'local_first'\n *\n * The strategy for prioritizing dictionaries. It can be either 'local_first' or 'distant_first'.\n * - 'local_first': The first dictionary found in the locale is used.\n * - 'distant_first': The first dictionary found in the distant locales is used.\n */\n dictionaryPriorityStrategy:\n customConfiguration?.dictionaryPriorityStrategy ??\n DICTIONARY_PRIORITY_STRATEGY,\n\n /**\n * Indicates if the application should hot reload the locale configurations when a change is detected.\n * For example, when a new dictionary is added or updated, the application will update the content tu display in the page.\n *\n * The hot reload is only available for clients of the `enterprise` plan.\n *\n * Default: false\n */\n liveSync: customConfiguration?.liveSync ?? LIVE_SYNC,\n\n /**\n * Port of the live sync server\n *\n * Default: 4000\n */\n liveSyncPort,\n\n /**\n * URL of the live sync server in case of remote live sync server\n *\n * Default: `http://localhost:${LIVE_SYNC_PORT}`\n */\n liveSyncURL:\n customConfiguration?.liveSyncURL ?? `http://localhost:${liveSyncPort}`,\n };\n};\n\n/**\n * Build the analytics section of the Intlayer configuration.\n *\n * Analytics is opt-out: `enabled` defaults to `true`, so installing the\n * optional `@intlayer/analytics` package is enough to turn it on. The runtime\n * additionally requires a project key (`editor.clientId`) for attribution\n * before collecting anything.\n *\n * An explicit `enabled` value always wins, so a project whose package manager\n * hides the package from the project root can still opt back in.\n *\n * @param customConfiguration - Partial user-supplied analytics config.\n * @param isPackageInstalled - Whether `@intlayer/analytics` is installed in the\n * project. Browser callers cannot resolve packages and pass `true`, letting\n * the runtime dynamic `import()` fail silently when it is absent.\n * @returns A fully-defaulted {@link AnalyticsConfig}.\n */\nexport const buildAnalyticsFields = (\n customConfiguration?: Partial<AnalyticsConfig>,\n isPackageInstalled = true\n): AnalyticsConfig => ({\n /**\n * Enables analytics collection (page views, content exposures, A/B events).\n *\n * Default: true, as soon as `@intlayer/analytics` is installed.\n */\n enabled:\n customConfiguration?.enabled ?? (ANALYTICS_ENABLED && isPackageInstalled),\n\n /**\n * Milliseconds between automatic batched flushes to the backend.\n *\n * Default: 20000\n */\n flushInterval: customConfiguration?.flushInterval ?? ANALYTICS_FLUSH_INTERVAL,\n\n /**\n * Fraction of sessions to record, from 0 (none) to 1 (all).\n *\n * Default: 1\n */\n sampleRate: customConfiguration?.sampleRate ?? ANALYTICS_SAMPLE_RATE,\n});\n\n/**\n * Build the log section of the Intlayer configuration.\n *\n * @param customConfiguration - Partial user-supplied log config.\n * @param logFunctions - Optional custom log function overrides (server-only).\n * @returns A fully-defaulted {@link LogConfig}.\n */\nexport const buildLogFields = (\n customConfiguration?: Partial<LogConfig>,\n logFunctions?: LogFunctions\n): LogConfig => ({\n /**\n * Indicates if the logger is enabled\n *\n * Default: 'prefix-no-default'\n *\n * If 'default', the logger is enabled and can be used.\n * If 'verbose', the logger will be enabled and can be used, but will log more information.\n * If 'disabled', the logger is disabled and cannot be used.\n */\n mode: customConfiguration?.mode ?? MODE,\n\n /**\n * Prefix of the logger\n *\n * Default: '[intlayer]'\n *\n * The prefix of the logger.\n */\n prefix: customConfiguration?.prefix ?? PREFIX,\n\n /**\n * Functions to log\n */\n error: logFunctions?.error,\n log: logFunctions?.log,\n info: logFunctions?.info,\n warn: logFunctions?.warn,\n});\n\n// ---------------------------------------------------------------------------\n// Browser configuration builders\n// ---------------------------------------------------------------------------\n\n/**\n * Build a browser-safe {@link BrowserIntlayerConfig} from a raw user config.\n *\n * Applies defaults for every field and strips all server-only or sensitive\n * information (`system`, `content`, `build`, `compiler`, `dictionary`, `ai`,\n * `editor.clientSecret`). The public `editor.clientId` is kept — see\n * {@link BrowserIntlayerConfig}.\n *\n * This is the browser counterpart of `buildConfigurationFields`. It is safe\n * to call in browser environments because it has no Node.js dependencies.\n *\n * @param customConfig - Optional partial user-supplied Intlayer config.\n * @returns A browser-safe configuration object ready for `window.INTLAYER_CONFIG`.\n *\n * @example\n * ```ts\n * import { buildBrowserConfiguration } from '@intlayer/config/client';\n *\n * window.INTLAYER_CONFIG = buildBrowserConfiguration({\n * internationalization: { locales: ['en', 'fr'], defaultLocale: 'en' },\n * });\n * ```\n */\nexport const buildBrowserConfiguration = (\n customConfig?: CustomIntlayerConfig\n): BrowserIntlayerConfig => {\n const { locales, defaultLocale } = buildInternationalizationFields(\n customConfig?.internationalization\n );\n const routing = buildRoutingFields(customConfig?.routing);\n const { clientSecret: _clientSecret, ...editorPublic } = buildEditorFields(\n customConfig?.editor\n );\n const analytics = buildAnalyticsFields(customConfig?.analytics);\n const { mode, prefix } = buildLogFields(customConfig?.log);\n\n return {\n internationalization: { locales, defaultLocale },\n routing,\n editor: editorPublic,\n analytics,\n log: { mode, prefix },\n };\n};\n\n/**\n * Extract a {@link BrowserIntlayerConfig} from an already-built full\n * {@link IntlayerConfig}.\n *\n * Used by build plugins (`vite-intlayer`, `withIntlayer`) which already hold\n * the full server-side config and need to inject the browser-safe subset at\n * compile time via a bundler `define`.\n *\n * @param config - A fully-built server-side Intlayer configuration.\n * @returns The browser-safe subset of that configuration.\n */\nexport const extractBrowserConfiguration = (\n config: IntlayerConfig\n): BrowserIntlayerConfig => {\n // Destructured rather than picked field by field so that any future addition\n // to `EditorConfig` is carried over automatically, while `clientSecret` stays\n // excluded by construction.\n const { clientSecret: _clientSecret, ...editorPublic } = config.editor;\n\n return {\n internationalization: {\n locales: config.internationalization.locales,\n defaultLocale: config.internationalization.defaultLocale,\n },\n routing: {\n mode: config.routing.mode,\n enableProxy: config.routing.enableProxy,\n storage: config.routing.storage,\n basePath: config.routing.basePath,\n rewrite: config.routing.rewrite,\n },\n editor: editorPublic,\n analytics: buildAnalyticsFields(config.analytics),\n log: {\n mode: config.log.mode,\n prefix: config.log.prefix,\n },\n };\n};\n"],"mappings":";;;;;;;;;;;;;;AAyFA,MAAa,mCACX,yBACgC;;;;;;;CAOhC,SAAS,qBAAqB,WAAW;;;;;;;;;;CAWzC,iBACE,qBAAqB,mBACrB,qBAAqB,WACrB;;;;;;;;;CAUF,YAAY,qBAAqB;;;;;;CAOjC,eAAe,qBAAqB;AACtC;;;;;;;AAQA,MAAa,sBACX,wBACkB;CAClB,MAAM,UAAU,qBAAqB,WAAW;CAEhD,OAAO;;;;;;;;;;;;;;;;;;;;;;;EAuBL,MAAM,qBAAqB;;;;;;;;;;;;;;;EAgB3B,aAAa,qBAAqB;;;;;;;;;;EAWlC,SAAS,qBAAqB,OAAO;;;;;;;;;;;;EAarC,UAAU,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA6B/B,SAAS,qBAAqB;;;;;;EAO9B,SAAS,qBAAqB;CAChC;AACF;;;;;;;;;;;;;;;;;;;AAoBA,MAAa,qBACX,wBACiB;CACjB,MAAM,eAAe,qBAAqB;CAC1C,OAAO;;;;;;;;EAQL,gBAAgB,qBAAqB;;;;;;;;EASrC,WAAW,qBAAqB;;;;EAKhC,QAAQ,qBAAqB;;;;;;EAO7B,YAAY,qBAAqB;;;;;EAMjC,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;;EAsB3B,SAAS,qBAAqB;;;;;;;;;;EAW9B,UAAU,qBAAqB;;;;;;;;;;EAW/B,cAAc,qBAAqB;;;;;;;;;;;EAYnC,4BACE,qBAAqB;;;;;;;;;EAWvB,UAAU,qBAAqB;;;;;;EAO/B;;;;;;EAOA,aACE,qBAAqB,eAAe,oBAAoB;CAC5D;AACF;;;;;;;;;;;;;;;;;;AAmBA,MAAa,wBACX,qBACA,qBAAqB,UACA;;;;;;CAMrB,SACE,qBAAqB,oBAAiC;;;;;;CAOxD,eAAe,qBAAqB;;;;;;CAOpC,YAAY,qBAAqB;AACnC;;;;;;;;AASA,MAAa,kBACX,qBACA,kBACe;;;;;;;;;;CAUf,MAAM,qBAAqB;;;;;;;;CAS3B,QAAQ,qBAAqB,UAAU;;;;CAKvC,OAAO,cAAc;CACrB,KAAK,cAAc;CACnB,MAAM,cAAc;CACpB,MAAM,cAAc;AACtB;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,MAAa,6BACX,iBAC0B;CAC1B,MAAM,EAAE,SAAS,kBAAkB,gCACjC,cAAc,oBAChB;CACA,MAAM,UAAU,mBAAmB,cAAc,OAAO;CACxD,MAAM,EAAE,cAAc,eAAe,GAAG,iBAAiB,kBACvD,cAAc,MAChB;CACA,MAAM,YAAY,qBAAqB,cAAc,SAAS;CAC9D,MAAM,EAAE,MAAM,WAAW,eAAe,cAAc,GAAG;CAEzD,OAAO;EACL,sBAAsB;GAAE;GAAS;EAAc;EAC/C;EACA,QAAQ;EACR;EACA,KAAK;GAAE;GAAM;EAAO;CACtB;AACF;;;;;;;;;;;;AAaA,MAAa,+BACX,WAC0B;CAI1B,MAAM,EAAE,cAAc,eAAe,GAAG,iBAAiB,OAAO;CAEhE,OAAO;EACL,sBAAsB;GACpB,SAAS,OAAO,qBAAqB;GACrC,eAAe,OAAO,qBAAqB;EAC7C;EACA,SAAS;GACP,MAAM,OAAO,QAAQ;GACrB,aAAa,OAAO,QAAQ;GAC5B,SAAS,OAAO,QAAQ;GACxB,UAAU,OAAO,QAAQ;GACzB,SAAS,OAAO,QAAQ;EAC1B;EACA,QAAQ;EACR,WAAW,qBAAqB,OAAO,SAAS;EAChD,KAAK;GACH,MAAM,OAAO,IAAI;GACjB,QAAQ,OAAO,IAAI;EACrB;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"buildBrowserConfiguration.mjs","names":[],"sources":["../../../src/configFile/buildBrowserConfiguration.ts"],"sourcesContent":["import type {\n AnalyticsConfig,\n CustomIntlayerConfig,\n CustomRoutingConfig,\n EditorConfig,\n InternationalizationConfig,\n IntlayerConfig,\n LogConfig,\n LogFunctions,\n RoutingConfig,\n} from '@intlayer/types/config';\nimport {\n ANALYTICS_ENABLED,\n ANALYTICS_FLUSH_INTERVAL,\n ANALYTICS_SAMPLE_RATE,\n} from '../defaultValues/analytics';\nimport {\n APPLICATION_URL,\n BACKEND_URL,\n CMS_URL,\n DICTIONARY_PRIORITY_STRATEGY,\n EDITOR_URL,\n IS_ENABLED,\n LIVE_SYNC,\n LIVE_SYNC_PORT,\n PORT,\n} from '../defaultValues/editor';\nimport {\n DEFAULT_LOCALE,\n LOCALES,\n REQUIRED_LOCALES,\n STRICT_MODE,\n} from '../defaultValues/internationalization';\nimport { MODE, PREFIX } from '../defaultValues/log';\nimport {\n BASE_PATH,\n ENABLE_PROXY,\n ROUTING_MODE,\n STORAGE,\n} from '../defaultValues/routing';\nimport { getStorageAttributes } from '../utils/getStorageAttributes';\n\n// ---------------------------------------------------------------------------\n// Type\n// ---------------------------------------------------------------------------\n\n/**\n * Browser-safe subset of {@link IntlayerConfig}.\n *\n * Excludes server-only fields (`system`, `content`, `build`, `compiler`,\n * `dictionary`, `ai`) and the `editor.clientSecret`, which must never be\n * shipped to the browser.\n *\n * `editor.clientId` is kept: it is the **public** project key, used by\n * `@intlayer/analytics` to identify the project when exchanging it for a\n * short-lived ingest token. It grants nothing on its own — every credentialed\n * backend call needs the secret, which only ever exists server-side.\n */\nexport type BrowserIntlayerConfig = {\n internationalization: Pick<\n InternationalizationConfig,\n 'locales' | 'defaultLocale'\n >;\n routing: RoutingConfig;\n editor: Omit<EditorConfig, 'clientSecret'>;\n analytics: AnalyticsConfig;\n log: Pick<LogConfig, 'mode' | 'prefix'>;\n};\n\ndeclare global {\n interface Window {\n /** Browser-safe Intlayer configuration injected by a build plugin or `installIntlayer`. */\n INTLAYER_CONFIG?: BrowserIntlayerConfig;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Shared field builders (browser-safe — no Node.js APIs)\n//\n// These functions are re-used by both `buildBrowserConfiguration` (browser)\n// and `buildConfigurationFields` (server) to avoid duplication.\n// ---------------------------------------------------------------------------\n\n/**\n * Build the internationalization section of the Intlayer configuration.\n *\n * @param customConfiguration - Partial user-supplied internationalization config.\n * @returns A fully-defaulted {@link InternationalizationConfig}.\n */\nexport const buildInternationalizationFields = (\n customConfiguration?: Partial<InternationalizationConfig>\n): InternationalizationConfig => ({\n /**\n * Locales available in the application\n *\n * Default: ['en']\n *\n */\n locales: customConfiguration?.locales ?? LOCALES,\n\n /**\n * Locales required by TypeScript to ensure strong implementations of internationalized content using typescript.\n *\n * Default: []\n *\n * If empty, all locales are required in `strict` mode.\n *\n * Ensure required locales are also defined in the `locales` field.\n */\n requiredLocales:\n customConfiguration?.requiredLocales ??\n customConfiguration?.locales ??\n REQUIRED_LOCALES,\n\n /**\n * Ensure strong implementations of internationalized content using typescript.\n * - If set to \"strict\", the translation `t` function will require each declared locales to be defined. If one locale is missing, or if a locale is not declared in your config, it will throw an error.\n * - If set to \"inclusive\", the translation `t` function will require each declared locales to be defined. If one locale is missing, it will throw a warning. But will accept if a locale is not declared in your config, but exist.\n * - If set to \"loose\", the translation `t` function will accept any existing locale.\n *\n * Default: \"inclusive\"\n */\n strictMode: customConfiguration?.strictMode ?? STRICT_MODE,\n\n /**\n * Default locale of the application for fallback\n *\n * Default: 'en'\n */\n defaultLocale: customConfiguration?.defaultLocale ?? DEFAULT_LOCALE,\n});\n\n/**\n * Build the routing section of the Intlayer configuration.\n *\n * @param customConfiguration - Partial user-supplied routing config.\n * @returns A fully-defaulted {@link RoutingConfig}.\n */\nexport const buildRoutingFields = (\n customConfiguration?: Partial<CustomRoutingConfig>\n): RoutingConfig => {\n const storage = customConfiguration?.storage ?? STORAGE;\n\n return {\n /**\n * URL routing mode for locale handling\n *\n * Controls how locales are represented in application URLs:\n * - 'prefix-no-default': Prefix all locales except the default locale (default)\n * - en → /dashboard\n * - fr → /fr/dashboard\n *\n * - 'prefix-all': Prefix all locales including the default locale\n * - en → /en/dashboard\n * - fr → /fr/dashboard\n *\n * - 'search-params': Use search parameters for locale handling\n * - en → /dashboard?locale=en\n * - fr → /fr/dashboard?locale=fr\n *\n * - 'no-prefix': No locale prefixing in URLs\n * - en → /dashboard\n * - fr → /dashboard\n *\n * Default: 'prefix-no-default'\n */\n mode: customConfiguration?.mode ?? ROUTING_MODE,\n\n /**\n * Enables the Intlayer locale-routing proxy (middleware).\n *\n * When enabled, the build-tool integration (e.g. the `intlayer()` Vite plugin)\n * automatically wires the locale-detection / redirect / rewrite middleware in\n * development, preview, and production SSR.\n *\n * - `undefined` (auto, default): the proxy runs, but development and preview\n * servers ignore the stored locale (cookie / header) as a redirect source.\n * - `true`: full proxy behaviour in every environment.\n * - `false`: no locale routing; the proxy is not registered.\n *\n * Default: undefined (auto)\n */\n enableProxy: customConfiguration?.enableProxy ?? ENABLE_PROXY,\n\n /**\n * Configuration for storing the locale in the client (localStorage or sessionStorage)\n *\n * If false, the locale will not be stored by the middleware.\n * If true, the locale storage will consider all default values. (cookie and header)\n *\n * Default: ['cookie', 'header']\n *\n */\n storage: getStorageAttributes(storage),\n\n /**\n * Base path of the application URL\n *\n * Default: ''\n *\n * Example:\n * - If the application is hosted at https://example.com/my-app\n * - The base path is '/my-app'\n * - The URL will be https://example.com/my-app/en\n * - If the base path is not set, the URL will be https://example.com/en\n */\n basePath: customConfiguration?.basePath ?? BASE_PATH,\n\n /**\n * Custom URL rewriting rules that override the default routing mode for specific paths.\n * Allows you to define locale-specific paths that differ from the standard routing behavior.\n * Supports dynamic route parameters using `[param]` syntax.\n *\n * Default: undefined\n *\n * Example:\n * ```typescript\n * rewrite: {\n * \"/about\": {\n * en: \"/about\",\n * fr: \"/a-propos\",\n * },\n * \"/product/[slug]\": {\n * en: \"/product/[slug]\",\n * fr: \"/produit/[slug]\",\n * },\n * }\n * ```\n *\n * Note:\n * - The rewrite rules take precedence over the default `mode` behavior.\n * - If a path matches a rewrite rule, the localized path from the rewrite configuration will be used.\n * - Dynamic route parameters are supported using bracket notation (e.g., `[slug]`, `[id]`).\n * - Works with both Next.js and Vite applications.\n */\n rewrite: customConfiguration?.rewrite,\n\n /**\n * Maps locales to specific domain hostnames for domain-based routing.\n *\n * Default: undefined\n */\n domains: customConfiguration?.domains,\n };\n};\n\n/**\n * Build the editor section of the Intlayer configuration.\n *\n * Returns the **full** {@link EditorConfig} including sensitive fields\n * (`clientId`, `clientSecret`). The browser-safe {@link BrowserIntlayerConfig}\n * omits those fields when exposing config to the client.\n *\n * `clientId` / `clientSecret` are never inferred from the environment: the\n * configuration file is the single source of truth. A project that wants to\n * authenticate from its `.env` file must wire the variables explicitly, e.g.\n * `clientId: process.env.INTLAYER_CLIENT_ID`. Commenting those lines out is\n * therefore enough to disable every credentialed behaviour (remote dictionary\n * fetching, CMS access) even when the variables remain defined in the\n * environment.\n *\n * @param customConfiguration - Partial user-supplied editor config.\n * @returns A fully-defaulted {@link EditorConfig}.\n */\nexport const buildEditorFields = (\n customConfiguration?: Partial<EditorConfig>\n): EditorConfig => {\n const liveSyncPort = customConfiguration?.liveSyncPort ?? LIVE_SYNC_PORT;\n return {\n /**\n * URL of the application. Used to restrict the origin of the editor for security reasons.\n *\n * > '*' means that the editor is accessible from any origin\n *\n * Default: '*'\n */\n applicationURL: customConfiguration?.applicationURL || APPLICATION_URL,\n\n /**\n * URL of the editor server. Used to restrict the origin of the editor for security reasons.\n *\n * > '*' means that the editor is accessible from any origin\n *\n * Default: '*'\n */\n editorURL: customConfiguration?.editorURL || EDITOR_URL,\n\n /**\n * URL of the CMS server. Used to restrict the origin of the editor for security reasons.\n */\n cmsURL: customConfiguration?.cmsURL || CMS_URL,\n\n /**\n * URL of the editor server\n *\n * Default: 'https://back.intlayer.org'\n */\n backendURL: customConfiguration?.backendURL || BACKEND_URL,\n\n /** Port of the editor server\n *\n * Default: 8000\n */\n port: customConfiguration?.port ?? PORT,\n\n /**\n * Indicates if the application interact with the visual editor\n *\n * Default: false;\n *\n * If true, the editor will be able to interact with the application.\n * If false, the editor will not be able to interact with the application.\n * In any case, the editor can only be enabled by the visual editor.\n * Disabling the editor for specific environments is a way to enforce the security.\n *\n * Usage:\n * ```js\n * {\n * // Other configurations\n * editor: {\n * enabled: process.env.NODE_ENV !== 'production',\n * }\n * };\n * ```\n */\n enabled: customConfiguration?.enabled ?? IS_ENABLED,\n\n /**\n * clientId and clientSecret allow the intlayer packages to authenticate with the backend using oAuth2 authentication.\n * An access token is use to authenticate the user related to the project.\n * To get an access token, go to https://app.intlayer.org/project and create an account.\n *\n * Default: undefined\n *\n * > Important: The clientId and clientSecret should be kept secret and not shared publicly. Please ensure to keep them in a secure location, such as environment variables.\n */\n clientId: customConfiguration?.clientId,\n\n /**\n * clientId and clientSecret allow the intlayer packages to authenticate with the backend using oAuth2 authentication.\n * An access token is use to authenticate the user related to the project.\n * To get an access token, go to https://app.intlayer.org/project and create an account.\n *\n * Default: undefined\n *\n * > Important: The clientId and clientSecret should be kept secret and not shared publicly. Please ensure to keep them in a secure location, such as environment variables.\n */\n clientSecret: customConfiguration?.clientSecret,\n\n /**\n * Strategy for prioritizing dictionaries. If a dictionary is both present online and locally, the content will be merge.\n * However, is a field is defined in both dictionary, this setting determines which fields takes the priority over the other.\n *\n * Default: 'local_first'\n *\n * The strategy for prioritizing dictionaries. It can be either 'local_first' or 'distant_first'.\n * - 'local_first': The first dictionary found in the locale is used.\n * - 'distant_first': The first dictionary found in the distant locales is used.\n */\n dictionaryPriorityStrategy:\n customConfiguration?.dictionaryPriorityStrategy ??\n DICTIONARY_PRIORITY_STRATEGY,\n\n /**\n * Indicates if the application should hot reload the locale configurations when a change is detected.\n * For example, when a new dictionary is added or updated, the application will update the content tu display in the page.\n *\n * The hot reload is only available for clients of the `enterprise` plan.\n *\n * Default: false\n */\n liveSync: customConfiguration?.liveSync ?? LIVE_SYNC,\n\n /**\n * Port of the live sync server\n *\n * Default: 4000\n */\n liveSyncPort,\n\n /**\n * URL of the live sync server in case of remote live sync server\n *\n * Default: `http://localhost:${LIVE_SYNC_PORT}`\n */\n liveSyncURL:\n customConfiguration?.liveSyncURL ?? `http://localhost:${liveSyncPort}`,\n };\n};\n\n/**\n * Build the analytics section of the Intlayer configuration.\n *\n * Analytics is opt-out: `enabled` defaults to `true`, so installing the\n * optional `@intlayer/analytics` package is enough to turn it on. The runtime\n * additionally requires a project key (`editor.clientId`) for attribution\n * before collecting anything.\n *\n * An explicit `enabled` value always wins, so a project whose package manager\n * hides the package from the project root can still opt back in.\n *\n * @param customConfiguration - Partial user-supplied analytics config.\n * @param isPackageInstalled - Whether `@intlayer/analytics` is installed in the\n * project. Browser callers cannot resolve packages and pass `true`, letting\n * the runtime dynamic `import()` fail silently when it is absent.\n * @returns A fully-defaulted {@link AnalyticsConfig}.\n */\nexport const buildAnalyticsFields = (\n customConfiguration?: Partial<AnalyticsConfig>,\n isPackageInstalled = true\n): AnalyticsConfig => ({\n /**\n * Enables analytics collection (page views, content exposures, A/B events).\n *\n * Default: true, as soon as `@intlayer/analytics` is installed.\n */\n enabled:\n customConfiguration?.enabled ?? (ANALYTICS_ENABLED && isPackageInstalled),\n\n /**\n * Milliseconds between automatic batched flushes to the backend.\n *\n * Default: 20000\n */\n flushInterval: customConfiguration?.flushInterval ?? ANALYTICS_FLUSH_INTERVAL,\n\n /**\n * Fraction of sessions to record, from 0 (none) to 1 (all).\n *\n * Default: 1\n */\n sampleRate: customConfiguration?.sampleRate ?? ANALYTICS_SAMPLE_RATE,\n});\n\n/**\n * Binds a custom log function to its owner, so logger instances whose methods\n * read their state from `this` (e.g. pino, used as `fastify.log`) keep working\n * once the method is detached and called on its own.\n *\n * @param logFunctions - The object holding the custom log functions.\n * @param level - The log function to bind.\n * @returns The bound function, or `undefined` when not provided.\n */\nexport const bindLogFunction = <Level extends keyof LogFunctions>(\n logFunctions: LogFunctions | undefined,\n level: Level\n): LogFunctions[Level] =>\n logFunctions?.[level]?.bind(logFunctions) as LogFunctions[Level];\n\n/**\n * Build the log section of the Intlayer configuration.\n *\n * @param customConfiguration - Partial user-supplied log config.\n * @param logFunctions - Optional custom log function overrides (server-only).\n * @returns A fully-defaulted {@link LogConfig}.\n */\nexport const buildLogFields = (\n customConfiguration?: Partial<LogConfig>,\n logFunctions?: LogFunctions\n): LogConfig => ({\n /**\n * Indicates if the logger is enabled\n *\n * Default: 'prefix-no-default'\n *\n * If 'default', the logger is enabled and can be used.\n * If 'verbose', the logger will be enabled and can be used, but will log more information.\n * If 'disabled', the logger is disabled and cannot be used.\n */\n mode: customConfiguration?.mode ?? MODE,\n\n /**\n * Prefix of the logger\n *\n * Default: '[intlayer]'\n *\n * The prefix of the logger.\n */\n prefix: customConfiguration?.prefix ?? PREFIX,\n\n /**\n * Functions to log\n */\n error: bindLogFunction(logFunctions, 'error'),\n log: bindLogFunction(logFunctions, 'log'),\n info: bindLogFunction(logFunctions, 'info'),\n warn: bindLogFunction(logFunctions, 'warn'),\n});\n\n// ---------------------------------------------------------------------------\n// Browser configuration builders\n// ---------------------------------------------------------------------------\n\n/**\n * Build a browser-safe {@link BrowserIntlayerConfig} from a raw user config.\n *\n * Applies defaults for every field and strips all server-only or sensitive\n * information (`system`, `content`, `build`, `compiler`, `dictionary`, `ai`,\n * `editor.clientSecret`). The public `editor.clientId` is kept — see\n * {@link BrowserIntlayerConfig}.\n *\n * This is the browser counterpart of `buildConfigurationFields`. It is safe\n * to call in browser environments because it has no Node.js dependencies.\n *\n * @param customConfig - Optional partial user-supplied Intlayer config.\n * @returns A browser-safe configuration object ready for `window.INTLAYER_CONFIG`.\n *\n * @example\n * ```ts\n * import { buildBrowserConfiguration } from '@intlayer/config/client';\n *\n * window.INTLAYER_CONFIG = buildBrowserConfiguration({\n * internationalization: { locales: ['en', 'fr'], defaultLocale: 'en' },\n * });\n * ```\n */\nexport const buildBrowserConfiguration = (\n customConfig?: CustomIntlayerConfig\n): BrowserIntlayerConfig => {\n const { locales, defaultLocale } = buildInternationalizationFields(\n customConfig?.internationalization\n );\n const routing = buildRoutingFields(customConfig?.routing);\n const { clientSecret: _clientSecret, ...editorPublic } = buildEditorFields(\n customConfig?.editor\n );\n const analytics = buildAnalyticsFields(customConfig?.analytics);\n const { mode, prefix } = buildLogFields(customConfig?.log);\n\n return {\n internationalization: { locales, defaultLocale },\n routing,\n editor: editorPublic,\n analytics,\n log: { mode, prefix },\n };\n};\n\n/**\n * Extract a {@link BrowserIntlayerConfig} from an already-built full\n * {@link IntlayerConfig}.\n *\n * Used by build plugins (`vite-intlayer`, `withIntlayer`) which already hold\n * the full server-side config and need to inject the browser-safe subset at\n * compile time via a bundler `define`.\n *\n * @param config - A fully-built server-side Intlayer configuration.\n * @returns The browser-safe subset of that configuration.\n */\nexport const extractBrowserConfiguration = (\n config: IntlayerConfig\n): BrowserIntlayerConfig => {\n // Destructured rather than picked field by field so that any future addition\n // to `EditorConfig` is carried over automatically, while `clientSecret` stays\n // excluded by construction.\n const { clientSecret: _clientSecret, ...editorPublic } = config.editor;\n\n return {\n internationalization: {\n locales: config.internationalization.locales,\n defaultLocale: config.internationalization.defaultLocale,\n },\n routing: {\n mode: config.routing.mode,\n enableProxy: config.routing.enableProxy,\n storage: config.routing.storage,\n basePath: config.routing.basePath,\n rewrite: config.routing.rewrite,\n },\n editor: editorPublic,\n analytics: buildAnalyticsFields(config.analytics),\n log: {\n mode: config.log.mode,\n prefix: config.log.prefix,\n },\n };\n};\n"],"mappings":";;;;;;;;;;;;;;AAyFA,MAAa,mCACX,yBACgC;;;;;;;CAOhC,SAAS,qBAAqB,WAAW;;;;;;;;;;CAWzC,iBACE,qBAAqB,mBACrB,qBAAqB,WACrB;;;;;;;;;CAUF,YAAY,qBAAqB;;;;;;CAOjC,eAAe,qBAAqB;AACtC;;;;;;;AAQA,MAAa,sBACX,wBACkB;CAClB,MAAM,UAAU,qBAAqB,WAAW;CAEhD,OAAO;;;;;;;;;;;;;;;;;;;;;;;EAuBL,MAAM,qBAAqB;;;;;;;;;;;;;;;EAgB3B,aAAa,qBAAqB;;;;;;;;;;EAWlC,SAAS,qBAAqB,OAAO;;;;;;;;;;;;EAarC,UAAU,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA6B/B,SAAS,qBAAqB;;;;;;EAO9B,SAAS,qBAAqB;CAChC;AACF;;;;;;;;;;;;;;;;;;;AAoBA,MAAa,qBACX,wBACiB;CACjB,MAAM,eAAe,qBAAqB;CAC1C,OAAO;;;;;;;;EAQL,gBAAgB,qBAAqB;;;;;;;;EASrC,WAAW,qBAAqB;;;;EAKhC,QAAQ,qBAAqB;;;;;;EAO7B,YAAY,qBAAqB;;;;;EAMjC,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;;EAsB3B,SAAS,qBAAqB;;;;;;;;;;EAW9B,UAAU,qBAAqB;;;;;;;;;;EAW/B,cAAc,qBAAqB;;;;;;;;;;;EAYnC,4BACE,qBAAqB;;;;;;;;;EAWvB,UAAU,qBAAqB;;;;;;EAO/B;;;;;;EAOA,aACE,qBAAqB,eAAe,oBAAoB;CAC5D;AACF;;;;;;;;;;;;;;;;;;AAmBA,MAAa,wBACX,qBACA,qBAAqB,UACA;;;;;;CAMrB,SACE,qBAAqB,oBAAiC;;;;;;CAOxD,eAAe,qBAAqB;;;;;;CAOpC,YAAY,qBAAqB;AACnC;;;;;;;;;;AAWA,MAAa,mBACX,cACA,UAEA,eAAe,MAAM,EAAE,KAAK,YAAY;;;;;;;;AAS1C,MAAa,kBACX,qBACA,kBACe;;;;;;;;;;CAUf,MAAM,qBAAqB;;;;;;;;CAS3B,QAAQ,qBAAqB,UAAU;;;;CAKvC,OAAO,gBAAgB,cAAc,OAAO;CAC5C,KAAK,gBAAgB,cAAc,KAAK;CACxC,MAAM,gBAAgB,cAAc,MAAM;CAC1C,MAAM,gBAAgB,cAAc,MAAM;AAC5C;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,MAAa,6BACX,iBAC0B;CAC1B,MAAM,EAAE,SAAS,kBAAkB,gCACjC,cAAc,oBAChB;CACA,MAAM,UAAU,mBAAmB,cAAc,OAAO;CACxD,MAAM,EAAE,cAAc,eAAe,GAAG,iBAAiB,kBACvD,cAAc,MAChB;CACA,MAAM,YAAY,qBAAqB,cAAc,SAAS;CAC9D,MAAM,EAAE,MAAM,WAAW,eAAe,cAAc,GAAG;CAEzD,OAAO;EACL,sBAAsB;GAAE;GAAS;EAAc;EAC/C;EACA,QAAQ;EACR;EACA,KAAK;GAAE;GAAM;EAAO;CACtB;AACF;;;;;;;;;;;;AAaA,MAAa,+BACX,WAC0B;CAI1B,MAAM,EAAE,cAAc,eAAe,GAAG,iBAAiB,OAAO;CAEhE,OAAO;EACL,sBAAsB;GACpB,SAAS,OAAO,qBAAqB;GACrC,eAAe,OAAO,qBAAqB;EAC7C;EACA,SAAS;GACP,MAAM,OAAO,QAAQ;GACrB,aAAa,OAAO,QAAQ;GAC5B,SAAS,OAAO,QAAQ;GACxB,UAAU,OAAO,QAAQ;GACzB,SAAS,OAAO,QAAQ;EAC1B;EACA,QAAQ;EACR,WAAW,qBAAqB,OAAO,SAAS;EAChD,KAAK;GACH,MAAM,OAAO,IAAI;GACjB,QAAQ,OAAO,IAAI;EACrB;CACF;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { __require } from "../_virtual/_rolldown/runtime.mjs";
|
|
2
|
-
import { buildAnalyticsFields, buildBrowserConfiguration, buildEditorFields, buildInternationalizationFields, buildLogFields, buildRoutingFields, extractBrowserConfiguration } from "./buildBrowserConfiguration.mjs";
|
|
2
|
+
import { bindLogFunction, buildAnalyticsFields, buildBrowserConfiguration, buildEditorFields, buildInternationalizationFields, buildLogFields, buildRoutingFields, extractBrowserConfiguration } from "./buildBrowserConfiguration.mjs";
|
|
3
3
|
import { BUILD_MODE, CACHE, CHUNK_GROUPING, DICTIONARIES_PRELOAD, MINIFY, OUTPUT_FORMAT, PURGE, TRAVERSE_PATTERN, TYPE_CHECKING } from "../defaultValues/build.mjs";
|
|
4
4
|
import { COMPILER_DICTIONARY_KEY_PREFIX, COMPILER_ENABLED, COMPILER_NO_METADATA, COMPILER_SAVE_COMPONENTS } from "../defaultValues/compiler.mjs";
|
|
5
5
|
import { CODE_DIR, CONTENT_DIR, EXCLUDED_PATHS, FILE_EXTENSIONS, WATCH } from "../defaultValues/content.mjs";
|
|
@@ -586,7 +586,7 @@ const buildConfigurationFields = (customConfiguration, baseDir, logFunctions) =>
|
|
|
586
586
|
if (customConfiguration) {
|
|
587
587
|
const result = intlayerConfigSchema.safeParse(customConfiguration, intlayerConfigSchemaParseContext);
|
|
588
588
|
if (!result.success) {
|
|
589
|
-
const logError = logFunctions
|
|
589
|
+
const logError = bindLogFunction(logFunctions, "error") ?? console.error;
|
|
590
590
|
for (const issue of result.error.issues) logError(`${issue.path.join(".")}: ${issue.message}`);
|
|
591
591
|
}
|
|
592
592
|
}
|