react-intlayer 3.5.4 → 3.5.6

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.
Files changed (78) hide show
  1. package/README.md +5 -5
  2. package/dist/cjs/cli/react-intlayer.cjs +4 -4
  3. package/dist/cjs/cli/react-intlayer.cjs.map +1 -1
  4. package/dist/cjs/client/index.cjs +3 -0
  5. package/dist/cjs/client/index.cjs.map +1 -1
  6. package/dist/cjs/client/useIntlayerAsync.cjs +55 -0
  7. package/dist/cjs/client/useIntlayerAsync.cjs.map +1 -0
  8. package/dist/cjs/distantDictionary/fetchDistantDictionary.cjs +59 -0
  9. package/dist/cjs/distantDictionary/fetchDistantDictionary.cjs.map +1 -0
  10. package/dist/cjs/editor/ContentSelectorWrapper.cjs.map +1 -1
  11. package/dist/cjs/editor/IntlayerEditorProvider.cjs +5 -1
  12. package/dist/cjs/editor/IntlayerEditorProvider.cjs.map +1 -1
  13. package/dist/cjs/editor/renderContentEditor.cjs.map +1 -1
  14. package/dist/cjs/getDictionary.cjs +1 -1
  15. package/dist/cjs/getDictionary.cjs.map +1 -1
  16. package/dist/cjs/getIntlayer.cjs.map +1 -1
  17. package/dist/cjs/getIntlayerAsync.cjs +42 -0
  18. package/dist/cjs/getIntlayerAsync.cjs.map +1 -0
  19. package/dist/cjs/index.cjs +2 -0
  20. package/dist/cjs/index.cjs.map +1 -1
  21. package/dist/cjs/processDictionary/contentDictionary.cjs.map +1 -1
  22. package/dist/cjs/processDictionary/index.cjs +13 -13
  23. package/dist/cjs/processDictionary/index.cjs.map +1 -1
  24. package/dist/cjs/utils/PoweredByMeta/index.cjs +40 -0
  25. package/dist/cjs/utils/PoweredByMeta/index.cjs.map +1 -0
  26. package/dist/cjs/vite/intlayerMiddlewarePlugin.cjs +185 -59
  27. package/dist/cjs/vite/intlayerMiddlewarePlugin.cjs.map +1 -1
  28. package/dist/esm/cli/react-intlayer.mjs +5 -5
  29. package/dist/esm/cli/react-intlayer.mjs.map +1 -1
  30. package/dist/esm/client/index.mjs +2 -0
  31. package/dist/esm/client/index.mjs.map +1 -1
  32. package/dist/esm/client/useIntlayerAsync.mjs +34 -0
  33. package/dist/esm/client/useIntlayerAsync.mjs.map +1 -0
  34. package/dist/esm/distantDictionary/fetchDistantDictionary.mjs +36 -0
  35. package/dist/esm/distantDictionary/fetchDistantDictionary.mjs.map +1 -0
  36. package/dist/esm/editor/ContentSelectorWrapper.mjs.map +1 -1
  37. package/dist/esm/editor/IntlayerEditorProvider.mjs +6 -2
  38. package/dist/esm/editor/IntlayerEditorProvider.mjs.map +1 -1
  39. package/dist/esm/editor/renderContentEditor.mjs.map +1 -1
  40. package/dist/esm/getDictionary.mjs +1 -1
  41. package/dist/esm/getDictionary.mjs.map +1 -1
  42. package/dist/esm/getIntlayer.mjs.map +1 -1
  43. package/dist/esm/getIntlayerAsync.mjs +19 -0
  44. package/dist/esm/getIntlayerAsync.mjs.map +1 -0
  45. package/dist/esm/index.mjs +2 -0
  46. package/dist/esm/index.mjs.map +1 -1
  47. package/dist/esm/processDictionary/index.mjs +13 -13
  48. package/dist/esm/processDictionary/index.mjs.map +1 -1
  49. package/dist/esm/utils/PoweredByMeta/index.mjs +17 -0
  50. package/dist/esm/utils/PoweredByMeta/index.mjs.map +1 -0
  51. package/dist/esm/vite/intlayerMiddlewarePlugin.mjs +186 -63
  52. package/dist/esm/vite/intlayerMiddlewarePlugin.mjs.map +1 -1
  53. package/dist/types/client/index.d.ts +1 -0
  54. package/dist/types/client/index.d.ts.map +1 -1
  55. package/dist/types/client/useIntlayerAsync.d.ts +15 -0
  56. package/dist/types/client/useIntlayerAsync.d.ts.map +1 -0
  57. package/dist/types/distantDictionary/fetchDistantDictionary.d.ts +6 -0
  58. package/dist/types/distantDictionary/fetchDistantDictionary.d.ts.map +1 -0
  59. package/dist/types/editor/ContentSelectorWrapper.d.ts +1 -1
  60. package/dist/types/editor/ContentSelectorWrapper.d.ts.map +1 -1
  61. package/dist/types/editor/IntlayerEditorProvider.d.ts.map +1 -1
  62. package/dist/types/editor/renderContentEditor.d.ts +1 -1
  63. package/dist/types/editor/renderContentEditor.d.ts.map +1 -1
  64. package/dist/types/getIntlayer.d.ts +1 -2
  65. package/dist/types/getIntlayer.d.ts.map +1 -1
  66. package/dist/types/getIntlayerAsync.d.ts +13 -0
  67. package/dist/types/getIntlayerAsync.d.ts.map +1 -0
  68. package/dist/types/index.d.ts +1 -1
  69. package/dist/types/index.d.ts.map +1 -1
  70. package/dist/types/processDictionary/contentDictionary.d.ts +1 -1
  71. package/dist/types/processDictionary/contentDictionary.d.ts.map +1 -1
  72. package/dist/types/processDictionary/index.d.ts +2 -2
  73. package/dist/types/processDictionary/index.d.ts.map +1 -1
  74. package/dist/types/utils/PoweredByMeta/index.d.ts +3 -0
  75. package/dist/types/utils/PoweredByMeta/index.d.ts.map +1 -0
  76. package/dist/types/vite/intlayerMiddlewarePlugin.d.ts +3 -10
  77. package/dist/types/vite/intlayerMiddlewarePlugin.d.ts.map +1 -1
  78. package/package.json +16 -15
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ "use client";
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+ var PoweredByMeta_exports = {};
21
+ __export(PoweredByMeta_exports, {
22
+ PoweredByMeta: () => PoweredByMeta
23
+ });
24
+ module.exports = __toCommonJS(PoweredByMeta_exports);
25
+ var import_react = require("react");
26
+ const PoweredByMeta = () => {
27
+ if (process.env.NODE_ENV !== "production") return null;
28
+ (0, import_react.useEffect)(() => {
29
+ const metaTag = document.createElement("meta");
30
+ metaTag.name = "content-powered-by";
31
+ metaTag.content = "Intlayer - https://intlayer.org";
32
+ document.head.appendChild(metaTag);
33
+ }, []);
34
+ return null;
35
+ };
36
+ // Annotate the CommonJS export names for ESM import in node:
37
+ 0 && (module.exports = {
38
+ PoweredByMeta
39
+ });
40
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/utils/PoweredByMeta/index.ts"],"sourcesContent":["'use client';\n\nimport { type FC, useEffect } from 'react';\n\nexport const PoweredByMeta: FC = () => {\n if (process.env.NODE_ENV !== 'production') return null;\n\n useEffect(() => {\n const metaTag = document.createElement('meta');\n metaTag.name = 'content-powered-by';\n metaTag.content = 'Intlayer - https://intlayer.org';\n document.head.appendChild(metaTag);\n }, []);\n\n return null; // This component does not render anything visible\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,mBAAmC;AAE5B,MAAM,gBAAoB,MAAM;AACrC,MAAI,QAAQ,IAAI,aAAa,aAAc,QAAO;AAElD,8BAAU,MAAM;AACd,UAAM,UAAU,SAAS,cAAc,MAAM;AAC7C,YAAQ,OAAO;AACf,YAAQ,UAAU;AAClB,aAAS,KAAK,YAAY,OAAO;AAAA,EACnC,GAAG,CAAC,CAAC;AAEL,SAAO;AACT;","names":[]}
@@ -21,75 +21,201 @@ __export(intlayerMiddlewarePlugin_exports, {
21
21
  intLayerMiddlewarePlugin: () => intLayerMiddlewarePlugin
22
22
  });
23
23
  module.exports = __toCommonJS(intlayerMiddlewarePlugin_exports);
24
+ var import_url = require("url");
24
25
  var import_config = require("@intlayer/config");
25
26
  var import_core = require("@intlayer/core");
26
27
  const intlayerConfig = (0, import_config.getConfiguration)();
27
28
  const { internationalization, middleware } = intlayerConfig;
28
29
  const { locales: supportedLocales, defaultLocale } = internationalization;
29
- const { cookieName, headerName, prefixDefault } = middleware;
30
- const intLayerMiddlewarePlugin = (_pluginOptions = {}) => ({
31
- name: "vite-intlayer-middleware-plugin",
32
- configureServer: (server) => {
33
- server.middlewares.use((req, res, next) => {
34
- if (req.url?.startsWith("/node_modules") || req.url?.startsWith("/@") || req.url?.split("?")[0].match(/\.[a-z]+$/i)) {
35
- return next();
36
- }
37
- const originalUrl = req.url ?? "/";
38
- const cookies = parseCookies(req.headers.cookie ?? "");
39
- const cookieLocale = cookies[cookieName];
40
- const headers = req.headers;
41
- const headerLocale = headers[headerName];
42
- const pathParts = originalUrl.split("?")[0].split("/").filter(Boolean);
43
- const firstPart = pathParts[0];
44
- const pathLocale = pathParts[0] && supportedLocales.includes(firstPart) ? pathParts[0] : void 0;
45
- if (!pathLocale) {
46
- let locale;
47
- if (!locale && cookieLocale && supportedLocales.includes(cookieLocale)) {
48
- locale = cookieLocale;
49
- }
50
- if (!locale && headerLocale && supportedLocales.includes(headerLocale)) {
51
- locale = headerLocale;
52
- }
53
- if (!locale) {
54
- const detectedLocale = (0, import_core.localeDetector)(
55
- headers,
56
- supportedLocales,
57
- defaultLocale
58
- );
59
- locale = detectedLocale;
60
- }
61
- req.url = formatUrlWithLocale(originalUrl, locale);
62
- if (req.url === originalUrl) {
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)) {
63
44
  return next();
64
45
  }
65
- res.writeHead(301, { Location: req.url });
66
- return res.end();
67
- }
68
- if (pathLocale.toString() === defaultLocale.toString() && !prefixDefault) {
69
- req.url = (0, import_core.getPathWithoutLocale)(originalUrl, supportedLocales);
70
- res.writeHead(301, { Location: req.url });
71
- return res.end();
72
- }
73
- return next();
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
74
150
  });
151
+ return;
75
152
  }
76
- });
77
- const parseCookies = (cookieHeader) => cookieHeader.split(";").reduce(
78
- (acc, cookie) => {
79
- const [key, val] = cookie.trim().split("=");
80
- acc[key] = val;
81
- return acc;
82
- },
83
- {}
84
- );
85
- const formatUrlWithLocale = (url, locale) => {
86
- if (locale.toString() === defaultLocale.toString()) {
87
- if (prefixDefault) {
88
- return `/${locale}${url}`;
89
- }
90
- return url;
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();
91
216
  }
92
- return `/${locale}${url}`;
217
+ rewriteUrl(req, res, originalPath, pathLocale);
218
+ return next();
93
219
  };
