@verbaly/next 0.63.0 → 0.65.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
@@ -82,7 +82,8 @@ export function Counter() {
82
82
  }
83
83
  ```
84
84
 
85
- **4. Switching languages**: persists the cookie the server reads and re-renders Server Components:
85
+ **4. Switching languages**: persists the cookie the server reads and re-renders Server Components,
86
+ or, when your `routing` puts the language in the URL, moves to the same page in the new language:
86
87
 
87
88
  ```tsx
88
89
  'use client';
@@ -94,12 +95,25 @@ export function LocalePicker() {
94
95
  }
95
96
  ```
96
97
 
97
- **5. If your URLs carry the language** (`app/[locale]/…`), hand Verbaly the segment. This is what
98
- keeps the route statically rendered, because the alternative is reading request headers:
98
+ **5. If your URLs carry the language** (`app/[locale]/…`), say so in the config first. That line
99
+ is what gives `getAlternates` the other languages and sends `useSwitchLocale` to the new URL;
100
+ leave it out and `setRequestLocale` warns once, because the segment and the config disagree:
101
+
102
+ ```ts
103
+ // verbaly.config.ts
104
+ export default {
105
+ locales: ['en', 'es', 'pt'],
106
+ routing: 'prefix-all', // every language has its segment: /en/…, /es/…, /pt/…
107
+ };
108
+ ```
109
+
110
+ Then hand Verbaly the segment. This is what keeps the route statically rendered, because the
111
+ alternative is reading request headers:
99
112
 
100
113
  ```tsx
101
114
  // app/[locale]/layout.tsx
102
115
  import { setRequestLocale, getVerbalyProps, getAlternates } from '@verbaly/next/server';
116
+ import { VerbalyProvider } from '@verbaly/next/client';
103
117
  import { locales } from 'virtual:verbaly';
104
118
 
