preact-intlayer 5.3.11

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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright
52
+ owner or by an individual or Legal Entity authorized to submit on
53
+ behalf of the copyright owner. For the purposes of this definition,
54
+ "submitted" means any form of electronic, verbal, or written
55
+ communication sent to the Licensor or its representatives, including
56
+ but not limited to communication on electronic mailing lists, source
57
+ code control systems, and issue tracking systems that are managed by,
58
+ or on behalf of, the Licensor for the purpose of discussing and improving
59
+ the Work, but excluding communication that is conspicuously marked or
60
+ otherwise designated in writing by the copyright owner as "Not a
61
+ Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2024 Aymeric PINEAU
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,125 @@
1
+ <div align="center">
2
+ <a href="https://intlayer.org">
3
+ <img src="https://raw.githubusercontent.com/aymericzip/intlayer/572ae9c9acafb74307b81530c1931a8e98990aef/docs/assets/logo.png" width="500" alt="intlayer" />
4
+ </a>
5
+ </div>
6
+
7
+ <div align="center">
8
+ <a href="https://www.npmjs.com/package/preact-intlayer">
9
+ <img alt="npm" src="https://img.shields.io/npm/v/preact-intlayer.svg?labelColor=49516F&color=8994BC" />
10
+ </a>
11
+ <a href="https://npmjs.org/package/preact-intlayer">
12
+ <img alt="downloads" src="https://badgen.net/npm/dm/preact-intlayer?labelColor=49516F&color=8994BC" />
13
+ </a>
14
+ <a href="https://npmjs.org/package/preact-intlayer">
15
+ <img alt="types included" src="https://badgen.net/npm/types/preact-intlayer?labelColor=49516F&color=8994BC"
16
+ />
17
+ </div>
18
+
19
+ > This package is in development.
20
+
21
+ # preact-intlayer: Internationalize (i18n) an Preact application
22
+
23
+ **Intlayer** is a suite of packages designed specifically for JavaScript developers. It is compatible with frameworks like Preact, Svelte, and Express.js.
24
+
25
+ **The `preact-intlayer` package** allows you to internationalize your Preact application. It provides context providers and hooks for Preact internationalization.
26
+
27
+ ## Why Internationalize Your Preact Application?
28
+
29
+ Internationalizing your Preact application is essential for serving a global audience effectively. It allows your application to deliver content and messages in the preferred language of each user. This capability enhances user experience and broadens your application's reach by making it more accessible and relevant to people from different linguistic backgrounds.
30
+
31
+ ## Why to integrate Intlayer?
32
+
33
+ - **JavaScript-Powered Content Management**: Harness the flexibility of JavaScript to define and manage your content efficiently.
34
+ - **Type-Safe Environment**: Leverage TypeScript to ensure all your content definitions are precise and error-free.
35
+ - **Integrated Content Files**: Keep your translations close to their respective components, enhancing maintainability and clarity.
36
+
37
+ ## Installation
38
+
39
+ Install the necessary package using your preferred package manager:
40
+
41
+ ```bash packageManager="npm"
42
+ npm install preact-intlayer
43
+ ```
44
+
45
+ ```bash packageManager="yarn"
46
+ yarn add preact-intlayer
47
+ ```
48
+
49
+ ```bash packageManager="pnpm"
50
+ pnpm add preact-intlayer
51
+ ```
52
+
53
+ ## Example of usage
54
+
55
+ With Intlayer, you can declare your content in a structured way anywhere in your codebase.
56
+
57
+ By default, Intlayer scans for files with the extension `.content.{json,ts,tsx,js,jsx,mjs,mjx,cjs,cjx}`.
58
+
59
+ > You can modify the default extension by setting the `contentDir` property in the [configuration file](https://intlayer.org/doc/concept/configuration).
60
+
61
+ ```bash codeFormat="typescript"
62
+ .
63
+ ├── intlayer.config.ts
64
+ └── src
65
+ └── components
66
+ ├── Component1
67
+ │   ├── index.content.ts
68
+ │   └── index.preact
69
+ └── Component2
70
+ ├── index.content.ts
71
+ └── index.preact
72
+ ```
73
+
74
+ ### Declare your content
75
+
76
+ `preact-intlayer` is made to work with the [`intlayer` package](https://github.com/aymericzip/intlayer/blob/main/docs/en/packages/intlayer/index.md).`intlayer` is a package that allows you to declare your content anywhere in your code. It converts multilingual content declarations into structured dictionaries that integrate seamlessly into your application.
77
+
78
+ Here’s an example of content declaration:
79
+
80
+ ```tsx filePath="src/Component1/index.content.ts" codeFormat="typescript"
81
+ import { t, type Dictionary } from "intlayer";
82
+
83
+ const component1Content = {
84
+ key: "component-1",
85
+ content: {
86
+ myTranslatedContent: t({
87
+ en: "Hello World",
88
+ fr: "Bonjour le monde",
89
+ es: "Hola Mundo",
90
+ }),
91
+ numberOfCar: enu({
92
+ "<-1": "Less than minus one car",
93
+ "-1": "Minus one car",
94
+ "0": "No cars",
95
+ "1": "One car",
96
+ ">5": "Some cars",
97
+ ">19": "Many cars",
98
+ }),
99
+ },
100
+ } satisfies Dictionary;
101
+
102
+ export default component1Content;
103
+ ```
104
+
105
+ ### Utilize Content in Your Code
106
+
107
+ ...
108
+
109
+ ## Mastering the internationalization of your Preact application
110
+
111
+ Intlayer provides a lot of features to help you internationalize your Preact application.
112
+
113
+ **To learn more about these features, refer to the [Preact Internationalization (i18n) with Intlayer and Vite and Preact](https://github.com/aymericzip/intlayer/blob/main/docs/en/intlayer_with_vite+react.md) guide for Vite and Preact Application, or the [Preact Internationalization (i18n) with Intlayer and Preact (CRA)](https://intlayer.org/doc/environment/create-react-app) guide for Preact Create App.**
114
+
115
+ ## Functions provided by `preact-intlayer` package
116
+
117
+ The `preact-intlayer` package also provides some functions to help you to internationalize your application.
118
+
119
+ ## Read about Intlayer
120
+
121
+ - [Intlayer Website](https://intlayer.org)
122
+ - [Intlayer Documentation](https://intlayer.org/docs)
123
+ - [Intlayer GitHub](https://github.com/aymericzip/intlayer)
124
+
125
+ - [Ask your questions to our smart documentation](https://intlayer.org/docs/chat)
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __copyProps = (to, from, except, desc) => {
7
+ if (from && typeof from === "object" || typeof from === "function") {
8
+ for (let key of __getOwnPropNames(from))
9
+ if (!__hasOwnProp.call(to, key) && key !== except)
10
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
11
+ }
12
+ return to;
13
+ };
14
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
15
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
16
+ var index_exports = {};
17
+ module.exports = __toCommonJS(index_exports);
18
+ __reExport(index_exports, require('./intlayerPlugin.cjs'), module.exports);
19
+ __reExport(index_exports, require('./intlayerMiddlewarePlugin.cjs'), module.exports);
20
+ // Annotate the CommonJS export names for ESM import in node:
21
+ 0 && (module.exports = {
22
+ ...require('./intlayerPlugin.cjs'),
23
+ ...require('./intlayerMiddlewarePlugin.cjs')
24
+ });
25
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/index.ts"],"sourcesContent":["export * from './intlayerPlugin';\nexport * from './intlayerMiddlewarePlugin';\n"],"mappings":";;;;;;;;;;;;;;;AAAA;AAAA;AAAA,0BAAc,6BAAd;AACA,0BAAc,uCADd;","names":[]}
@@ -0,0 +1,224 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var intlayerMiddlewarePlugin_exports = {};
20
+ __export(intlayerMiddlewarePlugin_exports, {
21
+ intLayerMiddlewarePlugin: () => intLayerMiddlewarePlugin
22
+ });
23
+ module.exports = __toCommonJS(intlayerMiddlewarePlugin_exports);
24
+ var import_url = require("url");
25
+ var import_config = require("@intlayer/config");
26
+ var import_core = require("@intlayer/core");
27
+ const intlayerConfig = (0, import_config.getConfiguration)();
28
+ const { internationalization, middleware } = intlayerConfig;
29
+ const { locales: supportedLocales, defaultLocale } = internationalization;
30
+ const {
31
+ cookieName,
32
+ headerName,
33
+ prefixDefault,
34
+ noPrefix,
35
+ serverSetCookie,
36
+ basePath = ""
37
+ } = middleware;
38
+ const intLayerMiddlewarePlugin = () => {
39
+ return {
40
+ name: "vite-intlayer-middleware-plugin",
41
+ configureServer: (server) => {
42
+ server.middlewares.use((req, res, next) => {
43
+ if (req.url?.startsWith("/node_modules") || req.url?.startsWith("/@") || req.url?.split("?")[0].match(/\.[a-z]+$/i)) {
44
+ return next();
45
+ }
46
+ const parsedUrl = (0, import_url.parse)(req.url ?? "/", true);
47
+ const originalPath = parsedUrl.pathname ?? "/";
48
+ const cookies = parseCookies(req.headers.cookie ?? "");
49
+ const cookieLocale = getValidLocaleFromCookie(cookies[cookieName]);
50
+ const pathLocale = getPathLocale(originalPath);
51
+ if (noPrefix) {
52
+ handleNoPrefix({
53
+ req,
54
+ res,
55
+ next,
56
+ originalPath,
57
+ cookieLocale
58
+ });
59
+ return;
60
+ }
61
+ handlePrefix({
62
+ req,
63
+ res,
64
+ next,
65
+ originalPath,
66
+ pathLocale,
67
+ cookieLocale
68
+ });
69
+ });
70
+ }
71
+ };
72
+ };
73
+ const parseCookies = (cookieHeader) => {
74
+ return cookieHeader.split(";").reduce(
75
+ (acc, cookie) => {
76
+ const [key, val] = cookie.trim().split("=");
77
+ acc[key] = val;
78
+ return acc;
79
+ },
80
+ {}
81
+ );
82
+ };
83
+ const getValidLocaleFromCookie = (locale) => {
84
+ if (locale && supportedLocales.includes(locale)) {
85
+ return locale;
86
+ }
87
+ return void 0;
88
+ };
89
+ const getPathLocale = (pathname) => {
90
+ const segments = pathname.split("/").filter(Boolean);
91
+ const firstSegment = segments[0];
92
+ if (firstSegment && supportedLocales.includes(firstSegment)) {
93
+ return firstSegment;
94
+ }
95
+ return void 0;
96
+ };
97
+ const redirectUrl = (res, newUrl) => {
98
+ res.writeHead(301, { Location: newUrl });
99
+ return res.end();
100
+ };
101
+ const rewriteUrl = (req, res, newUrl, locale) => {
102
+ req.url = newUrl;
103
+ if (locale && headerName) {
104
+ res.setHeader(headerName, locale);
105
+ }
106
+ };
107
+ const constructPath = (locale, currentPath) => {
108
+ const cleanBasePath = basePath.startsWith("/") ? basePath : `/${basePath}`;
109
+ const normalizedBasePath = cleanBasePath === "/" ? "" : cleanBasePath;
110
+ let newPath = `${normalizedBasePath}/${locale}${currentPath}`;
111
+ if (!prefixDefault && locale === defaultLocale) {
112
+ newPath = `${normalizedBasePath}${currentPath}`;
113
+ }
114
+ return newPath;
115
+ };
116
+ const handleNoPrefix = ({
117
+ req,
118
+ res,
119
+ next,
120
+ originalPath,
121
+ cookieLocale
122
+ }) => {
123
+ let locale = cookieLocale ?? defaultLocale;
124
+ if (!cookieLocale) {
125
+ const detectedLocale = (0, import_core.localeDetector)(
126
+ req.headers,
127
+ supportedLocales,
128
+ defaultLocale
129
+ );
130
+ locale = detectedLocale;
131
+ }
132
+ rewriteUrl(req, res, originalPath, locale);
133
+ return next();
134
+ };
135
+ const handlePrefix = ({
136
+ req,
137
+ res,
138
+ next,
139
+ originalPath,
140
+ pathLocale,
141
+ cookieLocale
142
+ }) => {
143
+ if (!pathLocale) {
144
+ handleMissingPathLocale({
145
+ req,
146
+ res,
147
+ next,
148
+ originalPath,
149
+ cookieLocale
150
+ });
151
+ return;
152
+ }
153
+ handleExistingPathLocale({
154
+ req,
155
+ res,
156
+ next,
157
+ originalPath,
158
+ pathLocale,
159
+ cookieLocale
160
+ });
161
+ };
162
+ const handleMissingPathLocale = ({
163
+ req,
164
+ res,
165
+ next,
166
+ originalPath,
167
+ cookieLocale
168
+ }) => {
169
+ let locale = cookieLocale ?? (0, import_core.localeDetector)(
170
+ req.headers,
171
+ supportedLocales,
172
+ defaultLocale
173
+ );
174
+ if (!supportedLocales.includes(locale)) {
175
+ locale = defaultLocale;
176
+ }
177
+ const newPath = constructPath(locale, originalPath);
178
+ if (prefixDefault || locale !== defaultLocale) {
179
+ return redirectUrl(res, newPath);
180
+ }
181
+ rewriteUrl(req, res, newPath, locale);
182
+ return next();
183
+ };
184
+ const handleExistingPathLocale = ({
185
+ req,
186
+ res,
187
+ next,
188
+ originalPath,
189
+ pathLocale,
190
+ cookieLocale
191
+ }) => {
192
+ if (cookieLocale && cookieLocale !== pathLocale && serverSetCookie !== "always") {
193
+ const newPath = originalPath.replace(`/${pathLocale}`, `/${cookieLocale}`);
194
+ const finalPath = constructPath(cookieLocale, newPath.replace(/^\/+/, "/"));
195
+ return redirectUrl(res, finalPath);
196
+ }
197
+ handleDefaultLocaleRedirect({
198
+ req,
199
+ res,
200
+ next,
201
+ originalPath,
202
+ pathLocale
203
+ });
204
+ };
205
+ const handleDefaultLocaleRedirect = ({
206
+ req,
207
+ res,
208
+ next,
209
+ originalPath,
210
+ pathLocale
211
+ }) => {
212
+ if (!prefixDefault && pathLocale === defaultLocale) {
213
+ const newPath = originalPath.replace(`/${defaultLocale}`, "") ?? "/";
214
+ rewriteUrl(req, res, newPath, pathLocale);
215
+ return next();
216
+ }
217
+ rewriteUrl(req, res, originalPath, pathLocale);
218
+ return next();
219
+ };
220
+ // Annotate the CommonJS export names for ESM import in node:
221
+ 0 && (module.exports = {
222
+ intLayerMiddlewarePlugin
223
+ });
224
+ //# sourceMappingURL=intlayerMiddlewarePlugin.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/intlayerMiddlewarePlugin.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'http';\nimport { parse } from 'url';\nimport { getConfiguration, type Locales } from '@intlayer/config';\nimport { localeDetector } from '@intlayer/core';\n/* @ts-ignore - Vite types error */\nimport type { Connect, Plugin } from 'vite';\n\n// Grab all the config you need.\n// Make sure your config includes the following fields if you want to replicate Next.js logic:\n// - internationalization.locales\n// - internationalization.defaultLocale\n// - middleware.cookieName\n// - middleware.headerName\n// - middleware.prefixDefault\n// - middleware.noPrefix\n// - middleware.serverSetCookie\n// - middleware.basePath\n// - etc.\nconst intlayerConfig = getConfiguration();\nconst { internationalization, middleware } = intlayerConfig;\nconst { locales: supportedLocales, defaultLocale } = internationalization;\n\nconst {\n cookieName,\n headerName,\n prefixDefault,\n noPrefix,\n serverSetCookie,\n basePath = '',\n} = middleware;\n\n/**\n * A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.\n */\nexport const intLayerMiddlewarePlugin = (): Plugin => {\n return {\n name: 'vite-intlayer-middleware-plugin',\n configureServer: (server) => {\n server.middlewares.use((req, res, next) => {\n // 1. Bypass assets and special Vite endpoints\n if (\n req.url?.startsWith('/node_modules') ||\n req.url?.startsWith('/@') ||\n req.url?.split('?')[0].match(/\\.[a-z]+$/i) // checks for file extensions\n ) {\n return next();\n }\n\n // 2. Parse original URL for path and query\n const parsedUrl = parse(req.url ?? '/', true);\n const originalPath = parsedUrl.pathname ?? '/';\n\n // 3. Attempt to read the cookie locale\n const cookies = parseCookies(req.headers.cookie ?? '');\n const cookieLocale = getValidLocaleFromCookie(cookies[cookieName]);\n\n // 4. Check if there's a locale prefix in the path\n const pathLocale = getPathLocale(originalPath);\n\n // 5. If noPrefix is true, we skip prefix logic altogether\n if (noPrefix) {\n handleNoPrefix({\n req,\n res,\n next,\n originalPath,\n cookieLocale,\n });\n return;\n }\n\n // 6. Otherwise, handle prefix logic\n handlePrefix({\n req,\n res,\n next,\n originalPath,\n pathLocale,\n cookieLocale,\n });\n });\n },\n };\n};\n\n/* --------------------------------------------------------------------\n * Helper & Utility Functions\n * --------------------------------------------------------------------\n */\n\n/**\n * Parses cookies from the Cookie header string into an object.\n */\nconst parseCookies = (cookieHeader: string) => {\n return cookieHeader.split(';').reduce(\n (acc, cookie) => {\n const [key, val] = cookie.trim().split('=');\n acc[key] = val;\n return acc;\n },\n {} as Record<string, string>\n );\n};\n\n/**\n * Checks if the cookie locale is valid and is included in the supported locales.\n */\nconst getValidLocaleFromCookie = (\n locale: string | undefined\n): Locales | undefined => {\n if (locale && supportedLocales.includes(locale as Locales)) {\n return locale as Locales;\n }\n return undefined;\n};\n\n/**\n * Extracts the locale from the URL pathname if present as the first segment.\n */\nconst getPathLocale = (pathname: string): Locales | undefined => {\n // e.g. if pathname is /en/some/page or /en\n // we check if \"en\" is in your supportedLocales\n const segments = pathname.split('/').filter(Boolean);\n const firstSegment = segments[0];\n if (firstSegment && supportedLocales.includes(firstSegment as Locales)) {\n return firstSegment as Locales;\n }\n return undefined;\n};\n\n/**\n * Writes a 301 redirect response with the given new URL.\n */\nconst redirectUrl = (res: ServerResponse<IncomingMessage>, newUrl: string) => {\n res.writeHead(301, { Location: newUrl });\n return res.end();\n};\n\n/**\n * \"Rewrite\" the request internally by adjusting req.url;\n * we also set the locale in the response header if needed.\n */\nconst rewriteUrl = (\n req: Connect.IncomingMessage,\n res: ServerResponse<IncomingMessage>,\n newUrl: string,\n locale?: Locales\n) => {\n req.url = newUrl;\n // If you want to mimic Next.js's behavior of setting a header for the locale:\n if (locale && headerName) {\n res.setHeader(headerName, locale);\n }\n};\n\n/**\n * Constructs a new path string, optionally including a locale prefix and basePath.\n * - basePath: (e.g., '/myapp')\n * - locale: (e.g., 'en')\n * - currentPath:(e.g., '/products/shoes')\n */\nconst constructPath = (locale: Locales, currentPath: string) => {\n // Ensure basePath always starts with '/', and remove trailing slash if needed\n const cleanBasePath = basePath.startsWith('/') ? basePath : `/${basePath}`;\n // If basePath is '/', no trailing slash is needed\n const normalizedBasePath = cleanBasePath === '/' ? '' : cleanBasePath;\n\n // Combine basePath + locale + the rest of the path\n // Example: basePath = '/myapp', locale = 'en', currentPath = '/products' => '/myapp/en/products'\n let newPath = `${normalizedBasePath}/${locale}${currentPath}`;\n\n // Special case: if prefixDefault is false and locale is defaultLocale, remove the locale prefix\n if (!prefixDefault && locale === defaultLocale) {\n newPath = `${normalizedBasePath}${currentPath}`;\n }\n\n return newPath;\n};\n\n/* --------------------------------------------------------------------\n * Handlers that mirror Next.js style logic\n * --------------------------------------------------------------------\n */\n\n/**\n * If `noPrefix` is true, we never prefix the locale in the URL.\n * We simply rewrite the request to the same path, but with the best-chosen locale\n * in a header or cookie if desired.\n */\nconst handleNoPrefix = ({\n req,\n res,\n next,\n originalPath,\n cookieLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n cookieLocale?: Locales;\n}) => {\n // Determine the best locale\n let locale = cookieLocale ?? defaultLocale;\n\n // Use fallback to localeDetector if no cookie\n if (!cookieLocale) {\n const detectedLocale = localeDetector(\n req.headers as Record<string, string>,\n supportedLocales,\n defaultLocale\n );\n locale = detectedLocale as Locales;\n }\n\n // Just rewrite the URL in-place (no prefix). We do NOT redirect because we do not want to alter the URL.\n rewriteUrl(req, res, originalPath, locale);\n return next();\n};\n\n/**\n * The main prefix logic:\n * - If there's no pathLocale in the URL, we might want to detect & redirect or rewrite\n * - If there is a pathLocale, handle cookie mismatch or default locale special cases\n */\nconst handlePrefix = ({\n req,\n res,\n next,\n originalPath,\n pathLocale,\n cookieLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n pathLocale?: Locales;\n cookieLocale?: Locales;\n}) => {\n // 1. If pathLocale is missing, handle\n if (!pathLocale) {\n handleMissingPathLocale({\n req,\n res,\n next,\n originalPath,\n cookieLocale,\n });\n return;\n }\n\n // 2. If pathLocale exists, handle possible mismatch with cookie\n handleExistingPathLocale({\n req,\n res,\n next,\n originalPath,\n pathLocale,\n cookieLocale,\n });\n};\n\n/**\n * Handles requests where the locale is missing from the URL pathname.\n * We detect a locale from cookie / headers / default, then either redirect or rewrite.\n */\nconst handleMissingPathLocale = ({\n req,\n res,\n next,\n originalPath,\n cookieLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n cookieLocale?: Locales;\n}) => {\n // 1. Choose the best locale\n let locale = (cookieLocale ??\n localeDetector(\n req.headers as Record<string, string>,\n supportedLocales,\n defaultLocale\n )) as Locales;\n\n // 2. If still invalid, fallback\n if (!supportedLocales.includes(locale)) {\n locale = defaultLocale;\n }\n\n // 3. Construct new path\n const newPath = constructPath(locale, originalPath);\n\n // If we always prefix default or if this is not the default locale, do a 301 redirect\n // so that the user sees the locale in the URL.\n if (prefixDefault || locale !== defaultLocale) {\n return redirectUrl(res, newPath);\n }\n\n // If we do NOT prefix the default locale, just rewrite in place\n rewriteUrl(req, res, newPath, locale);\n return next();\n};\n\n/**\n * Handles requests where the locale prefix is present in the pathname.\n * We verify if the cookie locale differs from the path locale; if so, handle.\n */\nconst handleExistingPathLocale = ({\n req,\n res,\n next,\n originalPath,\n pathLocale,\n cookieLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n pathLocale: Locales;\n cookieLocale?: Locales;\n}) => {\n // 1. If the cookie locale is set and differs from the path locale,\n // and we're not forcing the cookie to always override\n if (\n cookieLocale &&\n cookieLocale !== pathLocale &&\n serverSetCookie !== 'always'\n ) {\n // We want to swap out the pathLocale with the cookieLocale\n const newPath = originalPath.replace(`/${pathLocale}`, `/${cookieLocale}`);\n const finalPath = constructPath(cookieLocale, newPath.replace(/^\\/+/, '/'));\n return redirectUrl(res, finalPath);\n }\n\n // 2. Otherwise, handle default-locale prefix if needed\n handleDefaultLocaleRedirect({\n req,\n res,\n next,\n originalPath,\n pathLocale,\n });\n};\n\n/**\n * If the path locale is the default locale but we don't want to prefix the default, remove it.\n */\nconst handleDefaultLocaleRedirect = ({\n req,\n res,\n next,\n originalPath,\n pathLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n pathLocale: Locales;\n}) => {\n // If we don't prefix default AND the path locale is the default locale -> remove it\n if (!prefixDefault && pathLocale === defaultLocale) {\n // Remove the default locale part from the path\n const newPath = originalPath.replace(`/${defaultLocale}`, '') ?? '/';\n rewriteUrl(req, res, newPath, pathLocale);\n return next();\n }\n\n // If we do prefix default or pathLocale != default, keep as is, but rewrite headers\n rewriteUrl(req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H;AAKA,MAAM,8BAA8B,CAAC;AAAA,EACnC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,MAMM;AAEJ,MAAI,CAAC,iBAAiB,eAAe,eAAe;AAElD,UAAM,UAAU,aAAa,QAAQ,IAAI,aAAa,IAAI,EAAE,KAAK;AACjE,eAAW,KAAK,KAAK,SAAS,UAAU;AACxC,WAAO,KAAK;AAAA,EACd;AAGA,aAAW,KAAK,KAAK,cAAc,UAAU;AAC7C,SAAO,KAAK;AACd;","names":[]}
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var intlayerPlugin_exports = {};
20
+ __export(intlayerPlugin_exports, {
21
+ intlayerPlugin: () => intlayerPlugin
22
+ });
23
+ module.exports = __toCommonJS(intlayerPlugin_exports);
24
+ var import_path = require("path");
25
+ var import_chokidar = require("@intlayer/chokidar");
26
+ var import_config = require("@intlayer/config");
27
+ const intlayerPlugin = (_pluginOptions = {}) => ({
28
+ name: "vite-intlayer-plugin",
29
+ config: (config) => {
30
+ const intlayerConfig = (0, import_config.getConfiguration)();
31
+ const {
32
+ mainDir,
33
+ configDir,
34
+ baseDir,
35
+ watch: isWatchMode
36
+ } = intlayerConfig.content;
37
+ const dictionariesPath = (0, import_path.join)(mainDir, "dictionaries.mjs");
38
+ const relativeDictionariesPath = (0, import_path.relative)(baseDir, dictionariesPath);
39
+ const configurationPath = (0, import_path.join)(configDir, "configuration.json");
40
+ const relativeConfigurationPath = (0, import_path.relative)(baseDir, configurationPath);
41
+ config.resolve = {
42
+ ...config.resolve,
43
+ alias: {
44
+ ...config.resolve?.alias,
45
+ "@intlayer/dictionaries-entry": (0, import_path.resolve)(relativeDictionariesPath),
46
+ "@intlayer/config/built": (0, import_path.resolve)(relativeConfigurationPath)
47
+ }
48
+ };
49
+ if (isWatchMode) {
50
+ config.optimizeDeps = {
51
+ ...config.optimizeDeps,
52
+ exclude: [
53
+ ...config.optimizeDeps?.exclude ?? [],
54
+ "@intlayer/dictionaries-entry",
55
+ "@intlayer/config/built"
56
+ ]
57
+ };
58
+ }
59
+ return config;
60
+ },
61
+ configureServer: async () => {
62
+ const intlayerConfig = (0, import_config.getConfiguration)();
63
+ if (intlayerConfig.content.watch) {
64
+ (0, import_chokidar.watch)({ configuration: intlayerConfig });
65
+ }
66
+ },
67
+ buildStart: async () => {
68
+ const intlayerConfig = (0, import_config.getConfiguration)();
69
+ await (0, import_chokidar.prepareIntlayer)(intlayerConfig);
70
+ }
71
+ });
72
+ // Annotate the CommonJS export names for ESM import in node:
73
+ 0 && (module.exports = {
74
+ intlayerPlugin
75
+ });
76
+ //# sourceMappingURL=intlayerPlugin.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/intlayerPlugin.ts"],"sourcesContent":["import { join, relative, resolve } from 'path';\nimport { prepareIntlayer, watch } from '@intlayer/chokidar';\nimport { getConfiguration } from '@intlayer/config';\n// @ts-ignore - Fix error Module '\"vite\"' has no exported member\nimport { type PluginOption } from 'vite';\n\n// Plugin options type definition\ntype PluginOptions = {\n // Custom options for your plugin, if any\n};\n\n/**\n *\n * A Vite plugin that integrates Intlayer configuration into the build process\n *\n * ```ts\n * // Example usage of the plugin in a Vite configuration\n * export default defineConfig({\n * plugins: [ intlayerPlugin() ],\n * });\n * ```\n * */\nexport const intlayerPlugin = (\n _pluginOptions: PluginOptions = {}\n): PluginOption => ({\n name: 'vite-intlayer-plugin',\n\n config: (config) => {\n const intlayerConfig = getConfiguration();\n const {\n mainDir,\n configDir,\n baseDir,\n watch: isWatchMode,\n } = intlayerConfig.content;\n\n const dictionariesPath = join(mainDir, 'dictionaries.mjs');\n const relativeDictionariesPath = relative(baseDir, dictionariesPath);\n\n const configurationPath = join(configDir, 'configuration.json');\n const relativeConfigurationPath = relative(baseDir, configurationPath);\n\n // Update Vite's resolve alias\n config.resolve = {\n ...config.resolve,\n alias: {\n ...config.resolve?.alias,\n '@intlayer/dictionaries-entry': resolve(relativeDictionariesPath),\n '@intlayer/config/built': resolve(relativeConfigurationPath),\n },\n };\n\n if (isWatchMode) {\n // Ajout de l'option optimizeDeps.exclude\n config.optimizeDeps = {\n ...config.optimizeDeps,\n exclude: [\n ...(config.optimizeDeps?.exclude ?? []),\n '@intlayer/dictionaries-entry',\n '@intlayer/config/built',\n ],\n };\n }\n\n return config;\n },\n\n configureServer: async () => {\n // Runs when the dev server starts\n const intlayerConfig = getConfiguration();\n\n if (intlayerConfig.content.watch) {\n // Start watching (assuming watch is also async)\n watch({ configuration: intlayerConfig });\n }\n },\n\n buildStart: async () => {\n // Code to run when Vite build starts\n const intlayerConfig = getConfiguration();\n await prepareIntlayer(intlayerConfig);\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kBAAwC;AACxC,sBAAuC;AACvC,oBAAiC;AAoB1B,MAAM,iBAAiB,CAC5B,iBAAgC,CAAC,OACf;AAAA,EAClB,MAAM;AAAA,EAEN,QAAQ,CAAC,WAAW;AAClB,UAAM,qBAAiB,gCAAiB;AACxC,UAAM;AAAA,MACJ;AAAA,MACA;AAAA,MACA;AAAA,MACA,OAAO;AAAA,IACT,IAAI,eAAe;AAEnB,UAAM,uBAAmB,kBAAK,SAAS,kBAAkB;AACzD,UAAM,+BAA2B,sBAAS,SAAS,gBAAgB;AAEnE,UAAM,wBAAoB,kBAAK,WAAW,oBAAoB;AAC9D,UAAM,gCAA4B,sBAAS,SAAS,iBAAiB;AAGrE,WAAO,UAAU;AAAA,MACf,GAAG,OAAO;AAAA,MACV,OAAO;AAAA,QACL,GAAG,OAAO,SAAS;AAAA,QACnB,oCAAgC,qBAAQ,wBAAwB;AAAA,QAChE,8BAA0B,qBAAQ,yBAAyB;AAAA,MAC7D;AAAA,IACF;AAEA,QAAI,aAAa;AAEf,aAAO,eAAe;AAAA,QACpB,GAAG,OAAO;AAAA,QACV,SAAS;AAAA,UACP,GAAI,OAAO,cAAc,WAAW,CAAC;AAAA,UACrC;AAAA,UACA;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AAAA,EAEA,iBAAiB,YAAY;AAE3B,UAAM,qBAAiB,gCAAiB;AAExC,QAAI,eAAe,QAAQ,OAAO;AAEhC,iCAAM,EAAE,eAAe,eAAe,CAAC;AAAA,IACzC;AAAA,EACF;AAAA,EAEA,YAAY,YAAY;AAEtB,UAAM,qBAAiB,gCAAiB;AACxC,cAAM,iCAAgB,cAAc;AAAA,EACtC;AACF;","names":[]}
@@ -0,0 +1,3 @@
1
+ export * from "./intlayerPlugin.mjs";
2
+ export * from "./intlayerMiddlewarePlugin.mjs";
3
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/index.ts"],"sourcesContent":["export * from './intlayerPlugin';\nexport * from './intlayerMiddlewarePlugin';\n"],"mappings":"AAAA,cAAc;AACd,cAAc;","names":[]}
@@ -0,0 +1,200 @@
1
+ import { parse } from "url";
2
+ import { getConfiguration } from "@intlayer/config";
3
+ import { localeDetector } from "@intlayer/core";
4
+ const intlayerConfig = getConfiguration();
5
+ const { internationalization, middleware } = intlayerConfig;
6
+ const { locales: supportedLocales, defaultLocale } = internationalization;
7
+ const {
8
+ cookieName,
9
+ headerName,
10
+ prefixDefault,
11
+ noPrefix,
12
+ serverSetCookie,
13
+ basePath = ""
14
+ } = middleware;
15
+ const intLayerMiddlewarePlugin = () => {
16
+ return {
17
+ name: "vite-intlayer-middleware-plugin",
18
+ configureServer: (server) => {
19
+ server.middlewares.use((req, res, next) => {
20
+ if (req.url?.startsWith("/node_modules") || req.url?.startsWith("/@") || req.url?.split("?")[0].match(/\.[a-z]+$/i)) {
21
+ return next();
22
+ }
23
+ const parsedUrl = parse(req.url ?? "/", true);
24
+ const originalPath = parsedUrl.pathname ?? "/";
25
+ const cookies = parseCookies(req.headers.cookie ?? "");
26
+ const cookieLocale = getValidLocaleFromCookie(cookies[cookieName]);
27
+ const pathLocale = getPathLocale(originalPath);
28
+ if (noPrefix) {
29
+ handleNoPrefix({
30
+ req,
31
+ res,
32
+ next,
33
+ originalPath,
34
+ cookieLocale
35
+ });
36
+ return;
37
+ }
38
+ handlePrefix({
39
+ req,
40
+ res,
41
+ next,
42
+ originalPath,
43
+ pathLocale,
44
+ cookieLocale
45
+ });
46
+ });
47
+ }
48
+ };
49
+ };
50
+ const parseCookies = (cookieHeader) => {
51
+ return cookieHeader.split(";").reduce(
52
+ (acc, cookie) => {
53
+ const [key, val] = cookie.trim().split("=");
54
+ acc[key] = val;
55
+ return acc;
56
+ },
57
+ {}
58
+ );
59
+ };
60
+ const getValidLocaleFromCookie = (locale) => {
61
+ if (locale && supportedLocales.includes(locale)) {
62
+ return locale;
63
+ }
64
+ return void 0;
65
+ };
66
+ const getPathLocale = (pathname) => {
67
+ const segments = pathname.split("/").filter(Boolean);
68
+ const firstSegment = segments[0];
69
+ if (firstSegment && supportedLocales.includes(firstSegment)) {
70
+ return firstSegment;
71
+ }
72
+ return void 0;
73
+ };
74
+ const redirectUrl = (res, newUrl) => {
75
+ res.writeHead(301, { Location: newUrl });
76
+ return res.end();
77
+ };
78
+ const rewriteUrl = (req, res, newUrl, locale) => {
79
+ req.url = newUrl;
80
+ if (locale && headerName) {
81
+ res.setHeader(headerName, locale);
82
+ }
83
+ };
84
+ const constructPath = (locale, currentPath) => {
85
+ const cleanBasePath = basePath.startsWith("/") ? basePath : `/${basePath}`;
86
+ const normalizedBasePath = cleanBasePath === "/" ? "" : cleanBasePath;
87
+ let newPath = `${normalizedBasePath}/${locale}${currentPath}`;
88
+ if (!prefixDefault && locale === defaultLocale) {
89
+ newPath = `${normalizedBasePath}${currentPath}`;
90
+ }
91
+ return newPath;
92
+ };
93
+ const handleNoPrefix = ({
94
+ req,
95
+ res,
96
+ next,
97
+ originalPath,
98
+ cookieLocale
99
+ }) => {
100
+ let locale = cookieLocale ?? defaultLocale;
101
+ if (!cookieLocale) {
102
+ const detectedLocale = localeDetector(
103
+ req.headers,
104
+ supportedLocales,
105
+ defaultLocale
106
+ );
107
+ locale = detectedLocale;
108
+ }
109
+ rewriteUrl(req, res, originalPath, locale);
110
+ return next();
111
+ };
112
+ const handlePrefix = ({
113
+ req,
114
+ res,
115
+ next,
116
+ originalPath,
117
+ pathLocale,
118
+ cookieLocale
119
+ }) => {
120
+ if (!pathLocale) {
121
+ handleMissingPathLocale({
122
+ req,
123
+ res,
124
+ next,
125
+ originalPath,
126
+ cookieLocale
127
+ });
128
+ return;
129
+ }
130
+ handleExistingPathLocale({
131
+ req,
132
+ res,
133
+ next,
134
+ originalPath,
135
+ pathLocale,
136
+ cookieLocale
137
+ });
138
+ };
139
+ const handleMissingPathLocale = ({
140
+ req,
141
+ res,
142
+ next,
143
+ originalPath,
144
+ cookieLocale
145
+ }) => {
146
+ let locale = cookieLocale ?? localeDetector(
147
+ req.headers,
148
+ supportedLocales,
149
+ defaultLocale
150
+ );
151
+ if (!supportedLocales.includes(locale)) {
152
+ locale = defaultLocale;
153
+ }
154
+ const newPath = constructPath(locale, originalPath);
155
+ if (prefixDefault || locale !== defaultLocale) {
156
+ return redirectUrl(res, newPath);
157
+ }
158
+ rewriteUrl(req, res, newPath, locale);
159
+ return next();
160
+ };
161
+ const handleExistingPathLocale = ({
162
+ req,
163
+ res,
164
+ next,
165
+ originalPath,
166
+ pathLocale,
167
+ cookieLocale
168
+ }) => {
169
+ if (cookieLocale && cookieLocale !== pathLocale && serverSetCookie !== "always") {
170
+ const newPath = originalPath.replace(`/${pathLocale}`, `/${cookieLocale}`);
171
+ const finalPath = constructPath(cookieLocale, newPath.replace(/^\/+/, "/"));
172
+ return redirectUrl(res, finalPath);
173
+ }
174
+ handleDefaultLocaleRedirect({
175
+ req,
176
+ res,
177
+ next,
178
+ originalPath,
179
+ pathLocale
180
+ });
181
+ };
182
+ const handleDefaultLocaleRedirect = ({
183
+ req,
184
+ res,
185
+ next,
186
+ originalPath,
187
+ pathLocale
188
+ }) => {
189
+ if (!prefixDefault && pathLocale === defaultLocale) {
190
+ const newPath = originalPath.replace(`/${defaultLocale}`, "") ?? "/";
191
+ rewriteUrl(req, res, newPath, pathLocale);
192
+ return next();
193
+ }
194
+ rewriteUrl(req, res, originalPath, pathLocale);
195
+ return next();
196
+ };
197
+ export {
198
+ intLayerMiddlewarePlugin
199
+ };
200
+ //# sourceMappingURL=intlayerMiddlewarePlugin.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/intlayerMiddlewarePlugin.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'http';\nimport { parse } from 'url';\nimport { getConfiguration, type Locales } from '@intlayer/config';\nimport { localeDetector } from '@intlayer/core';\n/* @ts-ignore - Vite types error */\nimport type { Connect, Plugin } from 'vite';\n\n// Grab all the config you need.\n// Make sure your config includes the following fields if you want to replicate Next.js logic:\n// - internationalization.locales\n// - internationalization.defaultLocale\n// - middleware.cookieName\n// - middleware.headerName\n// - middleware.prefixDefault\n// - middleware.noPrefix\n// - middleware.serverSetCookie\n// - middleware.basePath\n// - etc.\nconst intlayerConfig = getConfiguration();\nconst { internationalization, middleware } = intlayerConfig;\nconst { locales: supportedLocales, defaultLocale } = internationalization;\n\nconst {\n cookieName,\n headerName,\n prefixDefault,\n noPrefix,\n serverSetCookie,\n basePath = '',\n} = middleware;\n\n/**\n * A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.\n */\nexport const intLayerMiddlewarePlugin = (): Plugin => {\n return {\n name: 'vite-intlayer-middleware-plugin',\n configureServer: (server) => {\n server.middlewares.use((req, res, next) => {\n // 1. Bypass assets and special Vite endpoints\n if (\n req.url?.startsWith('/node_modules') ||\n req.url?.startsWith('/@') ||\n req.url?.split('?')[0].match(/\\.[a-z]+$/i) // checks for file extensions\n ) {\n return next();\n }\n\n // 2. Parse original URL for path and query\n const parsedUrl = parse(req.url ?? '/', true);\n const originalPath = parsedUrl.pathname ?? '/';\n\n // 3. Attempt to read the cookie locale\n const cookies = parseCookies(req.headers.cookie ?? '');\n const cookieLocale = getValidLocaleFromCookie(cookies[cookieName]);\n\n // 4. Check if there's a locale prefix in the path\n const pathLocale = getPathLocale(originalPath);\n\n // 5. If noPrefix is true, we skip prefix logic altogether\n if (noPrefix) {\n handleNoPrefix({\n req,\n res,\n next,\n originalPath,\n cookieLocale,\n });\n return;\n }\n\n // 6. Otherwise, handle prefix logic\n handlePrefix({\n req,\n res,\n next,\n originalPath,\n pathLocale,\n cookieLocale,\n });\n });\n },\n };\n};\n\n/* --------------------------------------------------------------------\n * Helper & Utility Functions\n * --------------------------------------------------------------------\n */\n\n/**\n * Parses cookies from the Cookie header string into an object.\n */\nconst parseCookies = (cookieHeader: string) => {\n return cookieHeader.split(';').reduce(\n (acc, cookie) => {\n const [key, val] = cookie.trim().split('=');\n acc[key] = val;\n return acc;\n },\n {} as Record<string, string>\n );\n};\n\n/**\n * Checks if the cookie locale is valid and is included in the supported locales.\n */\nconst getValidLocaleFromCookie = (\n locale: string | undefined\n): Locales | undefined => {\n if (locale && supportedLocales.includes(locale as Locales)) {\n return locale as Locales;\n }\n return undefined;\n};\n\n/**\n * Extracts the locale from the URL pathname if present as the first segment.\n */\nconst getPathLocale = (pathname: string): Locales | undefined => {\n // e.g. if pathname is /en/some/page or /en\n // we check if \"en\" is in your supportedLocales\n const segments = pathname.split('/').filter(Boolean);\n const firstSegment = segments[0];\n if (firstSegment && supportedLocales.includes(firstSegment as Locales)) {\n return firstSegment as Locales;\n }\n return undefined;\n};\n\n/**\n * Writes a 301 redirect response with the given new URL.\n */\nconst redirectUrl = (res: ServerResponse<IncomingMessage>, newUrl: string) => {\n res.writeHead(301, { Location: newUrl });\n return res.end();\n};\n\n/**\n * \"Rewrite\" the request internally by adjusting req.url;\n * we also set the locale in the response header if needed.\n */\nconst rewriteUrl = (\n req: Connect.IncomingMessage,\n res: ServerResponse<IncomingMessage>,\n newUrl: string,\n locale?: Locales\n) => {\n req.url = newUrl;\n // If you want to mimic Next.js's behavior of setting a header for the locale:\n if (locale && headerName) {\n res.setHeader(headerName, locale);\n }\n};\n\n/**\n * Constructs a new path string, optionally including a locale prefix and basePath.\n * - basePath: (e.g., '/myapp')\n * - locale: (e.g., 'en')\n * - currentPath:(e.g., '/products/shoes')\n */\nconst constructPath = (locale: Locales, currentPath: string) => {\n // Ensure basePath always starts with '/', and remove trailing slash if needed\n const cleanBasePath = basePath.startsWith('/') ? basePath : `/${basePath}`;\n // If basePath is '/', no trailing slash is needed\n const normalizedBasePath = cleanBasePath === '/' ? '' : cleanBasePath;\n\n // Combine basePath + locale + the rest of the path\n // Example: basePath = '/myapp', locale = 'en', currentPath = '/products' => '/myapp/en/products'\n let newPath = `${normalizedBasePath}/${locale}${currentPath}`;\n\n // Special case: if prefixDefault is false and locale is defaultLocale, remove the locale prefix\n if (!prefixDefault && locale === defaultLocale) {\n newPath = `${normalizedBasePath}${currentPath}`;\n }\n\n return newPath;\n};\n\n/* --------------------------------------------------------------------\n * Handlers that mirror Next.js style logic\n * --------------------------------------------------------------------\n */\n\n/**\n * If `noPrefix` is true, we never prefix the locale in the URL.\n * We simply rewrite the request to the same path, but with the best-chosen locale\n * in a header or cookie if desired.\n */\nconst handleNoPrefix = ({\n req,\n res,\n next,\n originalPath,\n cookieLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n cookieLocale?: Locales;\n}) => {\n // Determine the best locale\n let locale = cookieLocale ?? defaultLocale;\n\n // Use fallback to localeDetector if no cookie\n if (!cookieLocale) {\n const detectedLocale = localeDetector(\n req.headers as Record<string, string>,\n supportedLocales,\n defaultLocale\n );\n locale = detectedLocale as Locales;\n }\n\n // Just rewrite the URL in-place (no prefix). We do NOT redirect because we do not want to alter the URL.\n rewriteUrl(req, res, originalPath, locale);\n return next();\n};\n\n/**\n * The main prefix logic:\n * - If there's no pathLocale in the URL, we might want to detect & redirect or rewrite\n * - If there is a pathLocale, handle cookie mismatch or default locale special cases\n */\nconst handlePrefix = ({\n req,\n res,\n next,\n originalPath,\n pathLocale,\n cookieLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n pathLocale?: Locales;\n cookieLocale?: Locales;\n}) => {\n // 1. If pathLocale is missing, handle\n if (!pathLocale) {\n handleMissingPathLocale({\n req,\n res,\n next,\n originalPath,\n cookieLocale,\n });\n return;\n }\n\n // 2. If pathLocale exists, handle possible mismatch with cookie\n handleExistingPathLocale({\n req,\n res,\n next,\n originalPath,\n pathLocale,\n cookieLocale,\n });\n};\n\n/**\n * Handles requests where the locale is missing from the URL pathname.\n * We detect a locale from cookie / headers / default, then either redirect or rewrite.\n */\nconst handleMissingPathLocale = ({\n req,\n res,\n next,\n originalPath,\n cookieLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n cookieLocale?: Locales;\n}) => {\n // 1. Choose the best locale\n let locale = (cookieLocale ??\n localeDetector(\n req.headers as Record<string, string>,\n supportedLocales,\n defaultLocale\n )) as Locales;\n\n // 2. If still invalid, fallback\n if (!supportedLocales.includes(locale)) {\n locale = defaultLocale;\n }\n\n // 3. Construct new path\n const newPath = constructPath(locale, originalPath);\n\n // If we always prefix default or if this is not the default locale, do a 301 redirect\n // so that the user sees the locale in the URL.\n if (prefixDefault || locale !== defaultLocale) {\n return redirectUrl(res, newPath);\n }\n\n // If we do NOT prefix the default locale, just rewrite in place\n rewriteUrl(req, res, newPath, locale);\n return next();\n};\n\n/**\n * Handles requests where the locale prefix is present in the pathname.\n * We verify if the cookie locale differs from the path locale; if so, handle.\n */\nconst handleExistingPathLocale = ({\n req,\n res,\n next,\n originalPath,\n pathLocale,\n cookieLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n pathLocale: Locales;\n cookieLocale?: Locales;\n}) => {\n // 1. If the cookie locale is set and differs from the path locale,\n // and we're not forcing the cookie to always override\n if (\n cookieLocale &&\n cookieLocale !== pathLocale &&\n serverSetCookie !== 'always'\n ) {\n // We want to swap out the pathLocale with the cookieLocale\n const newPath = originalPath.replace(`/${pathLocale}`, `/${cookieLocale}`);\n const finalPath = constructPath(cookieLocale, newPath.replace(/^\\/+/, '/'));\n return redirectUrl(res, finalPath);\n }\n\n // 2. Otherwise, handle default-locale prefix if needed\n handleDefaultLocaleRedirect({\n req,\n res,\n next,\n originalPath,\n pathLocale,\n });\n};\n\n/**\n * If the path locale is the default locale but we don't want to prefix the default, remove it.\n */\nconst handleDefaultLocaleRedirect = ({\n req,\n res,\n next,\n originalPath,\n pathLocale,\n}: {\n req: Connect.IncomingMessage;\n res: ServerResponse<IncomingMessage>;\n next: Connect.NextFunction;\n originalPath: string;\n pathLocale: Locales;\n}) => {\n // If we don't prefix default AND the path locale is the default locale -> remove it\n if (!prefixDefault && pathLocale === defaultLocale) {\n // Remove the default locale part from the path\n const newPath = originalPath.replace(`/${defaultLocale}`, '') ?? '/';\n rewriteUrl(req, res, newPath, pathLocale);\n return next();\n }\n\n // If we do prefix default or pathLocale != default, keep as is, but rewrite headers\n rewriteUrl(req, res, originalPath, pathLocale);\n return next();\n};\n"],"mapp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;AAAA,EACA;AACF,MAMM;AAEJ,MAAI,CAAC,iBAAiB,eAAe,eAAe;AAElD,UAAM,UAAU,aAAa,QAAQ,IAAI,aAAa,IAAI,EAAE,KAAK;AACjE,eAAW,KAAK,KAAK,SAAS,UAAU;AACxC,WAAO,KAAK;AAAA,EACd;AAGA,aAAW,KAAK,KAAK,cAAc,UAAU;AAC7C,SAAO,KAAK;AACd;","names":[]}
@@ -0,0 +1,52 @@
1
+ import { join, relative, resolve } from "path";
2
+ import { prepareIntlayer, watch } from "@intlayer/chokidar";
3
+ import { getConfiguration } from "@intlayer/config";
4
+ const intlayerPlugin = (_pluginOptions = {}) => ({
5
+ name: "vite-intlayer-plugin",
6
+ config: (config) => {
7
+ const intlayerConfig = getConfiguration();
8
+ const {
9
+ mainDir,
10
+ configDir,
11
+ baseDir,
12
+ watch: isWatchMode
13
+ } = intlayerConfig.content;
14
+ const dictionariesPath = join(mainDir, "dictionaries.mjs");
15
+ const relativeDictionariesPath = relative(baseDir, dictionariesPath);
16
+ const configurationPath = join(configDir, "configuration.json");
17
+ const relativeConfigurationPath = relative(baseDir, configurationPath);
18
+ config.resolve = {
19
+ ...config.resolve,
20
+ alias: {
21
+ ...config.resolve?.alias,
22
+ "@intlayer/dictionaries-entry": resolve(relativeDictionariesPath),
23
+ "@intlayer/config/built": resolve(relativeConfigurationPath)
24
+ }
25
+ };
26
+ if (isWatchMode) {
27
+ config.optimizeDeps = {
28
+ ...config.optimizeDeps,
29
+ exclude: [
30
+ ...config.optimizeDeps?.exclude ?? [],
31
+ "@intlayer/dictionaries-entry",
32
+ "@intlayer/config/built"
33
+ ]
34
+ };
35
+ }
36
+ return config;
37
+ },
38
+ configureServer: async () => {
39
+ const intlayerConfig = getConfiguration();
40
+ if (intlayerConfig.content.watch) {
41
+ watch({ configuration: intlayerConfig });
42
+ }
43
+ },
44
+ buildStart: async () => {
45
+ const intlayerConfig = getConfiguration();
46
+ await prepareIntlayer(intlayerConfig);
47
+ }
48
+ });
49
+ export {
50
+ intlayerPlugin
51
+ };
52
+ //# sourceMappingURL=intlayerPlugin.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/intlayerPlugin.ts"],"sourcesContent":["import { join, relative, resolve } from 'path';\nimport { prepareIntlayer, watch } from '@intlayer/chokidar';\nimport { getConfiguration } from '@intlayer/config';\n// @ts-ignore - Fix error Module '\"vite\"' has no exported member\nimport { type PluginOption } from 'vite';\n\n// Plugin options type definition\ntype PluginOptions = {\n // Custom options for your plugin, if any\n};\n\n/**\n *\n * A Vite plugin that integrates Intlayer configuration into the build process\n *\n * ```ts\n * // Example usage of the plugin in a Vite configuration\n * export default defineConfig({\n * plugins: [ intlayerPlugin() ],\n * });\n * ```\n * */\nexport const intlayerPlugin = (\n _pluginOptions: PluginOptions = {}\n): PluginOption => ({\n name: 'vite-intlayer-plugin',\n\n config: (config) => {\n const intlayerConfig = getConfiguration();\n const {\n mainDir,\n configDir,\n baseDir,\n watch: isWatchMode,\n } = intlayerConfig.content;\n\n const dictionariesPath = join(mainDir, 'dictionaries.mjs');\n const relativeDictionariesPath = relative(baseDir, dictionariesPath);\n\n const configurationPath = join(configDir, 'configuration.json');\n const relativeConfigurationPath = relative(baseDir, configurationPath);\n\n // Update Vite's resolve alias\n config.resolve = {\n ...config.resolve,\n alias: {\n ...config.resolve?.alias,\n '@intlayer/dictionaries-entry': resolve(relativeDictionariesPath),\n '@intlayer/config/built': resolve(relativeConfigurationPath),\n },\n };\n\n if (isWatchMode) {\n // Ajout de l'option optimizeDeps.exclude\n config.optimizeDeps = {\n ...config.optimizeDeps,\n exclude: [\n ...(config.optimizeDeps?.exclude ?? []),\n '@intlayer/dictionaries-entry',\n '@intlayer/config/built',\n ],\n };\n }\n\n return config;\n },\n\n configureServer: async () => {\n // Runs when the dev server starts\n const intlayerConfig = getConfiguration();\n\n if (intlayerConfig.content.watch) {\n // Start watching (assuming watch is also async)\n watch({ configuration: intlayerConfig });\n }\n },\n\n buildStart: async () => {\n // Code to run when Vite build starts\n const intlayerConfig = getConfiguration();\n await prepareIntlayer(intlayerConfig);\n },\n});\n"],"mappings":"AAAA,SAAS,MAAM,UAAU,eAAe;AACxC,SAAS,iBAAiB,aAAa;AACvC,SAAS,wBAAwB;AAoB1B,MAAM,iBAAiB,CAC5B,iBAAgC,CAAC,OACf;AAAA,EAClB,MAAM;AAAA,EAEN,QAAQ,CAAC,WAAW;AAClB,UAAM,iBAAiB,iBAAiB;AACxC,UAAM;AAAA,MACJ;AAAA,MACA;AAAA,MACA;AAAA,MACA,OAAO;AAAA,IACT,IAAI,eAAe;AAEnB,UAAM,mBAAmB,KAAK,SAAS,kBAAkB;AACzD,UAAM,2BAA2B,SAAS,SAAS,gBAAgB;AAEnE,UAAM,oBAAoB,KAAK,WAAW,oBAAoB;AAC9D,UAAM,4BAA4B,SAAS,SAAS,iBAAiB;AAGrE,WAAO,UAAU;AAAA,MACf,GAAG,OAAO;AAAA,MACV,OAAO;AAAA,QACL,GAAG,OAAO,SAAS;AAAA,QACnB,gCAAgC,QAAQ,wBAAwB;AAAA,QAChE,0BAA0B,QAAQ,yBAAyB;AAAA,MAC7D;AAAA,IACF;AAEA,QAAI,aAAa;AAEf,aAAO,eAAe;AAAA,QACpB,GAAG,OAAO;AAAA,QACV,SAAS;AAAA,UACP,GAAI,OAAO,cAAc,WAAW,CAAC;AAAA,UACrC;AAAA,UACA;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AAAA,EAEA,iBAAiB,YAAY;AAE3B,UAAM,iBAAiB,iBAAiB;AAExC,QAAI,eAAe,QAAQ,OAAO;AAEhC,YAAM,EAAE,eAAe,eAAe,CAAC;AAAA,IACzC;AAAA,EACF;AAAA,EAEA,YAAY,YAAY;AAEtB,UAAM,iBAAiB,iBAAiB;AACxC,UAAM,gBAAgB,cAAc;AAAA,EACtC;AACF;","names":[]}
@@ -0,0 +1,3 @@
1
+ export * from './intlayerPlugin';
2
+ export * from './intlayerMiddlewarePlugin';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,kBAAkB,CAAC;AACjC,cAAc,4BAA4B,CAAC"}
@@ -0,0 +1,6 @@
1
+ import type { Plugin } from 'vite';
2
+ /**
3
+ * A Vite plugin that integrates a logic similar to the Next.js intlayer middleware.
4
+ */
5
+ export declare const intLayerMiddlewarePlugin: () => Plugin;
6
+ //# sourceMappingURL=intlayerMiddlewarePlugin.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"intlayerMiddlewarePlugin.d.ts","sourceRoot":"","sources":["../../src/intlayerMiddlewarePlugin.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAW,MAAM,EAAE,MAAM,MAAM,CAAC;AA0B5C;;GAEG;AACH,eAAO,MAAM,wBAAwB,QAAO,MAiD3C,CAAC"}
@@ -0,0 +1,16 @@
1
+ import { type PluginOption } from 'vite';
2
+ type PluginOptions = {};
3
+ /**
4
+ *
5
+ * A Vite plugin that integrates Intlayer configuration into the build process
6
+ *
7
+ * ```ts
8
+ * // Example usage of the plugin in a Vite configuration
9
+ * export default defineConfig({
10
+ * plugins: [ intlayerPlugin() ],
11
+ * });
12
+ * ```
13
+ * */
14
+ export declare const intlayerPlugin: (_pluginOptions?: PluginOptions) => PluginOption;
15
+ export {};
16
+ //# sourceMappingURL=intlayerPlugin.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"intlayerPlugin.d.ts","sourceRoot":"","sources":["../../src/intlayerPlugin.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,KAAK,YAAY,EAAE,MAAM,MAAM,CAAC;AAGzC,KAAK,aAAa,GAAG,EAEpB,CAAC;AAEF;;;;;;;;;;MAUM;AACN,eAAO,MAAM,cAAc,GACzB,iBAAgB,aAAkB,KACjC,YA0DD,CAAC"}
package/package.json ADDED
@@ -0,0 +1,103 @@
1
+ {
2
+ "name": "preact-intlayer",
3
+ "version": "5.3.11",
4
+ "private": false,
5
+ "description": "Easily internationalize i18n your Preact applications with type-safe multilingual content management.",
6
+ "keywords": [
7
+ "intlayer",
8
+ "data",
9
+ "internationalization",
10
+ "multilingual",
11
+ "i18n",
12
+ "typescript",
13
+ "preact"
14
+ ],
15
+ "homepage": "https://intlayer.org",
16
+ "bugs": {
17
+ "url": "https://github.com/aymericzip/intlayer/issues"
18
+ },
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/aymericzip/intlayer.git"
22
+ },
23
+ "license": "Apache-2.0",
24
+ "author": {
25
+ "name": "Aymeric PINEAU",
26
+ "url": "https://github.com/aymericzip"
27
+ },
28
+ "contributors": [
29
+ {
30
+ "name": "Aymeric Pineau",
31
+ "email": "ay.pineau@gmail.com",
32
+ "url": "https://github.com/aymericzip"
33
+ }
34
+ ],
35
+ "sideEffects": false,
36
+ "exports": {
37
+ ".": {
38
+ "types": "./dist/types/index.d.ts",
39
+ "require": "./dist/cjs/index.cjs",
40
+ "import": "./dist/esm/index.mjs"
41
+ },
42
+ "./package.json": "./package.json"
43
+ },
44
+ "main": "dist/cjs/index.cjs",
45
+ "module": "dist/esm/index.mjs",
46
+ "types": "dist/types/index.d.ts",
47
+ "typesVersions": {
48
+ "*": {
49
+ "package.json": [
50
+ "./package.json"
51
+ ]
52
+ }
53
+ },
54
+ "files": [
55
+ "./dist",
56
+ "./package.json"
57
+ ],
58
+ "dependencies": {
59
+ "@intlayer/config": "5.3.11",
60
+ "@intlayer/core": "5.3.11",
61
+ "@intlayer/chokidar": "5.3.11"
62
+ },
63
+ "devDependencies": {
64
+ "@types/node": "^22.13.10",
65
+ "@typescript-eslint/parser": "^8.27.0",
66
+ "concurrently": "^9.1.2",
67
+ "eslint": "^9.22.0",
68
+ "prettier": "^3.5.3",
69
+ "rimraf": "^6.0.1",
70
+ "tsc-alias": "^1.8.11",
71
+ "tsup": "^8.4.0",
72
+ "typescript": "^5.8.2",
73
+ "@utils/eslint-config": "1.0.4",
74
+ "@utils/ts-config": "1.0.4",
75
+ "@utils/tsup-config": "1.0.4",
76
+ "@utils/ts-config-types": "1.0.4"
77
+ },
78
+ "peerDependencies": {
79
+ "@intlayer/chokidar": "5.3.11",
80
+ "@intlayer/config": "5.3.11",
81
+ "@intlayer/core": "5.3.11"
82
+ },
83
+ "engines": {
84
+ "node": ">=14.18"
85
+ },
86
+ "bug": {
87
+ "url": "https://github.com/aymericzip/intlayer/issues"
88
+ },
89
+ "scripts": {
90
+ "build": "pnpm build:package & pnpm build:types",
91
+ "build:package": "tsup",
92
+ "build:types": "tsc --project ./tsconfig.types.json && tsc-alias --project ./tsconfig.types.json",
93
+ "clean": "rimraf ./dist",
94
+ "dev": "concurrently --prefix none \"tsup --watch\" \"tsc --project ./tsconfig.types.json --watch\" \"tsc-alias --project ./tsconfig.types.json --watch\"",
95
+ "lint": "eslint . --cache",
96
+ "lint:fix": "eslint . --cache --fix",
97
+ "prettier": "prettier . --check",
98
+ "prettier:fix": "prettier . --write",
99
+ "reset": "pnpm clean & pnpm build",
100
+ "test": "",
101
+ "typecheck": "tsup --project ./tsconfig.json --noEmit"
102
+ }
103
+ }