94
220
  // Annotate the CommonJS export names for ESM import in node:
95
221
  0 && (module.exports = {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/vite/intlayerMiddlewarePlugin.ts"],"sourcesContent":["import { getConfiguration, Locales } from '@intlayer/config';\nimport {\n getPathWithoutLocale,\n localeDetector as localeDetector,\n} from '@intlayer/core';\n// @ts-ignore - Fix error Module '\"vite\"' has no exported member\nimport { type Plugin } from 'vite';\n\nconst intlayerConfig = getConfiguration();\nconst { internationalization, middleware } = intlayerConfig;\n\nconst { locales: supportedLocales, defaultLocale } = internationalization;\nconst { cookieName, headerName, prefixDefault } = middleware;\n\n/**\n * A Vite plugin that integrates IntLayer middleware into the build process\n *\n * ```ts\n * // Example usage of the plugin in a Vite configuration\n * export default defineConfig({\n * plugins: [ intLayerMiddlewarePlugin() ],\n * });\n * ```\n */\nexport const intLayerMiddlewarePlugin = (_pluginOptions = {}): Plugin => ({\n name: 'vite-intlayer-middleware-plugin',\n\n configureServer: (server) => {\n // server.middlewares is a Connect instance; you can add middleware here\n server.middlewares.use((req, res, next) => {\n // Skip if request looks like a static asset or internal Vite request\n if (\n req.url?.startsWith('/node_modules') ||\n req.url?.startsWith('/@') ||\n req.url?.split('?')[0].match(/\\.[a-z]+$/i) // checks if URL has a file extension\n ) {\n return next();\n }\n\n const originalUrl = req.url ?? '/';\n\n const cookies = parseCookies(req.headers.cookie ?? '');\n const cookieLocale = cookies[cookieName];\n\n const headers = req.headers;\n const headerLocale = headers[headerName];\n\n const pathParts = originalUrl.split('?')[0].split('/').filter(Boolean);\n\n const firstPart = pathParts[0] as unknown as Locales;\n\n const pathLocale =\n pathParts[0] && supportedLocales.includes(firstPart)\n ? pathParts[0]\n : undefined;\n\n if (!pathLocale) {\n let locale;\n\n // Try to get the locale from the request cookies\n if (\n !locale &&\n cookieLocale &&\n supportedLocales.includes(cookieLocale as Locales)\n ) {\n locale = cookieLocale as Locales;\n }\n\n // Try to get the locale from the request headers\n if (\n !locale &&\n headerLocale &&\n supportedLocales.includes(headerLocale as Locales)\n ) {\n locale = headerLocale as Locales;\n }\n\n // Get the locale from the negotiator\n if (!locale) {\n const detectedLocale = localeDetector(\n headers as Record<string, string>,\n supportedLocales,\n defaultLocale\n );\n locale = detectedLocale;\n }\n\n // Instead of redirecting, try rewriting internally:\n req.url = formatUrlWithLocale(originalUrl, locale);\n\n if (req.url === originalUrl) {\n return next();\n }\n\n res.writeHead(301, { Location: req.url });\n return res.end();\n }\n\n if (\n pathLocale.toString() === defaultLocale.toString() &&\n !prefixDefault\n ) {\n req.url = getPathWithoutLocale(originalUrl, supportedLocales);\n\n res.writeHead(301, { Location: req.url });\n return res.end();\n }\n\n return next();\n });\n },\n});\n\n// Simple cookie parser:\nconst parseCookies = (cookieHeader: string) =>\n cookieHeader.split(';').reduce(\n (acc, cookie) => {\n const [key, val] = cookie.trim().split('=');\n acc[key as keyof typeof acc] = val;\n return acc;\n },\n {} as Record<string, string>\n );\n\nconst formatUrlWithLocale = (url: string, locale: Locales) => {\n if (locale.toString() === defaultLocale.toString()) {\n if (prefixDefault) {\n return `/${locale}${url}`;\n }\n\n return url;\n }\n\n return `/${locale}${url}`;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAA0C;AAC1C,kBAGO;AAIP,MAAM,qBAAiB,gCAAiB;AACxC,MAAM,EAAE,sBAAsB,WAAW,IAAI;AAE7C,MAAM,EAAE,SAAS,kBAAkB,cAAc,IAAI;AACrD,MAAM,EAAE,YAAY,YAAY,cAAc,IAAI;AAY3C,MAAM,2BAA2B,CAAC,iBAAiB,CAAC,OAAe;AAAA,EACxE,MAAM;AAAA,EAEN,iBAAiB,CAAC,WAAW;AAE3B,WAAO,YAAY,IAAI,CAAC,KAAK,KAAK,SAAS;AAEzC,UACE,IAAI,KAAK,WAAW,eAAe,KACnC,IAAI,KAAK,WAAW,IAAI,KACxB,IAAI,KAAK,MAAM,GAAG,EAAE,CAAC,EAAE,MAAM,YAAY,GACzC;AACA,eAAO,KAAK;AAAA,MACd;AAEA,YAAM,cAAc,IAAI,OAAO;AAE/B,YAAM,UAAU,aAAa,IAAI,QAAQ,UAAU,EAAE;AACrD,YAAM,eAAe,QAAQ,UAAU;AAEvC,YAAM,UAAU,IAAI;AACpB,YAAM,eAAe,QAAQ,UAAU;AAEvC,YAAM,YAAY,YAAY,MAAM,GAAG,EAAE,CAAC,EAAE,MAAM,GAAG,EAAE,OAAO,OAAO;AAErE,YAAM,YAAY,UAAU,CAAC;AAE7B,YAAM,aACJ,UAAU,CAAC,KAAK,iBAAiB,SAAS,SAAS,IAC/C,UAAU,CAAC,IACX;AAEN,UAAI,CAAC,YAAY;AACf,YAAI;AAGJ,YACE,CAAC,UACD,gBACA,iBAAiB,SAAS,YAAuB,GACjD;AACA,mBAAS;AAAA,QACX;AAGA,YACE,CAAC,UACD,gBACA,iBAAiB,SAAS,YAAuB,GACjD;AACA,mBAAS;AAAA,QACX;AAGA,YAAI,CAAC,QAAQ;AACX,gBAAM,qBAAiB;AAAA,YACrB;AAAA,YACA;AAAA,YACA;AAAA,UACF;AACA,mBAAS;AAAA,QACX;AAGA,YAAI,MAAM,oBAAoB,aAAa,MAAM;AAEjD,YAAI,IAAI,QAAQ,aAAa;AAC3B,iBAAO,KAAK;AAAA,QACd;AAEA,YAAI,UAAU,KAAK,EAAE,UAAU,IAAI,IAAI,CAAC;AACxC,eAAO,IAAI,IAAI;AAAA,MACjB;AAEA,UACE,WAAW,SAAS,MAAM,cAAc,SAAS,KACjD,CAAC,eACD;AACA,YAAI,UAAM,kCAAqB,aAAa,gBAAgB;AAE5D,YAAI,UAAU,KAAK,EAAE,UAAU,IAAI,IAAI,CAAC;AACxC,eAAO,IAAI,IAAI;AAAA,MACjB;AAEA,aAAO,KAAK;AAAA,IACd,CAAC;AAAA,EACH;AACF;AAGA,MAAM,eAAe,CAAC,iBACpB,aAAa,MAAM,GAAG,EAAE;AAAA,EACtB,CAAC,KAAK,WAAW;AACf,UAAM,CAAC,KAAK,GAAG,IAAI,OAAO,KAAK,EAAE,MAAM,GAAG;AAC1C,QAAI,GAAuB,IAAI;AAC/B,WAAO;AAAA,EACT;AAAA,EACA,CAAC;AACH;AAEF,MAAM,sBAAsB,CAAC,KAAa,WAAoB;AAC5D,MAAI,OAAO,SAAS,MAAM,cAAc,SAAS,GAAG;AAClD,QAAI,eAAe;AACjB,aAAO,IAAI,MAAM,GAAG,GAAG;AAAA,IACzB;AAEA,WAAO;AAAA,EACT;AAEA,SAAO,IAAI,MAAM,GAAG,GAAG;AACzB;","names":[]}
1
+ {"version":3,"sources":["../../../src/vite/intlayerMiddlewarePlugin.ts"],"sourcesContent":["import { 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;\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 =\n cookieLocale ??\n localeDetector(\n req.headers as Record<string, string>,\n supportedLocales,\n defaultLocale\n );\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"],"mappings":"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","names":[]}
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { ESMxCJSRequire } from "@intlayer/config";
2
+ import { ESMxCJSRequire, appLogger } from "@intlayer/config";
3
3
  import spawn from "cross-spawn";
4
4
  const args = process.argv.slice(2);
5
5
  const scriptIndex = args.findIndex(
@@ -25,13 +25,13 @@ switch (script) {
25
25
  });
26
26
  if (child.signal) {
27
27
  if (child.signal === "SIGKILL") {
28
- console.info(`
28
+ appLogger(`
29
29
  The build failed because the process exited too early.
30
30
  This probably means the system ran out of memory or someone called
31
31
  \`kill -9\` on the process.
32
32
  `);
33
33
  } else if (child.signal === "SIGTERM") {
34
- console.info(`
34
+ appLogger(`
35
35
  The build failed because the process exited too early.
36
36
  Someone might have called \`kill\` or \`killall\`, or the system could
37
37
  be shutting down.
@@ -43,8 +43,8 @@ switch (script) {
43
43
  break;
44
44
  }
45
45
  default:
46
- console.info(`Unknown script "${script}".`);
47
- console.info("Perhaps you need to update craco?");
46
+ appLogger(`Unknown script "${script}".`);
47
+ appLogger("Perhaps you need to update craco?");
48
48
  break;
49
49
  }
50
50
  //# sourceMappingURL=react-intlayer.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/cli/react-intlayer.ts"],"sourcesContent":["#!/usr/bin/env node\n\n/**\n * To make the setup easier, we are using craco to override the webpack configuration.\n * This script is used to run the craco scripts with the custom configuration.\n *\n * The script is based on the original craco script from create-react-app.\n */\n\nimport { ESMxCJSRequire } from '@intlayer/config';\nimport spawn from 'cross-spawn';\n\nconst args = process.argv.slice(2);\nconst scriptIndex = args.findIndex(\n (x) => x === 'build' || x === 'start' || x === 'test'\n);\nconst script = scriptIndex === -1 ? args[0] : args[scriptIndex];\n\nswitch (script) {\n case 'build':\n case 'start':\n case 'test': {\n const nodeArgs = scriptIndex > 0 ? args.slice(0, scriptIndex) : [];\n const scriptPath = ESMxCJSRequire.resolve(\n `@craco/craco/dist/scripts/${script}`\n );\n\n const scriptArgs = args.slice(scriptIndex + 1);\n const processArgs = nodeArgs\n .concat(scriptPath)\n .concat([\n ...scriptArgs,\n '--config',\n './node_modules/react-intlayer/dist/cjs/craco/craco.config.cjs',\n ]);\n\n const child = spawn.sync('node', processArgs, {\n stdio: 'inherit',\n });\n\n if (child.signal) {\n if (child.signal === 'SIGKILL') {\n console.info(`\n The build failed because the process exited too early.\n This probably means the system ran out of memory or someone called\n \\`kill -9\\` on the process.\n `);\n } else if (child.signal === 'SIGTERM') {\n console.info(`\n The build failed because the process exited too early.\n Someone might have called \\`kill\\` or \\`killall\\`, or the system could\n be shutting down.\n `);\n }\n\n process.exit(1);\n }\n\n process.exit(child.status ?? undefined);\n break;\n }\n default:\n console.info(`Unknown script \"${script}\".`);\n console.info('Perhaps you need to update craco?');\n break;\n}\n"],"mappings":";AASA,SAAS,sBAAsB;AAC/B,OAAO,WAAW;AAElB,MAAM,OAAO,QAAQ,KAAK,MAAM,CAAC;AACjC,MAAM,cAAc,KAAK;AAAA,EACvB,CAAC,MAAM,MAAM,WAAW,MAAM,WAAW,MAAM;AACjD;AACA,MAAM,SAAS,gBAAgB,KAAK,KAAK,CAAC,IAAI,KAAK,WAAW;AAE9D,QAAQ,QAAQ;AAAA,EACd,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK,QAAQ;AACX,UAAM,WAAW,cAAc,IAAI,KAAK,MAAM,GAAG,WAAW,IAAI,CAAC;AACjE,UAAM,aAAa,eAAe;AAAA,MAChC,6BAA6B,MAAM;AAAA,IACrC;AAEA,UAAM,aAAa,KAAK,MAAM,cAAc,CAAC;AAC7C,UAAM,cAAc,SACjB,OAAO,UAAU,EACjB,OAAO;AAAA,MACN,GAAG;AAAA,MACH;AAAA,MACA;AAAA,IACF,CAAC;AAEH,UAAM,QAAQ,MAAM,KAAK,QAAQ,aAAa;AAAA,MAC5C,OAAO;AAAA,IACT,CAAC;AAED,QAAI,MAAM,QAAQ;AAChB,UAAI,MAAM,WAAW,WAAW;AAC9B,gBAAQ,KAAK;AAAA;AAAA;AAAA;AAAA,aAIR;AAAA,MACP,WAAW,MAAM,WAAW,WAAW;AACrC,gBAAQ,KAAK;AAAA;AAAA;AAAA;AAAA,aAIR;AAAA,MACP;AAEA,cAAQ,KAAK,CAAC;AAAA,IAChB;AAEA,YAAQ,KAAK,MAAM,UAAU,MAAS;AACtC;AAAA,EACF;AAAA,EACA;AACE,YAAQ,KAAK,mBAAmB,MAAM,IAAI;AAC1C,YAAQ,KAAK,mCAAmC;AAChD;AACJ;","names":[]}
1
+ {"version":3,"sources":["../../../src/cli/react-intlayer.ts"],"sourcesContent":["#!/usr/bin/env node\n\n/**\n * To make the setup easier, we are using craco to override the webpack configuration.\n * This script is used to run the craco scripts with the custom configuration.\n *\n * The script is based on the original craco script from create-react-app.\n */\n\nimport { ESMxCJSRequire, appLogger } from '@intlayer/config';\nimport spawn from 'cross-spawn';\n\nconst args = process.argv.slice(2);\nconst scriptIndex = args.findIndex(\n (x) => x === 'build' || x === 'start' || x === 'test'\n);\nconst script = scriptIndex === -1 ? args[0] : args[scriptIndex];\n\nswitch (script) {\n case 'build':\n case 'start':\n case 'test': {\n const nodeArgs = scriptIndex > 0 ? args.slice(0, scriptIndex) : [];\n const scriptPath = ESMxCJSRequire.resolve(\n `@craco/craco/dist/scripts/${script}`\n );\n\n const scriptArgs = args.slice(scriptIndex + 1);\n const processArgs = nodeArgs\n .concat(scriptPath)\n .concat([\n ...scriptArgs,\n '--config',\n './node_modules/react-intlayer/dist/cjs/craco/craco.config.cjs',\n ]);\n\n const child = spawn.sync('node', processArgs, {\n stdio: 'inherit',\n });\n\n if (child.signal) {\n if (child.signal === 'SIGKILL') {\n appLogger(`\n The build failed because the process exited too early.\n This probably means the system ran out of memory or someone called\n \\`kill -9\\` on the process.\n `);\n } else if (child.signal === 'SIGTERM') {\n appLogger(`\n The build failed because the process exited too early.\n Someone might have called \\`kill\\` or \\`killall\\`, or the system could\n be shutting down.\n `);\n }\n\n process.exit(1);\n }\n\n process.exit(child.status ?? undefined);\n break;\n }\n default:\n appLogger(`Unknown script \"${script}\".`);\n appLogger('Perhaps you need to update craco?');\n break;\n}\n"],"mappings":";AASA,SAAS,gBAAgB,iBAAiB;AAC1C,OAAO,WAAW;AAElB,MAAM,OAAO,QAAQ,KAAK,MAAM,CAAC;AACjC,MAAM,cAAc,KAAK;AAAA,EACvB,CAAC,MAAM,MAAM,WAAW,MAAM,WAAW,MAAM;AACjD;AACA,MAAM,SAAS,gBAAgB,KAAK,KAAK,CAAC,IAAI,KAAK,WAAW;AAE9D,QAAQ,QAAQ;AAAA,EACd,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK,QAAQ;AACX,UAAM,WAAW,cAAc,IAAI,KAAK,MAAM,GAAG,WAAW,IAAI,CAAC;AACjE,UAAM,aAAa,eAAe;AAAA,MAChC,6BAA6B,MAAM;AAAA,IACrC;AAEA,UAAM,aAAa,KAAK,MAAM,cAAc,CAAC;AAC7C,UAAM,cAAc,SACjB,OAAO,UAAU,EACjB,OAAO;AAAA,MACN,GAAG;AAAA,MACH;AAAA,MACA;AAAA,IACF,CAAC;AAEH,UAAM,QAAQ,MAAM,KAAK,QAAQ,aAAa;AAAA,MAC5C,OAAO;AAAA,IACT,CAAC;AAED,QAAI,MAAM,QAAQ;AAChB,UAAI,MAAM,WAAW,WAAW;AAC9B,kBAAU;AAAA;AAAA;AAAA;AAAA,aAIL;AAAA,MACP,WAAW,MAAM,WAAW,WAAW;AACrC,kBAAU;AAAA;AAAA;AAAA;AAAA,aAIL;AAAA,MACP;AAEA,cAAQ,KAAK,CAAC;AAAA,IAChB;AAEA,YAAQ,KAAK,MAAM,UAAU,MAAS;AACtC;AAAA,EACF;AAAA,EACA;AACE,cAAU,mBAAmB,MAAM,IAAI;AACvC,cAAU,mCAAmC;AAC7C;AACJ;","names":[]}
@@ -5,6 +5,7 @@ import {
5
5
  IntlayerProvider
6
6
  } from './IntlayerProvider.mjs';
7
7
  import { useIntlayer } from './useIntlayer.mjs';
8
+ import { useIntlayerAsync } from './useIntlayerAsync.mjs';
8
9
  import { useDictionary } from './useDictionary.mjs';
9
10
  import { useLocaleBase } from './useLocaleBase.mjs';
10
11
  import { useLocale } from './useLocale.mjs';
@@ -25,6 +26,7 @@ export {
25
26
  t,
26
27
  useDictionary,
27
28
  useIntlayer,
29
+ useIntlayerAsync,
28
30
  useIntlayerContext,
29
31
  useLocale,
30
32
  useLocaleBase,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/client/index.ts"],"sourcesContent":["export {\n type IntlayerProviderProps,\n IntlayerClientContext,\n useIntlayerContext,\n IntlayerProvider,\n} from './IntlayerProvider';\nexport { useIntlayer } from './useIntlayer';\nexport { useDictionary } from './useDictionary';\nexport { useLocaleBase } from './useLocaleBase';\nexport { useLocale } from './useLocale';\nexport { useTraduction } from './useTraduction';\nexport {\n useLocaleCookie,\n localeCookie,\n setLocaleCookie,\n} from './useLocaleCookie';\nexport { getBrowserLocale } from './getBrowserLocale';\nexport { t } from './t';\n"],"mappings":";AAAA;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,mBAAmB;AAC5B,SAAS,qBAAqB;AAC9B,SAAS,qBAAqB;AAC9B,SAAS,iBAAiB;AAC1B,SAAS,qBAAqB;AAC9B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,wBAAwB;AACjC,SAAS,SAAS;","names":[]}
1
+ {"version":3,"sources":["../../../src/client/index.ts"],"sourcesContent":["export {\n type IntlayerProviderProps,\n IntlayerClientContext,\n useIntlayerContext,\n IntlayerProvider,\n} from './IntlayerProvider';\nexport { useIntlayer } from './useIntlayer';\nexport { useIntlayerAsync } from './useIntlayerAsync';\nexport { useDictionary } from './useDictionary';\nexport { useLocaleBase } from './useLocaleBase';\nexport { useLocale } from './useLocale';\nexport { useTraduction } from './useTraduction';\nexport {\n useLocaleCookie,\n localeCookie,\n setLocaleCookie,\n} from './useLocaleCookie';\nexport { getBrowserLocale } from './getBrowserLocale';\nexport { t } from './t';\n"],"mappings":";AAAA;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,mBAAmB;AAC5B,SAAS,wBAAwB;AACjC,SAAS,qBAAqB;AAC9B,SAAS,qBAAqB;AAC9B,SAAS,iBAAiB;AAC1B,SAAS,qBAAqB;AAC9B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,wBAAwB;AACjC,SAAS,SAAS;","names":[]}
@@ -0,0 +1,34 @@
1
+ "use client";
2
+ import "../chunk-ZD7AOCMD.mjs";
3
+ import { useContext, useEffect, useMemo, useState } from "react";
4
+ import {
5
+ getIntlayer
6
+ } from '../getIntlayer.mjs';
7
+ import { getIntlayerAsync } from '../getIntlayerAsync.mjs';
8
+ import { IntlayerClientContext } from './IntlayerProvider.mjs';
9
+ const useIntlayerAsync = (key, locale, isRenderEditor = true) => {
10
+ const { locale: currentLocale } = useContext(IntlayerClientContext);
11
+ const localeTarget = locale ?? currentLocale;
12
+ const localeDictionary = getIntlayer(key, localeTarget, isRenderEditor);
13
+ const [distantDictionary, setDistantDictionary] = useState(void 0);
14
+ const [isLoading, setIsLoading] = useState(false);
15
+ useEffect(() => {
16
+ setIsLoading(true);
17
+ getIntlayerAsync(key).then((distantDictionary2) => {
18
+ if (distantDictionary2) {
19
+ setDistantDictionary(distantDictionary2);
20
+ }
21
+ }).finally(() => {
22
+ setIsLoading(false);
23
+ });
24
+ }, []);
25
+ const dictionary = useMemo(
26
+ () => distantDictionary ?? localeDictionary,
27
+ [distantDictionary, localeDictionary]
28
+ );
29
+ return { ...dictionary, isLoading };
30
+ };
31
+ export {
32
+ useIntlayerAsync
33
+ };
34
+ //# sourceMappingURL=useIntlayerAsync.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/client/useIntlayerAsync.ts"],"sourcesContent":["'use client';\n\nimport type { Locales } from '@intlayer/config/client';\nimport { useContext, useEffect, useMemo, useState } from 'react';\nimport {\n DataFromDictionaryKey,\n type DictionaryKeys,\n getIntlayer,\n} from '../getIntlayer';\nimport { getIntlayerAsync } from '../getIntlayerAsync';\nimport { IntlayerClientContext } from './IntlayerProvider';\n\nexport type UseIntlayerAsync = <\n T extends DictionaryKeys,\n L extends Locales,\n R extends boolean = true,\n>(\n key: T,\n locale?: L,\n isRenderEditor?: R\n) => DataFromDictionaryKey<T, L, R> & { isLoading: boolean };\n\n/**\n * On the client side, Hook that picking one dictionary by its key and return the content\n *\n * This hook will prerender the locale dictionary and fetch simultaneously the distant dictionaries to hydrate it.\n *\n *\n * If the locale is not provided, it will use the locale from the client context\n */\nexport const useIntlayerAsync: UseIntlayerAsync = <T extends DictionaryKeys>(\n key: T,\n locale?: Locales,\n isRenderEditor = true\n) => {\n const { locale: currentLocale } = useContext(IntlayerClientContext);\n const localeTarget = locale ?? currentLocale;\n const localeDictionary = getIntlayer(key, localeTarget, isRenderEditor);\n const [distantDictionary, setDistantDictionary] = useState<\n typeof localeDictionary | null | undefined\n >(undefined);\n const [isLoading, setIsLoading] = useState(false);\n\n useEffect(() => {\n setIsLoading(true);\n\n getIntlayerAsync(key)\n .then((distantDictionary) => {\n if (distantDictionary) {\n setDistantDictionary(distantDictionary);\n }\n })\n .finally(() => {\n setIsLoading(false);\n });\n }, []);\n\n const dictionary = useMemo(\n () => distantDictionary ?? localeDictionary,\n [distantDictionary, localeDictionary]\n );\n\n return { ...dictionary, isLoading };\n};\n"],"mappings":";;AAGA,SAAS,YAAY,WAAW,SAAS,gBAAgB;AACzD;AAAA,EAGE;AAAA,OACK;AACP,SAAS,wBAAwB;AACjC,SAAS,6BAA6B;AAoB/B,MAAM,mBAAqC,CAChD,KACA,QACA,iBAAiB,SACd;AACH,QAAM,EAAE,QAAQ,cAAc,IAAI,WAAW,qBAAqB;AAClE,QAAM,eAAe,UAAU;AAC/B,QAAM,mBAAmB,YAAY,KAAK,cAAc,cAAc;AACtE,QAAM,CAAC,mBAAmB,oBAAoB,IAAI,SAEhD,MAAS;AACX,QAAM,CAAC,WAAW,YAAY,IAAI,SAAS,KAAK;AAEhD,YAAU,MAAM;AACd,iBAAa,IAAI;AAEjB,qBAAiB,GAAG,EACjB,KAAK,CAACA,uBAAsB;AAC3B,UAAIA,oBAAmB;AACrB,6BAAqBA,kBAAiB;AAAA,MACxC;AAAA,IACF,CAAC,EACA,QAAQ,MAAM;AACb,mBAAa,KAAK;AAAA,IACpB,CAAC;AAAA,EACL,GAAG,CAAC,CAAC;AAEL,QAAM,aAAa;AAAA,IACjB,MAAM,qBAAqB;AAAA,IAC3B,CAAC,mBAAmB,gBAAgB;AAAA,EACtC;AAEA,SAAO,EAAE,GAAG,YAAY,UAAU;AACpC;","names":["distantDictionary"]}
@@ -0,0 +1,36 @@
1
+ import "../chunk-ZD7AOCMD.mjs";
2
+ import { getConfiguration } from "@intlayer/config/client";
3
+ import { getIntlayerAPI } from "@intlayer/design-system/libs";
4
+ const fetchDistantDictionary = async (dictionaryKey) => {
5
+ try {
6
+ const config = getConfiguration();
7
+ const { clientId, clientSecret } = config.editor;
8
+ const intlayerAPI = getIntlayerAPI(void 0, config);
9
+ if (!clientId || !clientSecret) {
10
+ throw new Error(
11
+ "Missing OAuth2 client ID or client secret. To get access token go to https://intlayer.org/dashboard/project."
12
+ );
13
+ }
14
+ const oAuth2TokenResult = await intlayerAPI.auth.getOAuth2AccessToken();
15
+ const oAuth2AccessToken = oAuth2TokenResult.data?.accessToken;
16
+ const getDictionaryResult = await intlayerAPI.dictionary.getDictionary(
17
+ dictionaryKey,
18
+ void 0,
19
+ {
20
+ headers: { Authorization: `Bearer ${oAuth2AccessToken}` }
21
+ }
22
+ );
23
+ const distantDictionary = getDictionaryResult.data;
24
+ if (!distantDictionary) {
25
+ throw new Error(`Dictionary ${dictionaryKey} not found on remote`);
26
+ }
27
+ return distantDictionary;
28
+ } catch (error) {
29
+ console.error(error);
30
+ return void 0;
31
+ }
32
+ };
33
+ export {
34
+ fetchDistantDictionary
35
+ };
36
+ //# sourceMappingURL=fetchDistantDictionary.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/distantDictionary/fetchDistantDictionary.ts"],"sourcesContent":["// @ts-ignore @intlayer/backend not build yet\nimport { type DictionaryAPI } from '@intlayer/backend';\nimport { getConfiguration } from '@intlayer/config/client';\n// @ts-ignore @intlayer/design-system not build yet\nimport { getIntlayerAPI } from '@intlayer/design-system/libs';\n\n/**\n * Fetch distant dictionary\n */\nexport const fetchDistantDictionary = async (\n dictionaryKey: string\n): Promise<DictionaryAPI> => {\n try {\n const config = getConfiguration();\n const { clientId, clientSecret } = config.editor;\n const intlayerAPI = getIntlayerAPI(undefined, config);\n\n if (!clientId || !clientSecret) {\n throw new Error(\n 'Missing OAuth2 client ID or client secret. To get access token go to https://intlayer.org/dashboard/project.'\n );\n }\n\n const oAuth2TokenResult = await intlayerAPI.auth.getOAuth2AccessToken();\n\n const oAuth2AccessToken = oAuth2TokenResult.data?.accessToken;\n\n // Fetch the dictionary\n const getDictionaryResult = await intlayerAPI.dictionary.getDictionary(\n dictionaryKey,\n undefined,\n {\n headers: { Authorization: `Bearer ${oAuth2AccessToken}` },\n }\n );\n\n const distantDictionary = getDictionaryResult.data;\n\n if (!distantDictionary) {\n throw new Error(`Dictionary ${dictionaryKey} not found on remote`);\n }\n\n return distantDictionary;\n } catch (error) {\n console.error(error);\n return undefined;\n }\n};\n"],"mappings":";AAEA,SAAS,wBAAwB;AAEjC,SAAS,sBAAsB;AAKxB,MAAM,yBAAyB,OACpC,kBAC2B;AAC3B,MAAI;AACF,UAAM,SAAS,iBAAiB;AAChC,UAAM,EAAE,UAAU,aAAa,IAAI,OAAO;AAC1C,UAAM,cAAc,eAAe,QAAW,MAAM;AAEpD,QAAI,CAAC,YAAY,CAAC,cAAc;AAC9B,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAEA,UAAM,oBAAoB,MAAM,YAAY,KAAK,qBAAqB;AAEtE,UAAM,oBAAoB,kBAAkB,MAAM;AAGlD,UAAM,sBAAsB,MAAM,YAAY,WAAW;AAAA,MACvD;AAAA,MACA;AAAA,MACA;AAAA,QACE,SAAS,EAAE,eAAe,UAAU,iBAAiB,GAAG;AAAA,MAC1D;AAAA,IACF;AAEA,UAAM,oBAAoB,oBAAoB;AAE9C,QAAI,CAAC,mBAAmB;AACtB,YAAM,IAAI,MAAM,cAAc,aAAa,sBAAsB;AAAA,IACnE;AAEA,WAAO;AAAA,EACT,SAAS,OAAO;AACd,YAAQ,MAAM,KAAK;AACnB,WAAO;AAAA,EACT;AACF;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/editor/ContentSelectorWrapper.tsx"],"sourcesContent":["'use client';\n\nimport { type KeyPath } from '@intlayer/core';\nimport { type FC, type ReactNode } from 'react';\n\nexport type ContentSelectorWrapperProps = {\n children: ReactNode;\n dictionaryId: string;\n dictionaryPath: string;\n keyPath: KeyPath[];\n};\n\nexport const ContentSelectorWrapper: FC<ContentSelectorWrapperProps> = ({\n children,\n}) => <>{children}</>;\n"],"mappings":";;AAcM;AAFC,MAAM,yBAA0D,CAAC;AAAA,EACtE;AACF,MAAM,gCAAG,UAAS;","names":[]}
1
+ {"version":3,"sources":["../../../src/editor/ContentSelectorWrapper.tsx"],"sourcesContent":["'use client';\n\nimport { type KeyPath } from '@intlayer/core';\nimport { type FC, type ReactNode } from 'react';\n\nexport type ContentSelectorWrapperProps = {\n children: ReactNode;\n dictionaryKey: string;\n dictionaryPath: string;\n keyPath: KeyPath[];\n};\n\nexport const ContentSelectorWrapper: FC<ContentSelectorWrapperProps> = ({\n children,\n}) => <>{children}</>;\n"],"mappings":";;AAcM;AAFC,MAAM,yBAA0D,CAAC;AAAA,EACtE;AACF,MAAM,gCAAG,UAAS;","names":[]}
@@ -1,7 +1,11 @@
1
1
  import "../chunk-ZD7AOCMD.mjs";
2
- import { jsx } from "react/jsx-runtime";
2
+ import { jsx, jsxs } from "react/jsx-runtime";
3
+ import { PoweredByMeta } from '../utils/PoweredByMeta/index.mjs';
3
4
  import { ContentSelectorProvider } from './ContentSelectorConnector.mjs';
4
- const IntlayerEditorProvider = ({ children }) => /* @__PURE__ */ jsx(ContentSelectorProvider, { children });
5
+ const IntlayerEditorProvider = ({ children }) => /* @__PURE__ */ jsxs(ContentSelectorProvider, { children: [
6
+ /* @__PURE__ */ jsx(PoweredByMeta, {}),
7
+ children
8
+ ] });
5
9
  export {
6
10
  IntlayerEditorProvider
7
11
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/editor/IntlayerEditorProvider.tsx"],"sourcesContent":["import { FC, PropsWithChildren } from 'react';\nimport { ContentSelectorProvider } from './ContentSelectorConnector';\n\nexport const IntlayerEditorProvider: FC<PropsWithChildren> = ({ children }) => (\n <ContentSelectorProvider>{children}</ContentSelectorProvider>\n);\n"],"mappings":";AAIE;AAHF,SAAS,+BAA+B;AAEjC,MAAM,yBAAgD,CAAC,EAAE,SAAS,MACvE,oBAAC,2BAAyB,UAAS;","names":[]}
1
+ {"version":3,"sources":["../../../src/editor/IntlayerEditorProvider.tsx"],"sourcesContent":["import { FC, PropsWithChildren } from 'react';\nimport { PoweredByMeta } from '../utils/PoweredByMeta/index';\nimport { ContentSelectorProvider } from './ContentSelectorConnector';\n\nexport const IntlayerEditorProvider: FC<PropsWithChildren> = ({ children }) => (\n <ContentSelectorProvider>\n <PoweredByMeta />\n {children}\n </ContentSelectorProvider>\n);\n"],"mappings":";AAKE,SACE,KADF;AAJF,SAAS,qBAAqB;AAC9B,SAAS,+BAA+B;AAEjC,MAAM,yBAAgD,CAAC,EAAE,SAAS,MACvE,qBAAC,2BACC;AAAA,sBAAC,iBAAc;AAAA,EACd;AAAA,GACH;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/editor/renderContentEditor.tsx"],"sourcesContent":["import { getConfiguration } from '@intlayer/config/client';\nimport type { KeyPath } from '@intlayer/core';\nimport type { FC, ReactNode } from 'react';\nimport { ContentSelectorConnector } from './ContentSelectorConnector';\n\nconst {\n editor: { enabled },\n} = getConfiguration();\n\nexport type IntlayerEditorElementProps = {\n content: string;\n dictionaryId: string;\n dictionaryPath: string;\n keyPath: KeyPath[];\n isContentSelectable: boolean;\n};\n\nconst IntlayerEditorElement: FC<IntlayerEditorElementProps> = ({\n content,\n isContentSelectable,\n ...props\n}) => {\n if (enabled && isContentSelectable) {\n return (\n <ContentSelectorConnector {...props}>{content}</ContentSelectorConnector>\n );\n }\n return content;\n};\n\nexport type IntlayerNode<T = string> = ReactNode & {\n value: T;\n};\n\nexport const renderIntlayerEditor = (\n data: IntlayerEditorElementProps,\n isContentSelectable = true\n): IntlayerNode => {\n const Result = (\n <IntlayerEditorElement\n {...data}\n isContentSelectable={isContentSelectable}\n />\n );\n\n return { ...Result, value: data.content };\n};\n"],"mappings":";AAwBM;AAxBN,SAAS,wBAAwB;AAGjC,SAAS,gCAAgC;AAEzC,MAAM;AAAA,EACJ,QAAQ,EAAE,QAAQ;AACpB,IAAI,iBAAiB;AAUrB,MAAM,wBAAwD,CAAC;AAAA,EAC7D;AAAA,EACA;AAAA,EACA,GAAG;AACL,MAAM;AACJ,MAAI,WAAW,qBAAqB;AAClC,WACE,oBAAC,4BAA0B,GAAG,OAAQ,mBAAQ;AAAA,EAElD;AACA,SAAO;AACT;AAMO,MAAM,uBAAuB,CAClC,MACA,sBAAsB,SACL;AACjB,QAAM,SACJ;AAAA,IAAC;AAAA;AAAA,MACE,GAAG;AAAA,MACJ;AAAA;AAAA,EACF;AAGF,SAAO,EAAE,GAAG,QAAQ,OAAO,KAAK,QAAQ;AAC1C;","names":[]}
1
+ {"version":3,"sources":["../../../src/editor/renderContentEditor.tsx"],"sourcesContent":["import { getConfiguration } from '@intlayer/config/client';\nimport type { KeyPath } from '@intlayer/core';\nimport type { FC, ReactNode } from 'react';\nimport { ContentSelectorConnector } from './ContentSelectorConnector';\n\nconst {\n editor: { enabled },\n} = getConfiguration();\n\nexport type IntlayerEditorElementProps = {\n content: string;\n dictionaryKey: string;\n dictionaryPath: string;\n keyPath: KeyPath[];\n isContentSelectable: boolean;\n};\n\nconst IntlayerEditorElement: FC<IntlayerEditorElementProps> = ({\n content,\n isContentSelectable,\n ...props\n}) => {\n if (enabled && isContentSelectable) {\n return (\n <ContentSelectorConnector {...props}>{content}</ContentSelectorConnector>\n );\n }\n return content;\n};\n\nexport type IntlayerNode<T = string> = ReactNode & {\n value: T;\n};\n\nexport const renderIntlayerEditor = (\n data: IntlayerEditorElementProps,\n isContentSelectable = true\n): IntlayerNode => {\n const Result = (\n <IntlayerEditorElement\n {...data}\n isContentSelectable={isContentSelectable}\n />\n );\n\n return { ...Result, value: data.content };\n};\n"],"mappings":";AAwBM;AAxBN,SAAS,wBAAwB;AAGjC,SAAS,gCAAgC;AAEzC,MAAM;AAAA,EACJ,QAAQ,EAAE,QAAQ;AACpB,IAAI,iBAAiB;AAUrB,MAAM,wBAAwD,CAAC;AAAA,EAC7D;AAAA,EACA;AAAA,EACA,GAAG;AACL,MAAM;AACJ,MAAI,WAAW,qBAAqB;AAClC,WACE,oBAAC,4BAA0B,GAAG,OAAQ,mBAAQ;AAAA,EAElD;AACA,SAAO;AACT;AAMO,MAAM,uBAAuB,CAClC,MACA,sBAAsB,SACL;AACjB,QAAM,SACJ;AAAA,IAAC;AAAA;AAAA,MACE,GAAG;AAAA,MACJ;AAAA;AAAA,EACF;AAGF,SAAO,EAAE,GAAG,QAAQ,OAAO,KAAK,QAAQ;AAC1C;","names":[]}
@@ -8,7 +8,7 @@ const recursiveTransformContent = (value, isRenderEditor = false) => {
8
8
  if (typeof value === "function") {
9
9
  return (props) => recursiveTransformContent(value(props), isRenderEditor);
10
10
  } else if (typeof value === "object") {
11
- if (typeof value.dictionaryId !== "undefined") {
11
+ if (typeof value.dictionaryKey !== "undefined") {
12
12
  if (isRenderEditor) {
13
13
  return renderIntlayerEditor(value);
14
14
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/getDictionary.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { Locales } from '@intlayer/config';\nimport type {\n DeclarationContent,\n DictionaryValue,\n NodeType,\n} from '@intlayer/core';\nimport { isValidElement, type ReactNode } from 'react';\nimport {\n type IntlayerNode,\n renderIntlayerEditor,\n} from './editor/renderContentEditor';\nimport { processDictionary } from './processDictionary/index';\n\ntype TransformNodeType<T, L extends Locales, R extends boolean> = T extends {\n [NodeType.Enumeration]: { '1': any };\n}\n ? (\n quantity: number\n ) => DeepTransformContent<T[NodeType.Enumeration]['1'], L, R>\n : T extends {\n [NodeType.Translation]: object;\n }\n ? L extends keyof T[NodeType.Translation]\n ? DeepTransformContent<T[NodeType.Translation][L], L, R>\n : never\n : T;\n\nexport type DeepTransformContent<\n T,\n L extends Locales,\n R extends boolean,\n> = T extends object // Check if the property is an object\n ? T extends (infer U)[] // If it's an array, infer the type of array elements\n ? DeepTransformContent<U, L, R>[] // Apply DeepTransformContent recursively to each element of the array\n : T extends {\n nodeType: NodeType | string;\n }\n ? TransformNodeType<T, L, R>\n : T extends { _owner: any; key: any; props: any; ref: any }\n ? ReactNode\n : {\n [K in keyof T]: DeepTransformContent<T[K], L, R>;\n }\n : T extends undefined\n ? never\n : R extends true\n ? IntlayerNode<T>\n : T;\n\n/**\n * Go through the object. If a object has a keyPath, render the intlayer editor if editor enabled.\n */\nexport const recursiveTransformContent = (\n value: any,\n isRenderEditor = false\n): object => {\n if (typeof value === 'function') {\n return (props: any) =>\n recursiveTransformContent(value(props), isRenderEditor);\n } else if (typeof value === 'object') {\n if (typeof value.dictionaryId !== 'undefined') {\n if (isRenderEditor) {\n return renderIntlayerEditor(value);\n }\n return value.content;\n } else if (Array.isArray(value)) {\n return value.map((el) => recursiveTransformContent(el, isRenderEditor));\n } else if (isValidElement(value)) {\n return value;\n }\n\n return Object.entries(value).reduce(\n (acc, [key, value]) => ({\n ...acc,\n [key]: recursiveTransformContent(value, isRenderEditor),\n }),\n {} as object\n );\n }\n\n return value;\n};\n\ntype DataFromDictionary<\n T extends DeclarationContent,\n K extends Locales,\n R extends boolean = false,\n> = DeepTransformContent<T['content'], K, R>;\n\nexport type UseDictionary = <\n T extends DeclarationContent,\n L extends Locales,\n R extends boolean = false,\n>(\n dictionary: T,\n locale?: L,\n isRenderEditor?: R\n) => DataFromDictionary<T, L, R>;\n\n/**\n * Hook that picks one dictionary by its id and return the content\n *\n * If the locale is not provided, it will use the locale from the client context\n */\nexport const getDictionary: UseDictionary = <\n T extends DeclarationContent,\n L extends Locales,\n R extends boolean = false,\n>(\n dictionary: T,\n locale?: L,\n isRenderEditor: R = false as R\n) => {\n const result = processDictionary(\n dictionary.content as DictionaryValue,\n dictionary.key,\n dictionary.filePath,\n [],\n locale\n );\n\n return recursiveTransformContent(\n result,\n isRenderEditor\n ) as DataFromDictionary<T, L, R>;\n};\n"],"mappings":";AAOA,SAAS,sBAAsC;AAC/C;AAAA,EAEE;AAAA,OACK;AACP,SAAS,yBAAyB;AAyC3B,MAAM,4BAA4B,CACvC,OACA,iBAAiB,UACN;AACX,MAAI,OAAO,UAAU,YAAY;AAC/B,WAAO,CAAC,UACN,0BAA0B,MAAM,KAAK,GAAG,cAAc;AAAA,EAC1D,WAAW,OAAO,UAAU,UAAU;AACpC,QAAI,OAAO,MAAM,iBAAiB,aAAa;AAC7C,UAAI,gBAAgB;AAClB,eAAO,qBAAqB,KAAK;AAAA,MACnC;AACA,aAAO,MAAM;AAAA,IACf,WAAW,MAAM,QAAQ,KAAK,GAAG;AAC/B,aAAO,MAAM,IAAI,CAAC,OAAO,0BAA0B,IAAI,cAAc,CAAC;AAAA,IACxE,WAAW,eAAe,KAAK,GAAG;AAChC,aAAO;AAAA,IACT;AAEA,WAAO,OAAO,QAAQ,KAAK,EAAE;AAAA,MAC3B,CAAC,KAAK,CAAC,KAAKA,MAAK,OAAO;AAAA,QACtB,GAAG;AAAA,QACH,CAAC,GAAG,GAAG,0BAA0BA,QAAO,cAAc;AAAA,MACxD;AAAA,MACA,CAAC;AAAA,IACH;AAAA,EACF;AAEA,SAAO;AACT;AAuBO,MAAM,gBAA+B,CAK1C,YACA,QACA,iBAAoB,UACjB;AACH,QAAM,SAAS;AAAA,IACb,WAAW;AAAA,IACX,WAAW;AAAA,IACX,WAAW;AAAA,IACX,CAAC;AAAA,IACD;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,EACF;AACF;","names":["value"]}
1
+ {"version":3,"sources":["../../src/getDictionary.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type { Locales } from '@intlayer/config';\nimport type {\n DeclarationContent,\n DictionaryValue,\n NodeType,\n} from '@intlayer/core';\nimport { isValidElement, type ReactNode } from 'react';\nimport {\n type IntlayerNode,\n renderIntlayerEditor,\n} from './editor/renderContentEditor';\nimport { processDictionary } from './processDictionary/index';\n\ntype TransformNodeType<T, L extends Locales, R extends boolean> = T extends {\n [NodeType.Enumeration]: { '1': any };\n}\n ? (\n quantity: number\n ) => DeepTransformContent<T[NodeType.Enumeration]['1'], L, R>\n : T extends {\n [NodeType.Translation]: object;\n }\n ? L extends keyof T[NodeType.Translation]\n ? DeepTransformContent<T[NodeType.Translation][L], L, R>\n : never\n : T;\n\nexport type DeepTransformContent<\n T,\n L extends Locales,\n R extends boolean,\n> = T extends object // Check if the property is an object\n ? T extends (infer U)[] // If it's an array, infer the type of array elements\n ? DeepTransformContent<U, L, R>[] // Apply DeepTransformContent recursively to each element of the array\n : T extends {\n nodeType: NodeType | string;\n }\n ? TransformNodeType<T, L, R>\n : T extends { _owner: any; key: any; props: any; ref: any }\n ? ReactNode\n : {\n [K in keyof T]: DeepTransformContent<T[K], L, R>;\n }\n : T extends undefined\n ? never\n : R extends true\n ? IntlayerNode<T>\n : T;\n\n/**\n * Go through the object. If a object has a keyPath, render the intlayer editor if editor enabled.\n */\nexport const recursiveTransformContent = (\n value: any,\n isRenderEditor = false\n): object => {\n if (typeof value === 'function') {\n return (props: any) =>\n recursiveTransformContent(value(props), isRenderEditor);\n } else if (typeof value === 'object') {\n if (typeof value.dictionaryKey !== 'undefined') {\n if (isRenderEditor) {\n return renderIntlayerEditor(value);\n }\n return value.content;\n } else if (Array.isArray(value)) {\n return value.map((el) => recursiveTransformContent(el, isRenderEditor));\n } else if (isValidElement(value)) {\n return value;\n }\n\n return Object.entries(value).reduce(\n (acc, [key, value]) => ({\n ...acc,\n [key]: recursiveTransformContent(value, isRenderEditor),\n }),\n {} as object\n );\n }\n\n return value;\n};\n\ntype DataFromDictionary<\n T extends DeclarationContent,\n K extends Locales,\n R extends boolean = false,\n> = DeepTransformContent<T['content'], K, R>;\n\nexport type UseDictionary = <\n T extends DeclarationContent,\n L extends Locales,\n R extends boolean = false,\n>(\n dictionary: T,\n locale?: L,\n isRenderEditor?: R\n) => DataFromDictionary<T, L, R>;\n\n/**\n * Hook that picks one dictionary by its id and return the content\n *\n * If the locale is not provided, it will use the locale from the client context\n */\nexport const getDictionary: UseDictionary = <\n T extends DeclarationContent,\n L extends Locales,\n R extends boolean = false,\n>(\n dictionary: T,\n locale?: L,\n isRenderEditor: R = false as R\n) => {\n const result = processDictionary(\n dictionary.content as DictionaryValue,\n dictionary.key,\n dictionary.filePath,\n [],\n locale\n );\n\n return recursiveTransformContent(\n result,\n isRenderEditor\n ) as DataFromDictionary<T, L, R>;\n};\n"],"mappings":";AAOA,SAAS,sBAAsC;AAC/C;AAAA,EAEE;AAAA,OACK;AACP,SAAS,yBAAyB;AAyC3B,MAAM,4BAA4B,CACvC,OACA,iBAAiB,UACN;AACX,MAAI,OAAO,UAAU,YAAY;AAC/B,WAAO,CAAC,UACN,0BAA0B,MAAM,KAAK,GAAG,cAAc;AAAA,EAC1D,WAAW,OAAO,UAAU,UAAU;AACpC,QAAI,OAAO,MAAM,kBAAkB,aAAa;AAC9C,UAAI,gBAAgB;AAClB,eAAO,qBAAqB,KAAK;AAAA,MACnC;AACA,aAAO,MAAM;AAAA,IACf,WAAW,MAAM,QAAQ,KAAK,GAAG;AAC/B,aAAO,MAAM,IAAI,CAAC,OAAO,0BAA0B,IAAI,cAAc,CAAC;AAAA,IACxE,WAAW,eAAe,KAAK,GAAG;AAChC,aAAO;AAAA,IACT;AAEA,WAAO,OAAO,QAAQ,KAAK,EAAE;AAAA,MAC3B,CAAC,KAAK,CAAC,KAAKA,MAAK,OAAO;AAAA,QACtB,GAAG;AAAA,QACH,CAAC,GAAG,GAAG,0BAA0BA,QAAO,cAAc;AAAA,MACxD;AAAA,MACA,CAAC;AAAA,IACH;AAAA,EACF;AAEA,SAAO;AACT;AAuBO,MAAM,gBAA+B,CAK1C,YACA,QACA,iBAAoB,UACjB;AACH,QAAM,SAAS;AAAA,IACb,WAAW;AAAA,IACX,WAAW;AAAA,IACX,WAAW;AAAA,IACX,CAAC;AAAA,IACD;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,EACF;AACF;","names":["value"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/getIntlayer.ts"],"sourcesContent":["import type { Locales } from '@intlayer/config';\nimport type { Dictionary } from '@intlayer/core';\n/**\n * @intlayer/dictionaries-entry is a package that only returns the dictionary entry path.\n * Using an external package allow to alias it in the bundle configuration (such as webpack).\n * The alias allow hot reload the app (such as nextjs) on any dictionary change.\n */\nimport dictionaries from '@intlayer/dictionaries-entry';\nimport type { IntlayerDictionaryTypesConnector } from 'intlayer';\nimport {\n type DeepTransformContent,\n recursiveTransformContent,\n} from './getDictionary';\nimport { processDictionary } from './processDictionary/index';\n\n/**\n * Provides a fallback to string type if the generic type T is never,\n * otherwise returns T. This is useful for handling cases where no keys are found.\n * Example: StringFallback<never> -> string; StringFallback<'key'> -> 'key'\n */\nexport type StringFallback<T> = T extends never ? string : T; // If no keys are found, return string to disable error, and accept any string as dictionary key\n\n/**\n * Represents the keys of the IntlayerDictionaryTypesConnector,\n * ensuring they are valid dictionary keys or fallback to string if none exist.\n *\n * Example:\n * ```ts\n * DictionaryKeys -> 'key1' | 'key2'\n * // or if IntlayerDictionaryTypesConnector is not defined,\n * DictionaryKeys -> string\n * ```\n */\nexport type DictionaryKeys = StringFallback<\n keyof IntlayerDictionaryTypesConnector\n>;\n\n/**\n * Represents the data type returned by the useIntlayer hook,\n * excluding the 'id' and 'filePath' keys from the dictionary content.\n */\ntype DataFromDictionaryKey<\n T extends DictionaryKeys,\n K extends Locales,\n R extends boolean = false,\n> = DeepTransformContent<IntlayerDictionaryTypesConnector[T]['content'], K, R>;\n\n/**\n * Type definition for the useIntlayer hook, which takes a dictionary ID and an optional locale,\n * and returns the deeply transformed dictionary content.\n *\n */\nexport type UseIntlayer = <\n T extends DictionaryKeys,\n L extends Locales,\n R extends boolean = false,\n>(\n key: T,\n locale?: L,\n isRenderEditor?: R\n) => DataFromDictionaryKey<T, L, R>;\n\nexport type UseIntlayerEditable = <\n T extends DictionaryKeys,\n L extends Locales,\n R extends boolean = true,\n>(\n key: T,\n locale?: L,\n isRenderEditor?: R\n) => DataFromDictionaryKey<T, L, R>;\n\nexport const getIntlayer: UseIntlayer = <\n T extends DictionaryKeys,\n L extends Locales,\n R extends boolean = false,\n>(\n key: T,\n locale?: L,\n isRenderEditor: R = false as R\n) => {\n const dictionary: Dictionary = dictionaries[key as keyof typeof dictionaries];\n\n if (!dictionary) {\n throw new Error(`Dictionary ${key} not found`, dictionaries);\n }\n\n const result = processDictionary(\n dictionary.content,\n dictionary.key,\n dictionary.filePath,\n [],\n locale\n );\n\n return recursiveTransformContent(\n result,\n isRenderEditor\n ) as DataFromDictionaryKey<T, L, R>;\n};\n"],"mappings":";AAOA,OAAO,kBAAkB;AAEzB;AAAA,EAEE;AAAA,OACK;AACP,SAAS,yBAAyB;AA2D3B,MAAM,cAA2B,CAKtC,KACA,QACA,iBAAoB,UACjB;AACH,QAAM,aAAyB,aAAa,GAAgC;AAE5E,MAAI,CAAC,YAAY;AACf,UAAM,IAAI,MAAM,cAAc,GAAG,cAAc,YAAY;AAAA,EAC7D;AAEA,QAAM,SAAS;AAAA,IACb,WAAW;AAAA,IACX,WAAW;AAAA,IACX,WAAW;AAAA,IACX,CAAC;AAAA,IACD;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/getIntlayer.ts"],"sourcesContent":["import type { Locales } from '@intlayer/config';\nimport type { Dictionary } from '@intlayer/core';\n/**\n * @intlayer/dictionaries-entry is a package that only returns the dictionary entry path.\n * Using an external package allow to alias it in the bundle configuration (such as webpack).\n * The alias allow hot reload the app (such as nextjs) on any dictionary change.\n */\nimport dictionaries from '@intlayer/dictionaries-entry';\nimport type { IntlayerDictionaryTypesConnector } from 'intlayer';\nimport {\n type DeepTransformContent,\n recursiveTransformContent,\n} from './getDictionary';\nimport { processDictionary } from './processDictionary/index';\n\n/**\n * Provides a fallback to string type if the generic type T is never,\n * otherwise returns T. This is useful for handling cases where no keys are found.\n * Example: StringFallback<never> -> string; StringFallback<'key'> -> 'key'\n */\nexport type StringFallback<T> = T extends never ? string : T; // If no keys are found, return string to disable error, and accept any string as dictionary key\n\n/**\n * Represents the keys of the IntlayerDictionaryTypesConnector,\n * ensuring they are valid dictionary keys or fallback to string if none exist.\n *\n * Example:\n * ```ts\n * DictionaryKeys -> 'key1' | 'key2'\n * // or if IntlayerDictionaryTypesConnector is not defined,\n * DictionaryKeys -> string\n * ```\n */\nexport type DictionaryKeys = StringFallback<\n keyof IntlayerDictionaryTypesConnector\n>;\n\n/**\n * Represents the data type returned by the useIntlayer hook,\n * excluding the 'id' and 'filePath' keys from the dictionary content.\n */\nexport type DataFromDictionaryKey<\n T extends DictionaryKeys,\n K extends Locales,\n R extends boolean = false,\n> = DeepTransformContent<IntlayerDictionaryTypesConnector[T]['content'], K, R>;\n\n/**\n * Type definition for the useIntlayer hook, which takes a dictionary ID and an optional locale,\n * and returns the deeply transformed dictionary content.\n *\n */\nexport type UseIntlayer = <\n T extends DictionaryKeys,\n L extends Locales,\n R extends boolean = false,\n>(\n key: T,\n locale?: L,\n isRenderEditor?: R\n) => DataFromDictionaryKey<T, L, R>;\n\nexport type UseIntlayerEditable = <\n T extends DictionaryKeys,\n L extends Locales,\n R extends boolean = true,\n>(\n key: T,\n locale?: L,\n isRenderEditor?: R\n) => DataFromDictionaryKey<T, L, R>;\n\nexport const getIntlayer: UseIntlayer = <\n T extends DictionaryKeys,\n L extends Locales,\n R extends boolean = false,\n>(\n key: T,\n locale?: L,\n isRenderEditor: R = false as R\n) => {\n const dictionary: Dictionary = dictionaries[key as keyof typeof dictionaries];\n\n if (!dictionary) {\n throw new Error(`Dictionary ${key} not found`, dictionaries);\n }\n\n const result = processDictionary(\n dictionary.content,\n dictionary.key,\n dictionary.filePath,\n [],\n locale\n );\n\n return recursiveTransformContent(\n result,\n isRenderEditor\n ) as DataFromDictionaryKey<T, L, R>;\n};\n"],"mappings":";AAOA,OAAO,kBAAkB;AAEzB;AAAA,EAEE;AAAA,OACK;AACP,SAAS,yBAAyB;AA2D3B,MAAM,cAA2B,CAKtC,KACA,QACA,iBAAoB,UACjB;AACH,QAAM,aAAyB,aAAa,GAAgC;AAE5E,MAAI,CAAC,YAAY;AACf,UAAM,IAAI,MAAM,cAAc,GAAG,cAAc,YAAY;AAAA,EAC7D;AAEA,QAAM,SAAS;AAAA,IACb,WAAW;AAAA,IACX,WAAW;AAAA,IACX,WAAW;AAAA,IACX,CAAC;AAAA,IACD;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
@@ -0,0 +1,19 @@
1
+ "use client";
2
+ import "./chunk-ZD7AOCMD.mjs";
3
+ import { fetchDistantDictionary } from './distantDictionary/fetchDistantDictionary.mjs';
4
+ import { getDictionary } from './getDictionary.mjs';
5
+ const getIntlayerAsync = async (key, locale, isRenderEditor = true) => {
6
+ const jsonDistantDictionary = await fetchDistantDictionary(key);
7
+ if (jsonDistantDictionary) {
8
+ return getDictionary(
9
+ jsonDistantDictionary,
10
+ locale,
11
+ isRenderEditor
12
+ );
13
+ }
14
+ return null;
15
+ };
16
+ export {
17
+ getIntlayerAsync
18
+ };
19
+ //# sourceMappingURL=getIntlayerAsync.mjs.map