hono-intlayer 9.5.12 → 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,16 +1,15 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ let node_async_hooks = require("node:async_hooks");
3
+ let _intlayer_config_built = require("@intlayer/config/built");
2
4
  let _intlayer_config_node = require("@intlayer/config/node");
3
5
  let _intlayer_core_interpreter = require("@intlayer/core/interpreter");
4
6
  let _intlayer_core_localization = require("@intlayer/core/localization");
5
7
  let _intlayer_core_utils = require("@intlayer/core/utils");
6
8
  let _intlayer_engine_build = require("@intlayer/engine/build");
7
- let cls_hooked = require("cls-hooked");
8
9
  let hono_cookie = require("hono/cookie");
9
10
 
10
11
  //#region src/index.ts
11
12
  let debug = () => {};
12
- const configuration = (0, _intlayer_config_node.getConfiguration)();
13
- const { internationalization } = configuration;
14
13
  if (process.env.NODE_ENV === "development") debug = (msg) => console.debug(msg);
15
14
  /**
16
15
  * Retrieves the locale from storage (cookies, headers).
@@ -19,28 +18,27 @@ const getStorageLocale = (context) => (0, _intlayer_core_utils.getLocaleFromStor
19
18
  getCookie: (name) => (0, hono_cookie.getCookie)(context, name),
20
19
  getHeader: (name) => context.req.header(name)
21
20
  });
22
- const appNamespace = (0, cls_hooked.createNamespace)("app");
23
- (0, _intlayer_core_interpreter.registerAmbientLocaleResolver)(() => appNamespace.get("locale"));
24
- (0, _intlayer_engine_build.prepareIntlayerServer)(configuration, { label: "hono-intlayer" });
25
- const translateFunction = (context) => (content, locale) => {
26
- const currentLocale = context.get("locale");
27
- const defaultLocale = context.get("defaultLocale");
28
- const targetLocale = locale ?? currentLocale;
29
- if (typeof content === "undefined") return "";
30
- if (typeof content === "string") return content;
31
- if (typeof content?.[targetLocale] === "undefined") {
32
- if (typeof content?.[defaultLocale] === "undefined") return content;
33
- else return (0, _intlayer_core_interpreter.getTranslation)(content, defaultLocale);
34
- }
35
- return (0, _intlayer_core_interpreter.getTranslation)(content, targetLocale);
36
- };
21
+ /**
22
+ * Request-scoped Intlayer context.
23
+ *
24
+ * `AsyncLocalStorage` rather than `cls-hooked`: the latter relies on
25
+ * `async_hooks.createHook`, which Bun does not implement, and is several times
26
+ * slower on Node.
27
+ */
28
+ const intlayerStorage = new node_async_hooks.AsyncLocalStorage();
29
+ (0, _intlayer_core_interpreter.registerAmbientLocaleResolver)(() => intlayerStorage.getStore()?.locale);
30
+ (0, _intlayer_engine_build.prepareIntlayerServer)((0, _intlayer_config_node.getConfiguration)(), { label: "hono-intlayer" });
31
+ /**
32
+ * Builds the translation function bound to the locale stored in the Hono context.
33
+ */
34
+ const translateFunction = (context) => (content, locale) => typeof content === "string" ? content : (0, _intlayer_core_interpreter.getTranslation)(content, locale ?? context.get("locale"), _intlayer_config_built.internationalization.defaultLocale);
37
35
  /**
38
36
  * Hono middleware that detects the user's locale and populates context with Intlayer data.
39
37
  *
40
38
  * It performs:
41
39
  * 1. Locale detection from cookies, headers, or default settings.
42
40
  * 2. Injects `t`, `getIntlayer`, and `getDictionary` functions into the context.
43
- * 3. Sets up a `cls-hooked` namespace for accessing these functions anywhere in the request lifecycle.
41
+ * 3. Sets up an `AsyncLocalStorage` context for accessing these functions anywhere in the request lifecycle.
44
42
  *
45
43
  * @returns A Hono middleware function.
46
44
  *
@@ -53,31 +51,26 @@ const translateFunction = (context) => (content, locale) => {
53
51
  * app.use('*', intlayer());
54
52
  * ```
55
53
  */
