gt-next 11.4.11 → 11.4.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +26 -0
- package/dist/config-dir/props/withGTConfigProps.d.ts +2 -1
- package/dist/config-dir/props/withGTConfigProps.d.ts.map +1 -1
- package/dist/config-dir/props/withGTConfigProps.js.map +1 -1
- package/dist/config-dir/props/withGTConfigProps.mjs.map +1 -1
- package/dist/config.d.ts +7 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +11 -1
- package/dist/config.js.map +1 -1
- package/dist/config.mjs +11 -1
- package/dist/config.mjs.map +1 -1
- package/dist/errors/createErrors.d.ts.map +1 -1
- package/dist/errors/createErrors.js +1 -2
- package/dist/errors/createErrors.js.map +1 -1
- package/dist/errors/createErrors.mjs +1 -2
- package/dist/errors/createErrors.mjs.map +1 -1
- package/dist/errors/middleware.d.ts +2 -0
- package/dist/errors/middleware.d.ts.map +1 -1
- package/dist/errors/middleware.js +17 -0
- package/dist/errors/middleware.js.map +1 -1
- package/dist/errors/middleware.mjs +15 -1
- package/dist/errors/middleware.mjs.map +1 -1
- package/dist/gt_swc_plugin.wasm +0 -0
- package/dist/index.client.d.ts +1 -0
- package/dist/index.client.d.ts.map +1 -1
- package/dist/index.client.js +2 -0
- package/dist/index.client.js.map +1 -1
- package/dist/index.client.mjs +2 -1
- package/dist/index.client.mjs.map +1 -1
- package/dist/index.rsc.d.ts +1 -0
- package/dist/index.rsc.d.ts.map +1 -1
- package/dist/index.rsc.js +2 -0
- package/dist/index.rsc.js.map +1 -1
- package/dist/index.rsc.mjs +2 -1
- package/dist/index.rsc.mjs.map +1 -1
- package/dist/index.server.d.ts +1 -0
- package/dist/index.server.d.ts.map +1 -1
- package/dist/index.server.js +2 -0
- package/dist/index.server.js.map +1 -1
- package/dist/index.server.mjs +2 -1
- package/dist/index.server.mjs.map +1 -1
- package/dist/index.types.d.ts +11 -0
- package/dist/index.types.d.ts.map +1 -1
- package/dist/link/Link.d.ts +7 -4
- package/dist/link/Link.d.ts.map +1 -1
- package/dist/link/Link.js +19 -41
- package/dist/link/Link.js.map +1 -1
- package/dist/link/Link.mjs +19 -41
- package/dist/link/Link.mjs.map +1 -1
- package/dist/link/getLocalizeHref.d.ts +43 -0
- package/dist/link/getLocalizeHref.d.ts.map +1 -0
- package/dist/link/getLocalizeHref.js +59 -0
- package/dist/link/getLocalizeHref.js.map +1 -0
- package/dist/link/getLocalizeHref.mjs +56 -0
- package/dist/link/getLocalizeHref.mjs.map +1 -0
- package/dist/link/localize-utils.d.ts +15 -0
- package/dist/link/localize-utils.d.ts.map +1 -0
- package/dist/link/localize-utils.js +49 -0
- package/dist/link/localize-utils.js.map +1 -0
- package/dist/link/localize-utils.mjs +48 -0
- package/dist/link/localize-utils.mjs.map +1 -0
- package/dist/link/useLocalizeHref.d.ts +34 -0
- package/dist/link/useLocalizeHref.d.ts.map +1 -0
- package/dist/link/useLocalizeHref.js +46 -0
- package/dist/link/useLocalizeHref.js.map +1 -0
- package/dist/link/useLocalizeHref.mjs +44 -0
- package/dist/link/useLocalizeHref.mjs.map +1 -0
- package/dist/link.d.ts +2 -0
- package/dist/link.d.ts.map +1 -1
- package/dist/link.js +2 -0
- package/dist/link.mjs +2 -1
- package/dist/middleware-dir/createMiddlewareRouting.d.ts +7 -0
- package/dist/middleware-dir/createMiddlewareRouting.d.ts.map +1 -0
- package/dist/middleware-dir/createMiddlewareRouting.js +79 -0
- package/dist/middleware-dir/createMiddlewareRouting.js.map +1 -0
- package/dist/middleware-dir/createMiddlewareRouting.mjs +77 -0
- package/dist/middleware-dir/createMiddlewareRouting.mjs.map +1 -0
- package/dist/middleware-dir/createNextMiddleware.d.ts +5 -12
- package/dist/middleware-dir/createNextMiddleware.d.ts.map +1 -1
- package/dist/middleware-dir/createNextMiddleware.js +14 -55
- package/dist/middleware-dir/createNextMiddleware.js.map +1 -1
- package/dist/middleware-dir/createNextMiddleware.mjs +15 -56
- package/dist/middleware-dir/createNextMiddleware.mjs.map +1 -1
- package/dist/middleware-dir/defaultMiddlewareConfig.d.ts +11 -0
- package/dist/middleware-dir/defaultMiddlewareConfig.d.ts.map +1 -0
- package/dist/middleware-dir/defaultMiddlewareConfig.js +33 -0
- package/dist/middleware-dir/defaultMiddlewareConfig.js.map +1 -0
- package/dist/middleware-dir/defaultMiddlewareConfig.mjs +31 -0
- package/dist/middleware-dir/defaultMiddlewareConfig.mjs.map +1 -0
- package/dist/middleware-dir/resolveMiddlewareConfig.d.ts +9 -0
- package/dist/middleware-dir/resolveMiddlewareConfig.d.ts.map +1 -0
- package/dist/middleware-dir/resolveMiddlewareConfig.js +32 -0
- package/dist/middleware-dir/resolveMiddlewareConfig.js.map +1 -0
- package/dist/middleware-dir/resolveMiddlewareConfig.mjs +30 -0
- package/dist/middleware-dir/resolveMiddlewareConfig.mjs.map +1 -0
- package/dist/middleware-dir/types.d.ts +56 -0
- package/dist/middleware-dir/types.d.ts.map +1 -0
- package/dist/middleware-dir/types.js +1 -0
- package/dist/middleware-dir/types.mjs +1 -0
- package/dist/server.d.ts +1 -0
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +2 -0
- package/dist/server.js.map +1 -1
- package/dist/server.mjs +2 -1
- package/dist/server.mjs.map +1 -1
- package/dist/utils/client-boundary.js +1 -1
- package/dist/utils/client-boundary.mjs +1 -1
- package/dist/variables/RelativeTime.js +1 -1
- package/dist/variables/RelativeTime.js.map +1 -1
- package/dist/variables/RelativeTime.mjs +1 -1
- package/dist/variables/RelativeTime.mjs.map +1 -1
- package/package.json +7 -13
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { localizeHref } from "./localize-utils.mjs";
|
|
2
|
+
import { use } from "../utils/use.mjs";
|
|
3
|
+
import { getLocale } from "../request/getLocale.mjs";
|
|
4
|
+
import { getI18nConfig } from "gt-i18n/internal";
|
|
5
|
+
//#region src/link/getLocalizeHref.ts
|
|
6
|
+
/**
|
|
7
|
+
* Returns a function that localizes hrefs the same way `gt-next/link` does,
|
|
8
|
+
* for server code such as Server Components, route handlers, and Server
|
|
9
|
+
* Actions.
|
|
10
|
+
*
|
|
11
|
+
* Internal paths are prefixed with the target locale, except default-locale
|
|
12
|
+
* paths when `prefixDefaultLocale` is `false` (an explicit default `locale`
|
|
13
|
+
* keeps its prefix while `enableSmartRouting` is on). Localized path aliases
|
|
14
|
+
* and locale availability are still resolved by the middleware. External URLs
|
|
15
|
+
* are never prefixed.
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```tsx
|
|
19
|
+
* import { getLocalizeHref } from 'gt-next/server';
|
|
20
|
+
*
|
|
21
|
+
* export async function CheckoutButton() {
|
|
22
|
+
* const localizeHref = await getLocalizeHref();
|
|
23
|
+
* return <Button href={localizeHref('/checkout')}>Checkout</Button>;
|
|
24
|
+
* }
|
|
25
|
+
* ```
|
|
26
|
+
*
|
|
27
|
+
* @returns A promise of a function taking an href and an optional locale (a
|
|
28
|
+
* locale string, or `false` to leave the href unchanged) that returns the
|
|
29
|
+
* localized href.
|
|
30
|
+
*/
|
|
31
|
+
async function getLocalizeHref() {
|
|
32
|
+
const currentLocale = await getLocale();
|
|
33
|
+
const defaultLocale = getI18nConfig().getDefaultLocale();
|
|
34
|
+
return (href, locale) => localizeHref(href, locale, currentLocale, defaultLocale);
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Server Component version of `useLocalizeHref()`: localizes hrefs the same
|
|
38
|
+
* way `gt-next/link` does, using the request locale.
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* ```tsx
|
|
42
|
+
* import { useLocalizeHref } from 'gt-next';
|
|
43
|
+
*
|
|
44
|
+
* export function CheckoutButton() {
|
|
45
|
+
* const localizeHref = useLocalizeHref();
|
|
46
|
+
* return <Button href={localizeHref('/checkout')}>Checkout</Button>;
|
|
47
|
+
* }
|
|
48
|
+
* ```
|
|
49
|
+
*/
|
|
50
|
+
function useLocalizeHref() {
|
|
51
|
+
return use(getLocalizeHref());
|
|
52
|
+
}
|
|
53
|
+
//#endregion
|
|
54
|
+
export { getLocalizeHref, useLocalizeHref };
|
|
55
|
+
|
|
56
|
+
//# sourceMappingURL=getLocalizeHref.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"getLocalizeHref.mjs","names":[],"sources":["../../src/link/getLocalizeHref.ts"],"sourcesContent":["import { getI18nConfig } from 'gt-i18n/internal';\nimport { getLocale } from '../request/getLocale';\nimport { use } from '../utils/use';\nimport { localizeHref, type LinkLocale } from './localize-utils';\n\n/**\n * Returns a function that localizes hrefs the same way `gt-next/link` does,\n * for server code such as Server Components, route handlers, and Server\n * Actions.\n *\n * Internal paths are prefixed with the target locale, except default-locale\n * paths when `prefixDefaultLocale` is `false` (an explicit default `locale`\n * keeps its prefix while `enableSmartRouting` is on). Localized path aliases\n * and locale availability are still resolved by the middleware. External URLs\n * are never prefixed.\n *\n * @example\n * ```tsx\n * import { getLocalizeHref } from 'gt-next/server';\n *\n * export async function CheckoutButton() {\n * const localizeHref = await getLocalizeHref();\n * return <Button href={localizeHref('/checkout')}>Checkout</Button>;\n * }\n * ```\n *\n * @returns A promise of a function taking an href and an optional locale (a\n * locale string, or `false` to leave the href unchanged) that returns the\n * localized href.\n */\nexport async function getLocalizeHref(): Promise<\n (href: string, locale?: LinkLocale) => string\n> {\n const currentLocale = await getLocale();\n const defaultLocale = getI18nConfig().getDefaultLocale();\n return (href, locale) =>\n localizeHref(href, locale, currentLocale, defaultLocale);\n}\n\n/**\n * Server Component version of `useLocalizeHref()`: localizes hrefs the same\n * way `gt-next/link` does, using the request locale.\n *\n * @example\n * ```tsx\n * import { useLocalizeHref } from 'gt-next';\n *\n * export function CheckoutButton() {\n * const localizeHref = useLocalizeHref();\n * return <Button href={localizeHref('/checkout')}>Checkout</Button>;\n * }\n * ```\n */\nexport function useLocalizeHref() {\n return use(getLocalizeHref());\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,eAAsB,kBAEpB;CACA,MAAM,gBAAgB,MAAM,WAAW;CACvC,MAAM,gBAAgB,eAAe,CAAC,kBAAkB;AACxD,SAAQ,MAAM,WACZ,aAAa,MAAM,QAAQ,eAAe,cAAc;;;;;;;;;;;;;;;;AAiB5D,SAAgB,kBAAkB;AAChC,QAAO,IAAI,iBAAiB,CAAC"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type NextLink from 'next/link';
|
|
2
|
+
import type { ComponentProps } from 'react';
|
|
3
|
+
/** A locale to prefix, `undefined` for the current locale, or `false` for none. */
|
|
4
|
+
export type LinkLocale = ComponentProps<typeof NextLink>['locale'];
|
|
5
|
+
/**
|
|
6
|
+
* Localizes an href the way `gt-next/link` does.
|
|
7
|
+
*
|
|
8
|
+
* Internal paths are prefixed with the target locale, except default-locale
|
|
9
|
+
* paths when `prefixDefaultLocale` is `false` (an explicit default `locale`
|
|
10
|
+
* keeps its prefix while `enableSmartRouting` is on). Localized path aliases
|
|
11
|
+
* and locale availability are still resolved by the middleware. External URLs
|
|
12
|
+
* are never prefixed.
|
|
13
|
+
*/
|
|
14
|
+
export declare function localizeHref(href: string, locale: LinkLocale, currentLocale: string, defaultLocale: string): string;
|
|
15
|
+
//# sourceMappingURL=localize-utils.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"localize-utils.d.ts","sourceRoot":"","sources":["../../src/link/localize-utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,QAAQ,MAAM,WAAW,CAAC;AACtC,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,OAAO,CAAC;AAG5C,mFAAmF;AACnF,MAAM,MAAM,UAAU,GAAG,cAAc,CAAC,OAAO,QAAQ,CAAC,CAAC,QAAQ,CAAC,CAAC;AA6CnE;;;;;;;;GAQG;AACH,wBAAgB,YAAY,CAC1B,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,UAAU,EAClB,aAAa,EAAE,MAAM,EACrB,aAAa,EAAE,MAAM,GACpB,MAAM,CAGR"}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_middleware_dir_resolveMiddlewareConfig = require("../middleware-dir/resolveMiddlewareConfig.js");
|
|
3
|
+
//#region src/link/localize-utils.ts
|
|
4
|
+
let routingConfig;
|
|
5
|
+
/**
|
|
6
|
+
* Reads the routing options passed to withGTConfig() on first use, so
|
|
7
|
+
* importing gt-next/link does no work.
|
|
8
|
+
*/
|
|
9
|
+
function getRoutingConfig() {
|
|
10
|
+
routingConfig ??= require_middleware_dir_resolveMiddlewareConfig.resolveMiddlewareConfig();
|
|
11
|
+
return routingConfig;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Returns the locale to prefix, or `false` when the middleware would not
|
|
15
|
+
* redirect the unprefixed path. Unprefixed default-locale paths are rewritten
|
|
16
|
+
* internally unless `prefixDefaultLocale` is set. An explicit default-locale
|
|
17
|
+
* switch keeps its prefix while smart routing would otherwise route to the
|
|
18
|
+
* locale cookie.
|
|
19
|
+
*/
|
|
20
|
+
function getPrefixLocale(locale, currentLocale, defaultLocale) {
|
|
21
|
+
if (locale === false) return false;
|
|
22
|
+
const targetLocale = locale ?? currentLocale;
|
|
23
|
+
const { prefixDefaultLocale, enableSmartRouting } = getRoutingConfig();
|
|
24
|
+
if (prefixDefaultLocale || targetLocale !== defaultLocale) return targetLocale;
|
|
25
|
+
return locale !== void 0 && enableSmartRouting ? targetLocale : false;
|
|
26
|
+
}
|
|
27
|
+
function prefixPath(path, locale) {
|
|
28
|
+
if (!path.startsWith("/") || path.startsWith("//")) return path;
|
|
29
|
+
const url = new URL(path, "http://localhost");
|
|
30
|
+
url.pathname = url.pathname === "/" ? `/${encodeURIComponent(locale)}` : `/${encodeURIComponent(locale)}${url.pathname}`;
|
|
31
|
+
return `${url.pathname}${url.search}${url.hash}`;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Localizes an href the way `gt-next/link` does.
|
|
35
|
+
*
|
|
36
|
+
* Internal paths are prefixed with the target locale, except default-locale
|
|
37
|
+
* paths when `prefixDefaultLocale` is `false` (an explicit default `locale`
|
|
38
|
+
* keeps its prefix while `enableSmartRouting` is on). Localized path aliases
|
|
39
|
+
* and locale availability are still resolved by the middleware. External URLs
|
|
40
|
+
* are never prefixed.
|
|
41
|
+
*/
|
|
42
|
+
function localizeHref(href, locale, currentLocale, defaultLocale) {
|
|
43
|
+
const prefixLocale = getPrefixLocale(locale, currentLocale, defaultLocale);
|
|
44
|
+
return prefixLocale ? prefixPath(href, prefixLocale) : href;
|
|
45
|
+
}
|
|
46
|
+
//#endregion
|
|
47
|
+
exports.localizeHref = localizeHref;
|
|
48
|
+
|
|
49
|
+
//# sourceMappingURL=localize-utils.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"localize-utils.js","names":["resolveMiddlewareConfig"],"sources":["../../src/link/localize-utils.ts"],"sourcesContent":["import type NextLink from 'next/link';\nimport type { ComponentProps } from 'react';\nimport { resolveMiddlewareConfig } from '../middleware-dir/resolveMiddlewareConfig';\n\n/** A locale to prefix, `undefined` for the current locale, or `false` for none. */\nexport type LinkLocale = ComponentProps<typeof NextLink>['locale'];\n\nlet routingConfig: ReturnType<typeof resolveMiddlewareConfig> | undefined;\n\n/**\n * Reads the routing options passed to withGTConfig() on first use, so\n * importing gt-next/link does no work.\n */\nfunction getRoutingConfig() {\n routingConfig ??= resolveMiddlewareConfig();\n return routingConfig;\n}\n\n/**\n * Returns the locale to prefix, or `false` when the middleware would not\n * redirect the unprefixed path. Unprefixed default-locale paths are rewritten\n * internally unless `prefixDefaultLocale` is set. An explicit default-locale\n * switch keeps its prefix while smart routing would otherwise route to the\n * locale cookie.\n */\nfunction getPrefixLocale(\n locale: LinkLocale,\n currentLocale: string,\n defaultLocale: string\n): string | false {\n if (locale === false) return false;\n const targetLocale = locale ?? currentLocale;\n const { prefixDefaultLocale, enableSmartRouting } = getRoutingConfig();\n if (prefixDefaultLocale || targetLocale !== defaultLocale)\n return targetLocale;\n return locale !== undefined && enableSmartRouting ? targetLocale : false;\n}\n\nfunction prefixPath(path: string, locale: string): string {\n if (!path.startsWith('/') || path.startsWith('//')) return path;\n\n const url = new URL(path, 'http://localhost');\n url.pathname =\n url.pathname === '/'\n ? `/${encodeURIComponent(locale)}`\n : `/${encodeURIComponent(locale)}${url.pathname}`;\n\n return `${url.pathname}${url.search}${url.hash}`;\n}\n\n/**\n * Localizes an href the way `gt-next/link` does.\n *\n * Internal paths are prefixed with the target locale, except default-locale\n * paths when `prefixDefaultLocale` is `false` (an explicit default `locale`\n * keeps its prefix while `enableSmartRouting` is on). Localized path aliases\n * and locale availability are still resolved by the middleware. External URLs\n * are never prefixed.\n */\nexport function localizeHref(\n href: string,\n locale: LinkLocale,\n currentLocale: string,\n defaultLocale: string\n): string {\n const prefixLocale = getPrefixLocale(locale, currentLocale, defaultLocale);\n return prefixLocale ? prefixPath(href, prefixLocale) : href;\n}\n"],"mappings":";;;AAOA,IAAI;;;;;AAMJ,SAAS,mBAAmB;AAC1B,mBAAkBA,+CAAAA,yBAAyB;AAC3C,QAAO;;;;;;;;;AAUT,SAAS,gBACP,QACA,eACA,eACgB;AAChB,KAAI,WAAW,MAAO,QAAO;CAC7B,MAAM,eAAe,UAAU;CAC/B,MAAM,EAAE,qBAAqB,uBAAuB,kBAAkB;AACtE,KAAI,uBAAuB,iBAAiB,cAC1C,QAAO;AACT,QAAO,WAAW,KAAA,KAAa,qBAAqB,eAAe;;AAGrE,SAAS,WAAW,MAAc,QAAwB;AACxD,KAAI,CAAC,KAAK,WAAW,IAAI,IAAI,KAAK,WAAW,KAAK,CAAE,QAAO;CAE3D,MAAM,MAAM,IAAI,IAAI,MAAM,mBAAmB;AAC7C,KAAI,WACF,IAAI,aAAa,MACb,IAAI,mBAAmB,OAAO,KAC9B,IAAI,mBAAmB,OAAO,GAAG,IAAI;AAE3C,QAAO,GAAG,IAAI,WAAW,IAAI,SAAS,IAAI;;;;;;;;;;;AAY5C,SAAgB,aACd,MACA,QACA,eACA,eACQ;CACR,MAAM,eAAe,gBAAgB,QAAQ,eAAe,cAAc;AAC1E,QAAO,eAAe,WAAW,MAAM,aAAa,GAAG"}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { resolveMiddlewareConfig } from "../middleware-dir/resolveMiddlewareConfig.mjs";
|
|
2
|
+
//#region src/link/localize-utils.ts
|
|
3
|
+
let routingConfig;
|
|
4
|
+
/**
|
|
5
|
+
* Reads the routing options passed to withGTConfig() on first use, so
|
|
6
|
+
* importing gt-next/link does no work.
|
|
7
|
+
*/
|
|
8
|
+
function getRoutingConfig() {
|
|
9
|
+
routingConfig ??= resolveMiddlewareConfig();
|
|
10
|
+
return routingConfig;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Returns the locale to prefix, or `false` when the middleware would not
|
|
14
|
+
* redirect the unprefixed path. Unprefixed default-locale paths are rewritten
|
|
15
|
+
* internally unless `prefixDefaultLocale` is set. An explicit default-locale
|
|
16
|
+
* switch keeps its prefix while smart routing would otherwise route to the
|
|
17
|
+
* locale cookie.
|
|
18
|
+
*/
|
|
19
|
+
function getPrefixLocale(locale, currentLocale, defaultLocale) {
|
|
20
|
+
if (locale === false) return false;
|
|
21
|
+
const targetLocale = locale ?? currentLocale;
|
|
22
|
+
const { prefixDefaultLocale, enableSmartRouting } = getRoutingConfig();
|
|
23
|
+
if (prefixDefaultLocale || targetLocale !== defaultLocale) return targetLocale;
|
|
24
|
+
return locale !== void 0 && enableSmartRouting ? targetLocale : false;
|
|
25
|
+
}
|
|
26
|
+
function prefixPath(path, locale) {
|
|
27
|
+
if (!path.startsWith("/") || path.startsWith("//")) return path;
|
|
28
|
+
const url = new URL(path, "http://localhost");
|
|
29
|
+
url.pathname = url.pathname === "/" ? `/${encodeURIComponent(locale)}` : `/${encodeURIComponent(locale)}${url.pathname}`;
|
|
30
|
+
return `${url.pathname}${url.search}${url.hash}`;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Localizes an href the way `gt-next/link` does.
|
|
34
|
+
*
|
|
35
|
+
* Internal paths are prefixed with the target locale, except default-locale
|
|
36
|
+
* paths when `prefixDefaultLocale` is `false` (an explicit default `locale`
|
|
37
|
+
* keeps its prefix while `enableSmartRouting` is on). Localized path aliases
|
|
38
|
+
* and locale availability are still resolved by the middleware. External URLs
|
|
39
|
+
* are never prefixed.
|
|
40
|
+
*/
|
|
41
|
+
function localizeHref(href, locale, currentLocale, defaultLocale) {
|
|
42
|
+
const prefixLocale = getPrefixLocale(locale, currentLocale, defaultLocale);
|
|
43
|
+
return prefixLocale ? prefixPath(href, prefixLocale) : href;
|
|
44
|
+
}
|
|
45
|
+
//#endregion
|
|
46
|
+
export { localizeHref };
|
|
47
|
+
|
|
48
|
+
//# sourceMappingURL=localize-utils.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"localize-utils.mjs","names":[],"sources":["../../src/link/localize-utils.ts"],"sourcesContent":["import type NextLink from 'next/link';\nimport type { ComponentProps } from 'react';\nimport { resolveMiddlewareConfig } from '../middleware-dir/resolveMiddlewareConfig';\n\n/** A locale to prefix, `undefined` for the current locale, or `false` for none. */\nexport type LinkLocale = ComponentProps<typeof NextLink>['locale'];\n\nlet routingConfig: ReturnType<typeof resolveMiddlewareConfig> | undefined;\n\n/**\n * Reads the routing options passed to withGTConfig() on first use, so\n * importing gt-next/link does no work.\n */\nfunction getRoutingConfig() {\n routingConfig ??= resolveMiddlewareConfig();\n return routingConfig;\n}\n\n/**\n * Returns the locale to prefix, or `false` when the middleware would not\n * redirect the unprefixed path. Unprefixed default-locale paths are rewritten\n * internally unless `prefixDefaultLocale` is set. An explicit default-locale\n * switch keeps its prefix while smart routing would otherwise route to the\n * locale cookie.\n */\nfunction getPrefixLocale(\n locale: LinkLocale,\n currentLocale: string,\n defaultLocale: string\n): string | false {\n if (locale === false) return false;\n const targetLocale = locale ?? currentLocale;\n const { prefixDefaultLocale, enableSmartRouting } = getRoutingConfig();\n if (prefixDefaultLocale || targetLocale !== defaultLocale)\n return targetLocale;\n return locale !== undefined && enableSmartRouting ? targetLocale : false;\n}\n\nfunction prefixPath(path: string, locale: string): string {\n if (!path.startsWith('/') || path.startsWith('//')) return path;\n\n const url = new URL(path, 'http://localhost');\n url.pathname =\n url.pathname === '/'\n ? `/${encodeURIComponent(locale)}`\n : `/${encodeURIComponent(locale)}${url.pathname}`;\n\n return `${url.pathname}${url.search}${url.hash}`;\n}\n\n/**\n * Localizes an href the way `gt-next/link` does.\n *\n * Internal paths are prefixed with the target locale, except default-locale\n * paths when `prefixDefaultLocale` is `false` (an explicit default `locale`\n * keeps its prefix while `enableSmartRouting` is on). Localized path aliases\n * and locale availability are still resolved by the middleware. External URLs\n * are never prefixed.\n */\nexport function localizeHref(\n href: string,\n locale: LinkLocale,\n currentLocale: string,\n defaultLocale: string\n): string {\n const prefixLocale = getPrefixLocale(locale, currentLocale, defaultLocale);\n return prefixLocale ? prefixPath(href, prefixLocale) : href;\n}\n"],"mappings":";;AAOA,IAAI;;;;;AAMJ,SAAS,mBAAmB;AAC1B,mBAAkB,yBAAyB;AAC3C,QAAO;;;;;;;;;AAUT,SAAS,gBACP,QACA,eACA,eACgB;AAChB,KAAI,WAAW,MAAO,QAAO;CAC7B,MAAM,eAAe,UAAU;CAC/B,MAAM,EAAE,qBAAqB,uBAAuB,kBAAkB;AACtE,KAAI,uBAAuB,iBAAiB,cAC1C,QAAO;AACT,QAAO,WAAW,KAAA,KAAa,qBAAqB,eAAe;;AAGrE,SAAS,WAAW,MAAc,QAAwB;AACxD,KAAI,CAAC,KAAK,WAAW,IAAI,IAAI,KAAK,WAAW,KAAK,CAAE,QAAO;CAE3D,MAAM,MAAM,IAAI,IAAI,MAAM,mBAAmB;AAC7C,KAAI,WACF,IAAI,aAAa,MACb,IAAI,mBAAmB,OAAO,KAC9B,IAAI,mBAAmB,OAAO,GAAG,IAAI;AAE3C,QAAO,GAAG,IAAI,WAAW,IAAI,SAAS,IAAI;;;;;;;;;;;AAY5C,SAAgB,aACd,MACA,QACA,eACA,eACQ;CACR,MAAM,eAAe,gBAAgB,QAAQ,eAAe,cAAc;AAC1E,QAAO,eAAe,WAAW,MAAM,aAAa,GAAG"}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { type LinkLocale } from './localize-utils';
|
|
2
|
+
/**
|
|
3
|
+
* Returns a function that localizes hrefs the same way `gt-next/link` does,
|
|
4
|
+
* for navigation that does not render a `<Link>`, such as `router.push()`.
|
|
5
|
+
*
|
|
6
|
+
* Internal paths are prefixed with the target locale, except default-locale
|
|
7
|
+
* paths when `prefixDefaultLocale` is `false` (an explicit default `locale`
|
|
8
|
+
* keeps its prefix while `enableSmartRouting` is on). Localized path aliases
|
|
9
|
+
* and locale availability are still resolved by the middleware. External URLs
|
|
10
|
+
* are never prefixed.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```tsx
|
|
14
|
+
* 'use client';
|
|
15
|
+
*
|
|
16
|
+
* import { useRouter } from 'next/navigation';
|
|
17
|
+
* import { useLocalizeHref } from 'gt-next/link';
|
|
18
|
+
*
|
|
19
|
+
* export function Checkout() {
|
|
20
|
+
* const router = useRouter();
|
|
21
|
+
* const localizeHref = useLocalizeHref();
|
|
22
|
+
* return (
|
|
23
|
+
* <button onClick={() => router.push(localizeHref('/checkout'))}>
|
|
24
|
+
* Checkout
|
|
25
|
+
* </button>
|
|
26
|
+
* );
|
|
27
|
+
* }
|
|
28
|
+
* ```
|
|
29
|
+
*
|
|
30
|
+
* @returns A function taking an href and an optional locale (a locale string,
|
|
31
|
+
* or `false` to leave the href unchanged) that returns the localized href.
|
|
32
|
+
*/
|
|
33
|
+
export declare function useLocalizeHref(): (href: string, locale?: LinkLocale) => string;
|
|
34
|
+
//# sourceMappingURL=useLocalizeHref.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useLocalizeHref.d.ts","sourceRoot":"","sources":["../../src/link/useLocalizeHref.ts"],"names":[],"mappings":"AAEA,OAAO,EAAgB,KAAK,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAEjE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,wBAAgB,eAAe,IAAI,CACjC,IAAI,EAAE,MAAM,EACZ,MAAM,CAAC,EAAE,UAAU,KAChB,MAAM,CAOV"}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
require("../_virtual/_rolldown/runtime.js");
|
|
3
|
+
const require_link_localize_utils = require("./localize-utils.js");
|
|
4
|
+
let gt_react = require("gt-react");
|
|
5
|
+
let react = require("react");
|
|
6
|
+
//#region src/link/useLocalizeHref.ts
|
|
7
|
+
/**
|
|
8
|
+
* Returns a function that localizes hrefs the same way `gt-next/link` does,
|
|
9
|
+
* for navigation that does not render a `<Link>`, such as `router.push()`.
|
|
10
|
+
*
|
|
11
|
+
* Internal paths are prefixed with the target locale, except default-locale
|
|
12
|
+
* paths when `prefixDefaultLocale` is `false` (an explicit default `locale`
|
|
13
|
+
* keeps its prefix while `enableSmartRouting` is on). Localized path aliases
|
|
14
|
+
* and locale availability are still resolved by the middleware. External URLs
|
|
15
|
+
* are never prefixed.
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```tsx
|
|
19
|
+
* 'use client';
|
|
20
|
+
*
|
|
21
|
+
* import { useRouter } from 'next/navigation';
|
|
22
|
+
* import { useLocalizeHref } from 'gt-next/link';
|
|
23
|
+
*
|
|
24
|
+
* export function Checkout() {
|
|
25
|
+
* const router = useRouter();
|
|
26
|
+
* const localizeHref = useLocalizeHref();
|
|
27
|
+
* return (
|
|
28
|
+
* <button onClick={() => router.push(localizeHref('/checkout'))}>
|
|
29
|
+
* Checkout
|
|
30
|
+
* </button>
|
|
31
|
+
* );
|
|
32
|
+
* }
|
|
33
|
+
* ```
|
|
34
|
+
*
|
|
35
|
+
* @returns A function taking an href and an optional locale (a locale string,
|
|
36
|
+
* or `false` to leave the href unchanged) that returns the localized href.
|
|
37
|
+
*/
|
|
38
|
+
function useLocalizeHref() {
|
|
39
|
+
const currentLocale = (0, gt_react.useLocale)();
|
|
40
|
+
const defaultLocale = (0, gt_react.useDefaultLocale)();
|
|
41
|
+
return (0, react.useCallback)((href, locale) => require_link_localize_utils.localizeHref(href, locale, currentLocale, defaultLocale), [currentLocale, defaultLocale]);
|
|
42
|
+
}
|
|
43
|
+
//#endregion
|
|
44
|
+
exports.useLocalizeHref = useLocalizeHref;
|
|
45
|
+
|
|
46
|
+
//# sourceMappingURL=useLocalizeHref.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useLocalizeHref.js","names":["localizeHref"],"sources":["../../src/link/useLocalizeHref.ts"],"sourcesContent":["import { useCallback } from 'react';\nimport { useDefaultLocale, useLocale } from 'gt-react';\nimport { localizeHref, type LinkLocale } from './localize-utils';\n\n/**\n * Returns a function that localizes hrefs the same way `gt-next/link` does,\n * for navigation that does not render a `<Link>`, such as `router.push()`.\n *\n * Internal paths are prefixed with the target locale, except default-locale\n * paths when `prefixDefaultLocale` is `false` (an explicit default `locale`\n * keeps its prefix while `enableSmartRouting` is on). Localized path aliases\n * and locale availability are still resolved by the middleware. External URLs\n * are never prefixed.\n *\n * @example\n * ```tsx\n * 'use client';\n *\n * import { useRouter } from 'next/navigation';\n * import { useLocalizeHref } from 'gt-next/link';\n *\n * export function Checkout() {\n * const router = useRouter();\n * const localizeHref = useLocalizeHref();\n * return (\n * <button onClick={() => router.push(localizeHref('/checkout'))}>\n * Checkout\n * </button>\n * );\n * }\n * ```\n *\n * @returns A function taking an href and an optional locale (a locale string,\n * or `false` to leave the href unchanged) that returns the localized href.\n */\nexport function useLocalizeHref(): (\n href: string,\n locale?: LinkLocale\n) => string {\n const currentLocale = useLocale();\n const defaultLocale = useDefaultLocale();\n return useCallback(\n (href, locale) => localizeHref(href, locale, currentLocale, defaultLocale),\n [currentLocale, defaultLocale]\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,SAAgB,kBAGJ;CACV,MAAM,iBAAA,GAAA,SAAA,YAA2B;CACjC,MAAM,iBAAA,GAAA,SAAA,mBAAkC;AACxC,SAAA,GAAA,MAAA,cACG,MAAM,WAAWA,4BAAAA,aAAa,MAAM,QAAQ,eAAe,cAAc,EAC1E,CAAC,eAAe,cAAc,CAC/B"}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { localizeHref } from "./localize-utils.mjs";
|
|
2
|
+
import { useDefaultLocale, useLocale } from "gt-react";
|
|
3
|
+
import { useCallback } from "react";
|
|
4
|
+
//#region src/link/useLocalizeHref.ts
|
|
5
|
+
/**
|
|
6
|
+
* Returns a function that localizes hrefs the same way `gt-next/link` does,
|
|
7
|
+
* for navigation that does not render a `<Link>`, such as `router.push()`.
|
|
8
|
+
*
|
|
9
|
+
* Internal paths are prefixed with the target locale, except default-locale
|
|
10
|
+
* paths when `prefixDefaultLocale` is `false` (an explicit default `locale`
|
|
11
|
+
* keeps its prefix while `enableSmartRouting` is on). Localized path aliases
|
|
12
|
+
* and locale availability are still resolved by the middleware. External URLs
|
|
13
|
+
* are never prefixed.
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```tsx
|
|
17
|
+
* 'use client';
|
|
18
|
+
*
|
|
19
|
+
* import { useRouter } from 'next/navigation';
|
|
20
|
+
* import { useLocalizeHref } from 'gt-next/link';
|
|
21
|
+
*
|
|
22
|
+
* export function Checkout() {
|
|
23
|
+
* const router = useRouter();
|
|
24
|
+
* const localizeHref = useLocalizeHref();
|
|
25
|
+
* return (
|
|
26
|
+
* <button onClick={() => router.push(localizeHref('/checkout'))}>
|
|
27
|
+
* Checkout
|
|
28
|
+
* </button>
|
|
29
|
+
* );
|
|
30
|
+
* }
|
|
31
|
+
* ```
|
|
32
|
+
*
|
|
33
|
+
* @returns A function taking an href and an optional locale (a locale string,
|
|
34
|
+
* or `false` to leave the href unchanged) that returns the localized href.
|
|
35
|
+
*/
|
|
36
|
+
function useLocalizeHref() {
|
|
37
|
+
const currentLocale = useLocale();
|
|
38
|
+
const defaultLocale = useDefaultLocale();
|
|
39
|
+
return useCallback((href, locale) => localizeHref(href, locale, currentLocale, defaultLocale), [currentLocale, defaultLocale]);
|
|
40
|
+
}
|
|
41
|
+
//#endregion
|
|
42
|
+
export { useLocalizeHref };
|
|
43
|
+
|
|
44
|
+
//# sourceMappingURL=useLocalizeHref.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useLocalizeHref.mjs","names":[],"sources":["../../src/link/useLocalizeHref.ts"],"sourcesContent":["import { useCallback } from 'react';\nimport { useDefaultLocale, useLocale } from 'gt-react';\nimport { localizeHref, type LinkLocale } from './localize-utils';\n\n/**\n * Returns a function that localizes hrefs the same way `gt-next/link` does,\n * for navigation that does not render a `<Link>`, such as `router.push()`.\n *\n * Internal paths are prefixed with the target locale, except default-locale\n * paths when `prefixDefaultLocale` is `false` (an explicit default `locale`\n * keeps its prefix while `enableSmartRouting` is on). Localized path aliases\n * and locale availability are still resolved by the middleware. External URLs\n * are never prefixed.\n *\n * @example\n * ```tsx\n * 'use client';\n *\n * import { useRouter } from 'next/navigation';\n * import { useLocalizeHref } from 'gt-next/link';\n *\n * export function Checkout() {\n * const router = useRouter();\n * const localizeHref = useLocalizeHref();\n * return (\n * <button onClick={() => router.push(localizeHref('/checkout'))}>\n * Checkout\n * </button>\n * );\n * }\n * ```\n *\n * @returns A function taking an href and an optional locale (a locale string,\n * or `false` to leave the href unchanged) that returns the localized href.\n */\nexport function useLocalizeHref(): (\n href: string,\n locale?: LinkLocale\n) => string {\n const currentLocale = useLocale();\n const defaultLocale = useDefaultLocale();\n return useCallback(\n (href, locale) => localizeHref(href, locale, currentLocale, defaultLocale),\n [currentLocale, defaultLocale]\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,SAAgB,kBAGJ;CACV,MAAM,gBAAgB,WAAW;CACjC,MAAM,gBAAgB,kBAAkB;AACxC,QAAO,aACJ,MAAM,WAAW,aAAa,MAAM,QAAQ,eAAe,cAAc,EAC1E,CAAC,eAAe,cAAc,CAC/B"}
|
package/dist/link.d.ts
CHANGED
package/dist/link.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"link.d.ts","sourceRoot":"","sources":["../src/link.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,IAAI,IAAI,OAAO,EAAE,MAAM,aAAa,CAAC;AAC9C,YAAY,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC"}
|
|
1
|
+
{"version":3,"file":"link.d.ts","sourceRoot":"","sources":["../src/link.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,IAAI,IAAI,OAAO,EAAE,MAAM,aAAa,CAAC;AAC9C,YAAY,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACzD,YAAY,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC"}
|
package/dist/link.js
CHANGED
|
@@ -3,5 +3,7 @@ Object.defineProperties(exports, {
|
|
|
3
3
|
__esModule: { value: true },
|
|
4
4
|
[Symbol.toStringTag]: { value: "Module" }
|
|
5
5
|
});
|
|
6
|
+
const require_link_useLocalizeHref = require("./link/useLocalizeHref.js");
|
|
6
7
|
const require_link_Link = require("./link/Link.js");
|
|
7
8
|
exports.default = require_link_Link.Link;
|
|
9
|
+
exports.useLocalizeHref = require_link_useLocalizeHref.useLocalizeHref;
|
package/dist/link.mjs
CHANGED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { MiddlewareRouting, ResolvedMiddlewareConfig } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* Pre-processes the locale, cookie, and path configuration once per
|
|
4
|
+
* middleware instance so requests only do lookups.
|
|
5
|
+
*/
|
|
6
|
+
export declare function createMiddlewareRouting({ pathConfig: inputPathConfig, routeOverrides: inputRouteOverrides, localeRoutes, prefixDefaultLocale, }: ResolvedMiddlewareConfig): MiddlewareRouting;
|
|
7
|
+
//# sourceMappingURL=createMiddlewareRouting.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"createMiddlewareRouting.d.ts","sourceRoot":"","sources":["../../src/middleware-dir/createMiddlewareRouting.ts"],"names":[],"mappings":"AAoBA,OAAO,KAAK,EAEV,iBAAiB,EACjB,wBAAwB,EAEzB,MAAM,SAAS,CAAC;AAEjB;;;GAGG;AACH,wBAAgB,uBAAuB,CAAC,EACtC,UAAU,EAAE,eAAe,EAC3B,cAAc,EAAE,mBAAmB,EACnC,YAAY,EACZ,mBAAmB,GACpB,EAAE,wBAAwB,GAAG,iBAAiB,CA6J9C"}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
require("../_virtual/_rolldown/runtime.js");
|
|
3
|
+
require("../utils/headers.js");
|
|
4
|
+
require("../utils/cookies.js");
|
|
5
|
+
const require_utils_pathRegex = require("../utils/pathRegex.js");
|
|
6
|
+
const require_errors_middleware = require("../errors/middleware.js");
|
|
7
|
+
const require_middleware_dir_resolveMiddlewareConfig = require("./resolveMiddlewareConfig.js");
|
|
8
|
+
const require_middleware_dir_createPathMatcher = require("./createPathMatcher.js");
|
|
9
|
+
let generaltranslation_internal = require("generaltranslation/internal");
|
|
10
|
+
let _generaltranslation_react_core_pure = require("@generaltranslation/react-core/pure");
|
|
11
|
+
let generaltranslation_runtime = require("generaltranslation/runtime");
|
|
12
|
+
//#region src/middleware-dir/createMiddlewareRouting.ts
|
|
13
|
+
/**
|
|
14
|
+
* Pre-processes the locale, cookie, and path configuration once per
|
|
15
|
+
* middleware instance so requests only do lookups.
|
|
16
|
+
*/
|
|
17
|
+
function createMiddlewareRouting({ pathConfig: inputPathConfig, routeOverrides: inputRouteOverrides, localeRoutes, prefixDefaultLocale }) {
|
|
18
|
+
const pathRegex = require_utils_pathRegex.compilePathRegex(process.env._GENERALTRANSLATION_PATH_REGEX);
|
|
19
|
+
const i18nConfig = require_middleware_dir_resolveMiddlewareConfig.parseEnvConfig("_GENERALTRANSLATION_I18N_CONFIG_PARAMS", process.env._GENERALTRANSLATION_I18N_CONFIG_PARAMS);
|
|
20
|
+
const gt = new generaltranslation_runtime.GTRuntime({ customMapping: i18nConfig.customMapping });
|
|
21
|
+
const defaultLocale = i18nConfig.defaultLocale || generaltranslation_internal.libraryDefaultLocale;
|
|
22
|
+
const locales = Array.from(new Set([defaultLocale, ...i18nConfig.locales || []]));
|
|
23
|
+
const resolvedConfigLocales = /* @__PURE__ */ new Map();
|
|
24
|
+
const determineLocaleWithCache = (locale) => {
|
|
25
|
+
const cached = resolvedConfigLocales.get(locale);
|
|
26
|
+
if (cached !== void 0) return cached;
|
|
27
|
+
const resolved = gt.determineLocale(locale, locales) ?? locale;
|
|
28
|
+
resolvedConfigLocales.set(locale, resolved);
|
|
29
|
+
return resolved;
|
|
30
|
+
};
|
|
31
|
+
const resolvePathConfigLocale = process.env._GENERALTRANSLATION_GT_SERVICES_ENABLED === "true" ? determineLocaleWithCache : (locale) => locale;
|
|
32
|
+
const headersAndCookies = i18nConfig.headersAndCookies || {};
|
|
33
|
+
const localeRoutingEnabledCookieName = headersAndCookies?.localeRoutingEnabledCookieName || "generaltranslation.locale-routing-enabled";
|
|
34
|
+
const referrerLocaleCookieName = headersAndCookies?.referrerLocaleCookieName || "generaltranslation.referrer-locale";
|
|
35
|
+
const localeCookieName = headersAndCookies?.localeCookieName || _generaltranslation_react_core_pure.defaultLocaleCookieName;
|
|
36
|
+
const resetLocaleCookieName = headersAndCookies?.resetLocaleCookieName || _generaltranslation_react_core_pure.defaultResetLocaleCookieName;
|
|
37
|
+
const localeHeaderName = headersAndCookies?.localeHeaderName || "x-generaltranslation-locale";
|
|
38
|
+
if (!gt.isValidLocale(defaultLocale)) throw new Error(`gt-next middleware: defaultLocale "${defaultLocale}" is not a valid locale.`);
|
|
39
|
+
const warningLocales = locales.filter((locale) => !gt.isValidLocale(locale));
|
|
40
|
+
if (warningLocales.length) console.warn(require_errors_middleware.createUnsupportedLocalesWarning(warningLocales));
|
|
41
|
+
const pathConfig = Object.entries(inputPathConfig).reduce((acc, [sharedPath, localizedPath]) => {
|
|
42
|
+
if (typeof localizedPath === "string") acc[sharedPath] = localizedPath;
|
|
43
|
+
else acc[sharedPath] = Object.entries(localizedPath).reduce((acc, [locale, localizedPath]) => {
|
|
44
|
+
acc[resolvePathConfigLocale(locale)] = localizedPath;
|
|
45
|
+
return acc;
|
|
46
|
+
}, {});
|
|
47
|
+
return acc;
|
|
48
|
+
}, {});
|
|
49
|
+
const { pathToSharedPath, defaultLocalePaths } = require_middleware_dir_createPathMatcher.createPathToSharedPathMap(Object.fromEntries(Object.entries(pathConfig).map(([sharedPath, localizedPath]) => [sharedPath, typeof localizedPath === "string" ? Object.fromEntries(locales.map((locale) => [determineLocaleWithCache(locale), localizedPath === "" ? "/" : localizedPath])) : localizedPath])), prefixDefaultLocale, defaultLocale);
|
|
50
|
+
const routeOverrides = Object.entries(inputRouteOverrides).reduce((acc, [locale, paths]) => {
|
|
51
|
+
acc[resolvePathConfigLocale(locale)] = paths;
|
|
52
|
+
return acc;
|
|
53
|
+
}, {});
|
|
54
|
+
return {
|
|
55
|
+
pathRegex,
|
|
56
|
+
gt,
|
|
57
|
+
defaultLocale,
|
|
58
|
+
locales,
|
|
59
|
+
localeRoutingEnabledCookieName,
|
|
60
|
+
referrerLocaleCookieName,
|
|
61
|
+
localeCookieName,
|
|
62
|
+
resetLocaleCookieName,
|
|
63
|
+
localeHeaderName,
|
|
64
|
+
pathConfig,
|
|
65
|
+
pathToSharedPath,
|
|
66
|
+
defaultLocalePaths,
|
|
67
|
+
routeOverridePathMaps: Object.entries(routeOverrides).reduce((acc, [locale, paths]) => {
|
|
68
|
+
acc[locale] = require_middleware_dir_createPathMatcher.createPathToSharedPathMap(Object.fromEntries(paths.map((path) => [path, path])), true, defaultLocale).pathToSharedPath;
|
|
69
|
+
return acc;
|
|
70
|
+
}, {}),
|
|
71
|
+
localeRoutePathMaps: new Map(Object.entries(localeRoutes).map(([locale, paths]) => {
|
|
72
|
+
return [determineLocaleWithCache(locale), require_middleware_dir_createPathMatcher.createPathMatcher(paths.map((path) => [path, path]))];
|
|
73
|
+
}))
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
//#endregion
|
|
77
|
+
exports.createMiddlewareRouting = createMiddlewareRouting;
|
|
78
|
+
|
|
79
|
+
//# sourceMappingURL=createMiddlewareRouting.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"createMiddlewareRouting.js","names":["compilePathRegex","parseEnvConfig","GTRuntime","libraryDefaultLocale","defaultLocaleCookieName","defaultResetLocaleCookieName","createUnsupportedLocalesWarning","createPathToSharedPathMap","createPathMatcher"],"sources":["../../src/middleware-dir/createMiddlewareRouting.ts"],"sourcesContent":["import { GTRuntime } from 'generaltranslation/runtime';\nimport { libraryDefaultLocale } from 'generaltranslation/internal';\nimport {\n defaultLocaleCookieName,\n defaultResetLocaleCookieName,\n} from '@generaltranslation/react-core/pure';\nimport { createUnsupportedLocalesWarning } from '../errors/middleware';\nimport {\n defaultLocaleRoutingEnabledCookieName,\n defaultReferrerLocaleCookieName,\n} from '../utils/cookies';\nimport { defaultLocaleHeaderName } from '../utils/headers';\nimport { compilePathRegex } from '../utils/pathRegex';\nimport {\n createPathMatcher,\n createPathToSharedPathMap,\n type PathConfig,\n type PathMatcher,\n} from './createPathMatcher';\nimport { parseEnvConfig } from './resolveMiddlewareConfig';\nimport type {\n MiddlewareI18nConfig,\n MiddlewareRouting,\n ResolvedMiddlewareConfig,\n RouteOverrides,\n} from './types';\n\n/**\n * Pre-processes the locale, cookie, and path configuration once per\n * middleware instance so requests only do lookups.\n */\nexport function createMiddlewareRouting({\n pathConfig: inputPathConfig,\n routeOverrides: inputRouteOverrides,\n localeRoutes,\n prefixDefaultLocale,\n}: ResolvedMiddlewareConfig): MiddlewareRouting {\n const pathRegex = compilePathRegex(\n process.env._GENERALTRANSLATION_PATH_REGEX\n );\n\n // i18n config\n const i18nConfig = parseEnvConfig<MiddlewareI18nConfig>(\n '_GENERALTRANSLATION_I18N_CONFIG_PARAMS',\n process.env._GENERALTRANSLATION_I18N_CONFIG_PARAMS\n );\n\n // gt instance\n const gt = new GTRuntime({\n customMapping: i18nConfig.customMapping,\n });\n\n // Configured spellings are the identity used by routes, cookies and caches.\n const defaultLocale: string =\n i18nConfig.defaultLocale || libraryDefaultLocale;\n const locales = Array.from(\n new Set([defaultLocale, ...(i18nConfig.locales || [])])\n );\n // Route entries repeat locale keys. Resolve each key once per factory instead\n // of rebuilding the full locale-resolution index for every route/locale pair.\n const resolvedConfigLocales = new Map<string, string>();\n const determineLocaleWithCache = (locale: string) => {\n const cached = resolvedConfigLocales.get(locale);\n if (cached !== undefined) return cached;\n const resolved = gt.determineLocale(locale, locales) ?? locale;\n resolvedConfigLocales.set(locale, resolved);\n return resolved;\n };\n const resolvePathConfigLocale =\n process.env._GENERALTRANSLATION_GT_SERVICES_ENABLED === 'true'\n ? determineLocaleWithCache\n : (locale: string) => locale;\n\n // cookies and header names\n const headersAndCookies = i18nConfig.headersAndCookies || {};\n const localeRoutingEnabledCookieName =\n headersAndCookies?.localeRoutingEnabledCookieName ||\n defaultLocaleRoutingEnabledCookieName;\n const referrerLocaleCookieName =\n headersAndCookies?.referrerLocaleCookieName ||\n defaultReferrerLocaleCookieName;\n const localeCookieName =\n headersAndCookies?.localeCookieName || defaultLocaleCookieName;\n const resetLocaleCookieName =\n headersAndCookies?.resetLocaleCookieName || defaultResetLocaleCookieName;\n const localeHeaderName =\n headersAndCookies?.localeHeaderName || defaultLocaleHeaderName;\n\n if (!gt.isValidLocale(defaultLocale))\n throw new Error(\n `gt-next middleware: defaultLocale \"${defaultLocale}\" is not a valid locale.`\n );\n\n const warningLocales = locales.filter((locale) => !gt.isValidLocale(locale));\n if (warningLocales.length)\n console.warn(createUnsupportedLocalesWarning(warningLocales));\n\n // --- localized routes --- //\n // Resolve pathConfig keys to the configured locale spelling.\n const pathConfig = Object.entries(inputPathConfig).reduce<PathConfig>(\n (acc, [sharedPath, localizedPath]) => {\n if (typeof localizedPath === 'string') {\n acc[sharedPath] = localizedPath;\n } else {\n acc[sharedPath] = Object.entries(localizedPath).reduce<{\n [key: string]: string;\n }>((acc, [locale, localizedPath]) => {\n acc[resolvePathConfigLocale(locale)] = localizedPath;\n return acc;\n }, {});\n }\n return acc;\n },\n {}\n );\n\n // String aliases apply to every locale, including the default locale.\n // Expand a copy for lookup while retaining string target semantics in routing.\n const matcherPathConfig = Object.fromEntries(\n Object.entries(pathConfig).map(([sharedPath, localizedPath]) => [\n sharedPath,\n typeof localizedPath === 'string'\n ? Object.fromEntries(\n locales.map((locale) => [\n determineLocaleWithCache(locale),\n localizedPath === '' ? '/' : localizedPath,\n ])\n )\n : localizedPath,\n ])\n );\n\n // Create the path mapping\n const { pathToSharedPath, defaultLocalePaths } = createPathToSharedPathMap(\n matcherPathConfig,\n prefixDefaultLocale,\n defaultLocale\n );\n\n // --- route overrides --- //\n // Resolve routeOverrides keys to the configured locale spelling.\n const routeOverrides = Object.entries(\n inputRouteOverrides\n ).reduce<RouteOverrides>((acc, [locale, paths]) => {\n acc[resolvePathConfigLocale(locale)] = paths;\n return acc;\n }, {});\n\n // Create the route override path mapping\n const routeOverridePathMaps = Object.entries(routeOverrides).reduce<\n Record<string, PathMatcher>\n >((acc, [locale, paths]) => {\n const overridePathConfig = Object.fromEntries(\n paths.map((path) => [path, path])\n );\n acc[locale] = createPathToSharedPathMap(\n overridePathConfig,\n true,\n defaultLocale\n ).pathToSharedPath;\n return acc;\n }, {});\n\n // --- locale routes --- //\n // Compile availability separately from aliases and overrides so it cannot\n // change route precedence. An empty list deliberately matches nothing.\n const localeRoutePathMaps = new Map(\n Object.entries(localeRoutes).map(([locale, paths]) => {\n // Match request resolution so equivalent spellings use the same map key.\n const resolvedLocale = determineLocaleWithCache(locale);\n return [\n resolvedLocale,\n createPathMatcher(paths.map((path) => [path, path])),\n ];\n })\n );\n\n return {\n pathRegex,\n gt,\n defaultLocale,\n locales,\n localeRoutingEnabledCookieName,\n referrerLocaleCookieName,\n localeCookieName,\n resetLocaleCookieName,\n localeHeaderName,\n pathConfig,\n pathToSharedPath,\n defaultLocalePaths,\n routeOverridePathMaps,\n localeRoutePathMaps,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA+BA,SAAgB,wBAAwB,EACtC,YAAY,iBACZ,gBAAgB,qBAChB,cACA,uBAC8C;CAC9C,MAAM,YAAYA,wBAAAA,iBAChB,QAAQ,IAAI,+BACb;CAGD,MAAM,aAAaC,+CAAAA,eACjB,0CACA,QAAQ,IAAI,uCACb;CAGD,MAAM,KAAK,IAAIC,2BAAAA,UAAU,EACvB,eAAe,WAAW,eAC3B,CAAC;CAGF,MAAM,gBACJ,WAAW,iBAAiBC,4BAAAA;CAC9B,MAAM,UAAU,MAAM,KACpB,IAAI,IAAI,CAAC,eAAe,GAAI,WAAW,WAAW,EAAE,CAAE,CAAC,CACxD;CAGD,MAAM,wCAAwB,IAAI,KAAqB;CACvD,MAAM,4BAA4B,WAAmB;EACnD,MAAM,SAAS,sBAAsB,IAAI,OAAO;AAChD,MAAI,WAAW,KAAA,EAAW,QAAO;EACjC,MAAM,WAAW,GAAG,gBAAgB,QAAQ,QAAQ,IAAI;AACxD,wBAAsB,IAAI,QAAQ,SAAS;AAC3C,SAAO;;CAET,MAAM,0BACJ,QAAQ,IAAI,4CAA4C,SACpD,4BACC,WAAmB;CAG1B,MAAM,oBAAoB,WAAW,qBAAqB,EAAE;CAC5D,MAAM,iCACJ,mBAAmB,kCAAA;CAErB,MAAM,2BACJ,mBAAmB,4BAAA;CAErB,MAAM,mBACJ,mBAAmB,oBAAoBC,oCAAAA;CACzC,MAAM,wBACJ,mBAAmB,yBAAyBC,oCAAAA;CAC9C,MAAM,mBACJ,mBAAmB,oBAAA;AAErB,KAAI,CAAC,GAAG,cAAc,cAAc,CAClC,OAAM,IAAI,MACR,sCAAsC,cAAc,0BACrD;CAEH,MAAM,iBAAiB,QAAQ,QAAQ,WAAW,CAAC,GAAG,cAAc,OAAO,CAAC;AAC5E,KAAI,eAAe,OACjB,SAAQ,KAAKC,0BAAAA,gCAAgC,eAAe,CAAC;CAI/D,MAAM,aAAa,OAAO,QAAQ,gBAAgB,CAAC,QAChD,KAAK,CAAC,YAAY,mBAAmB;AACpC,MAAI,OAAO,kBAAkB,SAC3B,KAAI,cAAc;MAElB,KAAI,cAAc,OAAO,QAAQ,cAAc,CAAC,QAE5C,KAAK,CAAC,QAAQ,mBAAmB;AACnC,OAAI,wBAAwB,OAAO,IAAI;AACvC,UAAO;KACN,EAAE,CAAC;AAER,SAAO;IAET,EAAE,CACH;CAmBD,MAAM,EAAE,kBAAkB,uBAAuBC,yCAAAA,0BAfvB,OAAO,YAC/B,OAAO,QAAQ,WAAW,CAAC,KAAK,CAAC,YAAY,mBAAmB,CAC9D,YACA,OAAO,kBAAkB,WACrB,OAAO,YACL,QAAQ,KAAK,WAAW,CACtB,yBAAyB,OAAO,EAChC,kBAAkB,KAAK,MAAM,cAC9B,CAAC,CACH,GACD,cACL,CAAC,CAKe,EACjB,qBACA,cACD;CAID,MAAM,iBAAiB,OAAO,QAC5B,oBACD,CAAC,QAAwB,KAAK,CAAC,QAAQ,WAAW;AACjD,MAAI,wBAAwB,OAAO,IAAI;AACvC,SAAO;IACN,EAAE,CAAC;AA+BN,QAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,uBAzC4B,OAAO,QAAQ,eAAe,CAAC,QAE1D,KAAK,CAAC,QAAQ,WAAW;AAI1B,OAAI,UAAUA,yCAAAA,0BAHa,OAAO,YAChC,MAAM,KAAK,SAAS,CAAC,MAAM,KAAK,CAAC,CAGf,EAClB,MACA,cACD,CAAC;AACF,UAAO;KACN,EAAE,CA6BkB;EACrB,qBAAA,IAzB8B,IAC9B,OAAO,QAAQ,aAAa,CAAC,KAAK,CAAC,QAAQ,WAAW;AAGpD,UAAO,CADgB,yBAAyB,OAEhC,EACdC,yCAAAA,kBAAkB,MAAM,KAAK,SAAS,CAAC,MAAM,KAAK,CAAC,CAAC,CACrD;IACD,CAiBiB;EACpB"}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import "../utils/headers.mjs";
|
|
2
|
+
import "../utils/cookies.mjs";
|
|
3
|
+
import { compilePathRegex } from "../utils/pathRegex.mjs";
|
|
4
|
+
import { createUnsupportedLocalesWarning } from "../errors/middleware.mjs";
|
|
5
|
+
import { parseEnvConfig } from "./resolveMiddlewareConfig.mjs";
|
|
6
|
+
import { createPathMatcher, createPathToSharedPathMap } from "./createPathMatcher.mjs";
|
|
7
|
+
import { libraryDefaultLocale } from "generaltranslation/internal";
|
|
8
|
+
import { defaultLocaleCookieName, defaultResetLocaleCookieName } from "@generaltranslation/react-core/pure";
|
|
9
|
+
import { GTRuntime } from "generaltranslation/runtime";
|
|
10
|
+
//#region src/middleware-dir/createMiddlewareRouting.ts
|
|
11
|
+
/**
|
|
12
|
+
* Pre-processes the locale, cookie, and path configuration once per
|
|
13
|
+
* middleware instance so requests only do lookups.
|
|
14
|
+
*/
|
|
15
|
+
function createMiddlewareRouting({ pathConfig: inputPathConfig, routeOverrides: inputRouteOverrides, localeRoutes, prefixDefaultLocale }) {
|
|
16
|
+
const pathRegex = compilePathRegex(process.env._GENERALTRANSLATION_PATH_REGEX);
|
|
17
|
+
const i18nConfig = parseEnvConfig("_GENERALTRANSLATION_I18N_CONFIG_PARAMS", process.env._GENERALTRANSLATION_I18N_CONFIG_PARAMS);
|
|
18
|
+
const gt = new GTRuntime({ customMapping: i18nConfig.customMapping });
|
|
19
|
+
const defaultLocale = i18nConfig.defaultLocale || libraryDefaultLocale;
|
|
20
|
+
const locales = Array.from(new Set([defaultLocale, ...i18nConfig.locales || []]));
|
|
21
|
+
const resolvedConfigLocales = /* @__PURE__ */ new Map();
|
|
22
|
+
const determineLocaleWithCache = (locale) => {
|
|
23
|
+
const cached = resolvedConfigLocales.get(locale);
|
|
24
|
+
if (cached !== void 0) return cached;
|
|
25
|
+
const resolved = gt.determineLocale(locale, locales) ?? locale;
|
|
26
|
+
resolvedConfigLocales.set(locale, resolved);
|
|
27
|
+
return resolved;
|
|
28
|
+
};
|
|
29
|
+
const resolvePathConfigLocale = process.env._GENERALTRANSLATION_GT_SERVICES_ENABLED === "true" ? determineLocaleWithCache : (locale) => locale;
|
|
30
|
+
const headersAndCookies = i18nConfig.headersAndCookies || {};
|
|
31
|
+
const localeRoutingEnabledCookieName = headersAndCookies?.localeRoutingEnabledCookieName || "generaltranslation.locale-routing-enabled";
|
|
32
|
+
const referrerLocaleCookieName = headersAndCookies?.referrerLocaleCookieName || "generaltranslation.referrer-locale";
|
|
33
|
+
const localeCookieName = headersAndCookies?.localeCookieName || defaultLocaleCookieName;
|
|
34
|
+
const resetLocaleCookieName = headersAndCookies?.resetLocaleCookieName || defaultResetLocaleCookieName;
|
|
35
|
+
const localeHeaderName = headersAndCookies?.localeHeaderName || "x-generaltranslation-locale";
|
|
36
|
+
if (!gt.isValidLocale(defaultLocale)) throw new Error(`gt-next middleware: defaultLocale "${defaultLocale}" is not a valid locale.`);
|
|
37
|
+
const warningLocales = locales.filter((locale) => !gt.isValidLocale(locale));
|
|
38
|
+
if (warningLocales.length) console.warn(createUnsupportedLocalesWarning(warningLocales));
|
|
39
|
+
const pathConfig = Object.entries(inputPathConfig).reduce((acc, [sharedPath, localizedPath]) => {
|
|
40
|
+
if (typeof localizedPath === "string") acc[sharedPath] = localizedPath;
|
|
41
|
+
else acc[sharedPath] = Object.entries(localizedPath).reduce((acc, [locale, localizedPath]) => {
|
|
42
|
+
acc[resolvePathConfigLocale(locale)] = localizedPath;
|
|
43
|
+
return acc;
|
|
44
|
+
}, {});
|
|
45
|
+
return acc;
|
|
46
|
+
}, {});
|
|
47
|
+
const { pathToSharedPath, defaultLocalePaths } = createPathToSharedPathMap(Object.fromEntries(Object.entries(pathConfig).map(([sharedPath, localizedPath]) => [sharedPath, typeof localizedPath === "string" ? Object.fromEntries(locales.map((locale) => [determineLocaleWithCache(locale), localizedPath === "" ? "/" : localizedPath])) : localizedPath])), prefixDefaultLocale, defaultLocale);
|
|
48
|
+
const routeOverrides = Object.entries(inputRouteOverrides).reduce((acc, [locale, paths]) => {
|
|
49
|
+
acc[resolvePathConfigLocale(locale)] = paths;
|
|
50
|
+
return acc;
|
|
51
|
+
}, {});
|
|
52
|
+
return {
|
|
53
|
+
pathRegex,
|
|
54
|
+
gt,
|
|
55
|
+
defaultLocale,
|
|
56
|
+
locales,
|
|
57
|
+
localeRoutingEnabledCookieName,
|
|
58
|
+
referrerLocaleCookieName,
|
|
59
|
+
localeCookieName,
|
|
60
|
+
resetLocaleCookieName,
|
|
61
|
+
localeHeaderName,
|
|
62
|
+
pathConfig,
|
|
63
|
+
pathToSharedPath,
|
|
64
|
+
defaultLocalePaths,
|
|
65
|
+
routeOverridePathMaps: Object.entries(routeOverrides).reduce((acc, [locale, paths]) => {
|
|
66
|
+
acc[locale] = createPathToSharedPathMap(Object.fromEntries(paths.map((path) => [path, path])), true, defaultLocale).pathToSharedPath;
|
|
67
|
+
return acc;
|
|
68
|
+
}, {}),
|
|
69
|
+
localeRoutePathMaps: new Map(Object.entries(localeRoutes).map(([locale, paths]) => {
|
|
70
|
+
return [determineLocaleWithCache(locale), createPathMatcher(paths.map((path) => [path, path]))];
|
|
71
|
+
}))
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
//#endregion
|
|
75
|
+
export { createMiddlewareRouting };
|
|
76
|
+
|
|
77
|
+
//# sourceMappingURL=createMiddlewareRouting.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"createMiddlewareRouting.mjs","names":[],"sources":["../../src/middleware-dir/createMiddlewareRouting.ts"],"sourcesContent":["import { GTRuntime } from 'generaltranslation/runtime';\nimport { libraryDefaultLocale } from 'generaltranslation/internal';\nimport {\n defaultLocaleCookieName,\n defaultResetLocaleCookieName,\n} from '@generaltranslation/react-core/pure';\nimport { createUnsupportedLocalesWarning } from '../errors/middleware';\nimport {\n defaultLocaleRoutingEnabledCookieName,\n defaultReferrerLocaleCookieName,\n} from '../utils/cookies';\nimport { defaultLocaleHeaderName } from '../utils/headers';\nimport { compilePathRegex } from '../utils/pathRegex';\nimport {\n createPathMatcher,\n createPathToSharedPathMap,\n type PathConfig,\n type PathMatcher,\n} from './createPathMatcher';\nimport { parseEnvConfig } from './resolveMiddlewareConfig';\nimport type {\n MiddlewareI18nConfig,\n MiddlewareRouting,\n ResolvedMiddlewareConfig,\n RouteOverrides,\n} from './types';\n\n/**\n * Pre-processes the locale, cookie, and path configuration once per\n * middleware instance so requests only do lookups.\n */\nexport function createMiddlewareRouting({\n pathConfig: inputPathConfig,\n routeOverrides: inputRouteOverrides,\n localeRoutes,\n prefixDefaultLocale,\n}: ResolvedMiddlewareConfig): MiddlewareRouting {\n const pathRegex = compilePathRegex(\n process.env._GENERALTRANSLATION_PATH_REGEX\n );\n\n // i18n config\n const i18nConfig = parseEnvConfig<MiddlewareI18nConfig>(\n '_GENERALTRANSLATION_I18N_CONFIG_PARAMS',\n process.env._GENERALTRANSLATION_I18N_CONFIG_PARAMS\n );\n\n // gt instance\n const gt = new GTRuntime({\n customMapping: i18nConfig.customMapping,\n });\n\n // Configured spellings are the identity used by routes, cookies and caches.\n const defaultLocale: string =\n i18nConfig.defaultLocale || libraryDefaultLocale;\n const locales = Array.from(\n new Set([defaultLocale, ...(i18nConfig.locales || [])])\n );\n // Route entries repeat locale keys. Resolve each key once per factory instead\n // of rebuilding the full locale-resolution index for every route/locale pair.\n const resolvedConfigLocales = new Map<string, string>();\n const determineLocaleWithCache = (locale: string) => {\n const cached = resolvedConfigLocales.get(locale);\n if (cached !== undefined) return cached;\n const resolved = gt.determineLocale(locale, locales) ?? locale;\n resolvedConfigLocales.set(locale, resolved);\n return resolved;\n };\n const resolvePathConfigLocale =\n process.env._GENERALTRANSLATION_GT_SERVICES_ENABLED === 'true'\n ? determineLocaleWithCache\n : (locale: string) => locale;\n\n // cookies and header names\n const headersAndCookies = i18nConfig.headersAndCookies || {};\n const localeRoutingEnabledCookieName =\n headersAndCookies?.localeRoutingEnabledCookieName ||\n defaultLocaleRoutingEnabledCookieName;\n const referrerLocaleCookieName =\n headersAndCookies?.referrerLocaleCookieName ||\n defaultReferrerLocaleCookieName;\n const localeCookieName =\n headersAndCookies?.localeCookieName || defaultLocaleCookieName;\n const resetLocaleCookieName =\n headersAndCookies?.resetLocaleCookieName || defaultResetLocaleCookieName;\n const localeHeaderName =\n headersAndCookies?.localeHeaderName || defaultLocaleHeaderName;\n\n if (!gt.isValidLocale(defaultLocale))\n throw new Error(\n `gt-next middleware: defaultLocale \"${defaultLocale}\" is not a valid locale.`\n );\n\n const warningLocales = locales.filter((locale) => !gt.isValidLocale(locale));\n if (warningLocales.length)\n console.warn(createUnsupportedLocalesWarning(warningLocales));\n\n // --- localized routes --- //\n // Resolve pathConfig keys to the configured locale spelling.\n const pathConfig = Object.entries(inputPathConfig).reduce<PathConfig>(\n (acc, [sharedPath, localizedPath]) => {\n if (typeof localizedPath === 'string') {\n acc[sharedPath] = localizedPath;\n } else {\n acc[sharedPath] = Object.entries(localizedPath).reduce<{\n [key: string]: string;\n }>((acc, [locale, localizedPath]) => {\n acc[resolvePathConfigLocale(locale)] = localizedPath;\n return acc;\n }, {});\n }\n return acc;\n },\n {}\n );\n\n // String aliases apply to every locale, including the default locale.\n // Expand a copy for lookup while retaining string target semantics in routing.\n const matcherPathConfig = Object.fromEntries(\n Object.entries(pathConfig).map(([sharedPath, localizedPath]) => [\n sharedPath,\n typeof localizedPath === 'string'\n ? Object.fromEntries(\n locales.map((locale) => [\n determineLocaleWithCache(locale),\n localizedPath === '' ? '/' : localizedPath,\n ])\n )\n : localizedPath,\n ])\n );\n\n // Create the path mapping\n const { pathToSharedPath, defaultLocalePaths } = createPathToSharedPathMap(\n matcherPathConfig,\n prefixDefaultLocale,\n defaultLocale\n );\n\n // --- route overrides --- //\n // Resolve routeOverrides keys to the configured locale spelling.\n const routeOverrides = Object.entries(\n inputRouteOverrides\n ).reduce<RouteOverrides>((acc, [locale, paths]) => {\n acc[resolvePathConfigLocale(locale)] = paths;\n return acc;\n }, {});\n\n // Create the route override path mapping\n const routeOverridePathMaps = Object.entries(routeOverrides).reduce<\n Record<string, PathMatcher>\n >((acc, [locale, paths]) => {\n const overridePathConfig = Object.fromEntries(\n paths.map((path) => [path, path])\n );\n acc[locale] = createPathToSharedPathMap(\n overridePathConfig,\n true,\n defaultLocale\n ).pathToSharedPath;\n return acc;\n }, {});\n\n // --- locale routes --- //\n // Compile availability separately from aliases and overrides so it cannot\n // change route precedence. An empty list deliberately matches nothing.\n const localeRoutePathMaps = new Map(\n Object.entries(localeRoutes).map(([locale, paths]) => {\n // Match request resolution so equivalent spellings use the same map key.\n const resolvedLocale = determineLocaleWithCache(locale);\n return [\n resolvedLocale,\n createPathMatcher(paths.map((path) => [path, path])),\n ];\n })\n );\n\n return {\n pathRegex,\n gt,\n defaultLocale,\n locales,\n localeRoutingEnabledCookieName,\n referrerLocaleCookieName,\n localeCookieName,\n resetLocaleCookieName,\n localeHeaderName,\n pathConfig,\n pathToSharedPath,\n defaultLocalePaths,\n routeOverridePathMaps,\n localeRoutePathMaps,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AA+BA,SAAgB,wBAAwB,EACtC,YAAY,iBACZ,gBAAgB,qBAChB,cACA,uBAC8C;CAC9C,MAAM,YAAY,iBAChB,QAAQ,IAAI,+BACb;CAGD,MAAM,aAAa,eACjB,0CACA,QAAQ,IAAI,uCACb;CAGD,MAAM,KAAK,IAAI,UAAU,EACvB,eAAe,WAAW,eAC3B,CAAC;CAGF,MAAM,gBACJ,WAAW,iBAAiB;CAC9B,MAAM,UAAU,MAAM,KACpB,IAAI,IAAI,CAAC,eAAe,GAAI,WAAW,WAAW,EAAE,CAAE,CAAC,CACxD;CAGD,MAAM,wCAAwB,IAAI,KAAqB;CACvD,MAAM,4BAA4B,WAAmB;EACnD,MAAM,SAAS,sBAAsB,IAAI,OAAO;AAChD,MAAI,WAAW,KAAA,EAAW,QAAO;EACjC,MAAM,WAAW,GAAG,gBAAgB,QAAQ,QAAQ,IAAI;AACxD,wBAAsB,IAAI,QAAQ,SAAS;AAC3C,SAAO;;CAET,MAAM,0BACJ,QAAQ,IAAI,4CAA4C,SACpD,4BACC,WAAmB;CAG1B,MAAM,oBAAoB,WAAW,qBAAqB,EAAE;CAC5D,MAAM,iCACJ,mBAAmB,kCAAA;CAErB,MAAM,2BACJ,mBAAmB,4BAAA;CAErB,MAAM,mBACJ,mBAAmB,oBAAoB;CACzC,MAAM,wBACJ,mBAAmB,yBAAyB;CAC9C,MAAM,mBACJ,mBAAmB,oBAAA;AAErB,KAAI,CAAC,GAAG,cAAc,cAAc,CAClC,OAAM,IAAI,MACR,sCAAsC,cAAc,0BACrD;CAEH,MAAM,iBAAiB,QAAQ,QAAQ,WAAW,CAAC,GAAG,cAAc,OAAO,CAAC;AAC5E,KAAI,eAAe,OACjB,SAAQ,KAAK,gCAAgC,eAAe,CAAC;CAI/D,MAAM,aAAa,OAAO,QAAQ,gBAAgB,CAAC,QAChD,KAAK,CAAC,YAAY,mBAAmB;AACpC,MAAI,OAAO,kBAAkB,SAC3B,KAAI,cAAc;MAElB,KAAI,cAAc,OAAO,QAAQ,cAAc,CAAC,QAE5C,KAAK,CAAC,QAAQ,mBAAmB;AACnC,OAAI,wBAAwB,OAAO,IAAI;AACvC,UAAO;KACN,EAAE,CAAC;AAER,SAAO;IAET,EAAE,CACH;CAmBD,MAAM,EAAE,kBAAkB,uBAAuB,0BAfvB,OAAO,YAC/B,OAAO,QAAQ,WAAW,CAAC,KAAK,CAAC,YAAY,mBAAmB,CAC9D,YACA,OAAO,kBAAkB,WACrB,OAAO,YACL,QAAQ,KAAK,WAAW,CACtB,yBAAyB,OAAO,EAChC,kBAAkB,KAAK,MAAM,cAC9B,CAAC,CACH,GACD,cACL,CAAC,CAKe,EACjB,qBACA,cACD;CAID,MAAM,iBAAiB,OAAO,QAC5B,oBACD,CAAC,QAAwB,KAAK,CAAC,QAAQ,WAAW;AACjD,MAAI,wBAAwB,OAAO,IAAI;AACvC,SAAO;IACN,EAAE,CAAC;AA+BN,QAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,uBAzC4B,OAAO,QAAQ,eAAe,CAAC,QAE1D,KAAK,CAAC,QAAQ,WAAW;AAI1B,OAAI,UAAU,0BAHa,OAAO,YAChC,MAAM,KAAK,SAAS,CAAC,MAAM,KAAK,CAAC,CAGf,EAClB,MACA,cACD,CAAC;AACF,UAAO;KACN,EAAE,CA6BkB;EACrB,qBAAA,IAzB8B,IAC9B,OAAO,QAAQ,aAAa,CAAC,KAAK,CAAC,QAAQ,WAAW;AAGpD,UAAO,CADgB,yBAAyB,OAEhC,EACd,kBAAkB,MAAM,KAAK,SAAS,CAAC,MAAM,KAAK,CAAC,CAAC,CACrD;IACD,CAiBiB;EACpB"}
|
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
import { NextResponse } from 'next/server';
|
|
2
2
|
import type { NextRequest } from 'next/server';
|
|
3
|
-
import {
|
|
4
|
-
export type RouteOverrides
|
|
5
|
-
export type LocaleRoutes = Record<string, readonly string[]>;
|
|
3
|
+
import type { MiddlewareConfig } from './types';
|
|
4
|
+
export type { RouteOverrides, LocaleRoutes } from './types';
|
|
6
5
|
/**
|
|
7
6
|
* Middleware factory to create a Next.js middleware for i18n routing and locale detection.
|
|
8
7
|
*
|
|
@@ -11,6 +10,8 @@ export type LocaleRoutes = Record<string, readonly string[]>;
|
|
|
11
10
|
* If locale routing is enabled, it redirects to the localized pathname and
|
|
12
11
|
* updates the locale cookie.
|
|
13
12
|
*
|
|
13
|
+
* Options omitted here fall back to the same options passed to `withGTConfig()`.
|
|
14
|
+
*
|
|
14
15
|
* @param {boolean} [config.localeRouting=true] - Flag to enable or disable automatic locale-based routing.
|
|
15
16
|
* @param {boolean} [config.prefixDefaultLocale=false] - Flag to enable or disable prefixing the default locale to the pathname, i.e., /en/about -> /about
|
|
16
17
|
* @param {boolean} [config.enableSmartRouting=true] - Keep automatic locale negotiation. Disable to treat returning visitors' unprefixed URLs as default-locale routes.
|
|
@@ -20,13 +21,5 @@ export type LocaleRoutes = Record<string, readonly string[]>;
|
|
|
20
21
|
* @param {LocaleRoutes} [config.localeRoutes] - Shared paths available per locale; other paths fall back to the default locale
|
|
21
22
|
* @returns {function} - A middleware function that processes the request and response.
|
|
22
23
|
*/
|
|
23
|
-
export declare function createNextMiddleware(
|
|
24
|
-
localeRouting?: boolean;
|
|
25
|
-
prefixDefaultLocale?: boolean;
|
|
26
|
-
enableSmartRouting?: boolean;
|
|
27
|
-
ignoreSourceMaps?: boolean;
|
|
28
|
-
pathConfig?: PathConfig;
|
|
29
|
-
routeOverrides?: RouteOverrides;
|
|
30
|
-
localeRoutes?: LocaleRoutes;
|
|
31
|
-
}): (req: NextRequest) => NextResponse<unknown>;
|
|
24
|
+
export declare function createNextMiddleware(options?: MiddlewareConfig): (req: NextRequest) => NextResponse<unknown>;
|
|
32
25
|
//# sourceMappingURL=createNextMiddleware.d.ts.map
|