@fluenti/next 0.4.0-rc.4 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-DyIg6Wiv.js +7 -0
- package/dist/i18n-config.cjs +1 -1
- package/dist/i18n-config.cjs.map +1 -1
- package/dist/index.cjs +69 -41
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +188 -124
- package/dist/index.js.map +1 -1
- package/dist/loader.cjs +1 -1
- package/dist/loader.cjs.map +1 -1
- package/dist/loader.js +5 -0
- package/dist/loader.js.map +1 -1
- package/dist/middleware.cjs +1 -1
- package/dist/middleware.cjs.map +1 -1
- package/dist/middleware.js +66 -71
- package/dist/middleware.js.map +1 -1
- package/dist/navigation.cjs +1 -1
- package/dist/navigation.cjs.map +1 -1
- package/dist/navigation.js +61 -63
- package/dist/navigation.js.map +1 -1
- package/dist/{client-provider.d.ts → packages/next-plugin/src/client-provider.d.ts} +1 -1
- package/dist/packages/next-plugin/src/client-provider.d.ts.map +1 -0
- package/dist/packages/next-plugin/src/create-navigation.d.ts.map +1 -0
- package/dist/packages/next-plugin/src/dev-runner.d.ts.map +1 -0
- package/dist/packages/next-plugin/src/dev-watcher.d.ts.map +1 -0
- package/dist/packages/next-plugin/src/generate-server-module.d.ts.map +1 -0
- package/dist/packages/next-plugin/src/i18n-config.d.ts.map +1 -0
- package/dist/{index.d.ts → packages/next-plugin/src/index.d.ts} +32 -29
- package/dist/packages/next-plugin/src/index.d.ts.map +1 -0
- package/dist/packages/next-plugin/src/middleware.d.ts.map +1 -0
- package/dist/{navigation.d.ts → packages/next-plugin/src/navigation.d.ts} +2 -2
- package/dist/packages/next-plugin/src/navigation.d.ts.map +1 -0
- package/dist/packages/next-plugin/src/provider.d.ts.map +1 -0
- package/dist/packages/next-plugin/src/read-config.d.ts.map +1 -0
- package/dist/packages/next-plugin/src/routing.d.ts.map +1 -0
- package/dist/packages/next-plugin/src/server.d.ts.map +1 -0
- package/dist/{types.d.ts → packages/next-plugin/src/types.d.ts} +11 -1
- package/dist/packages/next-plugin/src/types.d.ts.map +1 -0
- package/dist/packages/next-plugin/src/with-fluenti.d.ts.map +1 -0
- package/dist/packages/next-plugin/src/with-locale.d.ts.map +1 -0
- package/dist/provider.cjs +1 -1
- package/dist/provider.cjs.map +1 -1
- package/dist/routing-CRln5Gw7.js +65 -0
- package/dist/routing-CRln5Gw7.js.map +1 -0
- package/dist/routing-D4p8HvMH.cjs +2 -0
- package/dist/routing-D4p8HvMH.cjs.map +1 -0
- package/dist/server.cjs +1 -1
- package/dist/server.cjs.map +1 -1
- package/package.json +16 -16
- package/dist/client-provider.d.ts.map +0 -1
- package/dist/create-navigation.d.ts.map +0 -1
- package/dist/dev-runner.d.ts.map +0 -1
- package/dist/dev-watcher.d.ts.map +0 -1
- package/dist/generate-server-module.d.ts.map +0 -1
- package/dist/i18n-config.d.ts.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/middleware.d.ts.map +0 -1
- package/dist/navigation.d.ts.map +0 -1
- package/dist/provider.d.ts.map +0 -1
- package/dist/read-config.d.ts.map +0 -1
- package/dist/routing-DBVu_7tk.js +0 -72
- package/dist/routing-DBVu_7tk.js.map +0 -1
- package/dist/routing-Dy57-Uao.cjs +0 -2
- package/dist/routing-Dy57-Uao.cjs.map +0 -1
- package/dist/routing.d.ts.map +0 -1
- package/dist/server.d.ts.map +0 -1
- package/dist/types.d.ts.map +0 -1
- package/dist/with-fluenti.d.ts.map +0 -1
- package/dist/with-locale.d.ts.map +0 -1
- /package/dist/{create-navigation.d.ts → packages/next-plugin/src/create-navigation.d.ts} +0 -0
- /package/dist/{dev-runner.d.ts → packages/next-plugin/src/dev-runner.d.ts} +0 -0
- /package/dist/{dev-watcher.d.ts → packages/next-plugin/src/dev-watcher.d.ts} +0 -0
- /package/dist/{generate-server-module.d.ts → packages/next-plugin/src/generate-server-module.d.ts} +0 -0
- /package/dist/{i18n-config.d.ts → packages/next-plugin/src/i18n-config.d.ts} +0 -0
- /package/dist/{middleware.d.ts → packages/next-plugin/src/middleware.d.ts} +0 -0
- /package/dist/{provider.d.ts → packages/next-plugin/src/provider.d.ts} +0 -0
- /package/dist/{read-config.d.ts → packages/next-plugin/src/read-config.d.ts} +0 -0
- /package/dist/{routing.d.ts → packages/next-plugin/src/routing.d.ts} +0 -0
- /package/dist/{server.d.ts → packages/next-plugin/src/server.d.ts} +0 -0
- /package/dist/{with-fluenti.d.ts → packages/next-plugin/src/with-fluenti.d.ts} +0 -0
- /package/dist/{with-locale.d.ts → packages/next-plugin/src/with-locale.d.ts} +0 -0
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 if (!overrides?.config && overrides?.locales) {\n // Locales shorthand — build inline config with just locales\n fluentiConfig = { ...DEFAULT_FLUENTI_CONFIG, locales: overrides.locales }\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'\nimport { interpolate as __interpolate } from '@fluenti/core/internal'\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, interpolate: __interpolate }, 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'\nimport { interpolate as __interpolate } from '@fluenti/core/internal'\n${resolveLocaleImport ? `${resolveLocaleImport}\\n` : ''}\nconst __locales = ${localesArrayStr}\n\nconst serverI18n = createServerI18n({\n interpolate: __interpolate,\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\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/'/g, \"\\\\'\")\n .replace(/\\n/g, '\\\\n')\n .replace(/\\r/g, '\\\\r')\n .replace(/\\0/g, '\\\\0')\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, mkdirSync } 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 Minimal — no fluenti.config.ts needed\n * ```ts\n * import { withFluenti } from '@fluenti/next'\n * export default withFluenti({ locales: ['en', 'ja'] })({ reactStrictMode: true })\n * ```\n *\n * @example With fluenti.config.ts (advanced)\n * ```ts\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', 'locales', '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 // Auto-create compiled catalogs directory if missing\n const compiledDirAbs = resolve(projectRoot, compiledDir)\n if (!existsSync(compiledDirAbs)) {\n mkdirSync(compiledDirAbs, { recursive: true })\n }\n\n // Auto-detect app/[locale]/ directory structure\n // If detected and rewriteDefaultLocale not explicitly set, enable it automatically\n const appLocaleDir = resolve(projectRoot, 'app', '[locale]')\n const srcAppLocaleDir = resolve(projectRoot, 'src', 'app', '[locale]')\n if (existsSync(appLocaleDir) || existsSync(srcAppLocaleDir)) {\n if (!('rewriteDefaultLocale' in (fluentConfig as Record<string, unknown>))) {\n // Auto-enable rewriteDefaultLocale when app/[locale]/ is detected\n (resolved as { _autoRewriteDefaultLocale?: boolean })._autoRewriteDefaultLocale = true\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 // Detect Next.js version to use correct Turbopack config key\n // Next 15+: top-level `turbopack` key\n // Next 14: `experimental.turbo` key\n let nextMajor = 15\n try {\n const nextPkg = require('next/package.json') as { version?: string }\n if (nextPkg.version) nextMajor = parseInt(nextPkg.version.split('.')[0]!, 10) || 15\n } catch { /* next not resolvable at config time */ }\n\n const turboConfig = mergeTurbopackConfig(\n (nextMajor >= 15\n ? nextConfig['turbopack']\n : (nextConfig['experimental'] as Record<string, unknown> | undefined)?.['turbo']\n ) as Record<string, unknown> | undefined,\n { rules: fluentTurboRules, resolveAlias: fluentTurboAlias },\n )\n\n const turboKey = nextMajor >= 15\n ? { turbopack: turboConfig }\n : { experimental: { ...(nextConfig['experimental'] as Record<string, unknown> ?? {}), turbo: turboConfig } }\n\n return {\n ...nextConfig,\n ...turboKey,\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 { defineRouting } from './routing'\nexport type { RoutingConfig } from './routing'\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,CAQE,IARE,GAAW,UAAU,OAAO,EAAU,UAAW,WAEnC;EAAE,GAAG;EAAwB,GAAG,EAAU;EAAQ,GACzD,CAAC,GAAW,UAAU,GAAW,UAE1B;EAAE,GAAG;EAAwB,SAAS,EAAU;EAAS,GAGzD,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;;;;AChCT,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,IAAS,EAAQ,GAAa,EAAO,mBAAmB,EACxD,IAAU,EA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,MAAM,oBAAoB,GACzC,EAAO,QAAQ,MAAM,gCAAgC,GAGjD,IACK,EAAgB,GAAQ,EAAQ,GAGlC;;EAEV;;AAGH,SAAS,EACP,GACA,GACyB;CACzB,IAAM,IAAO,KAAY,EAAE,EACrB,IAAa,EAAK,SAAwC,EAAE,EAI5D,IADa,OAAO,KAAK,EAAQ,MAAM,CACd,QAAO,MAAK,KAAK,EAAU;AAS1D,QARI,EAAY,SAAS,KACvB,QAAQ,KACN,iEAAiE,EAAY,KAAK,KAAK,CAAC,2JAGzF,EAGI;EACL,GAAG;EACH,OAAO;GAAE,GAAG,EAAQ;GAAO,GAAG;GAAW;EACzC,cAAc;GAAE,GAAG,EAAQ;GAAc,GAAI,EAAK;GAA4C;EAC/F;;;;GCnN2B;AAc9B,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/compiler'\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 if (!overrides?.config && overrides?.locales) {\n // Locales shorthand — build inline config with just locales\n fluentiConfig = { ...DEFAULT_FLUENTI_CONFIG, locales: overrides.locales }\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 const runtimeInterpolate = overrides?.runtimeInterpolate ?? true\n\n const resolved: ResolvedFluentConfig = {\n fluentiConfig,\n serverModule: overrides?.serverModule ?? null,\n serverModuleOutDir,\n cookieName,\n runtimeInterpolate,\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/compiler'\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 cookieNameLiteral = toSingleQuotedJsString(config.cookieName)\n const defaultLocaleLiteral = toSingleQuotedJsString(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 ${toSingleQuotedJsString(locale)}: return import(${toSingleQuotedJsString(`${compiledRelative}/${locale}`)})`)\n .join('\\n')\n\n const fallbackChainStr = fallbackChain\n ? JSON.stringify(fallbackChain)\n : 'undefined'\n\n const clientProviderPath = resolve(outDir, 'client-provider.js')\n const dateFormatsStr = dateFormats !== undefined ? JSON.stringify(dateFormats) : 'undefined'\n const numberFormatsStr = numberFormats !== undefined ? JSON.stringify(numberFormats) : 'undefined'\n const runtimeInterpolateImport = config.runtimeInterpolate\n ? \"import { interpolate as __interpolate } from '@fluenti/core/runtime'\\n\"\n : ''\n const runtimeInterpolateProp = config.runtimeInterpolate ? ', interpolate: __interpolate' : ''\n const runtimeInterpolateServerOption = config.runtimeInterpolate ? ' interpolate: __interpolate,\\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${runtimeInterpolateImport}\nconst __dateFormats = ${dateFormatsStr}\nconst __numberFormats = ${numberFormatsStr}\n\nexport function ClientI18nProvider({ locale, fallbackLocale, messages, loadMessages, fallbackChain, children }) {\n return createElement(I18nProvider, { locale, fallbackLocale, messages, loadMessages, fallbackChain, dateFormats: __dateFormats, numberFormats: __numberFormats${runtimeInterpolateProp} }, 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'\nimport type { AllMessages, Messages } from '@fluenti/core'\n\nexport declare function ClientI18nProvider(props: {\n locale: string\n fallbackLocale: string\n messages: AllMessages\n loadMessages: (locale: string) => Promise<Messages | { default: Messages }>\n fallbackChain?: Record<string, string[]>\n children: ReactNode\n}): ReactElement\n`\n writeSafe(clientProviderDtsPath, clientProviderDtsSource)\n\n for (const locale of locales) {\n const clientLocaleProviderPath = resolve(outDir, getClientProviderModuleName(locale))\n const initialLocales = collectInitialClientLocales(locale, defaultLocale, fallbackChain, locales)\n const staticImports = initialLocales\n .map((initialLocale) => `import ${toLocaleBindingName(initialLocale)} from ${toSingleQuotedJsString(`${compiledRelative}/${initialLocale}`)}`)\n .join('\\n')\n const initialMessageEntries = initialLocales\n .map((initialLocale) => `${toSingleQuotedJsString(initialLocale)}: ${toLocaleBindingName(initialLocale)}`)\n .join(', ')\n const loaderCases = locales\n .map((candidateLocale) => {\n const modulePath = toSingleQuotedJsString(`${compiledRelative}/${candidateLocale}`)\n if (initialLocales.includes(candidateLocale)) {\n return ` case ${toSingleQuotedJsString(candidateLocale)}: return ${toLocaleBindingName(candidateLocale)}`\n }\n return ` case ${toSingleQuotedJsString(candidateLocale)}: return import(${modulePath})`\n })\n .join('\\n')\n\n const clientLocaleProviderSource = `\"use client\";\n// Auto-generated by @fluenti/next — do not edit\n// @ts-nocheck\nimport { createElement } from 'react'\nimport { ClientI18nProvider as __FluentiClientI18nProvider } from './client-provider.js'\n${staticImports}\n\nconst __messages = { ${initialMessageEntries} }\n\nasync function __loadMessages(locale) {\n switch (locale) {\n${loaderCases}\n default: return import(${toSingleQuotedJsString(`${compiledRelative}/${defaultLocale}`)})\n }\n}\n\nexport function ClientI18nProvider({ locale, fallbackLocale, fallbackChain, children }) {\n return createElement(__FluentiClientI18nProvider, { locale, fallbackLocale, messages: __messages, loadMessages: __loadMessages, fallbackChain }, children)\n}\n`\n\n writeSafe(clientLocaleProviderPath, clientLocaleProviderSource)\n }\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 ${toSingleQuotedJsString(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(${cookieNameLiteral})?.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 ${defaultLocaleLiteral}\n } catch {\n return ${defaultLocaleLiteral}\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${runtimeInterpolateImport}${resolveLocaleImport ? `${resolveLocaleImport}\\n` : ''}\nconst __locales = ${localesArrayStr}\n\nconst serverI18n = createServerI18n({\n${runtimeInterpolateServerOption} loadMessages: async (locale) => {\n switch (locale) {\n${localeImports}\n default: return import(${toSingleQuotedJsString(`${compiledRelative}/${defaultLocale}`)})\n }\n },\n fallbackLocale: ${defaultLocaleLiteral},\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 : ${defaultLocaleLiteral}\n\n // 1. Initialize server-side i18n (React.cache scoped)\n serverI18n.setLocale(activeLocale)\n await serverI18n.getI18n()\n\n // 2. Import the locale-specific client provider chunk. It eagerly bundles the\n // active locale plus only the fallback locales relevant to that locale.\n const { ClientI18nProvider } = await (async () => {\n switch (activeLocale) {\n${locales\n .map((locale) => ` case ${toSingleQuotedJsString(locale)}: return import(${toSingleQuotedJsString(`./${getClientProviderModuleName(locale)}`)})`)\n .join('\\n')}\n default: return import(${toSingleQuotedJsString(`./${getClientProviderModuleName(defaultLocale)}`)})\n }\n })()\n\n return createElement(ClientI18nProvider, {\n locale: activeLocale,\n fallbackLocale: ${defaultLocaleLiteral},\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 = ${defaultLocaleLiteral}\nexport const cookieName = ${cookieNameLiteral}\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/** Quote a string for safe embedding inside generated single-quoted JS source. */\nfunction toSingleQuotedJsString(s: string): string {\n return `'${s\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/'/g, \"\\\\'\")\n .replace(/\\n/g, '\\\\n')\n .replace(/\\r/g, '\\\\r')\n .replace(/\\0/g, '\\\\0')}'`\n}\n\nfunction toForwardSlash(p: string): string {\n return p.split('\\\\').join('/')\n}\n\nfunction getClientProviderModuleName(locale: string): string {\n return `client-provider-${locale.replace(/[^a-zA-Z0-9]/g, '_')}.js`\n}\n\nfunction toLocaleBindingName(locale: string): string {\n return `__messages_${locale.replace(/[^a-zA-Z0-9]/g, '_')}`\n}\n\nfunction collectInitialClientLocales(\n locale: string,\n defaultLocale: string,\n fallbackChain: Record<string, readonly string[]> | undefined,\n locales: readonly string[],\n): string[] {\n const result = new Set<string>([locale, defaultLocale])\n const localeFallbacks = fallbackChain?.[locale] ?? []\n for (const fallbackLocale of localeFallbacks) {\n if (locales.includes(fallbackLocale)) {\n result.add(fallbackLocale)\n }\n }\n return Array.from(result)\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, mkdirSync } from 'node:fs'\nimport { execSync } from 'node:child_process'\nimport { createRequire } from 'node:module'\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 Minimal — no fluenti.config.ts needed\n * ```ts\n * import { withFluenti } from '@fluenti/next'\n * export default withFluenti({ locales: ['en', 'ja'] })({ reactStrictMode: true })\n * ```\n *\n * @example With fluenti.config.ts (advanced)\n * ```ts\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', 'locales', 'serverModule', 'serverModuleOutDir', 'resolveLocale',\n 'cookieName', 'runtimeInterpolate', '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 // Auto-create compiled catalogs directory if missing\n const compiledDirAbs = resolve(projectRoot, compiledDir)\n if (!existsSync(compiledDirAbs)) {\n mkdirSync(compiledDirAbs, { recursive: true })\n }\n\n // Auto-detect app/[locale]/ directory structure\n // If detected and rewriteDefaultLocale not explicitly set, enable it automatically\n const appLocaleDir = resolve(projectRoot, 'app', '[locale]')\n const srcAppLocaleDir = resolve(projectRoot, 'src', 'app', '[locale]')\n if (existsSync(appLocaleDir) || existsSync(srcAppLocaleDir)) {\n if (!('rewriteDefaultLocale' in (fluentConfig as Record<string, unknown>))) {\n // Auto-enable rewriteDefaultLocale when app/[locale]/ is detected\n (resolved as { _autoRewriteDefaultLocale?: boolean })._autoRewriteDefaultLocale = true\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 // Resolve the CLI entry via Node module resolution so it works\n // in all package managers (pnpm, npm, yarn) without npx fallback\n const req = createRequire(resolve(projectRoot, 'noop.js'))\n const cliBin = resolve(dirname(req.resolve('@fluenti/cli')), 'cli.js')\n execSync(\n `node \"${cliBin}\" compile` + (fluentiConfig.parallelCompile ? ' --parallel' : ''),\n { cwd: projectRoot, stdio: 'inherit' },\n )\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error)\n throw new Error(\n `[fluenti] Production auto-compile failed. ` +\n `Run \"fluenti compile\" successfully before continuing the Next.js build.\\n` +\n ` ${detail}`,\n )\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 // Detect Next.js version to use correct Turbopack config key\n // Next 15+: top-level `turbopack` key\n // Next 14: `experimental.turbo` key\n let nextMajor = 15\n try {\n const nextPkg = require('next/package.json') as { version?: string }\n if (nextPkg.version) nextMajor = parseInt(nextPkg.version.split('.')[0]!, 10) || 15\n } catch { /* next not resolvable at config time */ }\n\n const turboConfig = mergeTurbopackConfig(\n (nextMajor >= 15\n ? nextConfig['turbopack']\n : (nextConfig['experimental'] as Record<string, unknown> | undefined)?.['turbo']\n ) as Record<string, unknown> | undefined,\n { rules: fluentTurboRules, resolveAlias: fluentTurboAlias },\n )\n\n const turboKey = nextMajor >= 15\n ? { turbopack: turboConfig }\n : { experimental: { ...(nextConfig['experimental'] as Record<string, unknown> ?? {}), turbo: turboConfig } }\n\n return {\n ...nextConfig,\n ...turboKey,\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 { defineRouting } from './routing'\nexport type { RoutingConfig } from './routing'\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'\nimport type { I18nProviderProps } from './types'\n\ninterface NextTransProps {\n children: ReactNode\n id?: string\n context?: string\n comment?: string\n render?: (translation: ReactNode) => ReactNode\n}\n\ninterface NextPluralProps {\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}\n\ninterface NextSelectProps {\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}\n\ninterface NextDateTimeProps {\n value: Date | number\n style?: string\n}\n\ninterface NextNumberFormatProps {\n value: number\n style?: string\n}\n\nconst NOT_CONFIGURED = [\n '[fluenti] `@fluenti/next` was imported before `withFluenti()` generated the server module.',\n 'Fix this by:',\n \" 1. Wrapping next.config.ts with `withFluenti()` from '@fluenti/next'\",\n ' 2. Restarting the Next dev server after the generated module is written',\n \" 3. Importing client runtime APIs from '@fluenti/react' and server APIs from '@fluenti/next'\",\n].join('\\n')\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 async function Trans(_props: NextTransProps): Promise<ReactElement> {\n return throwNotConfigured()\n}\n/** @see Generated module for the real implementation. */\nexport async function Plural(_props: NextPluralProps): Promise<ReactElement> {\n return throwNotConfigured()\n}\n/** @see Generated module for the real implementation. */\nexport async function Select(_props: NextSelectProps): Promise<ReactElement> {\n return throwNotConfigured()\n}\n/** @see Generated module for the real implementation. */\nexport async function DateTime(_props: NextDateTimeProps): Promise<ReactElement> {\n return throwNotConfigured()\n}\n/** @see Generated module for the real implementation. */\nexport async function NumberFormat(_props: NextNumberFormatProps): Promise<ReactElement> {\n return throwNotConfigured()\n}\n/** @see Generated module for the real implementation. */\nexport async function I18nProvider(_props: I18nProviderProps): Promise<ReactElement> {\n return throwNotConfigured()\n}\n"],"mappings":";;;;;;;;;;;;AASA,SAAgB,EACd,GACA,GACsB;CACtB,IAAI;AAEJ,CAQE,IARE,GAAW,UAAU,OAAO,EAAU,UAAW,WAEnC;EAAE,GAAG;EAAwB,GAAG,EAAU;EAAQ,GACzD,CAAC,GAAW,UAAU,GAAW,UAE1B;EAAE,GAAG;EAAwB,SAAS,EAAU;EAAS,GAGzD,EACd,OAAO,GAAW,UAAW,WAAW,EAAU,SAAS,KAAA,GAC3D,EACD;CAGH,IAAM,IAAqB,GAAW,sBAAsB,YACtD,IAAa,GAAW,cAAc,UACtC,IAAqB,GAAW,sBAAsB,IAEtD,IAAiC;EACrC;EACA,cAAc,GAAW,gBAAgB;EACzC;EACA;EACA;EACD;AAED,QADI,GAAW,kBAAe,EAAS,gBAAgB,EAAU,gBAC1D;;;;AClCT,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,IAAS,EAAQ,GAAa,EAAO,mBAAmB,EACxD,IAA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var t=(0,e.createTransformPipeline)({framework:`react`});function n(n){if(!/\.[jt]sx?$/.test(this.resourcePath)||/node_modules|\.next/.test(this.resourcePath))return n;let r=n,i=/^\s*['"]use client['"]/.test(r);if(/\.[jt]sx$/.test(this.resourcePath)&&/<Trans[\s>]/.test(r)){let e=t.transformTrans(r);e.transformed&&(r=e.code)}if(i&&/\.[jt]sx$/.test(this.resourcePath)&&/<(Plural|Select)[\s/>]/.test(r)){let e=t.transformPluralSelect(r,`@fluenti/react/components`);e.transformed&&(r=e.code)}if(!(0,e.hasScopeTransformCandidate)(r))return r;try{let e=t.transformScope(r,{componentModuleImport:i?`@fluenti/react/components`:`@fluenti/next`,serverModuleImport:`@fluenti/next`,treatFrameworkDirectImportsAsServer:!i,rerouteServerAuthoringImports:!i,errorOnServerUseI18n:!i});if(e.transformed)return e.code}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`[fluenti] Transform failed in ${this.resourcePath}: ${t}`)}return r}module.exports=n;
|
|
2
2
|
//# sourceMappingURL=loader.cjs.map
|
package/dist/loader.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loader.cjs","names":[],"sources":["../src/loader.ts"],"sourcesContent":["/**\n * Webpack loader for t`` and t() transforms in Next.js.\n *\n * Runs as enforce: 'pre' to transform source before other loaders.\n * Only statically provable `t` bindings are optimized; runtime `t()` calls\n * continue to work without injected proxy globals.\n */\nimport { createTransformPipeline, hasScopeTransformCandidate } from '@fluenti/core/transform'\n\nconst pipeline = createTransformPipeline({ framework: 'react' })\n\n/**\n * Webpack loader function.\n * `this` is the webpack LoaderContext.\n */\nexport default function fluentLoader(this: LoaderContext, source: string): string {\n // Only process .tsx, .ts, .jsx, .js files\n if (!/\\.[jt]sx?$/.test(this.resourcePath)) {\n return source\n }\n\n // Skip node_modules and .next directory\n if (/node_modules|\\.next/.test(this.resourcePath)) {\n return source\n }\n\n let result = source\n const isClientModule = /^\\s*['\"]use client['\"]/.test(result)\n\n // ── <Trans> compile-time optimization (JSX/TSX only) ──────────────\n if (/\\.[jt]sx$/.test(this.resourcePath) && /<Trans[\\s>]/.test(result)) {\n const transResult = pipeline.transformTrans(result)\n if (transResult.transformed) {\n result = transResult.code\n }\n }\n\n // Quick check: does this file contain any Fluenti patterns?\n if (!hasScopeTransformCandidate(result)) {\n return result\n }\n\n // Try scope-aware transform (AST-based, zero false positives)\n try {\n const scoped = pipeline.transformScope(result, {\n serverModuleImport: '@fluenti/next',\n treatFrameworkDirectImportsAsServer: !isClientModule,\n rerouteServerAuthoringImports: !isClientModule,\n errorOnServerUseI18n: !isClientModule,\n })\n if (scoped.transformed) {\n return scoped.code\n }\n } catch (error: unknown) {\n const msg = error instanceof Error ? error.message : String(error)\n throw new Error(`[fluenti] Transform failed in ${this.resourcePath}: ${msg}`)\n }\n\n return result\n}\n\ninterface LoaderContext {\n resourcePath: string\n getOptions(): Record<string, unknown>\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"loader.cjs","names":[],"sources":["../src/loader.ts"],"sourcesContent":["/**\n * Webpack loader for t`` and t() transforms in Next.js.\n *\n * Runs as enforce: 'pre' to transform source before other loaders.\n * Only statically provable `t` bindings are optimized; runtime `t()` calls\n * continue to work without injected proxy globals.\n */\nimport { createTransformPipeline, hasScopeTransformCandidate } from '@fluenti/core/transform'\n\nconst pipeline = createTransformPipeline({ framework: 'react' })\n\n/**\n * Webpack loader function.\n * `this` is the webpack LoaderContext.\n */\nexport default function fluentLoader(this: LoaderContext, source: string): string {\n // Only process .tsx, .ts, .jsx, .js files\n if (!/\\.[jt]sx?$/.test(this.resourcePath)) {\n return source\n }\n\n // Skip node_modules and .next directory\n if (/node_modules|\\.next/.test(this.resourcePath)) {\n return source\n }\n\n let result = source\n const isClientModule = /^\\s*['\"]use client['\"]/.test(result)\n\n // ── <Trans> compile-time optimization (JSX/TSX only) ──────────────\n if (/\\.[jt]sx$/.test(this.resourcePath) && /<Trans[\\s>]/.test(result)) {\n const transResult = pipeline.transformTrans(result)\n if (transResult.transformed) {\n result = transResult.code\n }\n }\n\n if (isClientModule && /\\.[jt]sx$/.test(this.resourcePath) && /<(Plural|Select)[\\s/>]/.test(result)) {\n const componentResult = pipeline.transformPluralSelect(result, '@fluenti/react/components')\n if (componentResult.transformed) {\n result = componentResult.code\n }\n }\n\n // Quick check: does this file contain any Fluenti patterns?\n if (!hasScopeTransformCandidate(result)) {\n return result\n }\n\n // Try scope-aware transform (AST-based, zero false positives)\n try {\n const scoped = pipeline.transformScope(result, {\n componentModuleImport: isClientModule ? '@fluenti/react/components' : '@fluenti/next',\n serverModuleImport: '@fluenti/next',\n treatFrameworkDirectImportsAsServer: !isClientModule,\n rerouteServerAuthoringImports: !isClientModule,\n errorOnServerUseI18n: !isClientModule,\n })\n if (scoped.transformed) {\n return scoped.code\n }\n } catch (error: unknown) {\n const msg = error instanceof Error ? error.message : String(error)\n throw new Error(`[fluenti] Transform failed in ${this.resourcePath}: ${msg}`)\n }\n\n return result\n}\n\ninterface LoaderContext {\n resourcePath: string\n getOptions(): Record<string, unknown>\n}\n"],"mappings":"yCASA,IAAM,GAAA,EAAA,EAAA,yBAAmC,CAAE,UAAW,QAAS,CAAC,CAMhE,SAAwB,EAAkC,EAAwB,CAOhF,GALI,CAAC,aAAa,KAAK,KAAK,aAAa,EAKrC,sBAAsB,KAAK,KAAK,aAAa,CAC/C,OAAO,EAGT,IAAI,EAAS,EACP,EAAiB,yBAAyB,KAAK,EAAO,CAG5D,GAAI,YAAY,KAAK,KAAK,aAAa,EAAI,cAAc,KAAK,EAAO,CAAE,CACrE,IAAM,EAAc,EAAS,eAAe,EAAO,CAC/C,EAAY,cACd,EAAS,EAAY,MAIzB,GAAI,GAAkB,YAAY,KAAK,KAAK,aAAa,EAAI,yBAAyB,KAAK,EAAO,CAAE,CAClG,IAAM,EAAkB,EAAS,sBAAsB,EAAQ,4BAA4B,CACvF,EAAgB,cAClB,EAAS,EAAgB,MAK7B,GAAI,EAAA,EAAA,EAAA,4BAA4B,EAAO,CACrC,OAAO,EAIT,GAAI,CACF,IAAM,EAAS,EAAS,eAAe,EAAQ,CAC7C,sBAAuB,EAAiB,4BAA8B,gBACtE,mBAAoB,gBACpB,oCAAqC,CAAC,EACtC,8BAA+B,CAAC,EAChC,qBAAsB,CAAC,EACxB,CAAC,CACF,GAAI,EAAO,YACT,OAAO,EAAO,WAET,EAAgB,CACvB,IAAM,EAAM,aAAiB,MAAQ,EAAM,QAAU,OAAO,EAAM,CAClE,MAAU,MAAM,iCAAiC,KAAK,aAAa,IAAI,IAAM,CAG/E,OAAO"}
|
package/dist/loader.js
CHANGED
|
@@ -8,9 +8,14 @@ function r(e) {
|
|
|
8
8
|
let e = n.transformTrans(r);
|
|
9
9
|
e.transformed && (r = e.code);
|
|
10
10
|
}
|
|
11
|
+
if (i && /\.[jt]sx$/.test(this.resourcePath) && /<(Plural|Select)[\s/>]/.test(r)) {
|
|
12
|
+
let e = n.transformPluralSelect(r, "@fluenti/react/components");
|
|
13
|
+
e.transformed && (r = e.code);
|
|
14
|
+
}
|
|
11
15
|
if (!t(r)) return r;
|
|
12
16
|
try {
|
|
13
17
|
let e = n.transformScope(r, {
|
|
18
|
+
componentModuleImport: i ? "@fluenti/react/components" : "@fluenti/next",
|
|
14
19
|
serverModuleImport: "@fluenti/next",
|
|
15
20
|
treatFrameworkDirectImportsAsServer: !i,
|
|
16
21
|
rerouteServerAuthoringImports: !i,
|
package/dist/loader.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loader.js","names":[],"sources":["../src/loader.ts"],"sourcesContent":["/**\n * Webpack loader for t`` and t() transforms in Next.js.\n *\n * Runs as enforce: 'pre' to transform source before other loaders.\n * Only statically provable `t` bindings are optimized; runtime `t()` calls\n * continue to work without injected proxy globals.\n */\nimport { createTransformPipeline, hasScopeTransformCandidate } from '@fluenti/core/transform'\n\nconst pipeline = createTransformPipeline({ framework: 'react' })\n\n/**\n * Webpack loader function.\n * `this` is the webpack LoaderContext.\n */\nexport default function fluentLoader(this: LoaderContext, source: string): string {\n // Only process .tsx, .ts, .jsx, .js files\n if (!/\\.[jt]sx?$/.test(this.resourcePath)) {\n return source\n }\n\n // Skip node_modules and .next directory\n if (/node_modules|\\.next/.test(this.resourcePath)) {\n return source\n }\n\n let result = source\n const isClientModule = /^\\s*['\"]use client['\"]/.test(result)\n\n // ── <Trans> compile-time optimization (JSX/TSX only) ──────────────\n if (/\\.[jt]sx$/.test(this.resourcePath) && /<Trans[\\s>]/.test(result)) {\n const transResult = pipeline.transformTrans(result)\n if (transResult.transformed) {\n result = transResult.code\n }\n }\n\n // Quick check: does this file contain any Fluenti patterns?\n if (!hasScopeTransformCandidate(result)) {\n return result\n }\n\n // Try scope-aware transform (AST-based, zero false positives)\n try {\n const scoped = pipeline.transformScope(result, {\n serverModuleImport: '@fluenti/next',\n treatFrameworkDirectImportsAsServer: !isClientModule,\n rerouteServerAuthoringImports: !isClientModule,\n errorOnServerUseI18n: !isClientModule,\n })\n if (scoped.transformed) {\n return scoped.code\n }\n } catch (error: unknown) {\n const msg = error instanceof Error ? error.message : String(error)\n throw new Error(`[fluenti] Transform failed in ${this.resourcePath}: ${msg}`)\n }\n\n return result\n}\n\ninterface LoaderContext {\n resourcePath: string\n getOptions(): Record<string, unknown>\n}\n"],"mappings":";;AASA,IAAM,IAAW,EAAwB,EAAE,WAAW,SAAS,CAAC;AAMhE,SAAwB,EAAkC,GAAwB;AAOhF,KALI,CAAC,aAAa,KAAK,KAAK,aAAa,IAKrC,sBAAsB,KAAK,KAAK,aAAa,CAC/C,QAAO;CAGT,IAAI,IAAS,GACP,IAAiB,yBAAyB,KAAK,EAAO;AAG5D,KAAI,YAAY,KAAK,KAAK,aAAa,IAAI,cAAc,KAAK,EAAO,EAAE;EACrE,IAAM,IAAc,EAAS,eAAe,EAAO;AACnD,EAAI,EAAY,gBACd,IAAS,EAAY;;
|
|
1
|
+
{"version":3,"file":"loader.js","names":[],"sources":["../src/loader.ts"],"sourcesContent":["/**\n * Webpack loader for t`` and t() transforms in Next.js.\n *\n * Runs as enforce: 'pre' to transform source before other loaders.\n * Only statically provable `t` bindings are optimized; runtime `t()` calls\n * continue to work without injected proxy globals.\n */\nimport { createTransformPipeline, hasScopeTransformCandidate } from '@fluenti/core/transform'\n\nconst pipeline = createTransformPipeline({ framework: 'react' })\n\n/**\n * Webpack loader function.\n * `this` is the webpack LoaderContext.\n */\nexport default function fluentLoader(this: LoaderContext, source: string): string {\n // Only process .tsx, .ts, .jsx, .js files\n if (!/\\.[jt]sx?$/.test(this.resourcePath)) {\n return source\n }\n\n // Skip node_modules and .next directory\n if (/node_modules|\\.next/.test(this.resourcePath)) {\n return source\n }\n\n let result = source\n const isClientModule = /^\\s*['\"]use client['\"]/.test(result)\n\n // ── <Trans> compile-time optimization (JSX/TSX only) ──────────────\n if (/\\.[jt]sx$/.test(this.resourcePath) && /<Trans[\\s>]/.test(result)) {\n const transResult = pipeline.transformTrans(result)\n if (transResult.transformed) {\n result = transResult.code\n }\n }\n\n if (isClientModule && /\\.[jt]sx$/.test(this.resourcePath) && /<(Plural|Select)[\\s/>]/.test(result)) {\n const componentResult = pipeline.transformPluralSelect(result, '@fluenti/react/components')\n if (componentResult.transformed) {\n result = componentResult.code\n }\n }\n\n // Quick check: does this file contain any Fluenti patterns?\n if (!hasScopeTransformCandidate(result)) {\n return result\n }\n\n // Try scope-aware transform (AST-based, zero false positives)\n try {\n const scoped = pipeline.transformScope(result, {\n componentModuleImport: isClientModule ? '@fluenti/react/components' : '@fluenti/next',\n serverModuleImport: '@fluenti/next',\n treatFrameworkDirectImportsAsServer: !isClientModule,\n rerouteServerAuthoringImports: !isClientModule,\n errorOnServerUseI18n: !isClientModule,\n })\n if (scoped.transformed) {\n return scoped.code\n }\n } catch (error: unknown) {\n const msg = error instanceof Error ? error.message : String(error)\n throw new Error(`[fluenti] Transform failed in ${this.resourcePath}: ${msg}`)\n }\n\n return result\n}\n\ninterface LoaderContext {\n resourcePath: string\n getOptions(): Record<string, unknown>\n}\n"],"mappings":";;AASA,IAAM,IAAW,EAAwB,EAAE,WAAW,SAAS,CAAC;AAMhE,SAAwB,EAAkC,GAAwB;AAOhF,KALI,CAAC,aAAa,KAAK,KAAK,aAAa,IAKrC,sBAAsB,KAAK,KAAK,aAAa,CAC/C,QAAO;CAGT,IAAI,IAAS,GACP,IAAiB,yBAAyB,KAAK,EAAO;AAG5D,KAAI,YAAY,KAAK,KAAK,aAAa,IAAI,cAAc,KAAK,EAAO,EAAE;EACrE,IAAM,IAAc,EAAS,eAAe,EAAO;AACnD,EAAI,EAAY,gBACd,IAAS,EAAY;;AAIzB,KAAI,KAAkB,YAAY,KAAK,KAAK,aAAa,IAAI,yBAAyB,KAAK,EAAO,EAAE;EAClG,IAAM,IAAkB,EAAS,sBAAsB,GAAQ,4BAA4B;AAC3F,EAAI,EAAgB,gBAClB,IAAS,EAAgB;;AAK7B,KAAI,CAAC,EAA2B,EAAO,CACrC,QAAO;AAIT,KAAI;EACF,IAAM,IAAS,EAAS,eAAe,GAAQ;GAC7C,uBAAuB,IAAiB,8BAA8B;GACtE,oBAAoB;GACpB,qCAAqC,CAAC;GACtC,+BAA+B,CAAC;GAChC,sBAAsB,CAAC;GACxB,CAAC;AACF,MAAI,EAAO,YACT,QAAO,EAAO;UAET,GAAgB;EACvB,IAAM,IAAM,aAAiB,QAAQ,EAAM,UAAU,OAAO,EAAM;AAClE,QAAU,MAAM,iCAAiC,KAAK,aAAa,IAAI,IAAM;;AAG/E,QAAO"}
|
package/dist/middleware.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./routing-
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./routing-D4p8HvMH.cjs`);let t=require(`@fluenti/next/i18n-config`);var n=`x-fluenti-locale`;function r(r){let{NextResponse:l}=r,f=r.locales??t.locales,p=r.sourceLocale??t.sourceLocale,m=r.cookieName??t.cookieName,h=r.localePrefix??`as-needed`,g=r.rewriteDefaultLocale??!1,_=r.setCookie??!1,v=r.cookieOptions??{},y=r.localeDetection??!0,b=r.alternateLinks??!1,x=r.pathnames,S=r.domains,C=r.beforeResponse;function w(e,t,i,a,s){if(e.headers.set(n,i),_&&o(e,t,i,m,s,v),b||r.getAlternateLinks){let n=r.getAlternateLinks?d(r.getAlternateLinks,t,i,f):u(t,f,p,h,t.nextUrl.basePath??``,x);e.headers.set(`Link`,n)}if(C){let n=C({response:e,request:t,locale:i,type:a});if(n)return n}return e}return function(t){let o=f,u=p,{pathname:d,search:_}=t.nextUrl,v=t.nextUrl.basePath??``,b=d.split(`/`),C=b[1]??``,T=h===`never`?null:i(C,o),E;if(T)E=T;else if(!y)E=u;else{let e=r.detectLocale?.(t);E=e!==void 0&&i(e,o)!==null?i(e,o):S?s(t,S,o)??c(t,o,u,m):c(t,o,u,m)}let D=new Headers(t.headers);if(D.set(n,E),h===`never`){if(g){let e=new URL(`${v}/${E}${d}${_}`,t.url);return w(l.rewrite(e,{request:{headers:D}}),t,E,`rewrite`,null)}return w(l.next({request:{headers:D}}),t,E,`next`,null)}if(x&&T){let n=a(`/`+b.slice(2).join(`/`)),r=e.n(n,E,x);if(r){let e=new URL(`${v}/${E}${r}${_}`,t.url);return w(l.rewrite(e,{request:{headers:D}}),t,E,`rewrite`,T)}let i=e.r(n,E,x);if(i&&i!==n){let e=new URL(`${v}/${E}${i}${_}`,t.url);return w(l.redirect(e),t,E,`redirect`,T)}}if(!T&&(h===`always`||E!==u)){let n=d;if(x){let t=e.r(d,E,x);t&&(n=t)}let r=new URL(`${v}/${E}${n}${_}`,t.url);return w(l.redirect(r),t,E,`redirect`,T)}if(!T&&E===u&&g){let e=new URL(`${v}/${u}${d}${_}`,t.url);return w(l.rewrite(e,{request:{headers:D}}),t,E,`rewrite`,T)}if(h===`as-needed`&&T===u){let e=a(`/`+b.slice(2).join(`/`));if(g){let n=new URL(`${v}${e}${_}`,t.url);return w(l.redirect(n),t,E,`redirect`,T)}let n=new URL(`${v}${e}${_}`,t.url);return w(l.rewrite(n,{request:{headers:D}}),t,E,`rewrite`,T)}return w(l.next({request:{headers:D}}),t,E,`next`,T)}}function i(e,t){if(!e)return null;let n=e.toLowerCase();return t.find(e=>e.toLowerCase()===n)??null}function a(e){return e.replace(/\/+/g,`/`)||`/`}function o(e,t,n,r,i,a){if(i||t.cookies.get(r)?.value===n)return;let o=[`${r}=${encodeURIComponent(n)}`];o.push(`path=${a.path??`/`}`),o.push(`max-age=${a.maxAge??31536e3}`),o.push(`samesite=${a.sameSite??`lax`}`),a.domain&&o.push(`domain=${a.domain}`),(a.secure??t.url.startsWith(`https`))&&o.push(`secure`),e.headers.set(`set-cookie`,o.join(`;`))}function s(e,t,n){let r=e.headers.get(`host`)?.split(`:`)[0]??``;for(let e of t)if(r===e.domain||r.endsWith(`.`+e.domain)){let t=i(e.defaultLocale,e.locales??n);if(t)return t}return null}function c(e,t,n,r){let a=e.cookies.get(r)?.value;if(a){let e=i(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(),r=i(n,t);if(r)return r;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}function l(e,t){let n=e.split(`/`);return i(n[1]??``,t)?a(`/`+n.slice(2).join(`/`)):e}function u(t,n,r,a,o,s){let c=new URL(t.url).origin,u=l(t.nextUrl.pathname,n),d=t.nextUrl.pathname.split(`/`)[1]??``,f=a===`never`?r:i(d,n)??r,p=s?e.n(u,f,s)??u:u,m=n.map(t=>{let n=s?e.r(p,t,s)??p:p,i;return i=a===`never`||a===`as-needed`&&t===r?n:`/${t}${n}`,`<${c}${o}${i}>; rel="alternate"; hreflang="${t}"`}),h=s?e.r(p,r,s)??p:p,g=a===`always`?`/${r}${h}`:h;return m.push(`<${c}${o}${g}>; rel="alternate"; hreflang="x-default"`),m.join(`, `)}function d(e,t,n,r){let i=new URL(t.url).origin;return e({pathname:l(t.nextUrl.pathname,r),locale:n,locales:r,origin:i,basePath:t.nextUrl.basePath??``}).map(e=>`<${e.href}>; rel="alternate"; hreflang="${e.hreflang}"`).join(`, `)}exports.LOCALE_HEADER=n,exports.createI18nMiddleware=r;
|
|
2
2
|
//# sourceMappingURL=middleware.cjs.map
|
package/dist/middleware.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"middleware.cjs","names":[],"sources":["../src/middleware.ts"],"sourcesContent":["/**\n * @module @fluenti/next/middleware\n *\n * Built-in i18n middleware for Next.js App Router.\n *\n * Uses `x-fluenti-locale` request header to pass locale from middleware to\n * server components — avoids `Set-Cookie` on every request (CDN-friendly).\n *\n * @example Minimal\n * ```ts\n * import { NextResponse } from 'next/server'\n * import { createI18nMiddleware } from '@fluenti/next/middleware'\n *\n * export default createI18nMiddleware({ NextResponse })\n * ```\n *\n * @example With pathnames + alternateLinks + domains\n * ```ts\n * import { NextResponse } from 'next/server'\n * import { createI18nMiddleware } from '@fluenti/next/middleware'\n *\n * export default createI18nMiddleware({\n * NextResponse,\n * rewriteDefaultLocale: true,\n * alternateLinks: true,\n * pathnames: {\n * '/about': { fr: '/a-propos' },\n * '/blog/[slug]': { fr: '/articles/[slug]' },\n * },\n * domains: [\n * { domain: 'fr.example.com', defaultLocale: 'fr' },\n * ],\n * })\n * ```\n */\n\nimport {\n locales as _configLocales,\n sourceLocale as _configSourceLocale,\n cookieName as _configCookieName,\n} from '@fluenti/next/i18n-config'\n\n/** Header name used to pass resolved locale from middleware to RSC */\nexport const LOCALE_HEADER = 'x-fluenti-locale'\n\nexport interface CookieOptions {\n /** Cookie domain (e.g. '.example.com' for cross-subdomain) */\n domain?: string\n /** Secure flag (default: auto-detect from request URL) */\n secure?: boolean\n /** SameSite attribute (default: 'lax') */\n sameSite?: 'lax' | 'strict' | 'none'\n /** Max age in seconds (default: 31536000 = 1 year) */\n maxAge?: number\n /** Cookie path (default: '/') */\n path?: string\n}\n\nexport interface DomainConfig {\n /** Domain hostname (e.g. 'fr.example.com') */\n domain: string\n /** Default locale for this domain */\n defaultLocale: string\n /** Optional subset of locales available on this domain */\n locales?: string[]\n}\n\nexport interface AlternateLinkEntry {\n href: string\n hreflang: string\n}\n\nexport interface I18nMiddlewareConfig {\n /** Available locales. If omitted, reads from `fluenti.config.ts`. */\n locales?: string[]\n /** Source/default locale. If omitted, reads from `fluenti.config.ts`. */\n sourceLocale?: string\n /** Cookie name for reading user preference (default: 'locale') */\n cookieName?: string\n /**\n * Locale prefix strategy:\n * - `'always'`: all locales get a URL prefix\n * - `'as-needed'`: source locale has no prefix, others do\n * - `'never'`: no locale prefix in URLs; locale determined by detection chain\n *\n * Default: `'as-needed'`\n */\n localePrefix?: 'always' | 'as-needed' | 'never'\n /**\n * When true, bare paths are internally rewritten to include the locale prefix.\n * Required when using `app/[locale]/` directory structure.\n *\n * Default: `false`\n */\n rewriteDefaultLocale?: boolean\n /**\n * When true, detected locale is persisted in a cookie.\n * Disabled by default to keep responses CDN-cacheable.\n */\n setCookie?: boolean\n /** Fine-grained cookie configuration for multi-domain / secure deployments. */\n cookieOptions?: CookieOptions\n /**\n * Set to false to disable automatic locale detection.\n * Bare paths will always use `sourceLocale` instead of detecting from cookie / Accept-Language.\n *\n * Default: `true`\n */\n localeDetection?: boolean\n /**\n * Custom locale detection function. Called when no locale is present in the URL path.\n * Return a locale string to override the default chain, or `undefined` to fall through.\n */\n detectLocale?: (req: NextRequest) => string | undefined\n /**\n * Domain-based locale routing. Each domain maps to a default locale.\n * Domain matching is checked before cookie/Accept-Language detection.\n *\n * @example\n * ```ts\n * domains: [\n * { domain: 'fr.example.com', defaultLocale: 'fr' },\n * { domain: 'example.co.jp', defaultLocale: 'ja' },\n * ]\n * ```\n */\n domains?: DomainConfig[]\n /**\n * Map internal paths to localized paths per locale.\n * Supports dynamic segments: `[param]` and `[...slug]`.\n *\n * @example\n * ```ts\n * pathnames: {\n * '/about': { fr: '/a-propos' },\n * '/blog/[slug]': { fr: '/articles/[slug]' },\n * }\n * ```\n */\n pathnames?: Record<string, Record<string, string>>\n /**\n * When true, adds `Link` response headers with `rel=\"alternate\"` hreflang\n * and `rel=\"canonical\"` for SEO.\n *\n * Default: `false`\n */\n alternateLinks?: boolean\n /**\n * Custom function to build alternate link entries. Overrides default `alternateLinks` behavior.\n * Return an array of `{ href, hreflang }` entries.\n */\n getAlternateLinks?: (context: {\n pathname: string\n locale: string\n locales: string[]\n origin: string\n basePath: string\n }) => AlternateLinkEntry[]\n /**\n * Called before the middleware returns a response.\n * Modify headers, cookies, or return a replacement response.\n */\n beforeResponse?: (context: {\n response: NextResponseInstance\n request: NextRequest\n locale: string\n type: 'redirect' | 'rewrite' | 'next'\n }) => NextResponseInstance | void | undefined\n}\n\n/** Minimal request shape required by the middleware. Compatible with Next.js NextRequest. */\ntype NextRequest = {\n nextUrl: { pathname: string; search: string; basePath?: string }\n url: string\n cookies: { get(name: string): { value: string } | undefined }\n headers: Headers\n}\n\ntype NextResponseStatic<R extends NextResponseInstance = NextResponseInstance> = {\n redirect(url: URL): R\n rewrite(url: URL, init?: Record<string, unknown>): R\n next(init?: Record<string, unknown>): R\n}\n\ntype NextResponseInstance = {\n headers: { set(name: string, value: string): void }\n}\n\n/**\n * Create an i18n middleware function for Next.js.\n */\nexport function createI18nMiddleware<R extends NextResponseInstance = NextResponseInstance>(\n config: I18nMiddlewareConfig & { NextResponse: NextResponseStatic<R> },\n) {\n const { NextResponse } = config\n const resolvedLocales: string[] = config.locales ?? _configLocales\n const resolvedSourceLocale: string = config.sourceLocale ?? _configSourceLocale\n const cookieName = config.cookieName ?? _configCookieName\n const localePrefix = config.localePrefix ?? 'as-needed'\n const rewriteDefaultLocale = config.rewriteDefaultLocale ?? false\n const setCookieEnabled = config.setCookie ?? false\n const cookieOpts: CookieOptions = config.cookieOptions ?? {}\n const localeDetectionEnabled = config.localeDetection ?? true\n const alternateLinksEnabled = config.alternateLinks ?? false\n const pathnamesMap = config.pathnames\n const domainsConfig = config.domains\n const beforeResponse = config.beforeResponse\n\n function finalizeResponse(\n response: R,\n request: NextRequest,\n locale: string,\n type: 'redirect' | 'rewrite' | 'next',\n pathLocale: string | null,\n ): R {\n response.headers.set(LOCALE_HEADER, locale)\n if (setCookieEnabled) {\n maybeSetCookie(response, request, locale, cookieName, pathLocale, cookieOpts)\n }\n if (alternateLinksEnabled || config.getAlternateLinks) {\n const linkHeader = config.getAlternateLinks\n ? buildCustomAlternateLinks(config.getAlternateLinks, request, locale, resolvedLocales)\n : buildAlternateLinks(request, resolvedLocales, resolvedSourceLocale, localePrefix, request.nextUrl.basePath ?? '', pathnamesMap)\n response.headers.set('Link', linkHeader)\n }\n if (beforeResponse) {\n const replacement = beforeResponse({ response, request, locale, type })\n if (replacement) return replacement as R\n }\n return response\n }\n\n return function i18nMiddleware(request: NextRequest): R {\n const locales = resolvedLocales\n const sourceLocale = resolvedSourceLocale\n const { pathname, search } = request.nextUrl\n const basePath = request.nextUrl.basePath ?? ''\n\n // Extract locale from URL path ('never' mode skips this)\n const segments = pathname.split('/')\n const firstSegment = segments[1] ?? ''\n const pathLocale = localePrefix === 'never' ? null : findLocale(firstSegment, locales)\n\n // Determine the active locale\n let locale: string\n\n if (pathLocale) {\n locale = pathLocale\n } else if (!localeDetectionEnabled) {\n locale = sourceLocale\n } else {\n // Detection chain: custom → domains → cookie → Accept-Language → default\n const custom = config.detectLocale?.(request)\n if (custom !== undefined && findLocale(custom, locales) !== null) {\n locale = findLocale(custom, locales)!\n } else if (domainsConfig) {\n const domainLocale = detectFromDomain(request, domainsConfig, locales)\n locale = domainLocale ?? detectLocale(request, locales, sourceLocale, cookieName)\n } else {\n locale = detectLocale(request, locales, sourceLocale, cookieName)\n }\n }\n\n // Build request headers\n const requestHeaders = new Headers(request.headers)\n requestHeaders.set(LOCALE_HEADER, locale)\n\n // ── 'never' mode ──────────────────────────────────────────────────────\n if (localePrefix === 'never') {\n if (rewriteDefaultLocale) {\n const rewriteUrl = new URL(`${basePath}/${locale}${pathname}${search}`, request.url)\n return finalizeResponse(\n NextResponse.rewrite(rewriteUrl, { request: { headers: requestHeaders } }),\n request, locale, 'rewrite', null,\n )\n }\n return finalizeResponse(\n NextResponse.next({ request: { headers: requestHeaders } }),\n request, locale, 'next', null,\n )\n }\n\n // ── Pathnames mapping ─────────────────────────────────────────────────\n if (pathnamesMap && pathLocale) {\n const pathWithoutLocale = normalizeSlashes('/' + segments.slice(2).join('/'))\n const internalPath = resolveInternalPath(pathWithoutLocale, locale, pathnamesMap)\n\n if (internalPath) {\n const rewriteUrl = new URL(`${basePath}/${locale}${internalPath}${search}`, request.url)\n return finalizeResponse(\n NextResponse.rewrite(rewriteUrl, { request: { headers: requestHeaders } }),\n request, locale, 'rewrite', pathLocale,\n )\n }\n\n const localizedPath = resolveLocalizedPath(pathWithoutLocale, locale, pathnamesMap)\n if (localizedPath && localizedPath !== pathWithoutLocale) {\n const redirectUrl = new URL(`${basePath}/${locale}${localizedPath}${search}`, request.url)\n return finalizeResponse(\n NextResponse.redirect(redirectUrl),\n request, locale, 'redirect', pathLocale,\n )\n }\n }\n\n // ── Case 1: No locale in path → redirect ──────────────────────────────\n if (!pathLocale && (localePrefix === 'always' || locale !== sourceLocale)) {\n // If pathnames configured, redirect to localized path\n let targetPath = pathname\n if (pathnamesMap) {\n const localized = resolveLocalizedPath(pathname, locale, pathnamesMap)\n if (localized) targetPath = localized\n }\n const redirectUrl = new URL(`${basePath}/${locale}${targetPath}${search}`, request.url)\n return finalizeResponse(\n NextResponse.redirect(redirectUrl),\n request, locale, 'redirect', pathLocale,\n )\n }\n\n // ── Case 2: as-needed + source locale + rewriteDefaultLocale ──────────\n if (!pathLocale && locale === sourceLocale && rewriteDefaultLocale) {\n const rewriteUrl = new URL(`${basePath}/${sourceLocale}${pathname}${search}`, request.url)\n return finalizeResponse(\n NextResponse.rewrite(rewriteUrl, { request: { headers: requestHeaders } }),\n request, locale, 'rewrite', pathLocale,\n )\n }\n\n // ── Case 3: as-needed, source locale has explicit prefix → strip ──────\n if (localePrefix === 'as-needed' && pathLocale === sourceLocale) {\n const pathWithoutLocale = normalizeSlashes('/' + segments.slice(2).join('/'))\n if (rewriteDefaultLocale) {\n const redirectUrl = new URL(`${basePath}${pathWithoutLocale}${search}`, request.url)\n return finalizeResponse(\n NextResponse.redirect(redirectUrl),\n request, locale, 'redirect', pathLocale,\n )\n }\n const rewriteUrl = new URL(`${basePath}${pathWithoutLocale}${search}`, request.url)\n return finalizeResponse(\n NextResponse.rewrite(rewriteUrl, { request: { headers: requestHeaders } }),\n request, locale, 'rewrite', pathLocale,\n )\n }\n\n // ── Case 4/5: pass through ────────────────────────────────────────────\n return finalizeResponse(\n NextResponse.next({ request: { headers: requestHeaders } }),\n request, locale, 'next', pathLocale,\n )\n }\n}\n\n// ── Helpers ────────────────────────────────────────────────────────────────\n\nfunction findLocale(candidate: string, locales: string[]): string | null {\n if (!candidate) return null\n const lower = candidate.toLowerCase()\n return locales.find(l => l.toLowerCase() === lower) ?? null\n}\n\nfunction normalizeSlashes(path: string): string {\n return path.replace(/\\/+/g, '/') || '/'\n}\n\nfunction maybeSetCookie(\n response: NextResponseInstance,\n request: NextRequest,\n locale: string,\n cookieName: string,\n pathLocale: string | null,\n opts: CookieOptions,\n): void {\n if (pathLocale) return\n if (request.cookies.get(cookieName)?.value === locale) return\n\n const parts = [`${cookieName}=${encodeURIComponent(locale)}`]\n parts.push(`path=${opts.path ?? '/'}`)\n parts.push(`max-age=${opts.maxAge ?? 31536000}`)\n parts.push(`samesite=${opts.sameSite ?? 'lax'}`)\n if (opts.domain) parts.push(`domain=${opts.domain}`)\n if (opts.secure ?? request.url.startsWith('https')) parts.push('secure')\n response.headers.set('set-cookie', parts.join(';'))\n}\n\nfunction detectFromDomain(\n request: NextRequest,\n domains: DomainConfig[],\n locales: string[],\n): string | null {\n const host = request.headers.get('host')?.split(':')[0] ?? ''\n for (const d of domains) {\n if (host === d.domain || host.endsWith('.' + d.domain)) {\n const found = findLocale(d.defaultLocale, d.locales ?? locales)\n if (found) return found\n }\n }\n return null\n}\n\nfunction detectLocale(\n request: NextRequest,\n locales: string[],\n defaultLocale: string,\n cookieName: string,\n): string {\n const cookieLocale = request.cookies.get(cookieName)?.value\n if (cookieLocale) {\n const found = findLocale(cookieLocale, locales)\n if (found) return found\n }\n\n const acceptLang = request.headers.get('accept-language')\n if (acceptLang) {\n for (const part of acceptLang.split(',')) {\n const lang = part.split(';')[0]!.trim()\n const exact = findLocale(lang, locales)\n if (exact) return exact\n const prefix = lang.split('-')[0]!.toLowerCase()\n const match = locales.find(l => {\n const ll = l.toLowerCase()\n return ll === prefix || ll.startsWith(prefix + '-')\n })\n if (match) return match\n }\n }\n\n return defaultLocale\n}\n\nfunction stripLocalePrefix(pathname: string, locales: string[]): string {\n const segments = pathname.split('/')\n const first = segments[1] ?? ''\n if (findLocale(first, locales)) {\n return normalizeSlashes('/' + segments.slice(2).join('/'))\n }\n return pathname\n}\n\n// Path resolution utilities imported from shared routing module\n// (bundled by tsup, safe for Edge Runtime)\nimport { resolveInternalPath, resolveLocalizedPath } from './routing'\n\nfunction buildAlternateLinks(\n request: NextRequest,\n locales: string[],\n sourceLocale: string,\n localePrefix: 'always' | 'as-needed' | 'never',\n basePath: string,\n pathnames?: Record<string, Record<string, string>>,\n): string {\n const origin = new URL(request.url).origin\n const cleanPath = stripLocalePrefix(request.nextUrl.pathname, locales)\n\n const links = locales.map(loc => {\n let localePath: string\n if (localePrefix === 'never') {\n localePath = cleanPath\n } else if (localePrefix === 'as-needed' && loc === sourceLocale) {\n localePath = cleanPath\n } else {\n localePath = `/${loc}${cleanPath}`\n }\n if (pathnames) {\n const mapped = resolveLocalizedPath(cleanPath, loc, pathnames)\n if (mapped) {\n localePath = localePrefix === 'never' || (localePrefix === 'as-needed' && loc === sourceLocale)\n ? mapped\n : `/${loc}${mapped}`\n }\n }\n return `<${origin}${basePath}${localePath}>; rel=\"alternate\"; hreflang=\"${loc}\"`\n })\n\n // x-default\n const defaultPath = localePrefix === 'always' ? `/${sourceLocale}${cleanPath}` : cleanPath\n links.push(`<${origin}${basePath}${defaultPath}>; rel=\"alternate\"; hreflang=\"x-default\"`)\n\n return links.join(', ')\n}\n\nfunction buildCustomAlternateLinks(\n getAlternateLinks: NonNullable<I18nMiddlewareConfig['getAlternateLinks']>,\n request: NextRequest,\n locale: string,\n locales: string[],\n): string {\n const origin = new URL(request.url).origin\n const cleanPath = stripLocalePrefix(request.nextUrl.pathname, locales)\n const basePath = request.nextUrl.basePath ?? ''\n const entries = getAlternateLinks({ pathname: cleanPath, locale, locales, origin, basePath })\n return entries.map(e => `<${e.href}>; rel=\"alternate\"; hreflang=\"${e.hreflang}\"`).join(', ')\n}\n"],"mappings":"6JA0b0D,CA/Y1D,IAAa,EAAgB,mBAoJ7B,SAAgB,EACd,EACA,CACA,GAAM,CAAE,gBAAiB,EACnB,EAA4B,EAAO,SAAW,EAAA,QAC9C,EAA+B,EAAO,cAAgB,EAAA,aACtD,EAAa,EAAO,YAAc,EAAA,WAClC,EAAe,EAAO,cAAgB,YACtC,EAAuB,EAAO,sBAAwB,GACtD,EAAmB,EAAO,WAAa,GACvC,EAA4B,EAAO,eAAiB,EAAE,CACtD,EAAyB,EAAO,iBAAmB,GACnD,EAAwB,EAAO,gBAAkB,GACjD,EAAe,EAAO,UACtB,EAAgB,EAAO,QACvB,EAAiB,EAAO,eAE9B,SAAS,EACP,EACA,EACA,EACA,EACA,EACG,CAKH,GAJA,EAAS,QAAQ,IAAI,EAAe,EAAO,CACvC,GACF,EAAe,EAAU,EAAS,EAAQ,EAAY,EAAY,EAAW,CAE3E,GAAyB,EAAO,kBAAmB,CACrD,IAAM,EAAa,EAAO,kBACtB,EAA0B,EAAO,kBAAmB,EAAS,EAAQ,EAAgB,CACrF,EAAoB,EAAS,EAAiB,EAAsB,EAAc,EAAQ,QAAQ,UAAY,GAAI,EAAa,CACnI,EAA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AAiB,aAAe,IAAQ,EAC9E,EACA,IAAI,IAAM,KAGlB,MAAO,IAAI,IAAS,IAAW,EAAW,gCAAgC,EAAI,IAC9E,CAGI,EAAc,IAAiB,SAAW,IAAI,IAAe,IAAc,EAGjF,OAFA,EAAM,KAAK,IAAI,IAAS,IAAW,EAAY,0CAA0C,CAElF,EAAM,KAAK,KAAK,CAGzB,SAAS,EACP,EACA,EACA,EACA,EACQ,CACR,IAAM,EAAS,IAAI,IAAI,EAAQ,IAAI,CAAC,OAIpC,OADgB,EAAkB,CAAE,SAFlB,EAAkB,EAAQ,QAAQ,SAAU,EAAQ,CAEb,SAAQ,UAAS,SAAQ,SADjE,EAAQ,QAAQ,UAAY,GAC+C,CAAC,CAC9E,IAAI,GAAK,IAAI,EAAE,KAAK,gCAAgC,EAAE,SAAS,GAAG,CAAC,KAAK,KAAK"}
|
|
1
|
+
{"version":3,"file":"middleware.cjs","names":[],"sources":["../src/middleware.ts"],"sourcesContent":["/**\n * @module @fluenti/next/middleware\n *\n * Built-in i18n middleware for Next.js App Router.\n *\n * Uses `x-fluenti-locale` request header to pass locale from middleware to\n * server components — avoids `Set-Cookie` on every request (CDN-friendly).\n *\n * @example Minimal\n * ```ts\n * import { NextResponse } from 'next/server'\n * import { createI18nMiddleware } from '@fluenti/next/middleware'\n *\n * export default createI18nMiddleware({ NextResponse })\n * ```\n *\n * @example With pathnames + alternateLinks + domains\n * ```ts\n * import { NextResponse } from 'next/server'\n * import { createI18nMiddleware } from '@fluenti/next/middleware'\n *\n * export default createI18nMiddleware({\n * NextResponse,\n * rewriteDefaultLocale: true,\n * alternateLinks: true,\n * pathnames: {\n * '/about': { fr: '/a-propos' },\n * '/blog/[slug]': { fr: '/articles/[slug]' },\n * },\n * domains: [\n * { domain: 'fr.example.com', defaultLocale: 'fr' },\n * ],\n * })\n * ```\n */\n\nimport {\n locales as _configLocales,\n sourceLocale as _configSourceLocale,\n cookieName as _configCookieName,\n} from '@fluenti/next/i18n-config'\n\n/** Header name used to pass resolved locale from middleware to RSC */\nexport const LOCALE_HEADER = 'x-fluenti-locale'\n\nexport interface CookieOptions {\n /** Cookie domain (e.g. '.example.com' for cross-subdomain) */\n domain?: string\n /** Secure flag (default: auto-detect from request URL) */\n secure?: boolean\n /** SameSite attribute (default: 'lax') */\n sameSite?: 'lax' | 'strict' | 'none'\n /** Max age in seconds (default: 31536000 = 1 year) */\n maxAge?: number\n /** Cookie path (default: '/') */\n path?: string\n}\n\nexport interface DomainConfig {\n /** Domain hostname (e.g. 'fr.example.com') */\n domain: string\n /** Default locale for this domain */\n defaultLocale: string\n /** Optional subset of locales available on this domain */\n locales?: string[]\n}\n\nexport interface AlternateLinkEntry {\n href: string\n hreflang: string\n}\n\nexport interface I18nMiddlewareConfig {\n /** Available locales. If omitted, reads from `fluenti.config.ts`. */\n locales?: string[]\n /** Source/default locale. If omitted, reads from `fluenti.config.ts`. */\n sourceLocale?: string\n /** Cookie name for reading user preference (default: 'locale') */\n cookieName?: string\n /**\n * Locale prefix strategy:\n * - `'always'`: all locales get a URL prefix\n * - `'as-needed'`: source locale has no prefix, others do\n * - `'never'`: no locale prefix in URLs; locale determined by detection chain\n *\n * Default: `'as-needed'`\n */\n localePrefix?: 'always' | 'as-needed' | 'never'\n /**\n * When true, bare paths are internally rewritten to include the locale prefix.\n * Required when using `app/[locale]/` directory structure.\n *\n * Default: `false`\n */\n rewriteDefaultLocale?: boolean\n /**\n * When true, detected locale is persisted in a cookie.\n * Disabled by default to keep responses CDN-cacheable.\n */\n setCookie?: boolean\n /** Fine-grained cookie configuration for multi-domain / secure deployments. */\n cookieOptions?: CookieOptions\n /**\n * Set to false to disable automatic locale detection.\n * Bare paths will always use `sourceLocale` instead of detecting from cookie / Accept-Language.\n *\n * Default: `true`\n */\n localeDetection?: boolean\n /**\n * Custom locale detection function. Called when no locale is present in the URL path.\n * Return a locale string to override the default chain, or `undefined` to fall through.\n */\n detectLocale?: (req: NextRequest) => string | undefined\n /**\n * Domain-based locale routing. Each domain maps to a default locale.\n * Domain matching is checked before cookie/Accept-Language detection.\n *\n * @example\n * ```ts\n * domains: [\n * { domain: 'fr.example.com', defaultLocale: 'fr' },\n * { domain: 'example.co.jp', defaultLocale: 'ja' },\n * ]\n * ```\n */\n domains?: DomainConfig[]\n /**\n * Map internal paths to localized paths per locale.\n * Supports dynamic segments: `[param]` and `[...slug]`.\n *\n * @example\n * ```ts\n * pathnames: {\n * '/about': { fr: '/a-propos' },\n * '/blog/[slug]': { fr: '/articles/[slug]' },\n * }\n * ```\n */\n pathnames?: Record<string, Record<string, string>>\n /**\n * When true, adds `Link` response headers with `rel=\"alternate\"` hreflang\n * and `rel=\"canonical\"` for SEO.\n *\n * Default: `false`\n */\n alternateLinks?: boolean\n /**\n * Custom function to build alternate link entries. Overrides default `alternateLinks` behavior.\n * Return an array of `{ href, hreflang }` entries.\n */\n getAlternateLinks?: (context: {\n pathname: string\n locale: string\n locales: string[]\n origin: string\n basePath: string\n }) => AlternateLinkEntry[]\n /**\n * Called before the middleware returns a response.\n * Modify headers, cookies, or return a replacement response.\n */\n beforeResponse?: (context: {\n response: NextResponseInstance\n request: NextRequest\n locale: string\n type: 'redirect' | 'rewrite' | 'next'\n }) => NextResponseInstance | void | undefined\n}\n\n/** Minimal request shape required by the middleware. Compatible with Next.js NextRequest. */\ntype NextRequest = {\n nextUrl: { pathname: string; search: string; basePath?: string }\n url: string\n cookies: { get(name: string): { value: string } | undefined }\n headers: Headers\n}\n\ntype NextResponseStatic<R extends NextResponseInstance = NextResponseInstance> = {\n redirect(url: URL): R\n rewrite(url: URL, init?: Record<string, unknown>): R\n next(init?: Record<string, unknown>): R\n}\n\ntype NextResponseInstance = {\n headers: { set(name: string, value: string): void }\n}\n\n/**\n * Create an i18n middleware function for Next.js.\n */\nexport function createI18nMiddleware<R extends NextResponseInstance = NextResponseInstance>(\n config: I18nMiddlewareConfig & { NextResponse: NextResponseStatic<R> },\n) {\n const { NextResponse } = config\n const resolvedLocales: string[] = config.locales ?? _configLocales\n const resolvedSourceLocale: string = config.sourceLocale ?? _configSourceLocale\n const cookieName = config.cookieName ?? _configCookieName\n const localePrefix = config.localePrefix ?? 'as-needed'\n const rewriteDefaultLocale = config.rewriteDefaultLocale ?? false\n const setCookieEnabled = config.setCookie ?? false\n const cookieOpts: CookieOptions = config.cookieOptions ?? {}\n const localeDetectionEnabled = config.localeDetection ?? true\n const alternateLinksEnabled = config.alternateLinks ?? false\n const pathnamesMap = config.pathnames\n const domainsConfig = config.domains\n const beforeResponse = config.beforeResponse\n\n function finalizeResponse(\n response: R,\n request: NextRequest,\n locale: string,\n type: 'redirect' | 'rewrite' | 'next',\n pathLocale: string | null,\n ): R {\n response.headers.set(LOCALE_HEADER, locale)\n if (setCookieEnabled) {\n maybeSetCookie(response, request, locale, cookieName, pathLocale, cookieOpts)\n }\n if (alternateLinksEnabled || config.getAlternateLinks) {\n const linkHeader = config.getAlternateLinks\n ? buildCustomAlternateLinks(config.getAlternateLinks, request, locale, resolvedLocales)\n : buildAlternateLinks(request, resolvedLocales, resolvedSourceLocale, localePrefix, request.nextUrl.basePath ?? '', pathnamesMap)\n response.headers.set('Link', linkHeader)\n }\n if (beforeResponse) {\n const replacement = beforeResponse({ response, request, locale, type })\n if (replacement) return replacement as R\n }\n return response\n }\n\n return function i18nMiddleware(request: NextRequest): R {\n const locales = resolvedLocales\n const sourceLocale = resolvedSourceLocale\n const { pathname, search } = request.nextUrl\n const basePath = request.nextUrl.basePath ?? ''\n\n // Extract locale from URL path ('never' mode skips this)\n const segments = pathname.split('/')\n const firstSegment = segments[1] ?? ''\n const pathLocale = localePrefix === 'never' ? null : findLocale(firstSegment, locales)\n\n // Determine the active locale\n let locale: string\n\n if (pathLocale) {\n locale = pathLocale\n } else if (!localeDetectionEnabled) {\n locale = sourceLocale\n } else {\n // Detection chain: custom → domains → cookie → Accept-Language → default\n const custom = config.detectLocale?.(request)\n if (custom !== undefined && findLocale(custom, locales) !== null) {\n locale = findLocale(custom, locales)!\n } else if (domainsConfig) {\n const domainLocale = detectFromDomain(request, domainsConfig, locales)\n locale = domainLocale ?? detectLocale(request, locales, sourceLocale, cookieName)\n } else {\n locale = detectLocale(request, locales, sourceLocale, cookieName)\n }\n }\n\n // Build request headers\n const requestHeaders = new Headers(request.headers)\n requestHeaders.set(LOCALE_HEADER, locale)\n\n // ── 'never' mode ──────────────────────────────────────────────────────\n if (localePrefix === 'never') {\n if (rewriteDefaultLocale) {\n const rewriteUrl = new URL(`${basePath}/${locale}${pathname}${search}`, request.url)\n return finalizeResponse(\n NextResponse.rewrite(rewriteUrl, { request: { headers: requestHeaders } }),\n request, locale, 'rewrite', null,\n )\n }\n return finalizeResponse(\n NextResponse.next({ request: { headers: requestHeaders } }),\n request, locale, 'next', null,\n )\n }\n\n // ── Pathnames mapping ─────────────────────────────────────────────────\n if (pathnamesMap && pathLocale) {\n const pathWithoutLocale = normalizeSlashes('/' + segments.slice(2).join('/'))\n const internalPath = resolveInternalPath(pathWithoutLocale, locale, pathnamesMap)\n\n if (internalPath) {\n const rewriteUrl = new URL(`${basePath}/${locale}${internalPath}${search}`, request.url)\n return finalizeResponse(\n NextResponse.rewrite(rewriteUrl, { request: { headers: requestHeaders } }),\n request, locale, 'rewrite', pathLocale,\n )\n }\n\n const localizedPath = resolveLocalizedPath(pathWithoutLocale, locale, pathnamesMap)\n if (localizedPath && localizedPath !== pathWithoutLocale) {\n const redirectUrl = new URL(`${basePath}/${locale}${localizedPath}${search}`, request.url)\n return finalizeResponse(\n NextResponse.redirect(redirectUrl),\n request, locale, 'redirect', pathLocale,\n )\n }\n }\n\n // ── Case 1: No locale in path → redirect ──────────────────────────────\n if (!pathLocale && (localePrefix === 'always' || locale !== sourceLocale)) {\n // If pathnames configured, redirect to localized path\n let targetPath = pathname\n if (pathnamesMap) {\n const localized = resolveLocalizedPath(pathname, locale, pathnamesMap)\n if (localized) targetPath = localized\n }\n const redirectUrl = new URL(`${basePath}/${locale}${targetPath}${search}`, request.url)\n return finalizeResponse(\n NextResponse.redirect(redirectUrl),\n request, locale, 'redirect', pathLocale,\n )\n }\n\n // ── Case 2: as-needed + source locale + rewriteDefaultLocale ──────────\n if (!pathLocale && locale === sourceLocale && rewriteDefaultLocale) {\n const rewriteUrl = new URL(`${basePath}/${sourceLocale}${pathname}${search}`, request.url)\n return finalizeResponse(\n NextResponse.rewrite(rewriteUrl, { request: { headers: requestHeaders } }),\n request, locale, 'rewrite', pathLocale,\n )\n }\n\n // ── Case 3: as-needed, source locale has explicit prefix → strip ──────\n if (localePrefix === 'as-needed' && pathLocale === sourceLocale) {\n const pathWithoutLocale = normalizeSlashes('/' + segments.slice(2).join('/'))\n if (rewriteDefaultLocale) {\n const redirectUrl = new URL(`${basePath}${pathWithoutLocale}${search}`, request.url)\n return finalizeResponse(\n NextResponse.redirect(redirectUrl),\n request, locale, 'redirect', pathLocale,\n )\n }\n const rewriteUrl = new URL(`${basePath}${pathWithoutLocale}${search}`, request.url)\n return finalizeResponse(\n NextResponse.rewrite(rewriteUrl, { request: { headers: requestHeaders } }),\n request, locale, 'rewrite', pathLocale,\n )\n }\n\n // ── Case 4/5: pass through ────────────────────────────────────────────\n return finalizeResponse(\n NextResponse.next({ request: { headers: requestHeaders } }),\n request, locale, 'next', pathLocale,\n )\n }\n}\n\n// ── Helpers ────────────────────────────────────────────────────────────────\n\nfunction findLocale(candidate: string, locales: string[]): string | null {\n if (!candidate) return null\n const lower = candidate.toLowerCase()\n return locales.find(l => l.toLowerCase() === lower) ?? null\n}\n\nfunction normalizeSlashes(path: string): string {\n return path.replace(/\\/+/g, '/') || '/'\n}\n\nfunction maybeSetCookie(\n response: NextResponseInstance,\n request: NextRequest,\n locale: string,\n cookieName: string,\n pathLocale: string | null,\n opts: CookieOptions,\n): void {\n if (pathLocale) return\n if (request.cookies.get(cookieName)?.value === locale) return\n\n const parts = [`${cookieName}=${encodeURIComponent(locale)}`]\n parts.push(`path=${opts.path ?? '/'}`)\n parts.push(`max-age=${opts.maxAge ?? 31536000}`)\n parts.push(`samesite=${opts.sameSite ?? 'lax'}`)\n if (opts.domain) parts.push(`domain=${opts.domain}`)\n if (opts.secure ?? request.url.startsWith('https')) parts.push('secure')\n response.headers.set('set-cookie', parts.join(';'))\n}\n\nfunction detectFromDomain(\n request: NextRequest,\n domains: DomainConfig[],\n locales: string[],\n): string | null {\n const host = request.headers.get('host')?.split(':')[0] ?? ''\n for (const d of domains) {\n if (host === d.domain || host.endsWith('.' + d.domain)) {\n const found = findLocale(d.defaultLocale, d.locales ?? locales)\n if (found) return found\n }\n }\n return null\n}\n\nfunction detectLocale(\n request: NextRequest,\n locales: string[],\n defaultLocale: string,\n cookieName: string,\n): string {\n const cookieLocale = request.cookies.get(cookieName)?.value\n if (cookieLocale) {\n const found = findLocale(cookieLocale, locales)\n if (found) return found\n }\n\n const acceptLang = request.headers.get('accept-language')\n if (acceptLang) {\n for (const part of acceptLang.split(',')) {\n const lang = part.split(';')[0]!.trim()\n const exact = findLocale(lang, locales)\n if (exact) return exact\n const prefix = lang.split('-')[0]!.toLowerCase()\n const match = locales.find(l => {\n const ll = l.toLowerCase()\n return ll === prefix || ll.startsWith(prefix + '-')\n })\n if (match) return match\n }\n }\n\n return defaultLocale\n}\n\nfunction stripLocalePrefix(pathname: string, locales: string[]): string {\n const segments = pathname.split('/')\n const first = segments[1] ?? ''\n if (findLocale(first, locales)) {\n return normalizeSlashes('/' + segments.slice(2).join('/'))\n }\n return pathname\n}\n\n// Path resolution utilities imported from shared routing module\n// (bundled by tsup, safe for Edge Runtime)\nimport { resolveInternalPath, resolveLocalizedPath } from './routing'\n\nfunction buildAlternateLinks(\n request: NextRequest,\n locales: string[],\n sourceLocale: string,\n localePrefix: 'always' | 'as-needed' | 'never',\n basePath: string,\n pathnames?: Record<string, Record<string, string>>,\n): string {\n const origin = new URL(request.url).origin\n const cleanPath = stripLocalePrefix(request.nextUrl.pathname, locales)\n const firstSegment = request.nextUrl.pathname.split('/')[1] ?? ''\n const requestLocale = localePrefix === 'never'\n ? sourceLocale\n : findLocale(firstSegment, locales) ?? sourceLocale\n const internalPath = pathnames\n ? resolveInternalPath(cleanPath, requestLocale, pathnames) ?? cleanPath\n : cleanPath\n\n const links = locales.map(loc => {\n const outwardPath = pathnames\n ? resolveLocalizedPath(internalPath, loc, pathnames) ?? internalPath\n : internalPath\n let localePath: string\n if (localePrefix === 'never') {\n localePath = outwardPath\n } else if (localePrefix === 'as-needed' && loc === sourceLocale) {\n localePath = outwardPath\n } else {\n localePath = `/${loc}${outwardPath}`\n }\n return `<${origin}${basePath}${localePath}>; rel=\"alternate\"; hreflang=\"${loc}\"`\n })\n\n // x-default\n const sourceOutwardPath = pathnames\n ? resolveLocalizedPath(internalPath, sourceLocale, pathnames) ?? internalPath\n : internalPath\n const defaultPath = localePrefix === 'always' ? `/${sourceLocale}${sourceOutwardPath}` : sourceOutwardPath\n links.push(`<${origin}${basePath}${defaultPath}>; rel=\"alternate\"; hreflang=\"x-default\"`)\n\n return links.join(', ')\n}\n\nfunction buildCustomAlternateLinks(\n getAlternateLinks: NonNullable<I18nMiddlewareConfig['getAlternateLinks']>,\n request: NextRequest,\n locale: string,\n locales: string[],\n): string {\n const origin = new URL(request.url).origin\n const cleanPath = stripLocalePrefix(request.nextUrl.pathname, locales)\n const basePath = request.nextUrl.basePath ?? ''\n const entries = getAlternateLinks({ pathname: cleanPath, locale, locales, origin, basePath })\n return entries.map(e => `<${e.href}>; rel=\"alternate\"; hreflang=\"${e.hreflang}\"`).join(', ')\n}\n"],"mappings":"wJA2CA,IAAa,EAAgB,mBAoJ7B,SAAgB,EACd,EACA,CACA,GAAM,CAAE,gBAAiB,EACnB,EAA4B,EAAO,SAAW,EAAA,QAC9C,EAA+B,EAAO,cAAgB,EAAA,aACtD,EAAa,EAAO,YAAc,EAAA,WAClC,EAAe,EAAO,cAAgB,YACtC,EAAuB,EAAO,sBAAwB,GACtD,EAAmB,EAAO,WAAa,GACvC,EAA4B,EAAO,eAAiB,EAAE,CACtD,EAAyB,EAAO,iBAA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