fuma-translate 0.0.3 → 1.0.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/dist/cli.d.mts ADDED
@@ -0,0 +1,24 @@
1
+ //#region src/cli.d.ts
2
+ interface CompileAndWriteOptions {
3
+ input: string[];
4
+ out: string;
5
+ strict: boolean;
6
+ }
7
+ interface WatchOptions extends CompileAndWriteOptions {
8
+ onCompiled?: (result: {
9
+ ok: true;
10
+ keyCount: number;
11
+ } | {
12
+ ok: false;
13
+ error: string;
14
+ }) => void;
15
+ }
16
+ declare function getWatchRoots(globs: string[]): string[];
17
+ declare function compileAndWrite(options: CompileAndWriteOptions): Promise<{
18
+ keyCount: number;
19
+ }>;
20
+ declare function watchCompile(options: WatchOptions, signal?: AbortSignal): Promise<void>;
21
+ declare function main(argv?: string[]): Promise<number>;
22
+ //#endregion
23
+ export { CompileAndWriteOptions, WatchOptions, compileAndWrite, getWatchRoots, main, watchCompile };
24
+ //# sourceMappingURL=cli.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.d.mts","names":[],"sources":["../src/cli.ts"],"mappings":";UA0BiB,sBAAA;EACf,KAAA;EACA,GAAA;EACA,MAAA;AAAA;AAAA,UAGe,YAAA,SAAqB,sBAAsB;EAC1D,UAAA,IAAc,MAAA;IAAU,EAAA;IAAU,QAAA;EAAA;IAAuB,EAAA;IAAW,KAAA;EAAA;AAAA;AAAA,iBAGtD,aAAA,CAAc,KAAe;AAAA,iBA0BvB,eAAA,CACpB,OAAA,EAAS,sBAAA,GACR,OAAO;EAAG,QAAA;AAAA;AAAA,iBAWS,YAAA,CAAa,OAAA,EAAS,YAAA,EAAc,MAAA,GAAS,WAAA,GAAc,OAAA;AAAA,iBA+D3D,IAAA,CAAK,IAAA,cAAyC,OAAO"}
package/dist/cli.mjs ADDED
@@ -0,0 +1,168 @@
1
+ #!/usr/bin/env node
2
+ import { n as compile, r as typegen, t as StaticAnalysisError } from "./compiler-DxWiaGcG.mjs";
3
+ import { mkdir, writeFile } from "node:fs/promises";
4
+ import { dirname, join, resolve } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { parseArgs } from "node:util";
7
+ import chokidar from "chokidar";
8
+ //#region src/cli.ts
9
+ function writeManifest(output) {
10
+ return `${JSON.stringify({ translationKeys: [...output.translationKeys].sort() }, null, 2)}\n`;
11
+ }
12
+ const HELP = `Usage: fuma-translate [options] <glob>...
13
+
14
+ Compile translation keys from source files.
15
+
16
+ Arguments:
17
+ <glob>... Glob patterns to scan (e.g. src/**/*.tsx)
18
+
19
+ Options:
20
+ -o, --out <dir> Output directory (default: .translations)
21
+ -w, --watch Recompile when matching files change
22
+ --no-strict Extract all static t() calls, not only hook-bound ones
23
+ -h, --help Show this help message
24
+ `;
25
+ function getWatchRoots(globs) {
26
+ const roots = /* @__PURE__ */ new Set();
27
+ for (const pattern of globs) {
28
+ const index = pattern.search(/[*?[{]/);
29
+ const root = index === -1 ? dirname(pattern) : pattern.slice(0, index).replace(/[/\\]+$/, "") || ".";
30
+ roots.add(resolve(root));
31
+ }
32
+ return [...roots];
33
+ }
34
+ function debounce(fn, ms) {
35
+ let timer;
36
+ return () => {
37
+ if (timer) clearTimeout(timer);
38
+ timer = setTimeout(fn, ms);
39
+ };
40
+ }
41
+ async function compileAndWrite(options) {
42
+ const output = await compile({
43
+ input: options.input,
44
+ strict: options.strict
45
+ });
46
+ const outDir = resolve(options.out);
47
+ await mkdir(outDir, { recursive: true });
48
+ await writeFile(join(outDir, "manifest.json"), writeManifest(output), "utf8");
49
+ await writeFile(join(outDir, "index.ts"), typegen(output), "utf8");
50
+ return { keyCount: output.translationKeys.length };
51
+ }
52
+ async function watchCompile(options, signal) {
53
+ const outDir = resolve(options.out);
54
+ const roots = getWatchRoots(options.input);
55
+ let compiling = false;
56
+ let queued = false;
57
+ const run = async () => {
58
+ if (compiling) {
59
+ queued = true;
60
+ return;
61
+ }
62
+ compiling = true;
63
+ try {
64
+ const { keyCount } = await compileAndWrite(options);
65
+ options.onCompiled?.({
66
+ ok: true,
67
+ keyCount
68
+ });
69
+ } catch (error) {
70
+ const message = error instanceof StaticAnalysisError ? error.message : String(error);
71
+ process.stderr.write(`${message}\n`);
72
+ options.onCompiled?.({
73
+ ok: false,
74
+ error: message
75
+ });
76
+ } finally {
77
+ compiling = false;
78
+ if (queued) {
79
+ queued = false;
80
+ run();
81
+ }
82
+ }
83
+ };
84
+ const schedule = debounce(() => {
85
+ run();
86
+ }, 100);
87
+ const watcher = chokidar.watch(roots, {
88
+ ignoreInitial: true,
89
+ ignored: (path) => path.startsWith(outDir),
90
+ awaitWriteFinish: {
91
+ stabilityThreshold: 100,
92
+ pollInterval: 50
93
+ }
94
+ });
95
+ watcher.on("all", schedule);
96
+ if (signal) {
97
+ if (signal.aborted) {
98
+ await watcher.close();
99
+ return;
100
+ }
101
+ signal.addEventListener("abort", () => {
102
+ watcher.close();
103
+ }, { once: true });
104
+ }
105
+ process.stdout.write(`Watching ${options.input.join(", ")}...\n`);
106
+ await run();
107
+ }
108
+ async function main(argv = process.argv.slice(2)) {
109
+ const { values, positionals } = parseArgs({
110
+ args: argv,
111
+ options: {
112
+ out: {
113
+ type: "string",
114
+ short: "o",
115
+ default: ".translations"
116
+ },
117
+ watch: {
118
+ type: "boolean",
119
+ short: "w",
120
+ default: false
121
+ },
122
+ strict: {
123
+ type: "boolean",
124
+ default: true
125
+ },
126
+ help: {
127
+ type: "boolean",
128
+ short: "h",
129
+ default: false
130
+ }
131
+ },
132
+ allowPositionals: true
133
+ });
134
+ if (values.help) {
135
+ process.stdout.write(HELP);
136
+ return 0;
137
+ }
138
+ if (positionals.length === 0) {
139
+ process.stderr.write(HELP);
140
+ return 1;
141
+ }
142
+ const options = {
143
+ input: positionals,
144
+ out: values.out,
145
+ strict: values.strict
146
+ };
147
+ if (values.watch) {
148
+ await watchCompile(options);
149
+ return 0;
150
+ }
151
+ try {
152
+ await compileAndWrite(options);
153
+ return 0;
154
+ } catch (error) {
155
+ if (error instanceof StaticAnalysisError) {
156
+ process.stderr.write(`${error.message}\n`);
157
+ return 1;
158
+ }
159
+ throw error;
160
+ }
161
+ }
162
+ if ((process.argv[1] ? resolve(process.argv[1]) : "") === fileURLToPath(import.meta.url)) main().then((code) => {
163
+ process.exitCode = code;
164
+ });
165
+ //#endregion
166
+ export { compileAndWrite, getWatchRoots, main, watchCompile };
167
+
168
+ //# sourceMappingURL=cli.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.mjs","names":[],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { parseArgs } from \"node:util\";\nimport chokidar from \"chokidar\";\nimport { compile, StaticAnalysisError, typegen, type CompileOutput } from \"./compiler.js\";\n\nfunction writeManifest(output: CompileOutput): string {\n return `${JSON.stringify({ translationKeys: [...output.translationKeys].sort() }, null, 2)}\\n`;\n}\n\nconst HELP = `Usage: fuma-translate [options] <glob>...\n\nCompile translation keys from source files.\n\nArguments:\n <glob>... Glob patterns to scan (e.g. src/**/*.tsx)\n\nOptions:\n -o, --out <dir> Output directory (default: .translations)\n -w, --watch Recompile when matching files change\n --no-strict Extract all static t() calls, not only hook-bound ones\n -h, --help Show this help message\n`;\n\nexport interface CompileAndWriteOptions {\n input: string[];\n out: string;\n strict: boolean;\n}\n\nexport interface WatchOptions extends CompileAndWriteOptions {\n onCompiled?: (result: { ok: true; keyCount: number } | { ok: false; error: string }) => void;\n}\n\nexport function getWatchRoots(globs: string[]): string[] {\n const roots = new Set<string>();\n\n for (const pattern of globs) {\n const index = pattern.search(/[*?[{]/);\n const root =\n index === -1 ? dirname(pattern) : pattern.slice(0, index).replace(/[/\\\\]+$/, \"\") || \".\";\n\n roots.add(resolve(root));\n }\n\n return [...roots];\n}\n\nfunction debounce(fn: () => void, ms: number): () => void {\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n return () => {\n if (timer) {\n clearTimeout(timer);\n }\n\n timer = setTimeout(fn, ms);\n };\n}\n\nexport async function compileAndWrite(\n options: CompileAndWriteOptions,\n): Promise<{ keyCount: number }> {\n const output = await compile({ input: options.input, strict: options.strict });\n const outDir = resolve(options.out);\n\n await mkdir(outDir, { recursive: true });\n await writeFile(join(outDir, \"manifest.json\"), writeManifest(output), \"utf8\");\n await writeFile(join(outDir, \"index.ts\"), typegen(output), \"utf8\");\n\n return { keyCount: output.translationKeys.length };\n}\n\nexport async function watchCompile(options: WatchOptions, signal?: AbortSignal): Promise<void> {\n const outDir = resolve(options.out);\n const roots = getWatchRoots(options.input);\n let compiling = false;\n let queued = false;\n\n const run = async () => {\n if (compiling) {\n queued = true;\n return;\n }\n\n compiling = true;\n\n try {\n const { keyCount } = await compileAndWrite(options);\n options.onCompiled?.({ ok: true, keyCount });\n } catch (error) {\n const message = error instanceof StaticAnalysisError ? error.message : String(error);\n\n process.stderr.write(`${message}\\n`);\n options.onCompiled?.({ ok: false, error: message });\n } finally {\n compiling = false;\n\n if (queued) {\n queued = false;\n void run();\n }\n }\n };\n\n const schedule = debounce(() => {\n void run();\n }, 100);\n\n const watcher = chokidar.watch(roots, {\n ignoreInitial: true,\n ignored: (path) => path.startsWith(outDir),\n awaitWriteFinish: { stabilityThreshold: 100, pollInterval: 50 },\n });\n\n watcher.on(\"all\", schedule);\n\n if (signal) {\n if (signal.aborted) {\n await watcher.close();\n return;\n }\n\n signal.addEventListener(\n \"abort\",\n () => {\n void watcher.close();\n },\n { once: true },\n );\n }\n\n process.stdout.write(`Watching ${options.input.join(\", \")}...\\n`);\n await run();\n}\n\nexport async function main(argv: string[] = process.argv.slice(2)): Promise<number> {\n const { values, positionals } = parseArgs({\n args: argv,\n options: {\n out: { type: \"string\", short: \"o\", default: \".translations\" },\n watch: { type: \"boolean\", short: \"w\", default: false },\n strict: { type: \"boolean\", default: true },\n help: { type: \"boolean\", short: \"h\", default: false },\n },\n allowPositionals: true,\n });\n\n if (values.help) {\n process.stdout.write(HELP);\n return 0;\n }\n\n if (positionals.length === 0) {\n process.stderr.write(HELP);\n return 1;\n }\n\n const options: CompileAndWriteOptions = {\n input: positionals,\n out: values.out,\n strict: values.strict,\n };\n\n if (values.watch) {\n await watchCompile(options);\n return 0;\n }\n\n try {\n await compileAndWrite(options);\n return 0;\n } catch (error) {\n if (error instanceof StaticAnalysisError) {\n process.stderr.write(`${error.message}\\n`);\n return 1;\n }\n\n throw error;\n }\n}\n\nconst entry = process.argv[1] ? resolve(process.argv[1]) : \"\";\nconst isMain = entry === fileURLToPath(import.meta.url);\n\nif (isMain) {\n main().then((code) => {\n process.exitCode = code;\n });\n}\n"],"mappings":";;;;;;;;AAQA,SAAS,cAAc,QAA+B;CACpD,OAAO,GAAG,KAAK,UAAU,EAAE,iBAAiB,CAAC,GAAG,OAAO,eAAe,CAAC,CAAC,KAAK,EAAE,GAAG,MAAM,CAAC,EAAE;AAC7F;AAEA,MAAM,OAAO;;;;;;;;;;;;;AAwBb,SAAgB,cAAc,OAA2B;CACvD,MAAM,wBAAQ,IAAI,IAAY;CAE9B,KAAK,MAAM,WAAW,OAAO;EAC3B,MAAM,QAAQ,QAAQ,OAAO,QAAQ;EACrC,MAAM,OACJ,UAAU,KAAK,QAAQ,OAAO,IAAI,QAAQ,MAAM,GAAG,KAAK,CAAC,CAAC,QAAQ,WAAW,EAAE,KAAK;EAEtF,MAAM,IAAI,QAAQ,IAAI,CAAC;CACzB;CAEA,OAAO,CAAC,GAAG,KAAK;AAClB;AAEA,SAAS,SAAS,IAAgB,IAAwB;CACxD,IAAI;CAEJ,aAAa;EACX,IAAI,OACF,aAAa,KAAK;EAGpB,QAAQ,WAAW,IAAI,EAAE;CAC3B;AACF;AAEA,eAAsB,gBACpB,SAC+B;CAC/B,MAAM,SAAS,MAAM,QAAQ;EAAE,OAAO,QAAQ;EAAO,QAAQ,QAAQ;CAAO,CAAC;CAC7E,MAAM,SAAS,QAA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A,QAAQ,OAAO,MAAM,YAAY,QAAQ,MAAM,KAAK,IAAI,EAAE,MAAM;CAChE,MAAM,IAAI;AACZ;AAEA,eAAsB,KAAK,OAAiB,QAAQ,KAAK,MAAM,CAAC,GAAoB;CAClF,MAAM,EAAE,QAAQ,gBAAgB,UAAU;EACxC,MAAM;EACN,SAAS;GACP,KAAK;IAAE,MAAM;IAAU,OAAO;IAAK,SAAS;GAAgB;GAC5D,OAAO;IAAE,MAAM;IAAW,OAAO;IAAK,SAAS;GAAM;GACrD,QAAQ;IAAE,MAAM;IAAW,SAAS;GAAK;GACzC,MAAM;IAAE,MAAM;IAAW,OAAO;IAAK,SAAS;GAAM;EACtD;EACA,kBAAkB;CACpB,CAAC;CAED,IAAI,OAAO,MAAM;EACf,QAAQ,OAAO,MAAM,IAAI;EACzB,OAAO;CACT;CAEA,IAAI,YAAY,WAAW,GAAG;EAC5B,QAAQ,OAAO,MAAM,IAAI;EACzB,OAAO;CACT;CAEA,MAAM,UAAkC;EACtC,OAAO;EACP,KAAK,OAAO;EACZ,QAAQ,OAAO;CACjB;CAEA,IAAI,OAAO,OAAO;EAChB,MAAM,aAAa,OAAO;EAC1B,OAAO;CACT;CAEA,IAAI;EACF,MAAM,gBAAgB,OAAO;EAC7B,OAAO;CACT,SAAS,OAAO;EACd,IAAI,iBAAiB,qBAAqB;GACxC,QAAQ,OAAO,MAAM,GAAG,MAAM,QAAQ,GAAG;GACzC,OAAO;EACT;EAEA,MAAM;CACR;AACF;AAKA,KAHc,QAAQ,KAAK,KAAK,QAAQ,QAAQ,KAAK,EAAE,IAAI,QAClC,cAAc,OAAO,KAAK,GAAG,GAGpD,KAAK,CAAC,CAAC,MAAM,SAAS;CACpB,QAAQ,WAAW;AACrB,CAAC"}
@@ -0,0 +1,28 @@
1
+ //#region src/compiler.ts
2
+ var StaticAnalysisError = class extends Error {
3
+ file;
4
+ span;
5
+ constructor(message, file = "", span) {
6
+ super(message);
7
+ this.file = file;
8
+ this.span = span;
9
+ this.name = "StaticAnalysisError";
10
+ }
11
+ };
12
+ async function compile(options) {
13
+ const { compileSync } = await import("../native/native.js");
14
+ try {
15
+ return compileSync(options.input, options.strict);
16
+ } catch (error) {
17
+ if (error instanceof Error) throw new StaticAnalysisError(error.message);
18
+ throw new StaticAnalysisError(String(error));
19
+ }
20
+ }
21
+ function typegen(output) {
22
+ if (output.translationKeys.length === 0) return "export type Translations = {};\n";
23
+ return `export type Translations = {\n${output.translationKeys.sort().map((key) => ` ${JSON.stringify(key)}: string;`).join("\n")}\n};\n`;
24
+ }
25
+ //#endregion
26
+ export { compile as n, typegen as r, StaticAnalysisError as t };
27
+
28
+ //# sourceMappingURL=compiler-DxWiaGcG.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compiler-DxWiaGcG.mjs","names":[],"sources":["../src/compiler.ts"],"sourcesContent":["export interface CompileOptions {\n /** glob patterns */\n input: string[];\n /** when false, extract all static t() calls; defaults to true (only useTranslations/fromTranslations) */\n strict?: boolean;\n}\n\nexport interface CompileOutput {\n /** All encoded keys */\n translationKeys: string[];\n}\n\nexport class StaticAnalysisError extends Error {\n constructor(\n message: string,\n readonly file: string = \"\",\n readonly span?: { start: number; end: number },\n ) {\n super(message);\n this.name = \"StaticAnalysisError\";\n }\n}\n\nexport async function compile(options: CompileOptions): Promise<CompileOutput> {\n const { compileSync } = await import(\"../native/native.js\");\n\n try {\n return compileSync(options.input, options.strict);\n } catch (error) {\n if (error instanceof Error) {\n throw new StaticAnalysisError(error.message);\n }\n\n throw new StaticAnalysisError(String(error));\n }\n}\n\nexport function typegen(output: CompileOutput): string {\n if (output.translationKeys.length === 0) {\n return \"export type Translations = {};\\n\";\n }\n\n const keys = output.translationKeys.sort();\n const entries = keys.map((key) => ` ${JSON.stringify(key)}: string;`).join(\"\\n\");\n\n return `export type Translations = {\\n${entries}\\n};\\n`;\n}\n"],"mappings":";AAYA,IAAa,sBAAb,cAAyC,MAAM;CAGlC;CACA;CAHX,YACE,SACA,OAAwB,IACxB,MACA;EACA,MAAM,OAAO;EAHJ,KAAA,OAAA;EACA,KAAA,OAAA;EAGT,KAAK,OAAO;CACd;AACF;AAEA,eAAsB,QAAQ,SAAiD;CAC7E,MAAM,EAAE,gBAAgB,MAAM,OAAO;CAErC,IAAI;EACF,OAAO,YAAY,QAAQ,OAAO,QAAQ,MAAM;CAClD,SAAS,OAAO;EACd,IAAI,iBAAiB,OACnB,MAAM,IAAI,oBAAoB,MAAM,OAAO;EAG7C,MAAM,IAAI,oBAAoB,OAAO,KAAK,CAAC;CAC7C;AACF;AAEA,SAAgB,QAAQ,QAA+B;CACrD,IAAI,OAAO,gBAAgB,WAAW,GACpC,OAAO;CAMT,OAAO,iCAHM,OAAO,gBAAgB,KACjB,CAAC,CAAC,KAAK,QAAQ,KAAK,KAAK,UAAU,GAAG,EAAE,UAAU,CAAC,CAAC,KAAK,IAE9B,EAAE;AAClD"}
package/dist/index.d.mts CHANGED
@@ -1,9 +1,9 @@
1
- import { Span } from "oxc-parser";
2
-
3
1
  //#region src/compiler.d.ts
4
2
  interface CompileOptions {
5
3
  /** glob patterns */
6
4
  input: string[];
5
+ /** when false, extract all static t() calls; defaults to true (only useTranslations/fromTranslations) */
6
+ strict?: boolean;
7
7
  }
8
8
  interface CompileOutput {
9
9
  /** All encoded keys */
@@ -11,8 +11,14 @@ interface CompileOutput {
11
11
  }
12
12
  declare class StaticAnalysisError extends Error {
13
13
  readonly file: string;
14
- readonly span?: Span | undefined;
15
- constructor(message: string, file: string, span?: Span | undefined);
14
+ readonly span?: {
15
+ start: number;
16
+ end: number;
17
+ } | undefined;
18
+ constructor(message: string, file?: string, span?: {
19
+ start: number;
20
+ end: number;
21
+ } | undefined);
16
22
  }
17
23
  declare function compile(options: CompileOptions): Promise<CompileOutput>;
18
24
  declare function typegen(output: CompileOutput): string;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/compiler.ts"],"mappings":";;;UAgBiB,cAAA;;EAEf,KAAK;AAAA;AAAA,UAGU,aAAA;EAHV;EAKL,eAAe;AAAA;AAAA,cAGJ,mBAAA,SAA4B,KAAA;EAAA,SAG5B,IAAA;EAAA,SACA,IAAA,GAAO,IAAA;cAFhB,OAAA,UACS,IAAA,UACA,IAAA,GAAO,IAAA;AAAA;AAAA,iBAyWE,OAAA,CAAQ,OAAA,EAAS,cAAA,GAAiB,OAAA,CAAQ,aAAA;AAAA,iBAkBhD,OAAA,CAAQ,MAAqB,EAAb,aAAa"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/compiler.ts"],"mappings":";UAAiB,cAAA;EAAA;EAEf,KAAA;;EAEA,MAAM;AAAA;AAAA,UAGS,aAAA;EAAa;EAE5B,eAAe;AAAA;AAAA,cAGJ,mBAAA,SAA4B,KAAK;EAAA,SAGjC,IAAA;EAAA,SACA,IAAA;IAAS,KAAA;IAAe,GAAA;EAAA;cAFjC,OAAA,UACS,IAAA,WACA,IAAA;IAAS,KAAA;IAAe,GAAA;EAAA;AAAA;AAAA,iBAOf,OAAA,CAAQ,OAAA,EAAS,cAAA,GAAiB,OAAA,CAAQ,aAAA;AAAA,iBAchD,OAAA,CAAQ,MAAqB,EAAb,aAAa"}
package/dist/index.mjs CHANGED
@@ -1,218 +1,2 @@
1
- import fs from "node:fs/promises";
2
- import path from "node:path";
3
- import { Visitor, parseSync } from "oxc-parser";
4
- import { glob } from "tinyglobby";
5
- //#region src/compiler.ts
6
- var StaticAnalysisError = class extends Error {
7
- file;
8
- span;
9
- constructor(message, file, span) {
10
- super(message);
11
- this.file = file;
12
- this.span = span;
13
- this.name = "StaticAnalysisError";
14
- }
15
- };
16
- function formatLocation(source, offset) {
17
- let line = 1;
18
- let column = 1;
19
- for (let i = 0; i < offset && i < source.length; i++) if (source[i] === "\n") {
20
- line++;
21
- column = 1;
22
- } else column++;
23
- return `${line}:${column}`;
24
- }
25
- function parseUseTranslationsCall(expr, source, file) {
26
- if (expr.type !== "CallExpression") return null;
27
- if (expr.callee.type !== "Identifier" || expr.callee.name !== "useTranslations") return null;
28
- if (expr.arguments.length === 0) return [void 0];
29
- if (expr.arguments.length > 1) fail(source, file, expr, "useTranslations accepts at most one options argument");
30
- const arg = expr.arguments[0];
31
- if (!arg || arg.type === "SpreadElement") fail(source, file, arg ?? expr, "useTranslations options must be a static object");
32
- return collectNotes(arg, source, file);
33
- }
34
- function unwrapExpression(expr) {
35
- while (expr.type === "ParenthesizedExpression" || expr.type === "TSAsExpression" || expr.type === "TSSatisfiesExpression" || expr.type === "TSTypeAssertion") expr = expr.expression;
36
- return expr;
37
- }
38
- function fail(source, file, span, message) {
39
- throw new StaticAnalysisError(`${file}:${formatLocation(source, span.start)}: ${message}`, file, span);
40
- }
41
- function collectStaticStrings(expr, source, file) {
42
- expr = unwrapExpression(expr);
43
- if (expr.type === "Literal" && typeof expr.value === "string") return [expr.value];
44
- if (expr.type === "TemplateLiteral") {
45
- if (expr.expressions.length > 0) fail(source, file, expr, "translation key must be a static string");
46
- return [expr.quasis.map((q) => q.value.cooked ?? q.value.raw).join("")];
47
- }
48
- if (expr.type === "ConditionalExpression") return [...collectStaticStrings(expr.consequent, source, file), ...collectStaticStrings(expr.alternate, source, file)];
49
- fail(source, file, expr, "translation key must be a static string");
50
- }
51
- function getNoteProperty(properties) {
52
- for (const prop of properties) {
53
- if (prop.type !== "Property") continue;
54
- if (prop.kind !== "init") continue;
55
- if (prop.shorthand && prop.key.type === "Identifier") {
56
- if (prop.key.name === "note") return prop;
57
- continue;
58
- }
59
- if (prop.key.type === "Identifier" && prop.key.name === "note") return prop;
60
- if (prop.key.type === "Literal" && typeof prop.key.value === "string" && prop.key.value === "note") return prop;
61
- }
62
- }
63
- function collectNotes(expr, source, file) {
64
- if (!expr) return [void 0];
65
- expr = unwrapExpression(expr);
66
- if (expr.type === "ConditionalExpression") return [...collectNotes(expr.consequent, source, file), ...collectNotes(expr.alternate, source, file)];
67
- if (expr.type !== "ObjectExpression") fail(source, file, expr, "translation options must be a static object");
68
- for (const prop of expr.properties) if (prop.type === "SpreadElement") fail(source, file, prop, "translation options cannot use spread properties");
69
- const noteProp = getNoteProperty(expr.properties);
70
- if (!noteProp) return [void 0];
71
- if (noteProp.shorthand) fail(source, file, noteProp, "translation note must be a static string");
72
- return collectStaticStrings(noteProp.value, source, file).map((note) => note);
73
- }
74
- function currentScope(scopes) {
75
- const scope = scopes.at(-1);
76
- if (!scope) throw new Error("scope stack is empty");
77
- return scope;
78
- }
79
- function registerBinding(pattern, hookNotes, scopes) {
80
- switch (pattern.type) {
81
- case "Identifier":
82
- currentScope(scopes).set(pattern.name, hookNotes);
83
- return;
84
- case "ObjectPattern":
85
- for (const prop of pattern.properties) if (prop.type === "RestElement") registerBinding(prop.argument, false, scopes);
86
- else registerBinding(prop.value, false, scopes);
87
- return;
88
- case "ArrayPattern":
89
- for (const element of pattern.elements) {
90
- if (!element) continue;
91
- if (element.type === "RestElement") registerBinding(element.argument, false, scopes);
92
- else registerBinding(element, false, scopes);
93
- }
94
- return;
95
- case "AssignmentPattern":
96
- registerBinding(pattern.left, hookNotes, scopes);
97
- return;
98
- }
99
- }
100
- function registerParams(params, scopes) {
101
- for (const param of params) if (param.type === "TSParameterProperty") registerBinding(param.parameter, false, scopes);
102
- else if (param.type === "RestElement") registerBinding(param.argument, false, scopes);
103
- else registerBinding(param, false, scopes);
104
- }
105
- function getTranslationHookNotes(name, scopes) {
106
- for (let i = scopes.length - 1; i >= 0; i--) {
107
- const scope = scopes[i];
108
- if (!scope) continue;
109
- if (scope.has(name)) return scope.get(name);
110
- }
111
- return false;
112
- }
113
- function encodeTranslationKey(text, hookNotes, callNotes) {
114
- const keys = [];
115
- for (const hookNote of hookNotes) for (const callNote of callNotes) {
116
- const notes = [];
117
- if (hookNote) notes.push(hookNote);
118
- if (callNote) notes.push(callNote);
119
- keys.push(encodeKey(text, notes));
120
- }
121
- return keys;
122
- }
123
- function analyzeCall(call, source, file, keys, scopes) {
124
- const callee = unwrapExpression(call.callee);
125
- if (callee.type !== "Identifier") return;
126
- const hookNotes = getTranslationHookNotes(callee.name, scopes);
127
- if (hookNotes === false) return;
128
- if (call.arguments.length === 0) fail(source, file, call, "translation call requires a static string argument");
129
- const firstArg = call.arguments[0];
130
- if (!firstArg || firstArg.type === "SpreadElement") fail(source, file, firstArg ?? call, "translation key must be a static string");
131
- const texts = collectStaticStrings(firstArg, source, file);
132
- let callNotes = [void 0];
133
- if (call.arguments.length > 1) {
134
- const secondArg = call.arguments[1];
135
- if (!secondArg || secondArg.type === "SpreadElement") fail(source, file, secondArg ?? call, "translation options must be a static object");
136
- callNotes = collectNotes(secondArg, source, file);
137
- }
138
- for (const text of texts) for (const key of encodeTranslationKey(text, hookNotes, callNotes)) keys.add(key);
139
- }
140
- function analyzeSource(file, lang, source) {
141
- const result = parseSync(file, source, {
142
- lang,
143
- sourceType: "module"
144
- });
145
- if (result.errors.length > 0) throw new StaticAnalysisError(result.errors.map((error) => error.message).join("\n"), file);
146
- const keys = /* @__PURE__ */ new Set();
147
- const scopes = [/* @__PURE__ */ new Map()];
148
- const pushScope = () => {
149
- scopes.push(/* @__PURE__ */ new Map());
150
- };
151
- const popScope = () => {
152
- scopes.pop();
153
- };
154
- new Visitor({
155
- BlockStatement: pushScope,
156
- "BlockStatement:exit": popScope,
157
- CatchClause: pushScope,
158
- "CatchClause:exit": popScope,
159
- FunctionDeclaration(node) {
160
- pushScope();
161
- registerParams(node.params, scopes);
162
- },
163
- "FunctionDeclaration:exit": popScope,
164
- FunctionExpression(node) {
165
- pushScope();
166
- registerParams(node.params, scopes);
167
- },
168
- "FunctionExpression:exit": popScope,
169
- ArrowFunctionExpression(node) {
170
- pushScope();
171
- registerParams(node.params, scopes);
172
- },
173
- "ArrowFunctionExpression:exit": popScope,
174
- VariableDeclarator(decl) {
175
- if (!decl.init) return;
176
- const hookNotes = parseUseTranslationsCall(unwrapExpression(decl.init), source, file);
177
- registerBinding(decl.id, hookNotes ?? false, scopes);
178
- },
179
- CallExpression(call) {
180
- analyzeCall(call, source, file, keys, scopes);
181
- }
182
- }).visit(result.program);
183
- return [...keys];
184
- }
185
- function getLang(file) {
186
- switch (path.extname(file)) {
187
- case ".tsx": return "tsx";
188
- case ".ts":
189
- case ".cts":
190
- case ".mts": return "ts";
191
- case ".jsx": return "jsx";
192
- case ".cjs":
193
- case ".mjs":
194
- case ".js": return "js";
195
- }
196
- }
197
- async function compile(options) {
198
- const files = await glob(options.input, { absolute: true });
199
- const keys = /* @__PURE__ */ new Set();
200
- for (const file of files) {
201
- const lang = getLang(file);
202
- if (!lang) continue;
203
- const source = await fs.readFile(file, "utf8");
204
- for (const key of analyzeSource(file, lang, source)) keys.add(key);
205
- }
206
- return { translationKeys: [...keys].sort() };
207
- }
208
- function typegen(output) {
209
- if (output.translationKeys.length === 0) return "export type Translations = {};\n";
210
- return `export type Translations = {\n${output.translationKeys.map((key) => ` ${JSON.stringify(key)}: string;`).join("\n")}\n};\n`;
211
- }
212
- function encodeKey(text, notes) {
213
- return text + notes.map((n) => `(${n})`).join("");
214
- }
215
- //#endregion
1
+ import { n as compile, r as typegen, t as StaticAnalysisError } from "./compiler-DxWiaGcG.mjs";
216
2
  export { StaticAnalysisError, compile, typegen };
217
-
218
- //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ export * from '@fuma-translate/binding-wasm32-wasi'
package/package.json CHANGED
@@ -1,35 +1,86 @@
1
1
  {
2
2
  "name": "fuma-translate",
3
- "version": "0.0.3",
3
+ "version": "1.0.0",
4
4
  "description": "The build-time package to implement multilingual in your JavaScript app",
5
5
  "license": "MIT",
6
6
  "author": "Fuma Nama",
7
- "repository": "github:fuma-nama/fuma-translate",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "github:fuma-nama/fuma-translate"
10
+ },
11
+ "bin": {
12
+ "fuma-translate": "./dist/cli.mjs"
13
+ },
8
14
  "files": [
9
- "dist"
15
+ "dist",
16
+ "native/native.js",
17
+ "native/native.d.ts",
18
+ "native/browser.js",
19
+ "native/webcontainer-fallback.cjs"
10
20
  ],
11
21
  "type": "module",
12
22
  "exports": {
13
23
  ".": "./dist/index.mjs",
24
+ "./cli": "./dist/cli.mjs",
14
25
  "./package.json": "./package.json"
15
26
  },
16
27
  "publishConfig": {
17
28
  "access": "public"
18
29
  },
19
30
  "dependencies": {
20
- "oxc-parser": "^0.134.0",
21
- "tinyglobby": "^0.2.17"
31
+ "chokidar": "^5.0.0"
22
32
  },
23
33
  "devDependencies": {
34
+ "@emnapi/core": "^1.11.0",
35
+ "@emnapi/runtime": "^1.11.0",
36
+ "@napi-rs/cli": "^3.7.1",
37
+ "@tybys/wasm-util": "^0.10.0",
24
38
  "@types/node": "^25.9.2",
25
39
  "@types/react": "^19.2.17",
26
40
  "tsdown": "^0.22.2",
27
41
  "typescript": "6.0.3",
28
42
  "@repo/typescript-config": "0.0.0"
29
43
  },
44
+ "napi": {
45
+ "binaryName": "fuma-translate",
46
+ "packageName": "@fuma-translate/binding",
47
+ "targets": [
48
+ "aarch64-apple-darwin",
49
+ "aarch64-unknown-linux-gnu",
50
+ "aarch64-unknown-linux-musl",
51
+ "aarch64-pc-windows-msvc",
52
+ "x86_64-apple-darwin",
53
+ "x86_64-unknown-linux-gnu",
54
+ "x86_64-unknown-linux-musl",
55
+ "x86_64-pc-windows-msvc",
56
+ "wasm32-wasip1-threads"
57
+ ],
58
+ "wasm": {
59
+ "browser": {
60
+ "fs": false
61
+ }
62
+ }
63
+ },
64
+ "engines": {
65
+ "node": ">=22"
66
+ },
67
+ "optionalDependencies": {
68
+ "@fuma-translate/binding-darwin-arm64": "1.0.0",
69
+ "@fuma-translate/binding-linux-arm64-gnu": "1.0.0",
70
+ "@fuma-translate/binding-linux-arm64-musl": "1.0.0",
71
+ "@fuma-translate/binding-win32-arm64-msvc": "1.0.0",
72
+ "@fuma-translate/binding-darwin-x64": "1.0.0",
73
+ "@fuma-translate/binding-linux-x64-gnu": "1.0.0",
74
+ "@fuma-translate/binding-linux-x64-musl": "1.0.0",
75
+ "@fuma-translate/binding-win32-x64-msvc": "1.0.0",
76
+ "@fuma-translate/binding-wasm32-wasi": "1.0.0"
77
+ },
30
78
  "scripts": {
31
79
  "types:check": "tsc --noEmit",
32
- "build": "tsdown",
33
- "dev": "tsdown --watch"
80
+ "build:native": "napi build --platform --release --esm --js native.js --dts native.d.ts --output-dir native",
81
+ "build:js": "tsdown",
82
+ "build": "pnpm build:native && pnpm build:js",
83
+ "dev": "tsdown --watch",
84
+ "artifacts": "napi create-npm-dirs && napi artifacts --npm-dir npm --output-dir native --build-output-dir native"
34
85
  }
35
86
  }
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/compiler.ts"],"sourcesContent":["import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type {\n BindingPattern,\n CallExpression,\n Expression,\n ObjectProperty,\n ObjectPropertyKind,\n ParamPattern,\n Span,\n} from \"oxc-parser\";\nimport { parseSync, Visitor } from \"oxc-parser\";\nimport { glob } from \"tinyglobby\";\n\ntype SupportedLang = \"js\" | \"jsx\" | \"ts\" | \"tsx\";\n\nexport interface CompileOptions {\n /** glob patterns */\n input: string[];\n}\n\nexport interface CompileOutput {\n /** All encoded keys */\n translationKeys: string[];\n}\n\nexport class StaticAnalysisError extends Error {\n constructor(\n message: string,\n readonly file: string,\n readonly span?: Span,\n ) {\n super(message);\n this.name = \"StaticAnalysisError\";\n }\n}\n\nfunction formatLocation(source: string, offset: number): string {\n let line = 1;\n let column = 1;\n\n for (let i = 0; i < offset && i < source.length; i++) {\n if (source[i] === \"\\n\") {\n line++;\n column = 1;\n } else {\n column++;\n }\n }\n\n return `${line}:${column}`;\n}\n\ntype HookNoteBranches = (string | undefined)[];\n\nfunction parseUseTranslationsCall(\n expr: Expression,\n source: string,\n file: string,\n): HookNoteBranches | null {\n if (expr.type !== \"CallExpression\") return null;\n if (expr.callee.type !== \"Identifier\" || expr.callee.name !== \"useTranslations\") {\n return null;\n }\n\n if (expr.arguments.length === 0) return [undefined];\n\n if (expr.arguments.length > 1) {\n fail(source, file, expr, \"useTranslations accepts at most one options argument\");\n }\n\n const arg = expr.arguments[0];\n if (!arg || arg.type === \"SpreadElement\") {\n fail(source, file, arg ?? expr, \"useTranslations options must be a static object\");\n }\n\n return collectNotes(arg, source, file);\n}\n\nfunction unwrapExpression(expr: Expression): Expression {\n while (\n expr.type === \"ParenthesizedExpression\" ||\n expr.type === \"TSAsExpression\" ||\n expr.type === \"TSSatisfiesExpression\" ||\n expr.type === \"TSTypeAssertion\"\n ) {\n expr = expr.expression;\n }\n return expr;\n}\n\nfunction fail(source: string, file: string, span: Span, message: string): never {\n throw new StaticAnalysisError(\n `${file}:${formatLocation(source, span.start)}: ${message}`,\n file,\n span,\n );\n}\n\nfunction collectStaticStrings(expr: Expression, source: string, file: string): string[] {\n expr = unwrapExpression(expr);\n\n if (expr.type === \"Literal\" && typeof expr.value === \"string\") {\n return [expr.value];\n }\n\n if (expr.type === \"TemplateLiteral\") {\n if (expr.expressions.length > 0) {\n fail(source, file, expr, \"translation key must be a static string\");\n }\n return [expr.quasis.map((q) => q.value.cooked ?? q.value.raw).join(\"\")];\n }\n\n if (expr.type === \"ConditionalExpression\") {\n return [\n ...collectStaticStrings(expr.consequent, source, file),\n ...collectStaticStrings(expr.alternate, source, file),\n ];\n }\n\n fail(source, file, expr, \"translation key must be a static string\");\n}\n\nfunction getNoteProperty(properties: ObjectPropertyKind[]): ObjectProperty | undefined {\n for (const prop of properties) {\n if (prop.type !== \"Property\") continue;\n if (prop.kind !== \"init\") continue;\n\n if (prop.shorthand && prop.key.type === \"Identifier\") {\n if (prop.key.name === \"note\") return prop;\n continue;\n }\n\n if (prop.key.type === \"Identifier\" && prop.key.name === \"note\") {\n return prop;\n }\n\n if (\n prop.key.type === \"Literal\" &&\n typeof prop.key.value === \"string\" &&\n prop.key.value === \"note\"\n ) {\n return prop;\n }\n }\n return undefined;\n}\n\nfunction collectNotes(\n expr: Expression | undefined,\n source: string,\n file: string,\n): (string | undefined)[] {\n if (!expr) return [undefined];\n\n expr = unwrapExpression(expr);\n\n if (expr.type === \"ConditionalExpression\") {\n return [\n ...collectNotes(expr.consequent, source, file),\n ...collectNotes(expr.alternate, source, file),\n ];\n }\n\n if (expr.type !== \"ObjectExpression\") {\n fail(source, file, expr, \"translation options must be a static object\");\n }\n\n for (const prop of expr.properties) {\n if (prop.type === \"SpreadElement\") {\n fail(source, file, prop, \"translation options cannot use spread properties\");\n }\n }\n\n const noteProp = getNoteProperty(expr.properties);\n if (!noteProp) return [undefined];\n\n if (noteProp.shorthand) {\n fail(source, file, noteProp, \"translation note must be a static string\");\n }\n\n const noteValues = collectStaticStrings(noteProp.value, source, file);\n return noteValues.map((note) => note);\n}\n\nfunction currentScope(\n scopes: Map<string, HookNoteBranches | false>[],\n): Map<string, HookNoteBranches | false> {\n const scope = scopes.at(-1);\n if (!scope) throw new Error(\"scope stack is empty\");\n return scope;\n}\n\nfunction registerBinding(\n pattern: BindingPattern,\n hookNotes: HookNoteBranches | false,\n scopes: Map<string, HookNoteBranches | false>[],\n): void {\n switch (pattern.type) {\n case \"Identifier\":\n currentScope(scopes).set(pattern.name, hookNotes);\n return;\n case \"ObjectPattern\":\n for (const prop of pattern.properties) {\n if (prop.type === \"RestElement\") {\n registerBinding(prop.argument, false, scopes);\n } else {\n registerBinding(prop.value, false, scopes);\n }\n }\n return;\n case \"ArrayPattern\":\n for (const element of pattern.elements) {\n if (!element) continue;\n if (element.type === \"RestElement\") {\n registerBinding(element.argument, false, scopes);\n } else {\n registerBinding(element, false, scopes);\n }\n }\n return;\n case \"AssignmentPattern\":\n registerBinding(pattern.left, hookNotes, scopes);\n return;\n }\n}\n\nfunction registerParams(\n params: ParamPattern[],\n scopes: Map<string, HookNoteBranches | false>[],\n): void {\n for (const param of params) {\n if (param.type === \"TSParameterProperty\") {\n registerBinding(param.parameter, false, scopes);\n } else if (param.type === \"RestElement\") {\n registerBinding(param.argument, false, scopes);\n } else {\n registerBinding(param, false, scopes);\n }\n }\n}\n\nfunction getTranslationHookNotes(\n name: string,\n scopes: Map<string, HookNoteBranches | false>[],\n): HookNoteBranches | false {\n for (let i = scopes.length - 1; i >= 0; i--) {\n const scope = scopes[i];\n if (!scope) continue;\n if (scope.has(name)) return scope.get(name)!;\n }\n return false;\n}\n\nfunction encodeTranslationKey(\n text: string,\n hookNotes: HookNoteBranches,\n callNotes: HookNoteBranches,\n): string[] {\n const keys: string[] = [];\n\n for (const hookNote of hookNotes) {\n for (const callNote of callNotes) {\n const notes: string[] = [];\n if (hookNote) notes.push(hookNote);\n if (callNote) notes.push(callNote);\n keys.push(encodeKey(text, notes));\n }\n }\n\n return keys;\n}\n\nfunction analyzeCall(\n call: CallExpression,\n source: string,\n file: string,\n keys: Set<string>,\n scopes: Map<string, HookNoteBranches | false>[],\n): void {\n const callee = unwrapExpression(call.callee);\n if (callee.type !== \"Identifier\") return;\n\n const hookNotes = getTranslationHookNotes(callee.name, scopes);\n if (hookNotes === false) return;\n\n if (call.arguments.length === 0) {\n fail(source, file, call, \"translation call requires a static string argument\");\n }\n\n const firstArg = call.arguments[0];\n if (!firstArg || firstArg.type === \"SpreadElement\") {\n fail(source, file, firstArg ?? call, \"translation key must be a static string\");\n }\n\n const texts = collectStaticStrings(firstArg, source, file);\n\n let callNotes: HookNoteBranches = [undefined];\n if (call.arguments.length > 1) {\n const secondArg = call.arguments[1];\n if (!secondArg || secondArg.type === \"SpreadElement\") {\n fail(source, file, secondArg ?? call, \"translation options must be a static object\");\n }\n callNotes = collectNotes(secondArg, source, file);\n }\n\n for (const text of texts) {\n for (const key of encodeTranslationKey(text, hookNotes, callNotes)) {\n keys.add(key);\n }\n }\n}\n\nfunction analyzeSource(file: string, lang: SupportedLang, source: string): string[] {\n const result = parseSync(file, source, { lang, sourceType: \"module\" });\n\n if (result.errors.length > 0) {\n const message = result.errors.map((error) => error.message).join(\"\\n\");\n throw new StaticAnalysisError(message, file);\n }\n\n const keys = new Set<string>();\n const scopes: Map<string, HookNoteBranches | false>[] = [new Map()];\n\n const pushScope = () => {\n scopes.push(new Map());\n };\n\n const popScope = () => {\n scopes.pop();\n };\n\n const visitor = new Visitor({\n BlockStatement: pushScope,\n \"BlockStatement:exit\": popScope,\n\n CatchClause: pushScope,\n \"CatchClause:exit\": popScope,\n\n FunctionDeclaration(node) {\n pushScope();\n registerParams(node.params, scopes);\n },\n \"FunctionDeclaration:exit\": popScope,\n\n FunctionExpression(node) {\n pushScope();\n registerParams(node.params, scopes);\n },\n \"FunctionExpression:exit\": popScope,\n\n ArrowFunctionExpression(node) {\n pushScope();\n registerParams(node.params, scopes);\n },\n \"ArrowFunctionExpression:exit\": popScope,\n\n VariableDeclarator(decl) {\n if (!decl.init) return;\n\n const init = unwrapExpression(decl.init);\n const hookNotes = parseUseTranslationsCall(init, source, file);\n registerBinding(decl.id, hookNotes ?? false, scopes);\n },\n\n CallExpression(call) {\n analyzeCall(call, source, file, keys, scopes);\n },\n });\n\n visitor.visit(result.program);\n return [...keys];\n}\n\nfunction getLang(file: string): SupportedLang | undefined {\n switch (path.extname(file)) {\n case \".tsx\":\n return \"tsx\";\n case \".ts\":\n case \".cts\":\n case \".mts\":\n return \"ts\";\n case \".jsx\":\n return \"jsx\";\n case \".cjs\":\n case \".mjs\":\n case \".js\":\n return \"js\";\n }\n}\n\nexport async function compile(options: CompileOptions): Promise<CompileOutput> {\n const files = await glob(options.input, { absolute: true });\n const keys = new Set<string>();\n\n for (const file of files) {\n const lang = getLang(file);\n if (!lang) continue;\n\n const source = await fs.readFile(file, \"utf8\");\n for (const key of analyzeSource(file, lang, source)) {\n keys.add(key);\n }\n }\n\n const translationKeys = [...keys].sort();\n return { translationKeys };\n}\n\nexport function typegen(output: CompileOutput): string {\n if (output.translationKeys.length === 0) {\n return \"export type Translations = {};\\n\";\n }\n\n const entries = output.translationKeys\n .map((key) => ` ${JSON.stringify(key)}: string;`)\n .join(\"\\n\");\n\n return `export type Translations = {\\n${entries}\\n};\\n`;\n}\n\nfunction encodeKey(text: string, notes: string[]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