next-translate-plugin 2.4.0-canary.5 → 2.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/cjs/index.js CHANGED
@@ -10,17 +10,6 @@ var __assign = (this && this.__assign) || function () {
10
10
  };
11
11
  return __assign.apply(this, arguments);
12
12
  };
13
- var __rest = (this && this.__rest) || function (s, e) {
14
- var t = {};
15
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
16
- t[p] = s[p];
17
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
18
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
19
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
20
- t[p[i]] = s[p[i]];
21
- }
22
- return t;
23
- };
24
13
  var __importDefault = (this && this.__importDefault) || function (mod) {
25
14
  return (mod && mod.__esModule) ? mod : { "default": mod };
26
15
  };
@@ -34,7 +23,7 @@ function nextTranslate(nextConfig) {
34
23
  var basePath = pkgDir();
35
24
  basePath = path_1.default.resolve(path_1.default.relative(basePath, process.env.NEXT_TRANSLATE_PATH || '.'));
36
25
  var nextConfigI18n = nextConfig.i18n || {};
37
- var _a = require(path_1.default.join(basePath, 'i18n')), _b = _a.locales, locales = _b === void 0 ? nextConfigI18n.locales || [] : _b, _c = _a.defaultLocale, defaultLocale = _c === void 0 ? nextConfigI18n.defaultLocale || 'en' : _c, _d = _a.domains, domains = _d === void 0 ? nextConfigI18n.domains : _d, _e = _a.localeDetection, localeDetection = _e === void 0 ? nextConfigI18n.localeDetection : _e, _f = _a.loader, loader = _f === void 0 ? true : _f, pagesInDir = _a.pagesInDir, restI18n = __rest(_a, ["locales", "defaultLocale", "domains", "localeDetection", "loader", "pagesInDir"]);
26
+ var _a = require(path_1.default.join(basePath, 'i18n')), _b = _a.locales, locales = _b === void 0 ? nextConfigI18n.locales || [] : _b, _c = _a.defaultLocale, defaultLocale = _c === void 0 ? nextConfigI18n.defaultLocale || 'en' : _c, _d = _a.domains, domains = _d === void 0 ? nextConfigI18n.domains : _d, _e = _a.localeDetection, localeDetection = _e === void 0 ? nextConfigI18n.localeDetection : _e, _f = _a.loader, loader = _f === void 0 ? true : _f, pagesInDir = _a.pagesInDir, _g = _a.extensionsRgx, extensionsRgx = _g === void 0 ? test : _g, _h = _a.revalidate, revalidate = _h === void 0 ? 0 : _h;
38
27
  var nextConfigWithI18n = __assign(__assign({}, nextConfig), { i18n: {
39
28
  locales: locales,
40
29
  defaultLocale: defaultLocale,
@@ -43,6 +32,7 @@ function nextTranslate(nextConfig) {
43
32
  } });
44
33
  var pagesFolder = (0, utils_1.calculatePageDir)('pages', pagesInDir, basePath);
45
34
  var appFolder = (0, utils_1.calculatePageDir)('app', pagesInDir, basePath);
35
+ var existLocalesFolder = (0, utils_1.existLocalesFolderWithNamespaces)(basePath);
46
36
  var existPagesFolder = (0, utils_1.existPages)(basePath, pagesFolder);
47
37
  var hasGetInitialPropsOnAppJs = false;
48
38
  var hasAppJs = false;
@@ -87,8 +77,9 @@ function nextTranslate(nextConfig) {
87
77
  appFolder: path_1.default.join(appFolder, '/'),
88
78
  hasAppJs: hasAppJs,
89
79
  hasGetInitialPropsOnAppJs: hasGetInitialPropsOnAppJs,
90
- extensionsRgx: restI18n.extensionsRgx || test,
91
- revalidate: restI18n.revalidate || 0,
80
+ extensionsRgx: extensionsRgx,
81
+ revalidate: revalidate,
82
+ existLocalesFolder: existLocalesFolder,
92
83
  },
93
84
  },
94
85
  });
package/lib/cjs/loader.js CHANGED
@@ -9,7 +9,7 @@ var templateWithLoader_1 = __importDefault(require("./templateWithLoader"));
9
9
  var templateAppDir_1 = __importDefault(require("./templateAppDir"));
10
10
  var utils_1 = require("./utils");