56
- const intlayer = () => async (context, next) => {
54
+ const intlayer = () => (context, next) => {
57
55
  const localeFromStorage = getStorageLocale(context);
58
- const negotiatorHeaders = context.req.header();
59
- const localeDetected = (0, _intlayer_core_localization.localeDetector)(negotiatorHeaders, internationalization.locales, internationalization.defaultLocale);
56
+ const localeDetected = (0, _intlayer_core_localization.localeDetector)({ "accept-language": context.req.header("accept-language") }, _intlayer_config_built.internationalization.locales, _intlayer_config_built.internationalization.defaultLocale);
60
57
  const locale = localeFromStorage ?? localeDetected;
61
58
  context.set("locale_storage", localeFromStorage);
62
59
  context.set("locale_detected", localeDetected);
63
60
  context.set("locale", locale);
64
- context.set("defaultLocale", internationalization.defaultLocale);
61
+ context.set("defaultLocale", _intlayer_config_built.internationalization.defaultLocale);
65
62
  const t = translateFunction(context);
66
63
  const getIntlayer = (key, localeArg = locale, ...props) => (0, _intlayer_core_interpreter.getIntlayer)(key, localeArg, ...props);
67
64
  const getDictionary = (key, localeArg = locale, ...props) => (0, _intlayer_core_interpreter.getDictionary)(key, localeArg, ...props);
68
65
  context.set("t", t);
69
66
  context.set("getIntlayer", getIntlayer);
70
67
  context.set("getDictionary", getDictionary);
71
- return new Promise((resolve) => {
72
- appNamespace.run(async () => {
73
- appNamespace.set("locale", locale);
74
- appNamespace.set("t", t);
75
- appNamespace.set("getIntlayer", getIntlayer);
76
- appNamespace.set("getDictionary", getDictionary);
77
- await next();
78
- resolve();
79
- });
80
- });
68
+ return intlayerStorage.run({
69
+ locale,
70
+ t,
71
+ getIntlayer,
72
+ getDictionary
73
+ }, next);
81
74
  };
82
75
  /**
83
76
  * Translation function to retrieve content for the current locale.
@@ -102,34 +95,28 @@ const intlayer = () => async (context, next) => {
102
95
  * ```
103
96
  */
104
97
  const t = (content, locale) => {
105
- try {
106
- if (typeof appNamespace === "undefined") throw new Error("Intlayer is not initialized. Add the `app.use(\"*\", intlayer());` middleware before using this function.");
107
- if (typeof appNamespace.get("t") !== "function") throw new Error("Using the import { t } from \"hono-intlayer\" is not supported in your environment. Use the context instead.");
108
- return appNamespace.get("t")(content, locale);
109
- } catch (error) {
110
- debug(error.message);
111
- return (0, _intlayer_core_interpreter.getTranslation)(content, locale ?? internationalization.defaultLocale);
98
+ const context = intlayerStorage.getStore();
99
+ if (!context) {
100
+ debug("Using the import { t } from \"hono-intlayer\" outside of a request handled by the `intlayer()` middleware. Use the context instead.");
101
+ return (0, _intlayer_core_interpreter.getTranslation)(content, locale ?? _intlayer_config_built.internationalization.defaultLocale);
112
102
  }
103
+ return context.t(content, locale);
113
104
  };
114
105
  const getIntlayer = (...args) => {
115
- try {
116
- if (typeof appNamespace === "undefined") throw new Error("Intlayer is not initialized. Add the `app.use(\"*\", intlayer());` middleware before using this function.");
117
- if (typeof appNamespace.get("getIntlayer") !== "function") throw new Error("Using the import { getIntlayer } from \"hono-intlayer\" is not supported in your environment. Use the context instead.");
118
- return appNamespace.get("getIntlayer")(...args);
119
- } catch (error) {
120
- debug(error.message);
106
+ const context = intlayerStorage.getStore();
107
+ if (!context) {
108
+ debug("Using the import { getIntlayer } from \"hono-intlayer\" outside of a request handled by the `intlayer()` middleware. Use the context instead.");
121
109
  return (0, _intlayer_core_interpreter.getIntlayer)(...args);
122
110
  }
111
+ return context.getIntlayer(...args);
123
112
  };
124
113
  const getDictionary = (...args) => {
125
- try {
126
- if (typeof appNamespace === "undefined") throw new Error("Intlayer is not initialized. Add the `app.use(\"*\", intlayer());` middleware before using this function.");
127
- if (typeof appNamespace.get("getDictionary") !== "function") throw new Error("Using the import { getDictionary } from \"hono-intlayer\" is not supported in your environment. Use the context instead.");
128
- return appNamespace.get("getDictionary")(...args);
129
- } catch (error) {
130
- debug(error.message);
114
+ const context = intlayerStorage.getStore();
115
+ if (!context) {
116
+ debug("Using the import { getDictionary } from \"hono-intlayer\" outside of a request handled by the `intlayer()` middleware. Use the context instead.");
131
117
  return (0, _intlayer_core_interpreter.getDictionary)(...args);
132
118
  }
119
+ return context.getDictionary(...args);
133
120
  };
134
121
 
135
122
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["getConfiguration","getLocaleFromStorageServer","getCookie","createNamespace","registerAmbientLocaleResolver","prepareIntlayerServer","getTranslation","localeDetector","getIntlayerFunction","getDictionaryFunction"],"sources":["../../src/index.ts"],"sourcesContent":["import { getConfiguration } from '@intlayer/config/node';\nimport {\n getDictionary as getDictionaryFunction,\n getIntlayer as getIntlayerFunction,\n getTranslation,\n registerAmbientLocaleResolver,\n} from '@intlayer/core/interpreter';\nimport { localeDetector } from '@intlayer/core/localization';\nimport { getLocaleFromStorageServer } from '@intlayer/core/utils';\nimport { prepareIntlayerServer } from '@intlayer/engine/build';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { StrictModeLocaleMap } from '@intlayer/types/module_augmentation';\nimport { createNamespace } from 'cls-hooked';\nimport type { Context, MiddlewareHandler } from 'hono';\nimport { getCookie } from 'hono/cookie';\n\n// Zero-cost fallback, will be updated with console logger in dev mode\nlet debug: (message: string) => void = () => {};\n\nconst configuration = getConfiguration();\nconst { internationalization } = configuration;\n\nif (process.env['NODE_ENV'] === 'development') {\n debug = (msg: string) => console.debug(msg);\n}\n\n/**\n * Retrieves the locale from storage (cookies, headers).\n */\nconst getStorageLocale = (context: Context): Locale | undefined =>\n getLocaleFromStorageServer({\n getCookie: (name: string) => getCookie(context, name),\n getHeader: (name: string) => context.req.header(name),\n });\n\nconst appNamespace = createNamespace('app');\n\n// Lets a bare `getIntlayer` / `getDictionary` from any Intlayer package resolve\n// to the locale of the request being handled.\nregisterAmbientLocaleResolver(() => appNamespace.get('locale'));\n\nprepareIntlayerServer(configuration, { label: 'hono-intlayer' });\n\nexport const translateFunction =\n (context: Context) =>\n <T extends string>(\n content: StrictModeLocaleMap<T> | string,\n locale?: Locale\n ): T => {\n const currentLocale = context.get('locale') as Locale;\n const defaultLocale = context.get('defaultLocale') as Locale;\n\n const targetLocale = locale ?? currentLocale;\n\n if (typeof content === 'undefined') {\n return '' as unknown as T;\n }\n\n if (typeof content === 'string') {\n return content as unknown as T;\n }\n\n if (\n typeof content?.[\n targetLocale as unknown as keyof StrictModeLocaleMap<T>\n ] === 'undefined'\n ) {\n if (\n typeof content?.[\n defaultLocale as unknown as keyof StrictModeLocaleMap<T>\n ] === 'undefined'\n ) {\n return content as unknown as T;\n } else {\n return getTranslation(content, defaultLocale);\n }\n }\n\n return getTranslation(content, targetLocale);\n };\n\n/**\n * Hono middleware that detects the user's locale and populates context with Intlayer data.\n *\n * It performs:\n * 1. Locale detection from cookies, headers, or default settings.\n * 2. Injects `t`, `getIntlayer`, and `getDictionary` functions into the context.\n * 3. Sets up a `cls-hooked` namespace for accessing these functions anywhere in the request lifecycle.\n *\n * @returns A Hono middleware function.\n *\n * @example\n * ```ts\n * import { Hono } from 'hono';\n * import { intlayer } from 'hono-intlayer';\n *\n * const app = new Hono();\n * app.use('*', intlayer());\n * ```\n */\nexport const intlayer =\n (): MiddlewareHandler =>\n async (context: Context, next: () => Promise<void>) => {\n // Detect if locale is set by intlayer frontend lib in the headers\n const localeFromStorage = getStorageLocale(context);\n\n const negotiatorHeaders: Record<string, string> = context.req.header();\n\n const localeDetected = localeDetector(\n negotiatorHeaders,\n internationalization.locales,\n internationalization.defaultLocale\n );\n\n const locale = localeFromStorage ?? localeDetected;\n\n context.set('locale_storage', localeFromStorage);\n context.set('locale_detected', localeDetected);\n context.set('locale', locale);\n context.set('defaultLocale', internationalization.defaultLocale);\n\n const t = translateFunction(context);\n\n const getIntlayer: typeof getIntlayerFunction = (\n key: Parameters<typeof getIntlayerFunction>[0],\n localeArg = locale as Parameters<typeof getIntlayerFunction>[1],\n ...props: any[]\n ) => getIntlayerFunction(key, localeArg, ...props);\n\n const getDictionary: typeof getDictionaryFunction = (\n key: Parameters<typeof getDictionaryFunction>[0],\n localeArg = locale as Parameters<typeof getDictionaryFunction>[1],\n ...props: any[]\n ) => getDictionaryFunction(key, localeArg, ...props);\n\n context.set('t', t);\n context.set('getIntlayer', getIntlayer);\n context.set('getDictionary', getDictionary);\n\n return new Promise<void>((resolve) => {\n appNamespace.run(async () => {\n appNamespace.set('locale', locale);\n appNamespace.set('t', t);\n appNamespace.set('getIntlayer', getIntlayer);\n appNamespace.set('getDictionary', getDictionary);\n\n await next();\n resolve();\n });\n });\n };\n\n/**\n * Translation function to retrieve content for the current locale.\n *\n * This function works within the request lifecycle managed by the `intlayer` middleware.\n *\n * @param content - A map of locales to content.\n * @param locale - Optional locale override.\n * @returns The translated content.\n *\n * @example\n * ```ts\n * import { t } from 'hono-intlayer';\n *\n * app.get('/', (c) => {\n * const greeting = t({\n * en: 'Hello',\n * fr: 'Bonjour',\n * });\n * return c.text(greeting);\n * });\n * ```\n */\nexport const t = <Content = string>(\n content: StrictModeLocaleMap<Content>,\n locale?: Locale\n): Content => {\n try {\n if (typeof appNamespace === 'undefined') {\n throw new Error(\n 'Intlayer is not initialized. Add the `app.use(\"*\", intlayer());` middleware before using this function.'\n );\n }\n\n if (typeof appNamespace.get('t') !== 'function') {\n throw new Error(\n 'Using the import { t } from \"hono-intlayer\" is not supported in your environment. Use the context instead.'\n );\n }\n\n return appNamespace.get('t')(content, locale);\n } catch (error) {\n debug((error as Error).message);\n\n return getTranslation(\n content,\n locale ?? internationalization.defaultLocale\n );\n }\n};\n\nexport const getIntlayer: typeof getIntlayerFunction = (\n ...args: Parameters<typeof getIntlayerFunction>\n) => {\n try {\n if (typeof appNamespace === 'undefined') {\n throw new Error(\n 'Intlayer is not initialized. Add the `app.use(\"*\", intlayer());` middleware before using this function.'\n );\n }\n\n if (typeof appNamespace.get('getIntlayer') !== 'function') {\n throw new Error(\n 'Using the import { getIntlayer } from \"hono-intlayer\" is not supported in your environment. Use the context instead.'\n );\n }\n\n return appNamespace.get('getIntlayer')(...args);\n } catch (error) {\n debug((error as Error).message);\n\n return getIntlayerFunction(...args);\n }\n};\n\nexport const getDictionary: typeof getDictionaryFunction = (\n ...args: Parameters<typeof getDictionaryFunction>\n) => {\n try {\n if (typeof appNamespace === 'undefined') {\n throw new Error(\n 'Intlayer is not initialized. Add the `app.use(\"*\", intlayer());` middleware before using this function.'\n );\n }\n\n if (typeof appNamespace.get('getDictionary') !== 'function') {\n throw new Error(\n 'Using the import { getDictionary } from \"hono-intlayer\" is not supported in your environment. Use the context instead.'\n );\n }\n\n return appNamespace.get('getDictionary')(...args);\n } catch (error) {\n debug((error as Error).message);\n\n return getDictionaryFunction(...args);\n }\n};\n"],"mappings":";;;;;;;;;;AAiBA,IAAI,cAAyC,CAAC;AAE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ACF;EAGF,OAAO,aAAa,IAAI,eAAe,CAAC,CAAC,GAAG,IAAI;CAClD,SAAS,OAAO;EACd,MAAO,MAAgB,OAAO;EAE9B,WAAOC,0CAAsB,GAAG,IAAI;CACtC;AACF"}
1
+ {"version":3,"file":"index.cjs","names":["getLocaleFromStorageServer","getCookie","AsyncLocalStorage","registerAmbientLocaleResolver","prepareIntlayerServer","getConfiguration","getTranslation","internationalization","localeDetector","getIntlayerFunction","getDictionaryFunction"],"sources":["../../src/index.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport { internationalization } from '@intlayer/config/built';\nimport { getConfiguration } from '@intlayer/config/node';\nimport {\n getDictionary as getDictionaryFunction,\n getIntlayer as getIntlayerFunction,\n getTranslation,\n registerAmbientLocaleResolver,\n} from '@intlayer/core/interpreter';\nimport { localeDetector } from '@intlayer/core/localization';\nimport { getLocaleFromStorageServer } from '@intlayer/core/utils';\nimport { prepareIntlayerServer } from '@intlayer/engine/build';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { StrictModeLocaleMap } from '@intlayer/types/module_augmentation';\nimport type { Context, MiddlewareHandler } from 'hono';\nimport { getCookie } from 'hono/cookie';\n\n// Zero-cost fallback, will be updated with console logger in dev mode\nlet debug: (message: string) => void = () => {};\n\nif (process.env['NODE_ENV'] === 'development') {\n debug = (msg: string) => console.debug(msg);\n}\n\n/**\n * Retrieves the locale from storage (cookies, headers).\n */\nconst getStorageLocale = (context: Context): Locale | undefined =>\n getLocaleFromStorageServer({\n getCookie: (name: string) => getCookie(context, name),\n getHeader: (name: string) => context.req.header(name),\n });\n\n/**\n * Intlayer helpers bound to the request being handled.\n */\ntype IntlayerRequestContext = {\n locale: Locale;\n t: ReturnType<typeof translateFunction>;\n getIntlayer: typeof getIntlayerFunction;\n getDictionary: typeof getDictionaryFunction;\n};\n\n/**\n * Request-scoped Intlayer context.\n *\n * `AsyncLocalStorage` rather than `cls-hooked`: the latter relies on\n * `async_hooks.createHook`, which Bun does not implement, and is several times\n * slower on Node.\n */\nconst intlayerStorage = new AsyncLocalStorage<IntlayerRequestContext>();\n\n// Lets a bare `getIntlayer` / `getDictionary` from any Intlayer package resolve\n// to the locale of the request being handled.\nregisterAmbientLocaleResolver(() => intlayerStorage.getStore()?.locale);\n\nprepareIntlayerServer(getConfiguration(), { label: 'hono-intlayer' });\n\n/**\n * Builds the translation function bound to the locale stored in the Hono context.\n */\nexport const translateFunction =\n (context: Context) =>\n <T extends string>(\n content: StrictModeLocaleMap<T> | string,\n locale?: Locale\n ): T =>\n typeof content === 'string'\n ? (content as T)\n : getTranslation(\n content,\n locale ?? (context.get('locale') as Locale),\n internationalization.defaultLocale\n );\n\n/**\n * Hono middleware that detects the user's locale and populates context with Intlayer data.\n *\n * It performs:\n * 1. Locale detection from cookies, headers, or default settings.\n * 2. Injects `t`, `getIntlayer`, and `getDictionary` functions into the context.\n * 3. Sets up an `AsyncLocalStorage` context for accessing these functions anywhere in the request lifecycle.\n *\n * @returns A Hono middleware function.\n *\n * @example\n * ```ts\n * import { Hono } from 'hono';\n * import { intlayer } from 'hono-intlayer';\n *\n * const app = new Hono();\n * app.use('*', intlayer());\n * ```\n */\nexport const intlayer =\n (): MiddlewareHandler => (context: Context, next: () => Promise<void>) => {\n // Detect if locale is set by intlayer frontend lib in the headers\n const localeFromStorage = getStorageLocale(context);\n\n const localeDetected = localeDetector(\n { 'accept-language': context.req.header('accept-language') },\n internationalization.locales,\n internationalization.defaultLocale\n );\n\n const locale = localeFromStorage ?? localeDetected;\n\n context.set('locale_storage', localeFromStorage);\n context.set('locale_detected', localeDetected);\n context.set('locale', locale);\n context.set('defaultLocale', internationalization.defaultLocale);\n\n const t = translateFunction(context);\n\n const getIntlayer: typeof getIntlayerFunction = (\n key,\n localeArg = locale as typeof localeArg,\n ...props\n ) => getIntlayerFunction(key, localeArg, ...props);\n\n const getDictionary: typeof getDictionaryFunction = (\n key,\n localeArg = locale as typeof localeArg,\n ...props\n ) => getDictionaryFunction(key, localeArg, ...props);\n\n context.set('t', t);\n context.set('getIntlayer', getIntlayer);\n context.set('getDictionary', getDictionary);\n\n return intlayerStorage.run({ locale, t, getIntlayer, getDictionary }, next);\n };\n\n/**\n * Translation function to retrieve content for the current locale.\n *\n * This function works within the request lifecycle managed by the `intlayer` middleware.\n *\n * @param content - A map of locales to content.\n * @param locale - Optional locale override.\n * @returns The translated content.\n *\n * @example\n * ```ts\n * import { t } from 'hono-intlayer';\n *\n * app.get('/', (c) => {\n * const greeting = t({\n * en: 'Hello',\n * fr: 'Bonjour',\n * });\n * return c.text(greeting);\n * });\n * ```\n */\nexport const t = <Content = string>(\n content: StrictModeLocaleMap<Content>,\n locale?: Locale\n): Content => {\n const context = intlayerStorage.getStore();\n\n if (!context) {\n debug(\n 'Using the import { t } from \"hono-intlayer\" outside of a request handled by the `intlayer()` middleware. Use the context instead.'\n );\n\n return getTranslation(\n content,\n locale ?? internationalization.defaultLocale\n );\n }\n\n return context.t(content as StrictModeLocaleMap<string>, locale) as Content;\n};\n\nexport const getIntlayer: typeof getIntlayerFunction = (\n ...args: Parameters<typeof getIntlayerFunction>\n) => {\n const context = intlayerStorage.getStore();\n\n if (!context) {\n debug(\n 'Using the import { getIntlayer } from \"hono-intlayer\" outside of a request handled by the `intlayer()` middleware. Use the context instead.'\n );\n\n return getIntlayerFunction(...args);\n }\n\n return context.getIntlayer(...args);\n};\n\nexport const getDictionary: typeof getDictionaryFunction = (\n ...args: Parameters<typeof getDictionaryFunction>\n) => {\n const context = intlayerStorage.getStore();\n\n if (!context) {\n debug(\n 'Using the import { getDictionary } from \"hono-intlayer\" outside of a request handled by the `intlayer()` middleware. Use the context instead.'\n );\n\n return getDictionaryFunction(...args);\n }\n\n return context.getDictionary(...args);\n};\n"],"mappings":";;;;;;;;;;;AAkBA,IAAI,cAAyC,CAAC;AAE9C,6BAAgC,eAC9B,SAAS,QAAgB,QAAQ,MAAM,GAAG;;;;AAM5C,MAAM,oBAAoB,gBACxBA,iDAA2B;CACzB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;EACZ,MACE,qIACF;EAEA,WAAOJ,2CACL,SACA,UAAUC,4CAAqB,aACjC;CACF;CAEA,OAAO,QAAQ,EAAE,SAAwC,MAAM;AACjE;AAEA,MAAa,eACX,GAAG,SACA;CACH,MAAM,UAAU,gBAAgB,SAAS;CAEzC,IAAI,CAAC,SAAS;EACZ,MACE,+IACF;EAEA,WAAOE,wCAAoB,GAAG,IAAI;CACpC;CAEA,OAAO,QAAQ,YAAY,GAAG,IAAI;AACpC;AAEA,MAAa,iBACX,GAAG,SACA;CACH,MAAM,UAAU,gBAAgB,SAAS;CAEzC,IAAI,CAAC,SAAS;EACZ,MACE,iJACF;EAEA,WAAOC,0CAAsB,GAAG,IAAI;CACtC;CAEA,OAAO,QAAQ,cAAc,GAAG,IAAI;AACtC"}
@@ -1,15 +1,14 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { internationalization } from "@intlayer/config/built";
1
3
  import { getConfiguration } from "@intlayer/config/node";
2
4
  import { getDictionary as getDictionary$1, getIntlayer as getIntlayer$1, getTranslation, registerAmbientLocaleResolver } from "@intlayer/core/interpreter";
3
5
  import { localeDetector } from "@intlayer/core/localization";
4
6
  import { getLocaleFromStorageServer } from "@intlayer/core/utils";
5
7
  import { prepareIntlayerServer } from "@intlayer/engine/build";
6
- import { createNamespace } from "cls-hooked";
7
8
  import { getCookie } from "hono/cookie";
8
9
 
9
10
  //#region src/index.ts
10
11
  let debug = () => {};
11
- const configuration = getConfiguration();
12
- const { internationalization } = configuration;
13
12
  if (process.env.NODE_ENV === "development") debug = (msg) => console.debug(msg);
14
13
  /**
15
14
  * Retrieves the locale from storage (cookies, headers).
@@ -18,28 +17,27 @@ const getStorageLocale = (context) => getLocaleFromStorageServer({
18
17
  getCookie: (name) => getCookie(context, name),
19
18
  getHeader: (name) => context.req.header(name)
20
19
  });
21
- const appNamespace = createNamespace("app");
22
- registerAmbientLocaleResolver(() => appNamespace.get("locale"));
23
- prepareIntlayerServer(configuration, { label: "hono-intlayer" });
24
- const translateFunction = (context) => (content, locale) => {
25
- const currentLocale = context.get("locale");
26
- const defaultLocale = context.get("defaultLocale");
27
- const targetLocale = locale ?? currentLocale;
28
- if (typeof content === "undefined") return "";
29
- if (typeof content === "string") return content;
30
- if (typeof content?.[targetLocale] === "undefined") {
31
- if (typeof content?.[defaultLocale] === "undefined") return content;
32
- else return getTranslation(content, defaultLocale);
33
- }
34
- return getTranslation(content, targetLocale);
35
- };
20
+ /**
21
+ * Request-scoped Intlayer context.
22
+ *
23
+ * `AsyncLocalStorage` rather than `cls-hooked`: the latter relies on
24
+ * `async_hooks.createHook`, which Bun does not implement, and is several times
25
+ * slower on Node.
26
+ */
27
+ const intlayerStorage = new AsyncLocalStorage();
28
+ registerAmbientLocaleResolver(() => intlayerStorage.getStore()?.locale);
29
+ prepareIntlayerServer(getConfiguration(), { label: "hono-intlayer" });
30
+ /**
31
+ * Builds the translation function bound to the locale stored in the Hono context.
32
+ */
33
+ const translateFunction = (context) => (content, locale) => typeof content === "string" ? content : getTranslation(content, locale ?? context.get("locale"), internationalization.defaultLocale);
36
34
  /**
37
35
  * Hono middleware that detects the user's locale and populates context with Intlayer data.
38
36
  *
39
37
  * It performs:
40
38
  * 1. Locale detection from cookies, headers, or default settings.
41
39
  * 2. Injects `t`, `getIntlayer`, and `getDictionary` functions into the context.
42
- * 3. Sets up a `cls-hooked` namespace for accessing these functions anywhere in the request lifecycle.
40
+ * 3. Sets up an `AsyncLocalStorage` context for accessing these functions anywhere in the request lifecycle.
43
41
  *
44
42
  * @returns A Hono middleware function.
45
43
  *
@@ -52,10 +50,9 @@ const translateFunction = (context) => (content, locale) => {
52
50
  * app.use('*', intlayer());
53
51
  * ```
54
52
  */
55
- const intlayer = () => async (context, next) => {
53
+ const intlayer = () => (context, next) => {
56
54
  const localeFromStorage = getStorageLocale(context);
57
- const negotiatorHeaders = context.req.header();
58
- const localeDetected = localeDetector(negotiatorHeaders, internationalization.locales, internationalization.defaultLocale);
55
+ const localeDetected = localeDetector({ "accept-language": context.req.header("accept-language") }, internationalization.locales, internationalization.defaultLocale);
59
56
  const locale = localeFromStorage ?? localeDetected;
60
57
  context.set("locale_storage", localeFromStorage);
61
58
  context.set("locale_detected", localeDetected);
@@ -67,16 +64,12 @@ const intlayer = () => async (context, next) => {
67
64
  context.set("t", t);
68
65
  context.set("getIntlayer", getIntlayer);
69
66
  context.set("getDictionary", getDictionary);
70
- return new Promise((resolve) => {
71
- appNamespace.run(async () => {
72
- appNamespace.set("locale", locale);
73
- appNamespace.set("t", t);
74
- appNamespace.set("getIntlayer", getIntlayer);
75
- appNamespace.set("getDictionary", getDictionary);
76
- await next();
77
- resolve();
78
- });
79
- });
67
+ return intlayerStorage.run({
68
+ locale,
69
+ t,
70
+ getIntlayer,
71
+ getDictionary
72
+ }, next);
80
73
  };
81
74
  /**
82
75
  * Translation function to retrieve content for the current locale.
@@ -101,34 +94,28 @@ const intlayer = () => async (context, next) => {
101
94
  * ```
102
95
  */
103
96
  const t = (content, locale) => {
104
- try {
105
- if (typeof appNamespace === "undefined") throw new Error("Intlayer is not initialized. Add the `app.use(\"*\", intlayer());` middleware before using this function.");
106
- if (typeof appNamespace.get("t") !== "function") throw new Error("Using the import { t } from \"hono-intlayer\" is not supported in your environment. Use the context instead.");
107
- return appNamespace.get("t")(content, locale);
108
- } catch (error) {
109
- debug(error.message);
97
+ const context = intlayerStorage.getStore();
98
+ if (!context) {
99
+ debug("Using the import { t } from \"hono-intlayer\" outside of a request handled by the `intlayer()` middleware. Use the context instead.");
110
100
  return getTranslation(content, locale ?? internationalization.defaultLocale);
111
101
  }
102
+ return context.t(content, locale);
112
103
  };
113
104
  const getIntlayer = (...args) => {
114
- try {
115
- if (typeof appNamespace === "undefined") throw new Error("Intlayer is not initialized. Add the `app.use(\"*\", intlayer());` middleware before using this function.");
116
- if (typeof appNamespace.get("getIntlayer") !== "function") throw new Error("Using the import { getIntlayer } from \"hono-intlayer\" is not supported in your environment. Use the context instead.");
117
- return appNamespace.get("getIntlayer")(...args);
118
- } catch (error) {
119
- debug(error.message);
105
+ const context = intlayerStorage.getStore();
106
+ if (!context) {
107
+ debug("Using the import { getIntlayer } from \"hono-intlayer\" outside of a request handled by the `intlayer()` middleware. Use the context instead.");
120
108
  return getIntlayer$1(...args);
121
109
  }
110
+ return context.getIntlayer(...args);
122
111
  };
123
112
  const getDictionary = (...args) => {
124
- try {
125
- if (typeof appNamespace === "undefined") throw new Error("Intlayer is not initialized. Add the `app.use(\"*\", intlayer());` middleware before using this function.");
126
- if (typeof appNamespace.get("getDictionary") !== "function") throw new Error("Using the import { getDictionary } from \"hono-intlayer\" is not supported in your environment. Use the context instead.");
127
- return appNamespace.get("getDictionary")(...args);
128
- } catch (error) {
129
- debug(error.message);
113
+ const context = intlayerStorage.getStore();
114
+ if (!context) {
115
+ debug("Using the import { getDictionary } from \"hono-intlayer\" outside of a request handled by the `intlayer()` middleware. Use the context instead.");
130
116
  return getDictionary$1(...args);
131
117
  }
118
+ return context.getDictionary(...args);
132
119
  };
133
120
 
134
121
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["getIntlayerFunction","getDictionaryFunction"],"sources":["../../src/index.ts"],"sourcesContent":["import { getConfiguration } from '@intlayer/config/node';\nimport {\n getDictionary as getDictionaryFunction,\n getIntlayer as getIntlayerFunction,\n getTranslation,\n registerAmbientLocaleResolver,\n} from '@intlayer/core/interpreter';\nimport { localeDetector } from '@intlayer/core/localization';\nimport { getLocaleFromStorageServer } from '@intlayer/core/utils';\nimport { prepareIntlayerServer } from '@intlayer/engine/build';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { StrictModeLocaleMap } from '@intlayer/types/module_augmentation';\nimport { createNamespace } from 'cls-hooked';\nimport type { Context, MiddlewareHandler } from 'hono';\nimport { getCookie } from 'hono/cookie';\n\n// Zero-cost fallback, will be updated with console logger in dev mode\nlet debug: (message: string) => void = () => {};\n\nconst configuration = getConfiguration();\nconst { internationalization } = configuration;\n\nif (process.env['NODE_ENV'] === 'development') {\n debug = (msg: string) => console.debug(msg);\n}\n\n/**\n * Retrieves the locale from storage (cookies, headers).\n */\nconst getStorageLocale = (context: Context): Locale | undefined =>\n getLocaleFromStorageServer({\n getCookie: (name: string) => getCookie(context, name),\n getHeader: (name: string) => context.req.header(name),\n });\n\nconst appNamespace = createNamespace('app');\n\n// Lets a bare `getIntlayer` / `getDictionary` from any Intlayer package resolve\n// to the locale of the request being handled.\nregisterAmbientLocaleResolver(() => appNamespace.get('locale'));\n\nprepareIntlayerServer(configuration, { label: 'hono-intlayer' });\n\nexport const translateFunction =\n (context: Context) =>\n <T extends string>(\n content: StrictModeLocaleMap<T> | string,\n locale?: Locale\n ): T => {\n const currentLocale = context.get('locale') as Locale;\n const defaultLocale = context.get('defaultLocale') as Locale;\n\n const targetLocale = locale ?? currentLocale;\n\n if (typeof content === 'undefined') {\n return '' as unknown as T;\n }\n\n if (typeof content === 'string') {\n return content as unknown as T;\n }\n\n if (\n typeof content?.[\n targetLocale as unknown as keyof StrictModeLocaleMap<T>\n ] === 'undefined'\n ) {\n if (\n typeof content?.[\n defaultLocale as unknown as keyof StrictModeLocaleMap<T>\n ] === 'undefined'\n ) {\n return content as unknown as T;\n } else {\n return getTranslation(content, defaultLocale);\n }\n }\n\n return getTranslation(content, targetLocale);\n };\n\n/**\n * Hono middleware that detects the user's locale and populates context with Intlayer data.\n *\n * It performs:\n * 1. Locale detection from cookies, headers, or default settings.\n * 2. Injects `t`, `getIntlayer`, and `getDictionary` functions into the context.\n * 3. Sets up a `cls-hooked` namespace for accessing these functions anywhere in the request lifecycle.\n *\n * @returns A Hono middleware function.\n *\n * @example\n * ```ts\n * import { Hono } from 'hono';\n * import { intlayer } from 'hono-intlayer';\n *\n * const app = new Hono();\n * app.use('*', intlayer());\n * ```\n */\nexport const intlayer =\n (): MiddlewareHandler =>\n async (context: Context, next: () => Promise<void>) => {\n // Detect if locale is set by intlayer frontend lib in the headers\n const localeFromStorage = getStorageLocale(context);\n\n const negotiatorHeaders: Record<string, string> = context.req.header();\n\n const localeDetected = localeDetector(\n negotiatorHeaders,\n internationalization.locales,\n internationalization.defaultLocale\n );\n\n const locale = localeFromStorage ?? localeDetected;\n\n context.set('locale_storage', localeFromStorage);\n context.set('locale_detected', localeDetected);\n context.set('locale', locale);\n context.set('defaultLocale', internationalization.defaultLocale);\n\n const t = translateFunction(context);\n\n const getIntlayer: typeof getIntlayerFunction = (\n key: Parameters<typeof getIntlayerFunction>[0],\n localeArg = locale as Parameters<typeof getIntlayerFunction>[1],\n ...props: any[]\n ) => getIntlayerFunction(key, localeArg, ...props);\n\n const getDictionary: typeof getDictionaryFunction = (\n key: Parameters<typeof getDictionaryFunction>[0],\n localeArg = locale as Parameters<typeof getDictionaryFunction>[1],\n ...props: any[]\n ) => getDictionaryFunction(key, localeArg, ...props);\n\n context.set('t', t);\n context.set('getIntlayer', getIntlayer);\n context.set('getDictionary', getDictionary);\n\n return new Promise<void>((resolve) => {\n appNamespace.run(async () => {\n appNamespace.set('locale', locale);\n appNamespace.set('t', t);\n appNamespace.set('getIntlayer', getIntlayer);\n appNamespace.set('getDictionary', getDictionary);\n\n await next();\n resolve();\n });\n });\n };\n\n/**\n * Translation function to retrieve content for the current locale.\n *\n * This function works within the request lifecycle managed by the `intlayer` middleware.\n *\n * @param content - A map of locales to content.\n * @param locale - Optional locale override.\n * @returns The translated content.\n *\n * @example\n * ```ts\n * import { t } from 'hono-intlayer';\n *\n * app.get('/', (c) => {\n * const greeting = t({\n * en: 'Hello',\n * fr: 'Bonjour',\n * });\n * return c.text(greeting);\n * });\n * ```\n */\nexport const t = <Content = string>(\n content: StrictModeLocaleMap<Content>,\n locale?: Locale\n): Content => {\n try {\n if (typeof appNamespace === 'undefined') {\n throw new Error(\n 'Intlayer is not initialized. Add the `app.use(\"*\", intlayer());` middleware before using this function.'\n );\n }\n\n if (typeof appNamespace.get('t') !== 'function') {\n throw new Error(\n 'Using the import { t } from \"hono-intlayer\" is not supported in your environment. Use the context instead.'\n );\n }\n\n return appNamespace.get('t')(content, locale);\n } catch (error) {\n debug((error as Error).message);\n\n return getTranslation(\n content,\n locale ?? internationalization.defaultLocale\n );\n }\n};\n\nexport const getIntlayer: typeof getIntlayerFunction = (\n ...args: Parameters<typeof getIntlayerFunction>\n) => {\n try {\n if (typeof appNamespace === 'undefined') {\n throw new Error(\n 'Intlayer is not initialized. Add the `app.use(\"*\", intlayer());` middleware before using this function.'\n );\n }\n\n if (typeof appNamespace.get('getIntlayer') !== 'function') {\n throw new Error(\n 'Using the import { getIntlayer } from \"hono-intlayer\" is not supported in your environment. Use the context instead.'\n );\n }\n\n return appNamespace.get('getIntlayer')(...args);\n } catch (error) {\n debug((error as Error).message);\n\n return getIntlayerFunction(...args);\n }\n};\n\nexport const getDictionary: typeof getDictionaryFunction = (\n ...args: Parameters<typeof getDictionaryFunction>\n) => {\n try {\n if (typeof appNamespace === 'undefined') {\n throw new Error(\n 'Intlayer is not initialized. Add the `app.use(\"*\", intlayer());` middleware before using this function.'\n );\n }\n\n if (typeof appNamespace.get('getDictionary') !== 'function') {\n throw new Error(\n 'Using the import { getDictionary } from \"hono-intlayer\" is not supported in your environment. Use the context instead.'\n );\n }\n\n return appNamespace.get('getDictionary')(...args);\n } catch (error) {\n debug((error as Error).message);\n\n return getDictionaryFunction(...args);\n }\n};\n"],"mappings":";;;;;;;;;AAiBA,IAAI,cAAyC,CAAC;AAE9C,MAAM,gBAAgB,iBAAiB;AACvC,MAAM,EAAE,yBAAyB;AAEjC,6BAAgC,eAC9B,SAAS,QAAgB,QAAQ,MAAM,GAAG;;;;AAM5C,MAAM,oBAAoB,YACxB,2BAA2B;CACzB,YAAY,SAAiB,UAAU,SAAS,IAAI;CACpD,YAAY,SAAiB,QAAQ,IAAI,OAAO,IAAI;AACtD,CAAC;AAEH,MAAM,eAAe,gBAAgB,KAAK;AAI1C,oCAAoC,aAAa,IAAI,QAAQ,CAAC;AAE9D,sBAAsB,eAAe,EAAE,OAAO,gBAAgB,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GACX,QAAQ;EACV,CAAC;CACH,CAAC;AACH;;;;;;;;;;;;;;;;;;;;;;;AAwBF,MAAa,KACX,SACA,WACY;CACZ,IAAI;EACF,IAAI,OAAO,iBAAiB,aAC1B,MAAM,IAAI,MACR,2GACF;EAGF,IAAI,OAAO,aAAa,IAAI,GAAG,MAAM,YACnC,MAAM,IAAI,MACR,8GACF;EAGF,OAAO,aAAa,IAAI,GAAG,CAAC,CAAC,SAAS,MAAM;CAC9C,SAAS,OAAO;EACd,MAAO,MAAgB,OAAO;EAE9B,OAAO,eACL,SACA,UAAU,qBAAqB,aACjC;CACF;AACF;AAEA,MAAa,eACX,GAAG,SACA;CACH,IAAI;EACF,IAAI,OAAO,iBAAiB,aAC1B,MAAM,IAAI,MACR,2GACF;EAGF,IAAI,OAAO,aAAa,IAAI,aAAa,MAAM,YAC7C,MAAM,IAAI,MACR,wHACF;EAGF,OAAO,aAAa,IAAI,aAAa,CAAC,CAAC,GAAG,IAAI;CAChD,SAAS,OAAO;EACd,MAAO,MAAgB,OAAO;EAE9B,OAAOD,cAAoB,GAAG,IAAI;CACpC;AACF;AAEA,MAAa,iBACX,GAAG,SACA;CACH,IAAI;EACF,IAAI,OAAO,iBAAiB,aAC1B,MAAM,IAAI,MACR,2GACF;EAGF,IAAI,OAAO,aAAa,IAAI,eAAe,MAAM,YAC/C,MAAM,IAAI,MACR,0HACF;EAGF,OAAO,aAAa,IAAI,eAAe,CAAC,CAAC,GAAG,IAAI;CAClD,SAAS,OAAO;EACd,MAAO,MAAgB,OAAO;EAE9B,OAAOC,gBAAsB,GAAG,IAAI;CACtC;AACF"}
1
+ {"version":3,"file":"index.mjs","names":["getIntlayerFunction","getDictionaryFunction"],"sources":["../../src/index.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport { internationalization } from '@intlayer/config/built';\nimport { getConfiguration } from '@intlayer/config/node';\nimport {\n getDictionary as getDictionaryFunction,\n getIntlayer as getIntlayerFunction,\n getTranslation,\n registerAmbientLocaleResolver,\n} from '@intlayer/core/interpreter';\nimport { localeDetector } from '@intlayer/core/localization';\nimport { getLocaleFromStorageServer } from '@intlayer/core/utils';\nimport { prepareIntlayerServer } from '@intlayer/engine/build';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { StrictModeLocaleMap } from '@intlayer/types/module_augmentation';\nimport type { Context, MiddlewareHandler } from 'hono';\nimport { getCookie } from 'hono/cookie';\n\n// Zero-cost fallback, will be updated with console logger in dev mode\nlet debug: (message: string) => void = () => {};\n\nif (process.env['NODE_ENV'] === 'development') {\n debug = (msg: string) => console.debug(msg);\n}\n\n/**\n * Retrieves the locale from storage (cookies, headers).\n */\nconst getStorageLocale = (context: Context): Locale | undefined =>\n getLocaleFromStorageServer({\n getCookie: (name: string) => getCookie(context, name),\n getHeader: (name: string) => context.req.header(name),\n });\n\n/**\n * Intlayer helpers bound to the request being handled.\n */\ntype IntlayerRequestContext = {\n locale: Locale;\n t: ReturnType<typeof translateFunction>;\n getIntlayer: typeof getIntlayerFunction;\n getDictionary: typeof getDictionaryFunction;\n};\n\n/**\n * Request-scoped Intlayer context.\n *\n * `AsyncLocalStorage` rather than `cls-hooked`: the latter relies on\n * `async_hooks.createHook`, which Bun does not implement, and is several times\n * slower on Node.\n */\nconst intlayerStorage = new AsyncLocalStorage<IntlayerRequestContext>();\n\n// Lets a bare `getIntlayer` / `getDictionary` from any Intlayer package resolve\n// to the locale of the request being handled.\nregisterAmbientLocaleResolver(() => intlayerStorage.getStore()?.locale);\n\nprepareIntlayerServer(getConfiguration(), { label: 'hono-intlayer' });\n\n/**\n * Builds the translation function bound to the locale stored in the Hono context.\n */\nexport const translateFunction =\n (context: Context) =>\n <T extends string>(\n content: StrictModeLocaleMap<T> | string,\n locale?: Locale\n ): T =>\n typeof content === 'string'\n ? (content as T)\n : getTranslation(\n content,\n locale ?? (context.get('locale') as Locale),\n internationalization.defaultLocale\n );\n\n/**\n * Hono middleware that detects the user's locale and populates context with Intlayer data.\n *\n * It performs:\n * 1. Locale detection from cookies, headers, or default settings.\n * 2. Injects `t`, `getIntlayer`, and `getDictionary` functions into the context.\n * 3. Sets up an `AsyncLocalStorage` context for accessing these functions anywhere in the request lifecycle.\n *\n * @returns A Hono middleware function.\n *\n * @example\n * ```ts\n * import { Hono } from 'hono';\n * import { intlayer } from 'hono-intlayer';\n *\n * const app = new Hono();\n * app.use('*', intlayer());\n * ```\n */\nexport const intlayer =\n (): MiddlewareHandler => (context: Context, next: () => Promise<void>) => {\n // Detect if locale is set by intlayer frontend lib in the headers\n const localeFromStorage = getStorageLocale(context);\n\n const localeDetected = localeDetector(\n { 'accept-language': context.req.header('accept-language') },\n internationalization.locales,\n internationalization.defaultLocale\n );\n\n const locale = localeFromStorage ?? localeDetected;\n\n context.set('locale_storage', localeFromStorage);\n context.set('locale_detected', localeDetected);\n context.set('locale', locale);\n context.set('defaultLocale', internationalization.defaultLocale);\n\n const t = translateFunction(context);\n\n const getIntlayer: typeof getIntlayerFunction = (\n key,\n localeArg = locale as typeof localeArg,\n ...props\n ) => getIntlayerFunction(key, localeArg, ...props);\n\n const getDictionary: typeof getDictionaryFunction = (\n key,\n localeArg = locale as typeof localeArg,\n ...props\n ) => getDictionaryFunction(key, localeArg, ...props);\n\n context.set('t', t);\n context.set('getIntlayer', getIntlayer);\n context.set('getDictionary', getDictionary);\n\n return intlayerStorage.run({ locale, t, getIntlayer, getDictionary }, next);\n };\n\n/**\n * Translation function to retrieve content for the current locale.\n *\n * This function works within the request lifecycle managed by the `intlayer` middleware.\n *\n * @param content - A map of locales to content.\n * @param locale - Optional locale override.\n * @returns The translated content.\n *\n * @example\n * ```ts\n * import { t } from 'hono-intlayer';\n *\n * app.get('/', (c) => {\n * const greeting = t({\n * en: 'Hello',\n * fr: 'Bonjour',\n * });\n * return c.text(greeting);\n * });\n * ```\n */\nexport const t = <Content = string>(\n content: StrictModeLocaleMap<Content>,\n locale?: Locale\n): Content => {\n const context = intlayerStorage.getStore();\n\n if (!context) {\n debug(\n 'Using the import { t } from \"hono-intlayer\" outside of a request handled by the `intlayer()` middleware. Use the context instead.'\n );\n\n return getTranslation(\n content,\n locale ?? internationalization.defaultLocale\n );\n }\n\n return context.t(content as StrictModeLocaleMap<string>, locale) as Content;\n};\n\nexport const getIntlayer: typeof getIntlayerFunction = (\n ...args: Parameters<typeof getIntlayerFunction>\n) => {\n const context = intlayerStorage.getStore();\n\n if (!context) {\n debug(\n 'Using the import { getIntlayer } from \"hono-intlayer\" outside of a request handled by the `intlayer()` middleware. Use the context instead.'\n );\n\n return getIntlayerFunction(...args);\n }\n\n return context.getIntlayer(...args);\n};\n\nexport const getDictionary: typeof getDictionaryFunction = (\n ...args: Parameters<typeof getDictionaryFunction>\n) => {\n const context = intlayerStorage.getStore();\n\n if (!context) {\n debug(\n 'Using the import { getDictionary } from \"hono-intlayer\" outside of a request handled by the `intlayer()` middleware. Use the context instead.'\n );\n\n return getDictionaryFunction(...args);\n }\n\n return context.getDictionary(...args);\n};\n"],"mappings":";;;;;;;;;;AAkBA,IAAI,cAAyC,CAAC;AAE9C,6BAAgC,eAC9B,SAAS,QAAgB,QAAQ,MAAM,GAAG;;;;AAM5C,MAAM,oBAAoB,YACxB,2BAA2B;CACzB,YAAY,SAAiB,UAAU,SAAS,IAAI;CACpD,YAAY,SAAiB,QAAQ,IAAI,OAAO,IAAI;AACtD,CAAC;;;;;;;;AAmBH,MAAM,kBAAkB,IAAI,kBAA0C;AAItE,oCAAoC,gBAAgB,SAAS,CAAC,EAAE,MAAM;AAEtE,sBAAsB,iBAAiB,GAAG,EAAE,OAAO,gBAAgB,CAAC;;;;AAKpE,MAAa,qBACV,aAEC,SACA,WAEA,OAAO,YAAY,WACd,UACD,eACE,SACA,UAAW,QAAQ,IAAI,QAAQ,GAC/B,qBAAqB,aACvB;;;;;;;;;;;;;;;;;;;;AAqBR,MAAa,kBACe,SAAkB,SAA8B;CAExE,MAAM,oBAAoB,iBAAiB,OAAO;CAElD,MAAM,iBAAiB,eACrB,EAA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@@ import { Locale } from "@intlayer/types/allLocales";
3
3
  import { StrictModeLocaleMap } from "@intlayer/types/module_augmentation";
4
4
  import { Context, MiddlewareHandler } from "hono";
5
5
  //#region src/index.d.ts
6
+ /**
7
+ * Builds the translation function bound to the locale stored in the Hono context.
8
+ */
6
9
  export declare const translateFunction: (context: Context) => <T extends string>(content: StrictModeLocaleMap<T> | string, locale?: Locale) => T;
7
10
  /**
8
11
  * Hono middleware that detects the user's locale and populates context with Intlayer data.
@@ -10,7 +13,7 @@ export declare const translateFunction: (context: Context) => <T extends string>
10
13
  * It performs:
11
14
  * 1. Locale detection from cookies, headers, or default settings.
12
15
  * 2. Injects `t`, `getIntlayer`, and `getDictionary` functions into the context.
13
- * 3. Sets up a `cls-hooked` namespace for accessing these functions anywhere in the request lifecycle.
16
+ * 3. Sets up an `AsyncLocalStorage` context for accessing these functions anywhere in the request lifecycle.
14
17
  *
15
18
  * @returns A Hono middleware function.
16
19
  *
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/index.ts"],"mappings":";;;;;qBA2Ca,oBAAiB,SAClB,aACT,kBAAgB,SACN,oBAAoB,aAAW,SAC/B,WACR;;;;;;;;;;;;;;;;;;;;qBAoDQ,gBACP;;;;;;;;;;;;;;;;;;;;;;;qBAyEO,IAAK,kBAAgB,SACvB,oBAAoB,UAAQ,SAC5B,WACR;qBAyBU,oBAAoB;qBAwBpB,sBAAsB"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/index.ts"],"mappings":";;;;;;;;qBA6Da,oBAAiB,SAClB,aACT,kBAAgB,SACN,oBAAoB,aAAW,SAC/B,WACR;;;;;;;;;;;;;;;;;;;;qBA4BQ,gBACP;;;;;;;;;;;;;;;;;;;;;;;qBA4DO,IAAK,kBAAgB,SACvB,oBAAoB,UAAQ,SAC5B,WACR;qBAiBU,oBAAoB;qBAgBpB,sBAAsB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hono-intlayer",
3
- "version": "9.5.12",
3
+ "version": "9.6.0",
4
4
  "private": false,
5
5
  "description": "Manage internationalization i18n in a simple way for hono application.",
6
6
  "keywords": [
@@ -76,14 +76,12 @@
76
76
  "typecheck": "tsc --noEmit --project tsconfig.types.json"
77
77
  },
78
78
  "dependencies": {
79
- "@intlayer/config": "9.5.12",
80
- "@intlayer/core": "9.5.12",
81
- "@intlayer/engine": "9.5.12",
82
- "@intlayer/types": "9.5.12",
83
- "cls-hooked": "4.2.2"
79
+ "@intlayer/config": "9.6.0",
80
+ "@intlayer/core": "9.6.0",
81
+ "@intlayer/engine": "9.6.0",
82
+ "@intlayer/types": "9.6.0"
84
83
  },
85
84
  "devDependencies": {
86
- "@types/cls-hooked": "4.3.9",
87
85
  "@types/node": "^22",
88
86
  "@utils/ts-config": "1.0.4",
89
87
  "@utils/ts-config-types": "1.0.4",
@@ -92,7 +90,7 @@
92
90
  "rimraf": "6.1.3",
93
91
  "tsdown": "0.23.0",
94
92
  "typescript": "7.0.2",
95
- "vitest": "5.0.2"
93
+ "vitest": "5.0.3"
96
94
  },
97
95
  "engines": {
98
96
  "node": ">=14.18"