@verbaly/next 0.76.0 → 0.78.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 CHANGED
@@ -138,14 +138,19 @@ export default {
138
138
  };
139
139
  ```
140
140
 
141
- Then hand Verbaly the segment. This is what keeps the route statically rendered, because the
142
- alternative is reading request headers:
141
+ Then hand Verbaly the segment. **On Next 16.3 and later there is nothing to write**: with the
142
+ segment in your root layout (`app/[locale]/layout.tsx`), Verbaly reads it through
143
+ `next/root-params` in every layout, page, `generateMetadata` and `'use cache'` function, so the
144
+ route prerenders and no request header is read. **On Next 15 up to 16.2, call `setRequestLocale` in
145
+ every layout and every page of the tree**: Next can render a page without running its layout, and
146
+ a page that finds no locale reads the cookie instead of the url (it warns once when that happens).
147
+ Inside a `'use cache'` function there, pass the language: `getT({ locale })`.
143
148
 
144
149
  ```tsx
145
150
  // app/[locale]/layout.tsx
146
151
  import { setRequestLocale, getVerbalyProps, getAlternates } from '@verbaly/next/server';
147
152
  import { VerbalyProvider } from '@verbaly/next/client';
148
- import { locales } from 'virtual:verbaly';
153
+ import { locales } from 'verbaly/app';
149
154
 
