@fluenti/next 0.3.2 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,17 +1,19 @@
1
1
  import { existsSync as e, mkdirSync as t, watch as n, writeFileSync as r } from "node:fs";
2
- import { dirname as i, join as a, relative as o, resolve as s } from "node:path";
3
- import { fileURLToPath as c } from "node:url";
4
- import { DEFAULT_FLUENTI_CONFIG as l, loadConfigSync as u } from "@fluenti/core/config";
5
- import { validateLocale as d } from "@fluenti/core";
6
- import { resolveLocaleCodes as f } from "@fluenti/core/internal";
7
- import { createRequire as p } from "node:module";
2
+ import { execSync as i } from "node:child_process";
3
+ import { dirname as a, join as o, relative as s, resolve as c } from "node:path";
4
+ import { fileURLToPath as l } from "node:url";
5
+ import { DEFAULT_FLUENTI_CONFIG as u, loadConfigSync as d } from "@fluenti/core/config";
6
+ import { validateLocale as f } from "@fluenti/core";
7
+ import { resolveLocaleCodes as p } from "@fluenti/core/internal";
8
+ import { createRequire as m } from "node:module";
9
+ import { msg as h } from "@fluenti/react";
8
10
  //#region src/read-config.ts
9
- function m(e, t) {
11
+ function g(e, t) {
10
12
  let n;
11
13
  n = t?.config && typeof t.config == "object" ? {
12
- ...l,
14
+ ...u,
13
15
  ...t.config
14
- } : u(typeof t?.config == "string" ? t.config : void 0, e);
16
+ } : d(typeof t?.config == "string" ? t.config : void 0, e);
15
17
  let r = t?.serverModuleOutDir ?? ".fluenti", i = t?.cookieName ?? "locale", a = {
16
18
  fluentiConfig: n,
17
19
  serverModule: t?.serverModule ?? null,
@@ -22,48 +24,52 @@ function m(e, t) {
22
24
  }
23
25
  //#endregion
24
26
  //#region src/generate-server-module.ts
25
- function h(n, i) {
26
- if (i.serverModule) return s(n, i.serverModule);
27
- let a = s(n, i.serverModuleOutDir), c = s(a, "server.js"), l = s(a, "server.d.ts");
28
- e(a) || t(a, { recursive: !0 });
29
- let u = f(i.fluentiConfig.locales), p = i.fluentiConfig.defaultLocale ?? i.fluentiConfig.sourceLocale, m = i.fluentiConfig.compileOutDir, h = i.fluentiConfig.fallbackChain, v = g(i.cookieName), y = g(p);
30
- for (let e of u) d(e, "next-plugin");
31
- let b = _(o(a, s(n, m))), x = u.map((e) => ` case '${g(e)}': return import('${b}/${e}')`).join("\n"), S = h ? JSON.stringify(h) : "undefined";
32
- r(s(a, "client-provider.js"), `"use client";
27
+ function _(e, t) {
28
+ try {
29
+ r(e, t, "utf-8");
30
+ } catch (t) {
31
+ throw Error(`[fluenti] Failed to write generated module at ${e}: ${t instanceof Error ? t.message : String(t)}`);
32
+ }
33
+ }
34
+ function v(n, r) {
35
+ if (r.serverModule) return c(n, r.serverModule);
36
+ let i = c(n, r.serverModuleOutDir), a = c(i, "server.js"), o = c(i, "server.d.ts");
37
+ e(i) || t(i, { recursive: !0 });
38
+ let l = p(r.fluentiConfig.locales), u = r.fluentiConfig.defaultLocale ?? r.fluentiConfig.sourceLocale, d = r.fluentiConfig.compileOutDir, m = r.fluentiConfig.fallbackChain, h = r.fluentiConfig.dateFormats, g = r.fluentiConfig.numberFormats, v = y(r.cookieName), x = y(u);
39
+ for (let e of l) f(e, "next-plugin");
40
+ let S = b(s(i, c(n, d))), C = l.map((e) => ` case '${y(e)}': return import('${S}/${e}')`).join("\n"), w = m ? JSON.stringify(m) : "undefined";
41
+ _(c(i, "client-provider.js"), `"use client";
33
42
  // Auto-generated by @fluenti/next — do not edit
34
43
  // @ts-nocheck
35
44
  import { createElement } from 'react'
36
45
  import { I18nProvider } from '@fluenti/react'
37
- ${u.map((e) => `import ${e.replace(/[^a-zA-Z0-9]/g, "_")} from '${b}/${e}'`).join("\n")}
46
+ ${l.map((e) => `import ${e.replace(/[^a-zA-Z0-9]/g, "_")} from '${S}/${e}'`).join("\n")}
38
47
 
39
- const __allMessages = { ${u.map((e) => {
48
+ const __allMessages = { ${l.map((e) => {
40
49
  let t = e.replace(/[^a-zA-Z0-9]/g, "_");
41
- return `'${g(e)}': ${t}`;
50
+ return `'${y(e)}': ${t}`;
42
51
  }).join(", ")} }
52
+ const __dateFormats = ${h === void 0 ? "undefined" : JSON.stringify(h)}
53
+ const __numberFormats = ${g === void 0 ? "undefined" : JSON.stringify(g)}
43
54
 
44
55
  export function ClientI18nProvider({ locale, fallbackLocale, fallbackChain, children }) {
45
- return createElement(I18nProvider, { locale, fallbackLocale, messages: __allMessages, fallbackChain }, children)
56
+ return createElement(I18nProvider, { locale, fallbackLocale, messages: __allMessages, fallbackChain, dateFormats: __dateFormats, numberFormats: __numberFormats }, children)
46
57
  }
47
- `, "utf-8"), r(s(a, "client-provider.d.ts"), "// Auto-generated by @fluenti/next — do not edit\nimport type { ReactNode, ReactElement } from 'react'\n\nexport declare function ClientI18nProvider(props: {\n locale: string\n fallbackLocale: string\n fallbackChain?: Record<string, string[]>\n children: ReactNode\n}): ReactElement\n", "utf-8");
48
- let C = i.resolveLocale ? `import __resolveLocale from '${_(o(a, s(n, i.resolveLocale)))}'` : null, w = i.resolveLocale ? "resolveLocale: __resolveLocale," : `resolveLocale: async () => {
58
+ `), _(c(i, "client-provider.d.ts"), "// Auto-generated by @fluenti/next — do not edit\nimport type { ReactNode, ReactElement } from 'react'\n\nexport declare function ClientI18nProvider(props: {\n locale: string\n fallbackLocale: string\n fallbackChain?: Record<string, string[]>\n children: ReactNode\n}): ReactElement\n");
59
+ let T = r.resolveLocale ? `import __resolveLocale from '${b(s(i, c(n, r.resolveLocale)))}'` : null, E = r.resolveLocale ? "resolveLocale: __resolveLocale," : `resolveLocale: async () => {
49
60
  try {
50
61
  const { cookies, headers } = await import('next/headers')
51
62
  const [cookieStore, headerStore] = await Promise.all([cookies(), headers()])
52
63
 
53
- // 1. Referer URL path segment (available in Server Action context)
54
- const referer = headerStore.get('referer')
55
- if (referer) {
56
- try {
57
- const seg = new URL(referer).pathname.split('/')[1]
58
- if (seg && __locales.includes(seg)) return seg
59
- } catch {}
60
- }
64
+ // 0. x-fluenti-locale header (set by createI18nMiddleware most authoritative)
65
+ const fromMiddleware = headerStore.get('x-fluenti-locale')
66
+ if (fromMiddleware && __locales.includes(fromMiddleware)) return fromMiddleware
61
67
 
62
- // 2. Cookie (configurable name)
68
+ // 1. Cookie (configurable name)
63
69
  const fromCookie = cookieStore.get('${v}')?.value
64
70
  if (fromCookie && __locales.includes(fromCookie)) return fromCookie
65
71
 
66
- // 3. Accept-Language header
72
+ // 2. Accept-Language header
67
73
  const acceptLang = headerStore.get('accept-language')
68
74
  if (acceptLang) {
69
75
  for (const part of acceptLang.split(',')) {
@@ -75,28 +81,28 @@ export function ClientI18nProvider({ locale, fallbackLocale, fallbackChain, chil
75
81
  }
76
82
  }
77
83
 
78
- return '${y}'
84
+ return '${x}'
79
85
  } catch {
80
- return '${y}'
86
+ return '${x}'
81
87
  }
82
- },`, T = JSON.stringify(u);
83
- return r(c, `// Auto-generated by @fluenti/next — do not edit
88
+ },`, D = JSON.stringify(l);
89
+ _(a, `// Auto-generated by @fluenti/next — do not edit
84
90
  // @ts-nocheck
85
91
  import { createServerI18n } from '@fluenti/react/server'
86
92
  import { createElement } from 'react'
87
- ${C ? `${C}\n` : ""}
88
- const __locales = ${T}
93
+ ${T ? `${T}\n` : ""}
94
+ const __locales = ${D}
89
95
 
90
96
  const serverI18n = createServerI18n({
91
97
  loadMessages: async (locale) => {
92
98
  switch (locale) {
93
- ${x}
94
- default: return import('${b}/${y}')
99
+ ${C}
100
+ default: return import('${S}/${x}')
95
101
  }
96
102
  },
97
- fallbackLocale: '${y}',
98
- fallbackChain: ${S},
99
- ${w}
103
+ fallbackLocale: '${x}',
104
+ fallbackChain: ${w},
105
+ ${E}
100
106
  })
101
107
 
102
108
  export const setLocale = serverI18n.setLocale
@@ -122,7 +128,7 @@ export const NumberFormat = serverI18n.NumberFormat
122
128
  * Sets up both server-side (React.cache) and client-side (I18nProvider) i18n.
123
129
  */
124
130
  export async function I18nProvider({ locale, children }) {
125
- const activeLocale = (locale && locale.trim()) ? locale : '${y}'
131
+ const activeLocale = (locale && locale.trim()) ? locale : '${x}'
126
132
 
127
133
  // 1. Initialize server-side i18n (React.cache scoped)
128
134
  serverI18n.setLocale(activeLocale)
@@ -134,23 +140,29 @@ export async function I18nProvider({ locale, children }) {
134
140
 
135
141
  return createElement(ClientI18nProvider, {
136
142
  locale: activeLocale,
137
- fallbackLocale: '${y}',
138
- fallbackChain: ${S},
143
+ fallbackLocale: '${x}',
144
+ fallbackChain: ${w},
139
145
  }, children)
140
146
  }
141
- `, "utf-8"), r(l, "// Auto-generated by @fluenti/next — do not edit\nimport type { ReactNode, ReactElement } from 'react'\nimport type { CompileTimeT, FluentiCoreInstanceFull } from '@fluenti/core'\n\nexport declare function setLocale(locale: string): void\nexport declare function getI18n(): Promise<FluentiCoreInstanceFull & { locale: string }>\nexport declare const t: CompileTimeT\n\nexport declare function Trans(props: {\n children: ReactNode\n id?: string\n context?: string\n comment?: string\n render?: (translation: ReactNode) => ReactNode\n}): Promise<ReactElement>\n\nexport declare function Plural(props: {\n value: number\n id?: string\n context?: string\n comment?: string\n zero?: ReactNode\n one?: ReactNode\n two?: ReactNode\n few?: ReactNode\n many?: ReactNode\n other: ReactNode\n offset?: number\n}): Promise<ReactElement>\n\nexport declare function Select(props: {\n value: string\n id?: string\n context?: string\n comment?: string\n other: ReactNode\n options?: Record<string, ReactNode>\n [key: string]: ReactNode | Record<string, ReactNode> | string | undefined\n}): Promise<ReactElement>\n\nexport declare function DateTime(props: {\n value: Date | number\n style?: string\n}): Promise<ReactElement>\n\nexport declare function NumberFormat(props: {\n value: number\n style?: string\n}): Promise<ReactElement>\n\nexport declare function I18nProvider(props: {\n locale?: string\n children: ReactNode\n}): Promise<ReactElement>\n", "utf-8"), c;
147
+ `), _(o, "// Auto-generated by @fluenti/next — do not edit\nimport type { ReactNode, ReactElement } from 'react'\nimport type { CompileTimeT, FluentiCoreInstanceFull } from '@fluenti/core'\n\nexport declare function setLocale(locale: string): void\nexport declare function getI18n(): Promise<FluentiCoreInstanceFull & { locale: string }>\nexport declare const t: CompileTimeT\n\nexport declare function Trans(props: {\n children: ReactNode\n id?: string\n context?: string\n comment?: string\n render?: (translation: ReactNode) => ReactNode\n}): Promise<ReactElement>\n\nexport declare function Plural(props: {\n value: number\n id?: string\n context?: string\n comment?: string\n zero?: ReactNode\n one?: ReactNode\n two?: ReactNode\n few?: ReactNode\n many?: ReactNode\n other: ReactNode\n offset?: number\n}): Promise<ReactElement>\n\nexport declare function Select(props: {\n value: string\n id?: string\n context?: string\n comment?: string\n other: ReactNode\n options?: Record<string, ReactNode>\n [key: string]: ReactNode | Record<string, ReactNode> | string | undefined\n}): Promise<ReactElement>\n\nexport declare function DateTime(props: {\n value: Date | number\n format?: string\n}): Promise<ReactElement>\n\nexport declare function NumberFormat(props: {\n value: number\n format?: string\n}): Promise<ReactElement>\n\nexport declare function I18nProvider(props: {\n locale?: string\n children: ReactNode\n}): Promise<ReactElement>\n");
148
+ let O = c(i, "i18n-config.js"), k = c(i, "i18n-config.d.ts");
149
+ return _(O, `// Auto-generated by @fluenti/next — do not edit
150
+ export const locales = ${D}
151
+ export const sourceLocale = '${x}'
152
+ export const cookieName = '${v}'
153
+ `), _(k, "// Auto-generated by @fluenti/next — do not edit\nexport declare const locales: string[]\nexport declare const sourceLocale: string\nexport declare const cookieName: string\n"), a;
142
154
  }
143
- function g(e) {
155
+ function y(e) {
144
156
  return e.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
145
157
  }
146
- function _(e) {
158
+ function b(e) {
147
159
  return e.split("\\").join("/");
148
160
  }
149
161
  //#endregion
150
162
  //#region src/dev-runner.ts
151
- async function v(e) {
163
+ async function x(e) {
152
164
  if (e.compileOnly) try {
153
- let { runCompile: t } = p(a(e.cwd, "package.json"))("@fluenti/cli");
165
+ let { runCompile: t } = m(o(e.cwd, "package.json"))("@fluenti/cli");
154
166
  await t(e.cwd), console.log("[fluenti] Compiling... done"), e.onSuccess?.();
155
167
  return;
156
168
  } catch (t) {
@@ -161,7 +173,7 @@ async function v(e) {
161
173
  }
162
174
  let t = null;
163
175
  try {
164
- t = p(a(e.cwd, "package.json"))("@fluenti/cli");
176
+ t = m(o(e.cwd, "package.json"))("@fluenti/cli");
165
177
  } catch {}
166
178
  if (t) try {
167
179
  await t.runExtract(e.cwd), e.parallelCompile ? await t.runCompile(e.cwd, { parallel: !0 }) : await t.runCompile(e.cwd), console.log("[fluenti] Extracting and compiling... done"), e.onSuccess?.();
@@ -176,12 +188,12 @@ async function v(e) {
176
188
  if (e.throwOnError) throw Error(n);
177
189
  console.warn(n), e.onError?.(Error(n));
178
190
  }
179
- function y(e, t = 300) {
191
+ function S(e, t = 300) {
180
192
  let n = null, r = !1, i = !1;
181
193
  async function a() {
182
194
  r = !0;
183
195
  try {
184
- await v(e);
196
+ await x(e);
185
197
  } finally {
186
198
  r = !1, i && (i = !1, o());
187
199
  }
@@ -195,40 +207,40 @@ function y(e, t = 300) {
195
207
  }
196
208
  //#endregion
197
209
  //#region src/dev-watcher.ts
198
- var b = null;
199
- function x(e, t) {
200
- if (!t || t.length === 0) return [s(e, "src")];
210
+ var C = null;
211
+ function w(e, t) {
212
+ if (!t || t.length === 0) return [c(e, "src")];
201
213
  let n = /* @__PURE__ */ new Set();
202
214
  for (let e of t) {
203
215
  let t = e.replace(/^\.\//, "").split("*")[0].replace(/\/+$/, "");
204
216
  n.add(t || ".");
205
217
  }
206
- return [...n].map((t) => s(e, t));
218
+ return [...n].map((t) => c(e, t));
207
219
  }
208
- function S(e) {
209
- b && b();
210
- let { cwd: t, compiledDir: r, delay: i = 1e3, include: a, exclude: o, parallelCompile: c } = e, l = s(t, r), u = p(typeof __filename < "u" ? __filename : import.meta.url)("picomatch"), d = o?.length ? u(o) : () => !1, f = { cwd: t };
211
- c && (f.parallelCompile = !0);
212
- let m = y(f, i);
213
- m();
214
- let h = x(t, a).map((e) => n(e, { recursive: !0 }, (t, n) => {
215
- n && /\.[jt]sx?$/.test(n) && (n.includes("node_modules") || n.includes(".next") || s(e, n).startsWith(l) || d(n) || m());
220
+ function T(e) {
221
+ C && C();
222
+ let { cwd: t, compiledDir: r, delay: i = 1e3, include: a, exclude: o, parallelCompile: s } = e, l = c(t, r), u = m(typeof __filename < "u" ? __filename : import.meta.url)("picomatch"), d = o?.length ? u(o) : () => !1, f = { cwd: t };
223
+ s && (f.parallelCompile = !0);
224
+ let p = S(f, i);
225
+ p();
226
+ let h = w(t, a).map((e) => n(e, { recursive: !0 }, (t, n) => {
227
+ n && /\.[jt]sx?$/.test(n) && (n.includes("node_modules") || n.includes(".next") || c(e, n).startsWith(l) || d(n) || p());
216
228
  })), g = () => {
217
229
  for (let e of h) e.close();
218
- b = null;
230
+ C = null;
219
231
  };
220
- return b = g, g;
232
+ return C = g, g;
221
233
  }
222
234
  //#endregion
223
235
  //#region src/with-fluenti.ts
224
- function C(e) {
225
- if (e && !w(e)) return T({}, e);
236
+ function E(e) {
237
+ if (e && !D(e)) return O({}, e);
226
238
  let t = e ?? {};
227
239
  return function(e) {
228
- return T(t, e ?? {});
240
+ return O(t, e ?? {});
229
241
  };
230
242
  }
231
- function w(e) {
243
+ function D(e) {
232
244
  return [
233
245
  "config",
234
246
  "serverModule",
@@ -238,10 +250,10 @@ function w(e) {
238
250
  "loaderEnforce"
239
251
  ].some((t) => t in e);
240
252
  }
241
- function T(t, n) {
242
- let r = process.cwd(), a = m(r, t), o = a.fluentiConfig, l = o.compileOutDir;
243
- e(s(r, l)) || console.warn(`\n[fluenti] Compiled catalogs not found at ${l}.\nRun: npx fluenti extract && npx fluenti compile\n`);
244
- let u = h(r, a), d = s(typeof __dirname < "u" ? __dirname : i(c(import.meta.url)), "loader.js"), f = n.webpack, p = !1, g = Object.fromEntries([
253
+ function O(t, n) {
254
+ let r = process.cwd(), o = g(r, t), u = o.fluentiConfig, d = u.compileOutDir;
255
+ e(c(r, d)) || console.warn(`\n[fluenti] Compiled catalogs not found at ${d}.\nRun: npx fluenti extract && npx fluenti compile\n`);
256
+ let f = v(r, o), p = c(typeof __dirname < "u" ? __dirname : a(l(import.meta.url)), "loader.js"), m = n.webpack, h = !1, _ = Object.fromEntries([
245
257
  "*.ts",
246
258
  "*.tsx",
247
259
  "*.js",
@@ -249,50 +261,49 @@ function T(t, n) {
249
261
  ].map((e) => [e, {
250
262
  condition: { not: "foreign" },
251
263
  loaders: ["@fluenti/next/loader"]
252
- }])), _ = "./" + u.replace(r + "/", "").replace(r + "\\", ""), v = { "@fluenti/next": _ }, y = process.env.NODE_ENV === "development" || process.argv.some((e) => e === "dev"), b = o.devAutoCompile ?? !0;
253
- if (y && b) {
264
+ }])), y = c(a(f), "i18n-config.js"), b = "./" + s(r, f).split("\\").join("/"), x = "./" + s(r, y).split("\\").join("/"), S = {
265
+ "@fluenti/next": b,
266
+ "@fluenti/next/i18n-config": x
267
+ }, C = process.env.NODE_ENV === "development" || process.argv.some((e) => e === "dev"), w = u.buildAutoCompile ?? !0;
268
+ if (!C && w && !h) {
269
+ h = !0;
270
+ try {
271
+ i("npx fluenti compile" + (u.parallelCompile ? " --parallel" : ""), {
272
+ cwd: r,
273
+ stdio: "inherit"
274
+ });
275
+ } catch {}
276
+ }
277
+ let E = u.devAutoCompile ?? !0;
278
+ if (C && E) {
254
279
  let e = {
255
280
  cwd: r,
256
- compiledDir: l,
257
- delay: o.devAutoCompileDelay ?? 1e3
281
+ compiledDir: d,
282
+ delay: u.devAutoCompileDelay ?? 1e3
258
283
  };
259
- o.parallelCompile && (e.parallelCompile = !0), o.include && (e.include = o.include), o.exclude && (e.exclude = o.exclude), S(e);
284
+ u.parallelCompile && (e.parallelCompile = !0), u.include && (e.include = u.include), u.exclude && (e.exclude = u.exclude), T(e);
260
285
  }
261
286
  return {
262
287
  ...n,
263
- turbopack: E(n.turbopack, {
264
- rules: g,
265
- resolveAlias: v
288
+ turbopack: k(n.turbopack, {
289
+ rules: _,
290
+ resolveAlias: S
266
291
  }),
267
292
  webpack(e, n) {
268
- let i = t.loaderEnforce === void 0 && !("loaderEnforce" in t) ? "pre" : t.loaderEnforce;
269
- e.module.rules.push({
293
+ let r = t.loaderEnforce === void 0 && !("loaderEnforce" in t) ? "pre" : t.loaderEnforce;
294
+ return e.module.rules.push({
270
295
  test: /\.[jt]sx?$/,
271
- ...i ? { enforce: i } : {},
296
+ ...r ? { enforce: r } : {},
272
297
  exclude: [/node_modules/, /\.next/],
273
298
  use: [{
274
- loader: d,
275
- options: { serverModulePath: u }
299
+ loader: p,
300
+ options: { serverModulePath: f }
276
301
  }]
277
- }), e.resolve = e.resolve ?? {}, e.resolve.alias = e.resolve.alias ?? {}, e.resolve.alias["@fluenti/next$"] = u;
278
- let a = o.buildAutoCompile ?? !0;
279
- return !n.dev && a && (e.plugins = e.plugins ?? [], e.plugins.push({ apply(e) {
280
- e.hooks.beforeRun.tapPromise("fluenti-compile", async () => {
281
- if (p) return;
282
- p = !0;
283
- let e;
284
- try {
285
- e = await import("@fluenti/cli");
286
- } catch {
287
- return;
288
- }
289
- await e.runCompile(r, o.parallelCompile ? { parallel: !0 } : void 0);
290
- });
291
- } })), f ? f(e, n) : e;
302
+ }), e.resolve = e.resolve ?? {}, e.resolve.alias = e.resolve.alias ?? {}, e.resolve.alias["@fluenti/next$"] = f, e.resolve.alias["@fluenti/next/i18n-config$"] = y, m ? m(e, n) : e;
292
303
  }
293
304
  };
294
305
  }
295
- function E(e, t) {
306
+ function k(e, t) {
296
307
  let n = e ?? {}, r = n.rules ?? {}, i = Object.keys(t.rules).filter((e) => e in r);
297
308
  return i.length > 0 && console.warn(`[fluenti] Your turbopack.rules override Fluenti's loader for: ${i.join(", ")}.\n Fluenti's t\`\` transform will NOT run on these file types.\n If this is intentional, you can suppress this warning with { devAutoCompile: false }.`), {
298
309
  ...n,
@@ -308,12 +319,12 @@ function E(e, t) {
308
319
  }
309
320
  //#endregion
310
321
  //#region src/index.ts
311
- var D = "[fluenti] `withFluenti()` must be configured in next.config.ts before importing from \"@fluenti/next\".";
312
- function O() {
313
- throw Error(D);
322
+ var A = "[fluenti] `withFluenti()` must be configured in next.config.ts before importing from \"@fluenti/next\".";
323
+ function j() {
324
+ throw Error(A);
314
325
  }
315
- var k = O, A = O, j = O, M = O, N = O, P = O, F = O, I = O, L = O;
326
+ var M = j, N = j, P = j, F = j, I = j, L = j, R = j, z = j, B = j;
316
327
  //#endregion
317
- export { F as DateTime, L as I18nProvider, I as NumberFormat, N as Plural, P as Select, M as Trans, A as getI18n, k as setLocale, j as t, C as withFluenti };
328
+ export { R as DateTime, B as I18nProvider, z as NumberFormat, I as Plural, L as Select, F as Trans, N as getI18n, h as msg, M as setLocale, P as t, E as withFluenti };
318
329
 
319
330
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/read-config.ts","../src/generate-server-module.ts","../src/dev-runner.ts","../src/dev-watcher.ts","../src/with-fluenti.ts","../src/index.ts"],"sourcesContent":["import { loadConfigSync, DEFAULT_FLUENTI_CONFIG } from '@fluenti/core/config'\nimport type { FluentiBuildConfig } from '@fluenti/core/internal'\nimport type { WithFluentConfig, ResolvedFluentConfig } from './types'\n\n/**\n * Read fluenti.config.ts and merge with withFluenti() overrides.\n *\n * Delegates config file loading to `@fluenti/core`'s shared `loadConfigSync()`.\n */\nexport function resolveConfig(\n projectRoot: string,\n overrides?: WithFluentConfig,\n): ResolvedFluentConfig {\n let fluentiConfig: FluentiBuildConfig\n\n if (overrides?.config && typeof overrides.config === 'object') {\n // Inline config — merge with defaults\n fluentiConfig = { ...DEFAULT_FLUENTI_CONFIG, ...overrides.config }\n } else {\n // string path or auto-discover\n fluentiConfig = loadConfigSync(\n typeof overrides?.config === 'string' ? overrides.config : undefined,\n projectRoot,\n )\n }\n\n const serverModuleOutDir = overrides?.serverModuleOutDir ?? '.fluenti'\n const cookieName = overrides?.cookieName ?? 'locale'\n\n const resolved: ResolvedFluentConfig = {\n fluentiConfig,\n serverModule: overrides?.serverModule ?? null,\n serverModuleOutDir,\n cookieName,\n }\n if (overrides?.resolveLocale) resolved.resolveLocale = overrides.resolveLocale\n return resolved\n}\n","import { writeFileSync, mkdirSync, existsSync } from 'node:fs'\nimport { resolve, relative } from 'node:path'\nimport { validateLocale } from '@fluenti/core'\nimport { resolveLocaleCodes } from '@fluenti/core/internal'\nimport type { ResolvedFluentConfig } from './types'\n\n/**\n * Generate the server module that provides:\n * - setLocale / getI18n\n * - Trans / Plural / Select / DateTime / NumberFormat (server components)\n * - I18nProvider (async server component for layouts)\n *\n * @returns Absolute path to the generated server module.\n */\nexport function generateServerModule(\n projectRoot: string,\n config: ResolvedFluentConfig,\n): string {\n if (config.serverModule) {\n return resolve(projectRoot, config.serverModule)\n }\n\n const outDir = resolve(projectRoot, config.serverModuleOutDir)\n const outPath = resolve(outDir, 'server.js')\n const dtsPath = resolve(outDir, 'server.d.ts')\n\n if (!existsSync(outDir)) {\n mkdirSync(outDir, { recursive: true })\n }\n\n const locales = resolveLocaleCodes(config.fluentiConfig.locales)\n const defaultLocale = config.fluentiConfig.defaultLocale ?? config.fluentiConfig.sourceLocale\n const compiledDir = config.fluentiConfig.compileOutDir\n const fallbackChain = config.fluentiConfig.fallbackChain\n const cookieName = escapeJsSingleQuoted(config.cookieName)\n const defaultLocaleSafe = escapeJsSingleQuoted(defaultLocale)\n\n for (const locale of locales) {\n validateLocale(locale, 'next-plugin')\n }\n\n const compiledDirAbs = resolve(projectRoot, compiledDir)\n const compiledRelative = toForwardSlash(relative(outDir, compiledDirAbs))\n\n const localeImports = locales\n .map((locale) => ` case '${escapeJsSingleQuoted(locale)}': return import('${compiledRelative}/${locale}')`)\n .join('\\n')\n\n const fallbackChainStr = fallbackChain\n ? JSON.stringify(fallbackChain)\n : 'undefined'\n\n // Generate a 'use client' provider that imports messages statically.\n // Messages contain functions (interpolation) which can't cross the RSC boundary.\n const clientProviderPath = resolve(outDir, 'client-provider.js')\n\n const clientStaticImports = locales\n .map((locale) => {\n const safe = locale.replace(/[^a-zA-Z0-9]/g, '_')\n return `import ${safe} from '${compiledRelative}/${locale}'`\n })\n .join('\\n')\n\n const clientAllMessagesEntries = locales\n .map((locale) => {\n const safe = locale.replace(/[^a-zA-Z0-9]/g, '_')\n return `'${escapeJsSingleQuoted(locale)}': ${safe}`\n })\n .join(', ')\n\n const clientProviderSource = `\"use client\";\n// Auto-generated by @fluenti/next — do not edit\n// @ts-nocheck\nimport { createElement } from 'react'\nimport { I18nProvider } from '@fluenti/react'\n${clientStaticImports}\n\nconst __allMessages = { ${clientAllMessagesEntries} }\n\nexport function ClientI18nProvider({ locale, fallbackLocale, fallbackChain, children }) {\n return createElement(I18nProvider, { locale, fallbackLocale, messages: __allMessages, fallbackChain }, children)\n}\n`\n writeFileSync(clientProviderPath, clientProviderSource, 'utf-8')\n\n const clientProviderDtsPath = resolve(outDir, 'client-provider.d.ts')\n const clientProviderDtsSource = `// Auto-generated by @fluenti/next — do not edit\nimport type { ReactNode, ReactElement } from 'react'\n\nexport declare function ClientI18nProvider(props: {\n locale: string\n fallbackLocale: string\n fallbackChain?: Record<string, string[]>\n children: ReactNode\n}): ReactElement\n`\n writeFileSync(clientProviderDtsPath, clientProviderDtsSource, 'utf-8')\n\n const resolveLocaleImport = config.resolveLocale\n ? (() => {\n const absPath = resolve(projectRoot, config.resolveLocale)\n const relPath = toForwardSlash(relative(outDir, absPath))\n return `import __resolveLocale from '${relPath}'`\n })()\n : null\n\n const resolveLocaleFn = config.resolveLocale\n ? `resolveLocale: __resolveLocale,`\n : `resolveLocale: async () => {\n try {\n const { cookies, headers } = await import('next/headers')\n const [cookieStore, headerStore] = await Promise.all([cookies(), headers()])\n\n // 1. Referer URL path segment (available in Server Action context)\n const referer = headerStore.get('referer')\n if (referer) {\n try {\n const seg = new URL(referer).pathname.split('/')[1]\n if (seg && __locales.includes(seg)) return seg\n } catch {}\n }\n\n // 2. Cookie (configurable name)\n const fromCookie = cookieStore.get('${cookieName}')?.value\n if (fromCookie && __locales.includes(fromCookie)) return fromCookie\n\n // 3. Accept-Language header\n const acceptLang = headerStore.get('accept-language')\n if (acceptLang) {\n for (const part of acceptLang.split(',')) {\n const lang = part.split(';')[0].trim()\n if (__locales.includes(lang)) return lang\n const prefix = lang.split('-')[0]\n const match = __locales.find(l => l === prefix || l.startsWith(prefix + '-'))\n if (match) return match\n }\n }\n\n return '${defaultLocaleSafe}'\n } catch {\n return '${defaultLocaleSafe}'\n }\n },`\n\n const localesArrayStr = JSON.stringify(locales)\n\n const moduleSource = `// Auto-generated by @fluenti/next — do not edit\n// @ts-nocheck\nimport { createServerI18n } from '@fluenti/react/server'\nimport { createElement } from 'react'\n${resolveLocaleImport ? `${resolveLocaleImport}\\n` : ''}\nconst __locales = ${localesArrayStr}\n\nconst serverI18n = createServerI18n({\n loadMessages: async (locale) => {\n switch (locale) {\n${localeImports}\n default: return import('${compiledRelative}/${defaultLocaleSafe}')\n }\n },\n fallbackLocale: '${defaultLocaleSafe}',\n fallbackChain: ${fallbackChainStr},\n ${resolveLocaleFn}\n})\n\nexport const setLocale = serverI18n.setLocale\nexport const getI18n = serverI18n.getI18n\nexport const t = (..._args) => {\n throw new Error(\n \"[fluenti] \\`t\\` imported from '@fluenti/next' is a compile-time API replaced at build time.\\\\n\" +\n ' Ensure:\\\\n' +\n ' 1. \\`withFluenti()\\` is configured in next.config.ts\\\\n' +\n ' 2. The file is inside src/ (not node_modules)\\\\n' +\n \" 3. For client components, import from '@fluenti/react'\",\n )\n}\nexport const Trans = serverI18n.Trans\nexport const Plural = serverI18n.Plural\nexport const Select = serverI18n.Select\nexport const DateTime = serverI18n.DateTime\nexport const NumberFormat = serverI18n.NumberFormat\n\n/**\n * Async server component for root layouts.\n *\n * Sets up both server-side (React.cache) and client-side (I18nProvider) i18n.\n */\nexport async function I18nProvider({ locale, children }) {\n const activeLocale = (locale && locale.trim()) ? locale : '${defaultLocaleSafe}'\n\n // 1. Initialize server-side i18n (React.cache scoped)\n serverI18n.setLocale(activeLocale)\n await serverI18n.getI18n()\n\n // 2. Import the local 'use client' provider that has messages statically bundled.\n // Messages contain functions (interpolation) which can't be serialized across the RSC boundary.\n const { ClientI18nProvider } = await import('./client-provider.js')\n\n return createElement(ClientI18nProvider, {\n locale: activeLocale,\n fallbackLocale: '${defaultLocaleSafe}',\n fallbackChain: ${fallbackChainStr},\n }, children)\n}\n`\n\n const dtsSource = `// Auto-generated by @fluenti/next — do not edit\nimport type { ReactNode, ReactElement } from 'react'\nimport type { CompileTimeT, FluentiCoreInstanceFull } from '@fluenti/core'\n\nexport declare function setLocale(locale: string): void\nexport declare function getI18n(): Promise<FluentiCoreInstanceFull & { locale: string }>\nexport declare const t: CompileTimeT\n\nexport declare function Trans(props: {\n children: ReactNode\n id?: string\n context?: string\n comment?: string\n render?: (translation: ReactNode) => ReactNode\n}): Promise<ReactElement>\n\nexport declare function Plural(props: {\n value: number\n id?: string\n context?: string\n comment?: string\n zero?: ReactNode\n one?: ReactNode\n two?: ReactNode\n few?: ReactNode\n many?: ReactNode\n other: ReactNode\n offset?: number\n}): Promise<ReactElement>\n\nexport declare function Select(props: {\n value: string\n id?: string\n context?: string\n comment?: string\n other: ReactNode\n options?: Record<string, ReactNode>\n [key: string]: ReactNode | Record<string, ReactNode> | string | undefined\n}): Promise<ReactElement>\n\nexport declare function DateTime(props: {\n value: Date | number\n style?: string\n}): Promise<ReactElement>\n\nexport declare function NumberFormat(props: {\n value: number\n style?: string\n}): Promise<ReactElement>\n\nexport declare function I18nProvider(props: {\n locale?: string\n children: ReactNode\n}): Promise<ReactElement>\n`\n\n writeFileSync(outPath, moduleSource, 'utf-8')\n writeFileSync(dtsPath, dtsSource, 'utf-8')\n\n return outPath\n}\n\n/** Escape a string for safe embedding inside a single-quoted JS string literal. */\nfunction escapeJsSingleQuoted(s: string): string {\n return s.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")\n}\n\nfunction toForwardSlash(p: string): string {\n return p.split('\\\\').join('/')\n}\n","import { join } from 'node:path'\nimport { createRequire } from 'node:module'\n\nexport interface DevRunnerOptions {\n cwd: string\n onSuccess?: () => void\n onError?: (err: Error) => void\n /** If true, reject the promise on failure instead of swallowing the error */\n throwOnError?: boolean\n /** Run only compile (skip extract). Useful for production builds where source is unchanged. */\n compileOnly?: boolean\n /** Enable parallel compilation across locales using worker threads */\n parallelCompile?: boolean\n}\n\n/**\n * Run compile in-process via `@fluenti/cli` (for compileOnly mode),\n * or extract + compile in dev mode. Requires `@fluenti/cli` to be installed\n * as a devDependency.\n */\nexport async function runExtractCompile(options: DevRunnerOptions): Promise<void> {\n if (options.compileOnly) {\n try {\n // Resolve @fluenti/cli from the project's cwd (not from this package's location)\n // using createRequire so pnpm's strict node_modules layout works correctly.\n // Use require() (not import()) to load @fluenti/cli — avoids CJS/ESM interop\n // issues when dynamic import() loads minified CJS with chunk requires.\n const projectRequire = createRequire(join(options.cwd, 'package.json'))\n const { runCompile } = projectRequire('@fluenti/cli')\n await runCompile(options.cwd)\n console.log('[fluenti] Compiling... done')\n options.onSuccess?.()\n return\n } catch (e) {\n const error = e instanceof Error ? e : new Error(String(e))\n if (options.throwOnError) throw error\n console.warn('[fluenti] Compile failed:', error.message)\n options.onError?.(error)\n return\n }\n }\n\n // Dev mode: run in-process extract + compile.\n // Step 1: load @fluenti/cli — if not installed, guide user to install it.\n // Step 2: run — errors here mean the CLI ran but failed; surface them.\n let fluentCli: { runExtract: (cwd: string) => Promise<void>; runCompile: (cwd: string, opts?: { parallel: boolean }) => Promise<void> } | null = null\n try {\n const projectRequire = createRequire(join(options.cwd, 'package.json'))\n fluentCli = projectRequire('@fluenti/cli')\n } catch {\n // @fluenti/cli not installed — will show install guide below\n }\n\n if (fluentCli) {\n try {\n await fluentCli.runExtract(options.cwd)\n if (options.parallelCompile) {\n await fluentCli.runCompile(options.cwd, { parallel: true })\n } else {\n await fluentCli.runCompile(options.cwd)\n }\n console.log('[fluenti] Extracting and compiling... done')\n options.onSuccess?.()\n return\n } catch (e) {\n const error = e instanceof Error ? e : new Error(String(e))\n if (options.throwOnError) throw error\n console.warn('[fluenti] Extract/compile failed:', error.message)\n options.onError?.(error)\n return\n }\n }\n\n const msg =\n '[fluenti] @fluenti/cli is required for auto-compile.\\n' +\n ' Install it as a devDependency:\\n' +\n ' pnpm add -D @fluenti/cli\\n' +\n ' See: https://fluenti.dev/start/introduction/'\n if (options.throwOnError) {\n throw new Error(msg)\n }\n console.warn(msg)\n options.onError?.(new Error(msg))\n}\n\n/**\n * Create a debounced runner that collapses rapid calls.\n *\n * - If called while idle, schedules a run after `delay` ms.\n * - If called while a run is in progress, marks a pending rerun.\n * - Never runs concurrently.\n */\nexport function createDebouncedRunner(\n options: DevRunnerOptions,\n delay = 300,\n): () => void {\n let timer: ReturnType<typeof setTimeout> | null = null\n let running = false\n let pendingRerun = false\n\n async function execute(): Promise<void> {\n running = true\n try {\n await runExtractCompile(options)\n } finally {\n running = false\n if (pendingRerun) {\n pendingRerun = false\n schedule()\n }\n }\n }\n\n function schedule(): void {\n if (timer !== null) {\n clearTimeout(timer)\n }\n timer = setTimeout(() => {\n timer = null\n if (running) {\n pendingRerun = true\n } else {\n execute()\n }\n }, delay)\n }\n\n return schedule\n}\n","import { watch } from 'node:fs'\nimport { resolve } from 'node:path'\nimport { createRequire } from 'node:module'\nimport { createDebouncedRunner } from './dev-runner'\n\nexport interface DevWatcherOptions {\n cwd: string\n compiledDir: string\n delay?: number\n /** Glob patterns from fluenti.config.ts `include` field */\n include?: string[]\n /** Glob patterns from fluenti.config.ts `exclude` field */\n exclude?: string[]\n /** Enable parallel compilation across locales using worker threads */\n parallelCompile?: boolean\n}\n\nlet activeWatcher: (() => void) | null = null\n\n/**\n * Extract watch directories from include glob patterns.\n *\n * Takes the static prefix before the first glob wildcard (`*`).\n * Falls back to `src` if no include patterns are provided.\n *\n * @example\n * extractWatchDirs('/proj', ['./src/**\\/*.tsx']) → ['/proj/src']\n * extractWatchDirs('/proj', ['./app/**\\/*.ts', './lib/**\\/*.ts']) → ['/proj/app', '/proj/lib']\n * extractWatchDirs('/proj', ['./**\\/*.ts']) → ['/proj']\n */\nexport function extractWatchDirs(cwd: string, include?: string[]): string[] {\n if (!include || include.length === 0) {\n return [resolve(cwd, 'src')]\n }\n\n const dirs = new Set<string>()\n for (const pattern of include) {\n const normalized = pattern.replace(/^\\.\\//, '')\n const staticPart = normalized.split('*')[0]!.replace(/\\/+$/, '')\n dirs.add(staticPart || '.')\n }\n return [...dirs].map(d => resolve(cwd, d))\n}\n\n/**\n * Start a standalone file watcher for dev auto-compile.\n *\n * Works independently of webpack/Turbopack — watches source directories\n * (inferred from `include` patterns) for changes and triggers\n * extract+compile via the debounced runner.\n *\n * Only one watcher is active at a time (guards against multiple `applyFluenti()` calls).\n *\n * @returns A cleanup function that stops the watcher.\n */\nexport function startDevWatcher(options: DevWatcherOptions): () => void {\n // Clean up previous watcher if one exists (e.g., dev server reload)\n if (activeWatcher) {\n activeWatcher()\n }\n\n const { cwd, compiledDir, delay = 1000, include, exclude, parallelCompile } = options\n const compiledDirResolved = resolve(cwd, compiledDir)\n const _require = createRequire(\n typeof __filename !== 'undefined' ? __filename : import.meta.url,\n )\n const picomatch = _require('picomatch') as (patterns: string[]) => (str: string) => boolean\n const isExcluded = exclude?.length ? picomatch(exclude) : () => false\n const runnerOpts: Parameters<typeof createDebouncedRunner>[0] = { cwd }\n if (parallelCompile) runnerOpts.parallelCompile = true\n const debouncedRun = createDebouncedRunner(runnerOpts, delay)\n\n // Initial run\n debouncedRun()\n\n const watchDirs = extractWatchDirs(cwd, include)\n const watchers = watchDirs.map(dir =>\n watch(dir, { recursive: true }, (_event, filename) => {\n if (!filename) return\n if (!/\\.[jt]sx?$/.test(filename)) return\n if (filename.includes('node_modules') || filename.includes('.next')) return\n const full = resolve(dir, filename)\n if (full.startsWith(compiledDirResolved)) return\n if (isExcluded(filename)) return\n debouncedRun()\n }),\n )\n\n const cleanup = (): void => {\n for (const w of watchers) w.close()\n activeWatcher = null\n }\n\n activeWatcher = cleanup\n return cleanup\n}\n","import { existsSync } from 'node:fs'\nimport { resolve, dirname } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport type { WithFluentConfig } from './types'\nimport { resolveConfig } from './read-config'\nimport { generateServerModule } from './generate-server-module'\nimport { startDevWatcher } from './dev-watcher'\n\ntype NextConfig = Record<string, unknown>\n\n/**\n * Wrap your Next.js config with Fluenti support.\n *\n * Adds a webpack loader that transforms `t\\`\\`` and `t()` calls,\n * and generates a server module for RSC i18n.\n *\n * @example\n * ```ts\n * // next.config.ts — function style (recommended)\n * import { withFluenti } from '@fluenti/next'\n * export default withFluenti()({ reactStrictMode: true })\n * ```\n *\n * @example\n * ```ts\n * // next.config.ts — direct style\n * import { withFluenti } from '@fluenti/next'\n * export default withFluenti({ reactStrictMode: true })\n * ```\n */\nexport function withFluenti(fluentConfig?: WithFluentConfig): (nextConfig?: NextConfig) => NextConfig\nexport function withFluenti(nextConfig: NextConfig): NextConfig\nexport function withFluenti(\n configOrNext?: WithFluentConfig | NextConfig,\n): NextConfig | ((nextConfig?: NextConfig) => NextConfig) {\n if (configOrNext && !isFluentConfig(configOrNext as Record<string, unknown>)) {\n // Has keys but none are fluent-specific → treat as NextConfig\n return applyFluenti({}, configOrNext as NextConfig)\n }\n\n const fluentConfig = (configOrNext ?? {}) as WithFluentConfig\n return function wrappedConfig(nextConfig?: NextConfig): NextConfig {\n return applyFluenti(fluentConfig, nextConfig ?? {})\n }\n}\n\nfunction isFluentConfig(obj: Record<string, unknown>): boolean {\n const fluentOnlyKeys = [\n 'config', 'serverModule', 'serverModuleOutDir', 'resolveLocale',\n 'cookieName', 'loaderEnforce',\n ]\n return fluentOnlyKeys.some((key) => key in obj)\n}\n\nfunction applyFluenti(\n fluentConfig: WithFluentConfig,\n nextConfig: NextConfig,\n): NextConfig {\n const projectRoot = process.cwd()\n const resolved = resolveConfig(projectRoot, fluentConfig)\n const fluentiConfig = resolved.fluentiConfig\n const compiledDir = fluentiConfig.compileOutDir\n\n // Warn if compiled catalogs directory doesn't exist yet\n const compiledDirAbs = resolve(projectRoot, compiledDir)\n if (!existsSync(compiledDirAbs)) {\n console.warn(\n `\\n[fluenti] Compiled catalogs not found at ${compiledDir}.\\n` +\n `Run: npx fluenti extract && npx fluenti compile\\n`,\n )\n }\n\n // Generate server module for RSC\n const serverModulePath = generateServerModule(projectRoot, resolved)\n\n // Resolve the loader path — use import.meta.url for ESM compatibility\n const thisDir = typeof __dirname !== 'undefined'\n ? __dirname\n : dirname(fileURLToPath(import.meta.url))\n const loaderPath = resolve(thisDir, 'loader.js')\n\n const existingWebpack = nextConfig['webpack'] as\n | ((config: WebpackConfig, options: WebpackOptions) => WebpackConfig)\n | undefined\n\n let buildCompileRan = false\n\n // ── Turbopack config ──────────────────────────────────────────────\n // Turbopack loader-runner supports webpack loaders via turbopack.rules.\n // Use package name (not file path) — Turbopack resolves loaders as packages,\n // file paths trigger static analysis errors (TP1006) in the loader-runner.\n const fluentTurboRules = Object.fromEntries(\n ['*.ts', '*.tsx', '*.js', '*.jsx'].map((ext) => [\n ext,\n {\n condition: { not: 'foreign' },\n loaders: ['@fluenti/next/loader'],\n },\n ]),\n )\n\n // Turbopack resolveAlias requires relative paths (absolute paths get\n // misinterpreted as \"./abs/path\"). Use \"./\" + relative-from-cwd.\n const relativeServerModule = './' + serverModulePath\n .replace(projectRoot + '/', '')\n .replace(projectRoot + '\\\\', '')\n const fluentTurboAlias: Record<string, string> = {\n '@fluenti/next': relativeServerModule,\n }\n\n // ── Dev auto-compile via standalone watcher (works with both webpack & Turbopack) ──\n const isDev = process.env['NODE_ENV'] === 'development'\n || process.argv.some(a => a === 'dev')\n const devAutoCompile = fluentiConfig.devAutoCompile ?? true\n\n if (isDev && devAutoCompile) {\n const watcherOpts: Parameters<typeof startDevWatcher>[0] = {\n cwd: projectRoot,\n compiledDir,\n delay: fluentiConfig.devAutoCompileDelay ?? 1000,\n }\n if (fluentiConfig.parallelCompile) watcherOpts.parallelCompile = true\n if (fluentiConfig.include) watcherOpts.include = fluentiConfig.include\n if (fluentiConfig.exclude) watcherOpts.exclude = fluentiConfig.exclude\n startDevWatcher(watcherOpts)\n }\n\n return {\n ...nextConfig,\n turbopack: mergeTurbopackConfig(\n nextConfig['turbopack'] as Record<string, unknown> | undefined,\n { rules: fluentTurboRules, resolveAlias: fluentTurboAlias },\n ),\n webpack(config: WebpackConfig, options: WebpackOptions) {\n // Add fluenti loader\n const loaderEnforce = fluentConfig.loaderEnforce === undefined && !('loaderEnforce' in (fluentConfig as Record<string, unknown>))\n ? 'pre' as const\n : fluentConfig.loaderEnforce\n config.module.rules.push({\n test: /\\.[jt]sx?$/,\n ...(loaderEnforce ? { enforce: loaderEnforce } : {}),\n exclude: [/node_modules/, /\\.next/],\n use: [\n {\n loader: loaderPath,\n options: {\n serverModulePath,\n },\n },\n ],\n })\n\n // Add resolve alias so loader can import from generated server module\n config.resolve = config.resolve ?? {} as WebpackConfig['resolve']\n config.resolve.alias = config.resolve.alias ?? {}\n config.resolve.alias['@fluenti/next$'] = serverModulePath\n\n // Auto compile before production build via async beforeRun hook\n const buildAutoCompile = fluentiConfig.buildAutoCompile ?? true\n if (!options.dev && buildAutoCompile) {\n config.plugins = config.plugins ?? []\n config.plugins.push({\n apply(compiler: WebpackCompiler) {\n compiler.hooks.beforeRun.tapPromise('fluenti-compile', async () => {\n if (buildCompileRan) return\n buildCompileRan = true\n // Step 1: try to load @fluenti/cli — if not installed, skip silently\n let fluentCli: { runCompile: (cwd: string, opts?: { parallel?: boolean }) => Promise<void> }\n try {\n // @ts-expect-error — @fluenti/cli is an optional peer dependency\n fluentCli = await import('@fluenti/cli')\n } catch {\n // @fluenti/cli not installed — optional peer dep, nothing to do\n return\n }\n // Step 2: run compile — errors here mean compilation failed, let them surface\n await fluentCli.runCompile(projectRoot, fluentiConfig.parallelCompile ? { parallel: true } : undefined)\n })\n },\n })\n }\n\n // Call user's webpack config if provided\n if (existingWebpack) {\n return existingWebpack(config, options)\n }\n\n return config\n },\n }\n}\n\nfunction mergeTurbopackConfig(\n existing: Record<string, unknown> | undefined,\n fluenti: { rules: Record<string, unknown>; resolveAlias: Record<string, string> },\n): Record<string, unknown> {\n const base = existing ?? {}\n const userRules = (base['rules'] as Record<string, unknown>) ?? {}\n\n // Warn when user rules override fluenti's source-file rules\n const fluentKeys = Object.keys(fluenti.rules)\n const overlapping = fluentKeys.filter(k => k in userRules)\n if (overlapping.length > 0) {\n console.warn(\n `[fluenti] Your turbopack.rules override Fluenti's loader for: ${overlapping.join(', ')}.\\n` +\n ` Fluenti's t\\`\\` transform will NOT run on these file types.\\n` +\n ` If this is intentional, you can suppress this warning with { devAutoCompile: false }.`,\n )\n }\n\n return {\n ...base,\n rules: { ...fluenti.rules, ...userRules },\n resolveAlias: { ...fluenti.resolveAlias, ...(base['resolveAlias'] as Record<string, string>) },\n }\n}\n\n// Minimal webpack types for the config function\ninterface WebpackCompiler {\n hooks: {\n beforeRun: {\n tapPromise(name: string, cb: () => Promise<void>): void\n }\n }\n}\n\ninterface WebpackConfig {\n module: {\n rules: Array<Record<string, unknown>>\n }\n resolve: {\n alias?: Record<string, string>\n }\n plugins?: Array<{ apply(compiler: WebpackCompiler): void }>\n}\n\ninterface WebpackOptions {\n isServer: boolean\n dev: boolean\n}\n","/**\n * @fluenti/next — Next.js plugin for Fluenti\n *\n * Provides:\n * - `withFluenti()` — wraps next.config.ts with t`` transform support\n * - I18nProvider — async server component (exported from generated module)\n * - Webpack loader for strict, binding-aware tagged-template optimization\n *\n * @example\n * ```ts\n * // next.config.ts\n * import { withFluenti } from '@fluenti/next'\n * export default withFluenti()({ reactStrictMode: true })\n * ```\n *\n * @example\n * ```tsx\n * // app/layout.tsx — resolved by webpack alias to the generated module\n * import { I18nProvider } from '@fluenti/next'\n * ```\n */\nexport { withFluenti } from './with-fluenti'\nexport type { WithFluentConfig, I18nProviderProps } from './types'\n\n// ── Runtime stubs ────────────────────────────────────────────────────\n// TypeScript resolves types from this file (via package.json exports).\n// At runtime, webpack `resolve.alias` redirects `@fluenti/next$` to the\n// generated server module, so these stubs are never actually called in\n// a correctly configured project. They exist only to provide helpful\n// errors if `withFluenti()` is not configured.\n\nimport type { ReactNode, ReactElement } from 'react'\nimport type { CompileTimeT, FluentiCoreInstanceFull } from '@fluenti/core'\n\nconst NOT_CONFIGURED =\n '[fluenti] `withFluenti()` must be configured in next.config.ts before importing from \"@fluenti/next\".'\n\nfunction throwNotConfigured(): never {\n throw new Error(NOT_CONFIGURED)\n}\n\n/** @see Generated module for the real implementation. */\nexport const setLocale: (locale: string) => void = throwNotConfigured\n/** @see Generated module for the real implementation. */\nexport const getI18n: () => Promise<FluentiCoreInstanceFull & { locale: string }> = throwNotConfigured as () => Promise<FluentiCoreInstanceFull & { locale: string }>\n/** @see Generated module for the real implementation. */\nexport const t: CompileTimeT = throwNotConfigured as unknown as CompileTimeT\n/** @see Generated module for the real implementation. */\nexport const Trans: (props: { children: ReactNode; id?: string; context?: string; comment?: string; render?: (translation: ReactNode) => ReactNode }) => Promise<ReactElement> = throwNotConfigured as unknown as typeof Trans\n/** @see Generated module for the real implementation. */\nexport const Plural: (props: { value: number; id?: string; context?: string; comment?: string; zero?: ReactNode; one?: ReactNode; two?: ReactNode; few?: ReactNode; many?: ReactNode; other: ReactNode; offset?: number }) => Promise<ReactElement> = throwNotConfigured as unknown as typeof Plural\n/** @see Generated module for the real implementation. */\nexport const Select: (props: { value: string; id?: string; context?: string; comment?: string; other: ReactNode; options?: Record<string, ReactNode>; [key: string]: ReactNode | Record<string, ReactNode> | string | undefined }) => Promise<ReactElement> = throwNotConfigured as unknown as typeof Select\n/** @see Generated module for the real implementation. */\nexport const DateTime: (props: { value: Date | number; style?: string }) => Promise<ReactElement> = throwNotConfigured as unknown as typeof DateTime\n/** @see Generated module for the real implementation. */\nexport const NumberFormat: (props: { value: number; style?: string }) => Promise<ReactElement> = throwNotConfigured as unknown as typeof NumberFormat\n/** @see Generated module for the real implementation. */\nexport const I18nProvider: (props: { locale?: string; children: ReactNode }) => Promise<ReactElement> = throwNotConfigured as unknown as typeof I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GAAG;EACH,OAAO;GAAE,GAAG,EAAQ;GAAO,GAAG;GAAW;EACzC,cAAc;GAAE,GAAG,EAAQ;GAAc,GAAI,EAAK;GAA4C;EAC/F;;;;ACpLH,IAAM,IACJ;AAEF,SAAS,IAA4B;AACnC,OAAU,MAAM,EAAe;;AAIjC,IAAa,IAAsC,GAEtC,IAAuE,GAEvE,IAAkB,GAElB,IAAoK,GAEpK,IAAyO,GAEzO,IAAiP,GAEjP,IAAuF,GAEvF,IAAoF,GAEpF,IAA2F"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/read-config.ts","../src/generate-server-module.ts","../src/dev-runner.ts","../src/dev-watcher.ts","../src/with-fluenti.ts","../src/index.ts"],"sourcesContent":["import { loadConfigSync, DEFAULT_FLUENTI_CONFIG } from '@fluenti/core/config'\nimport type { FluentiBuildConfig } from '@fluenti/core/internal'\nimport type { WithFluentConfig, ResolvedFluentConfig } from './types'\n\n/**\n * Read fluenti.config.ts and merge with withFluenti() overrides.\n *\n * Delegates config file loading to `@fluenti/core`'s shared `loadConfigSync()`.\n */\nexport function resolveConfig(\n projectRoot: string,\n overrides?: WithFluentConfig,\n): ResolvedFluentConfig {\n let fluentiConfig: FluentiBuildConfig\n\n if (overrides?.config && typeof overrides.config === 'object') {\n // Inline config — merge with defaults\n fluentiConfig = { ...DEFAULT_FLUENTI_CONFIG, ...overrides.config }\n } else {\n // string path or auto-discover\n fluentiConfig = loadConfigSync(\n typeof overrides?.config === 'string' ? overrides.config : undefined,\n projectRoot,\n )\n }\n\n const serverModuleOutDir = overrides?.serverModuleOutDir ?? '.fluenti'\n const cookieName = overrides?.cookieName ?? 'locale'\n\n const resolved: ResolvedFluentConfig = {\n fluentiConfig,\n serverModule: overrides?.serverModule ?? null,\n serverModuleOutDir,\n cookieName,\n }\n if (overrides?.resolveLocale) resolved.resolveLocale = overrides.resolveLocale\n return resolved\n}\n","import { writeFileSync, mkdirSync, existsSync } from 'node:fs'\nimport { resolve, relative } from 'node:path'\nimport { validateLocale } from '@fluenti/core'\nimport { resolveLocaleCodes } from '@fluenti/core/internal'\nimport type { ResolvedFluentConfig } from './types'\n\n/** Wrapper around writeFileSync with a Fluenti-specific error message. */\nfunction writeSafe(path: string, content: string): void {\n try {\n writeFileSync(path, content, 'utf-8')\n } catch (err) {\n throw new Error(\n `[fluenti] Failed to write generated module at ${path}: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n}\n\n/**\n * Generate the server module that provides:\n * - setLocale / getI18n\n * - Trans / Plural / Select / DateTime / NumberFormat (server components)\n * - I18nProvider (async server component for layouts)\n *\n * @returns Absolute path to the generated server module.\n */\nexport function generateServerModule(\n projectRoot: string,\n config: ResolvedFluentConfig,\n): string {\n if (config.serverModule) {\n return resolve(projectRoot, config.serverModule)\n }\n\n const outDir = resolve(projectRoot, config.serverModuleOutDir)\n const outPath = resolve(outDir, 'server.js')\n const dtsPath = resolve(outDir, 'server.d.ts')\n\n if (!existsSync(outDir)) {\n mkdirSync(outDir, { recursive: true })\n }\n\n const locales = resolveLocaleCodes(config.fluentiConfig.locales)\n const defaultLocale = config.fluentiConfig.defaultLocale ?? config.fluentiConfig.sourceLocale\n const compiledDir = config.fluentiConfig.compileOutDir\n const fallbackChain = config.fluentiConfig.fallbackChain\n const dateFormats = config.fluentiConfig.dateFormats\n const numberFormats = config.fluentiConfig.numberFormats\n const cookieName = escapeJsSingleQuoted(config.cookieName)\n const defaultLocaleSafe = escapeJsSingleQuoted(defaultLocale)\n\n for (const locale of locales) {\n validateLocale(locale, 'next-plugin')\n }\n\n const compiledDirAbs = resolve(projectRoot, compiledDir)\n const compiledRelative = toForwardSlash(relative(outDir, compiledDirAbs))\n\n const localeImports = locales\n .map((locale) => ` case '${escapeJsSingleQuoted(locale)}': return import('${compiledRelative}/${locale}')`)\n .join('\\n')\n\n const fallbackChainStr = fallbackChain\n ? JSON.stringify(fallbackChain)\n : 'undefined'\n\n // Generate a 'use client' provider that imports messages statically.\n // Messages contain functions (interpolation) which can't cross the RSC boundary.\n const clientProviderPath = resolve(outDir, 'client-provider.js')\n\n const clientStaticImports = locales\n .map((locale) => {\n const safe = locale.replace(/[^a-zA-Z0-9]/g, '_')\n return `import ${safe} from '${compiledRelative}/${locale}'`\n })\n .join('\\n')\n\n const clientAllMessagesEntries = locales\n .map((locale) => {\n const safe = locale.replace(/[^a-zA-Z0-9]/g, '_')\n return `'${escapeJsSingleQuoted(locale)}': ${safe}`\n })\n .join(', ')\n\n const dateFormatsStr = dateFormats !== undefined ? JSON.stringify(dateFormats) : 'undefined'\n const numberFormatsStr = numberFormats !== undefined ? JSON.stringify(numberFormats) : 'undefined'\n\n const clientProviderSource = `\"use client\";\n// Auto-generated by @fluenti/next — do not edit\n// @ts-nocheck\nimport { createElement } from 'react'\nimport { I18nProvider } from '@fluenti/react'\n${clientStaticImports}\n\nconst __allMessages = { ${clientAllMessagesEntries} }\nconst __dateFormats = ${dateFormatsStr}\nconst __numberFormats = ${numberFormatsStr}\n\nexport function ClientI18nProvider({ locale, fallbackLocale, fallbackChain, children }) {\n return createElement(I18nProvider, { locale, fallbackLocale, messages: __allMessages, fallbackChain, dateFormats: __dateFormats, numberFormats: __numberFormats }, children)\n}\n`\n writeSafe(clientProviderPath, clientProviderSource)\n\n const clientProviderDtsPath = resolve(outDir, 'client-provider.d.ts')\n const clientProviderDtsSource = `// Auto-generated by @fluenti/next — do not edit\nimport type { ReactNode, ReactElement } from 'react'\n\nexport declare function ClientI18nProvider(props: {\n locale: string\n fallbackLocale: string\n fallbackChain?: Record<string, string[]>\n children: ReactNode\n}): ReactElement\n`\n writeSafe(clientProviderDtsPath, clientProviderDtsSource)\n\n const resolveLocaleImport = config.resolveLocale\n ? (() => {\n const absPath = resolve(projectRoot, config.resolveLocale)\n const relPath = toForwardSlash(relative(outDir, absPath))\n return `import __resolveLocale from '${relPath}'`\n })()\n : null\n\n const resolveLocaleFn = config.resolveLocale\n ? `resolveLocale: __resolveLocale,`\n : `resolveLocale: async () => {\n try {\n const { cookies, headers } = await import('next/headers')\n const [cookieStore, headerStore] = await Promise.all([cookies(), headers()])\n\n // 0. x-fluenti-locale header (set by createI18nMiddleware — most authoritative)\n const fromMiddleware = headerStore.get('x-fluenti-locale')\n if (fromMiddleware && __locales.includes(fromMiddleware)) return fromMiddleware\n\n // 1. Cookie (configurable name)\n const fromCookie = cookieStore.get('${cookieName}')?.value\n if (fromCookie && __locales.includes(fromCookie)) return fromCookie\n\n // 2. Accept-Language header\n const acceptLang = headerStore.get('accept-language')\n if (acceptLang) {\n for (const part of acceptLang.split(',')) {\n const lang = part.split(';')[0].trim()\n if (__locales.includes(lang)) return lang\n const prefix = lang.split('-')[0]\n const match = __locales.find(l => l === prefix || l.startsWith(prefix + '-'))\n if (match) return match\n }\n }\n\n return '${defaultLocaleSafe}'\n } catch {\n return '${defaultLocaleSafe}'\n }\n },`\n\n const localesArrayStr = JSON.stringify(locales)\n\n const moduleSource = `// Auto-generated by @fluenti/next — do not edit\n// @ts-nocheck\nimport { createServerI18n } from '@fluenti/react/server'\nimport { createElement } from 'react'\n${resolveLocaleImport ? `${resolveLocaleImport}\\n` : ''}\nconst __locales = ${localesArrayStr}\n\nconst serverI18n = createServerI18n({\n loadMessages: async (locale) => {\n switch (locale) {\n${localeImports}\n default: return import('${compiledRelative}/${defaultLocaleSafe}')\n }\n },\n fallbackLocale: '${defaultLocaleSafe}',\n fallbackChain: ${fallbackChainStr},\n ${resolveLocaleFn}\n})\n\nexport const setLocale = serverI18n.setLocale\nexport const getI18n = serverI18n.getI18n\nexport const t = (..._args) => {\n throw new Error(\n \"[fluenti] \\`t\\` imported from '@fluenti/next' is a compile-time API replaced at build time.\\\\n\" +\n ' Ensure:\\\\n' +\n ' 1. \\`withFluenti()\\` is configured in next.config.ts\\\\n' +\n ' 2. The file is inside src/ (not node_modules)\\\\n' +\n \" 3. For client components, import from '@fluenti/react'\",\n )\n}\nexport const Trans = serverI18n.Trans\nexport const Plural = serverI18n.Plural\nexport const Select = serverI18n.Select\nexport const DateTime = serverI18n.DateTime\nexport const NumberFormat = serverI18n.NumberFormat\n\n/**\n * Async server component for root layouts.\n *\n * Sets up both server-side (React.cache) and client-side (I18nProvider) i18n.\n */\nexport async function I18nProvider({ locale, children }) {\n const activeLocale = (locale && locale.trim()) ? locale : '${defaultLocaleSafe}'\n\n // 1. Initialize server-side i18n (React.cache scoped)\n serverI18n.setLocale(activeLocale)\n await serverI18n.getI18n()\n\n // 2. Import the local 'use client' provider that has messages statically bundled.\n // Messages contain functions (interpolation) which can't be serialized across the RSC boundary.\n const { ClientI18nProvider } = await import('./client-provider.js')\n\n return createElement(ClientI18nProvider, {\n locale: activeLocale,\n fallbackLocale: '${defaultLocaleSafe}',\n fallbackChain: ${fallbackChainStr},\n }, children)\n}\n`\n\n const dtsSource = `// Auto-generated by @fluenti/next — do not edit\nimport type { ReactNode, ReactElement } from 'react'\nimport type { CompileTimeT, FluentiCoreInstanceFull } from '@fluenti/core'\n\nexport declare function setLocale(locale: string): void\nexport declare function getI18n(): Promise<FluentiCoreInstanceFull & { locale: string }>\nexport declare const t: CompileTimeT\n\nexport declare function Trans(props: {\n children: ReactNode\n id?: string\n context?: string\n comment?: string\n render?: (translation: ReactNode) => ReactNode\n}): Promise<ReactElement>\n\nexport declare function Plural(props: {\n value: number\n id?: string\n context?: string\n comment?: string\n zero?: ReactNode\n one?: ReactNode\n two?: ReactNode\n few?: ReactNode\n many?: ReactNode\n other: ReactNode\n offset?: number\n}): Promise<ReactElement>\n\nexport declare function Select(props: {\n value: string\n id?: string\n context?: string\n comment?: string\n other: ReactNode\n options?: Record<string, ReactNode>\n [key: string]: ReactNode | Record<string, ReactNode> | string | undefined\n}): Promise<ReactElement>\n\nexport declare function DateTime(props: {\n value: Date | number\n format?: string\n}): Promise<ReactElement>\n\nexport declare function NumberFormat(props: {\n value: number\n format?: string\n}): Promise<ReactElement>\n\nexport declare function I18nProvider(props: {\n locale?: string\n children: ReactNode\n}): Promise<ReactElement>\n`\n\n writeSafe(outPath, moduleSource)\n writeSafe(dtsPath, dtsSource)\n\n // Generate Edge-safe i18n config for use in middleware\n const configModulePath = resolve(outDir, 'i18n-config.js')\n const configModuleDtsPath = resolve(outDir, 'i18n-config.d.ts')\n\n const configModuleSource = `// Auto-generated by @fluenti/next — do not edit\nexport const locales = ${localesArrayStr}\nexport const sourceLocale = '${defaultLocaleSafe}'\nexport const cookieName = '${cookieName}'\n`\n writeSafe(configModulePath, configModuleSource)\n\n const configModuleDtsSource = `// Auto-generated by @fluenti/next — do not edit\nexport declare const locales: string[]\nexport declare const sourceLocale: string\nexport declare const cookieName: string\n`\n writeSafe(configModuleDtsPath, configModuleDtsSource)\n\n return outPath\n}\n\n/** Escape a string for safe embedding inside a single-quoted JS string literal. */\nfunction escapeJsSingleQuoted(s: string): string {\n return s.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")\n}\n\nfunction toForwardSlash(p: string): string {\n return p.split('\\\\').join('/')\n}\n","import { join } from 'node:path'\nimport { createRequire } from 'node:module'\n\nexport interface DevRunnerOptions {\n cwd: string\n onSuccess?: () => void\n onError?: (err: Error) => void\n /** If true, reject the promise on failure instead of swallowing the error */\n throwOnError?: boolean\n /** Run only compile (skip extract). Useful for production builds where source is unchanged. */\n compileOnly?: boolean\n /** Enable parallel compilation across locales using worker threads */\n parallelCompile?: boolean\n}\n\n/**\n * Run compile in-process via `@fluenti/cli` (for compileOnly mode),\n * or extract + compile in dev mode. Requires `@fluenti/cli` to be installed\n * as a devDependency.\n */\nexport async function runExtractCompile(options: DevRunnerOptions): Promise<void> {\n if (options.compileOnly) {\n try {\n // Resolve @fluenti/cli from the project's cwd (not from this package's location)\n // using createRequire so pnpm's strict node_modules layout works correctly.\n // Use require() (not import()) to load @fluenti/cli — avoids CJS/ESM interop\n // issues when dynamic import() loads minified CJS with chunk requires.\n const projectRequire = createRequire(join(options.cwd, 'package.json'))\n const { runCompile } = projectRequire('@fluenti/cli')\n await runCompile(options.cwd)\n console.log('[fluenti] Compiling... done')\n options.onSuccess?.()\n return\n } catch (e) {\n const error = e instanceof Error ? e : new Error(String(e))\n if (options.throwOnError) throw error\n console.warn('[fluenti] Compile failed:', error.message)\n options.onError?.(error)\n return\n }\n }\n\n // Dev mode: run in-process extract + compile.\n // Step 1: load @fluenti/cli — if not installed, guide user to install it.\n // Step 2: run — errors here mean the CLI ran but failed; surface them.\n let fluentCli: { runExtract: (cwd: string) => Promise<void>; runCompile: (cwd: string, opts?: { parallel: boolean }) => Promise<void> } | null = null\n try {\n const projectRequire = createRequire(join(options.cwd, 'package.json'))\n fluentCli = projectRequire('@fluenti/cli')\n } catch {\n // @fluenti/cli not installed — will show install guide below\n }\n\n if (fluentCli) {\n try {\n await fluentCli.runExtract(options.cwd)\n if (options.parallelCompile) {\n await fluentCli.runCompile(options.cwd, { parallel: true })\n } else {\n await fluentCli.runCompile(options.cwd)\n }\n console.log('[fluenti] Extracting and compiling... done')\n options.onSuccess?.()\n return\n } catch (e) {\n const error = e instanceof Error ? e : new Error(String(e))\n if (options.throwOnError) throw error\n console.warn('[fluenti] Extract/compile failed:', error.message)\n options.onError?.(error)\n return\n }\n }\n\n const msg =\n '[fluenti] @fluenti/cli is required for auto-compile.\\n' +\n ' Install it as a devDependency:\\n' +\n ' pnpm add -D @fluenti/cli\\n' +\n ' See: https://fluenti.dev/start/introduction/'\n if (options.throwOnError) {\n throw new Error(msg)\n }\n console.warn(msg)\n options.onError?.(new Error(msg))\n}\n\n/**\n * Create a debounced runner that collapses rapid calls.\n *\n * - If called while idle, schedules a run after `delay` ms.\n * - If called while a run is in progress, marks a pending rerun.\n * - Never runs concurrently.\n */\nexport function createDebouncedRunner(\n options: DevRunnerOptions,\n delay = 300,\n): () => void {\n let timer: ReturnType<typeof setTimeout> | null = null\n let running = false\n let pendingRerun = false\n\n async function execute(): Promise<void> {\n running = true\n try {\n await runExtractCompile(options)\n } finally {\n running = false\n if (pendingRerun) {\n pendingRerun = false\n schedule()\n }\n }\n }\n\n function schedule(): void {\n if (timer !== null) {\n clearTimeout(timer)\n }\n timer = setTimeout(() => {\n timer = null\n if (running) {\n pendingRerun = true\n } else {\n execute()\n }\n }, delay)\n }\n\n return schedule\n}\n","import { watch } from 'node:fs'\nimport { resolve } from 'node:path'\nimport { createRequire } from 'node:module'\nimport { createDebouncedRunner } from './dev-runner'\n\nexport interface DevWatcherOptions {\n cwd: string\n compiledDir: string\n delay?: number\n /** Glob patterns from fluenti.config.ts `include` field */\n include?: string[]\n /** Glob patterns from fluenti.config.ts `exclude` field */\n exclude?: string[]\n /** Enable parallel compilation across locales using worker threads */\n parallelCompile?: boolean\n}\n\nlet activeWatcher: (() => void) | null = null\n\n/**\n * Extract watch directories from include glob patterns.\n *\n * Takes the static prefix before the first glob wildcard (`*`).\n * Falls back to `src` if no include patterns are provided.\n *\n * @example\n * extractWatchDirs('/proj', ['./src/**\\/*.tsx']) → ['/proj/src']\n * extractWatchDirs('/proj', ['./app/**\\/*.ts', './lib/**\\/*.ts']) → ['/proj/app', '/proj/lib']\n * extractWatchDirs('/proj', ['./**\\/*.ts']) → ['/proj']\n */\nexport function extractWatchDirs(cwd: string, include?: string[]): string[] {\n if (!include || include.length === 0) {\n return [resolve(cwd, 'src')]\n }\n\n const dirs = new Set<string>()\n for (const pattern of include) {\n const normalized = pattern.replace(/^\\.\\//, '')\n const staticPart = normalized.split('*')[0]!.replace(/\\/+$/, '')\n dirs.add(staticPart || '.')\n }\n return [...dirs].map(d => resolve(cwd, d))\n}\n\n/**\n * Start a standalone file watcher for dev auto-compile.\n *\n * Works independently of webpack/Turbopack — watches source directories\n * (inferred from `include` patterns) for changes and triggers\n * extract+compile via the debounced runner.\n *\n * Only one watcher is active at a time (guards against multiple `applyFluenti()` calls).\n *\n * @returns A cleanup function that stops the watcher.\n */\nexport function startDevWatcher(options: DevWatcherOptions): () => void {\n // Clean up previous watcher if one exists (e.g., dev server reload)\n if (activeWatcher) {\n activeWatcher()\n }\n\n const { cwd, compiledDir, delay = 1000, include, exclude, parallelCompile } = options\n const compiledDirResolved = resolve(cwd, compiledDir)\n const _require = createRequire(\n typeof __filename !== 'undefined' ? __filename : import.meta.url,\n )\n const picomatch = _require('picomatch') as (patterns: string[]) => (str: string) => boolean\n const isExcluded = exclude?.length ? picomatch(exclude) : () => false\n const runnerOpts: Parameters<typeof createDebouncedRunner>[0] = { cwd }\n if (parallelCompile) runnerOpts.parallelCompile = true\n const debouncedRun = createDebouncedRunner(runnerOpts, delay)\n\n // Initial run\n debouncedRun()\n\n const watchDirs = extractWatchDirs(cwd, include)\n const watchers = watchDirs.map(dir =>\n watch(dir, { recursive: true }, (_event, filename) => {\n if (!filename) return\n if (!/\\.[jt]sx?$/.test(filename)) return\n if (filename.includes('node_modules') || filename.includes('.next')) return\n const full = resolve(dir, filename)\n if (full.startsWith(compiledDirResolved)) return\n if (isExcluded(filename)) return\n debouncedRun()\n }),\n )\n\n const cleanup = (): void => {\n for (const w of watchers) w.close()\n activeWatcher = null\n }\n\n activeWatcher = cleanup\n return cleanup\n}\n","import { existsSync } from 'node:fs'\nimport { execSync } from 'node:child_process'\nimport { resolve, dirname, relative } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport type { WithFluentConfig } from './types'\nimport { resolveConfig } from './read-config'\nimport { generateServerModule } from './generate-server-module'\nimport { startDevWatcher } from './dev-watcher'\n\n// Use Record<string, any> to accept both Next 15's and 16's NextConfig types\n// (Next 16 removed the index signature from NextConfig)\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype NextConfig = Record<string, any>\n\n/**\n * Wrap your Next.js config with Fluenti support.\n *\n * Adds a webpack loader that transforms `t\\`\\`` and `t()` calls,\n * and generates a server module for RSC i18n.\n *\n * @example\n * ```ts\n * // next.config.ts — function style (recommended)\n * import { withFluenti } from '@fluenti/next'\n * export default withFluenti()({ reactStrictMode: true })\n * ```\n *\n * @example\n * ```ts\n * // next.config.ts — direct style\n * import { withFluenti } from '@fluenti/next'\n * export default withFluenti({ reactStrictMode: true })\n * ```\n */\nexport function withFluenti(fluentConfig?: WithFluentConfig): (nextConfig?: NextConfig) => NextConfig\nexport function withFluenti(nextConfig: NextConfig): NextConfig\nexport function withFluenti(\n configOrNext?: WithFluentConfig | NextConfig,\n): NextConfig | ((nextConfig?: NextConfig) => NextConfig) {\n if (configOrNext && !isFluentConfig(configOrNext as Record<string, unknown>)) {\n // Has keys but none are fluent-specific → treat as NextConfig\n return applyFluenti({}, configOrNext as NextConfig)\n }\n\n const fluentConfig = (configOrNext ?? {}) as WithFluentConfig\n return function wrappedConfig(nextConfig?: NextConfig): NextConfig {\n return applyFluenti(fluentConfig, nextConfig ?? {})\n }\n}\n\nfunction isFluentConfig(obj: Record<string, unknown>): boolean {\n const fluentOnlyKeys = [\n 'config', 'serverModule', 'serverModuleOutDir', 'resolveLocale',\n 'cookieName', 'loaderEnforce',\n ]\n return fluentOnlyKeys.some((key) => key in obj)\n}\n\nfunction applyFluenti(\n fluentConfig: WithFluentConfig,\n nextConfig: NextConfig,\n): NextConfig {\n const projectRoot = process.cwd()\n const resolved = resolveConfig(projectRoot, fluentConfig)\n const fluentiConfig = resolved.fluentiConfig\n const compiledDir = fluentiConfig.compileOutDir\n\n // Warn if compiled catalogs directory doesn't exist yet\n const compiledDirAbs = resolve(projectRoot, compiledDir)\n if (!existsSync(compiledDirAbs)) {\n console.warn(\n `\\n[fluenti] Compiled catalogs not found at ${compiledDir}.\\n` +\n `Run: npx fluenti extract && npx fluenti compile\\n`,\n )\n }\n\n // Generate server module for RSC\n const serverModulePath = generateServerModule(projectRoot, resolved)\n\n // Resolve the loader path — use import.meta.url for ESM compatibility\n const thisDir = typeof __dirname !== 'undefined'\n ? __dirname\n : dirname(fileURLToPath(import.meta.url))\n const loaderPath = resolve(thisDir, 'loader.js')\n\n const existingWebpack = nextConfig['webpack'] as\n | ((config: WebpackConfig, options: WebpackOptions) => WebpackConfig)\n | undefined\n\n let buildCompileRan = false\n\n // ── Turbopack config ──────────────────────────────────────────────\n // Turbopack loader-runner supports webpack loaders via turbopack.rules.\n // Use package name (not file path) — Turbopack resolves loaders as packages,\n // file paths trigger static analysis errors (TP1006) in the loader-runner.\n const fluentTurboRules = Object.fromEntries(\n ['*.ts', '*.tsx', '*.js', '*.jsx'].map((ext) => [\n ext,\n {\n condition: { not: 'foreign' },\n loaders: ['@fluenti/next/loader'],\n },\n ]),\n )\n\n // Turbopack resolveAlias requires relative paths (absolute paths get\n // misinterpreted as \"./abs/path\"). Use \"./\" + relative-from-cwd.\n const configModulePath = resolve(dirname(serverModulePath), 'i18n-config.js')\n const relativeServerModule = './' + relative(projectRoot, serverModulePath).split('\\\\').join('/')\n const relativeConfigModule = './' + relative(projectRoot, configModulePath).split('\\\\').join('/')\n const fluentTurboAlias: Record<string, string> = {\n '@fluenti/next': relativeServerModule,\n '@fluenti/next/i18n-config': relativeConfigModule,\n }\n\n // ── Build auto-compile (bundler-agnostic — runs at config time) ──\n const isDev = process.env['NODE_ENV'] === 'development'\n || process.argv.some(a => a === 'dev')\n const buildAutoCompile = fluentiConfig.buildAutoCompile ?? true\n\n if (!isDev && buildAutoCompile && !buildCompileRan) {\n buildCompileRan = true\n try {\n execSync(\n 'npx fluenti compile' + (fluentiConfig.parallelCompile ? ' --parallel' : ''),\n { cwd: projectRoot, stdio: 'inherit' },\n )\n } catch {\n // @fluenti/cli not installed or compile failed — user sees stdio output\n }\n }\n\n // ── Dev auto-compile via standalone watcher (works with both webpack & Turbopack) ──\n const devAutoCompile = fluentiConfig.devAutoCompile ?? true\n\n if (isDev && devAutoCompile) {\n const watcherOpts: Parameters<typeof startDevWatcher>[0] = {\n cwd: projectRoot,\n compiledDir,\n delay: fluentiConfig.devAutoCompileDelay ?? 1000,\n }\n if (fluentiConfig.parallelCompile) watcherOpts.parallelCompile = true\n if (fluentiConfig.include) watcherOpts.include = fluentiConfig.include\n if (fluentiConfig.exclude) watcherOpts.exclude = fluentiConfig.exclude\n startDevWatcher(watcherOpts)\n }\n\n return {\n ...nextConfig,\n turbopack: mergeTurbopackConfig(\n nextConfig['turbopack'] as Record<string, unknown> | undefined,\n { rules: fluentTurboRules, resolveAlias: fluentTurboAlias },\n ),\n webpack(config: WebpackConfig, options: WebpackOptions) {\n // Add fluenti loader\n const loaderEnforce = fluentConfig.loaderEnforce === undefined && !('loaderEnforce' in (fluentConfig as Record<string, unknown>))\n ? 'pre' as const\n : fluentConfig.loaderEnforce\n config.module.rules.push({\n test: /\\.[jt]sx?$/,\n ...(loaderEnforce ? { enforce: loaderEnforce } : {}),\n exclude: [/node_modules/, /\\.next/],\n use: [\n {\n loader: loaderPath,\n options: {\n serverModulePath,\n },\n },\n ],\n })\n\n // Add resolve alias so loader can import from generated server module\n config.resolve = config.resolve ?? {} as WebpackConfig['resolve']\n config.resolve.alias = config.resolve.alias ?? {}\n config.resolve.alias['@fluenti/next$'] = serverModulePath\n config.resolve.alias['@fluenti/next/i18n-config$'] = configModulePath\n\n // Call user's webpack config if provided\n if (existingWebpack) {\n return existingWebpack(config, options)\n }\n\n return config\n },\n }\n}\n\nfunction mergeTurbopackConfig(\n existing: Record<string, unknown> | undefined,\n fluenti: { rules: Record<string, unknown>; resolveAlias: Record<string, string> },\n): Record<string, unknown> {\n const base = existing ?? {}\n const userRules = (base['rules'] as Record<string, unknown>) ?? {}\n\n // Warn when user rules override fluenti's source-file rules\n const fluentKeys = Object.keys(fluenti.rules)\n const overlapping = fluentKeys.filter(k => k in userRules)\n if (overlapping.length > 0) {\n console.warn(\n `[fluenti] Your turbopack.rules override Fluenti's loader for: ${overlapping.join(', ')}.\\n` +\n ` Fluenti's t\\`\\` transform will NOT run on these file types.\\n` +\n ` If this is intentional, you can suppress this warning with { devAutoCompile: false }.`,\n )\n }\n\n return {\n ...base,\n rules: { ...fluenti.rules, ...userRules },\n resolveAlias: { ...fluenti.resolveAlias, ...(base['resolveAlias'] as Record<string, string>) },\n }\n}\n\n// Minimal webpack types for the config function\ninterface WebpackConfig {\n module: {\n rules: Array<Record<string, unknown>>\n }\n resolve: {\n alias?: Record<string, string>\n }\n}\n\ninterface WebpackOptions {\n isServer: boolean\n dev: boolean\n}\n","/**\n * @fluenti/next — Next.js plugin for Fluenti\n *\n * Provides:\n * - `withFluenti()` — wraps next.config.ts with t`` transform support\n * - I18nProvider — async server component (exported from generated module)\n * - Webpack loader for strict, binding-aware tagged-template optimization\n *\n * @example\n * ```ts\n * // next.config.ts\n * import { withFluenti } from '@fluenti/next'\n * export default withFluenti()({ reactStrictMode: true })\n * ```\n *\n * @example\n * ```tsx\n * // app/layout.tsx — resolved by webpack alias to the generated module\n * import { I18nProvider } from '@fluenti/next'\n * ```\n */\nexport { withFluenti } from './with-fluenti'\nexport type { WithFluentConfig, I18nProviderProps } from './types'\nexport { msg } from '@fluenti/react'\n\n// ── Runtime stubs ────────────────────────────────────────────────────\n// TypeScript resolves types from this file (via package.json exports).\n// At runtime, webpack `resolve.alias` redirects `@fluenti/next$` to the\n// generated server module, so these stubs are never actually called in\n// a correctly configured project. They exist only to provide helpful\n// errors if `withFluenti()` is not configured.\n\nimport type { ReactNode, ReactElement } from 'react'\nimport type { CompileTimeT, FluentiCoreInstanceFull } from '@fluenti/core'\n\nconst NOT_CONFIGURED =\n '[fluenti] `withFluenti()` must be configured in next.config.ts before importing from \"@fluenti/next\".'\n\nfunction throwNotConfigured(): never {\n throw new Error(NOT_CONFIGURED)\n}\n\n/** @see Generated module for the real implementation. */\nexport const setLocale: (locale: string) => void = throwNotConfigured\n/** @see Generated module for the real implementation. */\nexport const getI18n: () => Promise<FluentiCoreInstanceFull & { locale: string }> = throwNotConfigured as () => Promise<FluentiCoreInstanceFull & { locale: string }>\n/** @see Generated module for the real implementation. */\nexport const t: CompileTimeT = throwNotConfigured as unknown as CompileTimeT\n/** @see Generated module for the real implementation. */\nexport const Trans: (props: { children: ReactNode; id?: string; context?: string; comment?: string; render?: (translation: ReactNode) => ReactNode }) => Promise<ReactElement> = throwNotConfigured as unknown as typeof Trans\n/** @see Generated module for the real implementation. */\nexport const Plural: (props: { value: number; id?: string; context?: string; comment?: string; zero?: ReactNode; one?: ReactNode; two?: ReactNode; few?: ReactNode; many?: ReactNode; other: ReactNode; offset?: number }) => Promise<ReactElement> = throwNotConfigured as unknown as typeof Plural\n/** @see Generated module for the real implementation. */\nexport const Select: (props: { value: string; id?: string; context?: string; comment?: string; other: ReactNode; options?: Record<string, ReactNode>; [key: string]: ReactNode | Record<string, ReactNode> | string | undefined }) => Promise<ReactElement> = throwNotConfigured as unknown as typeof Select\n/** @see Generated module for the real implementation. */\nexport const DateTime: (props: { value: Date | number; style?: string }) => Promise<ReactElement> = throwNotConfigured as unknown as typeof DateTime\n/** @see Generated module for the real implementation. */\nexport const NumberFormat: (props: { value: number; style?: string }) => Promise<ReactElement> = throwNotConfigured as unknown as typeof NumberFormat\n/** @see Generated module for the real implementation. */\nexport const I18nProvider: (props: { locale?: string; children: ReactNode }) => Promise<ReactElement> = throwNotConfigured as unknown as typeof I18nProvider\n"],"mappings":";;;;;;;;;;AASA,SAAgB,EACd,GACA,GACsB;CACtB,IAAI;AAEJ,CAKE,IALE,GAAW,UAAU,OAAO,EAAU,UAAW,WAEnC;EAAE,GAAG;EAAwB,GAAG,EAAU;EAAQ,GAGlD,EACd,OAAO,GAAW,UAAW,WAAW,EAAU,SAAS,KAAA,GAC3D,EACD;CAGH,IAAM,IAAqB,GAAW,sBAAsB,YACtD,IAAa,GAAW,cAAc,UAEtC,IAAiC;EACrC;EACA,cAAc,GAAW,gBAAgB;EACzC;EACA;EACD;AAED,QADI,GAAW,kBAAe,EAAS,gBAAgB,EAAU,gBAC1D;;;;AC7BT,SAAS,EAAU,GAAc,GAAuB;AACtD,KAAI;AACF,IAAc,GAAM,GAAS,QAAQ;UAC9B,GAAK;AACZ,QAAU,MACR,iDAAiD,EAAK,IAAI,aAAe,QAAQ,EAAI,UAAU,OAAO,EAAI,GAC3G;;;AAYL,SAAgB,EACd,GACA,GACQ;AACR,KAAI,EAAO,aACT,QAAO,EAAQ,GAAa,EAAO,aAAa;CAGlD,IAAM,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GAEtC,IAAuE,GAEvE,IAAkB,GAElB,IAAoK,GAEpK,IAAyO,GAEzO,IAAiP,GAEjP,IAAuF,GAEvF,IAAoF,GAEpF,IAA2F"}
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=`x-fluenti-locale`;function t(t){let{NextResponse:r}=t,i=t.locales??[`en`],a=t.sourceLocale??`en`,o=t.cookieName??`locale`,s=t.localePrefix??`as-needed`;return function(t){let c=i,l=a,{pathname:u}=t.nextUrl,d=u.split(`/`),f=d[1]??``,p=c.includes(f)?f:null,m;m=p||n(t,c,l,o);let h=new Headers(t.headers);if(h.set(e,m),!p&&(s===`always`||m!==l)){let n=new URL(`/${m}${u}${t.nextUrl.search}`,t.url),i=r.redirect(n);return i.headers.set(e,m),i}if(s===`as-needed`&&p===l){let n=`/`+d.slice(2).join(`/`),i=new URL(`${n}${t.nextUrl.search}`,t.url),a=r.rewrite(i,{request:{headers:h}});return a.headers.set(e,m),a}let g=r.next({request:{headers:h}});return g.headers.set(e,m),g}}function n(e,t,n,r){let i=e.cookies.get(r)?.value;if(i&&t.includes(i))return i;let a=e.headers.get(`accept-language`);if(a)for(let e of a.split(`,`)){let n=e.split(`;`)[0].trim();if(t.includes(n))return n;let r=n.split(`-`)[0],i=t.find(e=>e===r||e.startsWith(r+`-`));if(i)return i}return n}exports.LOCALE_HEADER=e,exports.createI18nMiddleware=t;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require(`@fluenti/next/i18n-config`);var t=`x-fluenti-locale`;function n(n){let{NextResponse:o}=n,s=n.locales??e.locales,c=n.sourceLocale??e.sourceLocale,l=n.cookieName??e.cookieName,u=n.localePrefix??`as-needed`,d=n.rewriteDefaultLocale??!1,f=n.setCookie??!1;return function(e){let p=s,m=c,{pathname:h,search:g}=e.nextUrl,_=e.nextUrl.basePath??``,v=h.split(`/`),y=r(v[1]??``,p),b;if(y)b=y;else{let t=n.detectLocale?.(e);b=t!==void 0&&r(t,p)!==null?r(t,p):a(e,p,m,l)}let x=new Headers(e.headers);if(x.set(t,b),!y&&(u===`always`||b!==m)){let n=new URL(`${_}/${b}${h}${g}`,e.url),r=o.redirect(n);return r.headers.set(t,b),i(r,e,b,l,f,y),r}if(!y&&b===m&&d){let n=new URL(`${_}/${m}${h}${g}`,e.url),r=o.rewrite(n,{request:{headers:x}});return r.headers.set(t,b),i(r,e,b,l,f,y),r}if(u===`as-needed`&&y===m){let n=(`/`+v.slice(2).join(`/`)).replace(/\/+/g,`/`);if(d){let r=new URL(`${_}${n}${g}`,e.url),i=o.redirect(r);return i.headers.set(t,b),i}let r=new URL(`${_}${n}${g}`,e.url),i=o.rewrite(r,{request:{headers:x}});return i.headers.set(t,b),i}let S=o.next({request:{headers:x}});return S.headers.set(t,b),i(S,e,b,l,f,y),S}}function r(e,t){if(!e)return null;let n=e.toLowerCase();return t.find(e=>e.toLowerCase()===n)??null}function i(e,t,n,r,i,a){!i||a||t.cookies.get(r)?.value!==n&&e.headers.set(`set-cookie`,`${r}=${n};path=/;max-age=31536000;samesite=lax`)}function a(e,t,n,i){let a=e.cookies.get(i)?.value;if(a){let e=r(a,t);if(e)return e}let o=e.headers.get(`accept-language`);if(o)for(let e of o.split(`,`)){let n=e.split(`;`)[0].trim(),i=r(n,t);if(i)return i;let a=n.split(`-`)[0].toLowerCase(),o=t.find(e=>{let t=e.toLowerCase();return t===a||t.startsWith(a+`-`)});if(o)return o}return n}exports.LOCALE_HEADER=t,exports.createI18nMiddleware=n;
2
2
  //# sourceMappingURL=middleware.cjs.map