express-intlayer 9.3.0 → 9.3.1
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/README.md +24 -24
- package/dist/cjs/index.cjs +4 -2
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/esm/index.mjs +4 -2
- package/dist/esm/index.mjs.map +1 -1
- package/package.json +5 -5
package/README.md
CHANGED
|
@@ -47,27 +47,27 @@ With **per-locale content files**, **TypeScript autocompletion**, **tree-shakabl
|
|
|
47
47
|
|
|
48
48
|
## Keys benefits of Intlayer:
|
|
49
49
|
|
|
50
|
-
| Feature | Description
|
|
51
|
-
| --------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
52
|
-
| <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/frameworks.png?raw=true" alt="Feature" width="700"> | **Cross-Frameworks Support**<br><br>Intlayer is compatible with all major frameworks and libraries, including Next.js, React, Vite, Vue.js, Nuxt, Preact, Express, and more.
|
|
53
|
-
| <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/javascript_content_management.jpg?raw=true" alt="Feature" width="700"> | **JavaScript-Powered Content Management**<br><br>Harness the flexibility of JavaScript to define and manage your content efficiently. <br><br> - [Content declaration](https://intlayer.org/doc/concept/content)
|
|
54
|
-
| <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/per_locale_content_declaration_file.png?raw=true" alt="Feature" width="700"> | **Per-Locale Content Declaration File**<br><br>Speed up your development by declaring your content once, before auto generation.<br><br> - [Per-Locale Content Declaration File](https://intlayer.org/doc/concept/per-locale-file)
|
|
55
|
-
| <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/compiler.jpg?raw=true" alt="Feature" width="700"> | **Compiler**<br><br>The Intlayer Compiler extract automatically the content from the components and generate the dictionary files.<br><br> - [Compiler](https://intlayer.org/doc/compiler)
|
|
56
|
-
| <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/autocompletion.png?raw=true" alt="Feature" width="700"> | **Type-Safe Environment**<br><br>Leverage TypeScript to ensure your content definitions and code are error-free, while also benefiting from IDE autocompletion.<br><br> - [TypeScript configuration](https://intlayer.org/doc/environment/vite-and-react#configure-typescript)
|
|
57
|
-
| <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/config_file.png?raw=true" alt="Feature" width="700"> | **Simplified Setup**<br><br>Get up and running quickly with minimal configuration. Adjust settings for internationalization, routing, AI, build, and content handling with ease. <br><br> - [Explore Next.js integration](https://intlayer.org/doc/environment/nextjs)
|
|
58
|
-
| <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/content_retrieval.png?raw=true" alt="Feature" width="700"> | **Simplified Content Retrieval**<br><br>No need to call your `t` function for each piece of content. Retrieve all your content directly using a single hook.<br><br> - [React integration](https://intlayer.org/doc/environment/create-react-app)
|
|
59
|
-
| <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/server_component.png?raw=true" alt="Feature" width="700"> | **Consistent Server Component Implementation**<br><br>Perfectly suited for Next.js server components, use the same implementation for both client and server components, no need to pass your `t` function across each server component. <br><br> - [Server Components](https://intlayer.org/doc/environment/nextjs#step-7-utilize-content-in-your-code)
|
|
60
|
-
| <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/file_tree.png?raw=true" alt="Feature" width="700"> | **Organized Codebase**<br><br>Keep your codebase more organized: 1 component = 1 dictionary in the same folder. Translations close to their respective components, enhance maintainability and clarity. <br><br> - [How Intlayer works](https://intlayer.org/doc/concept/how-works-intlayer)
|
|
61
|
-
| <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/url_routing.png?raw=true" alt="Feature" width="700"> | **Enhanced Routing**<br><br>Full support of app routing, adapting seamlessly to complex application structures, for Next.js, React, Vite, Vue.js, etc.<br><br> - [Explore Next.js integration](https://intlayer.org/doc/environment/nextjs)
|
|
62
|
-
| <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/markdown.png?raw=true" alt="Feature" width="700"> | **Markdown Support**<br><br>Import and interpret, locale files and remote Markdown for multilingual content like privacy policies, documentation, etc. Interpret and make Markdown metadata accessible in your code.<br><br> - [Content files](https://intlayer.org/doc/concept/content/file)
|
|
63
|
-
| <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/visual_editor.png?raw=true" alt="Feature" width="700"> | **Free Visual Editor & CMS**<br><br>A free visual editor and CMS are available for content writers, removing the need for a localization platform. Keep your content synchronized using Git, or externalize it totally or partially with the CMS.<br><br> - [Intlayer Editor](https://intlayer.org/doc/concept/editor) <br> - [Intlayer CMS](https://intlayer.org/doc/concept/cms)
|
|
64
|
-
| <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/bundle.png?raw=true" alt="Feature" width="700"> | **Tree-shakable Content**<br><br>Tree-shakable content, reducing the size of the final bundle. Loads content per component, excluding any unused content from your bundle. Supports lazy loading to enhance app loading efficiency. <br><br> - [App build optimization](https://intlayer.org/doc/concept/how-works-intlayer#app-build-optimization)
|
|
65
|
-
| <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/static_rendering.png?raw=true" alt="Feature" width="700"> | **Static Rendering**<br><br>Doesn't block Static Rendering. <br><br> - [Next.js integration](https://intlayer.org/doc/environment/nextjs)
|
|
66
|
-
| <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/AI_translation.png?raw=true" alt="Feature" width="700"> | **AI-Powered Translation**<br><br>Transform your website into 231 languages with just one click using Intlayer's advanced AI-powered translation tools using your own AI provider / API key. <br><br> - [CI/CD integration](https://intlayer.org/doc/concept/ci-cd) <br> - [Intlayer CLI](https://intlayer.org/doc/concept/cli) <br> - [Auto fill](https://intlayer.org/doc/concept/auto-fill)
|
|
67
|
-
| <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/mcp.png?raw=true" alt="Feature" width="700"> | **MCP Server Integration**<br><br>Provides an MCP (Model Context Protocol) server for IDE automation, enabling seamless content management and i18n workflows directly within your development environment. <br><br> - [MCP Server](https://github.com/aymericzip/intlayer/blob/main/docs/docs/en/mcp_server.md)
|
|
68
|
-
| <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/vscode_extension.png?raw=true" alt="Feature" width="700"> | **VSCode Extension**<br><br>Intlayer provides a VSCode extension to help you manage your content and translations, building your dictionaries, translating your content, and more. <br><br> - [VSCode Extension](https://intlayer.org/doc/vs-code-extension)
|
|
69
|
-
| <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/interoperability.png?raw=true" alt="Feature" width="700"> | **Interoperability**<br><br>Allow interoperability with react-i18next, next-i18next, next-intl, react-intl, vue-i18n. <br><br> - [Intlayer and react-intl](https://intlayer.org/blog/intlayer-with-react-intl) <br> - [Intlayer and next-intl](https://intlayer.org/blog/intlayer-with-next-intl) <br> - [Intlayer and next-i18next](https://intlayer.org/blog/intlayer-with-next-i18next) <br> - [Intlayer and vue-i18n](https://intlayer.org/blog/intlayer-with-vue-i18n) |
|
|
70
|
-
| <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/benchmark.png?raw=true" alt="Feature" width="700"> | **Performances & Benchmark**<br><br>Uses advanced tree-shaking and dynamic loading to boost performances and keep the solution as light as possible. <br><br> - [Performances & Benchmark](https://intlayer.org/doc/benchmark)
|
|
50
|
+
| Feature | Description |
|
|
51
|
+
| --------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
52
|
+
| <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/frameworks.png?raw=true" alt="Feature" width="700"> | **Cross-Frameworks Support**<br><br>Intlayer is compatible with all major frameworks and libraries, including Next.js, React, Vite, Vue.js, Nuxt, Preact, Express, and more. |
|
|
53
|
+
| <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/javascript_content_management.jpg?raw=true" alt="Feature" width="700"> | **JavaScript-Powered Content Management**<br><br>Harness the flexibility of JavaScript to define and manage your content efficiently. <br><br> - [Content declaration](https://intlayer.org/doc/concept/content) |
|
|
54
|
+
| <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/per_locale_content_declaration_file.png?raw=true" alt="Feature" width="700"> | **Per-Locale Content Declaration File**<br><br>Speed up your development by declaring your content once, before auto generation.<br><br> - [Per-Locale Content Declaration File](https://intlayer.org/doc/concept/per-locale-file) |
|
|
55
|
+
| <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/compiler.jpg?raw=true" alt="Feature" width="700"> | **Compiler**<br><br>The Intlayer Compiler extract automatically the content from the components and generate the dictionary files.<br><br> - [Compiler](https://intlayer.org/doc/compiler) |
|
|
56
|
+
| <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/autocompletion.png?raw=true" alt="Feature" width="700"> | **Type-Safe Environment**<br><br>Leverage TypeScript to ensure your content definitions and code are error-free, while also benefiting from IDE autocompletion.<br><br> - [TypeScript configuration](https://intlayer.org/doc/environment/vite-and-react#configure-typescript) |
|
|
57
|
+
| <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/config_file.png?raw=true" alt="Feature" width="700"> | **Simplified Setup**<br><br>Get up and running quickly with minimal configuration. Adjust settings for internationalization, routing, AI, build, and content handling with ease. <br><br> - [Explore Next.js integration](https://intlayer.org/doc/environment/nextjs) |
|
|
58
|
+
| <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/content_retrieval.png?raw=true" alt="Feature" width="700"> | **Simplified Content Retrieval**<br><br>No need to call your `t` function for each piece of content. Retrieve all your content directly using a single hook.<br><br> - [React integration](https://intlayer.org/doc/environment/create-react-app) |
|
|
59
|
+
| <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/server_component.png?raw=true" alt="Feature" width="700"> | **Consistent Server Component Implementation**<br><br>Perfectly suited for Next.js server components, use the same implementation for both client and server components, no need to pass your `t` function across each server component. <br><br> - [Server Components](https://intlayer.org/doc/environment/nextjs#step-7-utilize-content-in-your-code) |
|
|
60
|
+
| <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/file_tree.png?raw=true" alt="Feature" width="700"> | **Organized Codebase**<br><br>Keep your codebase more organized: 1 component = 1 dictionary in the same folder. Translations close to their respective components, enhance maintainability and clarity. <br><br> - [How Intlayer works](https://intlayer.org/doc/concept/how-works-intlayer) |
|
|
61
|
+
| <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/url_routing.png?raw=true" alt="Feature" width="700"> | **Enhanced Routing**<br><br>Full support of app routing, adapting seamlessly to complex application structures, for Next.js, React, Vite, Vue.js, etc.<br><br> - [Explore Next.js integration](https://intlayer.org/doc/environment/nextjs) |
|
|
62
|
+
| <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/markdown.png?raw=true" alt="Feature" width="700"> | **Markdown Support**<br><br>Import and interpret, locale files and remote Markdown for multilingual content like privacy policies, documentation, etc. Interpret and make Markdown metadata accessible in your code.<br><br> - [Content files](https://intlayer.org/doc/concept/content/file) |
|
|
63
|
+
| <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/visual_editor.png?raw=true" alt="Feature" width="700"> | **Free Visual Editor & CMS**<br><br>A free visual editor and CMS are available for content writers, removing the need for a localization platform. Keep your content synchronized using Git, or externalize it totally or partially with the CMS.<br><br> - [Intlayer Editor](https://intlayer.org/doc/concept/editor) <br> - [Intlayer CMS](https://intlayer.org/doc/concept/cms) |
|
|
64
|
+
| <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/bundle.png?raw=true" alt="Feature" width="700"> | **Tree-shakable Content**<br><br>Tree-shakable content, reducing the size of the final bundle. Loads content per component, excluding any unused content from your bundle. Supports lazy loading to enhance app loading efficiency. <br><br> - [App build optimization](https://intlayer.org/doc/concept/how-works-intlayer#app-build-optimization) |
|
|
65
|
+
| <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/static_rendering.png?raw=true" alt="Feature" width="700"> | **Static Rendering**<br><br>Doesn't block Static Rendering. <br><br> - [Next.js integration](https://intlayer.org/doc/environment/nextjs) |
|
|
66
|
+
| <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/AI_translation.png?raw=true" alt="Feature" width="700"> | **AI-Powered Translation**<br><br>Transform your website into 231 languages with just one click using Intlayer's advanced AI-powered translation tools using your own AI provider / API key. <br><br> - [CI/CD integration](https://intlayer.org/doc/concept/ci-cd) <br> - [Intlayer CLI](https://intlayer.org/doc/concept/cli) <br> - [Auto fill](https://intlayer.org/doc/concept/auto-fill) |
|
|
67
|
+
| <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/mcp.png?raw=true" alt="Feature" width="700"> | **MCP Server Integration**<br><br>Provides an MCP (Model Context Protocol) server for IDE automation, enabling seamless content management and i18n workflows directly within your development environment. <br><br> - [MCP Server](https://github.com/aymericzip/intlayer/blob/main/docs/docs/en/mcp_server.md) |
|
|
68
|
+
| <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/vscode_extension.png?raw=true" alt="Feature" width="700"> | **VSCode Extension**<br><br>Intlayer provides a VSCode extension to help you manage your content and translations, building your dictionaries, translating your content, and more. <br><br> - [VSCode Extension](https://intlayer.org/doc/vs-code-extension) |
|
|
69
|
+
| <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/interoperability.png?raw=true" alt="Feature" width="700"> | **Interoperability**<br><br>Allow interoperability with react-i18next, next-i18next, next-intl, react-intl, vue-i18n. <br><br> - [Intlayer and react-intl](https://intlayer.org/blog/intlayer-with-react-intl) <br> - [Intlayer and next-intl](https://intlayer.org/blog/intlayer-with-next-intl) <br> - [Intlayer and next-i18next](https://intlayer.org/blog/intlayer-with-next-i18next) <br> - [Intlayer and vue-i18n](https://intlayer.org/blog/intlayer-with-vue-i18n) <br> - [Intlayer compat adapters](https://intlayer.org/doc/compatibility) |
|
|
70
|
+
| <img src="https://github.com/aymericzip/intlayer/blob/main/docs/assets/benchmark.png?raw=true" alt="Feature" width="700"> | **Performances & Benchmark**<br><br>Uses advanced tree-shaking and dynamic loading to boost performances and keep the solution as light as possible. <br><br> - [Performances & Benchmark](https://intlayer.org/doc/benchmark) |
|
|
71
71
|
|
|
72
72
|
---
|
|
73
73
|
|
|
@@ -162,7 +162,7 @@ Explore our comprehensive documentation to get started with Intlayer and learn h
|
|
|
162
162
|
<li><a href="https://intlayer.org/doc/concept/cms" rel=''>Intlayer CMS</a></li>
|
|
163
163
|
<li><a href="https://intlayer.org/doc/concept/content" rel=''>Dictionary</a>
|
|
164
164
|
<ul>
|
|
165
|
-
<li><a href="https://intlayer.org/doc/concept/
|
|
165
|
+
<li><a href="https://intlayer.org/doc/concept/per-locale-file" rel=''>Per-Locale Content Declaration File</a></li>
|
|
166
166
|
<li><a href="https://intlayer.org/doc/concept/content/translation" rel=''>Translation</a></li>
|
|
167
167
|
<li><a href="https://intlayer.org/doc/concept/content/enumeration" rel=''>Enumeration</a></li>
|
|
168
168
|
<li><a href="https://intlayer.org/doc/concept/content/condition" rel=''>Condition</a></li>
|
|
@@ -183,7 +183,7 @@ Explore our comprehensive documentation to get started with Intlayer and learn h
|
|
|
183
183
|
<ul>
|
|
184
184
|
<li><a href="https://intlayer.org/doc/environment/nextjs/15" rel=''>Next.js 15</a></li>
|
|
185
185
|
<li><a href="https://intlayer.org/doc/environment/nextjs/14" rel=''>Next.js 14 (App Router)</a></li>
|
|
186
|
-
<li><a href="https://intlayer.org/doc/environment/nextjs/next-with-
|
|
186
|
+
<li><a href="https://intlayer.org/doc/environment/nextjs/next-with-page-router" rel=''>Next.js Page Router</a></li>
|
|
187
187
|
<li><a href="https://intlayer.org/doc/environment/nextjs/compiler" rel=''>Next.js using Compiler</a></li>
|
|
188
188
|
</ul>
|
|
189
189
|
</li>
|
|
@@ -212,7 +212,7 @@ Explore our comprehensive documentation to get started with Intlayer and learn h
|
|
|
212
212
|
<li><a href="https://intlayer.org/doc/environment/sveltekit" rel=''>SvelteKit</a></li>
|
|
213
213
|
<li><a href="https://intlayer.org/doc/environment/vite-and-preact" rel=''>Vite + Preact</a></li>
|
|
214
214
|
<li><a href="https://intlayer.org/doc/environment/vite-and-vue" rel=''>Vite + Vue</a></li>
|
|
215
|
-
<li><a href="https://intlayer.org/doc/environment/
|
|
215
|
+
<li><a href="https://intlayer.org/doc/environment/nuxt-and-vue" rel=''>Vite + Nuxt</a></li>
|
|
216
216
|
<li><a href="https://intlayer.org/doc/environment/vite-and-solid" rel=''>Vite + Solid</a></li>
|
|
217
217
|
<li><a href="https://intlayer.org/doc/environment/angular" rel=''>Angular</a></li>
|
|
218
218
|
<li>
|
package/dist/cjs/index.cjs
CHANGED
|
@@ -25,8 +25,10 @@ const translateFunction = (_req, res, _next) => (content, locale) => {
|
|
|
25
25
|
const targetLocale = locale ?? currentLocale;
|
|
26
26
|
if (typeof content === "undefined") return "";
|
|
27
27
|
if (typeof content === "string") return content;
|
|
28
|
-
if (typeof content?.[targetLocale] === "undefined")
|
|
29
|
-
|
|
28
|
+
if (typeof content?.[targetLocale] === "undefined") {
|
|
29
|
+
if (typeof content?.[defaultLocale] === "undefined") return content;
|
|
30
|
+
else return (0, _intlayer_core_interpreter.getTranslation)(content, defaultLocale);
|
|
31
|
+
}
|
|
30
32
|
return (0, _intlayer_core_interpreter.getTranslation)(content, targetLocale);
|
|
31
33
|
};
|
|
32
34
|
/**
|
package/dist/cjs/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":[],"sources":["../../src/index.ts"],"sourcesContent":["import { getConfiguration } from '@intlayer/config/node';\nimport {\n getDictionary as getDictionaryFunction,\n getIntlayer as getIntlayerFunction,\n getTranslation,\n} from '@intlayer/core/interpreter';\nimport { localeDetector } from '@intlayer/core/localization';\nimport { getLocaleFromStorageServer } from '@intlayer/core/utils';\nimport { prepareIntlayer } 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 { NextFunction, Request, RequestHandler, Response } from 'express';\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, localStorage, sessionStorage).\n */\nconst getStorageLocale = (req: Request): Locale | undefined =>\n getLocaleFromStorageServer({\n getCookie: (name: string) => req.cookies?.[name],\n getHeader: (name: string) => req.headers?.[name] as string | undefined,\n });\n\nconst appNamespace = createNamespace('app');\n\nprepareIntlayer(configuration);\n\nexport const translateFunction =\n (_req: Request, res: Response, _next?: NextFunction) =>\n <T extends string>(\n content: StrictModeLocaleMap<T> | string,\n locale?: Locale\n ): T => {\n const { locale: currentLocale, defaultLocale } = res.locals as {\n locale: Locale;\n defaultLocale: Locale;\n };\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 * Express middleware that detects the user's locale and populates `res.locals` 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 `res.locals`.\n * 3. Sets up a `cls-hooked` namespace for accessing these functions anywhere in the request lifecycle.\n *\n * @returns An Express middleware function.\n *\n * @example\n * ```ts\n * import express from 'express';\n * import { intlayer } from 'express-intlayer';\n *\n * const app = express();\n * app.use(intlayer());\n * ```\n */\nexport const intlayer = (): RequestHandler => async (req, res, next) => {\n // Detect if locale is set by intlayer frontend lib in the headers\n const localeFromStorage = getStorageLocale(req);\n // Interpret browser locale\n\n const negotiatorHeaders: Record<string, string> = {};\n\n // // Check if req.headers exists and is an object\n if (req && typeof req.headers === 'object') {\n // Copy all headers from the request to negotiatorHeaders\n for (const key in req.headers) {\n if (typeof req.headers[key] === 'string') {\n negotiatorHeaders[key] = req.headers[key];\n }\n }\n }\n\n const localeDetected = localeDetector(\n negotiatorHeaders,\n internationalization.locales,\n internationalization.defaultLocale\n );\n\n res.locals.locale_storage = localeFromStorage;\n res.locals.locale_detected = localeDetected;\n res.locals.locale = localeFromStorage ?? localeDetected;\n res.locals.defaultLocale = internationalization.defaultLocale;\n\n const t = translateFunction(req, res, next);\n\n const getIntlayer: typeof getIntlayerFunction = (\n key,\n localeArg = localeDetected as Parameters<typeof getIntlayerFunction>[1],\n ...props\n ) => getIntlayerFunction(key, localeArg, ...props);\n\n const getDictionary: typeof getDictionaryFunction = (\n key,\n localeArg = localeDetected as Parameters<typeof getDictionaryFunction>[1],\n ...props\n ) => getDictionaryFunction(key, localeArg, ...props);\n\n res.locals.t = t;\n res.locals.getIntlayer = getIntlayer;\n res.locals.getDictionary = getDictionary;\n\n appNamespace.run(() => {\n appNamespace.set('t', t);\n appNamespace.set('getIntlayer', getIntlayer);\n appNamespace.set('getDictionary', getDictionary);\n\n next();\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 'express-intlayer';\n *\n * app.get('/', (req, res) => {\n * const greeting = t({\n * en: 'Hello',\n * fr: 'Bonjour',\n * });\n * res.send(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 \"express-intlayer\" is not supported in your environment. Use the res.locals.t syntax 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 = (...args) => {\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 { t } from \"express-intlayer\" is not supported in your environment. Use the res.locals.t syntax 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 = (...args) => {\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 { t } from \"express-intlayer\" is not supported in your environment. Use the res.locals.t syntax 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":";;;;;;;;;AAeA,IAAI,cAAyC,CAAC;AAE9C,MAAM,
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["getConfiguration","getLocaleFromStorageServer","createNamespace","prepareIntlayer","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} from '@intlayer/core/interpreter';\nimport { localeDetector } from '@intlayer/core/localization';\nimport { getLocaleFromStorageServer } from '@intlayer/core/utils';\nimport { prepareIntlayer } 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 { NextFunction, Request, RequestHandler, Response } from 'express';\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, localStorage, sessionStorage).\n */\nconst getStorageLocale = (req: Request): Locale | undefined =>\n getLocaleFromStorageServer({\n getCookie: (name: string) => req.cookies?.[name],\n getHeader: (name: string) => req.headers?.[name] as string | undefined,\n });\n\nconst appNamespace = createNamespace('app');\n\nprepareIntlayer(configuration);\n\nexport const translateFunction =\n (_req: Request, res: Response, _next?: NextFunction) =>\n <T extends string>(\n content: StrictModeLocaleMap<T> | string,\n locale?: Locale\n ): T => {\n const { locale: currentLocale, defaultLocale } = res.locals as {\n locale: Locale;\n defaultLocale: Locale;\n };\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 * Express middleware that detects the user's locale and populates `res.locals` 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 `res.locals`.\n * 3. Sets up a `cls-hooked` namespace for accessing these functions anywhere in the request lifecycle.\n *\n * @returns An Express middleware function.\n *\n * @example\n * ```ts\n * import express from 'express';\n * import { intlayer } from 'express-intlayer';\n *\n * const app = express();\n * app.use(intlayer());\n * ```\n */\nexport const intlayer = (): RequestHandler => async (req, res, next) => {\n // Detect if locale is set by intlayer frontend lib in the headers\n const localeFromStorage = getStorageLocale(req);\n // Interpret browser locale\n\n const negotiatorHeaders: Record<string, string> = {};\n\n // // Check if req.headers exists and is an object\n if (req && typeof req.headers === 'object') {\n // Copy all headers from the request to negotiatorHeaders\n for (const key in req.headers) {\n if (typeof req.headers[key] === 'string') {\n negotiatorHeaders[key] = req.headers[key];\n }\n }\n }\n\n const localeDetected = localeDetector(\n negotiatorHeaders,\n internationalization.locales,\n internationalization.defaultLocale\n );\n\n res.locals.locale_storage = localeFromStorage;\n res.locals.locale_detected = localeDetected;\n res.locals.locale = localeFromStorage ?? localeDetected;\n res.locals.defaultLocale = internationalization.defaultLocale;\n\n const t = translateFunction(req, res, next);\n\n const getIntlayer: typeof getIntlayerFunction = (\n key,\n localeArg = localeDetected as Parameters<typeof getIntlayerFunction>[1],\n ...props\n ) => getIntlayerFunction(key, localeArg, ...props);\n\n const getDictionary: typeof getDictionaryFunction = (\n key,\n localeArg = localeDetected as Parameters<typeof getDictionaryFunction>[1],\n ...props\n ) => getDictionaryFunction(key, localeArg, ...props);\n\n res.locals.t = t;\n res.locals.getIntlayer = getIntlayer;\n res.locals.getDictionary = getDictionary;\n\n appNamespace.run(() => {\n appNamespace.set('t', t);\n appNamespace.set('getIntlayer', getIntlayer);\n appNamespace.set('getDictionary', getDictionary);\n\n next();\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 'express-intlayer';\n *\n * app.get('/', (req, res) => {\n * const greeting = t({\n * en: 'Hello',\n * fr: 'Bonjour',\n * });\n * res.send(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 \"express-intlayer\" is not supported in your environment. Use the res.locals.t syntax 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 = (...args) => {\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 { t } from \"express-intlayer\" is not supported in your environment. Use the res.locals.t syntax 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 = (...args) => {\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 { t } from \"express-intlayer\" is not supported in your environment. Use the res.locals.t syntax 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":"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"}
|
package/dist/esm/index.mjs
CHANGED
|
@@ -24,8 +24,10 @@ const translateFunction = (_req, res, _next) => (content, locale) => {
|
|
|
24
24
|
const targetLocale = locale ?? currentLocale;
|
|
25
25
|
if (typeof content === "undefined") return "";
|
|
26
26
|
if (typeof content === "string") return content;
|
|
27
|
-
if (typeof content?.[targetLocale] === "undefined")
|
|
28
|
-
|
|
27
|
+
if (typeof content?.[targetLocale] === "undefined") {
|
|
28
|
+
if (typeof content?.[defaultLocale] === "undefined") return content;
|
|
29
|
+
else return getTranslation(content, defaultLocale);
|
|
30
|
+
}
|
|
29
31
|
return getTranslation(content, targetLocale);
|
|
30
32
|
};
|
|
31
33
|
/**
|
package/dist/esm/index.mjs.map
CHANGED
|
@@ -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} from '@intlayer/core/interpreter';\nimport { localeDetector } from '@intlayer/core/localization';\nimport { getLocaleFromStorageServer } from '@intlayer/core/utils';\nimport { prepareIntlayer } 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 { NextFunction, Request, RequestHandler, Response } from 'express';\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, localStorage, sessionStorage).\n */\nconst getStorageLocale = (req: Request): Locale | undefined =>\n getLocaleFromStorageServer({\n getCookie: (name: string) => req.cookies?.[name],\n getHeader: (name: string) => req.headers?.[name] as string | undefined,\n });\n\nconst appNamespace = createNamespace('app');\n\nprepareIntlayer(configuration);\n\nexport const translateFunction =\n (_req: Request, res: Response, _next?: NextFunction) =>\n <T extends string>(\n content: StrictModeLocaleMap<T> | string,\n locale?: Locale\n ): T => {\n const { locale: currentLocale, defaultLocale } = res.locals as {\n locale: Locale;\n defaultLocale: Locale;\n };\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 * Express middleware that detects the user's locale and populates `res.locals` 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 `res.locals`.\n * 3. Sets up a `cls-hooked` namespace for accessing these functions anywhere in the request lifecycle.\n *\n * @returns An Express middleware function.\n *\n * @example\n * ```ts\n * import express from 'express';\n * import { intlayer } from 'express-intlayer';\n *\n * const app = express();\n * app.use(intlayer());\n * ```\n */\nexport const intlayer = (): RequestHandler => async (req, res, next) => {\n // Detect if locale is set by intlayer frontend lib in the headers\n const localeFromStorage = getStorageLocale(req);\n // Interpret browser locale\n\n const negotiatorHeaders: Record<string, string> = {};\n\n // // Check if req.headers exists and is an object\n if (req && typeof req.headers === 'object') {\n // Copy all headers from the request to negotiatorHeaders\n for (const key in req.headers) {\n if (typeof req.headers[key] === 'string') {\n negotiatorHeaders[key] = req.headers[key];\n }\n }\n }\n\n const localeDetected = localeDetector(\n negotiatorHeaders,\n internationalization.locales,\n internationalization.defaultLocale\n );\n\n res.locals.locale_storage = localeFromStorage;\n res.locals.locale_detected = localeDetected;\n res.locals.locale = localeFromStorage ?? localeDetected;\n res.locals.defaultLocale = internationalization.defaultLocale;\n\n const t = translateFunction(req, res, next);\n\n const getIntlayer: typeof getIntlayerFunction = (\n key,\n localeArg = localeDetected as Parameters<typeof getIntlayerFunction>[1],\n ...props\n ) => getIntlayerFunction(key, localeArg, ...props);\n\n const getDictionary: typeof getDictionaryFunction = (\n key,\n localeArg = localeDetected as Parameters<typeof getDictionaryFunction>[1],\n ...props\n ) => getDictionaryFunction(key, localeArg, ...props);\n\n res.locals.t = t;\n res.locals.getIntlayer = getIntlayer;\n res.locals.getDictionary = getDictionary;\n\n appNamespace.run(() => {\n appNamespace.set('t', t);\n appNamespace.set('getIntlayer', getIntlayer);\n appNamespace.set('getDictionary', getDictionary);\n\n next();\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 'express-intlayer';\n *\n * app.get('/', (req, res) => {\n * const greeting = t({\n * en: 'Hello',\n * fr: 'Bonjour',\n * });\n * res.send(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 \"express-intlayer\" is not supported in your environment. Use the res.locals.t syntax 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 = (...args) => {\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 { t } from \"express-intlayer\" is not supported in your environment. Use the res.locals.t syntax 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 = (...args) => {\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 { t } from \"express-intlayer\" is not supported in your environment. Use the res.locals.t syntax 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":";;;;;;;;AAeA,IAAI,cAAyC,CAAC;AAE9C,MAAM,gBAAgB,iBAAiB;AACvC,MAAM,EAAE,yBAAyB;AAG/B,SAAS,QAAgB,QAAQ,MAAM,GAAG;;;;AAM5C,MAAM,oBAAoB,QACxB,2BAA2B;CACzB,YAAY,SAAiB,IAAI,UAAU;CAC3C,YAAY,SAAiB,IAAI,UAAU;AAC7C,CAAC;AAEH,MAAM,eAAe,gBAAgB,KAAK;AAE1C,gBAAgB,aAAa;AAE7B,MAAa,qBACV,MAAe,KAAe,WAE7B,SACA,WACM;CACN,MAAM,EAAE,QAAQ,eAAe,kBAAkB,IAAI;CAKrD,MAAM,eAAe,UAAU;CAE/B,IAAI,OAAO,YAAY,aACrB,OAAO;CAGT,IAAI,OAAO,YAAY,UACrB,OAAO;CAGT,IACE,OAAO,UACL,kBACI,
|
|
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} from '@intlayer/core/interpreter';\nimport { localeDetector } from '@intlayer/core/localization';\nimport { getLocaleFromStorageServer } from '@intlayer/core/utils';\nimport { prepareIntlayer } 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 { NextFunction, Request, RequestHandler, Response } from 'express';\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, localStorage, sessionStorage).\n */\nconst getStorageLocale = (req: Request): Locale | undefined =>\n getLocaleFromStorageServer({\n getCookie: (name: string) => req.cookies?.[name],\n getHeader: (name: string) => req.headers?.[name] as string | undefined,\n });\n\nconst appNamespace = createNamespace('app');\n\nprepareIntlayer(configuration);\n\nexport const translateFunction =\n (_req: Request, res: Response, _next?: NextFunction) =>\n <T extends string>(\n content: StrictModeLocaleMap<T> | string,\n locale?: Locale\n ): T => {\n const { locale: currentLocale, defaultLocale } = res.locals as {\n locale: Locale;\n defaultLocale: Locale;\n };\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 * Express middleware that detects the user's locale and populates `res.locals` 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 `res.locals`.\n * 3. Sets up a `cls-hooked` namespace for accessing these functions anywhere in the request lifecycle.\n *\n * @returns An Express middleware function.\n *\n * @example\n * ```ts\n * import express from 'express';\n * import { intlayer } from 'express-intlayer';\n *\n * const app = express();\n * app.use(intlayer());\n * ```\n */\nexport const intlayer = (): RequestHandler => async (req, res, next) => {\n // Detect if locale is set by intlayer frontend lib in the headers\n const localeFromStorage = getStorageLocale(req);\n // Interpret browser locale\n\n const negotiatorHeaders: Record<string, string> = {};\n\n // // Check if req.headers exists and is an object\n if (req && typeof req.headers === 'object') {\n // Copy all headers from the request to negotiatorHeaders\n for (const key in req.headers) {\n if (typeof req.headers[key] === 'string') {\n negotiatorHeaders[key] = req.headers[key];\n }\n }\n }\n\n const localeDetected = localeDetector(\n negotiatorHeaders,\n internationalization.locales,\n internationalization.defaultLocale\n );\n\n res.locals.locale_storage = localeFromStorage;\n res.locals.locale_detected = localeDetected;\n res.locals.locale = localeFromStorage ?? localeDetected;\n res.locals.defaultLocale = internationalization.defaultLocale;\n\n const t = translateFunction(req, res, next);\n\n const getIntlayer: typeof getIntlayerFunction = (\n key,\n localeArg = localeDetected as Parameters<typeof getIntlayerFunction>[1],\n ...props\n ) => getIntlayerFunction(key, localeArg, ...props);\n\n const getDictionary: typeof getDictionaryFunction = (\n key,\n localeArg = localeDetected as Parameters<typeof getDictionaryFunction>[1],\n ...props\n ) => getDictionaryFunction(key, localeArg, ...props);\n\n res.locals.t = t;\n res.locals.getIntlayer = getIntlayer;\n res.locals.getDictionary = getDictionary;\n\n appNamespace.run(() => {\n appNamespace.set('t', t);\n appNamespace.set('getIntlayer', getIntlayer);\n appNamespace.set('getDictionary', getDictionary);\n\n next();\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 'express-intlayer';\n *\n * app.get('/', (req, res) => {\n * const greeting = t({\n * en: 'Hello',\n * fr: 'Bonjour',\n * });\n * res.send(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 \"express-intlayer\" is not supported in your environment. Use the res.locals.t syntax 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 = (...args) => {\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 { t } from \"express-intlayer\" is not supported in your environment. Use the res.locals.t syntax 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 = (...args) => {\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 { t } from \"express-intlayer\" is not supported in your environment. Use the res.locals.t syntax 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":";;;;;;;;AAeA,IAAI,cAAyC,CAAC;AAE9C,MAAM,gBAAgB,iBAAiB;AACvC,MAAM,EAAE,yBAAyB;AAG/B,SAAS,QAAgB,QAAQ,MAAM,GAAG;;;;AAM5C,MAAM,oBAAoB,QACxB,2BAA2B;CACzB,YAAY,SAAiB,IAAI,UAAU;CAC3C,YAAY,SAAiB,IAAI,UAAU;AAC7C,CAAC;AAEH,MAAM,eAAe,gBAAgB,KAAK;AAE1C,gBAAgB,aAAa;AAE7B,MAAa,qBACV,MAAe,KAAe,WAE7B,SACA,WACM;CACN,MAAM,EAAE,QAAQ,eAAe,kBAAkB,IAAI;CAKrD,MAAM,eAAe,UAAU;CAE/B,IAAI,OAAO,YAAY,aACrB,OAAO;CAGT,IAAI,OAAO,YAAY,UACrB,OAAO;CAGT,IACE,OAAO,UACL,kBACI,aACN;EACA,IACE,OAAO,UACL,mBACI,aAEN,OAAO;OAEP,OAAO,eAAe,SAAS,aAAa;CAEhD;CAEA,OAAO,eAAe,SAAS,YAAY;AAC7C;;;;;;;;;;;;;;;;;;;;AAqBF,MAAa,iBAAiC,OAAO,KAAK,KAAK,SAAS;CAEtE,MAAM,oBAAoB,iBAAiB,GAAG;CAG9C,MAAM,oBAA4C,CAAC;CAGnD,IAAI,OAAO,OAAO,IAAI,YAAY,UAEhC;OAAK,MAAM,OAAO,IAAI,SACpB,IAAI,OAAO,IAAI,QAAQ,SAAS,UAC9B,kBAAkB,OAAO,IAAI,QAAQ;CAEzC;CAGF,MAAM,iBAAiB,eACrB,mBACA,qBAAqB,SACrB,qBAAqB,aACvB;CAEA,IAAI,OAAO,iBAAiB;CAC5B,IAAI,OAAO,kBAAkB;CAC7B,IAAI,OAAO,SAAS,qBAAqB;CACzC,IAAI,OAAO,gBAAgB,qBAAqB;CAEhD,MAAM,IAAI,kBAAkB,KAAK,KAAK,IAAI;CAE1C,MAAM,eACJ,KACA,YAAY,gBACZ,GAAG,UACAA,cAAoB,KAAK,WAAW,GAAG,KAAK;CAEjD,MAAM,iBACJ,KACA,YAAY,gBACZ,GAAG,UACAC,gBAAsB,KAAK,WAAW,GAAG,KAAK;CAEnD,IAAI,OAAO,IAAI;CACf,IAAI,OAAO,cAAc;CACzB,IAAI,OAAO,gBAAgB;CAE3B,aAAa,UAAU;EACrB,aAAa,IAAI,KAAK,CAAC;EACvB,aAAa,IAAI,eAAe,WAAW;EAC3C,aAAa,IAAI,iBAAiB,aAAa;EAE/C,KAAK;CACP,CAAC;AACH;;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAa,KACX,SACA,WACY;CACZ,IAAI;EACF,IAAI,OAAO,iBAAiB,aAC1B,MAAM,IAAI,MACR,oGACF;EAGF,IAAI,OAAO,aAAa,IAAI,GAAG,MAAM,YACnC,MAAM,IAAI,MACR,6HACF;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,eAA2C,GAAG,SAAS;CAClE,IAAI;EACF,IAAI,OAAO,iBAAiB,aAC1B,MAAM,IAAI,MACR,oGACF;EAGF,IAAI,OAAO,aAAa,IAAI,aAAa,MAAM,YAC7C,MAAM,IAAI,MACR,6HACF;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,iBAA+C,GAAG,SAAS;CACtE,IAAI;EACF,IAAI,OAAO,iBAAiB,aAC1B,MAAM,IAAI,MACR,oGACF;EAGF,IAAI,OAAO,aAAa,IAAI,eAAe,MAAM,YAC/C,MAAM,IAAI,MACR,6HACF;EAGF,OAAO,aAAa,IAAI,eAAe,CAAC,CAAC,GAAG,IAAI;CAClD,SAAS,OAAO;EACd,MAAO,MAAgB,OAAO;EAE9B,OAAOC,gBAAsB,GAAG,IAAI;CACtC;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "express-intlayer",
|
|
3
|
-
"version": "9.3.
|
|
3
|
+
"version": "9.3.1",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Manage internationalization i18n in a simple way for express application.",
|
|
6
6
|
"keywords": [
|
|
@@ -75,10 +75,10 @@
|
|
|
75
75
|
"typecheck": "tsc --noEmit --project tsconfig.types.json"
|
|
76
76
|
},
|
|
77
77
|
"dependencies": {
|
|
78
|
-
"@intlayer/config": "9.3.
|
|
79
|
-
"@intlayer/core": "9.3.
|
|
80
|
-
"@intlayer/engine": "9.3.
|
|
81
|
-
"@intlayer/types": "9.3.
|
|
78
|
+
"@intlayer/config": "9.3.1",
|
|
79
|
+
"@intlayer/core": "9.3.1",
|
|
80
|
+
"@intlayer/engine": "9.3.1",
|
|
81
|
+
"@intlayer/types": "9.3.1",
|
|
82
82
|
"cls-hooked": "4.2.2"
|
|
83
83
|
},
|
|
84
84
|
"devDependencies": {
|