150
155
  export function generateStaticParams() {
151
156
  return locales.map((locale) => ({ locale }));
@@ -158,13 +163,13 @@ export async function generateMetadata({ params }: { params: Promise<{ locale: s
158
163
 
159
164
  export default async function LocaleLayout({ children, params }) {
160
165
  const { locale } = await params;
161
- setRequestLocale(locale); // before any getT() in this tree
166
+ setRequestLocale(locale); // Next 15 to 16.2: in every layout and page of the tree
162
167
  return <VerbalyProvider {...await getVerbalyProps()}>{children}</VerbalyProvider>;
163
168
  }
164
169
  ```
165
170
 
166
- Without `setRequestLocale`, Verbaly negotiates from the cookie and `Accept-Language`, and that read
167
- is what makes the route dynamic. With it, no header is read at all.
171
+ Where neither declares the language, Verbaly negotiates from the cookie and `Accept-Language`, and
172
+ that read is what makes the route dynamic. With either, no header is read at all.
168
173
 
169
174
  **Keys are typed.** `getT()` and `useT()` check every key and its params against your catalog, and `getRequestLocale()` returns one of your locales, so `ogLocale[await getRequestLocale()]` needs no cast. The types live in `.verbaly/types.d.ts`, next to the generated modules and never committed; TypeScript skips a dot folder, so Verbaly adds that file to the `include` of your `tsconfig.json`, the way Next adds `.next/types`. On a fresh clone, `next typegen && tsc --noEmit` writes them before it checks them.
170
175
 
@@ -176,13 +181,14 @@ The report rides on `compiler.runAfterProductionCompile`, and `withVerbaly` keep
176
181
 
177
182
  Second argument of `withVerbaly`: every [`verbaly.config`](https://www.npmjs.com/package/@verbaly/compiler) option, plus:
178
183
 
179
- | Option | What it does |
180
- | --------------- | ------------------------------------------------------------------------------------------------------- |
181
- | `cookie` | Cookie read/written for the user's choice (default `verbaly-locale`); `false` = `Accept-Language` only. |
182
- | `fallback` | Locale when nothing matches (defaults to the source locale). |
183
- | `failOnMissing` | `true` stops `next build` on whatever fails `verbaly check`; by default the build reports and goes on. |
184
+ | Option | What it does |
185
+ | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
186
+ | `cookie` | Cookie read/written for the user's choice (default `verbaly-locale`); `false` = `Accept-Language` only. |
187
+ | `fallback` | Locale when nothing matches (defaults to the source locale). |
188
+ | `failOnMissing` | `true` stops `next build` on whatever fails `verbaly check`; by default the build reports and goes on. |
189
+ | `liveExtraction` | `false` keeps `next dev` from writing your translation files: new texts render from memory, as in a build, and `npx verbaly extract` writes them. |
184
190
 
185
- - **Negotiation reads `headers()`/`cookies()`, which makes a route dynamic.** Call `setRequestLocale` with your `[locale]` segment and that read never happens, so the route prerenders. For a fully static site with no server at all, [`verbaly render`](https://www.npmjs.com/package/@verbaly/compiler) mirrors the output per locale.
191
+ - **Negotiation reads `headers()`/`cookies()`, which makes a route dynamic.** With your `[locale]` segment in the root layout (read by itself on Next 16.3 and later, or declared with `setRequestLocale` before that) that read never happens, so the route prerenders. For a fully static site with no server at all, [`verbaly render`](https://www.npmjs.com/package/@verbaly/compiler) mirrors the output per locale.
186
192
  - `getAlternates({ path, baseUrl? })` returns `{ canonical, languages }` for `generateMetadata`, the same hreflang set the static mirror writes. It is empty under `no-prefix` routing, where one URL answers every language.
187
193
  - Every url Verbaly builds (`getAlternates`, `localePath`, `useSwitchLocale`) follows your `trailingSlash` in `next.config`, so by default the Spanish home is `/es`, the form Next serves, and never `/es/`, which it redirects.
188
194
  - The generated `.verbaly/` directory is build output (it ships its own `.gitignore`).
package/dist/client.d.ts CHANGED
@@ -2,11 +2,9 @@ import { VerbalyProviderProps as VerbalyProviderProps$1 } from "./server.js";
2
2
  import { ReactElement, ReactNode } from "react";
3
3
  import { SwitchLocaleOptions } from "verbaly";
4
4
  import { Trans, useLocale, useT, useVerbaly } from "@verbaly/react";
5
- //#region src/client.d.ts
6
5
  export interface VerbalyProviderProps extends VerbalyProviderProps$1 {
7
6
  children?: ReactNode;
8
7
  }
9
8
  export declare function VerbalyProvider(props: VerbalyProviderProps): ReactElement;
10
9
  export declare function useSwitchLocale(): (locale: string, options?: SwitchLocaleOptions) => Promise<void>;
11
- //#endregion
12
10
  export { Trans, useLocale, useT, useVerbaly };
package/dist/client.js CHANGED
@@ -4,7 +4,7 @@ import { switchLocale } from "verbaly";
4
4
  import { createInstance, locales, requestOptions, routing, sourceLocale, trailingSlash } from "virtual:verbaly";
5
5
  import { useRouter } from "next/navigation";
6
6
  import { Trans, VerbalyProvider as VerbalyProvider$1, useLocale, useT, useVerbaly, useVerbaly as useVerbaly$1 } from "@verbaly/react";
7
- //#region src/client.ts
7
+ // src/client.ts
8
8
  function VerbalyProvider(props) {
9
9
  const [instance] = useState(() => {
10
10
  const created = createInstance({
@@ -45,5 +45,4 @@ function useSwitchLocale() {
45
45
  if (!routed) router.refresh();
46
46
  }, [instance, router]);
47
47
  }
48
- //#endregion
49
48
  export { Trans, VerbalyProvider, useLocale, useSwitchLocale, useT, useVerbaly };
package/dist/index.cjs CHANGED
@@ -1,8 +1,8 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let node_path = require("node:path");
2
3
  let node_fs = require("node:fs");
3
4
  let node_module = require("node:module");
4
- let node_path = require("node:path");
5
- //#region src/report.ts
5
+ // src/report.ts
6
6
  const reporters = /* @__PURE__ */ new Map();
7
7
  const brokenState = /* @__PURE__ */ new Set();
8
8
  function reportDev(compiler, cfg, result, previous) {
@@ -37,8 +37,81 @@ function reportDev(compiler, cfg, result, previous) {
37
37
  else brokenState.delete(cfg.root);
38
38
  return new Map([...result.registry.messages()].map(([key, msg]) => [key, msg.message]));
39
39
  }
40
- //#endregion
41
- //#region src/codegen.ts
40
+ // src/root-params.ts
41
+ const ROOT_PARAMS_SINCE = [16, 3];
42
+ const LAYOUT_FILE = /^layout\.[cm]?[jt]sx?$/;
43
+ const DYNAMIC_SEGMENT = /^\[([A-Za-z_$][\w$]*)\]$/;
44
+ const MAX_DEPTH = 4;
45
+ function resolveFromNext(root, file) {
46
+ for (let dir = root;; dir = (0, node_path.dirname)(dir)) {
47
+ if ((0, node_fs.existsSync)((0, node_path.join)(dir, "node_modules", "next", "package.json"))) {
48
+ const path = (0, node_path.join)(dir, "node_modules", file);
49
+ return (0, node_fs.existsSync)(path) ? path : void 0;
50
+ }
51
+ if ((0, node_path.dirname)(dir) === dir) break;
52
+ }
53
+ if (!process.versions.pnp) return void 0;
54
+ try {
55
+ return (0, node_module.createRequire)((0, node_path.join)(root, "package.json")).resolve(file);
56
+ } catch {
57
+ return;
58
+ }
59
+ }
60
+ const supported = /* @__PURE__ */ new Map();
61
+ function hasRootParams(root) {
62
+ let answer = supported.get(root);
63
+ if (answer === void 0) {
64
+ answer = readRootParamsSupport(root);
65
+ supported.set(root, answer);
66
+ }
67
+ return answer;
68
+ }
69
+ function readRootParamsSupport(root) {
70
+ const manifest = resolveFromNext(root, "next/package.json");
71
+ if (!manifest) return false;
72
+ try {
73
+ const [release = "", prerelease] = String(JSON.parse((0, node_fs.readFileSync)(manifest, "utf8")).version).split("-");
74
+ const [major = 0, minor = 0, patch = 0] = release.split(".").map(Number);
75
+ const [sinceMajor, sinceMinor] = ROOT_PARAMS_SINCE;
76
+ if (prerelease !== void 0 && major === sinceMajor && minor === sinceMinor && patch === 0) return false;
77
+ return major > sinceMajor || major === sinceMajor && minor >= sinceMinor;
78
+ } catch {
79
+ return false;
80
+ }
81
+ }
82
+ function findRootParam(root) {
83
+ const app = [(0, node_path.join)(root, "app"), (0, node_path.join)(root, "src", "app")].find((dir) => (0, node_fs.existsSync)(dir));
84
+ if (!app) return void 0;
85
+ const found = /* @__PURE__ */ new Set();
86
+ const walk = (dir, params, depth) => {
87
+ let entries;
88
+ try {
89
+ entries = (0, node_fs.readdirSync)(dir, { withFileTypes: true });
90
+ } catch {
91
+ return;
92
+ }
93
+ if (entries.some((entry) => entry.isFile() && LAYOUT_FILE.test(entry.name))) {
94
+ found.add(params.length === 1 ? params[0] : void 0);
95
+ return;
96
+ }
97
+ if (depth === MAX_DEPTH) return;
98
+ for (const entry of entries) {
99
+ if (!entry.isDirectory() || /^[_@.]/.test(entry.name) || entry.name === "node_modules") continue;
100
+ const segment = DYNAMIC_SEGMENT.exec(entry.name)?.[1];
101
+ walk((0, node_path.join)(dir, entry.name), segment ? [...params, segment] : params, depth + 1);
102
+ }
103
+ };
104
+ walk(app, [], 0);
105
+ const [only] = found;
106
+ return found.size === 1 ? only : void 0;
107
+ }
108
+ function generateServerModule(cfg) {
109
+ const param = cfg.routing !== "no-prefix" && hasRootParams(cfg.root) ? findRootParam(cfg.root) : void 0;
110
+ if (!param) return "// generated by @verbaly/next: no root segment to read, setRequestLocale declares it\nexport const rootLocale = undefined;\n";
111
+ return `// generated by @verbaly/next: the [${param}] segment of the root layout, through next/root-params\nimport { ${param} as segment } from 'next/root-params';\nexport const rootLocale = segment;
112
+ `;
113
+ }
114
+ // src/codegen.ts
42
115
  const GENERATED_DIR = ".verbaly";
43
116
  function generatedDir(root) {
44
117
  return (0, node_path.join)(root, GENERATED_DIR);
@@ -50,12 +123,14 @@ function writeIfChanged(file, content) {
50
123
  (0, node_fs.writeFileSync)(file, content);
51
124
  return true;
52
125
  }
53
- async function syncAndWrite(compiler, cfg, catalogs, registry, requestOptions, previous) {
126
+ async function syncAndWrite(compiler, cfg, catalogs, registry, requestOptions, previous, live = true) {
54
127
  const result = await compiler.syncProject(cfg, {
55
128
  registry,
56
129
  catalogs,
57
- write: "changed"
130
+ write: "changed",
131
+ dryRun: !live
58
132
  });
133
+ if (!live) compiler.writeDts(cfg, result.catalogs[cfg.sourceLocale] ?? {});
59
134
  writeGeneratedModules(compiler, cfg, result.catalogs, requestOptions);
60
135
  return reportDev(compiler, cfg, result, previous);
61
136
  }
@@ -73,6 +148,7 @@ function writeGeneratedModules(compiler, cfg, catalogs, requestOptions = {}) {
73
148
  inlineCatalog: cfg.render.inlineCatalog === true
74
149
  });
75
150
  changed = writeIfChanged((0, node_path.join)(dir, "index.js"), runtime) || changed;
151
+ changed = writeIfChanged((0, node_path.join)(dir, "server.js"), generateServerModule(cfg)) || changed;
76
152
  const expected = new Set(cfg.locales.map((locale) => `${locale}.js`));
77
153
  for (const locale of cfg.locales) changed = writeIfChanged((0, node_path.join)(localeDir, `${locale}.js`), compiler.generateLocaleModule(client[locale] ?? {})) || changed;
78
154
  for (const file of (0, node_fs.readdirSync)(localeDir)) if (!expected.has(file)) {
@@ -81,10 +157,9 @@ function writeGeneratedModules(compiler, cfg, catalogs, requestOptions = {}) {
81
157
  }
82
158
  return changed;
83
159
  }
84
- //#endregion
85
- //#region src/watch.ts
160
+ // src/watch.ts
86
161
  const active = /* @__PURE__ */ new Map();
87
- function startWatcher(compiler, cfg, requestOptions, startTexts) {
162
+ function startWatcher(compiler, cfg, requestOptions, startTexts, live = true) {
88
163
  const existing = active.get(cfg.root);
89
164
  if (existing) return existing;
90
165
  const catalogDir = (0, node_path.relative)(cfg.root, cfg.dir).replaceAll("\\", "/");
@@ -99,7 +174,7 @@ function startWatcher(compiler, cfg, requestOptions, startTexts) {
99
174
  }
100
175
  running = true;
101
176
  try {
102
- texts = await syncAndWrite(compiler, cfg, compiler.loadCatalogs(cfg), await compiler.extractProject(cfg), requestOptions, texts);
177
+ texts = await syncAndWrite(compiler, cfg, compiler.loadCatalogs(cfg), await compiler.extractProject(cfg), requestOptions, texts, live);
103
178
  } catch (error) {
104
179
  const reason = compiler.formatCliError(error).replace(/^\[verbaly\] /, "");
105
180
  console.warn(`[verbaly] live extraction paused: ${reason}`);
@@ -133,15 +208,16 @@ function startWatcher(compiler, cfg, requestOptions, startTexts) {
133
208
  active.set(cfg.root, dispose);
134
209
  return dispose;
135
210
  }
136
- //#endregion
137
- //#region src/index.ts
211
+ // src/index.ts
138
212
  const DEV_PHASE = "phase-development-server";
139
213
  const BUILD_PHASE = "phase-production-build";
140
214
  const ANALYZE_PHASE = "phase-analyze";
141
215
  const LOADER = "@verbaly/next/loader";
216
+ const APP_ID = "verbaly/app";
217
+ const SERVER_ID = "virtual:verbaly/server";
142
218
  const SOURCE_PATH_RE = /\.[cm]?[jt]sx?$/;
143
219
  function withVerbaly(nextConfig, options = {}) {
144
- const { failOnMissing, cookie, fallback, ...verbalyConfig } = options;
220
+ const { failOnMissing, liveExtraction, cookie, fallback, ...verbalyConfig } = options;
145
221
  const requestOptions = {
146
222
  cookie,
147
223
  fallback
@@ -161,8 +237,9 @@ function withVerbaly(nextConfig, options = {}) {
161
237
  await compiler.reportOutsideInclude(cfg);
162
238
  let gate;
163
239
  if (phase === DEV_PHASE) {
164
- const texts = await syncAndWrite(compiler, cfg, catalogs, registry, requestOptions);
165
- startWatcher(compiler, cfg, requestOptions, texts);
240
+ const live = liveExtraction !== false;
241
+ const texts = await syncAndWrite(compiler, cfg, catalogs, registry, requestOptions, void 0, live);
242
+ startWatcher(compiler, cfg, requestOptions, texts, live);
166
243
  } else {
167
244
  compiler.syncCatalogs(cfg, catalogs, registry);
168
245
  writeGeneratedModules(compiler, cfg, catalogs, requestOptions);
@@ -183,21 +260,11 @@ function withVerbaly(nextConfig, options = {}) {
183
260
  }
184
261
  const HOOK_FILE = "next/dist/build/after-production-compile.js";
185
262
  function hasAfterCompileHook(root) {
186
- for (let dir = root;; dir = (0, node_path.dirname)(dir)) {
187
- const next = (0, node_path.join)(dir, "node_modules", "next");
188
- if ((0, node_fs.existsSync)((0, node_path.join)(next, "package.json"))) return (0, node_fs.existsSync)((0, node_path.join)(dir, "node_modules", HOOK_FILE));
189
- if ((0, node_path.dirname)(dir) === dir) break;
190
- }
191
- if (!process.versions.pnp) return false;
192
- try {
193
- (0, node_module.createRequire)((0, node_path.join)(root, "package.json")).resolve(HOOK_FILE);
194
- return true;
195
- } catch {
196
- return false;
197
- }
263
+ return resolveFromNext(root, HOOK_FILE) !== void 0;
198
264
  }
199
265
  function composeConfig(base, root, scope, gate) {
200
266
  const runtimeModule = (0, node_path.join)(generatedDir(root), "index.js");
267
+ const serverModule = (0, node_path.join)(generatedDir(root), "server.js");
201
268
  const { webpack: userWebpack, turbopack, compiler: userCompiler } = base;
202
269
  const loader = scope ? {
203
270
  loader: LOADER,
@@ -228,7 +295,9 @@ function composeConfig(base, root, scope, gate) {
228
295
  ...turbopack,
229
296
  resolveAlias: {
230
297
  ...turbopack?.resolveAlias,
231
- "virtual:verbaly": `./${GENERATED_DIR}/index.js`
298
+ [APP_ID]: `./${GENERATED_DIR}/index.js`,
299
+ "virtual:verbaly": `./${GENERATED_DIR}/index.js`,
300
+ [SERVER_ID]: `./${GENERATED_DIR}/server.js`
232
301
  },
233
302
  rules
234
303
  },
@@ -236,11 +305,13 @@ function composeConfig(base, root, scope, gate) {
236
305
  const { webpack: webpackInstance } = context ?? {};
237
306
  if (webpackInstance?.NormalModuleReplacementPlugin) {
238
307
  config.plugins ??= [];
239
- config.plugins.push(new webpackInstance.NormalModuleReplacementPlugin(/^virtual:verbaly$/, runtimeModule));
308
+ config.plugins.push(new webpackInstance.NormalModuleReplacementPlugin(/^virtual:verbaly$/, runtimeModule), new webpackInstance.NormalModuleReplacementPlugin(/^virtual:verbaly[/]server$/, serverModule));
240
309
  }
241
310
  config.resolve ??= {};
242
311
  config.resolve.alias ??= {};
312
+ config.resolve.alias[`${APP_ID}$`] = runtimeModule;
243
313
  config.resolve.alias["virtual:verbaly"] = runtimeModule;
314
+ config.resolve.alias[SERVER_ID] = serverModule;
244
315
  config.module ??= {};
245
316
  config.module.rules ??= [];
246
317
  config.module.rules.push({
@@ -253,5 +324,4 @@ function composeConfig(base, root, scope, gate) {
253
324
  }
254
325
  };
255
326
  }
256
- //#endregion
257
327
  exports.withVerbaly = withVerbaly;
package/dist/index.d.cts CHANGED
@@ -1,11 +1,8 @@
1
1
  import { PluginOptions, VerbalyConfig } from "@verbaly/compiler";
2
- //#region src/codegen.d.ts
3
2
  interface RequestOptions {
4
3
  cookie?: string | false;
5
4
  fallback?: string;
6
5
  }
7
- //#endregion
8
- //#region src/index.d.ts
9
6
  export interface NextVerbalyOptions extends PluginOptions {
10
7
  cookie?: string | false;
11
8
  fallback?: string;
@@ -41,5 +38,4 @@ export type NextConfigInput<C extends object> = C | ((phase: string, context: {
41
38
  export declare function withVerbaly<C extends object>(nextConfig?: NextConfigInput<C>, options?: NextVerbalyOptions): (phase: string, context?: {
42
39
  defaultConfig?: unknown;
43
40
  }) => Promise<C>;
44
- //#endregion
45
41
  export type { RequestOptions, VerbalyConfig };
package/dist/index.d.ts CHANGED
@@ -1,11 +1,8 @@
1
1
  import { PluginOptions, VerbalyConfig } from "@verbaly/compiler";
2
- //#region src/codegen.d.ts
3
2
  interface RequestOptions {
4
3
  cookie?: string | false;
5
4
  fallback?: string;
6
5
  }
7
- //#endregion
8
- //#region src/index.d.ts
9
6
  export interface NextVerbalyOptions extends PluginOptions {
10
7
  cookie?: string | false;
11
8
  fallback?: string;
@@ -41,5 +38,4 @@ export type NextConfigInput<C extends object> = C | ((phase: string, context: {
41
38
  export declare function withVerbaly<C extends object>(nextConfig?: NextConfigInput<C>, options?: NextVerbalyOptions): (phase: string, context?: {
42
39
  defaultConfig?: unknown;
43
40
  }) => Promise<C>;
44
- //#endregion
45
41
  export type { RequestOptions, VerbalyConfig };
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { createRequire } from "node:module";
2
- import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
3
2
  import { basename, dirname, join, relative } from "node:path";
4
- //#region src/report.ts
3
+ import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
4
+ // src/report.ts
5
5
  const reporters = /* @__PURE__ */ new Map();
6
6
  const brokenState = /* @__PURE__ */ new Set();
7
7
  function reportDev(compiler, cfg, result, previous) {
@@ -36,8 +36,81 @@ function reportDev(compiler, cfg, result, previous) {
36
36
  else brokenState.delete(cfg.root);
37
37
  return new Map([...result.registry.messages()].map(([key, msg]) => [key, msg.message]));
38
38
  }
39
- //#endregion
40
- //#region src/codegen.ts
39
+ // src/root-params.ts
40
+ const ROOT_PARAMS_SINCE = [16, 3];
41
+ const LAYOUT_FILE = /^layout\.[cm]?[jt]sx?$/;
42
+ const DYNAMIC_SEGMENT = /^\[([A-Za-z_$][\w$]*)\]$/;
43
+ const MAX_DEPTH = 4;
44
+ function resolveFromNext(root, file) {
45
+ for (let dir = root;; dir = dirname(dir)) {
46
+ if (existsSync(join(dir, "node_modules", "next", "package.json"))) {
47
+ const path = join(dir, "node_modules", file);
48
+ return existsSync(path) ? path : void 0;
49
+ }
50
+ if (dirname(dir) === dir) break;
51
+ }
52
+ if (!process.versions.pnp) return void 0;
53
+ try {
54
+ return createRequire(join(root, "package.json")).resolve(file);
55
+ } catch {
56
+ return;
57
+ }
58
+ }
59
+ const supported = /* @__PURE__ */ new Map();
60
+ function hasRootParams(root) {
61
+ let answer = supported.get(root);
62
+ if (answer === void 0) {
63
+ answer = readRootParamsSupport(root);
64
+ supported.set(root, answer);
65
+ }
66
+ return answer;
67
+ }
68
+ function readRootParamsSupport(root) {
69
+ const manifest = resolveFromNext(root, "next/package.json");
70
+ if (!manifest) return false;
71
+ try {
72
+ const [release = "", prerelease] = String(JSON.parse(readFileSync(manifest, "utf8")).version).split("-");
73
+ const [major = 0, minor = 0, patch = 0] = release.split(".").map(Number);
74
+ const [sinceMajor, sinceMinor] = ROOT_PARAMS_SINCE;
75
+ if (prerelease !== void 0 && major === sinceMajor && minor === sinceMinor && patch === 0) return false;
76
+ return major > sinceMajor || major === sinceMajor && minor >= sinceMinor;
77
+ } catch {
78
+ return false;
79
+ }
80
+ }
81
+ function findRootParam(root) {
82
+ const app = [join(root, "app"), join(root, "src", "app")].find((dir) => existsSync(dir));
83
+ if (!app) return void 0;
84
+ const found = /* @__PURE__ */ new Set();
85
+ const walk = (dir, params, depth) => {
86
+ let entries;
87
+ try {
88
+ entries = readdirSync(dir, { withFileTypes: true });
89
+ } catch {
90
+ return;
91
+ }
92
+ if (entries.some((entry) => entry.isFile() && LAYOUT_FILE.test(entry.name))) {
93
+ found.add(params.length === 1 ? params[0] : void 0);
94
+ return;
95
+ }
96
+ if (depth === MAX_DEPTH) return;
97
+ for (const entry of entries) {
98
+ if (!entry.isDirectory() || /^[_@.]/.test(entry.name) || entry.name === "node_modules") continue;
99
+ const segment = DYNAMIC_SEGMENT.exec(entry.name)?.[1];
100
+ walk(join(dir, entry.name), segment ? [...params, segment] : params, depth + 1);
101
+ }
102
+ };
103
+ walk(app, [], 0);
104
+ const [only] = found;
105
+ return found.size === 1 ? only : void 0;
106
+ }
107
+ function generateServerModule(cfg) {
108
+ const param = cfg.routing !== "no-prefix" && hasRootParams(cfg.root) ? findRootParam(cfg.root) : void 0;
109
+ if (!param) return "// generated by @verbaly/next: no root segment to read, setRequestLocale declares it\nexport const rootLocale = undefined;\n";
110
+ return `// generated by @verbaly/next: the [${param}] segment of the root layout, through next/root-params\nimport { ${param} as segment } from 'next/root-params';\nexport const rootLocale = segment;
111
+ `;
112
+ }
113
+ // src/codegen.ts
41
114
  const GENERATED_DIR = ".verbaly";
42
115
  function generatedDir(root) {
43
116
  return join(root, GENERATED_DIR);
@@ -49,12 +122,14 @@ function writeIfChanged(file, content) {
49
122
  writeFileSync(file, content);
50
123
  return true;
51
124
  }
52
- async function syncAndWrite(compiler, cfg, catalogs, registry, requestOptions, previous) {
125
+ async function syncAndWrite(compiler, cfg, catalogs, registry, requestOptions, previous, live = true) {
53
126
  const result = await compiler.syncProject(cfg, {
54
127
  registry,
55
128
  catalogs,
56
- write: "changed"
129
+ write: "changed",
130
+ dryRun: !live
57
131
  });
132
+ if (!live) compiler.writeDts(cfg, result.catalogs[cfg.sourceLocale] ?? {});
58
133
  writeGeneratedModules(compiler, cfg, result.catalogs, requestOptions);
59
134
  return reportDev(compiler, cfg, result, previous);
60
135
  }
@@ -72,6 +147,7 @@ function writeGeneratedModules(compiler, cfg, catalogs, requestOptions = {}) {
72
147
  inlineCatalog: cfg.render.inlineCatalog === true
73
148
  });
74
149
  changed = writeIfChanged(join(dir, "index.js"), runtime) || changed;
150
+ changed = writeIfChanged(join(dir, "server.js"), generateServerModule(cfg)) || changed;
75
151
  const expected = new Set(cfg.locales.map((locale) => `${locale}.js`));
76
152
  for (const locale of cfg.locales) changed = writeIfChanged(join(localeDir, `${locale}.js`), compiler.generateLocaleModule(client[locale] ?? {})) || changed;
77
153
  for (const file of readdirSync(localeDir)) if (!expected.has(file)) {
@@ -80,10 +156,9 @@ function writeGeneratedModules(compiler, cfg, catalogs, requestOptions = {}) {
80
156
  }
81
157
  return changed;
82
158
  }
83
- //#endregion
84
- //#region src/watch.ts
159
+ // src/watch.ts
85
160
  const active = /* @__PURE__ */ new Map();
86
- function startWatcher(compiler, cfg, requestOptions, startTexts) {
161
+ function startWatcher(compiler, cfg, requestOptions, startTexts, live = true) {
87
162
  const existing = active.get(cfg.root);
88
163
  if (existing) return existing;
89
164
  const catalogDir = relative(cfg.root, cfg.dir).replaceAll("\\", "/");
@@ -98,7 +173,7 @@ function startWatcher(compiler, cfg, requestOptions, startTexts) {
98
173
  }
99
174
  running = true;
100
175
  try {
101
- texts = await syncAndWrite(compiler, cfg, compiler.loadCatalogs(cfg), await compiler.extractProject(cfg), requestOptions, texts);
176
+ texts = await syncAndWrite(compiler, cfg, compiler.loadCatalogs(cfg), await compiler.extractProject(cfg), requestOptions, texts, live);
102
177
  } catch (error) {
103
178
  const reason = compiler.formatCliError(error).replace(/^\[verbaly\] /, "");
104
179
  console.warn(`[verbaly] live extraction paused: ${reason}`);
@@ -132,15 +207,16 @@ function startWatcher(compiler, cfg, requestOptions, startTexts) {
132
207
  active.set(cfg.root, dispose);
133
208
  return dispose;
134
209
  }
135
- //#endregion
136
- //#region src/index.ts
210
+ // src/index.ts
137
211
  const DEV_PHASE = "phase-development-server";
138
212
  const BUILD_PHASE = "phase-production-build";
139
213
  const ANALYZE_PHASE = "phase-analyze";
140
214
  const LOADER = "@verbaly/next/loader";
215
+ const APP_ID = "verbaly/app";
216
+ const SERVER_ID = "virtual:verbaly/server";
141
217
  const SOURCE_PATH_RE = /\.[cm]?[jt]sx?$/;
142
218
  function withVerbaly(nextConfig, options = {}) {
143
- const { failOnMissing, cookie, fallback, ...verbalyConfig } = options;
219
+ const { failOnMissing, liveExtraction, cookie, fallback, ...verbalyConfig } = options;
144
220
  const requestOptions = {
145
221
  cookie,
146
222
  fallback
@@ -160,8 +236,9 @@ function withVerbaly(nextConfig, options = {}) {
160
236
  await compiler.reportOutsideInclude(cfg);
161
237
  let gate;
162
238
  if (phase === DEV_PHASE) {
163
- const texts = await syncAndWrite(compiler, cfg, catalogs, registry, requestOptions);
164
- startWatcher(compiler, cfg, requestOptions, texts);
239
+ const live = liveExtraction !== false;
240
+ const texts = await syncAndWrite(compiler, cfg, catalogs, registry, requestOptions, void 0, live);
241
+ startWatcher(compiler, cfg, requestOptions, texts, live);
165
242
  } else {
166
243
  compiler.syncCatalogs(cfg, catalogs, registry);
167
244
  writeGeneratedModules(compiler, cfg, catalogs, requestOptions);
@@ -182,21 +259,11 @@ function withVerbaly(nextConfig, options = {}) {
182
259
  }
183
260
  const HOOK_FILE = "next/dist/build/after-production-compile.js";
184
261
  function hasAfterCompileHook(root) {
185
- for (let dir = root;; dir = dirname(dir)) {
186
- const next = join(dir, "node_modules", "next");
187
- if (existsSync(join(next, "package.json"))) return existsSync(join(dir, "node_modules", HOOK_FILE));
188
- if (dirname(dir) === dir) break;
189
- }
190
- if (!process.versions.pnp) return false;
191
- try {
192
- createRequire(join(root, "package.json")).resolve(HOOK_FILE);
193
- return true;
194
- } catch {
195
- return false;
196
- }
262
+ return resolveFromNext(root, HOOK_FILE) !== void 0;
197
263
  }
198
264
  function composeConfig(base, root, scope, gate) {
199
265
  const runtimeModule = join(generatedDir(root), "index.js");
266
+ const serverModule = join(generatedDir(root), "server.js");
200
267
  const { webpack: userWebpack, turbopack, compiler: userCompiler } = base;
201
268
  const loader = scope ? {
202
269
  loader: LOADER,
@@ -227,7 +294,9 @@ function composeConfig(base, root, scope, gate) {
227
294
  ...turbopack,
228
295
  resolveAlias: {
229
296
  ...turbopack?.resolveAlias,
230
- "virtual:verbaly": `./${GENERATED_DIR}/index.js`
297
+ [APP_ID]: `./${GENERATED_DIR}/index.js`,
298
+ "virtual:verbaly": `./${GENERATED_DIR}/index.js`,
299
+ [SERVER_ID]: `./${GENERATED_DIR}/server.js`
231
300
  },
232
301
  rules
233
302
  },
@@ -235,11 +304,13 @@ function composeConfig(base, root, scope, gate) {
235
304
  const { webpack: webpackInstance } = context ?? {};
236
305
  if (webpackInstance?.NormalModuleReplacementPlugin) {
237
306
  config.plugins ??= [];
238
- config.plugins.push(new webpackInstance.NormalModuleReplacementPlugin(/^virtual:verbaly$/, runtimeModule));
307
+ config.plugins.push(new webpackInstance.NormalModuleReplacementPlugin(/^virtual:verbaly$/, runtimeModule), new webpackInstance.NormalModuleReplacementPlugin(/^virtual:verbaly[/]server$/, serverModule));
239
308
  }
240
309
  config.resolve ??= {};
241
310
  config.resolve.alias ??= {};
311
+ config.resolve.alias[`${APP_ID}$`] = runtimeModule;
242
312
  config.resolve.alias["virtual:verbaly"] = runtimeModule;
313
+ config.resolve.alias[SERVER_ID] = serverModule;
243
314
  config.module ??= {};
244
315
  config.module.rules ??= [];
245
316
  config.module.rules.push({
@@ -252,5 +323,4 @@ function composeConfig(base, root, scope, gate) {
252
323
  }
253
324
  };
254
325
  }
255
- //#endregion
256
326
  export { withVerbaly };
package/dist/loader.cjs CHANGED
@@ -1,4 +1,4 @@
1
- //#region src/loader.ts
1
+ // src/loader.ts
2
2
  let compiler;
3
3
  const filters = /* @__PURE__ */ new Map();
4
4
  function inScope(load, options, file) {
@@ -33,5 +33,4 @@ function verbalyLoader(source) {
33
33
  } else callback(null, source);
34
34
  }).catch((error) => callback(error));
35
35
  }
36
- //#endregion
37
36
  module.exports = verbalyLoader;
package/dist/server.d.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  import { TransProps } from "@verbaly/react/server";
2
2
  import * as React from "react";
3
3
  import { Locale, Translate, Verbaly } from "verbaly";
4
- //#region src/server.d.ts
5
4
  export declare function setRequestLocale(locale: string): void;
6
5
  export interface AlternatesOptions {
7
6
  path: string;
@@ -22,5 +21,4 @@ export interface VerbalyProviderProps {
22
21
  locale: string;
23
22
  messages?: Record<string, string>;
24
23
  }
25
- export declare function getVerbalyProps(): Promise<VerbalyProviderProps>;
26
- //#endregion
24
+ export declare function getVerbalyProps(): Promise<VerbalyProviderProps>;
package/dist/server.js CHANGED
@@ -3,7 +3,8 @@ import { cookies, headers } from "next/headers";
3
3
  import * as React from "react";
4
4
  import { LOCALE_STORAGE_KEY, alternateLinks, localeFromPath, resolveRequestLocale, warnOnce } from "verbaly";
5
5
  import { createRequestInstance, loadMessages, locales, requestOptions, routing, sourceLocale, trailingSlash } from "virtual:verbaly";
6
- //#region src/server.ts
6
+ import { rootLocale } from "virtual:verbaly/server";
7
+ // src/server.ts
7
8
  const perRequest = React.cache ?? ((fn) => fn);
8
9
  const scopedHolder = perRequest(() => ({}));
9
10
  const moduleHolder = {};
@@ -15,15 +16,32 @@ function setRequestLocale(locale) {
15
16
  if (routing === "no-prefix") warnOnce("setRequestLocale got a locale segment while routing is \"no-prefix\": if your urls start with the locale, set routing to 'prefix-all' or 'prefix-except-source' in your verbaly config");
16
17
  holder().locale = locale;
17
18
  }
18
- function declaredLocale() {
19
+ async function declaredLocale() {
19
20
  const raw = holder().locale;
20
- if (raw === void 0) return void 0;
21
+ if (raw !== void 0) {
22
+ const match = localeFromPath({
23
+ supported: locales,
24
+ path: `/${raw}`
25
+ });
26
+ if (match) return match;
27
+ warnOnce(`setRequestLocale was given a locale the project does not have, so it was ignored`);
28
+ return;
29
+ }
30
+ const segment = await rootSegment();
31
+ if (segment === void 0) return void 0;
21
32
  const match = localeFromPath({
22
33
  supported: locales,
23
- path: `/${raw}`
34
+ path: `/${segment}`
24
35
  });
25
36
  if (match) return match;
26
- warnOnce(`setRequestLocale was given a locale the project does not have, so it was ignored`);
37
+ warnOnce(`the locale segment of the url holds a locale the project does not have, so it was ignored`);
38
+ }
39
+ async function rootSegment() {
40
+ try {
41
+ return await rootLocale?.();
42
+ } catch {
43
+ return;
44
+ }
27
45
  }
28
46
  function namedLocale(raw) {
29
47
  const match = localeFromPath({
@@ -36,6 +54,7 @@ function namedLocale(raw) {
36
54
  }
37
55
  const instanceFor = perRequest((locale) => createRequestInstance(locale));
38
56
  async function negotiate() {
57
+ if (routing !== "no-prefix" && !rootLocale) warnOnce("getT() found no locale for this segment, so it read the cookie: under your locale segment, call setRequestLocale in this page or layout too, or pass getT({ locale }) (Next 16.3 and later read the segment by themselves)");
39
58
  const cookieName = requestOptions?.cookie ?? LOCALE_STORAGE_KEY;
40
59
  const headerStore = await headers();
41
60
  const cookieValue = cookieName === false ? void 0 : (await cookies()).get(cookieName)?.value;
@@ -48,7 +67,7 @@ async function negotiate() {
48
67
  });
49
68
  }
50
69
  const getRequestState = perRequest(async () => {
51
- const locale = declaredLocale() ?? await negotiate();
70
+ const locale = await declaredLocale() ?? await negotiate();
52
71
  return {
53
72
  locale,
54
73
  instance: await createRequestInstance(locale)
@@ -94,5 +113,4 @@ async function getVerbalyProps() {
94
113
  messages: await loadMessages(locale)
95
114
  };
96
115
  }
97
- //#endregion
98
116
  export { Trans, getAlternates, getRequestLocale, getT, getVerbaly, getVerbalyProps, setRequestLocale };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@verbaly/next",
3
- "version": "0.76.0",
3
+ "version": "0.78.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",
@@ -23,6 +23,10 @@
23
23
  "bugs": {
24
24
  "url": "https://github.com/AronSoto/verbaly/issues"
25
25
  },
26
+ "funding": {
27
+ "type": "github",
28
+ "url": "https://github.com/sponsors/AronSoto"
29
+ },
26
30
  "type": "module",
27
31
  "main": "./dist/index.cjs",
28
32
  "module": "./dist/index.js",
@@ -64,23 +68,23 @@
64
68
  "access": "public"
65
69
  },
66
70
  "dependencies": {
67
- "@verbaly/compiler": "^0.76.0"
71
+ "@verbaly/compiler": "^0.78.0"
68
72
  },
69
73
  "peerDependencies": {
70
- "@verbaly/react": "^0.76.0",
74
+ "@verbaly/react": "^0.78.0",
71
75
  "next": "^15.0.0 || ^16.0.0",
72
76
  "react": "^18.0.0 || ^19.0.0",
73
- "verbaly": "^0.76.0"
77
+ "verbaly": "^0.78.0"
74
78
  },
75
79
  "devDependencies": {
76
80
  "@types/react": "^19.3.0",
77
81
  "@types/react-dom": "^19.3.0",
78
- "@verbaly/react": "^0.76.0",
82
+ "@verbaly/react": "^0.78.0",
79
83
  "happy-dom": "^21.0.4",
80
- "next": "^16.4.2",
84
+ "next": "^16.4.3",
81
85
  "react": "^19.3.1",
82
86
  "react-dom": "^19.3.1",
83
- "verbaly": "^0.76.0"
87
+ "verbaly": "^0.78.0"
84
88
  },
85
89
  "scripts": {
86
90
  "build": "tsdown",