105
119
  export function generateStaticParams() {
package/dist/client.js CHANGED
@@ -1,7 +1,7 @@
1
1
  "use client";
2
2
  import { createElement, useCallback, useEffect, useState } from "react";
3
3
  import { switchLocale } from "verbaly";
4
- import { createInstance, requestOptions } from "virtual:verbaly";
4
+ import { createInstance, locales, requestOptions, routing, sourceLocale } 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
7
  //#region src/client.ts
@@ -28,12 +28,16 @@ function useSwitchLocale() {
28
28
  const instance = useVerbaly$1();
29
29
  const router = useRouter();
30
30
  return useCallback(async (locale, options) => {
31
- const routed = options?.routing !== void 0 && options.routing !== "no-prefix";
32
- await switchLocale(instance, locale, {
31
+ const settings = {
33
32
  cookie: requestOptions?.cookie,
33
+ routing,
34
+ supported: locales,
35
+ sourceLocale,
34
36
  navigate: (path) => router.push(path),
35
37
  ...options
36
- });
38
+ };
39
+ const routed = settings.routing !== void 0 && settings.routing !== "no-prefix";
40
+ await switchLocale(instance, locale, settings);
37
41
  if (!routed) router.refresh();
38
42
  }, [instance, router]);
39
43
  }
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","names":["ReactVerbalyProvider","useVerbaly"],"sources":["../src/client.ts"],"sourcesContent":["'use client';\n\nimport { useRouter } from 'next/navigation';\nimport {\n createElement,\n useCallback,\n useEffect,\n useState,\n type ReactElement,\n type ReactNode,\n} from 'react';\nimport { VerbalyProvider as ReactVerbalyProvider, useVerbaly } from '@verbaly/react';\nimport { switchLocale, type SwitchLocaleOptions } from 'verbaly';\nimport { createInstance, requestOptions } from 'virtual:verbaly';\nimport type { VerbalyProviderProps as SerializableProps } from './server';\n\nexport { Trans, useLocale, useT, useVerbaly } from '@verbaly/react';\n\n// the serializable props getVerbalyProps() produces, plus the client-side children\nexport interface VerbalyProviderProps extends SerializableProps {\n children?: ReactNode;\n}\n\nexport function VerbalyProvider(props: VerbalyProviderProps): ReactElement {\n // getVerbalyProps omits them for the source locale, so messages here were passed on purpose\n const [instance] = useState(() => {\n const created = createInstance({ locale: props.locale });\n if (props.messages) created.addMessages(props.locale, props.messages);\n return created;\n });\n\n // server changed the locale out-of-band (cookie edit + refresh): follow it\n useEffect(() => {\n if (props.locale === instance.locale) return;\n if (props.messages) {\n instance.addMessages(props.locale, props.messages);\n instance.setLocale(props.locale);\n } else {\n void instance.loadLocale(props.locale).then(() => instance.setLocale(props.locale));\n }\n }, [props.locale, props.messages, instance]);\n\n return createElement(ReactVerbalyProvider, { instance }, props.children);\n}\n\n// core switchLocale in whichever mode the app is in, with the app router as the navigation\nexport function useSwitchLocale(): (\n locale: string,\n options?: SwitchLocaleOptions,\n) => Promise<void> {\n const instance = useVerbaly();\n const router = useRouter();\n return useCallback(\n async (locale, options) => {\n const routed = options?.routing !== undefined && options.routing !== 'no-prefix';\n await switchLocale(instance, locale, {\n cookie: requestOptions?.cookie,\n // a full load would throw away the react tree the app router exists to keep\n navigate: (path) => router.push(path),\n ...options,\n });\n // the navigation already re-rendered the tree, so refreshing on top of it is a second render\n if (!routed) router.refresh();\n },\n [instance, router],\n );\n}\n"],"mappings":";;;;;;;AAuBA,SAAgB,gBAAgB,OAA2C;CAEzE,MAAM,CAAC,YAAY,eAAe;EAChC,MAAM,UAAU,eAAe,EAAE,QAAQ,MAAM,OAAO,CAAC;EACvD,IAAI,MAAM,UAAU,QAAQ,YAAY,MAAM,QAAQ,MAAM,QAAQ;EACpE,OAAO;CACT,CAAC;CAGD,gBAAgB;EACd,IAAI,MAAM,WAAW,SAAS,QAAQ;EACtC,IAAI,MAAM,UAAU;GAClB,SAAS,YAAY,MAAM,QAAQ,MAAM,QAAQ;GACjD,SAAS,UAAU,MAAM,MAAM;EACjC,OACE,SAAc,WAAW,MAAM,MAAM,CAAC,CAAC,WAAW,SAAS,UAAU,MAAM,MAAM,CAAC;CAEtF,GAAG;EAAC,MAAM;EAAQ,MAAM;EAAU;CAAQ,CAAC;CAE3C,OAAO,cAAcA,mBAAsB,EAAE,SAAS,GAAG,MAAM,QAAQ;AACzE;AAGA,SAAgB,kBAGG;CACjB,MAAM,WAAWC,aAAW;CAC5B,MAAM,SAAS,UAAU;CACzB,OAAO,YACL,OAAO,QAAQ,YAAY;EACzB,MAAM,SAAS,SAAS,YAAY,KAAA,KAAa,QAAQ,YAAY;EACrE,MAAM,aAAa,UAAU,QAAQ;GACnC,QAAQ,gBAAgB;GAExB,WAAW,SAAS,OAAO,KAAK,IAAI;GACpC,GAAG;EACL,CAAC;EAED,IAAI,CAAC,QAAQ,OAAO,QAAQ;CAC9B,GACA,CAAC,UAAU,MAAM,CACnB;AACF"}
1
+ {"version":3,"file":"client.js","names":["ReactVerbalyProvider","useVerbaly"],"sources":["../src/client.ts"],"sourcesContent":["'use client';\n\nimport { useRouter } from 'next/navigation';\nimport {\n createElement,\n useCallback,\n useEffect,\n useState,\n type ReactElement,\n type ReactNode,\n} from 'react';\nimport { VerbalyProvider as ReactVerbalyProvider, useVerbaly } from '@verbaly/react';\nimport { switchLocale, type SwitchLocaleOptions } from 'verbaly';\nimport { createInstance, locales, requestOptions, routing, sourceLocale } from 'virtual:verbaly';\nimport type { VerbalyProviderProps as SerializableProps } from './server';\n\nexport { Trans, useLocale, useT, useVerbaly } from '@verbaly/react';\n\n// the serializable props getVerbalyProps() produces, plus the client-side children\nexport interface VerbalyProviderProps extends SerializableProps {\n children?: ReactNode;\n}\n\nexport function VerbalyProvider(props: VerbalyProviderProps): ReactElement {\n // getVerbalyProps omits them for the source locale, so messages here were passed on purpose\n const [instance] = useState(() => {\n const created = createInstance({ locale: props.locale });\n if (props.messages) created.addMessages(props.locale, props.messages);\n return created;\n });\n\n // server changed the locale out-of-band (cookie edit + refresh): follow it\n useEffect(() => {\n if (props.locale === instance.locale) return;\n if (props.messages) {\n instance.addMessages(props.locale, props.messages);\n instance.setLocale(props.locale);\n } else {\n void instance.loadLocale(props.locale).then(() => instance.setLocale(props.locale));\n }\n }, [props.locale, props.messages, instance]);\n\n return createElement(ReactVerbalyProvider, { instance }, props.children);\n}\n\n// core switchLocale in the project's own routing, with the app router as the navigation\nexport function useSwitchLocale(): (\n locale: string,\n options?: SwitchLocaleOptions,\n) => Promise<void> {\n const instance = useVerbaly();\n const router = useRouter();\n return useCallback(\n async (locale, options) => {\n // the project's routing unless told otherwise: under a [locale] segment the url must change\n const settings: SwitchLocaleOptions = {\n cookie: requestOptions?.cookie,\n routing,\n supported: locales,\n sourceLocale,\n // a full load would throw away the react tree the app router exists to keep\n navigate: (path) => router.push(path),\n ...options,\n };\n const routed = settings.routing !== undefined && settings.routing !== 'no-prefix';\n await switchLocale(instance, locale, settings);\n // the navigation already re-rendered the tree, so refreshing on top of it is a second render\n if (!routed) router.refresh();\n },\n [instance, router],\n );\n}\n"],"mappings":";;;;;;;AAuBA,SAAgB,gBAAgB,OAA2C;CAEzE,MAAM,CAAC,YAAY,eAAe;EAChC,MAAM,UAAU,eAAe,EAAE,QAAQ,MAAM,OAAO,CAAC;EACvD,IAAI,MAAM,UAAU,QAAQ,YAAY,MAAM,QAAQ,MAAM,QAAQ;EACpE,OAAO;CACT,CAAC;CAGD,gBAAgB;EACd,IAAI,MAAM,WAAW,SAAS,QAAQ;EACtC,IAAI,MAAM,UAAU;GAClB,SAAS,YAAY,MAAM,QAAQ,MAAM,QAAQ;GACjD,SAAS,UAAU,MAAM,MAAM;EACjC,OACE,SAAc,WAAW,MAAM,MAAM,CAAC,CAAC,WAAW,SAAS,UAAU,MAAM,MAAM,CAAC;CAEtF,GAAG;EAAC,MAAM;EAAQ,MAAM;EAAU;CAAQ,CAAC;CAE3C,OAAO,cAAcA,mBAAsB,EAAE,SAAS,GAAG,MAAM,QAAQ;AACzE;AAGA,SAAgB,kBAGG;CACjB,MAAM,WAAWC,aAAW;CAC5B,MAAM,SAAS,UAAU;CACzB,OAAO,YACL,OAAO,QAAQ,YAAY;EAEzB,MAAM,WAAgC;GACpC,QAAQ,gBAAgB;GACxB;GACA,WAAW;GACX;GAEA,WAAW,SAAS,OAAO,KAAK,IAAI;GACpC,GAAG;EACL;EACA,MAAM,SAAS,SAAS,YAAY,KAAA,KAAa,SAAS,YAAY;EACtE,MAAM,aAAa,UAAU,QAAQ,QAAQ;EAE7C,IAAI,CAAC,QAAQ,OAAO,QAAQ;CAC9B,GACA,CAAC,UAAU,MAAM,CACnB;AACF"}
package/dist/index.cjs CHANGED
@@ -73,16 +73,19 @@ function startWatcher(compiler, cfg, requestOptions) {
73
73
  clearTimeout(timer);
74
74
  timer = setTimeout(() => void refresh(), 150);
75
75
  }
76
- const watcher = (0, node_fs.watch)(cfg.root, { recursive: true }, (_event, filename) => {
76
+ const keep = catalogDir.split("/")[0];
77
+ const close = compiler.watchTree(cfg.root, {
78
+ keep,
79
+ persistent: false
80
+ }, (filename) => {
77
81
  if (!filename) return;
78
82
  const file = filename.replaceAll("\\", "/");
79
83
  if (file.startsWith(`.verbaly/`) || file.startsWith(".next/") || file.includes("node_modules/") || file.endsWith(".d.ts")) return;
80
84
  if (file.startsWith(`${catalogDir}/`) && file.endsWith(".json") || compiler.SOURCE_FILE_RE.test(file)) schedule();
81
85
  });
82
- watcher.unref?.();
83
86
  const dispose = () => {
84
87
  clearTimeout(timer);
85
- watcher.close();
88
+ close();
86
89
  active.delete(cfg.root);
87
90
  };
88
91
  active.set(cfg.root, dispose);
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["join","readFileSync","readdirSync","relative","watch","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 { watch } from 'node:fs';\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 watcher = watch(cfg.root, { recursive: true }, (_event, 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 watcher.unref?.();\n\n const dispose = (): void => {\n clearTimeout(timer);\n watcher.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 { 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 return composeConfig(base, cfg.root);\n };\n}\n\nfunction composeConfig<C extends object>(base: C, root: string): C {\n const runtimeModule = join(generatedDir(root), 'index.js');\n const { webpack: userWebpack, turbopack } = base as NextConfigLike;\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: [{ 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,SAA0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AAgBC,UAAAA,KAAAA,CAAK,aAAa,IAAI,GAAG,UAAU;CACzD,MAAM,EAAE,SAAS,aAAa,cAAc;CAE5C,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,EAAE,QAAQ,OAAO,CAAC;GAC1B,CAAC;GACD,OAAO,cAAc,YAAY,QAAQ,OAAgB,IAAI;EAC/D;CACF;AACF"}
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 { 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 return composeConfig(base, cfg.root);\n };\n}\n\nfunction composeConfig<C extends object>(base: C, root: string): C {\n const runtimeModule = join(generatedDir(root), 'index.js');\n const { webpack: userWebpack, turbopack } = base as NextConfigLike;\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: [{ 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,MAAM,SAAS,OAAO;CACrD,QAAQ,CAER;CACA,CAAA,GAAA,QAAA,cAAA,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,aAAA,GAAYD,UAAAA,KAAAA,CAAK,KAAK,QAAQ;CACpC,CAAA,GAAA,QAAA,UAAA,CAAU,WAAW,EAAE,WAAW,KAAK,CAAC;CAExC,IAAI,UAAU,gBAAA,GAAeA,UAAAA,KAAAA,CAAK,KAAK,YAAY,GAAG,KAAK;CAG3D,MAAM,SAAS,SAAS,eAAe,KAAK,QAAQ;CACpD,MAAM,UAAU,SAAS,sBA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O,OAAO,UAAU,CAAC;GACzB,OAAO,OAAO,MAAM,KAAK;IACvB,MAAM;IACN,SAAS;IACT,SAAS;IACT,KAAK,CAAC,EAAE,QAAQ,OAAO,CAAC;GAC1B,CAAC;GACD,OAAO,cAAc,YAAY,QAAQ,OAAgB,IAAI;EAC/D;CACF;AACF"}
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { join, relative } from "node:path";
2
- import { mkdirSync, readFileSync, readdirSync, rmSync, watch, writeFileSync } from "node:fs";
2
+ import { mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
3
3
  //#region src/codegen.ts
4
4
  const GENERATED_DIR = ".verbaly";
5
5
  function generatedDir(root) {
@@ -72,16 +72,19 @@ function startWatcher(compiler, cfg, requestOptions) {
72
72
  clearTimeout(timer);
73
73
  timer = setTimeout(() => void refresh(), 150);
74
74
  }
75
- const watcher = watch(cfg.root, { recursive: true }, (_event, filename) => {
75
+ const keep = catalogDir.split("/")[0];
76
+ const close = compiler.watchTree(cfg.root, {
77
+ keep,
78
+ persistent: false
79
+ }, (filename) => {
76
80
  if (!filename) return;
77
81
  const file = filename.replaceAll("\\", "/");
78
82
  if (file.startsWith(`.verbaly/`) || file.startsWith(".next/") || file.includes("node_modules/") || file.endsWith(".d.ts")) return;
79
83
  if (file.startsWith(`${catalogDir}/`) && file.endsWith(".json") || compiler.SOURCE_FILE_RE.test(file)) schedule();
80
84
  });
81
- watcher.unref?.();
82
85
  const dispose = () => {
83
86
  clearTimeout(timer);
84
- watcher.close();
87
+ close();
85
88
  active.delete(cfg.root);
86
89
  };
87
90
  active.set(cfg.root, dispose);
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 { watch } from 'node:fs';\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 watcher = watch(cfg.root, { recursive: true }, (_event, 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 watcher.unref?.();\n\n const dispose = (): void => {\n clearTimeout(timer);\n watcher.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 { 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 return composeConfig(base, cfg.root);\n };\n}\n\nfunction composeConfig<C extends object>(base: C, root: string): C {\n const runtimeModule = join(generatedDir(root), 'index.js');\n const { webpack: userWebpack, turbopack } = base as NextConfigLike;\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: [{ 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,OAAO,SAAS,SAAS,MAAM;EAC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,cAAc;EAC5C;EAEA,OAAO,cAAc,MAAM,IAAI,IAAI;CACrC;AACF;AAEA,SAAS,cAAgC,MAAS,MAAiB;CACjE,MAAM,gBAAgB,KAAK,aAAa,IAAI,GAAG,UAAU;CACzD,MAAM,EAAE,SAAS,aAAa,cAAc;CAE5C,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,EAAE,QAAQ,OAAO,CAAC;GAC1B,CAAC;GACD,OAAO,cAAc,YAAY,QAAQ,OAAgB,IAAI;EAC/D;CACF;AACF"}
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 { 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 return composeConfig(base, cfg.root);\n };\n}\n\nfunction composeConfig<C extends object>(base: C, root: string): C {\n const runtimeModule = join(generatedDir(root), 'index.js');\n const { webpack: userWebpack, turbopack } = base as NextConfigLike;\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: [{ 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,U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,6 +11,7 @@ function holder() {
11
11
  return scoped === scopedHolder() ? scoped : moduleHolder;
12
12
  }
13
13
  function setRequestLocale(locale) {
14
+ 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");
14
15
  holder().locale = locale;
15
16
  }
16
17
  function declaredLocale() {
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","names":[],"sources":["../src/server.ts"],"sourcesContent":["import { cookies, headers } from 'next/headers';\nimport * as React from 'react';\nimport {\n alternateLinks,\n localeFromPath,\n LOCALE_STORAGE_KEY,\n resolveRequestLocale,\n warnOnce,\n type AlternateLink,\n type TFunction,\n type Verbaly,\n} from 'verbaly';\nimport {\n createRequestInstance,\n loadMessages,\n locales,\n requestOptions,\n routing,\n sourceLocale,\n} from 'virtual:verbaly';\n\ninterface RequestState {\n locale: string;\n instance: Verbaly;\n}\n\n// React.cache = per-request dedupe in RSC; identity fallback keeps plain-node tests runnable\nconst perRequest: <T extends (...args: never[]) => unknown>(fn: T) => T =\n (React as { cache?: <T>(fn: T) => T }).cache ?? ((fn) => fn);\n\ninterface LocaleHolder {\n locale?: string;\n}\n\nconst scopedHolder = perRequest((): LocaleHolder => ({}));\nconst moduleHolder: LocaleHolder = {};\n\n// React.cache only holds inside a request, and outside one there is a single request to hold for\nfunction holder(): LocaleHolder {\n const scoped = scopedHolder();\n return scoped === scopedHolder() ? scoped : moduleHolder;\n}\n\n// call it from the layout with the [locale] segment: reading headers() kills static rendering\nexport function setRequestLocale(locale: string): void {\n holder().locale = locale;\n}\n\n// a route segment is a url segment, so it narrows like one: a slug must never become a locale\nfunction declaredLocale(): string | undefined {\n const raw = holder().locale;\n if (raw === undefined) return undefined;\n const match = localeFromPath({ supported: locales, path: `/${raw}` });\n if (match) return match;\n warnOnce(`setRequestLocale was given a locale the project does not have, so it was ignored`);\n return undefined;\n}\n\n// only reached when no segment declared it: this read is what opts a route out of static\nasync function negotiate(): Promise<string> {\n const cookieName = requestOptions?.cookie ?? LOCALE_STORAGE_KEY;\n const headerStore = await headers();\n const cookieValue = cookieName === false ? undefined : (await cookies()).get(cookieName)?.value;\n return resolveRequestLocale({\n supported: locales,\n routing,\n cookie: cookieValue,\n header: headerStore.get('accept-language'),\n fallback: requestOptions?.fallback ?? sourceLocale,\n });\n}\n\nconst getRequestState = perRequest(async (): Promise<RequestState> => {\n const locale = declaredLocale() ?? (await negotiate());\n return { locale, instance: await createRequestInstance(locale) };\n});\n\nexport interface AlternatesOptions {\n path: string;\n baseUrl?: string;\n}\n\n// the hreflang set for generateMetadata, in the shape Next's alternates field takes\nexport function getAlternates(options: AlternatesOptions): {\n canonical?: string;\n languages: Record<string, string>;\n} {\n const links: AlternateLink[] = alternateLinks({\n supported: locales,\n sourceLocale,\n routing,\n path: options.path,\n baseUrl: options.baseUrl,\n });\n const languages: Record<string, string> = {};\n for (const link of links) languages[link.hreflang] = link.href;\n const self = localeFromPath({ supported: locales, path: options.path }) ?? sourceLocale;\n return { canonical: languages[self], languages };\n}\n\n// request-scoped instance: never the virtual:verbaly singleton (locale would leak between requests)\nexport async function getVerbaly(): Promise<Verbaly> {\n return (await getRequestState()).instance;\n}\n\nexport async function getT(): Promise<TFunction> {\n return (await getRequestState()).instance.t;\n}\n\nexport async function getRequestLocale(): Promise<string> {\n return (await getRequestState()).locale;\n}\n\nexport interface VerbalyProviderProps {\n locale: string;\n messages?: Record<string, string>;\n}\n\n// messages omitted for the source locale: it already ships inline in the client bundle\nexport async function getVerbalyProps(): Promise<VerbalyProviderProps> {\n const { locale } = await getRequestState();\n if (locale === sourceLocale) return { locale };\n return { locale, messages: await loadMessages(locale) };\n}\n"],"mappings":";;;;;AA2BA,MAAM,aACH,MAAsC,WAAW,OAAO;AAM3D,MAAM,eAAe,kBAAgC,CAAC,EAAE;AACxD,MAAM,eAA6B,CAAC;AAGpC,SAAS,SAAuB;CAC9B,MAAM,SAAS,aAAa;CAC5B,OAAO,WAA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;CACxD,QAAQ,MAAM,gBAAgB,EAAA,CAAG;AACnC;AAQA,eAAsB,kBAAiD;CACrE,MAAM,EAAE,WAAW,MAAM,gBAAgB;CACzC,IAAI,WAAW,cAAc,OAAO,EAAE,OAAO;CAC7C,OAAO;EAAE;EAAQ,UAAU,MAAM,aAAa,MAAM;CAAE;AACxD"}
1
+ {"version":3,"file":"server.js","names":[],"sources":["../src/server.ts"],"sourcesContent":["import { cookies, headers } from 'next/headers';\nimport * as React from 'react';\nimport {\n alternateLinks,\n localeFromPath,\n LOCALE_STORAGE_KEY,\n resolveRequestLocale,\n warnOnce,\n type AlternateLink,\n type TFunction,\n type Verbaly,\n} from 'verbaly';\nimport {\n createRequestInstance,\n loadMessages,\n locales,\n requestOptions,\n routing,\n sourceLocale,\n} from 'virtual:verbaly';\n\ninterface RequestState {\n locale: string;\n instance: Verbaly;\n}\n\n// React.cache = per-request dedupe in RSC; identity fallback keeps plain-node tests runnable\nconst perRequest: <T extends (...args: never[]) => unknown>(fn: T) => T =\n (React as { cache?: <T>(fn: T) => T }).cache ?? ((fn) => fn);\n\ninterface LocaleHolder {\n locale?: string;\n}\n\nconst scopedHolder = perRequest((): LocaleHolder => ({}));\nconst moduleHolder: LocaleHolder = {};\n\n// React.cache only holds inside a request, and outside one there is a single request to hold for\nfunction holder(): LocaleHolder {\n const scoped = scopedHolder();\n return scoped === scopedHolder() ? scoped : moduleHolder;\n}\n\n// call it from the layout with the [locale] segment: reading headers() kills static rendering\nexport function setRequestLocale(locale: string): void {\n // a segment says the url carries the locale, and no-prefix tells every url helper it does not\n if (routing === 'no-prefix') {\n warnOnce(\n `setRequestLocale got a locale segment while routing is \"no-prefix\": if your urls start ` +\n `with the locale, set routing to 'prefix-all' or 'prefix-except-source' in your verbaly config`,\n );\n }\n holder().locale = locale;\n}\n\n// a route segment is a url segment, so it narrows like one: a slug must never become a locale\nfunction declaredLocale(): string | undefined {\n const raw = holder().locale;\n if (raw === undefined) return undefined;\n const match = localeFromPath({ supported: locales, path: `/${raw}` });\n if (match) return match;\n warnOnce(`setRequestLocale was given a locale the project does not have, so it was ignored`);\n return undefined;\n}\n\n// only reached when no segment declared it: this read is what opts a route out of static\nasync function negotiate(): Promise<string> {\n const cookieName = requestOptions?.cookie ?? LOCALE_STORAGE_KEY;\n const headerStore = await headers();\n const cookieValue = cookieName === false ? undefined : (await cookies()).get(cookieName)?.value;\n return resolveRequestLocale({\n supported: locales,\n routing,\n cookie: cookieValue,\n header: headerStore.get('accept-language'),\n fallback: requestOptions?.fallback ?? sourceLocale,\n });\n}\n\nconst getRequestState = perRequest(async (): Promise<RequestState> => {\n const locale = declaredLocale() ?? (await negotiate());\n return { locale, instance: await createRequestInstance(locale) };\n});\n\nexport interface AlternatesOptions {\n path: string;\n baseUrl?: string;\n}\n\n// the hreflang set for generateMetadata, in the shape Next's alternates field takes\nexport function getAlternates(options: AlternatesOptions): {\n canonical?: string;\n languages: Record<string, string>;\n} {\n const links: AlternateLink[] = alternateLinks({\n supported: locales,\n sourceLocale,\n routing,\n path: options.path,\n baseUrl: options.baseUrl,\n });\n const languages: Record<string, string> = {};\n for (const link of links) languages[link.hreflang] = link.href;\n const self = localeFromPath({ supported: locales, path: options.path }) ?? sourceLocale;\n return { canonical: languages[self], languages };\n}\n\n// request-scoped instance: never the virtual:verbaly singleton (locale would leak between requests)\nexport async function getVerbaly(): Promise<Verbaly> {\n return (await getRequestState()).instance;\n}\n\nexport async function getT(): Promise<TFunction> {\n return (await getRequestState()).instance.t;\n}\n\nexport async function getRequestLocale(): Promise<string> {\n return (await getRequestState()).locale;\n}\n\nexport interface VerbalyProviderProps {\n locale: string;\n messages?: Record<string, string>;\n}\n\n// messages omitted for the source locale: it already ships inline in the client bundle\nexport async function getVerbalyProps(): Promise<VerbalyProviderProps> {\n const { locale } = await getRequestState();\n if (locale === sourceLocale) return { locale };\n return { locale, messages: await loadMessages(locale) };\n}\n"],"mappings":";;;;;AA2BA,MAAM,aACH,MAAsC,WAAW,OAAO;AAM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GA,eAAsB,aAA+B;CACnD,QAAQ,MAAM,gBAAgB,EAAA,CAAG;AACnC;AAEA,eAAsB,OAA2B;CAC/C,QAAQ,MAAM,gBAAgB,EAAA,CAAG,SAAS;AAC5C;AAEA,eAAsB,mBAAoC;CACxD,QAAQ,MAAM,gBAAgB,EAAA,CAAG;AACnC;AAQA,eAAsB,kBAAiD;CACrE,MAAM,EAAE,WAAW,MAAM,gBAAgB;CACzC,IAAI,WAAW,cAAc,OAAO,EAAE,OAAO;CAC7C,OAAO;EAAE;EAAQ,UAAU,MAAM,aAAa,MAAM;CAAE;AACxD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@verbaly/next",
3
- "version": "0.63.0",
3
+ "version": "0.65.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.63.0"
67
+ "@verbaly/compiler": "^0.65.0"
68
68
  },
69
69
  "peerDependencies": {
70
- "@verbaly/react": "^0.63.0",
70
+ "@verbaly/react": "^0.65.0",
71
71
  "next": "^15.0.0 || ^16.0.0",
72
72
  "react": "^18.0.0 || ^19.0.0",
73
- "verbaly": "^0.63.0"
73
+ "verbaly": "^0.65.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.63.0",
78
+ "@verbaly/react": "^0.65.0",
79
79
  "happy-dom": "^20.14.5",
80
- "next": "^16.3.5",
80
+ "next": "^16.3.6",
81
81
  "react": "^19.3.0",
82
82
  "react-dom": "^19.3.0",
83
- "verbaly": "^0.63.0"
83
+ "verbaly": "^0.65.0"
84
84
  },
85
85
  "scripts": {
86
86
  "build": "tsdown",