@verbaly/next 0.66.0 → 0.67.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 +1 -1
- package/dist/index.cjs +68 -15
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +69 -16
- package/dist/index.js.map +1 -1
- package/dist/loader.cjs.map +1 -1
- package/package.json +6 -6
package/README.md
CHANGED
|
@@ -135,7 +135,7 @@ export default async function LocaleLayout({ children, params }) {
|
|
|
135
135
|
Without `setRequestLocale`, Verbaly negotiates from the cookie and `Accept-Language`, and that read
|
|
136
136
|
is what makes the route dynamic. With it, no header is read at all.
|
|
137
137
|
|
|
138
|
-
That's it. `next dev` extracts your messages live (catalogs + `verbaly.d.ts` stay fresh)
|
|
138
|
+
That's it. `next dev` extracts your messages live (catalogs + `verbaly.d.ts` stay fresh) and says in the terminal what it would otherwise do quietly: a hand edit of a text your code owns, a key written with two texts, a translation that is now older than its source. `next build` blocks on missing translations once it has compiled, so `next typegen`, which loads the same config, never meets the gate. Dev and build show the same words: a text written in the code wins over the catalog in both.
|
|
139
139
|
|
|
140
140
|
## 📖 Options
|
|
141
141
|
|
package/dist/index.cjs
CHANGED
|
@@ -1,6 +1,27 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
let node_path = require("node:path");
|
|
3
2
|
let node_fs = require("node:fs");
|
|
3
|
+
let node_path = require("node:path");
|
|
4
|
+
//#region src/report.ts
|
|
5
|
+
const said = /* @__PURE__ */ new Set();
|
|
6
|
+
function once(id, line) {
|
|
7
|
+
if (said.has(id)) return;
|
|
8
|
+
said.add(id);
|
|
9
|
+
console.warn(`[verbaly] ${line}`);
|
|
10
|
+
}
|
|
11
|
+
function reportDev(compiler, cfg, registry, replaced, previous, outdated) {
|
|
12
|
+
const messages = registry.messages();
|
|
13
|
+
const rel = (file) => (0, node_path.relative)(cfg.root, file).replaceAll("\\", "/");
|
|
14
|
+
for (const key of replaced) {
|
|
15
|
+
const msg = messages.get(key);
|
|
16
|
+
if (!msg || previous && previous.get(key) !== msg.message) continue;
|
|
17
|
+
once(`replaced:${key}`, previous ? `${cfg.sourceLocale}.json: your edit of "${key}" was replaced, its text lives in ${rel(msg.file)}: change it there` : `${cfg.sourceLocale}.json: "${key}" took the text written in ${rel(msg.file)}, the code owns it`);
|
|
18
|
+
}
|
|
19
|
+
for (const entry of compiler.collisionEntries(registry)) once(`collision:${entry.key}`, compiler.formatCollision(entry, cfg.root).trim());
|
|
20
|
+
for (const { name, file } of registry.missed()) once(`missed:${file}:${name}`, `${rel(file)}: ${name}\`…\` is never extracted, so it stays in the source language: name it t`);
|
|
21
|
+
for (const { locale, key } of outdated) once(`outdated:${locale}:${key}`, `${locale}: "${key}" was translated from an older source text, update it or approve it`);
|
|
22
|
+
return new Map([...messages].map(([key, msg]) => [key, msg.message]));
|
|
23
|
+
}
|
|
24
|
+
//#endregion
|
|
4
25
|
//#region src/codegen.ts
|
|
5
26
|
const GENERATED_DIR = ".verbaly";
|
|
6
27
|
function generatedDir(root) {
|
|
@@ -13,11 +34,21 @@ function writeIfChanged(file, content) {
|
|
|
13
34
|
(0, node_fs.writeFileSync)(file, content);
|
|
14
35
|
return true;
|
|
15
36
|
}
|
|
16
|
-
|
|
17
|
-
|
|
37
|
+
let stateWarned = false;
|
|
38
|
+
function syncAndWrite(compiler, cfg, catalogs, registry, requestOptions, previous) {
|
|
39
|
+
const { added, replaced } = compiler.syncCatalogs(cfg, catalogs, registry);
|
|
18
40
|
for (const locale of Object.keys(added)) compiler.writeCatalog(cfg, locale, catalogs[locale] ?? {});
|
|
19
41
|
compiler.writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});
|
|
20
42
|
writeGeneratedModules(compiler, cfg, catalogs, requestOptions);
|
|
43
|
+
let outdated = [];
|
|
44
|
+
try {
|
|
45
|
+
const state = compiler.updateState(cfg, catalogs);
|
|
46
|
+
outdated = compiler.outdatedTranslations(cfg, catalogs, state.fingerprints);
|
|
47
|
+
} catch (error) {
|
|
48
|
+
if (!stateWarned) console.warn(`${compiler.formatCliError(error)}, so drafts are not tracked`);
|
|
49
|
+
stateWarned = true;
|
|
50
|
+
}
|
|
51
|
+
return reportDev(compiler, cfg, registry, replaced, previous, outdated);
|
|
21
52
|
}
|
|
22
53
|
function writeGeneratedModules(compiler, cfg, catalogs, requestOptions = {}) {
|
|
23
54
|
const dir = generatedDir(cfg.root);
|
|
@@ -44,13 +75,14 @@ function writeGeneratedModules(compiler, cfg, catalogs, requestOptions = {}) {
|
|
|
44
75
|
//#endregion
|
|
45
76
|
//#region src/watch.ts
|
|
46
77
|
const active = /* @__PURE__ */ new Map();
|
|
47
|
-
function startWatcher(compiler, cfg, requestOptions) {
|
|
78
|
+
function startWatcher(compiler, cfg, requestOptions, startTexts) {
|
|
48
79
|
const existing = active.get(cfg.root);
|
|
49
80
|
if (existing) return existing;
|
|
50
81
|
const catalogDir = (0, node_path.relative)(cfg.root, cfg.dir).replaceAll("\\", "/");
|
|
51
82
|
let timer;
|
|
52
83
|
let running = false;
|
|
53
84
|
let queued = false;
|
|
85
|
+
let texts = startTexts;
|
|
54
86
|
async function refresh() {
|
|
55
87
|
if (running) {
|
|
56
88
|
queued = true;
|
|
@@ -58,7 +90,7 @@ function startWatcher(compiler, cfg, requestOptions) {
|
|
|
58
90
|
}
|
|
59
91
|
running = true;
|
|
60
92
|
try {
|
|
61
|
-
syncAndWrite(compiler, cfg, compiler.loadCatalogs(cfg), await compiler.extractProject(cfg), requestOptions);
|
|
93
|
+
texts = syncAndWrite(compiler, cfg, compiler.loadCatalogs(cfg), await compiler.extractProject(cfg), requestOptions, texts);
|
|
62
94
|
} catch (error) {
|
|
63
95
|
console.warn("[verbaly] live extraction failed:", error);
|
|
64
96
|
} finally {
|
|
@@ -81,7 +113,7 @@ function startWatcher(compiler, cfg, requestOptions) {
|
|
|
81
113
|
if (!filename) return;
|
|
82
114
|
const file = filename.replaceAll("\\", "/");
|
|
83
115
|
if (file.startsWith(`.verbaly/`) || file.startsWith(".next/") || file.includes("node_modules/") || file.endsWith(".d.ts")) return;
|
|
84
|
-
if (file.startsWith(`${catalogDir}/`) && file.endsWith(".json") || compiler.SOURCE_FILE_RE.test(file)) schedule();
|
|
116
|
+
if (file.startsWith(`${catalogDir}/`) && file.endsWith(".json") && !(0, node_path.basename)(file).startsWith(".") || compiler.SOURCE_FILE_RE.test(file)) schedule();
|
|
85
117
|
});
|
|
86
118
|
const dispose = () => {
|
|
87
119
|
clearTimeout(timer);
|
|
@@ -95,6 +127,7 @@ function startWatcher(compiler, cfg, requestOptions) {
|
|
|
95
127
|
//#region src/index.ts
|
|
96
128
|
const DEV_PHASE = "phase-development-server";
|
|
97
129
|
const BUILD_PHASE = "phase-production-build";
|
|
130
|
+
const ANALYZE_PHASE = "phase-analyze";
|
|
98
131
|
const LOADER = "@verbaly/next/loader";
|
|
99
132
|
const SOURCE_PATH_RE = /\.[cm]?[jt]sx?$/;
|
|
100
133
|
function withVerbaly(nextConfig, options = {}) {
|
|
@@ -106,29 +139,42 @@ function withVerbaly(nextConfig, options = {}) {
|
|
|
106
139
|
return async (phase, context = {}) => {
|
|
107
140
|
const base = typeof nextConfig === "function" ? await nextConfig(phase, context) : nextConfig ?? {};
|
|
108
141
|
const root = verbalyConfig.root ?? process.cwd();
|
|
109
|
-
if (phase !== DEV_PHASE && phase !== BUILD_PHASE) return composeConfig(base, root);
|
|
142
|
+
if (phase !== DEV_PHASE && phase !== BUILD_PHASE && phase !== ANALYZE_PHASE) return composeConfig(base, root);
|
|
110
143
|
const compiler = await import("@verbaly/compiler");
|
|
111
144
|
const cfg = await compiler.loadConfig(root, verbalyConfig);
|
|
112
145
|
const catalogs = compiler.loadCatalogs(cfg);
|
|
113
146
|
const registry = await compiler.extractProject(cfg);
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
147
|
+
let gate;
|
|
148
|
+
if (phase === DEV_PHASE) {
|
|
149
|
+
const texts = syncAndWrite(compiler, cfg, catalogs, registry, requestOptions);
|
|
150
|
+
startWatcher(compiler, cfg, requestOptions, texts);
|
|
117
151
|
} else {
|
|
118
|
-
|
|
119
|
-
|
|
152
|
+
compiler.syncCatalogs(cfg, catalogs, registry);
|
|
153
|
+
writeGeneratedModules(compiler, cfg, catalogs, requestOptions);
|
|
154
|
+
if (phase === BUILD_PHASE) {
|
|
155
|
+
const runGate = () => compiler.runBuildGate(cfg, registry, failOnMissing);
|
|
156
|
+
if (hasAfterCompileHook(cfg.root)) gate = runGate;
|
|
157
|
+
else runGate();
|
|
158
|
+
}
|
|
120
159
|
}
|
|
121
160
|
const scope = {
|
|
122
161
|
root: cfg.root,
|
|
123
162
|
include: cfg.include,
|
|
124
163
|
exclude: cfg.exclude
|
|
125
164
|
};
|
|
126
|
-
return composeConfig(base, cfg.root, scope);
|
|
165
|
+
return composeConfig(base, cfg.root, scope, gate);
|
|
127
166
|
};
|
|
128
167
|
}
|
|
129
|
-
function
|
|
168
|
+
function hasAfterCompileHook(root) {
|
|
169
|
+
for (let dir = root;; dir = (0, node_path.dirname)(dir)) {
|
|
170
|
+
const next = (0, node_path.join)(dir, "node_modules", "next");
|
|
171
|
+
if ((0, node_fs.existsSync)((0, node_path.join)(next, "package.json"))) return (0, node_fs.existsSync)((0, node_path.join)(next, "dist", "build", "after-production-compile.js"));
|
|
172
|
+
if ((0, node_path.dirname)(dir) === dir) return false;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
function composeConfig(base, root, scope, gate) {
|
|
130
176
|
const runtimeModule = (0, node_path.join)(generatedDir(root), "index.js");
|
|
131
|
-
const { webpack: userWebpack, turbopack } = base;
|
|
177
|
+
const { webpack: userWebpack, turbopack, compiler: userCompiler } = base;
|
|
132
178
|
const loader = scope ? {
|
|
133
179
|
loader: LOADER,
|
|
134
180
|
options: scope
|
|
@@ -142,6 +188,13 @@ function composeConfig(base, root, scope) {
|
|
|
142
188
|
rules["*"] = existing ? [...Array.isArray(existing) ? existing : [existing], verbalyRule] : verbalyRule;
|
|
143
189
|
return {
|
|
144
190
|
...base,
|
|
191
|
+
...gate && { compiler: {
|
|
192
|
+
...userCompiler,
|
|
193
|
+
async runAfterProductionCompile(metadata) {
|
|
194
|
+
await userCompiler?.runAfterProductionCompile?.(metadata);
|
|
195
|
+
gate();
|
|
196
|
+
}
|
|
197
|
+
} },
|
|
145
198
|
turbopack: {
|
|
146
199
|
...turbopack,
|
|
147
200
|
resolveAlias: {
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["join","readFileSync","readdirSync","relative","join"],"sources":["../src/codegen.ts","../src/watch.ts","../src/index.ts"],"sourcesContent":["import type { Catalogs, ResolvedConfig } from '@verbaly/compiler';\nimport { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\n\nexport type Compiler = typeof import('@verbaly/compiler');\n\nexport interface RequestOptions {\n cookie?: string | false;\n fallback?: string;\n}\n\nexport const GENERATED_DIR = '.verbaly';\n\nexport function generatedDir(root: string): string {\n return join(root, GENERATED_DIR);\n}\n\n// content compare: identical rewrites must not retrigger the bundler\nfunction writeIfChanged(file: string, content: string): boolean {\n try {\n if (readFileSync(file, 'utf8') === content) return false;\n } catch {\n // new file\n }\n writeFileSync(file, content);\n return true;\n}\n\n// dev pipeline shared by withVerbaly and the watcher: catalogs, dts, runtime modules\nexport function syncAndWrite(\n compiler: Compiler,\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n registry: Awaited<ReturnType<Compiler['extractProject']>>,\n requestOptions: RequestOptions,\n): void {\n const { added } = compiler.syncCatalogs(cfg, catalogs, registry);\n for (const locale of Object.keys(added)) {\n compiler.writeCatalog(cfg, locale, catalogs[locale] ?? {});\n }\n compiler.writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});\n writeGeneratedModules(compiler, cfg, catalogs, requestOptions);\n}\n\n// real-file replacement for virtual:verbaly: Turbopack has no virtual modules\nexport function writeGeneratedModules(\n compiler: Compiler,\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n requestOptions: RequestOptions = {},\n): boolean {\n const dir = generatedDir(cfg.root);\n const localeDir = join(dir, 'locale');\n mkdirSync(localeDir, { recursive: true });\n\n let changed = writeIfChanged(join(dir, '.gitignore'), '*\\n');\n\n // these files are the client module here, so bundle.exclude has to be applied on this path too\n const client = compiler.clientCatalogs(cfg, catalogs);\n const runtime = compiler.generateRuntimeModule(cfg, {\n localeImport: (locale) => `./locale/${locale}.js`,\n extraExports: `export const requestOptions = ${JSON.stringify(requestOptions)};\\n`,\n icu: cfg.icu ?? compiler.needsIcu(client),\n relative: cfg.relative ?? compiler.needsRelative(client),\n inlineCatalog: cfg.render.inlineCatalog === true,\n });\n changed = writeIfChanged(join(dir, 'index.js'), runtime) || changed;\n\n const expected = new Set(cfg.locales.map((locale) => `${locale}.js`));\n for (const locale of cfg.locales) {\n changed =\n writeIfChanged(\n join(localeDir, `${locale}.js`),\n compiler.generateLocaleModule(client[locale] ?? {}),\n ) || changed;\n }\n for (const file of readdirSync(localeDir)) {\n if (!expected.has(file)) {\n rmSync(join(localeDir, file));\n changed = true;\n }\n }\n return changed;\n}\n","import type { ResolvedConfig } from '@verbaly/compiler';\nimport { relative } from 'node:path';\nimport { GENERATED_DIR, syncAndWrite, type Compiler, type RequestOptions } from './codegen';\n\n// one watcher per project root: next.config can be evaluated more than once\nconst active = new Map<string, () => void>();\n\nexport function startWatcher(\n compiler: Compiler,\n cfg: ResolvedConfig,\n requestOptions: RequestOptions,\n): () => void {\n const existing = active.get(cfg.root);\n if (existing) return existing;\n\n const catalogDir = relative(cfg.root, cfg.dir).replaceAll('\\\\', '/');\n let timer: ReturnType<typeof setTimeout> | undefined;\n let running = false;\n let queued = false;\n\n async function refresh(): Promise<void> {\n if (running) {\n queued = true;\n return;\n }\n running = true;\n try {\n const catalogs = compiler.loadCatalogs(cfg);\n const registry = await compiler.extractProject(cfg);\n syncAndWrite(compiler, cfg, catalogs, registry, requestOptions);\n } catch (error) {\n console.warn('[verbaly] live extraction failed:', error);\n } finally {\n running = false;\n if (queued) {\n queued = false;\n schedule();\n }\n }\n }\n\n function schedule(): void {\n clearTimeout(timer);\n timer = setTimeout(() => void refresh(), 150);\n }\n\n const keep = catalogDir.split('/')[0];\n const close = compiler.watchTree(cfg.root, { keep, persistent: false }, (filename) => {\n if (!filename) return;\n const file = filename.replaceAll('\\\\', '/');\n if (\n file.startsWith(`${GENERATED_DIR}/`) ||\n file.startsWith('.next/') ||\n file.includes('node_modules/') ||\n file.endsWith('.d.ts')\n ) {\n return;\n }\n const isCatalog = file.startsWith(`${catalogDir}/`) && file.endsWith('.json');\n if (isCatalog || compiler.SOURCE_FILE_RE.test(file)) schedule();\n });\n\n const dispose = (): void => {\n clearTimeout(timer);\n close();\n active.delete(cfg.root);\n };\n active.set(cfg.root, dispose);\n return dispose;\n}\n\n// test hook\nexport function stopWatcher(root: string): void {\n active.get(root)?.();\n}\n","import type { PluginOptions } from '@verbaly/compiler';\nimport { join } from 'node:path';\nimport {\n GENERATED_DIR,\n generatedDir,\n syncAndWrite,\n writeGeneratedModules,\n type Compiler,\n type RequestOptions,\n} from './codegen';\nimport type { LoaderOptions } from './loader';\nimport { startWatcher } from './watch';\n\nexport type { VerbalyConfig } from '@verbaly/compiler';\nexport type { RequestOptions } from './codegen';\n\nexport interface NextVerbalyOptions extends PluginOptions {\n cookie?: string | false;\n fallback?: string;\n}\n\n// structural NextConfig subset (compat asserted in tests): no index signatures, Next has none\nexport interface WebpackConfigLike {\n resolve?: { alias?: Record<string, unknown>; [key: string]: unknown };\n module?: { rules?: unknown[]; [key: string]: unknown };\n plugins?: unknown[];\n [key: string]: unknown;\n}\n\ninterface WebpackContextLike {\n webpack?: {\n NormalModuleReplacementPlugin: new (test: RegExp, resource: string) => unknown;\n };\n}\n\n// context param is `never` so Next's real webpack fn (specific context type) stays assignable\nexport type WebpackFn = (config: WebpackConfigLike, context: never) => unknown;\n\nexport interface TurbopackLike {\n resolveAlias?: Record<string, unknown>;\n rules?: Record<string, unknown>;\n}\n\nexport interface NextConfigLike {\n webpack?: WebpackFn | null;\n turbopack?: TurbopackLike;\n}\n\n// constraint is object, not NextConfigLike: an all-optional target rejects by weak-type\nexport type NextConfigInput<C extends object> =\n C | ((phase: string, context: { defaultConfig?: unknown }) => C | Promise<C>);\n\n// next/constants values: literal to keep this module import-free of next\nconst DEV_PHASE = 'phase-development-server';\nconst BUILD_PHASE = 'phase-production-build';\n\nconst LOADER = '@verbaly/next/loader';\n// matched via condition.path: a bare extension glob also hits Next's App Router entry\nconst SOURCE_PATH_RE = /\\.[cm]?[jt]sx?$/;\n\nexport function withVerbaly<C extends object>(\n nextConfig?: NextConfigInput<C>,\n options: NextVerbalyOptions = {},\n): (phase: string, context?: { defaultConfig?: unknown }) => Promise<C> {\n const { failOnMissing, cookie, fallback, ...verbalyConfig } = options;\n const requestOptions: RequestOptions = { cookie, fallback };\n\n return async (phase, context = {}) => {\n const base: C =\n typeof nextConfig === 'function'\n ? await nextConfig(phase, context)\n : (nextConfig ?? ({} as C));\n const root = verbalyConfig.root ?? process.cwd();\n\n // production server / export: everything is bundled, so no FS work, config only\n if (phase !== DEV_PHASE && phase !== BUILD_PHASE) {\n return composeConfig(base, root);\n }\n\n // dynamic: the compiler is ESM-only and this entry is also consumed as CJS\n const compiler: Compiler = await import('@verbaly/compiler');\n\n const cfg = await compiler.loadConfig(root, verbalyConfig);\n const catalogs = compiler.loadCatalogs(cfg);\n const registry = await compiler.extractProject(cfg);\n\n if (phase === BUILD_PHASE) {\n compiler.runBuildGate(cfg, registry, failOnMissing);\n writeGeneratedModules(compiler, cfg, catalogs, requestOptions);\n } else {\n syncAndWrite(compiler, cfg, catalogs, registry, requestOptions);\n startWatcher(compiler, cfg, requestOptions);\n }\n\n // the loader rewrites exactly what extract reads: a file outside include keeps its t`…`\n const scope: LoaderOptions = { root: cfg.root, include: cfg.include, exclude: cfg.exclude };\n return composeConfig(base, cfg.root, scope);\n };\n}\n\nfunction composeConfig<C extends object>(base: C, root: string, scope?: LoaderOptions): C {\n const runtimeModule = join(generatedDir(root), 'index.js');\n const { webpack: userWebpack, turbopack } = base as NextConfigLike;\n const loader = scope ? { loader: LOADER, options: scope } : LOADER;\n\n const rules: Record<string, unknown> = { ...turbopack?.rules };\n const verbalyRule = {\n condition: { all: [{ not: 'foreign' }, { path: SOURCE_PATH_RE }] },\n loaders: [loader],\n };\n const existing = rules['*'];\n rules['*'] = existing\n ? [...(Array.isArray(existing) ? existing : [existing]), verbalyRule]\n : verbalyRule;\n\n return {\n ...base,\n turbopack: {\n ...turbopack,\n resolveAlias: {\n ...turbopack?.resolveAlias,\n 'virtual:verbaly': `./${GENERATED_DIR}/index.js`,\n },\n rules,\n },\n webpack(config: WebpackConfigLike, context: unknown) {\n // webpack 5 parses 'virtual:' as a URI scheme, so resolve.alias never fires\n const { webpack: webpackInstance } = (context ?? {}) as WebpackContextLike;\n if (webpackInstance?.NormalModuleReplacementPlugin) {\n config.plugins ??= [];\n config.plugins.push(\n new webpackInstance.NormalModuleReplacementPlugin(/^virtual:verbaly$/, runtimeModule),\n );\n }\n config.resolve ??= {};\n config.resolve.alias ??= {};\n (config.resolve.alias as Record<string, unknown>)['virtual:verbaly'] = runtimeModule;\n config.module ??= {};\n config.module.rules ??= [];\n config.module.rules.push({\n test: SOURCE_PATH_RE,\n exclude: /node_modules/,\n enforce: 'pre',\n use: [typeof loader === 'string' ? { loader } : loader],\n });\n return userWebpack ? userWebpack(config, context as never) : config;\n },\n } as C;\n}\n"],"mappings":";;;;AAWA,MAAa,gBAAgB;AAE7B,SAAgB,aAAa,MAAsB;CACjD,QAAA,GAAOA,UAAAA,KAAAA,CAAK,MAAM,aAAa;AACjC;AAGA,SAAS,eAAe,MAAc,SAA0B;CAC9D,IAAI;EACF,KAAA,GAAIC,QAAAA,aAAAA,CAAa,MAAM,MAAM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MAAc,OAA0B;CACxF,MAAM,iBAAA,GAAgBC,UAAAA,KAAAA,CAAK,aAAa,IAAI,GAAG,UAAU;CACzD,MAAM,EAAE,SAAS,aAAa,cAAc;CAC5C,MAAM,SAAS,QAAQ;EAAE,QAAQ;EAAQ,SAAS;CAAM,IAAI;CAE5D,MAAM,QAAiC,EAAE,GAAG,WAAW,MAAM;CAC7D,MAAM,cAAc;EAClB,WAAW,EAAE,KAAK,CAAC,EAAE,KAAK,UAAU,GAAG,EAAE,MAAM,eAAe,CAAC,EAAE;EACjE,SAAS,CAAC,MAAM;CAClB;CACA,MAAM,WAAW,MAAM;CACvB,MAAM,OAAO,WACT,CAAC,GAAI,MAAM,QAAQ,QAAQ,IAAI,WAAW,CAAC,QAAQ,GAAI,WAAW,IAClE;CAEJ,OAAO;EACL,GAAG;EACH,WAAW;GACT,GAAG;GACH,cAAc;IACZ,GAAG,WAAW;IACd,mBAAmB,KAAK,cAAc;GACxC;GACA;EACF;EACA,QAAQ,QAA2B,SAAkB;GAEnD,MAAM,EAAE,SAAS,oBAAqB,WAAW,CAAC;GAClD,IAAI,iBAAiB,+BAA+B;IAClD,OAAO,YAAY,CAAC;IACpB,OAAO,QAAQ,KACb,IAAI,gBAAgB,8BAA8B,qBAAqB,aAAa,CACtF;GACF;GACA,OAAO,YAAY,CAAC;GACpB,OAAO,QAAQ,UAAU,CAAC;GAC1B,OAAQ,QAAQ,MAAkC,qBAAqB;GACvE,OAAO,WAAW,CAAC;GACnB,OAAO,OAAO,UAAU,CAAC;GACzB,OAAO,OAAO,MAAM,KAAK;IACvB,MAAM;IACN,SAAS;IACT,SAAS;IACT,KAAK,CAAC,OAAO,WAAW,WAAW,EAAE,OAAO,IAAI,MAAM;GACxD,CAAC;GACD,OAAO,cAAc,YAAY,QAAQ,OAAgB,IAAI;EAC/D;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["relative","join","readFileSync","readdirSync","relative","basename","dirname","join","existsSync"],"sources":["../src/report.ts","../src/codegen.ts","../src/watch.ts","../src/index.ts"],"sourcesContent":["import type { ResolvedConfig } from '@verbaly/compiler';\nimport { relative } from 'node:path';\nimport type { Compiler, Registry } from './codegen';\n\n// a dev server re-runs per keystroke: keyed on what it is about, never on the text being typed\nconst said = new Set<string>();\n\nfunction once(id: string, line: string): void {\n if (said.has(id)) return;\n said.add(id);\n console.warn(`[verbaly] ${line}`);\n}\n\n// the code texts of the last run tell an edit in the code from an edit in the catalog\nexport type CodeTexts = Map<string, string>;\n\nexport function reportDev(\n compiler: Compiler,\n cfg: ResolvedConfig,\n registry: Registry,\n replaced: string[],\n previous: CodeTexts | undefined,\n outdated: { locale: string; key: string }[],\n): CodeTexts {\n const messages = registry.messages();\n const rel = (file: string): string => relative(cfg.root, file).replaceAll('\\\\', '/');\n for (const key of replaced) {\n const msg = messages.get(key);\n // the code changed this text since the last run, which is how a text it owns is edited\n if (!msg || (previous && previous.get(key) !== msg.message)) continue;\n once(\n `replaced:${key}`,\n previous\n ? `${cfg.sourceLocale}.json: your edit of \"${key}\" was replaced, its text lives in ${rel(msg.file)}: change it there`\n : `${cfg.sourceLocale}.json: \"${key}\" took the text written in ${rel(msg.file)}, the code owns it`,\n );\n }\n for (const entry of compiler.collisionEntries(registry)) {\n once(`collision:${entry.key}`, compiler.formatCollision(entry, cfg.root).trim());\n }\n for (const { name, file } of registry.missed()) {\n once(\n `missed:${file}:${name}`,\n `${rel(file)}: ${name}\\`…\\` is never extracted, so it stays in the source language: name it t`,\n );\n }\n for (const { locale, key } of outdated) {\n once(\n `outdated:${locale}:${key}`,\n `${locale}: \"${key}\" was translated from an older source text, update it or approve it`,\n );\n }\n return new Map([...messages].map(([key, msg]) => [key, msg.message]));\n}\n\n// test hook: the set is module state, and each test starts from a server that said nothing\nexport function resetReported(): void {\n said.clear();\n}\n","import type { Catalogs, ResolvedConfig } from '@verbaly/compiler';\nimport { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { reportDev, type CodeTexts } from './report';\n\nexport type Compiler = typeof import('@verbaly/compiler');\nexport type Registry = Awaited<ReturnType<Compiler['extractProject']>>;\n\nexport interface RequestOptions {\n cookie?: string | false;\n fallback?: string;\n}\n\nexport const GENERATED_DIR = '.verbaly';\n\nexport function generatedDir(root: string): string {\n return join(root, GENERATED_DIR);\n}\n\n// content compare: identical rewrites must not retrigger the bundler\nfunction writeIfChanged(file: string, content: string): boolean {\n try {\n if (readFileSync(file, 'utf8') === content) return false;\n } catch {\n // new file\n }\n writeFileSync(file, content);\n return true;\n}\n\nlet stateWarned = false;\n\n// dev pipeline shared by withVerbaly and the watcher: catalogs, dts, runtime modules, state\nexport function syncAndWrite(\n compiler: Compiler,\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n registry: Registry,\n requestOptions: RequestOptions,\n previous?: CodeTexts,\n): CodeTexts {\n const { added, replaced } = compiler.syncCatalogs(cfg, catalogs, registry);\n for (const locale of Object.keys(added)) {\n compiler.writeCatalog(cfg, locale, catalogs[locale] ?? {});\n }\n compiler.writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});\n writeGeneratedModules(compiler, cfg, catalogs, requestOptions);\n let outdated: { locale: string; key: string }[] = [];\n try {\n // a pruned key takes its draft along, and an edited source text marks its translations\n const state = compiler.updateState(cfg, catalogs);\n outdated = compiler.outdatedTranslations(cfg, catalogs, state.fingerprints);\n } catch (error) {\n // a broken sidecar must not stop next dev: say it once and keep serving\n if (!stateWarned) console.warn(`${compiler.formatCliError(error)}, so drafts are not tracked`);\n stateWarned = true;\n }\n return reportDev(compiler, cfg, registry, replaced, previous, outdated);\n}\n\n// real-file replacement for virtual:verbaly: Turbopack has no virtual modules\nexport function writeGeneratedModules(\n compiler: Compiler,\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n requestOptions: RequestOptions = {},\n): boolean {\n const dir = generatedDir(cfg.root);\n const localeDir = join(dir, 'locale');\n mkdirSync(localeDir, { recursive: true });\n\n let changed = writeIfChanged(join(dir, '.gitignore'), '*\\n');\n\n // these files are the client module here, so bundle.exclude has to be applied on this path too\n const client = compiler.clientCatalogs(cfg, catalogs);\n const runtime = compiler.generateRuntimeModule(cfg, {\n localeImport: (locale) => `./locale/${locale}.js`,\n extraExports: `export const requestOptions = ${JSON.stringify(requestOptions)};\\n`,\n icu: cfg.icu ?? compiler.needsIcu(client),\n relative: cfg.relative ?? compiler.needsRelative(client),\n inlineCatalog: cfg.render.inlineCatalog === true,\n });\n changed = writeIfChanged(join(dir, 'index.js'), runtime) || changed;\n\n const expected = new Set(cfg.locales.map((locale) => `${locale}.js`));\n for (const locale of cfg.locales) {\n changed =\n writeIfChanged(\n join(localeDir, `${locale}.js`),\n compiler.generateLocaleModule(client[locale] ?? {}),\n ) || changed;\n }\n for (const file of readdirSync(localeDir)) {\n if (!expected.has(file)) {\n rmSync(join(localeDir, file));\n changed = true;\n }\n }\n return changed;\n}\n","import type { ResolvedConfig } from '@verbaly/compiler';\nimport { basename, relative } from 'node:path';\nimport { GENERATED_DIR, syncAndWrite, type Compiler, type RequestOptions } from './codegen';\nimport type { CodeTexts } from './report';\n\n// one watcher per project root: next.config can be evaluated more than once\nconst active = new Map<string, () => void>();\n\nexport function startWatcher(\n compiler: Compiler,\n cfg: ResolvedConfig,\n requestOptions: RequestOptions,\n startTexts?: CodeTexts,\n): () => void {\n const existing = active.get(cfg.root);\n if (existing) return existing;\n\n const catalogDir = relative(cfg.root, cfg.dir).replaceAll('\\\\', '/');\n let timer: ReturnType<typeof setTimeout> | undefined;\n let running = false;\n let queued = false;\n let texts = startTexts;\n\n async function refresh(): Promise<void> {\n if (running) {\n queued = true;\n return;\n }\n running = true;\n try {\n const catalogs = compiler.loadCatalogs(cfg);\n const registry = await compiler.extractProject(cfg);\n texts = syncAndWrite(compiler, cfg, catalogs, registry, requestOptions, texts);\n } catch (error) {\n console.warn('[verbaly] live extraction failed:', error);\n } finally {\n running = false;\n if (queued) {\n queued = false;\n schedule();\n }\n }\n }\n\n function schedule(): void {\n clearTimeout(timer);\n timer = setTimeout(() => void refresh(), 150);\n }\n\n const keep = catalogDir.split('/')[0];\n const close = compiler.watchTree(cfg.root, { keep, persistent: false }, (filename) => {\n if (!filename) return;\n const file = filename.replaceAll('\\\\', '/');\n if (\n file.startsWith(`${GENERATED_DIR}/`) ||\n file.startsWith('.next/') ||\n file.includes('node_modules/') ||\n file.endsWith('.d.ts')\n ) {\n return;\n }\n // a dotfile there is the state sidecar this pipeline writes: it changes no message\n const isCatalog =\n file.startsWith(`${catalogDir}/`) && file.endsWith('.json') && !basename(file).startsWith('.');\n if (isCatalog || compiler.SOURCE_FILE_RE.test(file)) schedule();\n });\n\n const dispose = (): void => {\n clearTimeout(timer);\n close();\n active.delete(cfg.root);\n };\n active.set(cfg.root, dispose);\n return dispose;\n}\n\n// test hook\nexport function stopWatcher(root: string): void {\n active.get(root)?.();\n}\n","import type { PluginOptions } from '@verbaly/compiler';\nimport { existsSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport {\n GENERATED_DIR,\n generatedDir,\n syncAndWrite,\n writeGeneratedModules,\n type Compiler,\n type RequestOptions,\n} from './codegen';\nimport type { LoaderOptions } from './loader';\nimport { startWatcher } from './watch';\n\nexport type { VerbalyConfig } from '@verbaly/compiler';\nexport type { RequestOptions } from './codegen';\n\nexport interface NextVerbalyOptions extends PluginOptions {\n cookie?: string | false;\n fallback?: string;\n}\n\n// structural NextConfig subset (compat asserted in tests): no index signatures, Next has none\nexport interface WebpackConfigLike {\n resolve?: { alias?: Record<string, unknown>; [key: string]: unknown };\n module?: { rules?: unknown[]; [key: string]: unknown };\n plugins?: unknown[];\n [key: string]: unknown;\n}\n\ninterface WebpackContextLike {\n webpack?: {\n NormalModuleReplacementPlugin: new (test: RegExp, resource: string) => unknown;\n };\n}\n\n// context param is `never` so Next's real webpack fn (specific context type) stays assignable\nexport type WebpackFn = (config: WebpackConfigLike, context: never) => unknown;\n\nexport interface TurbopackLike {\n resolveAlias?: Record<string, unknown>;\n rules?: Record<string, unknown>;\n}\n\n// metadata is `never` for the same reason as the webpack context: Next's own type stays assignable\nexport interface CompilerLike {\n runAfterProductionCompile?: (metadata: never) => Promise<void>;\n}\n\nexport interface NextConfigLike {\n webpack?: WebpackFn | null;\n turbopack?: TurbopackLike;\n compiler?: CompilerLike;\n}\n\n// constraint is object, not NextConfigLike: an all-optional target rejects by weak-type\nexport type NextConfigInput<C extends object> =\n C | ((phase: string, context: { defaultConfig?: unknown }) => C | Promise<C>);\n\n// next/constants values: literal to keep this module import-free of next\nconst DEV_PHASE = 'phase-development-server';\nconst BUILD_PHASE = 'phase-production-build';\n// next experimental-analyze compiles the app as well, so it needs the generated modules on disk\nconst ANALYZE_PHASE = 'phase-analyze';\n\nconst LOADER = '@verbaly/next/loader';\n// matched via condition.path: a bare extension glob also hits Next's App Router entry\nconst SOURCE_PATH_RE = /\\.[cm]?[jt]sx?$/;\n\nexport function withVerbaly<C extends object>(\n nextConfig?: NextConfigInput<C>,\n options: NextVerbalyOptions = {},\n): (phase: string, context?: { defaultConfig?: unknown }) => Promise<C> {\n const { failOnMissing, cookie, fallback, ...verbalyConfig } = options;\n const requestOptions: RequestOptions = { cookie, fallback };\n\n return async (phase, context = {}) => {\n const base: C =\n typeof nextConfig === 'function'\n ? await nextConfig(phase, context)\n : (nextConfig ?? ({} as C));\n const root = verbalyConfig.root ?? process.cwd();\n\n // production server / export: everything is bundled, so no FS work, config only\n if (phase !== DEV_PHASE && phase !== BUILD_PHASE && phase !== ANALYZE_PHASE) {\n return composeConfig(base, root);\n }\n\n // dynamic: the compiler is ESM-only and this entry is also consumed as CJS\n const compiler: Compiler = await import('@verbaly/compiler');\n\n const cfg = await compiler.loadConfig(root, verbalyConfig);\n const catalogs = compiler.loadCatalogs(cfg);\n const registry = await compiler.extractProject(cfg);\n let gate: (() => void) | undefined;\n\n if (phase === DEV_PHASE) {\n const texts = syncAndWrite(compiler, cfg, catalogs, registry, requestOptions);\n startWatcher(compiler, cfg, requestOptions, texts);\n } else {\n // the code's text ships, as it does in dev: a catalog edit of a text it owns never wins\n compiler.syncCatalogs(cfg, catalogs, registry);\n writeGeneratedModules(compiler, cfg, catalogs, requestOptions);\n if (phase === BUILD_PHASE) {\n const runGate = (): void => compiler.runBuildGate(cfg, registry, failOnMissing);\n // typegen loads this config in the build phase too, and only a real build runs the hook\n if (hasAfterCompileHook(cfg.root)) gate = runGate;\n else runGate();\n }\n }\n\n // the loader rewrites exactly what extract reads: a file outside include keeps its t`…`\n const scope: LoaderOptions = { root: cfg.root, include: cfg.include, exclude: cfg.exclude };\n return composeConfig(base, cfg.root, scope, gate);\n };\n}\n\n// next build calls compiler.runAfterProductionCompile since 15.4; NODE_PATH may name another next\nfunction hasAfterCompileHook(root: string): boolean {\n for (let dir = root; ; dir = dirname(dir)) {\n const next = join(dir, 'node_modules', 'next');\n if (existsSync(join(next, 'package.json'))) {\n return existsSync(join(next, 'dist', 'build', 'after-production-compile.js'));\n }\n if (dirname(dir) === dir) return false;\n }\n}\n\nfunction composeConfig<C extends object>(\n base: C,\n root: string,\n scope?: LoaderOptions,\n gate?: () => void,\n): C {\n const runtimeModule = join(generatedDir(root), 'index.js');\n const { webpack: userWebpack, turbopack, compiler: userCompiler } = base as NextConfigLike;\n const loader = scope ? { loader: LOADER, options: scope } : LOADER;\n\n const rules: Record<string, unknown> = { ...turbopack?.rules };\n const verbalyRule = {\n condition: { all: [{ not: 'foreign' }, { path: SOURCE_PATH_RE }] },\n loaders: [loader],\n };\n const existing = rules['*'];\n rules['*'] = existing\n ? [...(Array.isArray(existing) ? existing : [existing]), verbalyRule]\n : verbalyRule;\n\n return {\n ...base,\n ...(gate && {\n compiler: {\n ...userCompiler,\n // after the compile, so next typegen, which loads this config too, never meets the gate\n async runAfterProductionCompile(metadata: never) {\n await userCompiler?.runAfterProductionCompile?.(metadata);\n gate();\n },\n },\n }),\n turbopack: {\n ...turbopack,\n resolveAlias: {\n ...turbopack?.resolveAlias,\n 'virtual:verbaly': `./${GENERATED_DIR}/index.js`,\n },\n rules,\n },\n webpack(config: WebpackConfigLike, context: unknown) {\n // webpack 5 parses 'virtual:' as a URI scheme, so resolve.alias never fires\n const { webpack: webpackInstance } = (context ?? {}) as WebpackContextLike;\n if (webpackInstance?.NormalModuleReplacementPlugin) {\n config.plugins ??= [];\n config.plugins.push(\n new webpackInstance.NormalModuleReplacementPlugin(/^virtual:verbaly$/, runtimeModule),\n );\n }\n config.resolve ??= {};\n config.resolve.alias ??= {};\n (config.resolve.alias as Record<string, unknown>)['virtual:verbaly'] = runtimeModule;\n config.module ??= {};\n config.module.rules ??= [];\n config.module.rules.push({\n test: SOURCE_PATH_RE,\n exclude: /node_modules/,\n enforce: 'pre',\n use: [typeof loader === 'string' ? { loader } : loader],\n });\n return userWebpack ? userWebpack(config, context as never) : config;\n },\n } as C;\n}\n"],"mappings":";;;;AAKA,MAAM,uBAAO,IAAI,IAAY;AAE7B,SAAS,KAAK,IAAY,MAAoB;CAC5C,IAAI,KAAK,IAAI,EAAE,GAAG;CAClB,KAAK,IAAI,EAAE;CACX,QAAQ,KAAK,aAAa,MAAM;AAClC;AAKA,SAAgB,UACd,UACA,KACA,UACA,UACA,UACA,UACW;CACX,MAAM,WAAW,SAAS,SAAS;CACnC,MAAM,OAAO,UAAA,GAAyBA,UAAAA,SAAAA,CAAS,IAAI,MAAM,IAAI,CAAC,CAAC,WAAW,MAAM,GAAG;CACnF,KAAK,MAAM,OAAO,UAAU;EAC1B,MAAM,MAAM,SAAS,IAAI,GAAG;EAE5B,IAAI,CAAC,OAAQ,YAAY,SAAS,IAAI,GAAG,MAAM,IAAI,SAAU;EAC7D,KACE,YAAY,OACZ,WACI,GAAG,IAAI,aAAa,uBAAuB,IAAI,oCAAoC,IAAI,IAAI,IAAI,EAAE,qBACjG,GAAG,IAAI,aAAa,UAAU,IAAI,6BAA6B,IAAI,IAAI,IAAI,EAAE,mBACnF;CACF;CACA,KAAK,MAAM,SAAS,SAAS,iBAAiB,QAAQ,GACpD,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;EACF;EACA,QAAQ,QAA2B,SAAkB;GAEnD,MAAM,EAAE,SAAS,oBAAqB,WAAW,CAAC;GAClD,IAAI,iBAAiB,+BAA+B;IAClD,OAAO,YAAY,CAAC;IACpB,OAAO,QAAQ,KACb,IAAI,gBAAgB,8BAA8B,qBAAqB,aAAa,CACtF;GACF;GACA,OAAO,YAAY,CAAC;GACpB,OAAO,QAAQ,UAAU,CAAC;GAC1B,OAAQ,QAAQ,MAAkC,qBAAqB;GACvE,OAAO,WAAW,CAAC;GACnB,OAAO,OAAO,UAAU,CAAC;GACzB,OAAO,OAAO,MAAM,KAAK;IACvB,MAAM;IACN,SAAS;IACT,SAAS;IACT,KAAK,CAAC,OAAO,WAAW,WAAW,EAAE,OAAO,IAAI,MAAM;GACxD,CAAC;GACD,OAAO,cAAc,YAAY,QAAQ,OAAgB,IAAI;EAC/D;CACF;AACF"}
|
package/dist/index.d.cts
CHANGED
|
@@ -27,9 +27,13 @@ export interface TurbopackLike {
|
|
|
27
27
|
resolveAlias?: Record<string, unknown>;
|
|
28
28
|
rules?: Record<string, unknown>;
|
|
29
29
|
}
|
|
30
|
+
export interface CompilerLike {
|
|
31
|
+
runAfterProductionCompile?: (metadata: never) => Promise<void>;
|
|
32
|
+
}
|
|
30
33
|
export interface NextConfigLike {
|
|
31
34
|
webpack?: WebpackFn | null;
|
|
32
35
|
turbopack?: TurbopackLike;
|
|
36
|
+
compiler?: CompilerLike;
|
|
33
37
|
}
|
|
34
38
|
export type NextConfigInput<C extends object> = C | ((phase: string, context: {
|
|
35
39
|
defaultConfig?: unknown;
|
package/dist/index.d.ts
CHANGED
|
@@ -27,9 +27,13 @@ export interface TurbopackLike {
|
|
|
27
27
|
resolveAlias?: Record<string, unknown>;
|
|
28
28
|
rules?: Record<string, unknown>;
|
|
29
29
|
}
|
|
30
|
+
export interface CompilerLike {
|
|
31
|
+
runAfterProductionCompile?: (metadata: never) => Promise<void>;
|
|
32
|
+
}
|
|
30
33
|
export interface NextConfigLike {
|
|
31
34
|
webpack?: WebpackFn | null;
|
|
32
35
|
turbopack?: TurbopackLike;
|
|
36
|
+
compiler?: CompilerLike;
|
|
33
37
|
}
|
|
34
38
|
export type NextConfigInput<C extends object> = C | ((phase: string, context: {
|
|
35
39
|
defaultConfig?: unknown;
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,26 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { basename, dirname, join, relative } from "node:path";
|
|
3
|
+
//#region src/report.ts
|
|
4
|
+
const said = /* @__PURE__ */ new Set();
|
|
5
|
+
function once(id, line) {
|
|
6
|
+
if (said.has(id)) return;
|
|
7
|
+
said.add(id);
|
|
8
|
+
console.warn(`[verbaly] ${line}`);
|
|
9
|
+
}
|
|
10
|
+
function reportDev(compiler, cfg, registry, replaced, previous, outdated) {
|
|
11
|
+
const messages = registry.messages();
|
|
12
|
+
const rel = (file) => relative(cfg.root, file).replaceAll("\\", "/");
|
|
13
|
+
for (const key of replaced) {
|
|
14
|
+
const msg = messages.get(key);
|
|
15
|
+
if (!msg || previous && previous.get(key) !== msg.message) continue;
|
|
16
|
+
once(`replaced:${key}`, previous ? `${cfg.sourceLocale}.json: your edit of "${key}" was replaced, its text lives in ${rel(msg.file)}: change it there` : `${cfg.sourceLocale}.json: "${key}" took the text written in ${rel(msg.file)}, the code owns it`);
|
|
17
|
+
}
|
|
18
|
+
for (const entry of compiler.collisionEntries(registry)) once(`collision:${entry.key}`, compiler.formatCollision(entry, cfg.root).trim());
|
|
19
|
+
for (const { name, file } of registry.missed()) once(`missed:${file}:${name}`, `${rel(file)}: ${name}\`…\` is never extracted, so it stays in the source language: name it t`);
|
|
20
|
+
for (const { locale, key } of outdated) once(`outdated:${locale}:${key}`, `${locale}: "${key}" was translated from an older source text, update it or approve it`);
|
|
21
|
+
return new Map([...messages].map(([key, msg]) => [key, msg.message]));
|
|
22
|
+
}
|
|
23
|
+
//#endregion
|
|
3
24
|
//#region src/codegen.ts
|
|
4
25
|
const GENERATED_DIR = ".verbaly";
|
|
5
26
|
function generatedDir(root) {
|
|
@@ -12,11 +33,21 @@ function writeIfChanged(file, content) {
|
|
|
12
33
|
writeFileSync(file, content);
|
|
13
34
|
return true;
|
|
14
35
|
}
|
|
15
|
-
|
|
16
|
-
|
|
36
|
+
let stateWarned = false;
|
|
37
|
+
function syncAndWrite(compiler, cfg, catalogs, registry, requestOptions, previous) {
|
|
38
|
+
const { added, replaced } = compiler.syncCatalogs(cfg, catalogs, registry);
|
|
17
39
|
for (const locale of Object.keys(added)) compiler.writeCatalog(cfg, locale, catalogs[locale] ?? {});
|
|
18
40
|
compiler.writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});
|
|
19
41
|
writeGeneratedModules(compiler, cfg, catalogs, requestOptions);
|
|
42
|
+
let outdated = [];
|
|
43
|
+
try {
|
|
44
|
+
const state = compiler.updateState(cfg, catalogs);
|
|
45
|
+
outdated = compiler.outdatedTranslations(cfg, catalogs, state.fingerprints);
|
|
46
|
+
} catch (error) {
|
|
47
|
+
if (!stateWarned) console.warn(`${compiler.formatCliError(error)}, so drafts are not tracked`);
|
|
48
|
+
stateWarned = true;
|
|
49
|
+
}
|
|
50
|
+
return reportDev(compiler, cfg, registry, replaced, previous, outdated);
|
|
20
51
|
}
|
|
21
52
|
function writeGeneratedModules(compiler, cfg, catalogs, requestOptions = {}) {
|
|
22
53
|
const dir = generatedDir(cfg.root);
|
|
@@ -43,13 +74,14 @@ function writeGeneratedModules(compiler, cfg, catalogs, requestOptions = {}) {
|
|
|
43
74
|
//#endregion
|
|
44
75
|
//#region src/watch.ts
|
|
45
76
|
const active = /* @__PURE__ */ new Map();
|
|
46
|
-
function startWatcher(compiler, cfg, requestOptions) {
|
|
77
|
+
function startWatcher(compiler, cfg, requestOptions, startTexts) {
|
|
47
78
|
const existing = active.get(cfg.root);
|
|
48
79
|
if (existing) return existing;
|
|
49
80
|
const catalogDir = relative(cfg.root, cfg.dir).replaceAll("\\", "/");
|
|
50
81
|
let timer;
|
|
51
82
|
let running = false;
|
|
52
83
|
let queued = false;
|
|
84
|
+
let texts = startTexts;
|
|
53
85
|
async function refresh() {
|
|
54
86
|
if (running) {
|
|
55
87
|
queued = true;
|
|
@@ -57,7 +89,7 @@ function startWatcher(compiler, cfg, requestOptions) {
|
|
|
57
89
|
}
|
|
58
90
|
running = true;
|
|
59
91
|
try {
|
|
60
|
-
syncAndWrite(compiler, cfg, compiler.loadCatalogs(cfg), await compiler.extractProject(cfg), requestOptions);
|
|
92
|
+
texts = syncAndWrite(compiler, cfg, compiler.loadCatalogs(cfg), await compiler.extractProject(cfg), requestOptions, texts);
|
|
61
93
|
} catch (error) {
|
|
62
94
|
console.warn("[verbaly] live extraction failed:", error);
|
|
63
95
|
} finally {
|
|
@@ -80,7 +112,7 @@ function startWatcher(compiler, cfg, requestOptions) {
|
|
|
80
112
|
if (!filename) return;
|
|
81
113
|
const file = filename.replaceAll("\\", "/");
|
|
82
114
|
if (file.startsWith(`.verbaly/`) || file.startsWith(".next/") || file.includes("node_modules/") || file.endsWith(".d.ts")) return;
|
|
83
|
-
if (file.startsWith(`${catalogDir}/`) && file.endsWith(".json") || compiler.SOURCE_FILE_RE.test(file)) schedule();
|
|
115
|
+
if (file.startsWith(`${catalogDir}/`) && file.endsWith(".json") && !basename(file).startsWith(".") || compiler.SOURCE_FILE_RE.test(file)) schedule();
|
|
84
116
|
});
|
|
85
117
|
const dispose = () => {
|
|
86
118
|
clearTimeout(timer);
|
|
@@ -94,6 +126,7 @@ function startWatcher(compiler, cfg, requestOptions) {
|
|
|
94
126
|
//#region src/index.ts
|
|
95
127
|
const DEV_PHASE = "phase-development-server";
|
|
96
128
|
const BUILD_PHASE = "phase-production-build";
|
|
129
|
+
const ANALYZE_PHASE = "phase-analyze";
|
|
97
130
|
const LOADER = "@verbaly/next/loader";
|
|
98
131
|
const SOURCE_PATH_RE = /\.[cm]?[jt]sx?$/;
|
|
99
132
|
function withVerbaly(nextConfig, options = {}) {
|
|
@@ -105,29 +138,42 @@ function withVerbaly(nextConfig, options = {}) {
|
|
|
105
138
|
return async (phase, context = {}) => {
|
|
106
139
|
const base = typeof nextConfig === "function" ? await nextConfig(phase, context) : nextConfig ?? {};
|
|
107
140
|
const root = verbalyConfig.root ?? process.cwd();
|
|
108
|
-
if (phase !== DEV_PHASE && phase !== BUILD_PHASE) return composeConfig(base, root);
|
|
141
|
+
if (phase !== DEV_PHASE && phase !== BUILD_PHASE && phase !== ANALYZE_PHASE) return composeConfig(base, root);
|
|
109
142
|
const compiler = await import("@verbaly/compiler");
|
|
110
143
|
const cfg = await compiler.loadConfig(root, verbalyConfig);
|
|
111
144
|
const catalogs = compiler.loadCatalogs(cfg);
|
|
112
145
|
const registry = await compiler.extractProject(cfg);
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
146
|
+
let gate;
|
|
147
|
+
if (phase === DEV_PHASE) {
|
|
148
|
+
const texts = syncAndWrite(compiler, cfg, catalogs, registry, requestOptions);
|
|
149
|
+
startWatcher(compiler, cfg, requestOptions, texts);
|
|
116
150
|
} else {
|
|
117
|
-
|
|
118
|
-
|
|
151
|
+
compiler.syncCatalogs(cfg, catalogs, registry);
|
|
152
|
+
writeGeneratedModules(compiler, cfg, catalogs, requestOptions);
|
|
153
|
+
if (phase === BUILD_PHASE) {
|
|
154
|
+
const runGate = () => compiler.runBuildGate(cfg, registry, failOnMissing);
|
|
155
|
+
if (hasAfterCompileHook(cfg.root)) gate = runGate;
|
|
156
|
+
else runGate();
|
|
157
|
+
}
|
|
119
158
|
}
|
|
120
159
|
const scope = {
|
|
121
160
|
root: cfg.root,
|
|
122
161
|
include: cfg.include,
|
|
123
162
|
exclude: cfg.exclude
|
|
124
163
|
};
|
|
125
|
-
return composeConfig(base, cfg.root, scope);
|
|
164
|
+
return composeConfig(base, cfg.root, scope, gate);
|
|
126
165
|
};
|
|
127
166
|
}
|
|
128
|
-
function
|
|
167
|
+
function hasAfterCompileHook(root) {
|
|
168
|
+
for (let dir = root;; dir = dirname(dir)) {
|
|
169
|
+
const next = join(dir, "node_modules", "next");
|
|
170
|
+
if (existsSync(join(next, "package.json"))) return existsSync(join(next, "dist", "build", "after-production-compile.js"));
|
|
171
|
+
if (dirname(dir) === dir) return false;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
function composeConfig(base, root, scope, gate) {
|
|
129
175
|
const runtimeModule = join(generatedDir(root), "index.js");
|
|
130
|
-
const { webpack: userWebpack, turbopack } = base;
|
|
176
|
+
const { webpack: userWebpack, turbopack, compiler: userCompiler } = base;
|
|
131
177
|
const loader = scope ? {
|
|
132
178
|
loader: LOADER,
|
|
133
179
|
options: scope
|
|
@@ -141,6 +187,13 @@ function composeConfig(base, root, scope) {
|
|
|
141
187
|
rules["*"] = existing ? [...Array.isArray(existing) ? existing : [existing], verbalyRule] : verbalyRule;
|
|
142
188
|
return {
|
|
143
189
|
...base,
|
|
190
|
+
...gate && { compiler: {
|
|
191
|
+
...userCompiler,
|
|
192
|
+
async runAfterProductionCompile(metadata) {
|
|
193
|
+
await userCompiler?.runAfterProductionCompile?.(metadata);
|
|
194
|
+
gate();
|
|
195
|
+
}
|
|
196
|
+
} },
|
|
144
197
|
turbopack: {
|
|
145
198
|
...turbopack,
|
|
146
199
|
resolveAlias: {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/codegen.ts","../src/watch.ts","../src/index.ts"],"sourcesContent":["import type { Catalogs, ResolvedConfig } from '@verbaly/compiler';\nimport { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\n\nexport type Compiler = typeof import('@verbaly/compiler');\n\nexport interface RequestOptions {\n cookie?: string | false;\n fallback?: string;\n}\n\nexport const GENERATED_DIR = '.verbaly';\n\nexport function generatedDir(root: string): string {\n return join(root, GENERATED_DIR);\n}\n\n// content compare: identical rewrites must not retrigger the bundler\nfunction writeIfChanged(file: string, content: string): boolean {\n try {\n if (readFileSync(file, 'utf8') === content) return false;\n } catch {\n // new file\n }\n writeFileSync(file, content);\n return true;\n}\n\n// dev pipeline shared by withVerbaly and the watcher: catalogs, dts, runtime modules\nexport function syncAndWrite(\n compiler: Compiler,\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n registry: Awaited<ReturnType<Compiler['extractProject']>>,\n requestOptions: RequestOptions,\n): void {\n const { added } = compiler.syncCatalogs(cfg, catalogs, registry);\n for (const locale of Object.keys(added)) {\n compiler.writeCatalog(cfg, locale, catalogs[locale] ?? {});\n }\n compiler.writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});\n writeGeneratedModules(compiler, cfg, catalogs, requestOptions);\n}\n\n// real-file replacement for virtual:verbaly: Turbopack has no virtual modules\nexport function writeGeneratedModules(\n compiler: Compiler,\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n requestOptions: RequestOptions = {},\n): boolean {\n const dir = generatedDir(cfg.root);\n const localeDir = join(dir, 'locale');\n mkdirSync(localeDir, { recursive: true });\n\n let changed = writeIfChanged(join(dir, '.gitignore'), '*\\n');\n\n // these files are the client module here, so bundle.exclude has to be applied on this path too\n const client = compiler.clientCatalogs(cfg, catalogs);\n const runtime = compiler.generateRuntimeModule(cfg, {\n localeImport: (locale) => `./locale/${locale}.js`,\n extraExports: `export const requestOptions = ${JSON.stringify(requestOptions)};\\n`,\n icu: cfg.icu ?? compiler.needsIcu(client),\n relative: cfg.relative ?? compiler.needsRelative(client),\n inlineCatalog: cfg.render.inlineCatalog === true,\n });\n changed = writeIfChanged(join(dir, 'index.js'), runtime) || changed;\n\n const expected = new Set(cfg.locales.map((locale) => `${locale}.js`));\n for (const locale of cfg.locales) {\n changed =\n writeIfChanged(\n join(localeDir, `${locale}.js`),\n compiler.generateLocaleModule(client[locale] ?? {}),\n ) || changed;\n }\n for (const file of readdirSync(localeDir)) {\n if (!expected.has(file)) {\n rmSync(join(localeDir, file));\n changed = true;\n }\n }\n return changed;\n}\n","import type { ResolvedConfig } from '@verbaly/compiler';\nimport { relative } from 'node:path';\nimport { GENERATED_DIR, syncAndWrite, type Compiler, type RequestOptions } from './codegen';\n\n// one watcher per project root: next.config can be evaluated more than once\nconst active = new Map<string, () => void>();\n\nexport function startWatcher(\n compiler: Compiler,\n cfg: ResolvedConfig,\n requestOptions: RequestOptions,\n): () => void {\n const existing = active.get(cfg.root);\n if (existing) return existing;\n\n const catalogDir = relative(cfg.root, cfg.dir).replaceAll('\\\\', '/');\n let timer: ReturnType<typeof setTimeout> | undefined;\n let running = false;\n let queued = false;\n\n async function refresh(): Promise<void> {\n if (running) {\n queued = true;\n return;\n }\n running = true;\n try {\n const catalogs = compiler.loadCatalogs(cfg);\n const registry = await compiler.extractProject(cfg);\n syncAndWrite(compiler, cfg, catalogs, registry, requestOptions);\n } catch (error) {\n console.warn('[verbaly] live extraction failed:', error);\n } finally {\n running = false;\n if (queued) {\n queued = false;\n schedule();\n }\n }\n }\n\n function schedule(): void {\n clearTimeout(timer);\n timer = setTimeout(() => void refresh(), 150);\n }\n\n const keep = catalogDir.split('/')[0];\n const close = compiler.watchTree(cfg.root, { keep, persistent: false }, (filename) => {\n if (!filename) return;\n const file = filename.replaceAll('\\\\', '/');\n if (\n file.startsWith(`${GENERATED_DIR}/`) ||\n file.startsWith('.next/') ||\n file.includes('node_modules/') ||\n file.endsWith('.d.ts')\n ) {\n return;\n }\n const isCatalog = file.startsWith(`${catalogDir}/`) && file.endsWith('.json');\n if (isCatalog || compiler.SOURCE_FILE_RE.test(file)) schedule();\n });\n\n const dispose = (): void => {\n clearTimeout(timer);\n close();\n active.delete(cfg.root);\n };\n active.set(cfg.root, dispose);\n return dispose;\n}\n\n// test hook\nexport function stopWatcher(root: string): void {\n active.get(root)?.();\n}\n","import type { PluginOptions } from '@verbaly/compiler';\nimport { join } from 'node:path';\nimport {\n GENERATED_DIR,\n generatedDir,\n syncAndWrite,\n writeGeneratedModules,\n type Compiler,\n type RequestOptions,\n} from './codegen';\nimport type { LoaderOptions } from './loader';\nimport { startWatcher } from './watch';\n\nexport type { VerbalyConfig } from '@verbaly/compiler';\nexport type { RequestOptions } from './codegen';\n\nexport interface NextVerbalyOptions extends PluginOptions {\n cookie?: string | false;\n fallback?: string;\n}\n\n// structural NextConfig subset (compat asserted in tests): no index signatures, Next has none\nexport interface WebpackConfigLike {\n resolve?: { alias?: Record<string, unknown>; [key: string]: unknown };\n module?: { rules?: unknown[]; [key: string]: unknown };\n plugins?: unknown[];\n [key: string]: unknown;\n}\n\ninterface WebpackContextLike {\n webpack?: {\n NormalModuleReplacementPlugin: new (test: RegExp, resource: string) => unknown;\n };\n}\n\n// context param is `never` so Next's real webpack fn (specific context type) stays assignable\nexport type WebpackFn = (config: WebpackConfigLike, context: never) => unknown;\n\nexport interface TurbopackLike {\n resolveAlias?: Record<string, unknown>;\n rules?: Record<string, unknown>;\n}\n\nexport interface NextConfigLike {\n webpack?: WebpackFn | null;\n turbopack?: TurbopackLike;\n}\n\n// constraint is object, not NextConfigLike: an all-optional target rejects by weak-type\nexport type NextConfigInput<C extends object> =\n C | ((phase: string, context: { defaultConfig?: unknown }) => C | Promise<C>);\n\n// next/constants values: literal to keep this module import-free of next\nconst DEV_PHASE = 'phase-development-server';\nconst BUILD_PHASE = 'phase-production-build';\n\nconst LOADER = '@verbaly/next/loader';\n// matched via condition.path: a bare extension glob also hits Next's App Router entry\nconst SOURCE_PATH_RE = /\\.[cm]?[jt]sx?$/;\n\nexport function withVerbaly<C extends object>(\n nextConfig?: NextConfigInput<C>,\n options: NextVerbalyOptions = {},\n): (phase: string, context?: { defaultConfig?: unknown }) => Promise<C> {\n const { failOnMissing, cookie, fallback, ...verbalyConfig } = options;\n const requestOptions: RequestOptions = { cookie, fallback };\n\n return async (phase, context = {}) => {\n const base: C =\n typeof nextConfig === 'function'\n ? await nextConfig(phase, context)\n : (nextConfig ?? ({} as C));\n const root = verbalyConfig.root ?? process.cwd();\n\n // production server / export: everything is bundled, so no FS work, config only\n if (phase !== DEV_PHASE && phase !== BUILD_PHASE) {\n return composeConfig(base, root);\n }\n\n // dynamic: the compiler is ESM-only and this entry is also consumed as CJS\n const compiler: Compiler = await import('@verbaly/compiler');\n\n const cfg = await compiler.loadConfig(root, verbalyConfig);\n const catalogs = compiler.loadCatalogs(cfg);\n const registry = await compiler.extractProject(cfg);\n\n if (phase === BUILD_PHASE) {\n compiler.runBuildGate(cfg, registry, failOnMissing);\n writeGeneratedModules(compiler, cfg, catalogs, requestOptions);\n } else {\n syncAndWrite(compiler, cfg, catalogs, registry, requestOptions);\n startWatcher(compiler, cfg, requestOptions);\n }\n\n // the loader rewrites exactly what extract reads: a file outside include keeps its t`…`\n const scope: LoaderOptions = { root: cfg.root, include: cfg.include, exclude: cfg.exclude };\n return composeConfig(base, cfg.root, scope);\n };\n}\n\nfunction composeConfig<C extends object>(base: C, root: string, scope?: LoaderOptions): C {\n const runtimeModule = join(generatedDir(root), 'index.js');\n const { webpack: userWebpack, turbopack } = base as NextConfigLike;\n const loader = scope ? { loader: LOADER, options: scope } : LOADER;\n\n const rules: Record<string, unknown> = { ...turbopack?.rules };\n const verbalyRule = {\n condition: { all: [{ not: 'foreign' }, { path: SOURCE_PATH_RE }] },\n loaders: [loader],\n };\n const existing = rules['*'];\n rules['*'] = existing\n ? [...(Array.isArray(existing) ? existing : [existing]), verbalyRule]\n : verbalyRule;\n\n return {\n ...base,\n turbopack: {\n ...turbopack,\n resolveAlias: {\n ...turbopack?.resolveAlias,\n 'virtual:verbaly': `./${GENERATED_DIR}/index.js`,\n },\n rules,\n },\n webpack(config: WebpackConfigLike, context: unknown) {\n // webpack 5 parses 'virtual:' as a URI scheme, so resolve.alias never fires\n const { webpack: webpackInstance } = (context ?? {}) as WebpackContextLike;\n if (webpackInstance?.NormalModuleReplacementPlugin) {\n config.plugins ??= [];\n config.plugins.push(\n new webpackInstance.NormalModuleReplacementPlugin(/^virtual:verbaly$/, runtimeModule),\n );\n }\n config.resolve ??= {};\n config.resolve.alias ??= {};\n (config.resolve.alias as Record<string, unknown>)['virtual:verbaly'] = runtimeModule;\n config.module ??= {};\n config.module.rules ??= [];\n config.module.rules.push({\n test: SOURCE_PATH_RE,\n exclude: /node_modules/,\n enforce: 'pre',\n use: [typeof loader === 'string' ? { loader } : loader],\n });\n return userWebpack ? userWebpack(config, context as never) : config;\n },\n } as C;\n}\n"],"mappings":";;;AAWA,MAAa,gBAAgB;AAE7B,SAAgB,aAAa,MAAsB;CACjD,OAAO,KAAK,MAAM,aAAa;AACjC;AAGA,SAAS,eAAe,MAAc,SAA0B;CAC9D,IAAI;EACF,IAAI,aAAa,MAAM,MAAM,MAAM,SAAS,OAAO;CACrD,QAAQ,CAER;CACA,cAAc,MAAM,OAAO;CAC3B,OAAO;AACT;AAGA,SAAgB,aACd,UACA,KACA,UACA,UACA,gBACM;CACN,MAAM,EAAE,UAAU,SAAS,aAAa,KAAK,UAAU,QAAQ;CAC/D,KAAK,MAAM,UAAU,OAAO,KAAK,KAAK,GACpC,SAAS,aAAa,KAAK,QAAQ,SAAS,WAAW,CAAC,CAAC;CAE3D,SAAS,SAAS,KAAK,SAAS,IAAI,iBAAiB,CAAC,CAAC;CACvD,sBAAsB,UAAU,KAAK,UAAU,cAAc;AAC/D;AAGA,SAAgB,sBACd,UACA,KACA,UACA,iBAAiC,CAAC,GACzB;CACT,MAAM,MAAM,aAAa,IAAI,IAAI;CACjC,MAAM,YAAY,KAAK,KAAK,QAAQ;CACpC,UAAU,WAAW,EAAE,WAAW,KAAK,CAAC;CAExC,IAAI,UAAU,eAAe,KAAK,KAAK,YAAY,GAAG,KAAK;CAG3D,MAAM,SAAS,SAAS,eAAe,KAAK,QAAQ;CACpD,MAAM,UAAU,SAAS,sBAAsB,KAAK;EAClD,eAAe,WAAW,YAAY,OAAO;EAC7C,cAAc,iCAAiC,KAAK,UAAU,cAAc,EAAE;EAC9E,KAAK,IAAI,OA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O,WAAW,WAAW,EAAE,OAAO,IAAI,MAAM;GACxD,CAAC;GACD,OAAO,cAAc,YAAY,QAAQ,OAAgB,IAAI;EAC/D;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/report.ts","../src/codegen.ts","../src/watch.ts","../src/index.ts"],"sourcesContent":["import type { ResolvedConfig } from '@verbaly/compiler';\nimport { relative } from 'node:path';\nimport type { Compiler, Registry } from './codegen';\n\n// a dev server re-runs per keystroke: keyed on what it is about, never on the text being typed\nconst said = new Set<string>();\n\nfunction once(id: string, line: string): void {\n if (said.has(id)) return;\n said.add(id);\n console.warn(`[verbaly] ${line}`);\n}\n\n// the code texts of the last run tell an edit in the code from an edit in the catalog\nexport type CodeTexts = Map<string, string>;\n\nexport function reportDev(\n compiler: Compiler,\n cfg: ResolvedConfig,\n registry: Registry,\n replaced: string[],\n previous: CodeTexts | undefined,\n outdated: { locale: string; key: string }[],\n): CodeTexts {\n const messages = registry.messages();\n const rel = (file: string): string => relative(cfg.root, file).replaceAll('\\\\', '/');\n for (const key of replaced) {\n const msg = messages.get(key);\n // the code changed this text since the last run, which is how a text it owns is edited\n if (!msg || (previous && previous.get(key) !== msg.message)) continue;\n once(\n `replaced:${key}`,\n previous\n ? `${cfg.sourceLocale}.json: your edit of \"${key}\" was replaced, its text lives in ${rel(msg.file)}: change it there`\n : `${cfg.sourceLocale}.json: \"${key}\" took the text written in ${rel(msg.file)}, the code owns it`,\n );\n }\n for (const entry of compiler.collisionEntries(registry)) {\n once(`collision:${entry.key}`, compiler.formatCollision(entry, cfg.root).trim());\n }\n for (const { name, file } of registry.missed()) {\n once(\n `missed:${file}:${name}`,\n `${rel(file)}: ${name}\\`…\\` is never extracted, so it stays in the source language: name it t`,\n );\n }\n for (const { locale, key } of outdated) {\n once(\n `outdated:${locale}:${key}`,\n `${locale}: \"${key}\" was translated from an older source text, update it or approve it`,\n );\n }\n return new Map([...messages].map(([key, msg]) => [key, msg.message]));\n}\n\n// test hook: the set is module state, and each test starts from a server that said nothing\nexport function resetReported(): void {\n said.clear();\n}\n","import type { Catalogs, ResolvedConfig } from '@verbaly/compiler';\nimport { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { reportDev, type CodeTexts } from './report';\n\nexport type Compiler = typeof import('@verbaly/compiler');\nexport type Registry = Awaited<ReturnType<Compiler['extractProject']>>;\n\nexport interface RequestOptions {\n cookie?: string | false;\n fallback?: string;\n}\n\nexport const GENERATED_DIR = '.verbaly';\n\nexport function generatedDir(root: string): string {\n return join(root, GENERATED_DIR);\n}\n\n// content compare: identical rewrites must not retrigger the bundler\nfunction writeIfChanged(file: string, content: string): boolean {\n try {\n if (readFileSync(file, 'utf8') === content) return false;\n } catch {\n // new file\n }\n writeFileSync(file, content);\n return true;\n}\n\nlet stateWarned = false;\n\n// dev pipeline shared by withVerbaly and the watcher: catalogs, dts, runtime modules, state\nexport function syncAndWrite(\n compiler: Compiler,\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n registry: Registry,\n requestOptions: RequestOptions,\n previous?: CodeTexts,\n): CodeTexts {\n const { added, replaced } = compiler.syncCatalogs(cfg, catalogs, registry);\n for (const locale of Object.keys(added)) {\n compiler.writeCatalog(cfg, locale, catalogs[locale] ?? {});\n }\n compiler.writeDts(cfg, catalogs[cfg.sourceLocale] ?? {});\n writeGeneratedModules(compiler, cfg, catalogs, requestOptions);\n let outdated: { locale: string; key: string }[] = [];\n try {\n // a pruned key takes its draft along, and an edited source text marks its translations\n const state = compiler.updateState(cfg, catalogs);\n outdated = compiler.outdatedTranslations(cfg, catalogs, state.fingerprints);\n } catch (error) {\n // a broken sidecar must not stop next dev: say it once and keep serving\n if (!stateWarned) console.warn(`${compiler.formatCliError(error)}, so drafts are not tracked`);\n stateWarned = true;\n }\n return reportDev(compiler, cfg, registry, replaced, previous, outdated);\n}\n\n// real-file replacement for virtual:verbaly: Turbopack has no virtual modules\nexport function writeGeneratedModules(\n compiler: Compiler,\n cfg: ResolvedConfig,\n catalogs: Catalogs,\n requestOptions: RequestOptions = {},\n): boolean {\n const dir = generatedDir(cfg.root);\n const localeDir = join(dir, 'locale');\n mkdirSync(localeDir, { recursive: true });\n\n let changed = writeIfChanged(join(dir, '.gitignore'), '*\\n');\n\n // these files are the client module here, so bundle.exclude has to be applied on this path too\n const client = compiler.clientCatalogs(cfg, catalogs);\n const runtime = compiler.generateRuntimeModule(cfg, {\n localeImport: (locale) => `./locale/${locale}.js`,\n extraExports: `export const requestOptions = ${JSON.stringify(requestOptions)};\\n`,\n icu: cfg.icu ?? compiler.needsIcu(client),\n relative: cfg.relative ?? compiler.needsRelative(client),\n inlineCatalog: cfg.render.inlineCatalog === true,\n });\n changed = writeIfChanged(join(dir, 'index.js'), runtime) || changed;\n\n const expected = new Set(cfg.locales.map((locale) => `${locale}.js`));\n for (const locale of cfg.locales) {\n changed =\n writeIfChanged(\n join(localeDir, `${locale}.js`),\n compiler.generateLocaleModule(client[locale] ?? {}),\n ) || changed;\n }\n for (const file of readdirSync(localeDir)) {\n if (!expected.has(file)) {\n rmSync(join(localeDir, file));\n changed = true;\n }\n }\n return changed;\n}\n","import type { ResolvedConfig } from '@verbaly/compiler';\nimport { basename, relative } from 'node:path';\nimport { GENERATED_DIR, syncAndWrite, type Compiler, type RequestOptions } from './codegen';\nimport type { CodeTexts } from './report';\n\n// one watcher per project root: next.config can be evaluated more than once\nconst active = new Map<string, () => void>();\n\nexport function startWatcher(\n compiler: Compiler,\n cfg: ResolvedConfig,\n requestOptions: RequestOptions,\n startTexts?: CodeTexts,\n): () => void {\n const existing = active.get(cfg.root);\n if (existing) return existing;\n\n const catalogDir = relative(cfg.root, cfg.dir).replaceAll('\\\\', '/');\n let timer: ReturnType<typeof setTimeout> | undefined;\n let running = false;\n let queued = false;\n let texts = startTexts;\n\n async function refresh(): Promise<void> {\n if (running) {\n queued = true;\n return;\n }\n running = true;\n try {\n const catalogs = compiler.loadCatalogs(cfg);\n const registry = await compiler.extractProject(cfg);\n texts = syncAndWrite(compiler, cfg, catalogs, registry, requestOptions, texts);\n } catch (error) {\n console.warn('[verbaly] live extraction failed:', error);\n } finally {\n running = false;\n if (queued) {\n queued = false;\n schedule();\n }\n }\n }\n\n function schedule(): void {\n clearTimeout(timer);\n timer = setTimeout(() => void refresh(), 150);\n }\n\n const keep = catalogDir.split('/')[0];\n const close = compiler.watchTree(cfg.root, { keep, persistent: false }, (filename) => {\n if (!filename) return;\n const file = filename.replaceAll('\\\\', '/');\n if (\n file.startsWith(`${GENERATED_DIR}/`) ||\n file.startsWith('.next/') ||\n file.includes('node_modules/') ||\n file.endsWith('.d.ts')\n ) {\n return;\n }\n // a dotfile there is the state sidecar this pipeline writes: it changes no message\n const isCatalog =\n file.startsWith(`${catalogDir}/`) && file.endsWith('.json') && !basename(file).startsWith('.');\n if (isCatalog || compiler.SOURCE_FILE_RE.test(file)) schedule();\n });\n\n const dispose = (): void => {\n clearTimeout(timer);\n close();\n active.delete(cfg.root);\n };\n active.set(cfg.root, dispose);\n return dispose;\n}\n\n// test hook\nexport function stopWatcher(root: string): void {\n active.get(root)?.();\n}\n","import type { PluginOptions } from '@verbaly/compiler';\nimport { existsSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport {\n GENERATED_DIR,\n generatedDir,\n syncAndWrite,\n writeGeneratedModules,\n type Compiler,\n type RequestOptions,\n} from './codegen';\nimport type { LoaderOptions } from './loader';\nimport { startWatcher } from './watch';\n\nexport type { VerbalyConfig } from '@verbaly/compiler';\nexport type { RequestOptions } from './codegen';\n\nexport interface NextVerbalyOptions extends PluginOptions {\n cookie?: string | false;\n fallback?: string;\n}\n\n// structural NextConfig subset (compat asserted in tests): no index signatures, Next has none\nexport interface WebpackConfigLike {\n resolve?: { alias?: Record<string, unknown>; [key: string]: unknown };\n module?: { rules?: unknown[]; [key: string]: unknown };\n plugins?: unknown[];\n [key: string]: unknown;\n}\n\ninterface WebpackContextLike {\n webpack?: {\n NormalModuleReplacementPlugin: new (test: RegExp, resource: string) => unknown;\n };\n}\n\n// context param is `never` so Next's real webpack fn (specific context type) stays assignable\nexport type WebpackFn = (config: WebpackConfigLike, context: never) => unknown;\n\nexport interface TurbopackLike {\n resolveAlias?: Record<string, unknown>;\n rules?: Record<string, unknown>;\n}\n\n// metadata is `never` for the same reason as the webpack context: Next's own type stays assignable\nexport interface CompilerLike {\n runAfterProductionCompile?: (metadata: never) => Promise<void>;\n}\n\nexport interface NextConfigLike {\n webpack?: WebpackFn | null;\n turbopack?: TurbopackLike;\n compiler?: CompilerLike;\n}\n\n// constraint is object, not NextConfigLike: an all-optional target rejects by weak-type\nexport type NextConfigInput<C extends object> =\n C | ((phase: string, context: { defaultConfig?: unknown }) => C | Promise<C>);\n\n// next/constants values: literal to keep this module import-free of next\nconst DEV_PHASE = 'phase-development-server';\nconst BUILD_PHASE = 'phase-production-build';\n// next experimental-analyze compiles the app as well, so it needs the generated modules on disk\nconst ANALYZE_PHASE = 'phase-analyze';\n\nconst LOADER = '@verbaly/next/loader';\n// matched via condition.path: a bare extension glob also hits Next's App Router entry\nconst SOURCE_PATH_RE = /\\.[cm]?[jt]sx?$/;\n\nexport function withVerbaly<C extends object>(\n nextConfig?: NextConfigInput<C>,\n options: NextVerbalyOptions = {},\n): (phase: string, context?: { defaultConfig?: unknown }) => Promise<C> {\n const { failOnMissing, cookie, fallback, ...verbalyConfig } = options;\n const requestOptions: RequestOptions = { cookie, fallback };\n\n return async (phase, context = {}) => {\n const base: C =\n typeof nextConfig === 'function'\n ? await nextConfig(phase, context)\n : (nextConfig ?? ({} as C));\n const root = verbalyConfig.root ?? process.cwd();\n\n // production server / export: everything is bundled, so no FS work, config only\n if (phase !== DEV_PHASE && phase !== BUILD_PHASE && phase !== ANALYZE_PHASE) {\n return composeConfig(base, root);\n }\n\n // dynamic: the compiler is ESM-only and this entry is also consumed as CJS\n const compiler: Compiler = await import('@verbaly/compiler');\n\n const cfg = await compiler.loadConfig(root, verbalyConfig);\n const catalogs = compiler.loadCatalogs(cfg);\n const registry = await compiler.extractProject(cfg);\n let gate: (() => void) | undefined;\n\n if (phase === DEV_PHASE) {\n const texts = syncAndWrite(compiler, cfg, catalogs, registry, requestOptions);\n startWatcher(compiler, cfg, requestOptions, texts);\n } else {\n // the code's text ships, as it does in dev: a catalog edit of a text it owns never wins\n compiler.syncCatalogs(cfg, catalogs, registry);\n writeGeneratedModules(compiler, cfg, catalogs, requestOptions);\n if (phase === BUILD_PHASE) {\n const runGate = (): void => compiler.runBuildGate(cfg, registry, failOnMissing);\n // typegen loads this config in the build phase too, and only a real build runs the hook\n if (hasAfterCompileHook(cfg.root)) gate = runGate;\n else runGate();\n }\n }\n\n // the loader rewrites exactly what extract reads: a file outside include keeps its t`…`\n const scope: LoaderOptions = { root: cfg.root, include: cfg.include, exclude: cfg.exclude };\n return composeConfig(base, cfg.root, scope, gate);\n };\n}\n\n// next build calls compiler.runAfterProductionCompile since 15.4; NODE_PATH may name another next\nfunction hasAfterCompileHook(root: string): boolean {\n for (let dir = root; ; dir = dirname(dir)) {\n const next = join(dir, 'node_modules', 'next');\n if (existsSync(join(next, 'package.json'))) {\n return existsSync(join(next, 'dist', 'build', 'after-production-compile.js'));\n }\n if (dirname(dir) === dir) return false;\n }\n}\n\nfunction composeConfig<C extends object>(\n base: C,\n root: string,\n scope?: LoaderOptions,\n gate?: () => void,\n): C {\n const runtimeModule = join(generatedDir(root), 'index.js');\n const { webpack: userWebpack, turbopack, compiler: userCompiler } = base as NextConfigLike;\n const loader = scope ? { loader: LOADER, options: scope } : LOADER;\n\n const rules: Record<string, unknown> = { ...turbopack?.rules };\n const verbalyRule = {\n condition: { all: [{ not: 'foreign' }, { path: SOURCE_PATH_RE }] },\n loaders: [loader],\n };\n const existing = rules['*'];\n rules['*'] = existing\n ? [...(Array.isArray(existing) ? existing : [existing]), verbalyRule]\n : verbalyRule;\n\n return {\n ...base,\n ...(gate && {\n compiler: {\n ...userCompiler,\n // after the compile, so next typegen, which loads this config too, never meets the gate\n async runAfterProductionCompile(metadata: never) {\n await userCompiler?.runAfterProductionCompile?.(metadata);\n gate();\n },\n },\n }),\n turbopack: {\n ...turbopack,\n resolveAlias: {\n ...turbopack?.resolveAlias,\n 'virtual:verbaly': `./${GENERATED_DIR}/index.js`,\n },\n rules,\n },\n webpack(config: WebpackConfigLike, context: unknown) {\n // webpack 5 parses 'virtual:' as a URI scheme, so resolve.alias never fires\n const { webpack: webpackInstance } = (context ?? {}) as WebpackContextLike;\n if (webpackInstance?.NormalModuleReplacementPlugin) {\n config.plugins ??= [];\n config.plugins.push(\n new webpackInstance.NormalModuleReplacementPlugin(/^virtual:verbaly$/, runtimeModule),\n );\n }\n config.resolve ??= {};\n config.resolve.alias ??= {};\n (config.resolve.alias as Record<string, unknown>)['virtual:verbaly'] = runtimeModule;\n config.module ??= {};\n config.module.rules ??= [];\n config.module.rules.push({\n test: SOURCE_PATH_RE,\n exclude: /node_modules/,\n enforce: 'pre',\n use: [typeof loader === 'string' ? { loader } : loader],\n });\n return userWebpack ? userWebpack(config, context as never) : config;\n },\n } as C;\n}\n"],"mappings":";;;AAKA,MAAM,uBAAO,IAAI,IAAY;AAE7B,SAAS,KAAK,IAAY,MAAoB;CAC5C,IAAI,KAAK,IAAI,EAAE,GAAG;CAClB,KAAK,IAAI,EAAE;CACX,QAAQ,KAAK,aAAa,MAAM;AAClC;AAKA,SAAgB,UACd,UACA,KACA,UACA,UACA,UACA,UACW;CACX,MAAM,WAAW,SAAS,SAAS;CACnC,MAAM,OAAO,SAAyB,SAAS,IAAI,MAAM,IAAI,CAAC,CAAC,WAAW,MAAM,GAAG;CACnF,KAAK,MAAM,OAAO,UAAU;EAC1B,MAAM,MAAM,SAAS,IAAI,GAAG;EAE5B,IAAI,CAAC,OAAQ,YAAY,SAAS,IAAI,GAAG,MAAM,IAAI,SAAU;EAC7D,KACE,YAAY,OACZ,WACI,GAAG,IAAI,aAAa,uBAAuB,IAAI,oCAAoC,IAAI,IAAI,IAAI,E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AO,OAAO,UAAU,CAAC;GACzB,OAAO,OAAO,MAAM,KAAK;IACvB,MAAM;IACN,SAAS;IACT,SAAS;IACT,KAAK,CAAC,OAAO,WAAW,WAAW,EAAE,OAAO,IAAI,MAAM;GACxD,CAAC;GACD,OAAO,cAAc,YAAY,QAAQ,OAAgB,IAAI;EAC/D;CACF;AACF"}
|
package/dist/loader.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loader.cjs","names":[],"sources":["../src/loader.ts"],"sourcesContent":["// webpack/turbopack loader: async because @verbaly/compiler is ESM-only (dynamic import)\n// what withVerbaly passes: the scope extract reads, so the loader rewrites nothing outside it\nexport interface LoaderOptions {\n root?: string;\n include?: string[];\n exclude?: string[];\n}\n\nexport interface LoaderContext {\n resourcePath: string;\n async(): (error: unknown, code?: string, map?: unknown) => void;\n getOptions?(): LoaderOptions;\n}\n\ntype Compiler = typeof import('@verbaly/compiler');\n\nlet compiler: Promise<Compiler> | undefined;\n// one matcher per scope: the loader runs once per module and picomatch compiles the globs\nconst filters = new Map<string, (id: string) => boolean>();\n\nfunction inScope(load: Compiler, options: LoaderOptions, file: string): boolean {\n // wired by hand with no options, the loader keeps rewriting every source file it is given\n if (!options.root || !options.include) return true;\n const key = JSON.stringify(options);\n let filter = filters.get(key);\n if (!filter) {\n const scope = { root: options.root, include: options.include, exclude: options.exclude ?? [] };\n filter = load.createSourceFilter(scope as Parameters<Compiler['createSourceFilter']>[0]);\n filters.set(key, filter);\n }\n return filter(file);\n}\n\nexport default function verbalyLoader(this: LoaderContext, source: string): void {\n const callback = this.async();\n const file = this.resourcePath;\n const options = this.getOptions?.() ?? {};\n compiler ??= import('@verbaly/compiler');\n compiler\n .then((load) => {\n if (!load.isTransformTarget(file) || !inScope(load, options, file)) {\n callback(null, source);\n return;\n }\n const result = load.transformCode(source, file);\n if (result) {\n // MagicString maps carry an empty source and Turbopack panics resolving it to a directory\n result.map.sources = [file];\n callback(null, result.code, result.map);\n } else {\n callback(null, source);\n }\n })\n .catch((error: unknown) => callback(error));\n}\n"],"mappings":";
|
|
1
|
+
{"version":3,"file":"loader.cjs","names":[],"sources":["../src/loader.ts"],"sourcesContent":["// webpack/turbopack loader: async because @verbaly/compiler is ESM-only (dynamic import)\n\n// what withVerbaly passes: the scope extract reads, so the loader rewrites nothing outside it\nexport interface LoaderOptions {\n root?: string;\n include?: string[];\n exclude?: string[];\n}\n\nexport interface LoaderContext {\n resourcePath: string;\n async(): (error: unknown, code?: string, map?: unknown) => void;\n getOptions?(): LoaderOptions;\n}\n\ntype Compiler = typeof import('@verbaly/compiler');\n\nlet compiler: Promise<Compiler> | undefined;\n// one matcher per scope: the loader runs once per module and picomatch compiles the globs\nconst filters = new Map<string, (id: string) => boolean>();\n\nfunction inScope(load: Compiler, options: LoaderOptions, file: string): boolean {\n // wired by hand with no options, the loader keeps rewriting every source file it is given\n if (!options.root || !options.include) return true;\n const key = JSON.stringify(options);\n let filter = filters.get(key);\n if (!filter) {\n const scope = { root: options.root, include: options.include, exclude: options.exclude ?? [] };\n filter = load.createSourceFilter(scope as Parameters<Compiler['createSourceFilter']>[0]);\n filters.set(key, filter);\n }\n return filter(file);\n}\n\nexport default function verbalyLoader(this: LoaderContext, source: string): void {\n const callback = this.async();\n const file = this.resourcePath;\n const options = this.getOptions?.() ?? {};\n compiler ??= import('@verbaly/compiler');\n compiler\n .then((load) => {\n if (!load.isTransformTarget(file) || !inScope(load, options, file)) {\n callback(null, source);\n return;\n }\n const result = load.transformCode(source, file);\n if (result) {\n // MagicString maps carry an empty source and Turbopack panics resolving it to a directory\n result.map.sources = [file];\n callback(null, result.code, result.map);\n } else {\n callback(null, source);\n }\n })\n .catch((error: unknown) => callback(error));\n}\n"],"mappings":";AAiBA,IAAI;AAEJ,MAAM,0BAAU,IAAI,IAAqC;AAEzD,SAAS,QAAQ,MAAgB,SAAwB,MAAuB;CAE9E,IAAI,CAAC,QAAQ,QAAQ,CAAC,QAAQ,SAAS,OAAO;CAC9C,MAAM,MAAM,KAAK,UAAU,OAAO;CAClC,IAAI,SAAS,QAAQ,IAAI,GAAG;CAC5B,IAAI,CAAC,QAAQ;EACX,MAAM,QAAQ;GAAE,MAAM,QAAQ;GAAM,SAAS,QAAQ;GAAS,SAAS,QAAQ,WAAW,CAAC;EAAE;EAC7F,SAAS,KAAK,mBAAmB,KAAsD;EACvF,QAAQ,IAAI,KAAK,MAAM;CACzB;CACA,OAAO,OAAO,IAAI;AACpB;AAEA,SAAwB,cAAmC,QAAsB;CAC/E,MAAM,WAAW,KAAK,MAAM;CAC5B,MAAM,OAAO,KAAK;CAClB,MAAM,UAAU,KAAK,aAAa,KAAK,CAAC;CACxC,aAAa,OAAO;CACpB,SACG,MAAM,SAAS;EACd,IAAI,CAAC,KAAK,kBAAkB,IAAI,KAAK,CAAC,QAAQ,MAAM,SAAS,IAAI,GAAG;GAClE,SAAS,MAAM,MAAM;GACrB;EACF;EACA,MAAM,SAAS,KAAK,cAAc,QAAQ,IAAI;EAC9C,IAAI,QAAQ;GAEV,OAAO,IAAI,UAAU,CAAC,IAAI;GAC1B,SAAS,MAAM,OAAO,MAAM,OAAO,GAAG;EACxC,OACE,SAAS,MAAM,MAAM;CAEzB,CAAC,CAAC,CACD,OAAO,UAAmB,SAAS,KAAK,CAAC;AAC9C"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@verbaly/next",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.67.0",
|
|
4
4
|
"description": "Next.js integration for Verbaly: App Router/RSC with per-request locale negotiation, Turbopack and webpack support, flash-free hydration.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"i18n",
|
|
@@ -64,23 +64,23 @@
|
|
|
64
64
|
"access": "public"
|
|
65
65
|
},
|
|
66
66
|
"dependencies": {
|
|
67
|
-
"@verbaly/compiler": "^0.
|
|
67
|
+
"@verbaly/compiler": "^0.67.0"
|
|
68
68
|
},
|
|
69
69
|
"peerDependencies": {
|
|
70
|
-
"@verbaly/react": "^0.
|
|
70
|
+
"@verbaly/react": "^0.67.0",
|
|
71
71
|
"next": "^15.0.0 || ^16.0.0",
|
|
72
72
|
"react": "^18.0.0 || ^19.0.0",
|
|
73
|
-
"verbaly": "^0.
|
|
73
|
+
"verbaly": "^0.67.0"
|
|
74
74
|
},
|
|
75
75
|
"devDependencies": {
|
|
76
76
|
"@types/react": "^19.3.0",
|
|
77
77
|
"@types/react-dom": "^19.3.0",
|
|
78
|
-
"@verbaly/react": "^0.
|
|
78
|
+
"@verbaly/react": "^0.67.0",
|
|
79
79
|
"happy-dom": "^20.14.5",
|
|
80
80
|
"next": "^16.3.8",
|
|
81
81
|
"react": "^19.3.0",
|
|
82
82
|
"react-dom": "^19.3.0",
|
|
83
|
-
"verbaly": "^0.
|
|
83
|
+
"verbaly": "^0.67.0"
|
|
84
84
|
},
|
|
85
85
|
"scripts": {
|
|
86
86
|
"build": "tsdown",
|