remix-intlayer 9.5.11 → 9.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.
@@ -1 +1 @@
1
- {"version":3,"file":"localeRouting.cjs","names":["ROUTING_MODE","resolveProxyMode","isProxyStorageLocaleEnabled","getRewriteRules","getCanonicalPath","getLocaleFromStorageServer","getCookie","localeDetector","resolveLocalizedPath","getDomainHostname","getDomainOrigin","getLocaleFromDomain"],"sources":["../../src/localeRouting.ts"],"sourcesContent":["import { ROUTING_MODE } from '@intlayer/config/defaultValues';\nimport {\n getCanonicalPath,\n getDomainHostname,\n getDomainOrigin,\n getLocaleFromDomain,\n getRewriteRules,\n isProxyStorageLocaleEnabled,\n localeDetector,\n resolveLocalizedPath,\n resolveProxyMode,\n} from '@intlayer/core/localization';\nimport { getCookie, getLocaleFromStorageServer } from '@intlayer/core/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\n\n/**\n * The part of an incoming request the locale routing is decided from.\n */\nexport type LocaleRoutingRequest = {\n url: URL;\n headers: Headers;\n};\n\n/**\n * What the locale routing decided for a request.\n *\n * - `pass` — leave the request untouched (proxy disabled, ignored path).\n * - `rewrite` — keep serving the request, but from `path` (locale prefix\n * stripped, rewrite rule resolved to its canonical path). `locale` is the\n * locale the request resolved to, absent for a static asset.\n * - `redirect` — answer with a redirect to `location`. `persistLocale` asks\n * for the locale to be stored on the response so the follow-up request\n * resolves the same locale.\n */\nexport type LocaleRoutingAction =\n | { kind: 'pass' }\n | { kind: 'rewrite'; path: string; locale?: Locale }\n | {\n kind: 'redirect';\n location: string;\n status: 301 | 302;\n persistLocale?: Locale;\n };\n\nexport type LocaleRoutingOptions = {\n /**\n * Whether a development server is serving the app. In `enableProxy: auto`\n * mode, a development server ignores the stored locale (cookie / header)\n * when deciding where a request goes, so a stale cookie cannot keep pulling\n * every navigation to another locale while developing.\n *\n * @default process.env.NODE_ENV === 'development'\n */\n isDevServer?: boolean;\n /**\n * Requests to leave untouched, in addition to static assets.\n */\n ignore?: (request: LocaleRoutingRequest) => boolean;\n};\n\nexport type LocaleRoutingConfiguration = Pick<\n IntlayerConfig,\n 'internationalization' | 'routing'\n>;\n\n/** Matches a pathname ending with a file extension (`/logo.svg`). */\nconst STATIC_ASSET_PATTERN = /\\.[a-zA-Z0-9]+$/;\n\nconst PASS: LocaleRoutingAction = { kind: 'pass' };\n\n/**\n * Decodes a pathname so it can be matched against the rewrite rules, which are\n * written with the characters the locale actually uses (`/doc/релизы`) while\n * the browser sends them percent-encoded. A malformed escape is kept as is.\n */\nconst decodePathname = (pathname: string): string => {\n try {\n return decodeURI(pathname);\n } catch {\n return pathname;\n }\n};\n\n/**\n * Removes a trailing slash, except on the root path. A redirect to `/fr/`\n * would otherwise ping-pong with any trailing-slash normalisation downstream.\n */\nconst trimTrailingSlash = (path: string): string =>\n path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path;\n\n/**\n * Removes `/{locale}` from the start of a pathname that carries that prefix.\n */\nconst stripLocalePrefix = (pathname: string, locale: Locale): string =>\n pathname.slice(`/${locale}`.length) || '/';\n\n/**\n * Builds the locale-routing resolver of a Remix application.\n *\n * Decides, for each request, whether to serve it as is, serve it from another\n * internal path, or redirect it — mirroring the Intlayer proxies of\n * `next-intlayer` and `vite-intlayer`. Unlike them, an internal rewrite hands\n * the router the path *without* its locale prefix: the Remix router has no\n * trailing-slash normalisation to work around, and this lets an application\n * declare each route once (`/about`) whatever the routing mode, the locale\n * being read from the request context instead of a route param.\n *\n * @param configuration - The `internationalization` and `routing` configuration.\n * @param options - Runtime options.\n * @returns A pure function deciding the routing of a request.\n *\n * @example\n * ```ts\n * const resolveLocaleRouting = createLocaleRouting(configuration);\n *\n * resolveLocaleRouting({ url: new URL('http://host/fr/about'), headers });\n * // { kind: 'rewrite', path: '/about', locale: 'fr' }\n * ```\n */\nexport const createLocaleRouting = (\n configuration: LocaleRoutingConfiguration,\n options: LocaleRoutingOptions = {}\n): ((request: LocaleRoutingRequest) => LocaleRoutingAction) => {\n const { isDevServer = process.env.NODE_ENV === 'development', ignore } =\n options;\n const { locales, defaultLocale } = configuration.internationalization;\n const {\n basePath = '',\n mode = ROUTING_MODE,\n rewrite,\n domains,\n enableProxy,\n } = configuration.routing ?? {};\n\n const proxyMode = resolveProxyMode(enableProxy);\n const canUseStorageLocale = isProxyStorageLocaleEnabled(\n proxyMode,\n isDevServer\n );\n\n const isSearchParamsMode = mode === 'search-params';\n const noPrefix = mode === 'no-prefix' || isSearchParamsMode;\n const prefixDefault = mode === 'prefix-all';\n const rewriteRules = getRewriteRules(rewrite, 'url');\n const normalizedBasePath = trimTrailingSlash(\n basePath && !basePath.startsWith('/') ? `/${basePath}` : basePath\n );\n\n const isSupportedLocale = (value: string | undefined): value is Locale =>\n value !== undefined && locales.includes(value as Locale);\n\n /**\n * Locale carried by the first path segment (`/fr/about` → `fr`).\n */\n const getPathLocale = (pathname: string): Locale | undefined => {\n const firstSegment = pathname.split('/')[1];\n\n return isSupportedLocale(firstSegment) ? firstSegment : undefined;\n };\n\n /**\n * Locale a localized (\"pretty\") path belongs to. `/a-propos` only exists\n * because a rewrite rule maps it to French, so it declares its locale as\n * explicitly as an `/fr` prefix would; rules whose localized path equals the\n * canonical one carry no signal and are skipped.\n */\n const getRewriteLocale = (pathname: string): Locale | undefined =>\n rewriteRules\n ? locales.find(\n (candidate) =>\n getCanonicalPath(pathname, candidate, rewriteRules) !== pathname\n )\n : undefined;\n\n /**\n * Locale persisted by the client (cookie / header), when it may be used as\n * a routing source.\n */\n const getStorageLocale = (headers: Headers): Locale | undefined =>\n canUseStorageLocale\n ? getLocaleFromStorageServer({\n getCookie: (name) =>\n getCookie(name, headers.get('cookie') ?? undefined),\n getHeader: (name) => headers.get(name),\n })\n : undefined;\n\n /**\n * Best locale for a request that names none: storage, then\n * `Accept-Language`, then the default locale.\n */\n const detectLocale = (headers: Headers): Locale => {\n const locale =\n getStorageLocale(headers) ??\n localeDetector(\n { 'accept-language': headers.get('accept-language') ?? undefined },\n locales,\n defaultLocale\n );\n\n return isSupportedLocale(locale) ? locale : defaultLocale;\n };\n\n /**\n * Query string of a URL, with the `locale` param set in `search-params` mode.\n */\n const withLocaleSearch = (search: string, locale: Locale): string => {\n if (!isSearchParamsMode) return search;\n\n const params = new URLSearchParams(search);\n params.set('locale', locale);\n\n return `?${params.toString()}`;\n };\n\n /**\n * Public path of an application path for a locale: base path, then the\n * locale prefix when the routing mode shows one for that locale.\n */\n const toPublicPath = (\n locale: Locale,\n path: string,\n search: string\n ): string => {\n const showPrefix = !noPrefix && (prefixDefault || locale !== defaultLocale);\n const prefixedPath = showPrefix\n ? `/${locale}${path === '/' ? '' : path}`\n : path;\n\n return `${normalizedBasePath}${trimTrailingSlash(prefixedPath)}${withLocaleSearch(search, locale)}`;\n };\n\n /**\n * Internal path handed to the router: base path plus the canonical path.\n */\n const toInternalPath = (path: string, search: string): string =>\n `${normalizedBasePath}${path}${search}`;\n\n const rewriteTo = (\n path: string,\n search: string,\n locale?: Locale\n ): LocaleRoutingAction => ({\n kind: 'rewrite',\n path: encodeURI(toInternalPath(path, search)),\n locale,\n });\n\n /**\n * Same-origin redirect. A target equal to the request itself is served in\n * place instead, so a configuration mismatch can never loop.\n */\n const redirectTo = (\n location: string,\n current: string,\n persistLocale?: Locale\n ): LocaleRoutingAction => {\n const encodedLocation = encodeURI(location);\n\n if (encodedLocation === current) return PASS;\n\n return persistLocale\n ? {\n kind: 'redirect',\n location: encodedLocation,\n status: 302,\n persistLocale,\n }\n : { kind: 'redirect', location: encodedLocation, status: 302 };\n };\n\n /**\n * `no-prefix` and `search-params` modes: the URL never shows a prefix.\n */\n const handleNoPrefix = (\n { url, headers }: LocaleRoutingRequest,\n pathname: string,\n current: string\n ): LocaleRoutingAction => {\n const pathLocale = getPathLocale(pathname);\n\n if (pathLocale) {\n const canonicalPath = getCanonicalPath(\n stripLocalePrefix(pathname, pathLocale),\n pathLocale,\n rewriteRules\n );\n\n // Stripping the prefix drops the only locale signal from the URL, so the\n // locale is persisted for the follow-up request.\n return redirectTo(\n toPublicPath(pathLocale, canonicalPath, url.search),\n current,\n pathLocale\n );\n }\n\n if (isSearchParamsMode) {\n const searchLocale = url.searchParams.get('locale') ?? undefined;\n const locale =\n getStorageLocale(headers) ??\n (isSupportedLocale(searchLocale) ? searchLocale : undefined) ??\n detectLocale(headers);\n const canonicalPath = getCanonicalPath(pathname, locale, rewriteRules);\n\n return searchLocale === locale\n ? rewriteTo(canonicalPath, url.search, locale)\n : redirectTo(\n `${normalizedBasePath}${pathname}${withLocaleSearch(url.search, locale)}`,\n current\n );\n }\n\n const locale = getRewriteLocale(pathname) ?? detectLocale(headers);\n\n return rewriteTo(\n getCanonicalPath(pathname, locale, rewriteRules),\n url.search,\n locale\n );\n };\n\n /**\n * Prefix modes, URL without a locale prefix: redirect to the localized URL\n * when the mode shows a prefix for the resolved locale, serve it otherwise.\n */\n const handleMissingPathLocale = (\n { url, headers }: LocaleRoutingRequest,\n pathname: string,\n current: string\n ): LocaleRoutingAction => {\n // A localized path names its own locale and outranks storage and\n // `Accept-Language`, otherwise `/a-propos` read as `en` matches no rule.\n const locale = getRewriteLocale(pathname) ?? detectLocale(headers);\n const canonicalPath = getCanonicalPath(pathname, locale, rewriteRules);\n\n if (prefixDefault || locale !== defaultLocale) {\n const { path: localizedPath } = resolveLocalizedPath(\n canonicalPath,\n locale,\n rewriteRules\n );\n\n return redirectTo(\n toPublicPath(locale, localizedPath, url.search),\n current\n );\n }\n\n return rewriteTo(canonicalPath, url.search, locale);\n };\n\n /**\n * Prefix modes, URL with a locale prefix: normalise it to its localized\n * form, strip the prefix of the default locale when the mode hides it, and\n * serve the canonical path.\n */\n const handleExistingPathLocale = (\n { url }: LocaleRoutingRequest,\n pathname: string,\n pathLocale: Locale,\n current: string\n ): LocaleRoutingAction => {\n const rawPath = stripLocalePrefix(pathname, pathLocale);\n const canonicalPath = getCanonicalPath(rawPath, pathLocale, rewriteRules);\n const { path: localizedPath, isRewritten } = resolveLocalizedPath(\n canonicalPath,\n pathLocale,\n rewriteRules\n );\n\n // `/fr/about` → `/fr/a-propos`\n if (isRewritten && localizedPath !== rawPath) {\n return redirectTo(\n toPublicPath(pathLocale, localizedPath, url.search),\n current\n );\n }\n\n // `/en/about` → `/about`. The locale is persisted: the target no longer\n // names it, and detection could otherwise resolve another one.\n if (!prefixDefault && pathLocale === defaultLocale) {\n return redirectTo(\n toPublicPath(pathLocale, localizedPath, url.search),\n current,\n pathLocale\n );\n }\n\n return rewriteTo(canonicalPath, url.search, pathLocale);\n };\n\n return (request): LocaleRoutingAction => {\n if (proxyMode === 'disabled' || ignore?.(request)) return PASS;\n\n const { url } = request;\n const fullPathname = decodePathname(url.pathname);\n\n if (\n normalizedBasePath &&\n fullPathname !== normalizedBasePath &&\n !fullPathname.startsWith(`${normalizedBasePath}/`)\n ) {\n return PASS;\n }\n\n const pathname = fullPathname.slice(normalizedBasePath.length) || '/';\n const current = `${url.pathname}${url.search}`;\n const pathLocale = getPathLocale(pathname);\n\n // Static assets are served from their unprefixed path, untouched otherwise.\n if (STATIC_ASSET_PATTERN.test(pathname)) {\n return pathLocale\n ? rewriteTo(stripLocalePrefix(pathname, pathLocale), url.search)\n : PASS;\n }\n\n if (noPrefix) return handleNoPrefix(request, pathname, current);\n\n // `host/zh/about` → `https://host.zh/about` when `zh` has its own domain.\n // Domain mapping is stable configuration, hence a cacheable 301.\n const localeDomain = pathLocale && domains?.[pathLocale];\n\n if (localeDomain && getDomainHostname(localeDomain) !== url.hostname) {\n return {\n kind: 'redirect',\n location: `${getDomainOrigin(localeDomain)}${encodeURI(stripLocalePrefix(pathname, pathLocale))}${url.search}`,\n status: 301,\n };\n }\n\n // `host.zh/about` → `/about` as `zh`: the hostname alone names the locale.\n if (!pathLocale) {\n const domainLocale = getLocaleFromDomain(url.hostname, domains);\n\n if (domainLocale) {\n return rewriteTo(\n getCanonicalPath(pathname, domainLocale, rewriteRules),\n url.search,\n domainLocale\n );\n }\n\n return handleMissingPathLocale(request, pathname, current);\n }\n\n return handleExistingPathLocale(request, pathname, pathLocale, current);\n };\n};\n"],"mappings":";;;;;;;AAmEA,MAAM,uBAAuB;AAE7B,MAAM,OAA4B,EAAE,MAAM,OAAO;;;;;;AAOjD,MAAM,kBAAkB,aAA6B;CACnD,IAAI;EACF,OAAO,UAAU,QAAQ;CAC3B,QAAQ;EACN,OAAO;CACT;AACF;;;;;AAMA,MAAM,qBAAqB,SACzB,KAAK,SAAS,KAAK,KAAK,SAAS,GAAG,IAAI,KAAK,MAAM,GAAG,EAAE,IAAI;;;;AAK9D,MAAM,qBAAqB,UAAkB,WAC3C,SAAS,MAAM,IAAI,SAAS,MAAM,KAAK;;;;;;;;;;;;;;;;;;;;;;;;AAyBzC,MAAa,uBACX,eACA,UAAgC,CAAC,MAC4B;CAC7D,MAAM,EAAE,cAAc,QAAQ,IAAI,aAAa,eAAe,WAC5D;CACF,MAAM,EAAE,SAAS,kBAAkB,cAAc;CACjD,MAAM,EACJ,WAAW,IACX,OAAOA,6CACP,SACA,SACA,gBACE,cAAc,WAAW,CAAC;CAE9B,MAAM,gBAAYC,8CAAiB,WAAW;CAC9C,MAAM,0BAAsBC,yDAC1B,WACA,WACF;CAEA,MAAM,qBAAqB,SAAS;CACpC,MAAM,WAAW,SAAS,eAAe;CACzC,MAAM,gBAAgB,SAAS;CAC/B,MAAM,mBAAeC,6CAAgB,SAAS,KAAK;CACnD,MAAM,qBAAqB,kBACzB,YAAY,CAAC,SAAS,WAAW,GAAG,IAAI,IAAI,aAAa,QAC3D;CAEA,MAAM,qBAAqB,UACzB,UAAU,UAAa,QAAQ,SAAS,KAAe;;;;CAKzD,MAAM,iBAAiB,aAAyC;EAC9D,MAAM,eAAe,SAAS,MAAM,GAAG,CAAC,CAAC;EAEzC,OAAO,kBAAkB,YAAY,IAAI,eAAe;CAC1D;;;;;;;CAQA,MAAM,oBAAoB,aACxB,eACI,QAAQ,MACL,k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getLocaleFromStorageServer","getCookie","localeDetector","resolveLocalizedPath","getDomainHostname","getDomainOrigin","getLocaleFromDomain"],"sources":["../../src/localeRouting.ts"],"sourcesContent":["import { ROUTING_MODE } from '@intlayer/config/defaultValues';\nimport {\n getCanonicalPath,\n getDomainHostname,\n getDomainOrigin,\n getLocaleFromDomain,\n getRewriteRules,\n isProxyStorageLocaleEnabled,\n localeDetector,\n resolveLocalizedPath,\n resolveProxyMode,\n} from '@intlayer/core/localization';\nimport { getCookie, getLocaleFromStorageServer } from '@intlayer/core/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\n\n/**\n * The part of an incoming request the locale routing is decided from.\n */\nexport type LocaleRoutingRequest = {\n url: URL;\n headers: Headers;\n};\n\n/**\n * What the locale routing decided for a request.\n *\n * - `pass` — leave the request untouched (proxy disabled, ignored path).\n * - `rewrite` — keep serving the request, but from `path` (locale prefix\n * stripped, rewrite rule resolved to its canonical path). `locale` is the\n * locale the request resolved to, absent for a static asset.\n * - `redirect` — answer with a redirect to `location`. `persistLocale` asks\n * for the locale to be stored on the response so the follow-up request\n * resolves the same locale.\n */\nexport type LocaleRoutingAction =\n | { kind: 'pass' }\n | { kind: 'rewrite'; path: string; locale?: Locale }\n | {\n kind: 'redirect';\n location: string;\n status: 301 | 302;\n persistLocale?: Locale;\n };\n\nexport type LocaleRoutingOptions = {\n /**\n * Whether a development server is serving the app. In `enableProxy: auto`\n * mode, a development server ignores the stored locale (cookie / header)\n * when deciding where a request goes, so a stale cookie cannot keep pulling\n * every navigation to another locale while developing.\n *\n * @default process.env.NODE_ENV === 'development'\n */\n isDevServer?: boolean;\n /**\n * Requests to leave untouched, in addition to static assets.\n */\n ignore?: (request: LocaleRoutingRequest) => boolean;\n};\n\nexport type LocaleRoutingConfiguration = Pick<\n IntlayerConfig,\n 'internationalization' | 'routing'\n>;\n\n/** Matches a pathname ending with a file extension (`/logo.svg`). */\nconst STATIC_ASSET_PATTERN = /\\.[a-zA-Z0-9]+$/;\n\nconst PASS: LocaleRoutingAction = { kind: 'pass' };\n\n/**\n * Decodes a pathname so it can be matched against the rewrite rules, which are\n * written with the characters the locale actually uses (`/doc/релизы`) while\n * the browser sends them percent-encoded. A malformed escape is kept as is.\n */\nconst decodePathname = (pathname: string): string => {\n try {\n return decodeURI(pathname);\n } catch {\n return pathname;\n }\n};\n\n/**\n * Removes a trailing slash, except on the root path. A redirect to `/fr/`\n * would otherwise ping-pong with any trailing-slash normalisation downstream.\n */\nconst trimTrailingSlash = (path: string): string =>\n path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path;\n\n/**\n * Removes `/{locale}` from the start of a pathname that carries that prefix.\n */\nconst stripLocalePrefix = (pathname: string, locale: Locale): string =>\n pathname.slice(`/${locale}`.length) || '/';\n\n/**\n * Builds the locale-routing resolver of a Remix application.\n *\n * Decides, for each request, whether to serve it as is, serve it from another\n * internal path, or redirect it — mirroring the Intlayer proxies of\n * `next-intlayer` and `vite-intlayer`. Unlike them, an internal rewrite hands\n * the router the path *without* its locale prefix: the Remix router has no\n * trailing-slash normalisation to work around, and this lets an application\n * declare each route once (`/about`) whatever the routing mode, the locale\n * being read from the request context instead of a route param.\n *\n * @param configuration - The `internationalization` and `routing` configuration.\n * @param options - Runtime options.\n * @returns A pure function deciding the routing of a request.\n *\n * @example\n * ```ts\n * const resolveLocaleRouting = createLocaleRouting(configuration);\n *\n * resolveLocaleRouting({ url: new URL('http://host/fr/about'), headers });\n * // { kind: 'rewrite', path: '/about', locale: 'fr' }\n * ```\n */\nexport const createLocaleRouting = (\n configuration: LocaleRoutingConfiguration,\n options: LocaleRoutingOptions = {}\n): ((request: LocaleRoutingRequest) => LocaleRoutingAction) => {\n const { isDevServer = process.env.NODE_ENV === 'development', ignore } =\n options;\n const { locales, defaultLocale } = configuration.internationalization;\n const {\n basePath = '',\n mode = ROUTING_MODE,\n rewrite,\n domains,\n enableProxy,\n } = configuration.routing ?? {};\n\n const proxyMode = resolveProxyMode(enableProxy);\n const canUseStorageLocale = isProxyStorageLocaleEnabled(\n proxyMode,\n isDevServer\n );\n\n const isSearchParamsMode = mode === 'search-params';\n const noPrefix = mode === 'no-prefix' || isSearchParamsMode;\n const prefixDefault = mode === 'prefix-all';\n const rewriteRules = getRewriteRules(rewrite, 'url');\n const normalizedBasePath = trimTrailingSlash(\n basePath && !basePath.startsWith('/') ? `/${basePath}` : basePath\n );\n\n const isSupportedLocale = (value: string | undefined): value is Locale =>\n value !== undefined && locales.includes(value as Locale);\n\n /**\n * Locale carried by the first path segment (`/fr/about` → `fr`).\n */\n const getPathLocale = (pathname: string): Locale | undefined => {\n const firstSegment = pathname.split('/')[1];\n\n return isSupportedLocale(firstSegment) ? firstSegment : undefined;\n };\n\n /**\n * Locale a localized (\"pretty\") path belongs to. `/a-propos` only exists\n * because a rewrite rule maps it to French, so it declares its locale as\n * explicitly as an `/fr` prefix would; rules whose localized path equals the\n * canonical one carry no signal and are skipped.\n */\n const getRewriteLocale = (pathname: string): Locale | undefined =>\n rewriteRules\n ? locales.find(\n (candidate) =>\n getCanonicalPath(pathname, candidate, rewriteRules) !== pathname\n )\n : undefined;\n\n /**\n * Locale persisted by the client (cookie / header), when it may be used as\n * a routing source.\n */\n const getStorageLocale = (headers: Headers): Locale | undefined =>\n canUseStorageLocale\n ? getLocaleFromStorageServer({\n getCookie: (name) =>\n getCookie(name, headers.get('cookie') ?? undefined),\n getHeader: (name) => headers.get(name),\n })\n : undefined;\n\n /**\n * Best locale for a request that names none: storage, then\n * `Accept-Language`, then the default locale.\n */\n const detectLocale = (headers: Headers): Locale => {\n const locale =\n getStorageLocale(headers) ??\n localeDetector(\n { 'accept-language': headers.get('accept-language') ?? undefined },\n locales,\n defaultLocale\n );\n\n return isSupportedLocale(locale) ? locale : defaultLocale;\n };\n\n /**\n * Query string of a URL, with the `locale` param set in `search-params` mode.\n */\n const withLocaleSearch = (search: string, locale: Locale): string => {\n if (!isSearchParamsMode) return search;\n\n const params = new URLSearchParams(search);\n params.set('locale', locale);\n\n return `?${params.toString()}`;\n };\n\n /**\n * Public path of an application path for a locale: base path, then the\n * locale prefix when the routing mode shows one for that locale.\n */\n const toPublicPath = (\n locale: Locale,\n path: string,\n search: string\n ): string => {\n const showPrefix = !noPrefix && (prefixDefault || locale !== defaultLocale);\n const prefixedPath = showPrefix\n ? `/${locale}${path === '/' ? '' : path}`\n : path;\n\n return `${normalizedBasePath}${trimTrailingSlash(prefixedPath)}${withLocaleSearch(search, locale)}`;\n };\n\n /**\n * Internal path handed to the router: base path plus the canonical path.\n */\n const toInternalPath = (path: string, search: string): string =>\n `${normalizedBasePath}${path}${search}`;\n\n const rewriteTo = (\n path: string,\n search: string,\n locale?: Locale\n ): LocaleRoutingAction => ({\n kind: 'rewrite',\n path: encodeURI(toInternalPath(path, search)),\n locale,\n });\n\n /**\n * Same-origin redirect. A target equal to the request itself is served in\n * place instead, so a configuration mismatch can never loop.\n */\n const redirectTo = (\n location: string,\n current: string,\n persistLocale?: Locale\n ): LocaleRoutingAction => {\n const encodedLocation = encodeURI(location);\n\n if (encodedLocation === current) return PASS;\n\n return persistLocale\n ? {\n kind: 'redirect',\n location: encodedLocation,\n status: 302,\n persistLocale,\n }\n : { kind: 'redirect', location: encodedLocation, status: 302 };\n };\n\n /**\n * `no-prefix` and `search-params` modes: the URL never shows a prefix.\n */\n const handleNoPrefix = (\n { url, headers }: LocaleRoutingRequest,\n pathname: string,\n current: string\n ): LocaleRoutingAction => {\n const pathLocale = getPathLocale(pathname);\n\n if (pathLocale) {\n const canonicalPath = getCanonicalPath(\n stripLocalePrefix(pathname, pathLocale),\n pathLocale,\n rewriteRules\n );\n\n // Stripping the prefix drops the only locale signal from the URL, so the\n // locale is persisted for the follow-up request.\n return redirectTo(\n toPublicPath(pathLocale, canonicalPath, url.search),\n current,\n pathLocale\n );\n }\n\n if (isSearchParamsMode) {\n const searchLocale = url.searchParams.get('locale') ?? undefined;\n const locale =\n getStorageLocale(headers) ??\n (isSupportedLocale(searchLocale) ? searchLocale : undefined) ??\n detectLocale(headers);\n const canonicalPath = getCanonicalPath(pathname, locale, rewriteRules);\n\n return searchLocale === locale\n ? rewriteTo(canonicalPath, url.search, locale)\n : redirectTo(\n `${normalizedBasePath}${pathname}${withLocaleSearch(url.search, locale)}`,\n current\n );\n }\n\n const locale = getRewriteLocale(pathname) ?? detectLocale(headers);\n\n return rewriteTo(\n getCanonicalPath(pathname, locale, rewriteRules),\n url.search,\n locale\n );\n };\n\n /**\n * Prefix modes, URL without a locale prefix: redirect to the localized URL\n * when the mode shows a prefix for the resolved locale, serve it otherwise.\n */\n const handleMissingPathLocale = (\n { url, headers }: LocaleRoutingRequest,\n pathname: string,\n current: string\n ): LocaleRoutingAction => {\n // A localized path names its own locale and outranks storage and\n // `Accept-Language`, otherwise `/a-propos` read as `en` matches no rule.\n const locale = getRewriteLocale(pathname) ?? detectLocale(headers);\n const canonicalPath = getCanonicalPath(pathname, locale, rewriteRules);\n\n if (prefixDefault || locale !== defaultLocale) {\n const { path: localizedPath } = resolveLocalizedPath(\n canonicalPath,\n locale,\n rewriteRules\n );\n\n return redirectTo(\n toPublicPath(locale, localizedPath, url.search),\n current\n );\n }\n\n return rewriteTo(canonicalPath, url.search, locale);\n };\n\n /**\n * Prefix modes, URL with a locale prefix: normalise it to its localized\n * form, strip the prefix of the default locale when the mode hides it, and\n * serve the canonical path.\n */\n const handleExistingPathLocale = (\n { url }: LocaleRoutingRequest,\n pathname: string,\n pathLocale: Locale,\n current: string\n ): LocaleRoutingAction => {\n const rawPath = stripLocalePrefix(pathname, pathLocale);\n const canonicalPath = getCanonicalPath(rawPath, pathLocale, rewriteRules);\n const { path: localizedPath, isRewritten } = resolveLocalizedPath(\n canonicalPath,\n pathLocale,\n rewriteRules\n );\n\n // `/fr/about` → `/fr/a-propos`\n if (isRewritten && localizedPath !== rawPath) {\n return redirectTo(\n toPublicPath(pathLocale, localizedPath, url.search),\n current\n );\n }\n\n // `/en/about` → `/about`. The locale is persisted: the target no longer\n // names it, and detection could otherwise resolve another one.\n if (!prefixDefault && pathLocale === defaultLocale) {\n return redirectTo(\n toPublicPath(pathLocale, localizedPath, url.search),\n current,\n pathLocale\n );\n }\n\n return rewriteTo(canonicalPath, url.search, pathLocale);\n };\n\n return (request): LocaleRoutingAction => {\n if (proxyMode === 'disabled' || ignore?.(request)) return PASS;\n\n const { url } = request;\n const fullPathname = decodePathname(url.pathname);\n\n if (\n normalizedBasePath &&\n fullPathname !== normalizedBasePath &&\n !fullPathname.startsWith(`${normalizedBasePath}/`)\n ) {\n return PASS;\n }\n\n const pathname = fullPathname.slice(normalizedBasePath.length) || '/';\n const current = `${url.pathname}${url.search}`;\n const pathLocale = getPathLocale(pathname);\n\n // Static assets are served from their unprefixed path, untouched otherwise.\n if (STATIC_ASSET_PATTERN.test(pathname)) {\n return pathLocale\n ? rewriteTo(stripLocalePrefix(pathname, pathLocale), url.search)\n : PASS;\n }\n\n if (noPrefix) return handleNoPrefix(request, pathname, current);\n\n // `host/zh/about` → `https://host.zh/about` when `zh` has its own domain.\n // Domain mapping is stable configuration, hence a cacheable 301.\n const localeDomain = pathLocale && domains?.[pathLocale];\n\n if (localeDomain && getDomainHostname(localeDomain) !== url.hostname) {\n return {\n kind: 'redirect',\n location: `${getDomainOrigin(localeDomain)}${encodeURI(stripLocalePrefix(pathname, pathLocale))}${url.search}`,\n status: 301,\n };\n }\n\n // `host.zh/about` → `/about` as `zh`: the hostname alone names the locale.\n if (!pathLocale) {\n const domainLocale = getLocaleFromDomain(url.hostname, domains);\n\n if (domainLocale) {\n return rewriteTo(\n getCanonicalPath(pathname, domainLocale, rewriteRules),\n url.search,\n domainLocale\n );\n }\n\n return handleMissingPathLocale(request, pathname, current);\n }\n\n return handleExistingPathLocale(request, pathname, pathLocale, current);\n };\n};\n"],"mappings":";;;;;;;AAmEA,MAAM,uBAAuB;AAE7B,MAAM,OAA4B,EAAE,MAAM,OAAO;;;;;;AAOjD,MAAM,kBAAkB,aAA6B;CACn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,OAAO,GAAG,OAAO;EAE1D,MAAM,EAAE,QAAQ;EAChB,MAAM,eAAe,eAAe,IAAI,QAAQ;EAEhD,IACE,sBACA,iBAAiB,sBACjB,CAAC,aAAa,WAAW,GAAG,mBAAmB,EAAE,GAEjD,OAAO;EAGT,MAAM,WAAW,aAAa,MAAM,mBAAmB,MAAM,KAAK;EAClE,MAAM,UAAU,GAAG,IAAI,WAAW,IAAI;EACtC,MAAM,aAAa,cAAc,QAAQ;EAGzC,IAAI,qBAAqB,KAAK,QAAQ,GACpC,OAAO,aACH,UAAU,kBAAkB,UAAU,UAAU,GAAG,IAAI,MAAM,IAC7D;EAGN,IAAI,UAAU,OAAO,eAAe,SAAS,UAAU,OAAO;EAI9D,MAAM,eAAe,cAAc,UAAU;EAE7C,IAAI,oBAAgBC,+CAAkB,YAAY,MAAM,IAAI,UAC1D,OAAO;GACL,MAAM;GACN,UAAU,OAAGC,6CAAgB,YAAY,IAAI,UAAU,kBAAkB,UAAU,UAAU,CAAC,IAAI,IAAI;GACtG,QAAQ;EACV;EAIF,IAAI,CAAC,YAAY;GACf,MAAM,mBAAeC,iDAAoB,IAAI,UAAU,OAAO;GAE9D,IAAI,cACF,OAAO,cACLP,8CAAiB,UAAU,cAAc,YAAY,GACrD,IAAI,QACJ,YACF;GAGF,OAAO,wBAAwB,SAAS,UAAU,OAAO;EAC3D;EAEA,OAAO,yBAAyB,SAAS,UAAU,YAAY,OAAO;CACxE;AACF"}
@@ -62,7 +62,7 @@ const createRedirectResponse = (action) => {
62
62
  */
63
63
  const intlayer = (options = {}) => {
64
64
  const configuration = (0, _intlayer_config_node.getConfiguration)();
65
- (0, _intlayer_engine_build.prepareIntlayer)(configuration);
65
+ (0, _intlayer_engine_build.prepareIntlayerServer)(configuration, { label: "remix-intlayer" });
66
66
  const resolveLocaleRouting = require_localeRouting.createLocaleRouting({
67
67
  internationalization: configuration.internationalization ?? _intlayer_config_built.internationalization,
68
68
  routing: configuration.routing ?? _intlayer_config_built.routing
@@ -1 +1 @@
1
- {"version":3,"file":"middleware.cjs","names":["getConfiguration","createLocaleRouting","internationalization","routing","getLocaleFromRequest","Intlayer","INTLAYER_CONTEXT_PROPERTY","requestStorage","withLocaleHeaders"],"sources":["../../src/middleware.ts"],"sourcesContent":["import { internationalization, routing } from '@intlayer/config/built';\nimport { getConfiguration } from '@intlayer/config/node';\nimport { getLocaleFromRequest } from '@intlayer/core/localization';\nimport { prepareIntlayer } from '@intlayer/engine/build';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { DeclaredLocales } from '@intlayer/types/module_augmentation';\nimport type { Middleware } from 'remix/router';\nimport {\n INTLAYER_CONTEXT_PROPERTY,\n Intlayer,\n type IntlayerState,\n} from './context';\nimport {\n createLocaleRouting,\n type LocaleRoutingAction,\n type LocaleRoutingOptions,\n} from './localeRouting';\nimport { withLocaleHeaders, writeLocaleHeaders } from './persistLocale';\nimport { requestStorage } from './requestStorage';\n\nexport type IntlayerMiddlewareOptions = LocaleRoutingOptions;\n\n/**\n * Builds the redirect response of a locale-routing decision.\n *\n * Built by hand rather than with `Response.redirect`, whose headers are\n * immutable and could not carry the locale cookie.\n */\nconst createRedirectResponse = (\n action: Extract<LocaleRoutingAction, { kind: 'redirect' }>\n): Response => {\n const headers = new Headers({ location: action.location });\n\n if (action.persistLocale) {\n writeLocaleHeaders(headers, action.persistLocale, { includeCookie: true });\n }\n\n return new Response(null, { status: action.status, headers });\n};\n\n/**\n * Remix 3 router middleware handling the internationalization layer:\n * locale routing (redirects and internal rewrites, as `next-intlayer` and\n * `vite-intlayer` do), locale resolution and locale persistence.\n *\n * Locale routing follows `routing.mode`. In the prefix modes, `/fr/about` is\n * served from the `/about` route as French, `/about` is redirected to the\n * localized URL of the detected locale (cookie / header, then\n * `Accept-Language`) unless that locale needs no prefix, and `routing.rewrite`\n * rules are applied both ways (`/fr/about` → `/fr/a-propos`). The router\n * therefore matches every locale against the same unprefixed routes, and\n * `routing.enableProxy: false` turns the routing off while keeping the\n * locale resolution.\n *\n * The resolved locale is exposed as `context.get(Intlayer)` /\n * `context.intlayer`, and the rest of the request runs inside an\n * `AsyncLocalStorage` scope bound to the request context, so the hooks of this\n * package (`useLocale`, `useIntlayer`, `useDictionary`) read that state from\n * anywhere downstream — route handlers, views, Remix UI components — with the\n * same signature as `react-intlayer`.\n *\n * @param options - Locale-routing options.\n *\n * @example\n * ```ts\n * import { createRouter } from 'remix/router';\n * import { intlayer, useIntlayer } from 'remix-intlayer';\n *\n * const router = createRouter({ middleware: [intlayer()] });\n *\n * // Serves `/`, `/fr`, `/es`… — the locale comes from the request context.\n * router.get('/', () => {\n * const { title } = useIntlayer('home');\n * return new Response(title);\n * });\n * ```\n */\nexport const intlayer = (\n options: IntlayerMiddlewareOptions = {}\n): Middleware<{\n key: typeof Intlayer;\n value: IntlayerState;\n property: typeof INTLAYER_CONTEXT_PROPERTY;\n}> => {\n // Ensures the generated dictionaries exist when the server starts without a\n // prior `intlayer build`. Fire-and-forget, like the other server integrations.\n const configuration = getConfiguration();\n prepareIntlayer(configuration);\n\n const resolveLocaleRouting = createLocaleRouting(\n {\n internationalization:\n configuration.internationalization ?? internationalization,\n routing: configuration.routing ?? routing,\n },\n options\n );\n\n return async (context, next) => {\n const action = resolveLocaleRouting(context);\n\n if (action.kind === 'redirect') return createRedirectResponse(action);\n\n let routedLocale: Locale | undefined;\n\n if (action.kind === 'rewrite') {\n // The router matches against `context.url`, so reassigning it is the\n // internal rewrite. The original request stays untouched.\n context.url = new URL(action.path, context.url);\n routedLocale = action.locale;\n }\n\n const locale =\n routedLocale ?? ((await getLocaleFromRequest(context)) as Locale);\n\n if (routedLocale) {\n // Propagates the locale downstream through the configured storage\n // header, like the Next.js and Vite proxies do.\n writeLocaleHeaders(context.headers, routedLocale);\n }\n\n context.set(\n Intlayer,\n {\n locale: locale as DeclaredLocales,\n defaultLocale: (configuration.internationalization?.defaultLocale ??\n internationalization.defaultLocale) as DeclaredLocales,\n availableLocales: (configuration.internationalization?.locales ??\n internationalization.locales) as DeclaredLocales[],\n },\n { property: INTLAYER_CONTEXT_PROPERTY }\n );\n\n const response = await requestStorage.run(context, next);\n\n return routedLocale ? withLocaleHeaders(response, routedLocale) : response;\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AA4BA,MAAM,0BACJ,WACa;CACb,MAAM,UAAU,IAAI,QAAQ,EAAE,UAAU,OAAO,SAAS,CAAC;CAEzD,IAAI,OAAO,eACT,yCAAmB,SAAS,OAAO,eAAe,EAAE,eAAe,KAAK,CAAC;CAG3E,OAAO,IAAI,SAAS,MAAM;EAAE,QAAQ,OAAO;EAAQ;CAAQ,CAAC;AAC9D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,MAAa,YACX,UAAqC,CAAC,MAKlC;CAGJ,MAAM,oBAAgBA,wCAAiB;CACvC,4CAAgB,aAAa;CAE7B,MAAM,uBAAuBC,0CAC3B;EACE,sBACE,cAAc,wBAAwBC;EACxC,SAAS,cAAc,WAAWC;CACpC,GACA,OACF;CAEA,OAAO,OAAO,SAAS,SAAS;EAC9B,MAAM,SAAS,qBAAqB,OAAO;EAE3C,IAAI,OAAO,SAAS,YAAY,OAAO,uBAAuB,MAAM;EAEpE,IAAI;EAEJ,IAAI,OAAO,SAAS,WAAW;GAG7B,QAAQ,MAAM,IAAI,IAAI,OAAO,MAAM,QAAQ,GAAG;GAC9C,eAAe,OAAO;EACxB;EAEA,MAAM,SACJ,gBAAkB,UAAMC,kDAAqB,OAAO;EAEtD,IAAI,cAGF,yCAAmB,QAAQ,SAAS,YAAY;EAGlD,QAAQ,IACNC,0BACA;GACU;GACR,eAAgB,cAAc,sBAAsB,iBAClDH,4CAAqB;GACvB,kBAAmB,cAAc,sBAAsB,WACrDA,4CAAqB;EACzB,GACA,EAAE,UAAUI,0CAA0B,CACxC;EAEA,MAAM,WAAW,MAAMC,sCAAe,IAAI,SAAS,IAAI;EAEvD,OAAO,eAAeC,wCAAkB,UAAU,YAAY,IAAI;CACpE;AACF"}
1
+ {"version":3,"file":"middleware.cjs","names":["getConfiguration","createLocaleRouting","internationalization","routing","getLocaleFromRequest","Intlayer","INTLAYER_CONTEXT_PROPERTY","requestStorage","withLocaleHeaders"],"sources":["../../src/middleware.ts"],"sourcesContent":["import { internationalization, routing } from '@intlayer/config/built';\nimport { getConfiguration } from '@intlayer/config/node';\nimport { getLocaleFromRequest } from '@intlayer/core/localization';\nimport { prepareIntlayerServer } from '@intlayer/engine/build';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { DeclaredLocales } from '@intlayer/types/module_augmentation';\nimport type { Middleware } from 'remix/router';\nimport {\n INTLAYER_CONTEXT_PROPERTY,\n Intlayer,\n type IntlayerState,\n} from './context';\nimport {\n createLocaleRouting,\n type LocaleRoutingAction,\n type LocaleRoutingOptions,\n} from './localeRouting';\nimport { withLocaleHeaders, writeLocaleHeaders } from './persistLocale';\nimport { requestStorage } from './requestStorage';\n\nexport type IntlayerMiddlewareOptions = LocaleRoutingOptions;\n\n/**\n * Builds the redirect response of a locale-routing decision.\n *\n * Built by hand rather than with `Response.redirect`, whose headers are\n * immutable and could not carry the locale cookie.\n */\nconst createRedirectResponse = (\n action: Extract<LocaleRoutingAction, { kind: 'redirect' }>\n): Response => {\n const headers = new Headers({ location: action.location });\n\n if (action.persistLocale) {\n writeLocaleHeaders(headers, action.persistLocale, { includeCookie: true });\n }\n\n return new Response(null, { status: action.status, headers });\n};\n\n/**\n * Remix 3 router middleware handling the internationalization layer:\n * locale routing (redirects and internal rewrites, as `next-intlayer` and\n * `vite-intlayer` do), locale resolution and locale persistence.\n *\n * Locale routing follows `routing.mode`. In the prefix modes, `/fr/about` is\n * served from the `/about` route as French, `/about` is redirected to the\n * localized URL of the detected locale (cookie / header, then\n * `Accept-Language`) unless that locale needs no prefix, and `routing.rewrite`\n * rules are applied both ways (`/fr/about` → `/fr/a-propos`). The router\n * therefore matches every locale against the same unprefixed routes, and\n * `routing.enableProxy: false` turns the routing off while keeping the\n * locale resolution.\n *\n * The resolved locale is exposed as `context.get(Intlayer)` /\n * `context.intlayer`, and the rest of the request runs inside an\n * `AsyncLocalStorage` scope bound to the request context, so the hooks of this\n * package (`useLocale`, `useIntlayer`, `useDictionary`) read that state from\n * anywhere downstream — route handlers, views, Remix UI components — with the\n * same signature as `react-intlayer`.\n *\n * @param options - Locale-routing options.\n *\n * @example\n * ```ts\n * import { createRouter } from 'remix/router';\n * import { intlayer, useIntlayer } from 'remix-intlayer';\n *\n * const router = createRouter({ middleware: [intlayer()] });\n *\n * // Serves `/`, `/fr`, `/es`… — the locale comes from the request context.\n * router.get('/', () => {\n * const { title } = useIntlayer('home');\n * return new Response(title);\n * });\n * ```\n */\nexport const intlayer = (\n options: IntlayerMiddlewareOptions = {}\n): Middleware<{\n key: typeof Intlayer;\n value: IntlayerState;\n property: typeof INTLAYER_CONTEXT_PROPERTY;\n}> => {\n // Ensures the generated dictionaries exist when the server starts without a\n // prior `intlayer build`. Fire-and-forget, like the other server integrations.\n const configuration = getConfiguration();\n prepareIntlayerServer(configuration, { label: 'remix-intlayer' });\n\n const resolveLocaleRouting = createLocaleRouting(\n {\n internationalization:\n configuration.internationalization ?? internationalization,\n routing: configuration.routing ?? routing,\n },\n options\n );\n\n return async (context, next) => {\n const action = resolveLocaleRouting(context);\n\n if (action.kind === 'redirect') return createRedirectResponse(action);\n\n let routedLocale: Locale | undefined;\n\n if (action.kind === 'rewrite') {\n // The router matches against `context.url`, so reassigning it is the\n // internal rewrite. The original request stays untouched.\n context.url = new URL(action.path, context.url);\n routedLocale = action.locale;\n }\n\n const locale =\n routedLocale ?? ((await getLocaleFromRequest(context)) as Locale);\n\n if (routedLocale) {\n // Propagates the locale downstream through the configured storage\n // header, like the Next.js and Vite proxies do.\n writeLocaleHeaders(context.headers, routedLocale);\n }\n\n context.set(\n Intlayer,\n {\n locale: locale as DeclaredLocales,\n defaultLocale: (configuration.internationalization?.defaultLocale ??\n internationalization.defaultLocale) as DeclaredLocales,\n availableLocales: (configuration.internationalization?.locales ??\n internationalization.locales) as DeclaredLocales[],\n },\n { property: INTLAYER_CONTEXT_PROPERTY }\n );\n\n const response = await requestStorage.run(context, next);\n\n return routedLocale ? withLocaleHeaders(response, routedLocale) : response;\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AA4BA,MAAM,0BACJ,WACa;CACb,MAAM,UAAU,IAAI,QAAQ,EAAE,UAAU,OAAO,SAAS,CAAC;CAEzD,IAAI,OAAO,eACT,yCAAmB,SAAS,OAAO,eAAe,EAAE,eAAe,KAAK,CAAC;CAG3E,OAAO,IAAI,SAAS,MAAM;EAAE,QAAQ,OAAO;EAAQ;CAAQ,CAAC;AAC9D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,MAAa,YACX,UAAqC,CAAC,MAKlC;CAGJ,MAAM,oBAAgBA,wCAAiB;CACvC,kDAAsB,eAAe,EAAE,OAAO,iBAAiB,CAAC;CAEhE,MAAM,uBAAuBC,0CAC3B;EACE,sBACE,cAAc,wBAAwBC;EACxC,SAAS,cAAc,WAAWC;CACpC,GACA,OACF;CAEA,OAAO,OAAO,SAAS,SAAS;EAC9B,MAAM,SAAS,qBAAqB,OAAO;EAE3C,IAAI,OAAO,SAAS,YAAY,OAAO,uBAAuB,MAAM;EAEpE,IAAI;EAEJ,IAAI,OAAO,SAAS,WAAW;GAG7B,QAAQ,MAAM,IAAI,IAAI,OAAO,MAAM,QAAQ,GAAG;GAC9C,eAAe,OAAO;EACxB;EAEA,MAAM,SACJ,gBAAkB,UAAMC,kDAAqB,OAAO;EAEtD,IAAI,cAGF,yCAAmB,QAAQ,SAAS,YAAY;EAGlD,QAAQ,IACNC,0BACA;GACU;GACR,eAAgB,cAAc,sBAAsB,iBAClDH,4CAAqB;GACvB,kBAAmB,cAAc,sBAAsB,WACrDA,4CAAqB;EACzB,GACA,EAAE,UAAUI,0CAA0B,CACxC;EAEA,MAAM,WAAW,MAAMC,sCAAe,IAAI,SAAS,IAAI;EAEvD,OAAO,eAAeC,wCAAkB,UAAU,YAAY,IAAI;CACpE;AACF"}
@@ -1,6 +1,7 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
  const require_context = require('./context.cjs');
3
3
  let node_async_hooks = require("node:async_hooks");
4
+ let _intlayer_core_interpreter = require("@intlayer/core/interpreter");
4
5
 
5
6
  //#region src/requestStorage.ts
6
7
  /**
@@ -17,6 +18,7 @@ const getIntlayerState = () => requestStorage.getStore()?.get(require_context.In
17
18
  * Returns the locale of the request being handled, if any.
18
19
  */
19
20
  const getRequestLocale = () => getIntlayerState()?.locale;
21
+ (0, _intlayer_core_interpreter.registerAmbientLocaleResolver)(getRequestLocale);
20
22
 
21
23
  //#endregion
22
24
  exports.getIntlayerState = getIntlayerState;
@@ -1 +1 @@
1
- {"version":3,"file":"requestStorage.cjs","names":["AsyncLocalStorage","Intlayer"],"sources":["../../src/requestStorage.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { DeclaredLocales } from '@intlayer/types/module_augmentation';\nimport type { RequestContext } from 'remix/router';\nimport { Intlayer, type IntlayerState } from './context';\n\n/**\n * Request context of the request being handled, made available to every\n * function running inside the `intlayer()` middleware scope — route handlers,\n * views, Remix UI components rendered from them — without passing it around.\n */\nexport const requestStorage = new AsyncLocalStorage<RequestContext<any, any>>();\n\n/**\n * Returns the Intlayer state of the request being handled, if any.\n */\nexport const getIntlayerState = (): IntlayerState | undefined =>\n requestStorage.getStore()?.get(Intlayer) as IntlayerState | undefined;\n\n/**\n * Returns the locale of the request being handled, if any.\n */\nexport const getRequestLocale = (): DeclaredLocales | undefined =>\n getIntlayerState()?.locale;\n"],"mappings":";;;;;;;;;;AAUA,MAAa,iBAAiB,IAAIA,mCAA4C;;;;AAK9E,MAAa,yBACX,eAAe,SAAS,CAAC,EAAE,IAAIC,wBAAQ;;;;AAKzC,MAAa,yBACX,iBAAiB,CAAC,EAAE"}
1
+ {"version":3,"file":"requestStorage.cjs","names":["AsyncLocalStorage","Intlayer","registerAmbientLocaleResolver"],"sources":["../../src/requestStorage.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport { registerAmbientLocaleResolver } from '@intlayer/core/interpreter';\nimport type { DeclaredLocales } from '@intlayer/types/module_augmentation';\nimport type { RequestContext } from 'remix/router';\nimport { Intlayer, type IntlayerState } from './context';\n\n/**\n * Request context of the request being handled, made available to every\n * function running inside the `intlayer()` middleware scope — route handlers,\n * views, Remix UI components rendered from them — without passing it around.\n */\nexport const requestStorage = new AsyncLocalStorage<RequestContext<any, any>>();\n\n/**\n * Returns the Intlayer state of the request being handled, if any.\n */\nexport const getIntlayerState = (): IntlayerState | undefined =>\n requestStorage.getStore()?.get(Intlayer) as IntlayerState | undefined;\n\n/**\n * Returns the locale of the request being handled, if any.\n */\nexport const getRequestLocale = (): DeclaredLocales | undefined =>\n getIntlayerState()?.locale;\n\n// Lets a bare `getIntlayer` / `getDictionary` from any Intlayer package resolve\n// to the locale of the request being handled.\nregisterAmbientLocaleResolver(getRequestLocale);\n"],"mappings":";;;;;;;;;;;AAWA,MAAa,iBAAiB,IAAIA,mCAA4C;;;;AAK9E,MAAa,yBACX,eAAe,SAAS,CAAC,EAAE,IAAIC,wBAAQ;;;;AAKzC,MAAa,yBACX,iBAAiB,CAAC,EAAE;IAItBC,0DAA8B,gBAAgB"}
@@ -1,8 +1,8 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
  const require_requestStorage = require('./requestStorage.cjs');
3
3
  const require_plugins = require('./plugins.cjs');
4
- let _intlayer_core_dictionaryManipulator = require("@intlayer/core/dictionaryManipulator");
5
4
  let _intlayer_core_interpreter = require("@intlayer/core/interpreter");
5
+ let _intlayer_core_dictionaryManipulator = require("@intlayer/core/dictionaryManipulator");
6
6
 
7
7
  //#region src/useDictionary.ts
8
8
  /**
@@ -1,8 +1,8 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
  const require_requestStorage = require('./requestStorage.cjs');
3
3
  const require_plugins = require('./plugins.cjs');
4
- let _intlayer_core_dictionaryManipulator = require("@intlayer/core/dictionaryManipulator");
5
4
  let _intlayer_core_interpreter = require("@intlayer/core/interpreter");
5
+ let _intlayer_core_dictionaryManipulator = require("@intlayer/core/dictionaryManipulator");
6
6
 
7
7
  //#region src/useIntlayer.ts
8
8
  /**
@@ -51,7 +51,7 @@ const stripLocalePrefix = (pathname, locale) => pathname.slice(`/${locale}`.leng
51
51
  * ```
52
52
  */
53
53
  const createLocaleRouting = (configuration, options = {}) => {
54
- const { isDevServer = true, ignore } = options;
54
+ const { isDevServer = process.env.NODE_ENV === "development", ignore } = options;
55
55
  const { locales, defaultLocale } = configuration.internationalization;
56
56
  const { basePath = "", mode = ROUTING_MODE, rewrite, domains, enableProxy } = configuration.routing ?? {};
57
57
  const proxyMode = resolveProxyMode(enableProxy);
@@ -1 +1 @@
1
- {"version":3,"file":"localeRouting.mjs","names":[],"sources":["../../src/localeRouting.ts"],"sourcesContent":["import { ROUTING_MODE } from '@intlayer/config/defaultValues';\nimport {\n getCanonicalPath,\n getDomainHostname,\n getDomainOrigin,\n getLocaleFromDomain,\n getRewriteRules,\n isProxyStorageLocaleEnabled,\n localeDetector,\n resolveLocalizedPath,\n resolveProxyMode,\n} from '@intlayer/core/localization';\nimport { getCookie, getLocaleFromStorageServer } from '@intlayer/core/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\n\n/**\n * The part of an incoming request the locale routing is decided from.\n */\nexport type LocaleRoutingRequest = {\n url: URL;\n headers: Headers;\n};\n\n/**\n * What the locale routing decided for a request.\n *\n * - `pass` — leave the request untouched (proxy disabled, ignored path).\n * - `rewrite` — keep serving the request, but from `path` (locale prefix\n * stripped, rewrite rule resolved to its canonical path). `locale` is the\n * locale the request resolved to, absent for a static asset.\n * - `redirect` — answer with a redirect to `location`. `persistLocale` asks\n * for the locale to be stored on the response so the follow-up request\n * resolves the same locale.\n */\nexport type LocaleRoutingAction =\n | { kind: 'pass' }\n | { kind: 'rewrite'; path: string; locale?: Locale }\n | {\n kind: 'redirect';\n location: string;\n status: 301 | 302;\n persistLocale?: Locale;\n };\n\nexport type LocaleRoutingOptions = {\n /**\n * Whether a development server is serving the app. In `enableProxy: auto`\n * mode, a development server ignores the stored locale (cookie / header)\n * when deciding where a request goes, so a stale cookie cannot keep pulling\n * every navigation to another locale while developing.\n *\n * @default process.env.NODE_ENV === 'development'\n */\n isDevServer?: boolean;\n /**\n * Requests to leave untouched, in addition to static assets.\n */\n ignore?: (request: LocaleRoutingRequest) => boolean;\n};\n\nexport type LocaleRoutingConfiguration = Pick<\n IntlayerConfig,\n 'internationalization' | 'routing'\n>;\n\n/** Matches a pathname ending with a file extension (`/logo.svg`). */\nconst STATIC_ASSET_PATTERN = /\\.[a-zA-Z0-9]+$/;\n\nconst PASS: LocaleRoutingAction = { kind: 'pass' };\n\n/**\n * Decodes a pathname so it can be matched against the rewrite rules, which are\n * written with the characters the locale actually uses (`/doc/релизы`) while\n * the browser sends them percent-encoded. A malformed escape is kept as is.\n */\nconst decodePathname = (pathname: string): string => {\n try {\n return decodeURI(pathname);\n } catch {\n return pathname;\n }\n};\n\n/**\n * Removes a trailing slash, except on the root path. A redirect to `/fr/`\n * would otherwise ping-pong with any trailing-slash normalisation downstream.\n */\nconst trimTrailingSlash = (path: string): string =>\n path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path;\n\n/**\n * Removes `/{locale}` from the start of a pathname that carries that prefix.\n */\nconst stripLocalePrefix = (pathname: string, locale: Locale): string =>\n pathname.slice(`/${locale}`.length) || '/';\n\n/**\n * Builds the locale-routing resolver of a Remix application.\n *\n * Decides, for each request, whether to serve it as is, serve it from another\n * internal path, or redirect it — mirroring the Intlayer proxies of\n * `next-intlayer` and `vite-intlayer`. Unlike them, an internal rewrite hands\n * the router the path *without* its locale prefix: the Remix router has no\n * trailing-slash normalisation to work around, and this lets an application\n * declare each route once (`/about`) whatever the routing mode, the locale\n * being read from the request context instead of a route param.\n *\n * @param configuration - The `internationalization` and `routing` configuration.\n * @param options - Runtime options.\n * @returns A pure function deciding the routing of a request.\n *\n * @example\n * ```ts\n * const resolveLocaleRouting = createLocaleRouting(configuration);\n *\n * resolveLocaleRouting({ url: new URL('http://host/fr/about'), headers });\n * // { kind: 'rewrite', path: '/about', locale: 'fr' }\n * ```\n */\nexport const createLocaleRouting = (\n configuration: LocaleRoutingConfiguration,\n options: LocaleRoutingOptions = {}\n): ((request: LocaleRoutingRequest) => LocaleRoutingAction) => {\n const { isDevServer = process.env.NODE_ENV === 'development', ignore } =\n options;\n const { locales, defaultLocale } = configuration.internationalization;\n const {\n basePath = '',\n mode = ROUTING_MODE,\n rewrite,\n domains,\n enableProxy,\n } = configuration.routing ?? {};\n\n const proxyMode = resolveProxyMode(enableProxy);\n const canUseStorageLocale = isProxyStorageLocaleEnabled(\n proxyMode,\n isDevServer\n );\n\n const isSearchParamsMode = mode === 'search-params';\n const noPrefix = mode === 'no-prefix' || isSearchParamsMode;\n const prefixDefault = mode === 'prefix-all';\n const rewriteRules = getRewriteRules(rewrite, 'url');\n const normalizedBasePath = trimTrailingSlash(\n basePath && !basePath.startsWith('/') ? `/${basePath}` : basePath\n );\n\n const isSupportedLocale = (value: string | undefined): value is Locale =>\n value !== undefined && locales.includes(value as Locale);\n\n /**\n * Locale carried by the first path segment (`/fr/about` → `fr`).\n */\n const getPathLocale = (pathname: string): Locale | undefined => {\n const firstSegment = pathname.split('/')[1];\n\n return isSupportedLocale(firstSegment) ? firstSegment : undefined;\n };\n\n /**\n * Locale a localized (\"pretty\") path belongs to. `/a-propos` only exists\n * because a rewrite rule maps it to French, so it declares its locale as\n * explicitly as an `/fr` prefix would; rules whose localized path equals the\n * canonical one carry no signal and are skipped.\n */\n const getRewriteLocale = (pathname: string): Locale | undefined =>\n rewriteRules\n ? locales.find(\n (candidate) =>\n getCanonicalPath(pathname, candidate, rewriteRules) !== pathname\n )\n : undefined;\n\n /**\n * Locale persisted by the client (cookie / header), when it may be used as\n * a routing source.\n */\n const getStorageLocale = (headers: Headers): Locale | undefined =>\n canUseStorageLocale\n ? getLocaleFromStorageServer({\n getCookie: (name) =>\n getCookie(name, headers.get('cookie') ?? undefined),\n getHeader: (name) => headers.get(name),\n })\n : undefined;\n\n /**\n * Best locale for a request that names none: storage, then\n * `Accept-Language`, then the default locale.\n */\n const detectLocale = (headers: Headers): Locale => {\n const locale =\n getStorageLocale(headers) ??\n localeDetector(\n { 'accept-language': headers.get('accept-language') ?? undefined },\n locales,\n defaultLocale\n );\n\n return isSupportedLocale(locale) ? locale : defaultLocale;\n };\n\n /**\n * Query string of a URL, with the `locale` param set in `search-params` mode.\n */\n const withLocaleSearch = (search: string, locale: Locale): string => {\n if (!isSearchParamsMode) return search;\n\n const params = new URLSearchParams(search);\n params.set('locale', locale);\n\n return `?${params.toString()}`;\n };\n\n /**\n * Public path of an application path for a locale: base path, then the\n * locale prefix when the routing mode shows one for that locale.\n */\n const toPublicPath = (\n locale: Locale,\n path: string,\n search: string\n ): string => {\n const showPrefix = !noPrefix && (prefixDefault || locale !== defaultLocale);\n const prefixedPath = showPrefix\n ? `/${locale}${path === '/' ? '' : path}`\n : path;\n\n return `${normalizedBasePath}${trimTrailingSlash(prefixedPath)}${withLocaleSearch(search, locale)}`;\n };\n\n /**\n * Internal path handed to the router: base path plus the canonical path.\n */\n const toInternalPath = (path: string, search: string): string =>\n `${normalizedBasePath}${path}${search}`;\n\n const rewriteTo = (\n path: string,\n search: string,\n locale?: Locale\n ): LocaleRoutingAction => ({\n kind: 'rewrite',\n path: encodeURI(toInternalPath(path, search)),\n locale,\n });\n\n /**\n * Same-origin redirect. A target equal to the request itself is served in\n * place instead, so a configuration mismatch can never loop.\n */\n const redirectTo = (\n location: string,\n current: string,\n persistLocale?: Locale\n ): LocaleRoutingAction => {\n const encodedLocation = encodeURI(location);\n\n if (encodedLocation === current) return PASS;\n\n return persistLocale\n ? {\n kind: 'redirect',\n location: encodedLocation,\n status: 302,\n persistLocale,\n }\n : { kind: 'redirect', location: encodedLocation, status: 302 };\n };\n\n /**\n * `no-prefix` and `search-params` modes: the URL never shows a prefix.\n */\n const handleNoPrefix = (\n { url, headers }: LocaleRoutingRequest,\n pathname: string,\n current: string\n ): LocaleRoutingAction => {\n const pathLocale = getPathLocale(pathname);\n\n if (pathLocale) {\n const canonicalPath = getCanonicalPath(\n stripLocalePrefix(pathname, pathLocale),\n pathLocale,\n rewriteRules\n );\n\n // Stripping the prefix drops the only locale signal from the URL, so the\n // locale is persisted for the follow-up request.\n return redirectTo(\n toPublicPath(pathLocale, canonicalPath, url.search),\n current,\n pathLocale\n );\n }\n\n if (isSearchParamsMode) {\n const searchLocale = url.searchParams.get('locale') ?? undefined;\n const locale =\n getStorageLocale(headers) ??\n (isSupportedLocale(searchLocale) ? searchLocale : undefined) ??\n detectLocale(headers);\n const canonicalPath = getCanonicalPath(pathname, locale, rewriteRules);\n\n return searchLocale === locale\n ? rewriteTo(canonicalPath, url.search, locale)\n : redirectTo(\n `${normalizedBasePath}${pathname}${withLocaleSearch(url.search, locale)}`,\n current\n );\n }\n\n const locale = getRewriteLocale(pathname) ?? detectLocale(headers);\n\n return rewriteTo(\n getCanonicalPath(pathname, locale, rewriteRules),\n url.search,\n locale\n );\n };\n\n /**\n * Prefix modes, URL without a locale prefix: redirect to the localized URL\n * when the mode shows a prefix for the resolved locale, serve it otherwise.\n */\n const handleMissingPathLocale = (\n { url, headers }: LocaleRoutingRequest,\n pathname: string,\n current: string\n ): LocaleRoutingAction => {\n // A localized path names its own locale and outranks storage and\n // `Accept-Language`, otherwise `/a-propos` read as `en` matches no rule.\n const locale = getRewriteLocale(pathname) ?? detectLocale(headers);\n const canonicalPath = getCanonicalPath(pathname, locale, rewriteRules);\n\n if (prefixDefault || locale !== defaultLocale) {\n const { path: localizedPath } = resolveLocalizedPath(\n canonicalPath,\n locale,\n rewriteRules\n );\n\n return redirectTo(\n toPublicPath(locale, localizedPath, url.search),\n current\n );\n }\n\n return rewriteTo(canonicalPath, url.search, locale);\n };\n\n /**\n * Prefix modes, URL with a locale prefix: normalise it to its localized\n * form, strip the prefix of the default locale when the mode hides it, and\n * serve the canonical path.\n */\n const handleExistingPathLocale = (\n { url }: LocaleRoutingRequest,\n pathname: string,\n pathLocale: Locale,\n current: string\n ): LocaleRoutingAction => {\n const rawPath = stripLocalePrefix(pathname, pathLocale);\n const canonicalPath = getCanonicalPath(rawPath, pathLocale, rewriteRules);\n const { path: localizedPath, isRewritten } = resolveLocalizedPath(\n canonicalPath,\n pathLocale,\n rewriteRules\n );\n\n // `/fr/about` → `/fr/a-propos`\n if (isRewritten && localizedPath !== rawPath) {\n return redirectTo(\n toPublicPath(pathLocale, localizedPath, url.search),\n current\n );\n }\n\n // `/en/about` → `/about`. The locale is persisted: the target no longer\n // names it, and detection could otherwise resolve another one.\n if (!prefixDefault && pathLocale === defaultLocale) {\n return redirectTo(\n toPublicPath(pathLocale, localizedPath, url.search),\n current,\n pathLocale\n );\n }\n\n return rewriteTo(canonicalPath, url.search, pathLocale);\n };\n\n return (request): LocaleRoutingAction => {\n if (proxyMode === 'disabled' || ignore?.(request)) return PASS;\n\n const { url } = request;\n const fullPathname = decodePathname(url.pathname);\n\n if (\n normalizedBasePath &&\n fullPathname !== normalizedBasePath &&\n !fullPathname.startsWith(`${normalizedBasePath}/`)\n ) {\n return PASS;\n }\n\n const pathname = fullPathname.slice(normalizedBasePath.length) || '/';\n const current = `${url.pathname}${url.search}`;\n const pathLocale = getPathLocale(pathname);\n\n // Static assets are served from their unprefixed path, untouched otherwise.\n if (STATIC_ASSET_PATTERN.test(pathname)) {\n return pathLocale\n ? rewriteTo(stripLocalePrefix(pathname, pathLocale), url.search)\n : PASS;\n }\n\n if (noPrefix) return handleNoPrefix(request, pathname, current);\n\n // `host/zh/about` → `https://host.zh/about` when `zh` has its own domain.\n // Domain mapping is stable configuration, hence a cacheable 301.\n const localeDomain = pathLocale && domains?.[pathLocale];\n\n if (localeDomain && getDomainHostname(localeDomain) !== url.hostname) {\n return {\n kind: 'redirect',\n location: `${getDomainOrigin(localeDomain)}${encodeURI(stripLocalePrefix(pathname, pathLocale))}${url.search}`,\n status: 301,\n };\n }\n\n // `host.zh/about` → `/about` as `zh`: the hostname alone names the locale.\n if (!pathLocale) {\n const domainLocale = getLocaleFromDomain(url.hostname, domains);\n\n if (domainLocale) {\n return rewriteTo(\n getCanonicalPath(pathname, domainLocale, rewriteRules),\n url.search,\n domainLocale\n );\n }\n\n return handleMissingPathLocale(request, pathname, current);\n }\n\n return handleExistingPathLocale(request, pathname, pathLocale, current);\n };\n};\n"],"mappings":";;;;;;AAmEA,MAAM,uBAAuB;AAE7B,MAAM,OAA4B,EAAE,MAAM,OAAO;;;;;;AAOjD,MAAM,kBAAkB,aAA6B;CACnD,IAAI;EACF,OAAO,UAAU,QAAQ;CAC3B,QAAQ;EACN,OAAO;CACT;AACF;;;;;AAMA,MAAM,qBAAqB,SACzB,KAAK,SAAS,KAAK,KAAK,SAAS,GAAG,IAAI,KAAK,MAAM,GAAG,EAAE,IAAI;;;;AAK9D,MAAM,qBAAqB,UAAkB,WAC3C,SAAS,MAAM,IAAI,SAAS,MAAM,KAAK;;;;;;;;;;;;;;;;;;;;;;;;AAyBzC,MAAa,uBACX,eACA,UAAgC,CAAC,MAC4B;CAC7D,MAAM,EAAE,cAAc,MAAwC,WAC5D;CACF,MAAM,EAAE,SAAS,kBAAkB,cAAc;CACjD,MAAM,EACJ,WAAW,IACX,OAAO,cACP,SACA,SACA,gBACE,cAAc,WAAW,CAAC;CAE9B,MAAM,YAAY,iBAAiB,WAAW;CAC9C,MAAM,sBAAsB,4BAC1B,WACA,WACF;CAEA,MAAM,qBAAqB,SAAS;CACpC,MAAM,WAAW,SAAS,eAAe;CACzC,MAAM,gBAAgB,SAAS;CAC/B,MAAM,eAAe,gBAAgB,SAAS,KAAK;CACnD,MAAM,qBAAqB,kBACzB,YAA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I,cACF,OAAO,UACL,iBAAiB,UAAU,cAAc,YAAY,GACrD,IAAI,QACJ,YACF;GAGF,OAAO,wBAAwB,SAAS,UAAU,OAAO;EAC3D;EAEA,OAAO,yBAAyB,SAAS,UAAU,YAAY,OAAO;CACxE;AACF"}
1
+ {"version":3,"file":"localeRouting.mjs","names":[],"sources":["../../src/localeRouting.ts"],"sourcesContent":["import { ROUTING_MODE } from '@intlayer/config/defaultValues';\nimport {\n getCanonicalPath,\n getDomainHostname,\n getDomainOrigin,\n getLocaleFromDomain,\n getRewriteRules,\n isProxyStorageLocaleEnabled,\n localeDetector,\n resolveLocalizedPath,\n resolveProxyMode,\n} from '@intlayer/core/localization';\nimport { getCookie, getLocaleFromStorageServer } from '@intlayer/core/utils';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { IntlayerConfig } from '@intlayer/types/config';\n\n/**\n * The part of an incoming request the locale routing is decided from.\n */\nexport type LocaleRoutingRequest = {\n url: URL;\n headers: Headers;\n};\n\n/**\n * What the locale routing decided for a request.\n *\n * - `pass` — leave the request untouched (proxy disabled, ignored path).\n * - `rewrite` — keep serving the request, but from `path` (locale prefix\n * stripped, rewrite rule resolved to its canonical path). `locale` is the\n * locale the request resolved to, absent for a static asset.\n * - `redirect` — answer with a redirect to `location`. `persistLocale` asks\n * for the locale to be stored on the response so the follow-up request\n * resolves the same locale.\n */\nexport type LocaleRoutingAction =\n | { kind: 'pass' }\n | { kind: 'rewrite'; path: string; locale?: Locale }\n | {\n kind: 'redirect';\n location: string;\n status: 301 | 302;\n persistLocale?: Locale;\n };\n\nexport type LocaleRoutingOptions = {\n /**\n * Whether a development server is serving the app. In `enableProxy: auto`\n * mode, a development server ignores the stored locale (cookie / header)\n * when deciding where a request goes, so a stale cookie cannot keep pulling\n * every navigation to another locale while developing.\n *\n * @default process.env.NODE_ENV === 'development'\n */\n isDevServer?: boolean;\n /**\n * Requests to leave untouched, in addition to static assets.\n */\n ignore?: (request: LocaleRoutingRequest) => boolean;\n};\n\nexport type LocaleRoutingConfiguration = Pick<\n IntlayerConfig,\n 'internationalization' | 'routing'\n>;\n\n/** Matches a pathname ending with a file extension (`/logo.svg`). */\nconst STATIC_ASSET_PATTERN = /\\.[a-zA-Z0-9]+$/;\n\nconst PASS: LocaleRoutingAction = { kind: 'pass' };\n\n/**\n * Decodes a pathname so it can be matched against the rewrite rules, which are\n * written with the characters the locale actually uses (`/doc/релизы`) while\n * the browser sends them percent-encoded. A malformed escape is kept as is.\n */\nconst decodePathname = (pathname: string): string => {\n try {\n return decodeURI(pathname);\n } catch {\n return pathname;\n }\n};\n\n/**\n * Removes a trailing slash, except on the root path. A redirect to `/fr/`\n * would otherwise ping-pong with any trailing-slash normalisation downstream.\n */\nconst trimTrailingSlash = (path: string): string =>\n path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path;\n\n/**\n * Removes `/{locale}` from the start of a pathname that carries that prefix.\n */\nconst stripLocalePrefix = (pathname: string, locale: Locale): string =>\n pathname.slice(`/${locale}`.length) || '/';\n\n/**\n * Builds the locale-routing resolver of a Remix application.\n *\n * Decides, for each request, whether to serve it as is, serve it from another\n * internal path, or redirect it — mirroring the Intlayer proxies of\n * `next-intlayer` and `vite-intlayer`. Unlike them, an internal rewrite hands\n * the router the path *without* its locale prefix: the Remix router has no\n * trailing-slash normalisation to work around, and this lets an application\n * declare each route once (`/about`) whatever the routing mode, the locale\n * being read from the request context instead of a route param.\n *\n * @param configuration - The `internationalization` and `routing` configuration.\n * @param options - Runtime options.\n * @returns A pure function deciding the routing of a request.\n *\n * @example\n * ```ts\n * const resolveLocaleRouting = createLocaleRouting(configuration);\n *\n * resolveLocaleRouting({ url: new URL('http://host/fr/about'), headers });\n * // { kind: 'rewrite', path: '/about', locale: 'fr' }\n * ```\n */\nexport const createLocaleRouting = (\n configuration: LocaleRoutingConfiguration,\n options: LocaleRoutingOptions = {}\n): ((request: LocaleRoutingRequest) => LocaleRoutingAction) => {\n const { isDevServer = process.env.NODE_ENV === 'development', ignore } =\n options;\n const { locales, defaultLocale } = configuration.internationalization;\n const {\n basePath = '',\n mode = ROUTING_MODE,\n rewrite,\n domains,\n enableProxy,\n } = configuration.routing ?? {};\n\n const proxyMode = resolveProxyMode(enableProxy);\n const canUseStorageLocale = isProxyStorageLocaleEnabled(\n proxyMode,\n isDevServer\n );\n\n const isSearchParamsMode = mode === 'search-params';\n const noPrefix = mode === 'no-prefix' || isSearchParamsMode;\n const prefixDefault = mode === 'prefix-all';\n const rewriteRules = getRewriteRules(rewrite, 'url');\n const normalizedBasePath = trimTrailingSlash(\n basePath && !basePath.startsWith('/') ? `/${basePath}` : basePath\n );\n\n const isSupportedLocale = (value: string | undefined): value is Locale =>\n value !== undefined && locales.includes(value as Locale);\n\n /**\n * Locale carried by the first path segment (`/fr/about` → `fr`).\n */\n const getPathLocale = (pathname: string): Locale | undefined => {\n const firstSegment = pathname.split('/')[1];\n\n return isSupportedLocale(firstSegment) ? firstSegment : undefined;\n };\n\n /**\n * Locale a localized (\"pretty\") path belongs to. `/a-propos` only exists\n * because a rewrite rule maps it to French, so it declares its locale as\n * explicitly as an `/fr` prefix would; rules whose localized path equals the\n * canonical one carry no signal and are skipped.\n */\n const getRewriteLocale = (pathname: string): Locale | undefined =>\n rewriteRules\n ? locales.find(\n (candidate) =>\n getCanonicalPath(pathname, candidate, rewriteRules) !== pathname\n )\n : undefined;\n\n /**\n * Locale persisted by the client (cookie / header), when it may be used as\n * a routing source.\n */\n const getStorageLocale = (headers: Headers): Locale | undefined =>\n canUseStorageLocale\n ? getLocaleFromStorageServer({\n getCookie: (name) =>\n getCookie(name, headers.get('cookie') ?? undefined),\n getHeader: (name) => headers.get(name),\n })\n : undefined;\n\n /**\n * Best locale for a request that names none: storage, then\n * `Accept-Language`, then the default locale.\n */\n const detectLocale = (headers: Headers): Locale => {\n const locale =\n getStorageLocale(headers) ??\n localeDetector(\n { 'accept-language': headers.get('accept-language') ?? undefined },\n locales,\n defaultLocale\n );\n\n return isSupportedLocale(locale) ? locale : defaultLocale;\n };\n\n /**\n * Query string of a URL, with the `locale` param set in `search-params` mode.\n */\n const withLocaleSearch = (search: string, locale: Locale): string => {\n if (!isSearchParamsMode) return search;\n\n const params = new URLSearchParams(search);\n params.set('locale', locale);\n\n return `?${params.toString()}`;\n };\n\n /**\n * Public path of an application path for a locale: base path, then the\n * locale prefix when the routing mode shows one for that locale.\n */\n const toPublicPath = (\n locale: Locale,\n path: string,\n search: string\n ): string => {\n const showPrefix = !noPrefix && (prefixDefault || locale !== defaultLocale);\n const prefixedPath = showPrefix\n ? `/${locale}${path === '/' ? '' : path}`\n : path;\n\n return `${normalizedBasePath}${trimTrailingSlash(prefixedPath)}${withLocaleSearch(search, locale)}`;\n };\n\n /**\n * Internal path handed to the router: base path plus the canonical path.\n */\n const toInternalPath = (path: string, search: string): string =>\n `${normalizedBasePath}${path}${search}`;\n\n const rewriteTo = (\n path: string,\n search: string,\n locale?: Locale\n ): LocaleRoutingAction => ({\n kind: 'rewrite',\n path: encodeURI(toInternalPath(path, search)),\n locale,\n });\n\n /**\n * Same-origin redirect. A target equal to the request itself is served in\n * place instead, so a configuration mismatch can never loop.\n */\n const redirectTo = (\n location: string,\n current: string,\n persistLocale?: Locale\n ): LocaleRoutingAction => {\n const encodedLocation = encodeURI(location);\n\n if (encodedLocation === current) return PASS;\n\n return persistLocale\n ? {\n kind: 'redirect',\n location: encodedLocation,\n status: 302,\n persistLocale,\n }\n : { kind: 'redirect', location: encodedLocation, status: 302 };\n };\n\n /**\n * `no-prefix` and `search-params` modes: the URL never shows a prefix.\n */\n const handleNoPrefix = (\n { url, headers }: LocaleRoutingRequest,\n pathname: string,\n current: string\n ): LocaleRoutingAction => {\n const pathLocale = getPathLocale(pathname);\n\n if (pathLocale) {\n const canonicalPath = getCanonicalPath(\n stripLocalePrefix(pathname, pathLocale),\n pathLocale,\n rewriteRules\n );\n\n // Stripping the prefix drops the only locale signal from the URL, so the\n // locale is persisted for the follow-up request.\n return redirectTo(\n toPublicPath(pathLocale, canonicalPath, url.search),\n current,\n pathLocale\n );\n }\n\n if (isSearchParamsMode) {\n const searchLocale = url.searchParams.get('locale') ?? undefined;\n const locale =\n getStorageLocale(headers) ??\n (isSupportedLocale(searchLocale) ? searchLocale : undefined) ??\n detectLocale(headers);\n const canonicalPath = getCanonicalPath(pathname, locale, rewriteRules);\n\n return searchLocale === locale\n ? rewriteTo(canonicalPath, url.search, locale)\n : redirectTo(\n `${normalizedBasePath}${pathname}${withLocaleSearch(url.search, locale)}`,\n current\n );\n }\n\n const locale = getRewriteLocale(pathname) ?? detectLocale(headers);\n\n return rewriteTo(\n getCanonicalPath(pathname, locale, rewriteRules),\n url.search,\n locale\n );\n };\n\n /**\n * Prefix modes, URL without a locale prefix: redirect to the localized URL\n * when the mode shows a prefix for the resolved locale, serve it otherwise.\n */\n const handleMissingPathLocale = (\n { url, headers }: LocaleRoutingRequest,\n pathname: string,\n current: string\n ): LocaleRoutingAction => {\n // A localized path names its own locale and outranks storage and\n // `Accept-Language`, otherwise `/a-propos` read as `en` matches no rule.\n const locale = getRewriteLocale(pathname) ?? detectLocale(headers);\n const canonicalPath = getCanonicalPath(pathname, locale, rewriteRules);\n\n if (prefixDefault || locale !== defaultLocale) {\n const { path: localizedPath } = resolveLocalizedPath(\n canonicalPath,\n locale,\n rewriteRules\n );\n\n return redirectTo(\n toPublicPath(locale, localizedPath, url.search),\n current\n );\n }\n\n return rewriteTo(canonicalPath, url.search, locale);\n };\n\n /**\n * Prefix modes, URL with a locale prefix: normalise it to its localized\n * form, strip the prefix of the default locale when the mode hides it, and\n * serve the canonical path.\n */\n const handleExistingPathLocale = (\n { url }: LocaleRoutingRequest,\n pathname: string,\n pathLocale: Locale,\n current: string\n ): LocaleRoutingAction => {\n const rawPath = stripLocalePrefix(pathname, pathLocale);\n const canonicalPath = getCanonicalPath(rawPath, pathLocale, rewriteRules);\n const { path: localizedPath, isRewritten } = resolveLocalizedPath(\n canonicalPath,\n pathLocale,\n rewriteRules\n );\n\n // `/fr/about` → `/fr/a-propos`\n if (isRewritten && localizedPath !== rawPath) {\n return redirectTo(\n toPublicPath(pathLocale, localizedPath, url.search),\n current\n );\n }\n\n // `/en/about` → `/about`. The locale is persisted: the target no longer\n // names it, and detection could otherwise resolve another one.\n if (!prefixDefault && pathLocale === defaultLocale) {\n return redirectTo(\n toPublicPath(pathLocale, localizedPath, url.search),\n current,\n pathLocale\n );\n }\n\n return rewriteTo(canonicalPath, url.search, pathLocale);\n };\n\n return (request): LocaleRoutingAction => {\n if (proxyMode === 'disabled' || ignore?.(request)) return PASS;\n\n const { url } = request;\n const fullPathname = decodePathname(url.pathname);\n\n if (\n normalizedBasePath &&\n fullPathname !== normalizedBasePath &&\n !fullPathname.startsWith(`${normalizedBasePath}/`)\n ) {\n return PASS;\n }\n\n const pathname = fullPathname.slice(normalizedBasePath.length) || '/';\n const current = `${url.pathname}${url.search}`;\n const pathLocale = getPathLocale(pathname);\n\n // Static assets are served from their unprefixed path, untouched otherwise.\n if (STATIC_ASSET_PATTERN.test(pathname)) {\n return pathLocale\n ? rewriteTo(stripLocalePrefix(pathname, pathLocale), url.search)\n : PASS;\n }\n\n if (noPrefix) return handleNoPrefix(request, pathname, current);\n\n // `host/zh/about` → `https://host.zh/about` when `zh` has its own domain.\n // Domain mapping is stable configuration, hence a cacheable 301.\n const localeDomain = pathLocale && domains?.[pathLocale];\n\n if (localeDomain && getDomainHostname(localeDomain) !== url.hostname) {\n return {\n kind: 'redirect',\n location: `${getDomainOrigin(localeDomain)}${encodeURI(stripLocalePrefix(pathname, pathLocale))}${url.search}`,\n status: 301,\n };\n }\n\n // `host.zh/about` → `/about` as `zh`: the hostname alone names the locale.\n if (!pathLocale) {\n const domainLocale = getLocaleFromDomain(url.hostname, domains);\n\n if (domainLocale) {\n return rewriteTo(\n getCanonicalPath(pathname, domainLocale, rewriteRules),\n url.search,\n domainLocale\n );\n }\n\n return handleMissingPathLocale(request, pathname, current);\n }\n\n return handleExistingPathLocale(request, pathname, pathLocale,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;EAGF,OAAO,UAAU,eAAe,IAAI,QAAQ,UAAU;CACxD;CAEA,QAAQ,YAAiC;EACvC,IAAI,cAAc,cAAc,SAAS,OAAO,GAAG,OAAO;EAE1D,MAAM,EAAE,QAAQ;EAChB,MAAM,eAAe,eAAe,IAAI,QAAQ;EAEhD,IACE,sBACA,iBAAiB,sBACjB,CAAC,aAAa,WAAW,GAAG,mBAAmB,EAAE,GAEjD,OAAO;EAGT,MAAM,WAAW,aAAa,MAAM,mBAAmB,MAAM,KAAK;EAClE,MAAM,UAAU,GAAG,IAAI,WAAW,IAAI;EACtC,MAAM,aAAa,cAAc,QAAQ;EAGzC,IAAI,qBAAqB,KAAK,QAAQ,GACpC,OAAO,aACH,UAAU,kBAAkB,UAAU,UAAU,GAAG,IAAI,MAAM,IAC7D;EAGN,IAAI,UAAU,OAAO,eAAe,SAAS,UAAU,OAAO;EAI9D,MAAM,eAAe,cAAc,UAAU;EAE7C,IAAI,gBAAgB,kBAAkB,YAAY,MAAM,IAAI,UAC1D,OAAO;GACL,MAAM;GACN,UAAU,GAAG,gBAAgB,YAAY,IAAI,UAAU,kBAAkB,UAAU,UAAU,CAAC,IAAI,IAAI;GACtG,QAAQ;EACV;EAIF,IAAI,CAAC,YAAY;GACf,MAAM,eAAe,oBAAoB,IAAI,UAAU,OAAO;GAE9D,IAAI,cACF,OAAO,UACL,iBAAiB,UAAU,cAAc,YAAY,GACrD,IAAI,QACJ,YACF;GAGF,OAAO,wBAAwB,SAAS,UAAU,OAAO;EAC3D;EAEA,OAAO,yBAAyB,SAAS,UAAU,YAAY,OAAO;CACxE;AACF"}
@@ -5,7 +5,7 @@ import { requestStorage } from "./requestStorage.mjs";
5
5
  import { internationalization, routing } from "@intlayer/config/built";
6
6
  import { getConfiguration } from "@intlayer/config/node";
7
7
  import { getLocaleFromRequest } from "@intlayer/core/localization";
8
- import { prepareIntlayer } from "@intlayer/engine/build";
8
+ import { prepareIntlayerServer } from "@intlayer/engine/build";
9
9
 
10
10
  //#region src/middleware.ts
11
11
  /**
@@ -61,7 +61,7 @@ const createRedirectResponse = (action) => {
61
61
  */
62
62
  const intlayer = (options = {}) => {
63
63
  const configuration = getConfiguration();
64
- prepareIntlayer(configuration);
64
+ prepareIntlayerServer(configuration, { label: "remix-intlayer" });
65
65
  const resolveLocaleRouting = createLocaleRouting({
66
66
  internationalization: configuration.internationalization ?? internationalization,
67
67
  routing: configuration.routing ?? routing
@@ -1 +1 @@
1
- {"version":3,"file":"middleware.mjs","names":[],"sources":["../../src/middleware.ts"],"sourcesContent":["import { internationalization, routing } from '@intlayer/config/built';\nimport { getConfiguration } from '@intlayer/config/node';\nimport { getLocaleFromRequest } from '@intlayer/core/localization';\nimport { prepareIntlayer } from '@intlayer/engine/build';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { DeclaredLocales } from '@intlayer/types/module_augmentation';\nimport type { Middleware } from 'remix/router';\nimport {\n INTLAYER_CONTEXT_PROPERTY,\n Intlayer,\n type IntlayerState,\n} from './context';\nimport {\n createLocaleRouting,\n type LocaleRoutingAction,\n type LocaleRoutingOptions,\n} from './localeRouting';\nimport { withLocaleHeaders, writeLocaleHeaders } from './persistLocale';\nimport { requestStorage } from './requestStorage';\n\nexport type IntlayerMiddlewareOptions = LocaleRoutingOptions;\n\n/**\n * Builds the redirect response of a locale-routing decision.\n *\n * Built by hand rather than with `Response.redirect`, whose headers are\n * immutable and could not carry the locale cookie.\n */\nconst createRedirectResponse = (\n action: Extract<LocaleRoutingAction, { kind: 'redirect' }>\n): Response => {\n const headers = new Headers({ location: action.location });\n\n if (action.persistLocale) {\n writeLocaleHeaders(headers, action.persistLocale, { includeCookie: true });\n }\n\n return new Response(null, { status: action.status, headers });\n};\n\n/**\n * Remix 3 router middleware handling the internationalization layer:\n * locale routing (redirects and internal rewrites, as `next-intlayer` and\n * `vite-intlayer` do), locale resolution and locale persistence.\n *\n * Locale routing follows `routing.mode`. In the prefix modes, `/fr/about` is\n * served from the `/about` route as French, `/about` is redirected to the\n * localized URL of the detected locale (cookie / header, then\n * `Accept-Language`) unless that locale needs no prefix, and `routing.rewrite`\n * rules are applied both ways (`/fr/about` → `/fr/a-propos`). The router\n * therefore matches every locale against the same unprefixed routes, and\n * `routing.enableProxy: false` turns the routing off while keeping the\n * locale resolution.\n *\n * The resolved locale is exposed as `context.get(Intlayer)` /\n * `context.intlayer`, and the rest of the request runs inside an\n * `AsyncLocalStorage` scope bound to the request context, so the hooks of this\n * package (`useLocale`, `useIntlayer`, `useDictionary`) read that state from\n * anywhere downstream — route handlers, views, Remix UI components — with the\n * same signature as `react-intlayer`.\n *\n * @param options - Locale-routing options.\n *\n * @example\n * ```ts\n * import { createRouter } from 'remix/router';\n * import { intlayer, useIntlayer } from 'remix-intlayer';\n *\n * const router = createRouter({ middleware: [intlayer()] });\n *\n * // Serves `/`, `/fr`, `/es`… — the locale comes from the request context.\n * router.get('/', () => {\n * const { title } = useIntlayer('home');\n * return new Response(title);\n * });\n * ```\n */\nexport const intlayer = (\n options: IntlayerMiddlewareOptions = {}\n): Middleware<{\n key: typeof Intlayer;\n value: IntlayerState;\n property: typeof INTLAYER_CONTEXT_PROPERTY;\n}> => {\n // Ensures the generated dictionaries exist when the server starts without a\n // prior `intlayer build`. Fire-and-forget, like the other server integrations.\n const configuration = getConfiguration();\n prepareIntlayer(configuration);\n\n const resolveLocaleRouting = createLocaleRouting(\n {\n internationalization:\n configuration.internationalization ?? internationalization,\n routing: configuration.routing ?? routing,\n },\n options\n );\n\n return async (context, next) => {\n const action = resolveLocaleRouting(context);\n\n if (action.kind === 'redirect') return createRedirectResponse(action);\n\n let routedLocale: Locale | undefined;\n\n if (action.kind === 'rewrite') {\n // The router matches against `context.url`, so reassigning it is the\n // internal rewrite. The original request stays untouched.\n context.url = new URL(action.path, context.url);\n routedLocale = action.locale;\n }\n\n const locale =\n routedLocale ?? ((await getLocaleFromRequest(context)) as Locale);\n\n if (routedLocale) {\n // Propagates the locale downstream through the configured storage\n // header, like the Next.js and Vite proxies do.\n writeLocaleHeaders(context.headers, routedLocale);\n }\n\n context.set(\n Intlayer,\n {\n locale: locale as DeclaredLocales,\n defaultLocale: (configuration.internationalization?.defaultLocale ??\n internationalization.defaultLocale) as DeclaredLocales,\n availableLocales: (configuration.internationalization?.locales ??\n internationalization.locales) as DeclaredLocales[],\n },\n { property: INTLAYER_CONTEXT_PROPERTY }\n );\n\n const response = await requestStorage.run(context, next);\n\n return routedLocale ? withLocaleHeaders(response, routedLocale) : response;\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;AA4BA,MAAM,0BACJ,WACa;CACb,MAAM,UAAU,IAAI,QAAQ,EAAE,UAAU,OAAO,SAAS,CAAC;CAEzD,IAAI,OAAO,eACT,mBAAmB,SAAS,OAAO,eAAe,EAAE,eAAe,KAAK,CAAC;CAG3E,OAAO,IAAI,SAAS,MAAM;EAAE,QAAQ,OAAO;EAAQ;CAAQ,CAAC;AAC9D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,MAAa,YACX,UAAqC,CAAC,MAKlC;CAGJ,MAAM,gBAAgB,iBAAiB;CACvC,gBAAgB,aAAa;CAE7B,MAAM,uBAAuB,oBAC3B;EACE,sBACE,cAAc,wBAAwB;EACxC,SAAS,cAAc,WAAW;CACpC,GACA,OACF;CAEA,OAAO,OAAO,SAAS,SAAS;EAC9B,MAAM,SAAS,qBAAqB,OAAO;EAE3C,IAAI,OAAO,SAAS,YAAY,OAAO,uBAAuB,MAAM;EAEpE,IAAI;EAEJ,IAAI,OAAO,SAAS,WAAW;GAG7B,QAAQ,MAAM,IAAI,IAAI,OAAO,MAAM,QAAQ,GAAG;GAC9C,eAAe,OAAO;EACxB;EAEA,MAAM,SACJ,gBAAkB,MAAM,qBAAqB,OAAO;EAEtD,IAAI,cAGF,mBAAmB,QAAQ,SAAS,YAAY;EAGlD,QAAQ,IACN,UACA;GACU;GACR,eAAgB,cAAc,sBAAsB,iBAClD,qBAAqB;GACvB,kBAAmB,cAAc,sBAAsB,WACrD,qBAAqB;EACzB,GACA,EAAE,UAAU,0BAA0B,CACxC;EAEA,MAAM,WAAW,MAAM,eAAe,IAAI,SAAS,IAAI;EAEvD,OAAO,eAAe,kBAAkB,UAAU,YAAY,IAAI;CACpE;AACF"}
1
+ {"version":3,"file":"middleware.mjs","names":[],"sources":["../../src/middleware.ts"],"sourcesContent":["import { internationalization, routing } from '@intlayer/config/built';\nimport { getConfiguration } from '@intlayer/config/node';\nimport { getLocaleFromRequest } from '@intlayer/core/localization';\nimport { prepareIntlayerServer } from '@intlayer/engine/build';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { DeclaredLocales } from '@intlayer/types/module_augmentation';\nimport type { Middleware } from 'remix/router';\nimport {\n INTLAYER_CONTEXT_PROPERTY,\n Intlayer,\n type IntlayerState,\n} from './context';\nimport {\n createLocaleRouting,\n type LocaleRoutingAction,\n type LocaleRoutingOptions,\n} from './localeRouting';\nimport { withLocaleHeaders, writeLocaleHeaders } from './persistLocale';\nimport { requestStorage } from './requestStorage';\n\nexport type IntlayerMiddlewareOptions = LocaleRoutingOptions;\n\n/**\n * Builds the redirect response of a locale-routing decision.\n *\n * Built by hand rather than with `Response.redirect`, whose headers are\n * immutable and could not carry the locale cookie.\n */\nconst createRedirectResponse = (\n action: Extract<LocaleRoutingAction, { kind: 'redirect' }>\n): Response => {\n const headers = new Headers({ location: action.location });\n\n if (action.persistLocale) {\n writeLocaleHeaders(headers, action.persistLocale, { includeCookie: true });\n }\n\n return new Response(null, { status: action.status, headers });\n};\n\n/**\n * Remix 3 router middleware handling the internationalization layer:\n * locale routing (redirects and internal rewrites, as `next-intlayer` and\n * `vite-intlayer` do), locale resolution and locale persistence.\n *\n * Locale routing follows `routing.mode`. In the prefix modes, `/fr/about` is\n * served from the `/about` route as French, `/about` is redirected to the\n * localized URL of the detected locale (cookie / header, then\n * `Accept-Language`) unless that locale needs no prefix, and `routing.rewrite`\n * rules are applied both ways (`/fr/about` → `/fr/a-propos`). The router\n * therefore matches every locale against the same unprefixed routes, and\n * `routing.enableProxy: false` turns the routing off while keeping the\n * locale resolution.\n *\n * The resolved locale is exposed as `context.get(Intlayer)` /\n * `context.intlayer`, and the rest of the request runs inside an\n * `AsyncLocalStorage` scope bound to the request context, so the hooks of this\n * package (`useLocale`, `useIntlayer`, `useDictionary`) read that state from\n * anywhere downstream — route handlers, views, Remix UI components — with the\n * same signature as `react-intlayer`.\n *\n * @param options - Locale-routing options.\n *\n * @example\n * ```ts\n * import { createRouter } from 'remix/router';\n * import { intlayer, useIntlayer } from 'remix-intlayer';\n *\n * const router = createRouter({ middleware: [intlayer()] });\n *\n * // Serves `/`, `/fr`, `/es`… — the locale comes from the request context.\n * router.get('/', () => {\n * const { title } = useIntlayer('home');\n * return new Response(title);\n * });\n * ```\n */\nexport const intlayer = (\n options: IntlayerMiddlewareOptions = {}\n): Middleware<{\n key: typeof Intlayer;\n value: IntlayerState;\n property: typeof INTLAYER_CONTEXT_PROPERTY;\n}> => {\n // Ensures the generated dictionaries exist when the server starts without a\n // prior `intlayer build`. Fire-and-forget, like the other server integrations.\n const configuration = getConfiguration();\n prepareIntlayerServer(configuration, { label: 'remix-intlayer' });\n\n const resolveLocaleRouting = createLocaleRouting(\n {\n internationalization:\n configuration.internationalization ?? internationalization,\n routing: configuration.routing ?? routing,\n },\n options\n );\n\n return async (context, next) => {\n const action = resolveLocaleRouting(context);\n\n if (action.kind === 'redirect') return createRedirectResponse(action);\n\n let routedLocale: Locale | undefined;\n\n if (action.kind === 'rewrite') {\n // The router matches against `context.url`, so reassigning it is the\n // internal rewrite. The original request stays untouched.\n context.url = new URL(action.path, context.url);\n routedLocale = action.locale;\n }\n\n const locale =\n routedLocale ?? ((await getLocaleFromRequest(context)) as Locale);\n\n if (routedLocale) {\n // Propagates the locale downstream through the configured storage\n // header, like the Next.js and Vite proxies do.\n writeLocaleHeaders(context.headers, routedLocale);\n }\n\n context.set(\n Intlayer,\n {\n locale: locale as DeclaredLocales,\n defaultLocale: (configuration.internationalization?.defaultLocale ??\n internationalization.defaultLocale) as DeclaredLocales,\n availableLocales: (configuration.internationalization?.locales ??\n internationalization.locales) as DeclaredLocales[],\n },\n { property: INTLAYER_CONTEXT_PROPERTY }\n );\n\n const response = await requestStorage.run(context, next);\n\n return routedLocale ? withLocaleHeaders(response, routedLocale) : response;\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;AA4BA,MAAM,0BACJ,WACa;CACb,MAAM,UAAU,IAAI,QAAQ,EAAE,UAAU,OAAO,SAAS,CAAC;CAEzD,IAAI,OAAO,eACT,mBAAmB,SAAS,OAAO,eAAe,EAAE,eAAe,KAAK,CAAC;CAG3E,OAAO,IAAI,SAAS,MAAM;EAAE,QAAQ,OAAO;EAAQ;CAAQ,CAAC;AAC9D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,MAAa,YACX,UAAqC,CAAC,MAKlC;CAGJ,MAAM,gBAAgB,iBAAiB;CACvC,sBAAsB,eAAe,EAAE,OAAO,iBAAiB,CAAC;CAEhE,MAAM,uBAAuB,oBAC3B;EACE,sBACE,cAAc,wBAAwB;EACxC,SAAS,cAAc,WAAW;CACpC,GACA,OACF;CAEA,OAAO,OAAO,SAAS,SAAS;EAC9B,MAAM,SAAS,qBAAqB,OAAO;EAE3C,IAAI,OAAO,SAAS,YAAY,OAAO,uBAAuB,MAAM;EAEpE,IAAI;EAEJ,IAAI,OAAO,SAAS,WAAW;GAG7B,QAAQ,MAAM,IAAI,IAAI,OAAO,MAAM,QAAQ,GAAG;GAC9C,eAAe,OAAO;EACxB;EAEA,MAAM,SACJ,gBAAkB,MAAM,qBAAqB,OAAO;EAEtD,IAAI,cAGF,mBAAmB,QAAQ,SAAS,YAAY;EAGlD,QAAQ,IACN,UACA;GACU;GACR,eAAgB,cAAc,sBAAsB,iBAClD,qBAAqB;GACvB,kBAAmB,cAAc,sBAAsB,WACrD,qBAAqB;EACzB,GACA,EAAE,UAAU,0BAA0B,CACxC;EAEA,MAAM,WAAW,MAAM,eAAe,IAAI,SAAS,IAAI;EAEvD,OAAO,eAAe,kBAAkB,UAAU,YAAY,IAAI;CACpE;AACF"}
@@ -1,5 +1,6 @@
1
1
  import { Intlayer } from "./context.mjs";
2
2
  import { AsyncLocalStorage } from "node:async_hooks";
3
+ import { registerAmbientLocaleResolver } from "@intlayer/core/interpreter";
3
4
 
4
5
  //#region src/requestStorage.ts
5
6
  /**
@@ -16,6 +17,7 @@ const getIntlayerState = () => requestStorage.getStore()?.get(Intlayer);
16
17
  * Returns the locale of the request being handled, if any.
17
18
  */
18
19
  const getRequestLocale = () => getIntlayerState()?.locale;
20
+ registerAmbientLocaleResolver(getRequestLocale);
19
21
 
20
22
  //#endregion
21
23
  export { getIntlayerState, getRequestLocale, requestStorage };
@@ -1 +1 @@
1
- {"version":3,"file":"requestStorage.mjs","names":[],"sources":["../../src/requestStorage.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { DeclaredLocales } from '@intlayer/types/module_augmentation';\nimport type { RequestContext } from 'remix/router';\nimport { Intlayer, type IntlayerState } from './context';\n\n/**\n * Request context of the request being handled, made available to every\n * function running inside the `intlayer()` middleware scope — route handlers,\n * views, Remix UI components rendered from them — without passing it around.\n */\nexport const requestStorage = new AsyncLocalStorage<RequestContext<any, any>>();\n\n/**\n * Returns the Intlayer state of the request being handled, if any.\n */\nexport const getIntlayerState = (): IntlayerState | undefined =>\n requestStorage.getStore()?.get(Intlayer) as IntlayerState | undefined;\n\n/**\n * Returns the locale of the request being handled, if any.\n */\nexport const getRequestLocale = (): DeclaredLocales | undefined =>\n getIntlayerState()?.locale;\n"],"mappings":";;;;;;;;;AAUA,MAAa,iBAAiB,IAAI,kBAA4C;;;;AAK9E,MAAa,yBACX,eAAe,SAAS,CAAC,EAAE,IAAI,QAAQ;;;;AAKzC,MAAa,yBACX,iBAAiB,CAAC,EAAE"}
1
+ {"version":3,"file":"requestStorage.mjs","names":[],"sources":["../../src/requestStorage.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport { registerAmbientLocaleResolver } from '@intlayer/core/interpreter';\nimport type { DeclaredLocales } from '@intlayer/types/module_augmentation';\nimport type { RequestContext } from 'remix/router';\nimport { Intlayer, type IntlayerState } from './context';\n\n/**\n * Request context of the request being handled, made available to every\n * function running inside the `intlayer()` middleware scope — route handlers,\n * views, Remix UI components rendered from them — without passing it around.\n */\nexport const requestStorage = new AsyncLocalStorage<RequestContext<any, any>>();\n\n/**\n * Returns the Intlayer state of the request being handled, if any.\n */\nexport const getIntlayerState = (): IntlayerState | undefined =>\n requestStorage.getStore()?.get(Intlayer) as IntlayerState | undefined;\n\n/**\n * Returns the locale of the request being handled, if any.\n */\nexport const getRequestLocale = (): DeclaredLocales | undefined =>\n getIntlayerState()?.locale;\n\n// Lets a bare `getIntlayer` / `getDictionary` from any Intlayer package resolve\n// to the locale of the request being handled.\nregisterAmbientLocaleResolver(getRequestLocale);\n"],"mappings":";;;;;;;;;;AAWA,MAAa,iBAAiB,IAAI,kBAA4C;;;;AAK9E,MAAa,yBACX,eAAe,SAAS,CAAC,EAAE,IAAI,QAAQ;;;;AAKzC,MAAa,yBACX,iBAAiB,CAAC,EAAE;AAItB,8BAA8B,gBAAgB"}
@@ -1,7 +1,7 @@
1
1
  import { getRequestLocale } from "./requestStorage.mjs";
2
2
  import { getPlugins } from "./plugins.mjs";
3
- import { parseDictionarySelector, resolveDictionaryArgument } from "@intlayer/core/dictionaryManipulator";
4
3
  import { getDictionary } from "@intlayer/core/interpreter";
4
+ import { parseDictionarySelector, resolveDictionaryArgument } from "@intlayer/core/dictionaryManipulator";
5
5
 
6
6
  //#region src/useDictionary.ts
7
7
  /**
@@ -1,7 +1,7 @@
1
1
  import { getRequestLocale } from "./requestStorage.mjs";
2
2
  import { getPlugins } from "./plugins.mjs";
3
- import { parseDictionarySelector, resolveDictionaryArgument } from "@intlayer/core/dictionaryManipulator";
4
3
  import { getIntlayer } from "@intlayer/core/interpreter";
4
+ import { parseDictionarySelector, resolveDictionaryArgument } from "@intlayer/core/dictionaryManipulator";
5
5
 
6
6
  //#region src/useIntlayer.ts
7
7
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"requestStorage.d.ts","names":[],"sources":["../../src/requestStorage.ts"],"mappings":";;;;;;;;;;qBAUa,gBAAc,kBAAA;;;;qBAKd,wBAAuB;;;;qBAMvB,wBAAuB"}
1
+ {"version":3,"file":"requestStorage.d.ts","names":[],"sources":["../../src/requestStorage.ts"],"mappings":";;;;;;;;;;qBAWa,gBAAc,kBAAA;;;;qBAKd,wBAAuB;;;;qBAMvB,wBAAuB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "remix-intlayer",
3
- "version": "9.5.11",
3
+ "version": "9.6.0",
4
4
  "private": false,
5
5
  "description": "Manage internationalization i18n in a simple way for Remix 3 applications.",
6
6
  "keywords": [
@@ -99,14 +99,14 @@
99
99
  "typecheck": "tsc --noEmit --project tsconfig.types.json"
100
100
  },
101
101
  "dependencies": {
102
- "@intlayer/config": "9.5.11",
103
- "@intlayer/core": "9.5.11",
104
- "@intlayer/engine": "9.5.11",
105
- "@intlayer/types": "9.5.11",
106
- "vanilla-intlayer": "9.5.11"
102
+ "@intlayer/config": "9.6.0",
103
+ "@intlayer/core": "9.6.0",
104
+ "@intlayer/engine": "9.6.0",
105
+ "@intlayer/types": "9.6.0",
106
+ "vanilla-intlayer": "9.6.0"
107
107
  },
108
108
  "devDependencies": {
109
- "@intlayer/dictionaries-entry": "9.5.11",
109
+ "@intlayer/dictionaries-entry": "9.6.0",
110
110
  "@types/node": "^22",
111
111
  "@utils/ts-config": "1.0.4",
112
112
  "@utils/ts-config-types": "1.0.4",
@@ -115,10 +115,10 @@
115
115
  "rimraf": "6.1.3",
116
116
  "tsdown": "0.23.0",
117
117
  "typescript": "7.0.2",
118
- "vitest": "5.0.2"
118
+ "vitest": "5.0.3"
119
119
  },
120
120
  "peerDependencies": {
121
- "remix": ">=3.0.0-rc.0"
121
+ "remix": ">=3.0.0"
122
122
  },
123
123
  "engines": {
124
124
  "node": ">=14.18"