@inlang/paraglide-js 2.26.0 → 2.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -1
- package/dist/bundler-plugins/per-locale-build/vite-environments.test.js +2 -2
- package/dist/bundler-plugins/per-locale-build/vite-environments.test.js.map +1 -1
- package/dist/cli/commands/init/command.js +19 -1
- package/dist/cli/commands/init/command.js.map +1 -1
- package/dist/cli/defaults.js +2 -2
- package/dist/cli/defaults.js.map +1 -1
- package/dist/cli/steps/add-inlang-check.d.ts +19 -0
- package/dist/cli/steps/add-inlang-check.js +60 -0
- package/dist/cli/steps/add-inlang-check.js.map +1 -0
- package/dist/cli/steps/add-inlang-check.test.d.ts +1 -0
- package/dist/cli/steps/add-inlang-check.test.js +88 -0
- package/dist/cli/steps/add-inlang-check.test.js.map +1 -0
- package/dist/cli/steps/agents-md-suggestion.d.ts +11 -0
- package/dist/cli/steps/agents-md-suggestion.js +19 -0
- package/dist/cli/steps/agents-md-suggestion.js.map +1 -0
- package/dist/cli/steps/agents-md-suggestion.test.d.ts +1 -0
- package/dist/cli/steps/agents-md-suggestion.test.js +36 -0
- package/dist/cli/steps/agents-md-suggestion.test.js.map +1 -0
- package/dist/cli/steps/maybe-add-machine-translation.js +3 -2
- package/dist/cli/steps/maybe-add-machine-translation.js.map +1 -1
- package/dist/cli/steps/maybe-add-sherlock.js +1 -1
- package/dist/cli/steps/maybe-add-sherlock.js.map +1 -1
- package/dist/cli/utils.d.ts +9 -0
- package/dist/cli/utils.js +15 -0
- package/dist/cli/utils.js.map +1 -1
- package/dist/compiler/compile-annotation.d.ts +48 -1
- package/dist/compiler/compile-annotation.js +238 -10
- package/dist/compiler/compile-annotation.js.map +1 -1
- package/dist/compiler/compile-bundle.d.ts +3 -2
- package/dist/compiler/compile-bundle.js +30 -1
- package/dist/compiler/compile-bundle.js.map +1 -1
- package/dist/compiler/compile-bundle.test.js +18 -18
- package/dist/compiler/compile-bundle.test.js.map +1 -1
- package/dist/compiler/compile-local-variable.d.ts +3 -0
- package/dist/compiler/compile-local-variable.js +5 -2
- package/dist/compiler/compile-local-variable.js.map +1 -1
- package/dist/compiler/compile-local-variable.test.js +44 -4
- package/dist/compiler/compile-local-variable.test.js.map +1 -1
- package/dist/compiler/compile-message.d.ts +29 -1
- package/dist/compiler/compile-message.exact-number.test.d.ts +1 -0
- package/dist/compiler/compile-message.exact-number.test.js +786 -0
- package/dist/compiler/compile-message.exact-number.test.js.map +1 -0
- package/dist/compiler/compile-message.js +162 -66
- package/dist/compiler/compile-message.js.map +1 -1
- package/dist/compiler/compile-message.locals.test.d.ts +1 -0
- package/dist/compiler/compile-message.locals.test.js +498 -0
- package/dist/compiler/compile-message.locals.test.js.map +1 -0
- package/dist/compiler/compile-message.test.js +111 -20
- package/dist/compiler/compile-message.test.js.map +1 -1
- package/dist/compiler/compile-pattern.d.ts +5 -0
- package/dist/compiler/compile-pattern.js +6 -18
- package/dist/compiler/compile-pattern.js.map +1 -1
- package/dist/compiler/compile-pattern.test.js +165 -1
- package/dist/compiler/compile-pattern.test.js.map +1 -1
- package/dist/compiler/compile-project.js +4 -1
- package/dist/compiler/compile-project.js.map +1 -1
- package/dist/compiler/compile-project.test.js +1013 -31
- package/dist/compiler/compile-project.test.js.map +1 -1
- package/dist/compiler/compile.test.js +1 -1
- package/dist/compiler/compile.test.js.map +1 -1
- package/dist/compiler/create-readme.d.ts +4 -1
- package/dist/compiler/create-readme.js +33 -125
- package/dist/compiler/create-readme.js.map +1 -1
- package/dist/compiler/emit-ts-declarations.interop.test.js +2 -2
- package/dist/compiler/emit-ts-declarations.interop.test.js.map +1 -1
- package/dist/compiler/emit-ts-declarations.test.js +4 -4
- package/dist/compiler/emit-ts-declarations.test.js.map +1 -1
- package/dist/compiler/index.d.ts +1 -1
- package/dist/compiler/index.js +1 -1
- package/dist/compiler/index.js.map +1 -1
- package/dist/compiler/input-alias.d.ts +21 -0
- package/dist/compiler/input-alias.js +42 -0
- package/dist/compiler/input-alias.js.map +1 -0
- package/dist/compiler/input-alias.test.d.ts +1 -0
- package/dist/compiler/input-alias.test.js +58 -0
- package/dist/compiler/input-alias.test.js.map +1 -0
- package/dist/compiler/message-locals.d.ts +46 -0
- package/dist/compiler/message-locals.js +129 -0
- package/dist/compiler/message-locals.js.map +1 -0
- package/dist/compiler/output-structure/locale-modules.js +7 -1
- package/dist/compiler/output-structure/locale-modules.js.map +1 -1
- package/dist/compiler/output-structure/locale-modules.test.js +35 -0
- package/dist/compiler/output-structure/locale-modules.test.js.map +1 -1
- package/dist/compiler/output-structure/message-modules.js +5 -3
- package/dist/compiler/output-structure/message-modules.js.map +1 -1
- package/dist/compiler/output-structure/message-modules.test.js +35 -0
- package/dist/compiler/output-structure/message-modules.test.js.map +1 -1
- package/dist/compiler/registry.d.ts +12 -0
- package/dist/compiler/registry.js +97 -28
- package/dist/compiler/registry.js.map +1 -1
- package/dist/compiler/server/create-server-file.js +24 -0
- package/dist/compiler/server/create-server-file.js.map +1 -1
- package/dist/compiler/server/create-server-file.test.js +8 -2
- package/dist/compiler/server/create-server-file.test.js.map +1 -1
- package/dist/compiler/server/middleware.js +29 -4
- package/dist/compiler/server/middleware.js.map +1 -1
- package/dist/services/env-variables/index.js +1 -1
- package/dist/services/env-variables/index.js.map +1 -1
- package/package.json +3 -3
|
@@ -13,10 +13,12 @@ test("should emit per locale message files", () => {
|
|
|
13
13
|
en: {
|
|
14
14
|
code: 'console.log("message in English");',
|
|
15
15
|
node: {},
|
|
16
|
+
registryFunctions: [],
|
|
16
17
|
},
|
|
17
18
|
de: {
|
|
18
19
|
code: 'console.log("message in German");',
|
|
19
20
|
node: {},
|
|
21
|
+
registryFunctions: [],
|
|
20
22
|
},
|
|
21
23
|
},
|
|
22
24
|
matchTypes: new Map(),
|
|
@@ -48,6 +50,7 @@ test("handles case senstivity by creating directories and files only in lowercas
|
|
|
48
50
|
en: {
|
|
49
51
|
code: 'export const HappyElephant = () => "HappyElephant0"',
|
|
50
52
|
node: {},
|
|
53
|
+
registryFunctions: [],
|
|
51
54
|
},
|
|
52
55
|
},
|
|
53
56
|
matchTypes: new Map(),
|
|
@@ -63,6 +66,7 @@ test("handles case senstivity by creating directories and files only in lowercas
|
|
|
63
66
|
en: {
|
|
64
67
|
code: 'export const happyelephant = () => "happyelephant1"',
|
|
65
68
|
node: {},
|
|
69
|
+
registryFunctions: [],
|
|
66
70
|
},
|
|
67
71
|
},
|
|
68
72
|
matchTypes: new Map(),
|
|
@@ -91,6 +95,7 @@ test("emits minimal runtime imports when middleware splitting is disabled", () =
|
|
|
91
95
|
en: {
|
|
92
96
|
code: '() => "happy"',
|
|
93
97
|
node: {},
|
|
98
|
+
registryFunctions: [],
|
|
94
99
|
},
|
|
95
100
|
},
|
|
96
101
|
matchTypes: new Map(),
|
|
@@ -117,6 +122,7 @@ test("emits fallback definitions after their dependencies", () => {
|
|
|
117
122
|
en: {
|
|
118
123
|
code: '/** @type {(inputs: {}) => string} */ () => "admin"',
|
|
119
124
|
node: {},
|
|
125
|
+
registryFunctions: [],
|
|
120
126
|
},
|
|
121
127
|
},
|
|
122
128
|
matchTypes: new Map(),
|
|
@@ -145,4 +151,33 @@ test("emits fallback definitions after their dependencies", () => {
|
|
|
145
151
|
expect(frCaIndex).toBeGreaterThan(-1);
|
|
146
152
|
expect(frIndex).toBeLessThan(frCaIndex);
|
|
147
153
|
});
|
|
154
|
+
test("imports the registry only when a message calls it, not when the text mentions it", () => {
|
|
155
|
+
const bundle = (id, code, registryFunctions) => ({
|
|
156
|
+
bundle: {
|
|
157
|
+
code: `export const ${id} = () => en_${id}()`,
|
|
158
|
+
node: { id },
|
|
159
|
+
},
|
|
160
|
+
messages: {
|
|
161
|
+
en: { code, node: {}, registryFunctions },
|
|
162
|
+
},
|
|
163
|
+
matchTypes: new Map(),
|
|
164
|
+
});
|
|
165
|
+
const settings = {
|
|
166
|
+
locales: ["en"],
|
|
167
|
+
baseLocale: "en",
|
|
168
|
+
};
|
|
169
|
+
const registryImport = /import \* as registry from ['"]\.\.\/registry\.js['"]/;
|
|
170
|
+
const textOnly = generateOutput([bundle("registry_text", "() => `Open the registry. Now.`", [])], settings, { en: undefined });
|
|
171
|
+
for (const [fileName, code] of Object.entries(textOnly)) {
|
|
172
|
+
if (fileName.startsWith("messages/")) {
|
|
173
|
+
expect(code).not.toMatch(registryImport);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
const withNumber = generateOutput([
|
|
177
|
+
bundle("amount", '(i) => `${registry.number("en", i?.amount, {})}`', [
|
|
178
|
+
"number",
|
|
179
|
+
]),
|
|
180
|
+
], settings, { en: undefined });
|
|
181
|
+
expect(Object.values(withNumber).some((code) => registryImport.test(code))).toBe(true);
|
|
182
|
+
});
|
|
148
183
|
//# sourceMappingURL=message-modules.test.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"message-modules.test.js","sourceRoot":"","sources":["../../../src/compiler/output-structure/message-modules.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACtC,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAItD,IAAI,CAAC,sCAAsC,EAAE,GAAG,EAAE;IACjD,MAAM,SAAS,GAAiC;QAC/C;YACC,MAAM,EAAE;gBACP,IAAI,EAAE,6BAA6B;gBACnC,IAAI,EAAE;oBACL,EAAE,EAAE,gBAAgB;iBACC;aACtB;YACD,QAAQ,EAAE;gBACT,EAAE,EAAE;oBACH,IAAI,EAAE,oCAAoC;oBAC1C,IAAI,EAAE,EAAwB;iBAC9B;gBACD,EAAE,EAAE;oBACH,IAAI,EAAE,mCAAmC;oBACzC,IAAI,EAAE,EAAwB;iBAC9B;aACD;YACD,UAAU,EAAE,IAAI,GAAG,EAAE;SACrB;KACD,CAAC;IAEF,MAAM,QAAQ,GAAoD;QACjE,OAAO,EAAE,CAAC,IAAI,EAAE,IAAI,CAAC;QACrB,UAAU,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YAAY,CAAC,SAAS,CAAC,CAAC;AACzC,CAAC,CAAC,CAAC","sourcesContent":["import { test, expect } from \"vitest\";\nimport { generateOutput } from \"./message-modules.js\";\nimport type { Bundle, Message, ProjectSettings } from \"@inlang/sdk\";\nimport type { CompiledBundleWithMessages } from \"../compile-bundle.js\";\n\ntest(\"should emit per locale message files\", () => {\n\tconst resources: CompiledBundleWithMessages[] = [\n\t\t{\n\t\t\tbundle: {\n\t\t\t\tcode: 'console.log(\"bundle code\");',\n\t\t\t\tnode: {\n\t\t\t\t\tid: \"happy_elephant\",\n\t\t\t\t} as unknown as Bundle,\n\t\t\t},\n\t\t\tmessages: {\n\t\t\t\ten: {\n\t\t\t\t\tcode: 'console.log(\"message in English\");',\n\t\t\t\t\tnode: {} as unknown as Message,\n\t\t\t\t},\n\t\t\t\tde: {\n\t\t\t\t\tcode: 'console.log(\"message in German\");',\n\t\t\t\t\tnode: {} as unknown as Message,\n\t\t\t\t},\n\t\t\t},\n\t\t\tmatchTypes: new Map(),\n\t\t},\n\t];\n\n\tconst settings: Pick<ProjectSettings, \"locales\" | \"baseLocale\"> = {\n\t\tlocales: [\"en\", \"de\"],\n\t\tbaseLocale: \"en\",\n\t};\n\n\tconst fallbackMap: Record<string, string | undefined> = {\n\t\ten: \"de\",\n\t\tde: \"en\",\n\t};\n\n\tconst output = generateOutput(resources, settings, fallbackMap);\n\n\texpect(output).not.toHaveProperty(\"messages/en.js\");\n\texpect(output).not.toHaveProperty(\"messages/de.js\");\n\texpect(output).toHaveProperty(\"messages/happy_elephant.js\");\n});\n\ntest(\"handles case senstivity by creating directories and files only in lowercase\", () => {\n\tconst resources: CompiledBundleWithMessages[] = [\n\t\t{\n\t\t\tbundle: {\n\t\t\t\tcode: \"export const HappyElephant = () => en.HappyElephant\",\n\t\t\t\tnode: {\n\t\t\t\t\tid: \"HappyElephant\",\n\t\t\t\t} as unknown as Bundle,\n\t\t\t},\n\t\t\tmessages: {\n\t\t\t\ten: {\n\t\t\t\t\tcode: 'export const HappyElephant = () => \"HappyElephant0\"',\n\t\t\t\t\tnode: {} as unknown as Message,\n\t\t\t\t},\n\t\t\t},\n\t\t\tmatchTypes: new Map(),\n\t\t},\n\t\t{\n\t\t\tbundle: {\n\t\t\t\tcode: \"export const happyelephant = () => en.happyelephant\",\n\t\t\t\tnode: {\n\t\t\t\t\tid: \"happyelephant\",\n\t\t\t\t} as unknown as Bundle,\n\t\t\t},\n\t\t\tmessages: {\n\t\t\t\ten: {\n\t\t\t\t\tcode: 'export const happyelephant = () => \"happyelephant1\"',\n\t\t\t\t\tnode: {} as unknown as Message,\n\t\t\t\t},\n\t\t\t},\n\t\t\tmatchTypes: new Map(),\n\t\t},\n\t];\n\tconst settings: Pick<ProjectSettings, \"locales\" | \"baseLocale\"> = {\n\t\tlocales: [\"en\"],\n\t\tbaseLocale: \"en\",\n\t};\n\tconst output = generateOutput(resources, settings, {});\n\n\t// expecting only lowercase directories and files\n\texpect(output).toHaveProperty(\"messages/happyelephant.js\");\n\texpect(output).toHaveProperty(\"messages/happyelephant2.js\");\n\texpect(output).not.toHaveProperty(\"messages/HappyElephant.js\");\n});\n\ntest(\"emits minimal runtime imports when middleware splitting is disabled\", () => {\n\tconst resources: CompiledBundleWithMessages[] = [\n\t\t{\n\t\t\tbundle: {\n\t\t\t\tcode: \"export const happy_elephant = () => en_happy_elephant()\",\n\t\t\t\tnode: {\n\t\t\t\t\tid: \"happy_elephant\",\n\t\t\t\t} as unknown as Bundle,\n\t\t\t},\n\t\t\tmessages: {\n\t\t\t\ten: {\n\t\t\t\t\tcode: '() => \"happy\"',\n\t\t\t\t\tnode: {} as unknown as Message,\n\t\t\t\t},\n\t\t\t},\n\t\t\tmatchTypes: new Map(),\n\t\t},\n\t];\n\n\tconst output = generateOutput(\n\t\tresources,\n\t\t{ locales: [\"en\"], baseLocale: \"en\" },\n\t\t{},\n\t\tfalse\n\t);\n\n\texpect(output[\"messages/happy_elephant.js\"]).toContain(\n\t\t\"import { getLocale, experimentalStaticLocale } from '../runtime.js';\"\n\t);\n\texpect(output[\"messages/happy_elephant.js\"]).not.toContain(\n\t\t\"trackMessageCall\"\n\t);\n\texpect(output[\"messages/happy_elephant.js\"]).not.toContain(\n\t\t\"experimentalMiddlewareLocaleSplitting\"\n\t);\n\texpect(output[\"messages/happy_elephant.js\"]).not.toContain(\"isServer\");\n});\n\n// Regression test for https://github.com/opral/inlang-paraglide-js/issues/507\ntest(\"emits fallback definitions after their dependencies\", () => {\n\tconst resources: CompiledBundleWithMessages[] = [\n\t\t{\n\t\t\tbundle: {\n\t\t\t\tcode: \"export const admin_tasks = (inputs) => inputs;\",\n\t\t\t\tnode: {\n\t\t\t\t\tid: \"admin_tasks\",\n\t\t\t\t\tdeclarations: [],\n\t\t\t\t} as unknown as Bundle,\n\t\t\t},\n\t\t\tmessages: {\n\t\t\t\ten: {\n\t\t\t\t\tcode: '/** @type {(inputs: {}) => string} */ () => \"admin\"',\n\t\t\t\t\tnode: {} as unknown as Message,\n\t\t\t\t},\n\t\t\t},\n\t\t\tmatchTypes: new Map(),\n\t\t},\n\t];\n\n\tconst settings: Pick<ProjectSettings, \"locales\" | \"baseLocale\"> = {\n\t\tlocales: [\"fr-ca\", \"fr\", \"en\"],\n\t\tbaseLocale: \"en\",\n\t};\n\n\tconst fallbackMap: Record<string, string | undefined> = {\n\t\t\"fr-ca\": \"fr\",\n\t\tfr: \"en\",\n\t\ten: undefined,\n\t};\n\n\tconst output = generateOutput(resources, settings, fallbackMap);\n\n\tconst file = output[\"messages/admin_tasks.js\"];\n\n\texpect(file).toBeDefined();\n\n\tif (!file) {\n\t\tthrow new Error(\"messages/admin_tasks.js should have been generated\");\n\t}\n\n\texpect(file).toContain(\"const fr_admin_tasks = en_admin_tasks;\");\n\texpect(file).toContain(\"const fr_ca_admin_tasks = fr_admin_tasks;\");\n\n\tconst frIndex = file.indexOf(\"const fr_admin_tasks\");\n\tconst frCaIndex = file.indexOf(\"const fr_ca_admin_tasks\");\n\n\texpect(frIndex).toBeGreaterThan(-1);\n\texpect(frCaIndex).toBeGreaterThan(-1);\n\texpect(frIndex).toBeLessThan(frCaIndex);\n});\n"]}
|
|
1
|
+
{"version":3,"file":"message-modules.test.js","sourceRoot":"","sources":["../../../src/compiler/output-structure/message-modules.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACtC,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAItD,IAAI,CAAC,sCAAsC,EAAE,GAAG,EAAE;IACjD,MAAM,SAAS,GAAiC;QAC/C;YACC,MAAM,EAAE;gBACP,IAAI,EAAE,6BAA6B;gBACnC,IAAI,EAAE;oBACL,EAAE,EAAE,gBAAgB;iBACC;aACtB;YACD,QAAQ,EAAE;gBACT,EAAE,EAAE;oBACH,IAAI,EAAE,oCAAoC;oBAC1C,IAAI,EAAE,EAAwB;oBAC9B,iBAAiB,EAAE,EAAE;iBACrB;gBACD,EAAE,EAAE;oBACH,IAAI,EAAE,mCAAmC;oBACzC,IAAI,EAAE,EAAwB;oBAC9B,iBAAiB,EAAE,EAAE;iBACrB;aACD;YACD,UAAU,EAAE,IAAI,GAAG,EAAE;SACrB;KACD,CAAC;IAEF,MAAM,QAAQ,GAAoD;QACjE,OAAO,EAAE,CAAC,IAAI,EAAE,IAAI,CAAC;QACrB,UAAU,EAAE,IAAI;KAChB,CAAC;IAEF,MAAM,WAAW,GAAuC;QACvD,EAAE,EAAE,IAAI;QACR,EAAE,EAAE,IAAI;KACR,CAAC;IAEF,MAAM,MAAM,GAAG,cAAc,CAAC,SAAS,EAAE,QAAQ,EAAE,WAAW,CAAC,CAAC;IAEhE,MAAM,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,cAAc,CAAC,gBAAgB,CAAC,CAAC;IACpD,MAAM,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,cAAc,CAAC,gBAAgB,CAAC,CAAC;IACpD,MAAM,CAAC,MAAM,CAAC,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,EAAE,EAAE,EAAuB;SACjC;QACD,QAAQ,EAAE;YACT,EAAE,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,EAAwB,EAAE,iBAAiB,EAAE;SAC/D;QACD,UAAU,EAAE,IAAI,GAAG,EAAE;KACrB,CAAC,CAAC;IACH,MAAM,QAAQ,GAAoD;QACjE,OAAO,EAAE,CAAC,IAAI,CAAC;QACf,UAAU,EAAE,IAAI;KAChB,CAAC;IACF,MAAM,cAAc,GACnB,uDAAuD,CAAC;IAEzD,MAAM,QAAQ,GAAG,cAAc,CAC9B,CAAC,MAAM,CAAC,eAAe,EAAE,iCAAiC,EAAE,EAAE,CAAC,CAAC,EAChE,QAAQ,EACR,EAAE,EAAE,EAAE,SAAS,EAAE,CACjB,CAAC;IACF,KAAK,MAAM,CAAC,QAAQ,EAAE,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,CAAC;QACzD,IAAI,QAAQ,CAAC,UAAU,CAAC,WAAW,CAAC,EAAE,CAAC;YACtC,MAAM,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC;QAC1C,CAAC;IACF,CAAC;IAED,MAAM,UAAU,GAAG,cAAc,CAChC;QACC,MAAM,CAAC,QAAQ,EAAE,kDAAkD,EAAE;YACpE,QAAQ;SACR,CAAC;KACF,EACD,QAAQ,EACR,EAAE,EAAE,EAAE,SAAS,EAAE,CACjB,CAAC;IACF,MAAM,CACL,MAAM,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CACnE,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACd,CAAC,CAAC,CAAC","sourcesContent":["import { test, expect } from \"vitest\";\nimport { generateOutput } from \"./message-modules.js\";\nimport type { Bundle, Message, ProjectSettings } from \"@inlang/sdk\";\nimport type { CompiledBundleWithMessages } from \"../compile-bundle.js\";\n\ntest(\"should emit per locale message files\", () => {\n\tconst resources: CompiledBundleWithMessages[] = [\n\t\t{\n\t\t\tbundle: {\n\t\t\t\tcode: 'console.log(\"bundle code\");',\n\t\t\t\tnode: {\n\t\t\t\t\tid: \"happy_elephant\",\n\t\t\t\t} as unknown as Bundle,\n\t\t\t},\n\t\t\tmessages: {\n\t\t\t\ten: {\n\t\t\t\t\tcode: 'console.log(\"message in English\");',\n\t\t\t\t\tnode: {} as unknown as Message,\n\t\t\t\t\tregistryFunctions: [],\n\t\t\t\t},\n\t\t\t\tde: {\n\t\t\t\t\tcode: 'console.log(\"message in German\");',\n\t\t\t\t\tnode: {} as unknown as Message,\n\t\t\t\t\tregistryFunctions: [],\n\t\t\t\t},\n\t\t\t},\n\t\t\tmatchTypes: new Map(),\n\t\t},\n\t];\n\n\tconst settings: Pick<ProjectSettings, \"locales\" | \"baseLocale\"> = {\n\t\tlocales: [\"en\", \"de\"],\n\t\tbaseLocale: \"en\",\n\t};\n\n\tconst fallbackMap: Record<string, string | undefined> = {\n\t\ten: \"de\",\n\t\tde: \"en\",\n\t};\n\n\tconst output = generateOutput(resources, settings, fallbackMap);\n\n\texpect(output).not.toHaveProperty(\"messages/en.js\");\n\texpect(output).not.toHaveProperty(\"messages/de.js\");\n\texpect(output).toHaveProperty(\"messages/happy_elephant.js\");\n});\n\ntest(\"handles case senstivity by creating directories and files only in lowercase\", () => {\n\tconst resources: CompiledBundleWithMessages[] = [\n\t\t{\n\t\t\tbundle: {\n\t\t\t\tcode: \"export const HappyElephant = () => en.HappyElephant\",\n\t\t\t\tnode: {\n\t\t\t\t\tid: \"HappyElephant\",\n\t\t\t\t} as unknown as Bundle,\n\t\t\t},\n\t\t\tmessages: {\n\t\t\t\ten: {\n\t\t\t\t\tcode: 'export const HappyElephant = () => \"HappyElephant0\"',\n\t\t\t\t\tnode: {} as unknown as Message,\n\t\t\t\t\tregistryFunctions: [],\n\t\t\t\t},\n\t\t\t},\n\t\t\tmatchTypes: new Map(),\n\t\t},\n\t\t{\n\t\t\tbundle: {\n\t\t\t\tcode: \"export const happyelephant = () => en.happyelephant\",\n\t\t\t\tnode: {\n\t\t\t\t\tid: \"happyelephant\",\n\t\t\t\t} as unknown as Bundle,\n\t\t\t},\n\t\t\tmessages: {\n\t\t\t\ten: {\n\t\t\t\t\tcode: 'export const happyelephant = () => \"happyelephant1\"',\n\t\t\t\t\tnode: {} as unknown as Message,\n\t\t\t\t\tregistryFunctions: [],\n\t\t\t\t},\n\t\t\t},\n\t\t\tmatchTypes: new Map(),\n\t\t},\n\t];\n\tconst settings: Pick<ProjectSettings, \"locales\" | \"baseLocale\"> = {\n\t\tlocales: [\"en\"],\n\t\tbaseLocale: \"en\",\n\t};\n\tconst output = generateOutput(resources, settings, {});\n\n\t// expecting only lowercase directories and files\n\texpect(output).toHaveProperty(\"messages/happyelephant.js\");\n\texpect(output).toHaveProperty(\"messages/happyelephant2.js\");\n\texpect(output).not.toHaveProperty(\"messages/HappyElephant.js\");\n});\n\ntest(\"emits minimal runtime imports when middleware splitting is disabled\", () => {\n\tconst resources: CompiledBundleWithMessages[] = [\n\t\t{\n\t\t\tbundle: {\n\t\t\t\tcode: \"export const happy_elephant = () => en_happy_elephant()\",\n\t\t\t\tnode: {\n\t\t\t\t\tid: \"happy_elephant\",\n\t\t\t\t} as unknown as Bundle,\n\t\t\t},\n\t\t\tmessages: {\n\t\t\t\ten: {\n\t\t\t\t\tcode: '() => \"happy\"',\n\t\t\t\t\tnode: {} as unknown as Message,\n\t\t\t\t\tregistryFunctions: [],\n\t\t\t\t},\n\t\t\t},\n\t\t\tmatchTypes: new Map(),\n\t\t},\n\t];\n\n\tconst output = generateOutput(\n\t\tresources,\n\t\t{ locales: [\"en\"], baseLocale: \"en\" },\n\t\t{},\n\t\tfalse\n\t);\n\n\texpect(output[\"messages/happy_elephant.js\"]).toContain(\n\t\t\"import { getLocale, experimentalStaticLocale } from '../runtime.js';\"\n\t);\n\texpect(output[\"messages/happy_elephant.js\"]).not.toContain(\n\t\t\"trackMessageCall\"\n\t);\n\texpect(output[\"messages/happy_elephant.js\"]).not.toContain(\n\t\t\"experimentalMiddlewareLocaleSplitting\"\n\t);\n\texpect(output[\"messages/happy_elephant.js\"]).not.toContain(\"isServer\");\n});\n\n// Regression test for https://github.com/opral/inlang-paraglide-js/issues/507\ntest(\"emits fallback definitions after their dependencies\", () => {\n\tconst resources: CompiledBundleWithMessages[] = [\n\t\t{\n\t\t\tbundle: {\n\t\t\t\tcode: \"export const admin_tasks = (inputs) => inputs;\",\n\t\t\t\tnode: {\n\t\t\t\t\tid: \"admin_tasks\",\n\t\t\t\t\tdeclarations: [],\n\t\t\t\t} as unknown as Bundle,\n\t\t\t},\n\t\t\tmessages: {\n\t\t\t\ten: {\n\t\t\t\t\tcode: '/** @type {(inputs: {}) => string} */ () => \"admin\"',\n\t\t\t\t\tnode: {} as unknown as Message,\n\t\t\t\t\tregistryFunctions: [],\n\t\t\t\t},\n\t\t\t},\n\t\t\tmatchTypes: new Map(),\n\t\t},\n\t];\n\n\tconst settings: Pick<ProjectSettings, \"locales\" | \"baseLocale\"> = {\n\t\tlocales: [\"fr-ca\", \"fr\", \"en\"],\n\t\tbaseLocale: \"en\",\n\t};\n\n\tconst fallbackMap: Record<string, string | undefined> = {\n\t\t\"fr-ca\": \"fr\",\n\t\tfr: \"en\",\n\t\ten: undefined,\n\t};\n\n\tconst output = generateOutput(resources, settings, fallbackMap);\n\n\tconst file = output[\"messages/admin_tasks.js\"];\n\n\texpect(file).toBeDefined();\n\n\tif (!file) {\n\t\tthrow new Error(\"messages/admin_tasks.js should have been generated\");\n\t}\n\n\texpect(file).toContain(\"const fr_admin_tasks = en_admin_tasks;\");\n\texpect(file).toContain(\"const fr_ca_admin_tasks = fr_admin_tasks;\");\n\n\tconst frIndex = file.indexOf(\"const fr_admin_tasks\");\n\tconst frCaIndex = file.indexOf(\"const fr_ca_admin_tasks\");\n\n\texpect(frIndex).toBeGreaterThan(-1);\n\texpect(frCaIndex).toBeGreaterThan(-1);\n\texpect(frIndex).toBeLessThan(frCaIndex);\n});\n\ntest(\"imports the registry only when a message calls it, not when the text mentions it\", () => {\n\tconst bundle = (\n\t\tid: string,\n\t\tcode: string,\n\t\tregistryFunctions: string[]\n\t): CompiledBundleWithMessages => ({\n\t\tbundle: {\n\t\t\tcode: `export const ${id} = () => en_${id}()`,\n\t\t\tnode: { id } as unknown as Bundle,\n\t\t},\n\t\tmessages: {\n\t\t\ten: { code, node: {} as unknown as Message, registryFunctions },\n\t\t},\n\t\tmatchTypes: new Map(),\n\t});\n\tconst settings: Pick<ProjectSettings, \"locales\" | \"baseLocale\"> = {\n\t\tlocales: [\"en\"],\n\t\tbaseLocale: \"en\",\n\t};\n\tconst registryImport =\n\t\t/import \\* as registry from ['\"]\\.\\.\\/registry\\.js['\"]/;\n\n\tconst textOnly = generateOutput(\n\t\t[bundle(\"registry_text\", \"() => `Open the registry. Now.`\", [])],\n\t\tsettings,\n\t\t{ en: undefined }\n\t);\n\tfor (const [fileName, code] of Object.entries(textOnly)) {\n\t\tif (fileName.startsWith(\"messages/\")) {\n\t\t\texpect(code).not.toMatch(registryImport);\n\t\t}\n\t}\n\n\tconst withNumber = generateOutput(\n\t\t[\n\t\t\tbundle(\"amount\", '(i) => `${registry.number(\"en\", i?.amount, {})}`', [\n\t\t\t\t\"number\",\n\t\t\t]),\n\t\t],\n\t\tsettings,\n\t\t{ en: undefined }\n\t);\n\texpect(\n\t\tObject.values(withNumber).some((code) => registryImport.test(code))\n\t).toBe(true);\n});\n"]}
|
|
@@ -11,3 +11,15 @@
|
|
|
11
11
|
* Creates the Registry file
|
|
12
12
|
*/
|
|
13
13
|
export declare function createRegistry(): string;
|
|
14
|
+
/**
|
|
15
|
+
* Returns the given registry functions and the registry functions they call,
|
|
16
|
+
* in registry order.
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* withRegistryDependencies(["icuPound"]) // ["number", "icuPound"]
|
|
20
|
+
*/
|
|
21
|
+
export declare function withRegistryDependencies(names: Iterable<string>): string[];
|
|
22
|
+
/**
|
|
23
|
+
* Returns the code of the given registry functions without `export`, by name.
|
|
24
|
+
*/
|
|
25
|
+
export declare function registryFunctionCode(names: Iterable<string>): Record<string, string>;
|
|
@@ -8,53 +8,122 @@
|
|
|
8
8
|
* For now, Paraglide ships a custom solution with INTL functions.
|
|
9
9
|
*/
|
|
10
10
|
/**
|
|
11
|
-
*
|
|
12
|
-
*/
|
|
13
|
-
export function createRegistry() {
|
|
14
|
-
return `
|
|
15
|
-
/**
|
|
16
|
-
* @typedef {"year" | "years" | "quarter" | "quarters" | "month" | "months" | "week" | "weeks" | "day" | "days" | "hour" | "hours" | "minute" | "minutes" | "second" | "seconds"} RelativeTimeFormatUnit
|
|
11
|
+
* The functions of the generated registry.js file, by name.
|
|
17
12
|
*/
|
|
18
|
-
|
|
19
|
-
|
|
13
|
+
const registryFunctions = {
|
|
14
|
+
plural: {
|
|
15
|
+
jsdoc: `/**
|
|
16
|
+
* Selects the plural category of "input - options.offset". The offset
|
|
17
|
+
* comes from ICU MessageFormat 1 "{count, plural, offset:1 ...}" and does not
|
|
18
|
+
* change exact matches like "=0", which compare the input itself.
|
|
19
|
+
*
|
|
20
20
|
* @param {import("./runtime.js").Locale} locale
|
|
21
21
|
* @param {unknown} input
|
|
22
|
-
* @param {Intl.PluralRulesOptions} [options]
|
|
22
|
+
* @param {Intl.PluralRulesOptions & { offset?: unknown }} [options]
|
|
23
23
|
* @returns {string}
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
return new Intl.PluralRules(locale, options).select(Number(input))
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
|
|
24
|
+
*/`,
|
|
25
|
+
code: `function plural(locale, input, options) {
|
|
26
|
+
return new Intl.PluralRules(locale, options).select(Number(input) - Number(options?.offset ?? 0))
|
|
27
|
+
};`,
|
|
28
|
+
dependencies: [],
|
|
29
|
+
},
|
|
30
|
+
number: {
|
|
31
|
+
jsdoc: `/**
|
|
30
32
|
* @param {import("./runtime.js").Locale} locale
|
|
31
33
|
* @param {unknown} input
|
|
32
34
|
* @param {Intl.NumberFormatOptions} [options]
|
|
33
35
|
* @returns {string}
|
|
34
|
-
|
|
35
|
-
|
|
36
|
+
*/`,
|
|
37
|
+
code: `function number(locale, input, options) {
|
|
36
38
|
return new Intl.NumberFormat(locale, options).format(Number(input))
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
|
|
39
|
+
};`,
|
|
40
|
+
dependencies: [],
|
|
41
|
+
},
|
|
42
|
+
icuPound: {
|
|
43
|
+
jsdoc: `/**
|
|
44
|
+
* Formats "#" in ICU MessageFormat 1 plurals: the number "input - options.offset",
|
|
45
|
+
* formatted like number(). The offset comes from "{count, plural, offset:1 ...}".
|
|
46
|
+
* An input that is not a finite number (or a numeric string) is displayed as is,
|
|
47
|
+
* without subtracting the offset.
|
|
48
|
+
*
|
|
49
|
+
* @param {import("./runtime.js").Locale} locale
|
|
50
|
+
* @param {unknown} input
|
|
51
|
+
* @param {{ offset?: unknown }} [options]
|
|
52
|
+
* @returns {string}
|
|
53
|
+
*/`,
|
|
54
|
+
code: `function icuPound(locale, input, options) {
|
|
55
|
+
const value = typeof input === "number" ? input : typeof input === "string" && input.trim() !== "" ? Number(input) : NaN
|
|
56
|
+
if (!Number.isFinite(value)) return String(input)
|
|
57
|
+
return number(locale, value - Number(options?.offset ?? 0))
|
|
58
|
+
};`,
|
|
59
|
+
dependencies: ["number"],
|
|
60
|
+
},
|
|
61
|
+
datetime: {
|
|
62
|
+
jsdoc: `/**
|
|
40
63
|
* @param {import("./runtime.js").Locale} locale
|
|
41
64
|
* @param {unknown} input
|
|
42
65
|
* @param {Intl.DateTimeFormatOptions} [options]
|
|
43
66
|
* @returns {string}
|
|
44
|
-
|
|
45
|
-
|
|
67
|
+
*/`,
|
|
68
|
+
code: `function datetime(locale, input, options) {
|
|
46
69
|
return new Intl.DateTimeFormat(locale, options).format(new Date(/** @type {string} */ (input)))
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
|
|
70
|
+
};`,
|
|
71
|
+
dependencies: [],
|
|
72
|
+
},
|
|
73
|
+
relativetime: {
|
|
74
|
+
jsdoc: `/**
|
|
50
75
|
* @param {import("./runtime.js").Locale} locale
|
|
51
76
|
* @param {unknown} input
|
|
52
77
|
* @param {Intl.RelativeTimeFormatOptions & { unit: RelativeTimeFormatUnit }} options
|
|
53
78
|
* @returns {string}
|
|
54
|
-
|
|
55
|
-
|
|
79
|
+
*/`,
|
|
80
|
+
code: `function relativetime(locale, input, options) {
|
|
56
81
|
const { unit, ...intlOptions } = options;
|
|
57
82
|
return new Intl.RelativeTimeFormat(locale, intlOptions).format(Number(input), unit);
|
|
58
|
-
}
|
|
83
|
+
};`,
|
|
84
|
+
dependencies: [],
|
|
85
|
+
},
|
|
86
|
+
};
|
|
87
|
+
/**
|
|
88
|
+
* Creates the Registry file
|
|
89
|
+
*/
|
|
90
|
+
export function createRegistry() {
|
|
91
|
+
return `
|
|
92
|
+
/**
|
|
93
|
+
* @typedef {"year" | "years" | "quarter" | "quarters" | "month" | "months" | "week" | "weeks" | "day" | "days" | "hour" | "hours" | "minute" | "minutes" | "second" | "seconds"} RelativeTimeFormatUnit
|
|
94
|
+
*/
|
|
95
|
+
|
|
96
|
+
${Object.values(registryFunctions)
|
|
97
|
+
.map((fn) => `${fn.jsdoc}\nexport ${fn.code}`)
|
|
98
|
+
.join("\n\n")}`;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Returns the given registry functions and the registry functions they call,
|
|
102
|
+
* in registry order.
|
|
103
|
+
*
|
|
104
|
+
* @example
|
|
105
|
+
* withRegistryDependencies(["icuPound"]) // ["number", "icuPound"]
|
|
106
|
+
*/
|
|
107
|
+
export function withRegistryDependencies(names) {
|
|
108
|
+
const needed = new Set();
|
|
109
|
+
const add = (name) => {
|
|
110
|
+
const fn = registryFunctions[name];
|
|
111
|
+
if (!fn || needed.has(name))
|
|
112
|
+
return;
|
|
113
|
+
needed.add(name);
|
|
114
|
+
fn.dependencies.forEach(add);
|
|
115
|
+
};
|
|
116
|
+
for (const name of names)
|
|
117
|
+
add(name);
|
|
118
|
+
return Object.keys(registryFunctions).filter((name) => needed.has(name));
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Returns the code of the given registry functions without `export`, by name.
|
|
122
|
+
*/
|
|
123
|
+
export function registryFunctionCode(names) {
|
|
124
|
+
return Object.fromEntries(Array.from(names).flatMap((name) => {
|
|
125
|
+
const fn = registryFunctions[name];
|
|
126
|
+
return fn ? [[name, fn.code]] : [];
|
|
127
|
+
}));
|
|
59
128
|
}
|
|
60
129
|
//# sourceMappingURL=registry.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registry.js","sourceRoot":"","sources":["../../src/compiler/registry.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;
|
|
1
|
+
{"version":3,"file":"registry.js","sourceRoot":"","sources":["../../src/compiler/registry.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAWH;;GAEG;AACH,MAAM,iBAAiB,GAAqC;IAC3D,MAAM,EAAE;QACP,KAAK,EAAE;;;;;;;;;IASL;QACF,IAAI,EAAE;;GAEL;QACD,YAAY,EAAE,EAAE;KAChB;IACD,MAAM,EAAE;QACP,KAAK,EAAE;;;;;IAKL;QACF,IAAI,EAAE;;GAEL;QACD,YAAY,EAAE,EAAE;KAChB;IACD,QAAQ,EAAE;QACT,KAAK,EAAE;;;;;;;;;;IAUL;QACF,IAAI,EAAE;;;;GAIL;QACD,YAAY,EAAE,CAAC,QAAQ,CAAC;KACxB;IACD,QAAQ,EAAE;QACT,KAAK,EAAE;;;;;IAKL;QACF,IAAI,EAAE;;GAEL;QACD,YAAY,EAAE,EAAE;KAChB;IACD,YAAY,EAAE;QACb,KAAK,EAAE;;;;;IAKL;QACF,IAAI,EAAE;;;GAGL;QACD,YAAY,EAAE,EAAE;KAChB;CAC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AAC,CAAC,CAAC,EAAE,CAAC;IACpC,CAAC,CAAC,CACF,CAAC;AACH,CAAC","sourcesContent":["/**\n * Re: CUSTOMIZING THE REGISTRY\n *\n * We want to enable anyone (designer, developer, translator) to\n * specify options for functions. That requires design work in\n * the inlang SDK.\n *\n * For now, Paraglide ships a custom solution with INTL functions.\n */\n\ntype RegistryFunction = {\n\t/** JSDoc of the function in registry.js */\n\tjsdoc: string;\n\t/** The function declaration, without `export` */\n\tcode: string;\n\t/** Registry functions the code calls */\n\tdependencies: string[];\n};\n\n/**\n * The functions of the generated registry.js file, by name.\n */\nconst registryFunctions: Record<string, RegistryFunction> = {\n\tplural: {\n\t\tjsdoc: `/**\n * Selects the plural category of \"input - options.offset\". The offset\n * comes from ICU MessageFormat 1 \"{count, plural, offset:1 ...}\" and does not\n * change exact matches like \"=0\", which compare the input itself.\n *\n * @param {import(\"./runtime.js\").Locale} locale\n * @param {unknown} input\n * @param {Intl.PluralRulesOptions & { offset?: unknown }} [options]\n * @returns {string}\n */`,\n\t\tcode: `function plural(locale, input, options) {\n\treturn new Intl.PluralRules(locale, options).select(Number(input) - Number(options?.offset ?? 0))\n};`,\n\t\tdependencies: [],\n\t},\n\tnumber: {\n\t\tjsdoc: `/**\n * @param {import(\"./runtime.js\").Locale} locale\n * @param {unknown} input\n * @param {Intl.NumberFormatOptions} [options]\n * @returns {string}\n */`,\n\t\tcode: `function number(locale, input, options) {\n\treturn new Intl.NumberFormat(locale, options).format(Number(input))\n};`,\n\t\tdependencies: [],\n\t},\n\ticuPound: {\n\t\tjsdoc: `/**\n * Formats \"#\" in ICU MessageFormat 1 plurals: the number \"input - options.offset\",\n * formatted like number(). The offset comes from \"{count, plural, offset:1 ...}\".\n * An input that is not a finite number (or a numeric string) is displayed as is,\n * without subtracting the offset.\n *\n * @param {import(\"./runtime.js\").Locale} locale\n * @param {unknown} input\n * @param {{ offset?: unknown }} [options]\n * @returns {string}\n */`,\n\t\tcode: `function icuPound(locale, input, options) {\n\tconst value = typeof input === \"number\" ? input : typeof input === \"string\" && input.trim() !== \"\" ? Number(input) : NaN\n\tif (!Number.isFinite(value)) return String(input)\n\treturn number(locale, value - Number(options?.offset ?? 0))\n};`,\n\t\tdependencies: [\"number\"],\n\t},\n\tdatetime: {\n\t\tjsdoc: `/**\n * @param {import(\"./runtime.js\").Locale} locale\n * @param {unknown} input\n * @param {Intl.DateTimeFormatOptions} [options]\n * @returns {string}\n */`,\n\t\tcode: `function datetime(locale, input, options) {\n\treturn new Intl.DateTimeFormat(locale, options).format(new Date(/** @type {string} */ (input)))\n};`,\n\t\tdependencies: [],\n\t},\n\trelativetime: {\n\t\tjsdoc: `/**\n * @param {import(\"./runtime.js\").Locale} locale\n * @param {unknown} input\n * @param {Intl.RelativeTimeFormatOptions & { unit: RelativeTimeFormatUnit }} options\n * @returns {string}\n */`,\n\t\tcode: `function relativetime(locale, input, options) {\n\tconst { unit, ...intlOptions } = options;\n\treturn new Intl.RelativeTimeFormat(locale, intlOptions).format(Number(input), unit);\n};`,\n\t\tdependencies: [],\n\t},\n};\n\n/**\n * Creates the Registry file\n */\nexport function createRegistry(): string {\n\treturn `\n/**\n * @typedef {\"year\" | \"years\" | \"quarter\" | \"quarters\" | \"month\" | \"months\" | \"week\" | \"weeks\" | \"day\" | \"days\" | \"hour\" | \"hours\" | \"minute\" | \"minutes\" | \"second\" | \"seconds\"} RelativeTimeFormatUnit\n */\n\n${Object.values(registryFunctions)\n\t.map((fn) => `${fn.jsdoc}\\nexport ${fn.code}`)\n\t.join(\"\\n\\n\")}`;\n}\n\n/**\n * Returns the given registry functions and the registry functions they call,\n * in registry order.\n *\n * @example\n * withRegistryDependencies([\"icuPound\"]) // [\"number\", \"icuPound\"]\n */\nexport function withRegistryDependencies(names: Iterable<string>): string[] {\n\tconst needed = new Set<string>();\n\tconst add = (name: string) => {\n\t\tconst fn = registryFunctions[name];\n\t\tif (!fn || needed.has(name)) return;\n\t\tneeded.add(name);\n\t\tfn.dependencies.forEach(add);\n\t};\n\tfor (const name of names) add(name);\n\treturn Object.keys(registryFunctions).filter((name) => needed.has(name));\n}\n\n/**\n * Returns the code of the given registry functions without `export`, by name.\n */\nexport function registryFunctionCode(\n\tnames: Iterable<string>\n): Record<string, string> {\n\treturn Object.fromEntries(\n\t\tArray.from(names).flatMap((name) => {\n\t\t\tconst fn = registryFunctions[name];\n\t\t\treturn fn ? [[name, fn.code]] : [];\n\t\t})\n\t);\n}\n"]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
2
|
import { toSafeModuleId } from "../safe-module-id.js";
|
|
3
|
+
import { registryFunctionCode, withRegistryDependencies } from "../registry.js";
|
|
3
4
|
/**
|
|
4
5
|
* Returns the code for the `runtime.js` module
|
|
5
6
|
*/
|
|
@@ -57,6 +58,7 @@ ${injectCode("./middleware.js")}
|
|
|
57
58
|
// corrupting the generated server file. A function's return value is
|
|
58
59
|
// used literally, with no pattern expansion.
|
|
59
60
|
code = code.replace("const compiledBundles = {};", () => `const compiledBundles = ${JSON.stringify(createCompiledMessagesObject(args.compiledBundles))};`);
|
|
61
|
+
code = code.replace("const compiledRegistry = { functions: {}, messages: {} };", () => `const compiledRegistry = ${JSON.stringify(createCompiledRegistryObject(args.compiledBundles))};`);
|
|
60
62
|
}
|
|
61
63
|
return code.replace(/\t/g, " ");
|
|
62
64
|
}
|
|
@@ -81,6 +83,28 @@ function createCompiledMessagesObject(compiledBundles) {
|
|
|
81
83
|
}
|
|
82
84
|
return result;
|
|
83
85
|
}
|
|
86
|
+
/**
|
|
87
|
+
* The registry functions each compiled message calls, and their code, for
|
|
88
|
+
* the messages the middleware injects into the page. Those run without
|
|
89
|
+
* registry.js.
|
|
90
|
+
*/
|
|
91
|
+
function createCompiledRegistryObject(compiledBundles) {
|
|
92
|
+
const messages = {};
|
|
93
|
+
const used = new Set();
|
|
94
|
+
for (const compiledBundle of compiledBundles) {
|
|
95
|
+
const safeModuleId = toSafeModuleId(compiledBundle.bundle.node.id);
|
|
96
|
+
for (const [locale, compiledMessage] of Object.entries(compiledBundle.messages)) {
|
|
97
|
+
const names = withRegistryDependencies(compiledMessage.registryFunctions);
|
|
98
|
+
if (names.length === 0)
|
|
99
|
+
continue;
|
|
100
|
+
messages[safeModuleId] ??= {};
|
|
101
|
+
messages[safeModuleId][locale] = names;
|
|
102
|
+
for (const name of names)
|
|
103
|
+
used.add(name);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return { functions: registryFunctionCode(used), messages };
|
|
107
|
+
}
|
|
84
108
|
/**
|
|
85
109
|
* Load a file from the current directory.
|
|
86
110
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-server-file.js","sourceRoot":"","sources":["../../../src/compiler/server/create-server-file.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,SAAS,CAAC;AAGzB,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAGtD;;GAEG;AACH,MAAM,UAAU,gBAAgB,CAAC,IAUhC;IACA,IAAI,IAAI,GAAG;;;EAGV,UAAU,CAAC,iBAAiB,CAAC;CAC9B,CAAC;IAED,MAAM,uBAAuB,GAAG,yBAAyB,CAAC;IAC1D,MAAM,WAAW,GAAG,IAAI,CAAC,OAAO,CAAC,uBAAuB,CAAC,CAAC;IAC1D,IAAI,WAAW,KAAK,CAAC,CAAC,EAAE,CAAC;QACxB,MAAM,IAAI,KAAK,CACd,qEAAqE,CACrE,CAAC;IACH,CAAC;IAED,MAAM,SAAS,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,EAAE,WAAW,CAAC,GAAG,CAAC,CAAC;IAC1D,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;IACvE,MAAM,WAAW,GAAG,GAAG,MAAM,IAAI,CAAC;IAClC,MAAM,sBAAsB,GAAG,IAAI,CAAC,eAAe,CAAC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AAC;IAC9D,OAAO,IAAI;SACT,OAAO,CAAC,WAAW,EAAE,EAAE,CAAC;SACxB,OAAO,CAAC,cAAc,EAAE,EAAE,CAAC;SAC3B,OAAO,CAAC,mBAAmB,EAAE,EAAE,CAAC;SAChC,IAAI,EAAE,CAAC;AACV,CAAC","sourcesContent":["import fs from \"node:fs\";\nimport type { CompiledBundleWithMessages } from \"../compile-bundle.js\";\nimport type { CompilerOptions } from \"../compiler-options.js\";\nimport { toSafeModuleId } from \"../safe-module-id.js\";\nimport type { Locale } from \"./runtime.d.ts\";\n\n/**\n * Returns the code for the `runtime.js` module\n */\nexport function createServerFile(args: {\n\tcompiledBundles: CompiledBundleWithMessages[];\n\tcompilerOptions: {\n\t\texperimentalMiddlewareLocaleSplitting: NonNullable<\n\t\t\tCompilerOptions[\"experimentalMiddlewareLocaleSplitting\"]\n\t\t>;\n\t\tdisableAsyncLocalStorage: NonNullable<\n\t\t\tCompilerOptions[\"disableAsyncLocalStorage\"]\n\t\t>;\n\t};\n}): string {\n\tlet code = `\nimport * as runtime from \"./runtime.js\";\n\n${injectCode(\"./middleware.js\")}\n`;\n\n\tconst asyncLocalStorageMarker = \"// %async-local-storage\";\n\tconst markerIndex = code.indexOf(asyncLocalStorageMarker);\n\tif (markerIndex === -1) {\n\t\tthrow new Error(\n\t\t\t\"Expected a single %async-local-storage marker in server middleware.\"\n\t\t);\n\t}\n\n\tconst lineStart = code.lastIndexOf(\"\\n\", markerIndex) + 1;\n\tconst indent = code.slice(lineStart, markerIndex).replace(/\\t/g, \" \");\n\tconst innerIndent = `${indent} `;\n\tconst asyncLocalStorageBlock = args.compilerOptions.disableAsyncLocalStorage\n\t\t? [\n\t\t\t\t`${indent}requestAsyncLocalStorage = runtime.getServerAsyncLocalStorage();`,\n\t\t\t\t`${indent}if (!requestAsyncLocalStorage) {`,\n\t\t\t\t`${innerIndent}requestAsyncLocalStorage = createMockAsyncLocalStorage();`,\n\t\t\t\t`${innerIndent}runtime.overwriteServerAsyncLocalStorage(requestAsyncLocalStorage);`,\n\t\t\t\t`${indent}}`,\n\t\t\t]\n\t\t: [\n\t\t\t\t`${indent}requestAsyncLocalStorage = runtime.getServerAsyncLocalStorage();`,\n\t\t\t\t`${indent}if (!runtime.disableAsyncLocalStorage && !requestAsyncLocalStorage) {`,\n\t\t\t\t`${innerIndent}const { AsyncLocalStorage } = await import(\"async_hooks\");`,\n\t\t\t\t`${innerIndent}requestAsyncLocalStorage = runtime.getServerAsyncLocalStorage();`,\n\t\t\t\t`${innerIndent}if (!requestAsyncLocalStorage) {`,\n\t\t\t\t`${innerIndent} requestAsyncLocalStorage = new AsyncLocalStorage();`,\n\t\t\t\t`${innerIndent} runtime.overwriteServerAsyncLocalStorage(requestAsyncLocalStorage);`,\n\t\t\t\t`${innerIndent}}`,\n\t\t\t\t`${indent}}`,\n\t\t\t\t`${indent}if (!requestAsyncLocalStorage) {`,\n\t\t\t\t`${innerIndent}requestAsyncLocalStorage = createMockAsyncLocalStorage();`,\n\t\t\t\t`${innerIndent}runtime.overwriteServerAsyncLocalStorage(requestAsyncLocalStorage);`,\n\t\t\t\t`${indent}}`,\n\t\t\t];\n\n\tconst lineEnd = code.indexOf(\"\\n\", markerIndex);\n\tconst endOfMarkerLine = lineEnd === -1 ? code.length : lineEnd + 1;\n\n\tcode =\n\t\tcode.slice(0, lineStart) +\n\t\t`${asyncLocalStorageBlock.join(\"\\n\")}\\n` +\n\t\tcode.slice(endOfMarkerLine);\n\n\tif (args.compilerOptions.experimentalMiddlewareLocaleSplitting) {\n\t\t// Use a replacer function, not a replacement string. `String.replace()`\n\t\t// treats a string replacement as a pattern where `$&`, `` $` ``, `$'`,\n\t\t// `$$`, and `$<name>` have special meaning. A translated message value\n\t\t// that contains a literal `$` (a price, a currency symbol) can produce\n\t\t// one of these sequences inside the JSON payload, which `String.replace`\n\t\t// then expands - e.g. `` $` `` is replaced with \"everything before the\n\t\t// match\", splicing the file's own header into the string being built and\n\t\t// corrupting the generated server file. A function's return value is\n\t\t// used literally, with no pattern expansion.\n\t\tcode = code.replace(\n\t\t\t\"const compiledBundles = {};\",\n\t\t\t() =>\n\t\t\t\t`const compiledBundles = ${JSON.stringify(createCompiledMessagesObject(args.compiledBundles))};`\n\t\t);\n\t}\n\n\treturn code.replace(/\\t/g, \" \");\n}\n\nfunction createCompiledMessagesObject(\n\tcompiledBundles: CompiledBundleWithMessages[]\n): Record<string, Record<Locale, string>> {\n\tconst result = {} as Record<string, Record<Locale, string>>;\n\n\tfor (const compiledBundle of compiledBundles) {\n\t\tconst bundleId = compiledBundle.bundle.node.id;\n\t\tconst safeModuleId = toSafeModuleId(bundleId);\n\t\t// Key by the safe module id, not the raw bundle id: trackMessageCall()\n\t\t// records calls under safeModuleId, the client reads\n\t\t// globalThis.__paraglide.ssr[safeModuleId], and middleware.js looks up\n\t\t// compiledBundles[id] with that same safe id. Keying by the raw\n\t\t// bundleId here made every split-mode lookup miss.\n\t\tif (result[safeModuleId] === undefined) {\n\t\t\tresult[safeModuleId] = {};\n\t\t}\n\t\tfor (const [locale, compiledMessage] of Object.entries(\n\t\t\tcompiledBundle.messages\n\t\t)) {\n\t\t\tresult[safeModuleId][locale] = compiledMessage.code\n\t\t\t\t.replace(`export const ${safeModuleId} = `, \"\")\n\t\t\t\t.replace(/;$/, \"\");\n\t\t}\n\t}\n\treturn result;\n}\n\n/**\n * Load a file from the current directory.\n *\n * Prunes the imports on top of the file as the runtime is\n * self-contained.\n *\n * @param {string} path\n * @returns {string}\n */\nfunction injectCode(path: string): string {\n\tconst code = fs.readFileSync(new URL(path, import.meta.url), \"utf-8\");\n\t// Regex to match single-line and multi-line imports\n\tconst importRegex = /^\\s*import\\s+[\\s\\S]*?from\\s+['\"][^'\"]+['\"]\\s*;?/gm;\n\tconst sourceMapRegex = /\\/\\/# sourceMappingURL=.*$/gm;\n\tconst blockSourceMapRegex = /\\/\\*# sourceMappingURL=.*?\\*\\//g;\n\treturn code\n\t\t.replace(importRegex, \"\")\n\t\t.replace(sourceMapRegex, \"\")\n\t\t.replace(blockSourceMapRegex, \"\")\n\t\t.trim();\n}\n"]}
|
|
1
|
+
{"version":3,"file":"create-server-file.js","sourceRoot":"","sources":["../../../src/compiler/server/create-server-file.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,SAAS,CAAC;AAGzB,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAEtD,OAAO,EAAE,oBAAoB,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAC;AAEhF;;GAEG;AACH,MAAM,UAAU,gBAAgB,CAAC,IAUhC;IACA,IAAI,IAAI,GAAG;;;EAGV,UAAU,CAAC,iBAAiB,CAAC;CAC9B,CAAC;IAED,MAAM,uBAAuB,GAAG,yBAAyB,CAAC;IAC1D,MAAM,WAAW,GAAG,IAAI,CAAC,OAAO,CAAC,uBAAuB,CAAC,CAAC;IAC1D,IAAI,WAAW,KAAK,CAAC,CAAC,EAAE,CAAC;QACxB,MAAM,IAAI,KAAK,CACd,qEAAqE,CACrE,CAAC;IACH,CAAC;IAED,MAAM,SAAS,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,EAAE,WAAW,CAAC,GAAG,CAAC,CAAC;IAC1D,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;IACvE,MAAM,WAAW,GAAG,GAAG,MAAM,IAAI,CAAC;IAClC,MAAM,sBAAsB,GAAG,IAAI,CAAC,eAAe,CAAC,wBAAwB;QAC3E,CAAC,CAAC;YACA,GAAG,MAAM,kEAAkE;YAC3E,GAAG,MAAM,kCAAkC;YAC3C,GAAG,WAAW,2DAA2D;YACzE,GAAG,WAAW,qEAAqE;YACnF,GAAG,MAAM,GAAG;SACZ;QACF,CAAC,CAAC;YACA,GAAG,MAAM,kEAAkE;YAC3E,GAAG,MAAM,uEAAuE;YAChF,GAAG,WAAW,4DAA4D;YAC1E,GA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AG,wBAAwB,CAAC,eAAe,CAAC,iBAAiB,CAAC,CAAC;YAC1E,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;gBAAE,SAAS;YACjC,QAAQ,CAAC,YAAY,CAAC,KAAK,EAAE,CAAC;YAC9B,QAAQ,CAAC,YAAY,CAAC,CAAC,MAAM,CAAC,GAAG,KAAK,CAAC;YACvC,KAAK,MAAM,IAAI,IAAI,KAAK;gBAAE,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAC1C,CAAC;IACF,CAAC;IAED,OAAO,EAAE,SAAS,EAAE,oBAAoB,CAAC,IAAI,CAAC,EAAE,QAAQ,EAAE,CAAC;AAC5D,CAAC;AAED;;;;;;;;GAQG;AACH,SAAS,UAAU,CAAC,IAAY;IAC/B,MAAM,IAAI,GAAG,EAAE,CAAC,YAAY,CAAC,IAAI,GAAG,CAAC,IAAI,EAAE,OAAO,IAAI,CAAC,GAAG,CAAC,EAAE,OAAO,CAAC,CAAC;IACtE,oDAAoD;IACpD,MAAM,WAAW,GAAG,mDAAmD,CAAC;IACxE,MAAM,cAAc,GAAG,8BAA8B,CAAC;IACtD,MAAM,mBAAmB,GAAG,iCAAiC,CAAC;IAC9D,OAAO,IAAI;SACT,OAAO,CAAC,WAAW,EAAE,EAAE,CAAC;SACxB,OAAO,CAAC,cAAc,EAAE,EAAE,CAAC;SAC3B,OAAO,CAAC,mBAAmB,EAAE,EAAE,CAAC;SAChC,IAAI,EAAE,CAAC;AACV,CAAC","sourcesContent":["import fs from \"node:fs\";\nimport type { CompiledBundleWithMessages } from \"../compile-bundle.js\";\nimport type { CompilerOptions } from \"../compiler-options.js\";\nimport { toSafeModuleId } from \"../safe-module-id.js\";\nimport type { Locale } from \"./runtime.d.ts\";\nimport { registryFunctionCode, withRegistryDependencies } from \"../registry.js\";\n\n/**\n * Returns the code for the `runtime.js` module\n */\nexport function createServerFile(args: {\n\tcompiledBundles: CompiledBundleWithMessages[];\n\tcompilerOptions: {\n\t\texperimentalMiddlewareLocaleSplitting: NonNullable<\n\t\t\tCompilerOptions[\"experimentalMiddlewareLocaleSplitting\"]\n\t\t>;\n\t\tdisableAsyncLocalStorage: NonNullable<\n\t\t\tCompilerOptions[\"disableAsyncLocalStorage\"]\n\t\t>;\n\t};\n}): string {\n\tlet code = `\nimport * as runtime from \"./runtime.js\";\n\n${injectCode(\"./middleware.js\")}\n`;\n\n\tconst asyncLocalStorageMarker = \"// %async-local-storage\";\n\tconst markerIndex = code.indexOf(asyncLocalStorageMarker);\n\tif (markerIndex === -1) {\n\t\tthrow new Error(\n\t\t\t\"Expected a single %async-local-storage marker in server middleware.\"\n\t\t);\n\t}\n\n\tconst lineStart = code.lastIndexOf(\"\\n\", markerIndex) + 1;\n\tconst indent = code.slice(lineStart, markerIndex).replace(/\\t/g, \" \");\n\tconst innerIndent = `${indent} `;\n\tconst asyncLocalStorageBlock = args.compilerOptions.disableAsyncLocalStorage\n\t\t? [\n\t\t\t\t`${indent}requestAsyncLocalStorage = runtime.getServerAsyncLocalStorage();`,\n\t\t\t\t`${indent}if (!requestAsyncLocalStorage) {`,\n\t\t\t\t`${innerIndent}requestAsyncLocalStorage = createMockAsyncLocalStorage();`,\n\t\t\t\t`${innerIndent}runtime.overwriteServerAsyncLocalStorage(requestAsyncLocalStorage);`,\n\t\t\t\t`${indent}}`,\n\t\t\t]\n\t\t: [\n\t\t\t\t`${indent}requestAsyncLocalStorage = runtime.getServerAsyncLocalStorage();`,\n\t\t\t\t`${indent}if (!runtime.disableAsyncLocalStorage && !requestAsyncLocalStorage) {`,\n\t\t\t\t`${innerIndent}const { AsyncLocalStorage } = await import(\"async_hooks\");`,\n\t\t\t\t`${innerIndent}requestAsyncLocalStorage = runtime.getServerAsyncLocalStorage();`,\n\t\t\t\t`${innerIndent}if (!requestAsyncLocalStorage) {`,\n\t\t\t\t`${innerIndent} requestAsyncLocalStorage = new AsyncLocalStorage();`,\n\t\t\t\t`${innerIndent} runtime.overwriteServerAsyncLocalStorage(requestAsyncLocalStorage);`,\n\t\t\t\t`${innerIndent}}`,\n\t\t\t\t`${indent}}`,\n\t\t\t\t`${indent}if (!requestAsyncLocalStorage) {`,\n\t\t\t\t`${innerIndent}requestAsyncLocalStorage = createMockAsyncLocalStorage();`,\n\t\t\t\t`${innerIndent}runtime.overwriteServerAsyncLocalStorage(requestAsyncLocalStorage);`,\n\t\t\t\t`${indent}}`,\n\t\t\t];\n\n\tconst lineEnd = code.indexOf(\"\\n\", markerIndex);\n\tconst endOfMarkerLine = lineEnd === -1 ? code.length : lineEnd + 1;\n\n\tcode =\n\t\tcode.slice(0, lineStart) +\n\t\t`${asyncLocalStorageBlock.join(\"\\n\")}\\n` +\n\t\tcode.slice(endOfMarkerLine);\n\n\tif (args.compilerOptions.experimentalMiddlewareLocaleSplitting) {\n\t\t// Use a replacer function, not a replacement string. `String.replace()`\n\t\t// treats a string replacement as a pattern where `$&`, `` $` ``, `$'`,\n\t\t// `$$`, and `$<name>` have special meaning. A translated message value\n\t\t// that contains a literal `$` (a price, a currency symbol) can produce\n\t\t// one of these sequences inside the JSON payload, which `String.replace`\n\t\t// then expands - e.g. `` $` `` is replaced with \"everything before the\n\t\t// match\", splicing the file's own header into the string being built and\n\t\t// corrupting the generated server file. A function's return value is\n\t\t// used literally, with no pattern expansion.\n\t\tcode = code.replace(\n\t\t\t\"const compiledBundles = {};\",\n\t\t\t() =>\n\t\t\t\t`const compiledBundles = ${JSON.stringify(createCompiledMessagesObject(args.compiledBundles))};`\n\t\t);\n\t\tcode = code.replace(\n\t\t\t\"const compiledRegistry = { functions: {}, messages: {} };\",\n\t\t\t() =>\n\t\t\t\t`const compiledRegistry = ${JSON.stringify(createCompiledRegistryObject(args.compiledBundles))};`\n\t\t);\n\t}\n\n\treturn code.replace(/\\t/g, \" \");\n}\n\nfunction createCompiledMessagesObject(\n\tcompiledBundles: CompiledBundleWithMessages[]\n): Record<string, Record<Locale, string>> {\n\tconst result = {} as Record<string, Record<Locale, string>>;\n\n\tfor (const compiledBundle of compiledBundles) {\n\t\tconst bundleId = compiledBundle.bundle.node.id;\n\t\tconst safeModuleId = toSafeModuleId(bundleId);\n\t\t// Key by the safe module id, not the raw bundle id: trackMessageCall()\n\t\t// records calls under safeModuleId, the client reads\n\t\t// globalThis.__paraglide.ssr[safeModuleId], and middleware.js looks up\n\t\t// compiledBundles[id] with that same safe id. Keying by the raw\n\t\t// bundleId here made every split-mode lookup miss.\n\t\tif (result[safeModuleId] === undefined) {\n\t\t\tresult[safeModuleId] = {};\n\t\t}\n\t\tfor (const [locale, compiledMessage] of Object.entries(\n\t\t\tcompiledBundle.messages\n\t\t)) {\n\t\t\tresult[safeModuleId][locale] = compiledMessage.code\n\t\t\t\t.replace(`export const ${safeModuleId} = `, \"\")\n\t\t\t\t.replace(/;$/, \"\");\n\t\t}\n\t}\n\treturn result;\n}\n\n/**\n * The registry functions each compiled message calls, and their code, for\n * the messages the middleware injects into the page. Those run without\n * registry.js.\n */\nfunction createCompiledRegistryObject(\n\tcompiledBundles: CompiledBundleWithMessages[]\n): {\n\tfunctions: Record<string, string>;\n\tmessages: Record<string, Record<string, string[]>>;\n} {\n\tconst messages: Record<string, Record<string, string[]>> = {};\n\tconst used = new Set<string>();\n\n\tfor (const compiledBundle of compiledBundles) {\n\t\tconst safeModuleId = toSafeModuleId(compiledBundle.bundle.node.id);\n\t\tfor (const [locale, compiledMessage] of Object.entries(\n\t\t\tcompiledBundle.messages\n\t\t)) {\n\t\t\tconst names = withRegistryDependencies(compiledMessage.registryFunctions);\n\t\t\tif (names.length === 0) continue;\n\t\t\tmessages[safeModuleId] ??= {};\n\t\t\tmessages[safeModuleId][locale] = names;\n\t\t\tfor (const name of names) used.add(name);\n\t\t}\n\t}\n\n\treturn { functions: registryFunctionCode(used), messages };\n}\n\n/**\n * Load a file from the current directory.\n *\n * Prunes the imports on top of the file as the runtime is\n * self-contained.\n *\n * @param {string} path\n * @returns {string}\n */\nfunction injectCode(path: string): string {\n\tconst code = fs.readFileSync(new URL(path, import.meta.url), \"utf-8\");\n\t// Regex to match single-line and multi-line imports\n\tconst importRegex = /^\\s*import\\s+[\\s\\S]*?from\\s+['\"][^'\"]+['\"]\\s*;?/gm;\n\tconst sourceMapRegex = /\\/\\/# sourceMappingURL=.*$/gm;\n\tconst blockSourceMapRegex = /\\/\\*# sourceMappingURL=.*?\\*\\//g;\n\treturn code\n\t\t.replace(importRegex, \"\")\n\t\t.replace(sourceMapRegex, \"\")\n\t\t.replace(blockSourceMapRegex, \"\")\n\t\t.trim();\n}\n"]}
|
|
@@ -71,7 +71,10 @@ test("keys compiledBundles by the safe module id, not the raw bundle id (experim
|
|
|
71
71
|
{
|
|
72
72
|
bundle: { node: { id: bundleId } },
|
|
73
73
|
messages: {
|
|
74
|
-
en: {
|
|
74
|
+
en: {
|
|
75
|
+
code: `export const ${safeModuleId} = () => "hello";`,
|
|
76
|
+
registryFunctions: [],
|
|
77
|
+
},
|
|
75
78
|
},
|
|
76
79
|
},
|
|
77
80
|
];
|
|
@@ -99,7 +102,10 @@ test("a literal '$' in a compiled message does not corrupt the generated file (e
|
|
|
99
102
|
{
|
|
100
103
|
bundle: { node: { id: "price_symbol" } },
|
|
101
104
|
messages: {
|
|
102
|
-
en: {
|
|
105
|
+
en: {
|
|
106
|
+
code: "export const price_symbol = () => `$`;",
|
|
107
|
+
registryFunctions: [],
|
|
108
|
+
},
|
|
103
109
|
},
|
|
104
110
|
},
|
|
105
111
|
];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-server-file.test.js","sourceRoot":"","sources":["../../../src/compiler/server/create-server-file.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,EAAE,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC1D,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,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AAI,CAAC,SAAS,EAAE,YAAY,CAAC,EAC7B;;;;;;;;;;;;;;;EAeA,CACA,CAAC;IACF,MAAM,SAAS,CAAC,IAAI,CAAC,SAAS,EAAE,YAAY,CAAC,EAAE,UAAU,CAAC,CAAC;IAE3D,MAAM,MAAM,CACX,MAAM,CAAC,aAAa,CAAC,IAAI,CAAC,SAAS,EAAE,YAAY,CAAC,CAAC,CAAC,IAAI,CAAC,CACzD,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC;AAC1B,CAAC,CAAC,CAAC","sourcesContent":["import { mkdtemp, rm, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { afterEach, expect, test } from \"vitest\";\nimport type { CompiledBundleWithMessages } from \"../compile-bundle.js\";\nimport { toSafeModuleId } from \"../safe-module-id.js\";\nimport { createServerFile } from \"./create-server-file.js\";\n\nconst temporaryDirectories: string[] = [];\n\nafterEach(async () => {\n\tawait Promise.all(\n\t\ttemporaryDirectories\n\t\t\t.splice(0)\n\t\t\t.map((directory) => rm(directory, { recursive: true, force: true }))\n\t);\n});\n\ntest(\"uses the initialized AsyncLocalStorage when an import interceptor snapshots the initial export\", async () => {\n\tconst directory = await mkdtemp(join(tmpdir(), \"paraglide-server-\"));\n\ttemporaryDirectories.push(directory);\n\n\tconst serverCode = createServerFile({\n\t\tcompiledBundles: [],\n\t\tcompilerOptions: {\n\t\t\tdisableAsyncLocalStorage: false,\n\t\t\texperimentalMiddlewareLocaleSplitting: false,\n\t\t},\n\t}).replace('\"./runtime.js\"', '\"./runtime-wrapper.mjs\"');\n\n\tawait writeFile(join(directory, \"server.mjs\"), serverCode);\n\tawait writeFile(\n\t\tjoin(directory, \"runtime-real.mjs\"),\n\t\t`export let serverAsyncLocalStorage;\nexport const disableAsyncLocalStorage = false;\nexport function overwriteServerAsyncLocalStorage(value) {\n serverAsyncLocalStorage = value;\n}\nexport function getServerAsyncLocalStorage() {\n return serverAsyncLocalStorage;\n}\nexport const baseLocale = \"en\";\nexport function isExcludedByRouteStrategy() {\n return true;\n}`\n\t);\n\tawait writeFile(\n\t\tjoin(directory, \"runtime-wrapper.mjs\"),\n\t\t`import * as runtime from \"./runtime-real.mjs\";\nexport const serverAsyncLocalStorage = runtime.serverAsyncLocalStorage;\nexport const disableAsyncLocalStorage = runtime.disableAsyncLocalStorage;\nexport const overwriteServerAsyncLocalStorage = runtime.overwriteServerAsyncLocalStorage;\nexport const getServerAsyncLocalStorage = runtime.getServerAsyncLocalStorage;\nexport const baseLocale = runtime.baseLocale;\nexport const isExcludedByRouteStrategy = runtime.isExcludedByRouteStrategy;`\n\t);\n\n\tconst server = await import(\n\t\tpathToFileURL(join(directory, \"server.mjs\")).href\n\t);\n\tconst response = await server.paraglideMiddleware(\n\t\tnew Request(\"https://example.com/api/ready\"),\n\t\t() => new Response(\"ready\")\n\t);\n\n\texpect(response.status).toBe(200);\n\texpect(await response.text()).toBe(\"ready\");\n});\n\ntest(\"import statements in JSDoc examples survive in the generated server file\", () => {\n\tconst serverCode = createServerFile({\n\t\tcompiledBundles: [],\n\t\tcompilerOptions: {\n\t\t\tdisableAsyncLocalStorage: false,\n\t\t\texperimentalMiddlewareLocaleSplitting: false,\n\t\t},\n\t});\n\n\texpect(serverCode).toContain(\n\t\t` * import { paraglideMiddleware } from './paraglide/server.js'\\n * import handler from '@tanstack/react-start/server-entry'\\n *\\n * export default {`\n\t);\n\t// only the `import * as runtime` line that createServerFile itself prepends\n\texpect(serverCode.match(/^\\s*import\\s/gm)).toHaveLength(1);\n});\n\ntest(\"keys compiledBundles by the safe module id, not the raw bundle id (experimentalMiddlewareLocaleSplitting)\", () => {\n\t// A bundle id that changes under toSafeModuleId (case-folded + a numeric\n\t// suffix appended for the uppercase letters). trackMessageCall(), the\n\t// client's SSR message guard, and middleware.js all look up\n\t// compiledBundles by this safe id - only createCompiledMessagesObject\n\t// (inside createServerFile) used the raw id instead.\n\tconst bundleId = \"GREETING\";\n\tconst safeModuleId = toSafeModuleId(bundleId);\n\texpect(safeModuleId).not.toBe(bundleId);\n\n\tconst compiledBundles = [\n\t\t{\n\t\t\tbundle: { node: { id: bundleId } },\n\t\t\tmessages: {\n\t\t\t\ten: { code: `export const ${safeModuleId} = () => \"hello\";` },\n\t\t\t},\n\t\t},\n\t] as unknown as CompiledBundleWithMessages[];\n\n\tconst serverCode = createServerFile({\n\t\tcompiledBundles,\n\t\tcompilerOptions: {\n\t\t\tdisableAsyncLocalStorage: false,\n\t\t\texperimentalMiddlewareLocaleSplitting: true,\n\t\t},\n\t});\n\n\texpect(serverCode).toContain(`\"${safeModuleId}\":{\"en\":`);\n\texpect(serverCode).not.toContain(`\"${bundleId}\":{\"en\":`);\n});\n\ntest(\"a literal '$' in a compiled message does not corrupt the generated file (experimentalMiddlewareLocaleSplitting)\", async () => {\n\tconst directory = await mkdtemp(join(tmpdir(), \"paraglide-server-dollar-\"));\n\ttemporaryDirectories.push(directory);\n\n\t// The compiled message source for locale \"en\" evaluates to the literal\n\t// text \"$\", wrapped in a template literal by the compiler (i.e. it\n\t// contains a backtick immediately followed by a `$` immediately followed\n\t// by another backtick). Passed as a *string* to `code.replace()`, `` $` ``\n\t// is a special replacement pattern (\"insert everything before the\n\t// match\"), which splices the file's own header into the string being\n\t// built and corrupts the generated server file.\n\tconst compiledBundles = [\n\t\t{\n\t\t\tbundle: { node: { id: \"price_symbol\" } },\n\t\t\tmessages: {\n\t\t\t\ten: { code: \"export const price_symbol = () => `$`;\" },\n\t\t\t},\n\t\t},\n\t] as unknown as CompiledBundleWithMessages[];\n\n\tconst serverCode = createServerFile({\n\t\tcompiledBundles,\n\t\tcompilerOptions: {\n\t\t\tdisableAsyncLocalStorage: false,\n\t\t\texperimentalMiddlewareLocaleSplitting: true,\n\t\t},\n\t});\n\n\t// The message value must survive JSON serialization untouched.\n\texpect(serverCode).toContain('\"price_symbol\":{\"en\":\"() => `$`\"}');\n\n\t// The generated file must still be syntactically valid and importable\n\t// (the bug produces an unterminated string / invalid JS).\n\tawait writeFile(\n\t\tjoin(directory, \"runtime.js\"),\n\t\t`export const serverAsyncLocalStorage = undefined;\nexport const disableAsyncLocalStorage = false;\nexport const experimentalMiddlewareLocaleSplitting = true;\nexport const baseLocale = \"en\";\nexport function isExcludedByRouteStrategy() {\n return true;\n}\nexport function getStrategyForUrl() {\n return [];\n}\nexport async function shouldRedirect() {\n return { locale: \"en\", shouldRedirect: false };\n}\nexport function deLocalizeUrl(url) {\n return url;\n}`\n\t);\n\tawait writeFile(join(directory, \"server.mjs\"), serverCode);\n\n\tawait expect(\n\t\timport(pathToFileURL(join(directory, \"server.mjs\")).href)\n\t).resolves.toBeDefined();\n});\n"]}
|
|
1
|
+
{"version":3,"file":"create-server-file.test.js","sourceRoot":"","sources":["../../../src/compiler/server/create-server-file.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,EAAE,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC1D,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AAEjD,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAE3D,MAAM,oBAAoB,GAAa,EAAE,CAAC;AAE1C,SAAS,CAAC,KAAK,IAAI,EAAE;IACpB,MAAM,OAAO,CAAC,GAAG,CAChB,oBAAoB;SAClB,MAAM,CAAC,CAAC,CAAC;SACT,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,EAAE,CAAC,SAAS,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,CACrE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} from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { afterEach, expect, test } from \"vitest\";\nimport type { CompiledBundleWithMessages } from \"../compile-bundle.js\";\nimport { toSafeModuleId } from \"../safe-module-id.js\";\nimport { createServerFile } from \"./create-server-file.js\";\n\nconst temporaryDirectories: string[] = [];\n\nafterEach(async () => {\n\tawait Promise.all(\n\t\ttemporaryDirectories\n\t\t\t.splice(0)\n\t\t\t.map((directory) => rm(directory, { recursive: true, force: true }))\n\t);\n});\n\ntest(\"uses the initialized AsyncLocalStorage when an import interceptor snapshots the initial export\", async () => {\n\tconst directory = await mkdtemp(join(tmpdir(), \"paraglide-server-\"));\n\ttemporaryDirectories.push(directory);\n\n\tconst serverCode = createServerFile({\n\t\tcompiledBundles: [],\n\t\tcompilerOptions: {\n\t\t\tdisableAsyncLocalStorage: false,\n\t\t\texperimentalMiddlewareLocaleSplitting: false,\n\t\t},\n\t}).replace('\"./runtime.js\"', '\"./runtime-wrapper.mjs\"');\n\n\tawait writeFile(join(directory, \"server.mjs\"), serverCode);\n\tawait writeFile(\n\t\tjoin(directory, \"runtime-real.mjs\"),\n\t\t`export let serverAsyncLocalStorage;\nexport const disableAsyncLocalStorage = false;\nexport function overwriteServerAsyncLocalStorage(value) {\n serverAsyncLocalStorage = value;\n}\nexport function getServerAsyncLocalStorage() {\n return serverAsyncLocalStorage;\n}\nexport const baseLocale = \"en\";\nexport function isExcludedByRouteStrategy() {\n return true;\n}`\n\t);\n\tawait writeFile(\n\t\tjoin(directory, \"runtime-wrapper.mjs\"),\n\t\t`import * as runtime from \"./runtime-real.mjs\";\nexport const serverAsyncLocalStorage = runtime.serverAsyncLocalStorage;\nexport const disableAsyncLocalStorage = runtime.disableAsyncLocalStorage;\nexport const overwriteServerAsyncLocalStorage = runtime.overwriteServerAsyncLocalStorage;\nexport const getServerAsyncLocalStorage = runtime.getServerAsyncLocalStorage;\nexport const baseLocale = runtime.baseLocale;\nexport const isExcludedByRouteStrategy = runtime.isExcludedByRouteStrategy;`\n\t);\n\n\tconst server = await import(\n\t\tpathToFileURL(join(directory, \"server.mjs\")).href\n\t);\n\tconst response = await server.paraglideMiddleware(\n\t\tnew Request(\"https://example.com/api/ready\"),\n\t\t() => new Response(\"ready\")\n\t);\n\n\texpect(response.status).toBe(200);\n\texpect(await response.text()).toBe(\"ready\");\n});\n\ntest(\"import statements in JSDoc examples survive in the generated server file\", () => {\n\tconst serverCode = createServerFile({\n\t\tcompiledBundles: [],\n\t\tcompilerOptions: {\n\t\t\tdisableAsyncLocalStorage: false,\n\t\t\texperimentalMiddlewareLocaleSplitting: false,\n\t\t},\n\t});\n\n\texpect(serverCode).toContain(\n\t\t` * import { paraglideMiddleware } from './paraglide/server.js'\\n * import handler from '@tanstack/react-start/server-entry'\\n *\\n * export default {`\n\t);\n\t// only the `import * as runtime` line that createServerFile itself prepends\n\texpect(serverCode.match(/^\\s*import\\s/gm)).toHaveLength(1);\n});\n\ntest(\"keys compiledBundles by the safe module id, not the raw bundle id (experimentalMiddlewareLocaleSplitting)\", () => {\n\t// A bundle id that changes under toSafeModuleId (case-folded + a numeric\n\t// suffix appended for the uppercase letters). trackMessageCall(), the\n\t// client's SSR message guard, and middleware.js all look up\n\t// compiledBundles by this safe id - only createCompiledMessagesObject\n\t// (inside createServerFile) used the raw id instead.\n\tconst bundleId = \"GREETING\";\n\tconst safeModuleId = toSafeModuleId(bundleId);\n\texpect(safeModuleId).not.toBe(bundleId);\n\n\tconst compiledBundles = [\n\t\t{\n\t\t\tbundle: { node: { id: bundleId } },\n\t\t\tmessages: {\n\t\t\t\ten: {\n\t\t\t\t\tcode: `export const ${safeModuleId} = () => \"hello\";`,\n\t\t\t\t\tregistryFunctions: [],\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t] as unknown as CompiledBundleWithMessages[];\n\n\tconst serverCode = createServerFile({\n\t\tcompiledBundles,\n\t\tcompilerOptions: {\n\t\t\tdisableAsyncLocalStorage: false,\n\t\t\texperimentalMiddlewareLocaleSplitting: true,\n\t\t},\n\t});\n\n\texpect(serverCode).toContain(`\"${safeModuleId}\":{\"en\":`);\n\texpect(serverCode).not.toContain(`\"${bundleId}\":{\"en\":`);\n});\n\ntest(\"a literal '$' in a compiled message does not corrupt the generated file (experimentalMiddlewareLocaleSplitting)\", async () => {\n\tconst directory = await mkdtemp(join(tmpdir(), \"paraglide-server-dollar-\"));\n\ttemporaryDirectories.push(directory);\n\n\t// The compiled message source for locale \"en\" evaluates to the literal\n\t// text \"$\", wrapped in a template literal by the compiler (i.e. it\n\t// contains a backtick immediately followed by a `$` immediately followed\n\t// by another backtick). Passed as a *string* to `code.replace()`, `` $` ``\n\t// is a special replacement pattern (\"insert everything before the\n\t// match\"), which splices the file's own header into the string being\n\t// built and corrupts the generated server file.\n\tconst compiledBundles = [\n\t\t{\n\t\t\tbundle: { node: { id: \"price_symbol\" } },\n\t\t\tmessages: {\n\t\t\t\ten: {\n\t\t\t\t\tcode: \"export const price_symbol = () => `$`;\",\n\t\t\t\t\tregistryFunctions: [],\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t] as unknown as CompiledBundleWithMessages[];\n\n\tconst serverCode = createServerFile({\n\t\tcompiledBundles,\n\t\tcompilerOptions: {\n\t\t\tdisableAsyncLocalStorage: false,\n\t\t\texperimentalMiddlewareLocaleSplitting: true,\n\t\t},\n\t});\n\n\t// The message value must survive JSON serialization untouched.\n\texpect(serverCode).toContain('\"price_symbol\":{\"en\":\"() => `$`\"}');\n\n\t// The generated file must still be syntactically valid and importable\n\t// (the bug produces an unterminated string / invalid JS).\n\tawait writeFile(\n\t\tjoin(directory, \"runtime.js\"),\n\t\t`export const serverAsyncLocalStorage = undefined;\nexport const disableAsyncLocalStorage = false;\nexport const experimentalMiddlewareLocaleSplitting = true;\nexport const baseLocale = \"en\";\nexport function isExcludedByRouteStrategy() {\n return true;\n}\nexport function getStrategyForUrl() {\n return [];\n}\nexport async function shouldRedirect() {\n return { locale: \"en\", shouldRedirect: false };\n}\nexport function deLocalizeUrl(url) {\n return url;\n}`\n\t);\n\tawait writeFile(join(directory, \"server.mjs\"), serverCode);\n\n\tawait expect(\n\t\timport(pathToFileURL(join(directory, \"server.mjs\")).href)\n\t).resolves.toBeDefined();\n});\n"]}
|
|
@@ -151,23 +151,35 @@ export async function paraglideMiddleware(request, resolve, options) {
|
|
|
151
151
|
response.headers.get("Content-Type")?.includes("html")) {
|
|
152
152
|
const body = await response.text();
|
|
153
153
|
const messages = [];
|
|
154
|
+
/** @type {Set<string>} */
|
|
155
|
+
const registryFunctionNames = new Set();
|
|
154
156
|
// using .values() to avoid polyfilling in older projects. else the following error is thrown
|
|
155
157
|
// Type 'Set<string>' can only be iterated through when using the '--downlevelIteration' flag or with a '--target' of 'es2015' or higher.
|
|
156
158
|
for (const messageCall of Array.from(messageCalls)) {
|
|
157
159
|
const [id, locale] =
|
|
158
160
|
/** @type {[string, import("./runtime.js").Locale]} */ (messageCall.split(":"));
|
|
159
161
|
messages.push(`${id}: ${compiledBundles[id]?.[locale]}`);
|
|
162
|
+
for (const name of compiledRegistry.messages[id]?.[locale] ?? []) {
|
|
163
|
+
registryFunctionNames.add(name);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
// The injected messages run without registry.js. Declare the registry
|
|
167
|
+
// functions they call (including the ones those call) in a closure.
|
|
168
|
+
let ssr = `{ ${messages.join(",")} }`;
|
|
169
|
+
if (registryFunctionNames.size > 0) {
|
|
170
|
+
const names = Array.from(registryFunctionNames);
|
|
171
|
+
ssr = `(() => { ${names
|
|
172
|
+
.map((name) => compiledRegistry.functions[name])
|
|
173
|
+
.join("\n")}\nconst registry = { ${names.join(", ")} };\nreturn ${ssr} })()`;
|
|
160
174
|
}
|
|
161
175
|
// Prevent translated content from terminating the inline script tag.
|
|
162
|
-
const
|
|
163
|
-
.join(",")
|
|
164
|
-
.replace(/<\/(script)/gi, "<\\/$1");
|
|
176
|
+
const escapedSsr = ssr.replace(/<\/(script)/gi, "<\\/$1");
|
|
165
177
|
// Reuse the request's CSP nonce (if any) so the injected script is allowed under a strict CSP
|
|
166
178
|
const nonce = response.headers
|
|
167
179
|
.get("Content-Security-Policy")
|
|
168
180
|
?.match(/'nonce-([\w+/=-]+)'/)?.[1];
|
|
169
181
|
const nonceAttr = nonce ? `nonce="${nonce}"` : "";
|
|
170
|
-
const script = `<script ${nonceAttr}>globalThis.__paraglide = globalThis.__paraglide ?? {}; globalThis.__paraglide.ssr =
|
|
182
|
+
const script = `<script ${nonceAttr}>globalThis.__paraglide = globalThis.__paraglide ?? {}; globalThis.__paraglide.ssr = ${escapedSsr}</script>`;
|
|
171
183
|
// Insert the script before the closing head tag
|
|
172
184
|
const newBody = body.replace("</head>", `${script}</head>`);
|
|
173
185
|
// Create a new response with the modified body
|
|
@@ -279,4 +291,17 @@ void createMockAsyncLocalStorage;
|
|
|
279
291
|
* @type {Record<string, Record<import("./runtime.js").Locale, string>>}
|
|
280
292
|
*/
|
|
281
293
|
const compiledBundles = {};
|
|
294
|
+
/**
|
|
295
|
+
* The registry functions the compiled messages call, for the injected
|
|
296
|
+
* messages that run without registry.js.
|
|
297
|
+
*
|
|
298
|
+
* `messages[id][locale]` lists the registry functions a message calls,
|
|
299
|
+
* including the ones those call. `functions[name]` is the code of a registry
|
|
300
|
+
* function.
|
|
301
|
+
*
|
|
302
|
+
* Only populated if `enableMiddlewareOptimizations` is set to `true`.
|
|
303
|
+
*
|
|
304
|
+
* @type {{ functions: Record<string, string>, messages: Record<string, Record<string, string[]>> }}
|
|
305
|
+
*/
|
|
306
|
+
const compiledRegistry = { functions: {}, messages: {} };
|
|
282
307
|
//# sourceMappingURL=middleware.js.map
|