11
11
  function loader(rawCode) {
12
- var _a = this.getOptions(), basePath = _a.basePath, pagesFolder = _a.pagesFolder, appFolder = _a.appFolder, hasAppJs = _a.hasAppJs, hasGetInitialPropsOnAppJs = _a.hasGetInitialPropsOnAppJs, extensionsRgx = _a.extensionsRgx, revalidate = _a.revalidate;
12
+ var _a = this.getOptions(), basePath = _a.basePath, pagesFolder = _a.pagesFolder, appFolder = _a.appFolder, hasAppJs = _a.hasAppJs, hasGetInitialPropsOnAppJs = _a.hasGetInitialPropsOnAppJs, extensionsRgx = _a.extensionsRgx, revalidate = _a.revalidate, existLocalesFolder = _a.existLocalesFolder;
13
13
  try {
14
14
  var codeWithoutComments_1 = (0, utils_1.removeCommentsFromCode)(rawCode).trim();
15
15
  var normalizedResourcePath = path_1.default
@@ -22,8 +22,9 @@ function loader(rawCode) {
22
22
  normalizedResourcePath.includes(appFolder.replace(/\\/g, '/'));
23
23
  var pagesPath = (shouldUseTemplateAppDir ? appFolder : pagesFolder);
24
24
  var normalizedPagesPath = pagesPath.replace(/\\/g, '/');
25
- if (normalizedResourcePath.includes('node_modules/next/dist/pages/_app') && !hasAppJs) {
26
- return (0, utils_1.getDefaultAppJs)();
25
+ if (normalizedResourcePath.includes('node_modules/next/dist/pages/_app') &&
26
+ !hasAppJs) {
27
+ return (0, utils_1.getDefaultAppJs)(existLocalesFolder);
27
28
  }
28
29
  if (normalizedResourcePath.includes('node_modules/'))
29
30
  return rawCode;
@@ -44,6 +45,7 @@ function loader(rawCode) {
44
45
  appFolder: appFolder,
45
46
  isClientComponent: isClientComponent,
46
47
  code: rawCode,
48
+ existLocalesFolder: existLocalesFolder,
47
49
  });
48
50
  }
49
51
  var defaultExport = (0, utils_1.getDefaultExport)(pagePkg);
@@ -51,12 +53,13 @@ function loader(rawCode) {
51
53
  return rawCode;
52
54
  if (hasGetInitialPropsOnAppJs) {
53
55
  return pageNoExt === '/_app'
54
- ? (0, templateWithHoc_1.default)(pagePkg)
56
+ ? (0, templateWithHoc_1.default)(pagePkg, { existLocalesFolder: existLocalesFolder })
55
57
  : rawCode;
56
58
  }
57
59
  if (pageNoExt === '/_app') {
58
60
  return (0, templateWithHoc_1.default)(pagePkg, {
59
61
  skipInitialProps: true,
62
+ existLocalesFolder: existLocalesFolder,
60
63
  });
61
64
  }
62
65
  if ((0, utils_1.isPageToIgnore)(page))
@@ -69,7 +72,7 @@ function loader(rawCode) {
69
72
  var isGetInitialProps = (0, utils_1.hasStaticName)(pagePkg, defaultExport, 'getInitialProps');
70
73
  var hasLoader = isGetStaticProps || isGetServerSideProps || isGetInitialProps;
71
74
  if (isGetInitialProps || (!hasLoader && isWrapperWithExternalHOC)) {
72
- return (0, templateWithHoc_1.default)(pagePkg);
75
+ return (0, templateWithHoc_1.default)(pagePkg, { existLocalesFolder: existLocalesFolder });
73
76
  }
74
77
  var loader_1 = isGetServerSideProps || (!hasLoader && isDynamicPage && !isGetStaticPaths)
75
78
  ? 'getServerSideProps'
@@ -78,6 +81,7 @@ function loader(rawCode) {
78
81
  page: pageNoExt,
79
82
  loader: loader_1,
80
83
  revalidate: revalidate,
84
+ existLocalesFolder: existLocalesFolder,
81
85
  });
82
86
  }
83
87
  catch (e) {
@@ -1,70 +1,57 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  var utils_1 = require("./utils");
4
- var validPages = ['/page', '/layout', '/error', '/loading', '/not-found', '/global-error'];
4
+ var validPages = [
5
+ '/page',
6
+ '/layout',
7
+ '/error',
8
+ '/loading',
9
+ '/not-found',
10
+ '/global-error',
11
+ ];
5
12
  var validPagesRegex = new RegExp("(".concat(validPages.join('|'), ")$"));
6
- var lastPathname = '';
7
13
  function templateAppDir(pagePkg, _a) {
8
- var _b = _a === void 0 ? {} : _a, _c = _b.code, code = _c === void 0 ? '' : _c, _d = _b.pageNoExt, pageNoExt = _d === void 0 ? '/' : _d, _e = _b.normalizedResourcePath, normalizedResourcePath = _e === void 0 ? '' : _e, _f = _b.appFolder, appFolder = _f === void 0 ? '' : _f, _g = _b.isClientComponent, isClientComponent = _g === void 0 ? false : _g;
14
+ var _b = _a === void 0 ? {} : _a, _c = _b.code, code = _c === void 0 ? '' : _c, _d = _b.pageNoExt, pageNoExt = _d === void 0 ? '/' : _d, _e = _b.normalizedResourcePath, normalizedResourcePath = _e === void 0 ? '' : _e, _f = _b.appFolder, appFolder = _f === void 0 ? '' : _f, _g = _b.isClientComponent, isClientComponent = _g === void 0 ? false : _g, _h = _b.existLocalesFolder, existLocalesFolder = _h === void 0 ? true : _h;
9
15
  var routeType = validPages.find(function (pageName) { return pageNoExt.endsWith(pageName); }) || 'component';
10
16
  var isPage = routeType !== 'component' && normalizedResourcePath.includes(appFolder);
11
- if (!isPage && !isClientComponent)
17
+ if (!isPage)
12
18
  return code;
13
19
  var hash = Date.now().toString(16);
14
- var pathname = isPage ? pageNoExt.replace(validPagesRegex, '/') : lastPathname;
15
- lastPathname = pathname;
20
+ var pathname = pageNoExt.replace(validPagesRegex, '/');
16
21
  var pageVariableName = (0, utils_1.interceptExport)(pagePkg, 'default', "__Next_Translate__Page__".concat(hash, "__"));
17
22
  if (isPage && !pageVariableName)
18
23
  return code;
19
- if (isClientComponent && !code.includes('next-translate'))
20
- return code;
21
24
  if (isClientComponent) {
22
- return templateClientComponent({
25
+ return templateRCCPage({
23
26
  pagePkg: pagePkg,
24
27
  hash: hash,
25
28
  pageVariableName: pageVariableName,
26
29
  pathname: pathname,
27
- isPage: isPage,
28
30
  routeType: routeType,
31
+ existLocalesFolder: existLocalesFolder,
29
32
  });
30
33
  }
31
- return templateServerPage({
34
+ return templateRSCPage({
32
35
  pagePkg: pagePkg,
33
36
  hash: hash,
34
37
  pageVariableName: pageVariableName,
35
38
  pathname: pathname,
36
39
  routeType: routeType,
40
+ existLocalesFolder: existLocalesFolder,
37
41
  });
38
42
  }
39
43
  exports.default = templateAppDir;
40
- function templateServerPage(_a) {
41
- var pagePkg = _a.pagePkg, hash = _a.hash, pageVariableName = _a.pageVariableName, pathname = _a.pathname, routeType = _a.routeType;
44
+ function templateRSCPage(_a) {
45
+ var pagePkg = _a.pagePkg, hash = _a.hash, pageVariableName = _a.pageVariableName, pathname = _a.pathname, routeType = _a.routeType, existLocalesFolder = _a.existLocalesFolder;
42
46
  var code = pagePkg.getCode();
43
- return "\n import ".concat(utils_1.INTERNAL_CONFIG_KEY, " from '@next-translate-root/i18n'\n import __loadNamespaces from 'next-translate/loadNamespaces'\n import __nt_store from 'next-translate/_store'\n\n ").concat(code, "\n\n export default async function __Next_Translate_new__").concat(hash, "__(props) {\n const config = { \n ...").concat(utils_1.INTERNAL_CONFIG_KEY, ",\n locale: props.params?.lang ?? props.searchParams?.lang ?? ").concat(utils_1.INTERNAL_CONFIG_KEY, ".defaultLocale,\n loaderName: 'server ").concat(routeType, "',\n pathname: '").concat(pathname, "',\n ").concat((0, utils_1.addLoadLocalesFrom)(), "\n }\n const { __lang, __namespaces } = await __loadNamespaces(config)\n\n __nt_store.set({ lang: __lang, namespaces: __namespaces, config })\n\n return <").concat(pageVariableName, " {...props} />\n }\n");
47
+ return "\n import ".concat(utils_1.INTERNAL_CONFIG_KEY, " from '@next-translate-root/i18n'\n import AppDirI18nProvider from 'next-translate/AppDirI18nProvider'\n import __loadNamespaces from 'next-translate/loadNamespaces'\n\n ").concat(code, "\n\n export default async function __Next_Translate_new__").concat(hash, "__(props) {\n const config = { \n ...").concat(utils_1.INTERNAL_CONFIG_KEY, ",\n locale: props.params?.lang ?? props.searchParams?.lang ?? ").concat(utils_1.INTERNAL_CONFIG_KEY, ".defaultLocale,\n loaderName: 'server ").concat(routeType, "',\n pathname: '").concat(pathname, "'\n }\n\n const { __lang, __namespaces } = await __loadNamespaces({ ...config, ").concat((0, utils_1.addLoadLocalesFrom)(existLocalesFolder), " });\n globalThis.__NEXT_TRANSLATE__ = { lang: __lang, namespaces: __namespaces, config }\n\n return <AppDirI18nProvider lang={__lang} namespaces={__namespaces} config={config}><").concat(pageVariableName, " {...props} /></AppDirI18nProvider>\n }\n");
44
48
  }
45
- function templateClientComponent(_a) {
46
- var pagePkg = _a.pagePkg, hash = _a.hash, pageVariableName = _a.pageVariableName, pathname = _a.pathname, isPage = _a.isPage, routeType = _a.routeType;
49
+ function templateRCCPage(_a) {
50
+ var pagePkg = _a.pagePkg, hash = _a.hash, pageVariableName = _a.pageVariableName, pathname = _a.pathname, routeType = _a.routeType, existLocalesFolder = _a.existLocalesFolder;
47
51
  var topLine = utils_1.clientLine[0];
48
- var namedExportsModified = modifyNamedExportsComponents(pagePkg, hash);
49
- var exportDefault = pageVariableName
50
- ? "export default " + wrapClientComponent({ name: "__Next_Translate_new__".concat(hash, "__"), pathname: pathname, isPage: isPage, pageVariableName: pageVariableName, routeType: routeType })
51
- : '';
52
52
  var clientCode = pagePkg.getCode();
53
53
  utils_1.clientLine.forEach(function (line) {
54
54
  clientCode = clientCode.replace(line, '');
55
55
  });
56
- return "".concat(topLine, "\n import ").concat(utils_1.INTERNAL_CONFIG_KEY, " from '@next-translate-root/i18n'\n import __loadNamespaces from 'next-translate/loadNamespaces'\n import __nt_store from 'next-translate/_store'\n import { useSearchParams as __useSearchParams, useParams as __useParams } from 'next/navigation'\n import { use as __use } from 'react';\n\n ").concat(clientCode, "\n\n ").concat(exportDefault, "\n ").concat(namedExportsModified, "\n");
57
- }
58
- function wrapClientComponent(_a) {
59
- var _b = _a.name, name = _b === void 0 ? '' : _b, _c = _a.pathname, pathname = _c === void 0 ? '' : _c, _d = _a.isPage, isPage = _d === void 0 ? false : _d, _e = _a.pageVariableName, pageVariableName = _e === void 0 ? '' : _e, _f = _a.routeType, routeType = _f === void 0 ? 'component' : _f;
60
- return "function ".concat(name, "(props) {\n const searchParams = __useSearchParams()\n const params = __useParams()\n const lang = params.lang ?? searchParams.get('lang') ?? ").concat(utils_1.INTERNAL_CONFIG_KEY, ".defaultLocale\n const config = {\n ...").concat(utils_1.INTERNAL_CONFIG_KEY, ",\n locale: lang,\n loaderName: 'client ").concat(routeType, "',\n pathname: '").concat(pathname, "',\n logBuild: ").concat(isPage, ",\n ").concat((0, utils_1.addLoadLocalesFrom)(), "\n }\n const { __lang, __namespaces } = __use(__loadNamespaces(config));\n\n __nt_store.set({ lang, namespaces: __namespaces, config })\n\n return <").concat(pageVariableName, " {...props} />\n }");
61
- }
62
- function modifyNamedExportsComponents(pagePkg, hash) {
63
- return (0, utils_1.interceptNamedExportsFromReactComponents)(pagePkg, hash)
64
- .map(function (_a) {
65
- var exportName = _a.exportName, defaultLocalName = _a.defaultLocalName;
66
- return "\n ".concat(wrapClientComponent({ name: defaultLocalName, pathname: lastPathname, isPage: false, pageVariableName: exportName }), "\n export { ").concat(defaultLocalName, " as ").concat(exportName, " }\n ");
67
- })
68
- .join('')
69
- .trim();
56
+ return "".concat(topLine, "\n import ").concat(utils_1.INTERNAL_CONFIG_KEY, " from '@next-translate-root/i18n'\n import AppDirI18nProvider from 'next-translate/AppDirI18nProvider'\n import { useSearchParams as __useSearchParams, useParams as __useParams } from 'next/navigation'\n import { use as __use } from 'react'\n import __loadNamespaces from 'next-translate/loadNamespaces'\n\n ").concat(clientCode, "\n\n export default function __Next_Translate_new__").concat(hash, "__(props) {\n const searchParams = __useSearchParams()\n const params = __useParams()\n const lang = params.lang ?? searchParams.get('lang') ?? ").concat(utils_1.INTERNAL_CONFIG_KEY, ".defaultLocale\n const config = {\n ...").concat(utils_1.INTERNAL_CONFIG_KEY, ",\n locale: lang,\n loaderName: 'client ").concat(routeType, "',\n pathname: '").concat(pathname, "',\n }\n\n const { __lang, __namespaces } = __use(__loadNamespaces({ ...config, ").concat((0, utils_1.addLoadLocalesFrom)(existLocalesFolder), " }));\n globalThis.__NEXT_TRANSLATE__ = { lang: __lang, namespaces: __namespaces, config }\n\n return <").concat(pageVariableName, " {...props} />\n }\n");
70
57
  }
@@ -2,12 +2,12 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  var utils_1 = require("./utils");
4
4
  function templateWithHoc(pagePkg, _a) {
5
- var _b = _a === void 0 ? {} : _a, _c = _b.skipInitialProps, skipInitialProps = _c === void 0 ? false : _c;
5
+ var _b = _a === void 0 ? {} : _a, _c = _b.skipInitialProps, skipInitialProps = _c === void 0 ? false : _c, _d = _b.existLocalesFolder, existLocalesFolder = _d === void 0 ? true : _d;
6
6
  var hash = Date.now().toString(16);
7
7
  var pageVariableName = (0, utils_1.interceptExport)(pagePkg, 'default', "__Next_Translate__Page__".concat(hash, "__"));
8
8
  var hasDefaultExport = Boolean(pageVariableName);
9
9
  if (!hasDefaultExport)
10
10
  return pagePkg.getCode();
11
- return "\n import ".concat(utils_1.INTERNAL_CONFIG_KEY, " from '@next-translate-root/i18n'\n import __appWithI18n from 'next-translate/appWithI18n'\n ").concat(pagePkg.getCode(), "\n export default __appWithI18n(").concat(pageVariableName, ", {\n ...").concat(utils_1.INTERNAL_CONFIG_KEY, ",\n isLoader: true,\n skipInitialProps: ").concat(skipInitialProps, ",\n ").concat((0, utils_1.addLoadLocalesFrom)(), "\n });\n ");
11
+ return "\n import ".concat(utils_1.INTERNAL_CONFIG_KEY, " from '@next-translate-root/i18n'\n import __appWithI18n from 'next-translate/appWithI18n'\n ").concat(pagePkg.getCode(), "\n export default __appWithI18n(").concat(pageVariableName, ", {\n ...").concat(utils_1.INTERNAL_CONFIG_KEY, ",\n isLoader: true,\n skipInitialProps: ").concat(skipInitialProps, ",\n ").concat((0, utils_1.addLoadLocalesFrom)(existLocalesFolder), "\n });\n ");
12
12
  }
13
13
  exports.default = templateWithHoc;
@@ -2,11 +2,11 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  var utils_1 = require("./utils");
4
4
  function templateWithLoader(pagePkg, _a) {
5
- var _b = _a === void 0 ? {} : _a, _c = _b.page, page = _c === void 0 ? '' : _c, _d = _b.loader, loader = _d === void 0 ? 'getStaticProps' : _d, _e = _b.revalidate, revalidate = _e === void 0 ? 0 : _e;
5
+ var _b = _a === void 0 ? {} : _a, _c = _b.page, page = _c === void 0 ? '' : _c, _d = _b.loader, loader = _d === void 0 ? 'getStaticProps' : _d, _e = _b.revalidate, revalidate = _e === void 0 ? 0 : _e, _f = _b.existLocalesFolder, existLocalesFolder = _f === void 0 ? true : _f;
6
6
  var hash = Date.now().toString(16);
7
7
  var oldLoaderName = (0, utils_1.interceptExport)(pagePkg, loader, "__Next_Translate_old_".concat(loader, "__").concat(hash, "__"));
8
8
  var newLoaderName = "__Next_Translate__".concat(loader, "__").concat(hash, "__");
9
9
  var hasLoader = Boolean(oldLoaderName);
10
- return "\n import ".concat(utils_1.INTERNAL_CONFIG_KEY, " from '@next-translate-root/i18n'\n import __loadNamespaces from 'next-translate/loadNamespaces'\n ").concat(pagePkg.getCode(), "\n async function ").concat(newLoaderName, "(ctx) {\n ").concat(hasLoader ? "const res = await ".concat(oldLoaderName, "(ctx)") : '', "\n return {\n ").concat(hasLoader && revalidate > 0 ? "revalidate: ".concat(revalidate, ",") : '', "\n ").concat(hasLoader ? '...res,' : '', "\n props: {\n ").concat(hasLoader ? '...(res.props || {}),' : '', "\n ...(await __loadNamespaces({\n ...ctx,\n ...").concat(utils_1.INTERNAL_CONFIG_KEY, ",\n pathname: '").concat(page, "',\n loaderName: '").concat(loader, "',\n ").concat((0, utils_1.addLoadLocalesFrom)(), "\n }))\n }\n }\n }\n export { ").concat(newLoaderName, " as ").concat(loader, " }\n ");
10
+ return "\n import ".concat(utils_1.INTERNAL_CONFIG_KEY, " from '@next-translate-root/i18n'\n import __loadNamespaces from 'next-translate/loadNamespaces'\n ").concat(pagePkg.getCode(), "\n async function ").concat(newLoaderName, "(ctx) {\n ").concat(hasLoader ? "const res = await ".concat(oldLoaderName, "(ctx)") : '', "\n return {\n ").concat(hasLoader && revalidate > 0 ? "revalidate: ".concat(revalidate, ",") : '', "\n ").concat(hasLoader ? '...res,' : '', "\n props: {\n ").concat(hasLoader ? '...(res.props || {}),' : '', "\n ...(await __loadNamespaces({\n ...ctx,\n ...").concat(utils_1.INTERNAL_CONFIG_KEY, ",\n pathname: '").concat(page, "',\n loaderName: '").concat(loader, "',\n ").concat((0, utils_1.addLoadLocalesFrom)(existLocalesFolder), "\n }))\n }\n }\n }\n export { ").concat(newLoaderName, " as ").concat(loader, " }\n ");
11
11
  }
12
12
  exports.default = templateWithLoader;
package/lib/cjs/utils.js CHANGED
@@ -23,7 +23,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
23
23
  return (mod && mod.__esModule) ? mod : { "default": mod };
24
24
  };
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.existPages = exports.calculatePageDir = exports.removeCommentsFromCode = exports.interceptExport = exports.interceptNamedExportsFromReactComponents = exports.isNotExportModifier = exports.hasHOC = exports.isPageToIgnore = exports.hasStaticName = exports.getStaticName = exports.hasExportName = exports.getDefaultExport = exports.getNamedExport = exports.resolveIdentifier = exports.resolveParenthesis = exports.getImportedNames = exports.getSymbol = exports.parseCode = exports.parseFile = exports.getFilePkg = exports.getTsCompilerOptions = exports.addLoadLocalesFrom = exports.getDefaultAppJs = exports.defaultLoader = exports.clientLine = exports.INTERNAL_CONFIG_KEY = void 0;
26
+ exports.existLocalesFolderWithNamespaces = exports.existPages = exports.calculatePageDir = exports.removeCommentsFromCode = exports.interceptExport = exports.isNotExportModifier = exports.hasHOC = exports.isPageToIgnore = exports.hasStaticName = exports.getStaticName = exports.hasExportName = exports.getDefaultExport = exports.getNamedExport = exports.resolveIdentifier = exports.resolveParenthesis = exports.getImportedNames = exports.getSymbol = exports.parseCode = exports.parseFile = exports.getFilePkg = exports.getTsCompilerOptions = exports.addLoadLocalesFrom = exports.getDefaultAppJs = exports.defaultLoader = exports.clientLine = exports.INTERNAL_CONFIG_KEY = void 0;
27
27
  var typescript_1 = __importDefault(require("typescript"));
28
28
  var path_1 = __importDefault(require("path"));
29
29
  var fs_1 = __importDefault(require("fs"));
@@ -31,12 +31,15 @@ var specFileOrFolderRgx = /(__mocks__|__tests__)|(\.(spec|test)\.(tsx|ts|js|jsx)
31
31
  exports.INTERNAL_CONFIG_KEY = '__i18nConfig';
32
32
  exports.clientLine = ['"use client"', "'use client'"];
33
33
  exports.defaultLoader = '(l, n) => import(`@next-translate-root/locales/${l}/${n}`).then(m => m.default)';
34
- function getDefaultAppJs() {
35
- return "\n import ".concat(exports.INTERNAL_CONFIG_KEY, " from '@next-translate-root/i18n'\n import appWithI18n from 'next-translate/appWithI18n'\n \n function MyApp({ Component, pageProps }) {\n return <Component {...pageProps} />\n }\n \n export default appWithI18n(MyApp, {\n ...").concat(exports.INTERNAL_CONFIG_KEY, ",\n skipInitialProps: true,\n isLoader: true,\n ").concat(addLoadLocalesFrom(), "\n })\n ");
34
+ function getDefaultAppJs(existLocalesFolder) {
35
+ return "\n import ".concat(exports.INTERNAL_CONFIG_KEY, " from '@next-translate-root/i18n'\n import appWithI18n from 'next-translate/appWithI18n'\n \n function MyApp({ Component, pageProps }) {\n return <Component {...pageProps} />\n }\n \n export default appWithI18n(MyApp, {\n ...").concat(exports.INTERNAL_CONFIG_KEY, ",\n skipInitialProps: true,\n isLoader: true,\n ").concat(addLoadLocalesFrom(existLocalesFolder), "\n })\n ");
36
36
  }
37
37
  exports.getDefaultAppJs = getDefaultAppJs;
38
- function addLoadLocalesFrom() {
39
- return "loadLocaleFrom: typeof ".concat(exports.INTERNAL_CONFIG_KEY, ".loadLocaleFrom === 'function' ? ").concat(exports.INTERNAL_CONFIG_KEY, ".loadLocaleFrom : ").concat(exports.defaultLoader, ",");
38
+ function addLoadLocalesFrom(existLocalesFolder) {
39
+ var defaultFn = existLocalesFolder
40
+ ? exports.defaultLoader
41
+ : "() => Promise.resolve({})";
42
+ return "loadLocaleFrom: ".concat(exports.INTERNAL_CONFIG_KEY, ".loadLocaleFrom || (").concat(defaultFn, "),");
40
43
  }
41
44
  exports.addLoadLocalesFrom = addLoadLocalesFrom;
42
45
  function getTsCompilerOptions(basePath, cutDependencies) {
@@ -290,35 +293,6 @@ function isNotExportModifier(modifier) {
290
293
  return !exportModifiers.includes(modifier.kind);
291
294
  }
292
295
  exports.isNotExportModifier = isNotExportModifier;
293
- function isPascalCase(str) {
294
- return str.length > 1 && str[0] === str[0].toUpperCase() && str[1] === str[1].toLowerCase();
295
- }
296
- function interceptNamedExportsFromReactComponents(filePkg, hash) {
297
- var sourceFile = filePkg.sourceFile;
298
- var interceptedExports = [];
299
- sourceFile.statements
300
- .filter(function (node) { var _a; return (_a = node.modifiers) === null || _a === void 0 ? void 0 : _a.some(function (modifier) { return (modifier === null || modifier === void 0 ? void 0 : modifier.kind) === typescript_1.default.SyntaxKind.ExportKeyword; }); })
301
- .forEach(function (node) {
302
- var _a, _b, _c;
303
- var exportName = '';
304
- if (typescript_1.default.isFunctionDeclaration(node) || typescript_1.default.isClassDeclaration(node)) {
305
- exportName = (_b = (_a = node.name) === null || _a === void 0 ? void 0 : _a.getText()) !== null && _b !== void 0 ? _b : '';
306
- }
307
- else if (typescript_1.default.isVariableStatement(node)) {
308
- var declaration = node.declarationList.declarations[0];
309
- if (!typescript_1.default.isArrowFunction(declaration.initializer))
310
- return;
311
- exportName = (_c = declaration.name) === null || _c === void 0 ? void 0 : _c.getText();
312
- }
313
- if (isPascalCase(exportName)) {
314
- var defaultLocalName = "__Next_Translate_Component_".concat(hash, "_").concat(interceptedExports.length);
315
- interceptExport(filePkg, exportName, defaultLocalName);
316
- interceptedExports.push({ exportName: exportName, defaultLocalName: defaultLocalName });
317
- }
318
- });
319
- return interceptedExports;
320
- }
321
- exports.interceptNamedExportsFromReactComponents = interceptNamedExportsFromReactComponents;
322
296
  function interceptExport(filePkg, exportName, defaultLocalName) {
323
297
  var exportContent = getNamedExport(filePkg, exportName, false);
324
298
  var finalLocalName = '';
@@ -407,3 +381,24 @@ function existPages(dir, pages) {
407
381
  return pages && fs_1.default.existsSync(path_1.default.join(dir, pages));
408
382
  }
409
383
  exports.existPages = existPages;
384
+ function existLocalesFolderWithNamespaces(dir) {
385
+ var existLocalesFolder = fs_1.default.existsSync(path_1.default.join(dir, 'locales'));
386
+ if (!existLocalesFolder)
387
+ return false;
388
+ var langFolder = fs_1.default.readdirSync(path_1.default.join(dir, 'locales')).find(function (file) {
389
+ var currentLangFolder = path_1.default.join(dir, 'locales', file);
390
+ return (fs_1.default.existsSync(currentLangFolder) &&
391
+ fs_1.default.lstatSync(currentLangFolder).isDirectory());
392
+ });
393
+ if (!langFolder)
394
+ return false;
395
+ var existNamespaceFile = fs_1.default
396
+ .readdirSync(path_1.default.join(dir, 'locales', langFolder))
397
+ .some(function (file) {
398
+ var namespaceFile = path_1.default.join(dir, 'locales', langFolder, file);
399
+ return (fs_1.default.existsSync(namespaceFile) &&
400
+ !fs_1.default.lstatSync(namespaceFile).isDirectory());
401
+ });
402
+ return existNamespaceFile;
403
+ }
404
+ exports.existLocalesFolderWithNamespaces = existLocalesFolderWithNamespaces;
package/lib/esm/index.js CHANGED
@@ -9,27 +9,16 @@ var __assign = (this && this.__assign) || function () {
9
9
  };
10
10
  return __assign.apply(this, arguments);
11
11
  };
12
- var __rest = (this && this.__rest) || function (s, e) {
13
- var t = {};
14
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
15
- t[p] = s[p];
16
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
17
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
18
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
19
- t[p[i]] = s[p[i]];
20
- }
21
- return t;
22
- };
23
12
  import fs from 'fs';
24
13
  import path from 'path';
25
- import { getDefaultExport, hasHOC, hasStaticName, parseFile, calculatePageDir, existPages, } from './utils';
14
+ import { getDefaultExport, hasHOC, hasStaticName, parseFile, calculatePageDir, existPages, existLocalesFolderWithNamespaces, } from './utils';
26
15
  var test = /\.(tsx|ts|js|mjs|jsx)$/;
27
16
  function nextTranslate(nextConfig) {
28
17
  if (nextConfig === void 0) { nextConfig = {}; }
29
18
  var basePath = pkgDir();
30
19
  basePath = path.resolve(path.relative(basePath, process.env.NEXT_TRANSLATE_PATH || '.'));
31
20
  var nextConfigI18n = nextConfig.i18n || {};
32
- var _a = require(path.join(basePath, 'i18n')), _b = _a.locales, locales = _b === void 0 ? nextConfigI18n.locales || [] : _b, _c = _a.defaultLocale, defaultLocale = _c === void 0 ? nextConfigI18n.defaultLocale || 'en' : _c, _d = _a.domains, domains = _d === void 0 ? nextConfigI18n.domains : _d, _e = _a.localeDetection, localeDetection = _e === void 0 ? nextConfigI18n.localeDetection : _e, _f = _a.loader, loader = _f === void 0 ? true : _f, pagesInDir = _a.pagesInDir, restI18n = __rest(_a, ["locales", "defaultLocale", "domains", "localeDetection", "loader", "pagesInDir"]);
21
+ var _a = require(path.join(basePath, 'i18n')), _b = _a.locales, locales = _b === void 0 ? nextConfigI18n.locales || [] : _b, _c = _a.defaultLocale, defaultLocale = _c === void 0 ? nextConfigI18n.defaultLocale || 'en' : _c, _d = _a.domains, domains = _d === void 0 ? nextConfigI18n.domains : _d, _e = _a.localeDetection, localeDetection = _e === void 0 ? nextConfigI18n.localeDetection : _e, _f = _a.loader, loader = _f === void 0 ? true : _f, pagesInDir = _a.pagesInDir, _g = _a.extensionsRgx, extensionsRgx = _g === void 0 ? test : _g, _h = _a.revalidate, revalidate = _h === void 0 ? 0 : _h;
33
22
  var nextConfigWithI18n = __assign(__assign({}, nextConfig), { i18n: {
34
23
  locales: locales,
35
24
  defaultLocale: defaultLocale,
@@ -38,6 +27,7 @@ function nextTranslate(nextConfig) {
38
27
  } });
39
28
  var pagesFolder = calculatePageDir('pages', pagesInDir, basePath);
40
29
  var appFolder = calculatePageDir('app', pagesInDir, basePath);
30
+ var existLocalesFolder = existLocalesFolderWithNamespaces(basePath);
41
31
  var existPagesFolder = existPages(basePath, pagesFolder);
42
32
  var hasGetInitialPropsOnAppJs = false;
43
33
  var hasAppJs = false;
@@ -82,8 +72,9 @@ function nextTranslate(nextConfig) {
82
72
  appFolder: path.join(appFolder, '/'),
83
73
  hasAppJs: hasAppJs,
84
74
  hasGetInitialPropsOnAppJs: hasGetInitialPropsOnAppJs,
85
- extensionsRgx: restI18n.extensionsRgx || test,
86
- revalidate: restI18n.revalidate || 0,
75
+ extensionsRgx: extensionsRgx,
76
+ revalidate: revalidate,
77
+ existLocalesFolder: existLocalesFolder,
87
78
  },
88
79
  },
89
80
  });
package/lib/esm/loader.js CHANGED
@@ -4,7 +4,7 @@ import templateWithLoader from './templateWithLoader';
4
4
  import templateAppDir from './templateAppDir';
5
5
  import { parseFile, getDefaultAppJs, getDefaultExport, hasExportName, hasStaticName, isPageToIgnore, hasHOC, removeCommentsFromCode, clientLine, } from './utils';
6
6
  export default function loader(rawCode) {
7
- var _a = this.getOptions(), basePath = _a.basePath, pagesFolder = _a.pagesFolder, appFolder = _a.appFolder, hasAppJs = _a.hasAppJs, hasGetInitialPropsOnAppJs = _a.hasGetInitialPropsOnAppJs, extensionsRgx = _a.extensionsRgx, revalidate = _a.revalidate;
7
+ var _a = this.getOptions(), basePath = _a.basePath, pagesFolder = _a.pagesFolder, appFolder = _a.appFolder, hasAppJs = _a.hasAppJs, hasGetInitialPropsOnAppJs = _a.hasGetInitialPropsOnAppJs, extensionsRgx = _a.extensionsRgx, revalidate = _a.revalidate, existLocalesFolder = _a.existLocalesFolder;
8
8
  try {
9
9
  var codeWithoutComments_1 = removeCommentsFromCode(rawCode).trim();
10
10
  var normalizedResourcePath = path
@@ -17,8 +17,9 @@ export default function loader(rawCode) {
17
17
  normalizedResourcePath.includes(appFolder.replace(/\\/g, '/'));
18
18
  var pagesPath = (shouldUseTemplateAppDir ? appFolder : pagesFolder);
19
19
  var normalizedPagesPath = pagesPath.replace(/\\/g, '/');
20
- if (normalizedResourcePath.includes('node_modules/next/dist/pages/_app') && !hasAppJs) {
21
- return getDefaultAppJs();
20
+ if (normalizedResourcePath.includes('node_modules/next/dist/pages/_app') &&
21
+ !hasAppJs) {
22
+ return getDefaultAppJs(existLocalesFolder);
22
23
  }
23
24
  if (normalizedResourcePath.includes('node_modules/'))
24
25
  return rawCode;
@@ -39,6 +40,7 @@ export default function loader(rawCode) {
39
40
  appFolder: appFolder,
40
41
  isClientComponent: isClientComponent,
41
42
  code: rawCode,
43
+ existLocalesFolder: existLocalesFolder,
42
44
  });
43
45
  }
44
46
  var defaultExport = getDefaultExport(pagePkg);
@@ -46,12 +48,13 @@ export default function loader(rawCode) {
46
48
  return rawCode;
47
49
  if (hasGetInitialPropsOnAppJs) {
48
50
  return pageNoExt === '/_app'
49
- ? templateWithHoc(pagePkg)
51
+ ? templateWithHoc(pagePkg, { existLocalesFolder: existLocalesFolder })
50
52
  : rawCode;
51
53
  }
52
54
  if (pageNoExt === '/_app') {
53
55
  return templateWithHoc(pagePkg, {
54
56
  skipInitialProps: true,
57
+ existLocalesFolder: existLocalesFolder,
55
58
  });
56
59
  }
57
60
  if (isPageToIgnore(page))
@@ -64,7 +67,7 @@ export default function loader(rawCode) {
64
67
  var isGetInitialProps = hasStaticName(pagePkg, defaultExport, 'getInitialProps');
65
68
  var hasLoader = isGetStaticProps || isGetServerSideProps || isGetInitialProps;
66
69
  if (isGetInitialProps || (!hasLoader && isWrapperWithExternalHOC)) {
67
- return templateWithHoc(pagePkg);
70
+ return templateWithHoc(pagePkg, { existLocalesFolder: existLocalesFolder });
68
71
  }
69
72
  var loader_1 = isGetServerSideProps || (!hasLoader && isDynamicPage && !isGetStaticPaths)
70
73
  ? 'getServerSideProps'
@@ -73,6 +76,7 @@ export default function loader(rawCode) {
73
76
  page: pageNoExt,
74
77
  loader: loader_1,
75
78
  revalidate: revalidate,
79
+ existLocalesFolder: existLocalesFolder,
76
80
  });
77
81
  }
78
82
  catch (e) {
@@ -1,67 +1,54 @@
1
- import { interceptExport, addLoadLocalesFrom, clientLine, interceptNamedExportsFromReactComponents, INTERNAL_CONFIG_KEY, } from './utils';
2
- var validPages = ['/page', '/layout', '/error', '/loading', '/not-found', '/global-error'];
1
+ import { interceptExport, addLoadLocalesFrom, clientLine, INTERNAL_CONFIG_KEY, } from './utils';
2
+ var validPages = [
3
+ '/page',
4
+ '/layout',
5
+ '/error',
6
+ '/loading',
7
+ '/not-found',
8
+ '/global-error',
9
+ ];
3
10
  var validPagesRegex = new RegExp("(".concat(validPages.join('|'), ")$"));
4
- var lastPathname = '';
5
11
  export default function templateAppDir(pagePkg, _a) {
6
- var _b = _a === void 0 ? {} : _a, _c = _b.code, code = _c === void 0 ? '' : _c, _d = _b.pageNoExt, pageNoExt = _d === void 0 ? '/' : _d, _e = _b.normalizedResourcePath, normalizedResourcePath = _e === void 0 ? '' : _e, _f = _b.appFolder, appFolder = _f === void 0 ? '' : _f, _g = _b.isClientComponent, isClientComponent = _g === void 0 ? false : _g;
12
+ var _b = _a === void 0 ? {} : _a, _c = _b.code, code = _c === void 0 ? '' : _c, _d = _b.pageNoExt, pageNoExt = _d === void 0 ? '/' : _d, _e = _b.normalizedResourcePath, normalizedResourcePath = _e === void 0 ? '' : _e, _f = _b.appFolder, appFolder = _f === void 0 ? '' : _f, _g = _b.isClientComponent, isClientComponent = _g === void 0 ? false : _g, _h = _b.existLocalesFolder, existLocalesFolder = _h === void 0 ? true : _h;
7
13
  var routeType = validPages.find(function (pageName) { return pageNoExt.endsWith(pageName); }) || 'component';
8
14
  var isPage = routeType !== 'component' && normalizedResourcePath.includes(appFolder);
9
- if (!isPage && !isClientComponent)
15
+ if (!isPage)
10
16
  return code;
11
17
  var hash = Date.now().toString(16);
12
- var pathname = isPage ? pageNoExt.replace(validPagesRegex, '/') : lastPathname;
13
- lastPathname = pathname;
18
+ var pathname = pageNoExt.replace(validPagesRegex, '/');
14
19
  var pageVariableName = interceptExport(pagePkg, 'default', "__Next_Translate__Page__".concat(hash, "__"));
15
20
  if (isPage && !pageVariableName)
16
21
  return code;
17
- if (isClientComponent && !code.includes('next-translate'))
18
- return code;
19
22
  if (isClientComponent) {
20
- return templateClientComponent({
23
+ return templateRCCPage({
21
24
  pagePkg: pagePkg,
22
25
  hash: hash,
23
26
  pageVariableName: pageVariableName,
24
27
  pathname: pathname,
25
- isPage: isPage,
26
28
  routeType: routeType,
29
+ existLocalesFolder: existLocalesFolder,
27
30
  });
28
31
  }
29
- return templateServerPage({
32
+ return templateRSCPage({
30
33
  pagePkg: pagePkg,
31
34
  hash: hash,
32
35
  pageVariableName: pageVariableName,
33
36
  pathname: pathname,
34
37
  routeType: routeType,
38
+ existLocalesFolder: existLocalesFolder,
35
39
  });
36
40
  }
37
- function templateServerPage(_a) {
38
- var pagePkg = _a.pagePkg, hash = _a.hash, pageVariableName = _a.pageVariableName, pathname = _a.pathname, routeType = _a.routeType;
41
+ function templateRSCPage(_a) {
42
+ var pagePkg = _a.pagePkg, hash = _a.hash, pageVariableName = _a.pageVariableName, pathname = _a.pathname, routeType = _a.routeType, existLocalesFolder = _a.existLocalesFolder;
39
43
  var code = pagePkg.getCode();
40
- return "\n import ".concat(INTERNAL_CONFIG_KEY, " from '@next-translate-root/i18n'\n import __loadNamespaces from 'next-translate/loadNamespaces'\n import __nt_store from 'next-translate/_store'\n\n ").concat(code, "\n\n export default async function __Next_Translate_new__").concat(hash, "__(props) {\n const config = { \n ...").concat(INTERNAL_CONFIG_KEY, ",\n locale: props.params?.lang ?? props.searchParams?.lang ?? ").concat(INTERNAL_CONFIG_KEY, ".defaultLocale,\n loaderName: 'server ").concat(routeType, "',\n pathname: '").concat(pathname, "',\n ").concat(addLoadLocalesFrom(), "\n }\n const { __lang, __namespaces } = await __loadNamespaces(config)\n\n __nt_store.set({ lang: __lang, namespaces: __namespaces, config })\n\n return <").concat(pageVariableName, " {...props} />\n }\n");
44
+ return "\n import ".concat(INTERNAL_CONFIG_KEY, " from '@next-translate-root/i18n'\n import AppDirI18nProvider from 'next-translate/AppDirI18nProvider'\n import __loadNamespaces from 'next-translate/loadNamespaces'\n\n ").concat(code, "\n\n export default async function __Next_Translate_new__").concat(hash, "__(props) {\n const config = { \n ...").concat(INTERNAL_CONFIG_KEY, ",\n locale: props.params?.lang ?? props.searchParams?.lang ?? ").concat(INTERNAL_CONFIG_KEY, ".defaultLocale,\n loaderName: 'server ").concat(routeType, "',\n pathname: '").concat(pathname, "'\n }\n\n const { __lang, __namespaces } = await __loadNamespaces({ ...config, ").concat(addLoadLocalesFrom(existLocalesFolder), " });\n globalThis.__NEXT_TRANSLATE__ = { lang: __lang, namespaces: __namespaces, config }\n\n return <AppDirI18nProvider lang={__lang} namespaces={__namespaces} config={config}><").concat(pageVariableName, " {...props} /></AppDirI18nProvider>\n }\n");
41
45
  }
42
- function templateClientComponent(_a) {
43
- var pagePkg = _a.pagePkg, hash = _a.hash, pageVariableName = _a.pageVariableName, pathname = _a.pathname, isPage = _a.isPage, routeType = _a.routeType;
46
+ function templateRCCPage(_a) {
47
+ var pagePkg = _a.pagePkg, hash = _a.hash, pageVariableName = _a.pageVariableName, pathname = _a.pathname, routeType = _a.routeType, existLocalesFolder = _a.existLocalesFolder;
44
48
  var topLine = clientLine[0];
45
- var namedExportsModified = modifyNamedExportsComponents(pagePkg, hash);
46
- var exportDefault = pageVariableName
47
- ? "export default " + wrapClientComponent({ name: "__Next_Translate_new__".concat(hash, "__"), pathname: pathname, isPage: isPage, pageVariableName: pageVariableName, routeType: routeType })
48
- : '';
49
49
  var clientCode = pagePkg.getCode();
50
50
  clientLine.forEach(function (line) {
51
51
  clientCode = clientCode.replace(line, '');
52
52
  });
53
- return "".concat(topLine, "\n import ").concat(INTERNAL_CONFIG_KEY, " from '@next-translate-root/i18n'\n import __loadNamespaces from 'next-translate/loadNamespaces'\n import __nt_store from 'next-translate/_store'\n import { useSearchParams as __useSearchParams, useParams as __useParams } from 'next/navigation'\n import { use as __use } from 'react';\n\n ").concat(clientCode, "\n\n ").concat(exportDefault, "\n ").concat(namedExportsModified, "\n");
54
- }
55
- function wrapClientComponent(_a) {
56
- var _b = _a.name, name = _b === void 0 ? '' : _b, _c = _a.pathname, pathname = _c === void 0 ? '' : _c, _d = _a.isPage, isPage = _d === void 0 ? false : _d, _e = _a.pageVariableName, pageVariableName = _e === void 0 ? '' : _e, _f = _a.routeType, routeType = _f === void 0 ? 'component' : _f;
57
- return "function ".concat(name, "(props) {\n const searchParams = __useSearchParams()\n const params = __useParams()\n const lang = params.lang ?? searchParams.get('lang') ?? ").concat(INTERNAL_CONFIG_KEY, ".defaultLocale\n const config = {\n ...").concat(INTERNAL_CONFIG_KEY, ",\n locale: lang,\n loaderName: 'client ").concat(routeType, "',\n pathname: '").concat(pathname, "',\n logBuild: ").concat(isPage, ",\n ").concat(addLoadLocalesFrom(), "\n }\n const { __lang, __namespaces } = __use(__loadNamespaces(config));\n\n __nt_store.set({ lang, namespaces: __namespaces, config })\n\n return <").concat(pageVariableName, " {...props} />\n }");
58
- }
59
- function modifyNamedExportsComponents(pagePkg, hash) {
60
- return interceptNamedExportsFromReactComponents(pagePkg, hash)
61
- .map(function (_a) {
62
- var exportName = _a.exportName, defaultLocalName = _a.defaultLocalName;
63
- return "\n ".concat(wrapClientComponent({ name: defaultLocalName, pathname: lastPathname, isPage: false, pageVariableName: exportName }), "\n export { ").concat(defaultLocalName, " as ").concat(exportName, " }\n ");
64
- })
65
- .join('')
66
- .trim();
53
+ return "".concat(topLine, "\n import ").concat(INTERNAL_CONFIG_KEY, " from '@next-translate-root/i18n'\n import AppDirI18nProvider from 'next-translate/AppDirI18nProvider'\n import { useSearchParams as __useSearchParams, useParams as __useParams } from 'next/navigation'\n import { use as __use } from 'react'\n import __loadNamespaces from 'next-translate/loadNamespaces'\n\n ").concat(clientCode, "\n\n export default function __Next_Translate_new__").concat(hash, "__(props) {\n const searchParams = __useSearchParams()\n const params = __useParams()\n const lang = params.lang ?? searchParams.get('lang') ?? ").concat(INTERNAL_CONFIG_KEY, ".defaultLocale\n const config = {\n ...").concat(INTERNAL_CONFIG_KEY, ",\n locale: lang,\n loaderName: 'client ").concat(routeType, "',\n pathname: '").concat(pathname, "',\n }\n\n const { __lang, __namespaces } = __use(__loadNamespaces({ ...config, ").concat(addLoadLocalesFrom(existLocalesFolder), " }));\n globalThis.__NEXT_TRANSLATE__ = { lang: __lang, namespaces: __namespaces, config }\n\n return <").concat(pageVariableName, " {...props} />\n }\n");
67
54
  }
@@ -1,10 +1,10 @@
1
- import { INTERNAL_CONFIG_KEY, interceptExport, addLoadLocalesFrom } from './utils';
1
+ import { INTERNAL_CONFIG_KEY, interceptExport, addLoadLocalesFrom, } from './utils';
2
2
  export default function templateWithHoc(pagePkg, _a) {
3
- var _b = _a === void 0 ? {} : _a, _c = _b.skipInitialProps, skipInitialProps = _c === void 0 ? false : _c;
3
+ var _b = _a === void 0 ? {} : _a, _c = _b.skipInitialProps, skipInitialProps = _c === void 0 ? false : _c, _d = _b.existLocalesFolder, existLocalesFolder = _d === void 0 ? true : _d;
4
4
  var hash = Date.now().toString(16);
5
5
  var pageVariableName = interceptExport(pagePkg, 'default', "__Next_Translate__Page__".concat(hash, "__"));
6
6
  var hasDefaultExport = Boolean(pageVariableName);
7
7
  if (!hasDefaultExport)
8
8
  return pagePkg.getCode();
9
- return "\n import ".concat(INTERNAL_CONFIG_KEY, " from '@next-translate-root/i18n'\n import __appWithI18n from 'next-translate/appWithI18n'\n ").concat(pagePkg.getCode(), "\n export default __appWithI18n(").concat(pageVariableName, ", {\n ...").concat(INTERNAL_CONFIG_KEY, ",\n isLoader: true,\n skipInitialProps: ").concat(skipInitialProps, ",\n ").concat(addLoadLocalesFrom(), "\n });\n ");
9
+ return "\n import ".concat(INTERNAL_CONFIG_KEY, " from '@next-translate-root/i18n'\n import __appWithI18n from 'next-translate/appWithI18n'\n ").concat(pagePkg.getCode(), "\n export default __appWithI18n(").concat(pageVariableName, ", {\n ...").concat(INTERNAL_CONFIG_KEY, ",\n isLoader: true,\n skipInitialProps: ").concat(skipInitialProps, ",\n ").concat(addLoadLocalesFrom(existLocalesFolder), "\n });\n ");
10
10
  }
@@ -1,9 +1,9 @@
1
- import { interceptExport, addLoadLocalesFrom, INTERNAL_CONFIG_KEY } from './utils';
1
+ import { interceptExport, addLoadLocalesFrom, INTERNAL_CONFIG_KEY, } from './utils';
2
2
  export default function templateWithLoader(pagePkg, _a) {
3
- var _b = _a === void 0 ? {} : _a, _c = _b.page, page = _c === void 0 ? '' : _c, _d = _b.loader, loader = _d === void 0 ? 'getStaticProps' : _d, _e = _b.revalidate, revalidate = _e === void 0 ? 0 : _e;
3
+ var _b = _a === void 0 ? {} : _a, _c = _b.page, page = _c === void 0 ? '' : _c, _d = _b.loader, loader = _d === void 0 ? 'getStaticProps' : _d, _e = _b.revalidate, revalidate = _e === void 0 ? 0 : _e, _f = _b.existLocalesFolder, existLocalesFolder = _f === void 0 ? true : _f;
4
4
  var hash = Date.now().toString(16);
5
5
  var oldLoaderName = interceptExport(pagePkg, loader, "__Next_Translate_old_".concat(loader, "__").concat(hash, "__"));
6
6
  var newLoaderName = "__Next_Translate__".concat(loader, "__").concat(hash, "__");
7
7
  var hasLoader = Boolean(oldLoaderName);
8
- return "\n import ".concat(INTERNAL_CONFIG_KEY, " from '@next-translate-root/i18n'\n import __loadNamespaces from 'next-translate/loadNamespaces'\n ").concat(pagePkg.getCode(), "\n async function ").concat(newLoaderName, "(ctx) {\n ").concat(hasLoader ? "const res = await ".concat(oldLoaderName, "(ctx)") : '', "\n return {\n ").concat(hasLoader && revalidate > 0 ? "revalidate: ".concat(revalidate, ",") : '', "\n ").concat(hasLoader ? '...res,' : '', "\n props: {\n ").concat(hasLoader ? '...(res.props || {}),' : '', "\n ...(await __loadNamespaces({\n ...ctx,\n ...").concat(INTERNAL_CONFIG_KEY, ",\n pathname: '").concat(page, "',\n loaderName: '").concat(loader, "',\n ").concat(addLoadLocalesFrom(), "\n }))\n }\n }\n }\n export { ").concat(newLoaderName, " as ").concat(loader, " }\n ");
8
+ return "\n import ".concat(INTERNAL_CONFIG_KEY, " from '@next-translate-root/i18n'\n import __loadNamespaces from 'next-translate/loadNamespaces'\n ").concat(pagePkg.getCode(), "\n async function ").concat(newLoaderName, "(ctx) {\n ").concat(hasLoader ? "const res = await ".concat(oldLoaderName, "(ctx)") : '', "\n return {\n ").concat(hasLoader && revalidate > 0 ? "revalidate: ".concat(revalidate, ",") : '', "\n ").concat(hasLoader ? '...res,' : '', "\n props: {\n ").concat(hasLoader ? '...(res.props || {}),' : '', "\n ...(await __loadNamespaces({\n ...ctx,\n ...").concat(INTERNAL_CONFIG_KEY, ",\n pathname: '").concat(page, "',\n loaderName: '").concat(loader, "',\n ").concat(addLoadLocalesFrom(existLocalesFolder), "\n }))\n }\n }\n }\n export { ").concat(newLoaderName, " as ").concat(loader, " }\n ");
9
9
  }
package/lib/esm/utils.js CHANGED
@@ -25,11 +25,14 @@ var specFileOrFolderRgx = /(__mocks__|__tests__)|(\.(spec|test)\.(tsx|ts|js|jsx)
25
25
  export var INTERNAL_CONFIG_KEY = '__i18nConfig';
26
26
  export var clientLine = ['"use client"', "'use client'"];
27
27
  export var defaultLoader = '(l, n) => import(`@next-translate-root/locales/${l}/${n}`).then(m => m.default)';
28
- export function getDefaultAppJs() {
29
- return "\n import ".concat(INTERNAL_CONFIG_KEY, " from '@next-translate-root/i18n'\n import appWithI18n from 'next-translate/appWithI18n'\n \n function MyApp({ Component, pageProps }) {\n return <Component {...pageProps} />\n }\n \n export default appWithI18n(MyApp, {\n ...").concat(INTERNAL_CONFIG_KEY, ",\n skipInitialProps: true,\n isLoader: true,\n ").concat(addLoadLocalesFrom(), "\n })\n ");
28
+ export function getDefaultAppJs(existLocalesFolder) {
29
+ return "\n import ".concat(INTERNAL_CONFIG_KEY, " from '@next-translate-root/i18n'\n import appWithI18n from 'next-translate/appWithI18n'\n \n function MyApp({ Component, pageProps }) {\n return <Component {...pageProps} />\n }\n \n export default appWithI18n(MyApp, {\n ...").concat(INTERNAL_CONFIG_KEY, ",\n skipInitialProps: true,\n isLoader: true,\n ").concat(addLoadLocalesFrom(existLocalesFolder), "\n })\n ");
30
30
  }
31
- export function addLoadLocalesFrom() {
32
- return "loadLocaleFrom: typeof ".concat(INTERNAL_CONFIG_KEY, ".loadLocaleFrom === 'function' ? ").concat(INTERNAL_CONFIG_KEY, ".loadLocaleFrom : ").concat(defaultLoader, ",");
31
+ export function addLoadLocalesFrom(existLocalesFolder) {
32
+ var defaultFn = existLocalesFolder
33
+ ? defaultLoader
34
+ : "() => Promise.resolve({})";
35
+ return "loadLocaleFrom: ".concat(INTERNAL_CONFIG_KEY, ".loadLocaleFrom || (").concat(defaultFn, "),");
33
36
  }
34
37
  export function getTsCompilerOptions(basePath, cutDependencies) {
35
38
  if (cutDependencies === void 0) { cutDependencies = false; }
@@ -266,34 +269,6 @@ export function isNotExportModifier(modifier) {
266
269
  ];
267
270
  return !exportModifiers.includes(modifier.kind);
268
271
  }
269
- function isPascalCase(str) {
270
- return str.length > 1 && str[0] === str[0].toUpperCase() && str[1] === str[1].toLowerCase();
271
- }
272
- export function interceptNamedExportsFromReactComponents(filePkg, hash) {
273
- var sourceFile = filePkg.sourceFile;
274
- var interceptedExports = [];
275
- sourceFile.statements
276
- .filter(function (node) { var _a; return (_a = node.modifiers) === null || _a === void 0 ? void 0 : _a.some(function (modifier) { return (modifier === null || modifier === void 0 ? void 0 : modifier.kind) === ts.SyntaxKind.ExportKeyword; }); })
277
- .forEach(function (node) {
278
- var _a, _b, _c;
279
- var exportName = '';
280
- if (ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node)) {
281
- exportName = (_b = (_a = node.name) === null || _a === void 0 ? void 0 : _a.getText()) !== null && _b !== void 0 ? _b : '';
282
- }
283
- else if (ts.isVariableStatement(node)) {
284
- var declaration = node.declarationList.declarations[0];
285
- if (!ts.isArrowFunction(declaration.initializer))
286
- return;
287
- exportName = (_c = declaration.name) === null || _c === void 0 ? void 0 : _c.getText();
288
- }
289
- if (isPascalCase(exportName)) {
290
- var defaultLocalName = "__Next_Translate_Component_".concat(hash, "_").concat(interceptedExports.length);
291
- interceptExport(filePkg, exportName, defaultLocalName);
292
- interceptedExports.push({ exportName: exportName, defaultLocalName: defaultLocalName });
293
- }
294
- });
295
- return interceptedExports;
296
- }
297
272
  export function interceptExport(filePkg, exportName, defaultLocalName) {
298
273
  var exportContent = getNamedExport(filePkg, exportName, false);
299
274
  var finalLocalName = '';
@@ -378,3 +353,23 @@ export function calculatePageDir(name, pagesInDir, dir) {
378
353
  export function existPages(dir, pages) {
379
354
  return pages && fs.existsSync(path.join(dir, pages));
380
355
  }
356
+ export function existLocalesFolderWithNamespaces(dir) {
357
+ var existLocalesFolder = fs.existsSync(path.join(dir, 'locales'));
358
+ if (!existLocalesFolder)
359
+ return false;
360
+ var langFolder = fs.readdirSync(path.join(dir, 'locales')).find(function (file) {
361
+ var currentLangFolder = path.join(dir, 'locales', file);
362
+ return (fs.existsSync(currentLangFolder) &&
363
+ fs.lstatSync(currentLangFolder).isDirectory());
364
+ });
365
+ if (!langFolder)
366
+ return false;
367
+ var existNamespaceFile = fs
368
+ .readdirSync(path.join(dir, 'locales', langFolder))
369
+ .some(function (file) {
370
+ var namespaceFile = path.join(dir, 'locales', langFolder, file);
371
+ return (fs.existsSync(namespaceFile) &&
372
+ !fs.lstatSync(namespaceFile).isDirectory());
373
+ });
374
+ return existNamespaceFile;
375
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "next-translate-plugin",
3
- "version": "2.4.0-canary.5",
3
+ "version": "2.4.1",
4
4
  "description": "Tiny and powerful i18n plugin to translate your Next.js pages.",
5
5
  "license": "MIT",
6
6
  "keywords": [
@@ -72,7 +72,7 @@
72
72
  "husky": "7.0.4",
73
73
  "jest": "27.3.1",
74
74
  "next": "13.1.2",
75
- "next-translate": "2.0.0-canary.1",
75
+ "next-translate": "2.4.0",
76
76
  "prettier": "2.8.3",
77
77
  "pretty-quick": "3.1.3",
78
78
  "react": "18.2.0",
@@ -80,7 +80,7 @@
80
80
  "supertest": "6.3.3"
81
81
  },
82
82
  "peerDependencies": {
83
- "next-translate": ">= 2.3.0"
83
+ "next-translate": ">= 2.4.1"
84
84
  },
85
85
  "prettier": {
86
86
  "trailingComma": "es5",
@@ -104,4 +104,4 @@
104
104
  "^.+\\.(j|t)sx?$": "babel-jest"
105
105
  }
106
106
  }
107
- }
107
+ }
@@ -1,8 +1,9 @@
1
1
  import { ParsedFilePkg } from './types';
2
- export default function templateAppDir(pagePkg: ParsedFilePkg, { code, pageNoExt, normalizedResourcePath, appFolder, isClientComponent, }?: {
2
+ export default function templateAppDir(pagePkg: ParsedFilePkg, { code, pageNoExt, normalizedResourcePath, appFolder, isClientComponent, existLocalesFolder, }?: {
3
3
  code?: string | undefined;
4
4
  pageNoExt?: string | undefined;
5
5
  normalizedResourcePath?: string | undefined;
6
6
  appFolder?: string | undefined;
7
7
  isClientComponent?: boolean | undefined;
8
+ existLocalesFolder?: boolean | undefined;
8
9
  }): string;
@@ -1,4 +1,5 @@
1
1
  import { ParsedFilePkg } from './types';
2
- export default function templateWithHoc(pagePkg: ParsedFilePkg, { skipInitialProps }?: {
2
+ export default function templateWithHoc(pagePkg: ParsedFilePkg, { skipInitialProps, existLocalesFolder }?: {
3
3
  skipInitialProps?: boolean | undefined;
4
+ existLocalesFolder?: boolean | undefined;
4
5
  }): string;
@@ -1,6 +1,7 @@
1
1
  import { ParsedFilePkg } from './types';
2
- export default function templateWithLoader(pagePkg: ParsedFilePkg, { page, loader, revalidate, }?: {
2
+ export default function templateWithLoader(pagePkg: ParsedFilePkg, { page, loader, revalidate, existLocalesFolder, }?: {
3
3
  page?: string | undefined;
4
4
  loader?: string | undefined;
5
5
  revalidate?: number | undefined;
6
+ existLocalesFolder?: boolean | undefined;
6
7
  }): string;
package/types.d.ts CHANGED
@@ -7,6 +7,7 @@ export interface LoaderOptions {
7
7
  hasGetInitialPropsOnAppJs: boolean;
8
8
  extensionsRgx: RegExp;
9
9
  revalidate: number;
10
+ existLocalesFolder: boolean;
10
11
  }
11
12
  export declare type Transformer = (rootNode: ts.SourceFile, context: ts.TransformationContext) => ts.SourceFile;
12
13
  export interface ParsedFilePkg {
package/utils.d.ts CHANGED
@@ -3,8 +3,8 @@ import { ParsedFilePkg } from './types';
3
3
  export declare const INTERNAL_CONFIG_KEY = "__i18nConfig";
4
4
  export declare const clientLine: string[];
5
5
  export declare const defaultLoader = "(l, n) => import(`@next-translate-root/locales/${l}/${n}`).then(m => m.default)";
6
- export declare function getDefaultAppJs(): string;
7
- export declare function addLoadLocalesFrom(): string;
6
+ export declare function getDefaultAppJs(existLocalesFolder: boolean): string;
7
+ export declare function addLoadLocalesFrom(existLocalesFolder: boolean): string;
8
8
  export declare function getTsCompilerOptions(basePath: string, cutDependencies?: boolean): ts.CompilerOptions;
9
9
  export declare function getFilePkg(program: ts.Program, filename: string): ParsedFilePkg;
10
10
  export declare function parseFile(basePath: string, filename: string): ParsedFilePkg;
@@ -21,13 +21,8 @@ export declare function hasStaticName(filePkg: ParsedFilePkg, target: ts.Declara
21
21
  export declare function isPageToIgnore(pageFilePath: string): boolean;
22
22
  export declare function hasHOC(filePkg: ParsedFilePkg): boolean;
23
23
  export declare function isNotExportModifier(modifier: ts.Modifier): boolean;
24
- declare type InterceptedExport = {
25
- exportName: string;
26
- defaultLocalName: string;
27
- };
28
- export declare function interceptNamedExportsFromReactComponents(filePkg: ParsedFilePkg, hash: string): InterceptedExport[];
29
24
  export declare function interceptExport(filePkg: ParsedFilePkg, exportName: string, defaultLocalName: string): string;
30
25
  export declare function removeCommentsFromCode(code: string): string;
31
26
  export declare function calculatePageDir(name: 'pages' | 'app', pagesInDir: string | undefined, dir: string): string;
32
27
  export declare function existPages(dir: string, pages: string | undefined): boolean | "" | undefined;
33
- export {};
28
+ export declare function existLocalesFolderWithNamespaces(dir: string): boolean;