vike 0.4.228-commit-1bb55f1 → 0.4.229-commit-2a06dcc

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 (36) hide show
  1. package/dist/cjs/node/plugin/index.js +3 -1
  2. package/dist/cjs/node/plugin/plugins/build/pluginModuleBanner.js +4 -4
  3. package/dist/cjs/node/plugin/plugins/devConfig/determineOptimizeDeps.js +5 -0
  4. package/dist/cjs/node/plugin/plugins/envVars.js +17 -19
  5. package/dist/cjs/node/plugin/plugins/importUserCode/getVirtualFileImportUserCode.js +3 -1
  6. package/dist/cjs/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/configDefinitionsBuiltIn.js +1 -0
  7. package/dist/cjs/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/crawlPlusFiles.js +1 -1
  8. package/dist/cjs/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/transpileAndExecuteFile.js +2 -2
  9. package/dist/cjs/node/plugin/plugins/replaceConstants.js +76 -0
  10. package/dist/cjs/node/plugin/shared/applyRegExWithMagicString.js +10 -0
  11. package/dist/cjs/node/plugin/shared/findPageFiles.js +1 -1
  12. package/dist/cjs/node/runtime/html/renderHtml.js +6 -0
  13. package/dist/cjs/utils/PROJECT_VERSION.js +1 -1
  14. package/dist/cjs/utils/isScriptFile.js +24 -21
  15. package/dist/cjs/utils/parseNpmPackage.js +1 -0
  16. package/dist/esm/node/plugin/index.js +3 -1
  17. package/dist/esm/node/plugin/plugins/build/pluginModuleBanner.js +4 -4
  18. package/dist/esm/node/plugin/plugins/devConfig/determineOptimizeDeps.js +6 -1
  19. package/dist/esm/node/plugin/plugins/envVars.js +18 -20
  20. package/dist/esm/node/plugin/plugins/importUserCode/getVirtualFileImportUserCode.js +4 -2
  21. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/configDefinitionsBuiltIn.js +1 -0
  22. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/crawlPlusFiles.js +2 -2
  23. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/transpileAndExecuteFile.js +3 -3
  24. package/dist/esm/node/plugin/plugins/replaceConstants.d.ts +3 -0
  25. package/dist/esm/node/plugin/plugins/replaceConstants.js +71 -0
  26. package/dist/esm/node/plugin/shared/applyRegExWithMagicString.d.ts +3 -0
  27. package/dist/esm/node/plugin/shared/applyRegExWithMagicString.js +8 -0
  28. package/dist/esm/node/plugin/shared/findPageFiles.js +2 -2
  29. package/dist/esm/node/runtime/html/renderHtml.js +6 -0
  30. package/dist/esm/utils/PROJECT_VERSION.d.ts +1 -1
  31. package/dist/esm/utils/PROJECT_VERSION.js +1 -1
  32. package/dist/esm/utils/isScriptFile.d.ts +5 -5
  33. package/dist/esm/utils/isScriptFile.js +23 -20
  34. package/dist/esm/utils/parseNpmPackage.d.ts +2 -0
  35. package/dist/esm/utils/parseNpmPackage.js +1 -1
  36. package/package.json +1 -1
@@ -28,6 +28,7 @@ const getPageAssets_js_1 = require("../runtime/renderPage/getPageAssets.js");
28
28
  const resolveClientEntriesDev_js_1 = require("./shared/resolveClientEntriesDev.js");
29
29
  const workaroundCssModuleHmr_js_1 = require("./plugins/workaroundCssModuleHmr.js");
30
30
  const workaroundVite6HmrRegression_js_1 = require("./plugins/workaroundVite6HmrRegression.js");
31
+ const replaceConstants_js_1 = require("./plugins/replaceConstants.js");
31
32
  // We don't call this in ./onLoad.ts to avoid a cyclic dependency with utils.ts
32
33
  (0, getPageAssets_js_1.setResolveClientEntriesDev)(resolveClientEntriesDev_js_1.resolveClientEntriesDev);
33
34
  // Return `PluginInterop` instead of `Plugin` to avoid type mismatch upon different Vite versions
@@ -45,7 +46,8 @@ function plugin(vikeVitePluginOptions = {}) {
45
46
  (0, envVars_js_1.envVarsPlugin)(),
46
47
  (0, fileEnv_js_1.fileEnv)(),
47
48
  (0, workaroundCssModuleHmr_js_1.workaroundCssModuleHmr)(),
48
- (0, workaroundVite6HmrRegression_js_1.workaroundVite6HmrRegression)()
49
+ (0, workaroundVite6HmrRegression_js_1.workaroundVite6HmrRegression)(),
50
+ (0, replaceConstants_js_1.replaceConstants)()
49
51
  ];
50
52
  Object.assign(plugins, { __vikeVitePluginOptions: vikeVitePluginOptions });
51
53
  return plugins;
@@ -32,14 +32,14 @@ function pluginModuleBanner() {
32
32
  if (id.startsWith(config.root))
33
33
  id = id.slice(config.root.length + 1);
34
34
  id = id.replaceAll('*/', '*\\/'); // https://github.com/vikejs/vike/issues/2377
35
- const s = new magic_string_1.default(code);
35
+ const magicString = new magic_string_1.default(code);
36
36
  // Use legal comment so that esbuild doesn't remove it.
37
37
  // - Terser still removes the comment, but I guess users use terser to minify JavaScript so I guess it's a good thing that comment is removed.
38
38
  // - https://esbuild.github.io/api/#legal-comments
39
- s.prepend(`/*! ${id} [vike:pluginModuleBanner] */\n`);
39
+ magicString.prepend(`/*! ${id} [vike:pluginModuleBanner] */\n`);
40
40
  return {
41
- code: s.toString(),
42
- map: s.generateMap({ hires: true, source: id })
41
+ code: magicString.toString(),
42
+ map: magicString.generateMap({ hires: true, source: id })
43
43
  };
44
44
  }
45
45
  }
@@ -57,6 +57,11 @@ async function getPageDeps(config, pageConfigs) {
57
57
  return;
58
58
  if (definedAt.definedBy)
59
59
  return;
60
+ if (definedAt.importPathAbsolute) {
61
+ const npmPackageName = (0, utils_js_1.getNpmPackageName)(definedAt.importPathAbsolute);
62
+ if (npmPackageName && config.optimizeDeps.exclude?.includes(npmPackageName))
63
+ return;
64
+ }
60
65
  if (definedAt.filePathAbsoluteUserRootDir !== null) {
61
66
  // Vite expects entries to be filesystem absolute paths (surprisingly so).
62
67
  addEntry(definedAt.filePathAbsoluteFilesystem);
@@ -10,7 +10,8 @@ const utils_js_1 = require("../utils.js");
10
10
  const getFilePath_js_1 = require("../shared/getFilePath.js");
11
11
  const normalizeId_js_1 = require("../shared/normalizeId.js");
12
12
  const isViteServerBuild_js_1 = require("../shared/isViteServerBuild.js");
13
- // TODO/enventually: (after we implemented vike.config.js)
13
+ const applyRegExWithMagicString_js_1 = require("../shared/applyRegExWithMagicString.js");
14
+ // TODO/enventually:
14
15
  // - Make import.meta.env work inside +config.js
15
16
  // - For it to work, we'll probably need the user to define the settings (e.g. `envDir`) for loadEnv() inside vike.config.js instead of vite.config.js
16
17
  // - Or stop using Vite's `mode` implemention and have Vike implement its own `mode` feature? (So that the only dependencies are `$ vike build --mode staging` and `$ MODE=staging vike build`.)
@@ -27,7 +28,6 @@ function envVarsPlugin() {
27
28
  enforce: 'post',
28
29
  configResolved(config_) {
29
30
  config = config_;
30
- config.command;
31
31
  envsAll = (0, vite_1.loadEnv)(config.mode, config.envDir || config.root, '');
32
32
  config.plugins.sort((0, utils_js_1.lowerFirst)((plugin) => (plugin.name === 'vite:define' ? 1 : 0)));
33
33
  },
@@ -43,21 +43,22 @@ function envVarsPlugin() {
43
43
  return;
44
44
  const isBuild = config.command === 'build';
45
45
  const isClientSide = !(0, isViteServerBuild_js_1.isViteServerBuild_safe)(config, options);
46
- const s = new magic_string_1.default(code);
47
- Object.entries(envsAll)
46
+ const magicString = new magic_string_1.default(code);
47
+ // Find & check
48
+ const replacements = Object.entries(envsAll)
48
49
  .filter(([key]) => {
49
50
  // Already handled by Vite
50
51
  const envPrefix = !config.envPrefix ? [] : (0, utils_js_1.isArray)(config.envPrefix) ? config.envPrefix : [config.envPrefix];
51
52
  return !envPrefix.some((prefix) => key.startsWith(prefix));
52
53
  })
53
- .forEach(([envName, envVal]) => {
54
+ .map(([envName, envVal]) => {
54
55
  const envStatement = `import.meta.env.${envName}`;
55
- const envStatementRegExStr = (0, utils_js_1.escapeRegex)(envStatement) + '\\b';
56
+ const envStatementRegExpStr = (0, utils_js_1.escapeRegex)(envStatement) + '\\b';
56
57
  // Security check
57
58
  {
58
59
  const isPrivate = !envName.startsWith(PUBLIC_ENV_PREFIX) && !PUBLIC_ENV_ALLOWLIST.includes(envName);
59
60
  if (isPrivate && isClientSide) {
60
- if (!new RegExp(envStatementRegExStr).test(code))
61
+ if (!new RegExp(envStatementRegExpStr).test(code))
61
62
  return;
62
63
  const modulePath = (0, getFilePath_js_1.getModuleFilePathAbsolute)(id, config);
63
64
  const errMsgAddendum = isBuild ? '' : ' (Vike will prevent your app from building for production)';
@@ -75,22 +76,19 @@ function envVarsPlugin() {
75
76
  // Double check
76
77
  (0, utils_js_1.assert)(!(isPrivate && isClientSide) || !isBuild);
77
78
  }
78
- // Apply
79
- applyEnvVar(s, envStatementRegExStr, envVal);
79
+ return { regExpStr: envStatementRegExpStr, replacement: envVal };
80
+ })
81
+ .filter(utils_js_1.isNotNullish);
82
+ // Apply
83
+ replacements.forEach(({ regExpStr, replacement }) => {
84
+ (0, applyRegExWithMagicString_js_1.applyRegExpWithMagicString)(magicString, regExpStr, replacement);
80
85
  });
81
- if (!s.hasChanged())
86
+ if (!magicString.hasChanged())
82
87
  return null;
83
88
  return {
84
- code: s.toString(),
85
- map: s.generateMap({ hires: true, source: id })
89
+ code: magicString.toString(),
90
+ map: magicString.generateMap({ hires: true, source: id })
86
91
  };
87
92
  }
88
93
  };
89
94
  }
90
- function applyEnvVar(s, envStatementRegExStr, envVal) {
91
- const envStatementRegEx = new RegExp(envStatementRegExStr, 'g');
92
- let match;
93
- while ((match = envStatementRegEx.exec(s.original))) {
94
- s.overwrite(match.index, match.index + match[0].length, JSON.stringify(envVal));
95
- }
96
- }
@@ -179,7 +179,9 @@ function getGlobRoots(config) {
179
179
  }
180
180
  function getGlobPath(globRootDir, fileType) {
181
181
  (0, utils_js_1.assertPosixPath)(globRootDir);
182
- let globPath = [...globRootDir.split('/'), '**', `*${fileType}.${utils_js_1.scriptFileExtensions}`].filter(Boolean).join('/');
182
+ let globPath = [...globRootDir.split('/'), '**', `*${fileType}.${utils_js_1.scriptFileExtensionPattern}`]
183
+ .filter(Boolean)
184
+ .join('/');
183
185
  if (!globPath.startsWith('/')) {
184
186
  globPath = '/' + globPath;
185
187
  }
@@ -21,6 +21,7 @@ const configDefinitionsBuiltIn = {
21
21
  },
22
22
  onCreatePageContext: {
23
23
  env: { server: true, client: true },
24
+ // Required because `onCreatePageContext()` is called before routing
24
25
  global: true,
25
26
  cumulative: true
26
27
  },
@@ -120,7 +120,7 @@ async function gitLsFiles(userRootDir, ignorePatterns, ignoreMatchers) {
120
120
  }
121
121
  // Same as gitLsFiles() but using tinyglobby
122
122
  async function tinyglobby(userRootDir, ignorePatterns) {
123
- const pattern = `**/+*.${utils_js_1.scriptFileExtensions}`;
123
+ const pattern = `**/+*.${utils_js_1.scriptFileExtensionPattern}`;
124
124
  const options = {
125
125
  ignore: ignorePatterns,
126
126
  cwd: userRootDir,
@@ -31,7 +31,7 @@ async function transpileAndExecuteFile(filePath, userRootDir, isExtensionConfig,
31
31
  }
32
32
  const { promise, resolve } = (0, utils_js_1.genPromise)();
33
33
  esbuildCache.transpileCache[filePathAbsoluteFilesystem] = promise;
34
- (0, utils_js_1.assertUsage)((0, utils_js_1.isPlainJavaScriptFile)(filePathAbsoluteFilesystem), `${filePathToShowToUserResolved} has file extension .${fileExtension} but a config file can only be a JavaScript/TypeScript file`);
34
+ (0, utils_js_1.assertUsage)((0, utils_js_1.isPlainScriptFile)(filePathAbsoluteFilesystem), `${filePathToShowToUserResolved} has file extension .${fileExtension} but a config file can only be a JavaScript/TypeScript file`);
35
35
  const isHeader = isHeaderFile(filePathAbsoluteFilesystem);
36
36
  if (isHeader) {
37
37
  (0, utils_js_1.assertWarning)(false, `${picocolors_1.default.cyan('.h.js')} files are deprecated: simply renaming ${filePathToShowToUserResolved} to ${removeHeaderFileExtension(filePathToShowToUserResolved)} is usually enough, although you may occasionally need to use ${picocolors_1.default.cyan("with { type: 'pointer' }")} as explained at https://vike.dev/config#pointer-imports`, { onlyOnce: true });
@@ -157,7 +157,7 @@ async function transpileWithEsbuild(filePath, userRootDir, transformImports, esb
157
157
  const isVikeExtensionImport = (path.startsWith('vike-') && path.endsWith('/config')) || importPathResolved.endsWith('+config.js');
158
158
  const isPointerImport = transformImports === 'all' ||
159
159
  // .jsx, .vue, .svg, ... => obviously not config code => pointer import
160
- !(0, utils_js_1.isPlainJavaScriptFile)(importPathResolved) ||
160
+ !(0, utils_js_1.isPlainScriptFile)(importPathResolved) ||
161
161
  // Import of a Vike extension config => make it a pointer import because we want to show nice error messages (that can display whether a config has been set by the user or by a Vike extension).
162
162
  // - Should we stop doing this? (And instead let Node.js directly load Vike extensions.)
163
163
  // - In principle, we can use the setting 'name' value of Vike extensions.
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.replaceConstants = replaceConstants;
7
+ const magic_string_1 = __importDefault(require("magic-string"));
8
+ const utils_js_1 = require("../utils.js");
9
+ const normalizeId_js_1 = require("../shared/normalizeId.js");
10
+ const isViteServerBuild_js_1 = require("../shared/isViteServerBuild.js");
11
+ const applyRegExWithMagicString_js_1 = require("../shared/applyRegExWithMagicString.js");
12
+ function replaceConstants() {
13
+ let config;
14
+ return {
15
+ name: 'vike:replaceConstants',
16
+ enforce: 'post',
17
+ apply: 'build',
18
+ configResolved(config_) {
19
+ config = config_;
20
+ },
21
+ transform(code, id, options) {
22
+ id = (0, normalizeId_js_1.normalizeId)(id);
23
+ (0, utils_js_1.assertPosixPath)(id);
24
+ if (id.includes('/node_modules/'))
25
+ return;
26
+ (0, utils_js_1.assertPosixPath)(config.root);
27
+ if (!id.startsWith(config.root))
28
+ return;
29
+ if (!code.includes('import.meta.env.'))
30
+ return;
31
+ const isBuild = config.command === 'build';
32
+ (0, utils_js_1.assert)(isBuild);
33
+ // Used by vike.dev
34
+ // https://github.com/vikejs/vike/blob/08a1ff55c80ddca64ca6d4417fefd45fefeb4ffb/docs/vite.config.ts#L12
35
+ // @ts-expect-error
36
+ if (config._skipVikeReplaceConstants?.(id))
37
+ return;
38
+ const magicString = new magic_string_1.default(code);
39
+ const constantsMap = [];
40
+ constantsMap.push({
41
+ constants: ['pageContext.isClientSide', 'globalContext.isClientSide', 'pageContext.globalContext.isClientSide'],
42
+ replacement: !(0, isViteServerBuild_js_1.isViteServerBuild_safe)(config, options)
43
+ });
44
+ constantsMap.forEach(({ constants, replacement }) => {
45
+ if (!constants.some((c) => code.includes(c)))
46
+ return;
47
+ const regExp = getConstantRegExp(constants);
48
+ (0, applyRegExWithMagicString_js_1.applyRegExpWithMagicString)(magicString, regExp, replacement);
49
+ });
50
+ if (!magicString.hasChanged())
51
+ return null;
52
+ return {
53
+ code: magicString.toString(),
54
+ map: magicString.generateMap({ hires: true, source: id })
55
+ };
56
+ }
57
+ };
58
+ }
59
+ // Copied & adapted from:
60
+ // https://github.com/rollup/plugins/blob/e1a5ef99f1578eb38a8c87563cb9651db228f3bd/packages/replace/src/index.js#L57-L67
61
+ function getConstantRegExp(constants) {
62
+ const keys = Object.values(constants).sort(longest).map(escape);
63
+ // const delimiters = ['\\b', '\\b(?!\\.)']
64
+ const delimiters = ['(?<!\\.)\\b', '\\b(?!\\.)']; // Improved version, to avoid replacing `globalContext.pageContext.isClientSide` with `globalContext.false`
65
+ const preventAssignment = false; // Let's try without it first, let's see if a user complains
66
+ const lookbehind = preventAssignment ? '(?<!\\b(?:const|let|var)\\s*)' : '';
67
+ const lookahead = preventAssignment ? '(?!\\s*=[^=])' : '';
68
+ const pattern = new RegExp(`${lookbehind}${delimiters[0]}(${keys.join('|')})${delimiters[1]}${lookahead}`, 'g');
69
+ return pattern;
70
+ }
71
+ function escape(str) {
72
+ return str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
73
+ }
74
+ function longest(a, b) {
75
+ return b.length - a.length;
76
+ }
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.applyRegExpWithMagicString = applyRegExpWithMagicString;
4
+ function applyRegExpWithMagicString(magicString, regExp, replacement) {
5
+ const envStatementRegEx = typeof regExp === 'string' ? new RegExp(regExp, 'g') : regExp;
6
+ let match;
7
+ while ((match = envStatementRegEx.exec(magicString.original))) {
8
+ magicString.overwrite(match.index, match.index + match[0].length, JSON.stringify(replacement));
9
+ }
10
+ }
@@ -12,7 +12,7 @@ async function findPageFiles(config, fileTypes, isDev) {
12
12
  const cwd = config.root;
13
13
  const { outDirRoot } = (0, getOutDirs_js_1.getOutDirs)(config);
14
14
  const timeBase = new Date().getTime();
15
- let pageFiles = await (0, tinyglobby_1.glob)(fileTypes.map((fileType) => `**/*${fileType}.${utils_js_1.scriptFileExtensions}`), { ignore: ['**/node_modules/**', `${outDirRoot}/**`], cwd, dot: false, expandDirectories: false });
15
+ let pageFiles = await (0, tinyglobby_1.glob)(fileTypes.map((fileType) => `**/*${fileType}.${utils_js_1.scriptFileExtensionPattern}`), { ignore: ['**/node_modules/**', `${outDirRoot}/**`], cwd, dot: false, expandDirectories: false });
16
16
  pageFiles = pageFiles.map((p) => '/' + (0, utils_js_1.toPosixPath)(p));
17
17
  const time = new Date().getTime() - timeBase;
18
18
  if (isDev) {
@@ -76,7 +76,13 @@ async function renderHtmlStream(streamOriginal, injectString, pageContext, onErr
76
76
  return injectAtStreamAfterFirstChunk();
77
77
  };
78
78
  }
79
+ let makeClosableAgain = () => { };
80
+ if ((0, react_streaming_js_1.isStreamFromReactStreamingPackage)(streamOriginal)) {
81
+ // Make sure Vike injects its HTML fragments, such as `<script id="vike_pageContext" type="application/json">`, before the stream is closed
82
+ makeClosableAgain = streamOriginal.doNotClose();
83
+ }
79
84
  const streamWrapper = await (0, stream_js_1.processStream)(streamOriginal, processStreamOptions);
85
+ makeClosableAgain();
80
86
  return streamWrapper;
81
87
  }
82
88
  function isTemplateWrapped(something) {
@@ -2,4 +2,4 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.PROJECT_VERSION = void 0;
4
4
  // Automatically updated by @brillout/release-me
5
- exports.PROJECT_VERSION = '0.4.228-commit-1bb55f1';
5
+ exports.PROJECT_VERSION = '0.4.229-commit-2a06dcc';
@@ -1,10 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.scriptFileExtensionList = exports.scriptFileExtensions = void 0;
3
+ exports.scriptFileExtensionList = exports.scriptFileExtensionPattern = void 0;
4
4
  exports.isScriptFile = isScriptFile;
5
- exports.isPlainJavaScriptFile = isPlainJavaScriptFile;
5
+ exports.isPlainScriptFile = isPlainScriptFile;
6
6
  exports.isTemplateFile = isTemplateFile;
7
- const assert_js_1 = require("./assert.js");
8
7
  // We can't use a RegExp:
9
8
  // - Needs to work with Micromatch: https://github.com/micromatch/micromatch because:
10
9
  // - Vite's `import.meta.glob()` uses Micromatch
@@ -16,26 +15,36 @@ const assert_js_1 = require("./assert.js");
16
15
  // - A post `import.meta.glob()` blocklist filtering doesn't work because Vite would still process the files (e.g. including them in the bundle).
17
16
  // prettier-ignore
18
17
  // biome-ignore format:
19
- const extJavaScript = [
18
+ const extJs = [
20
19
  'js',
21
- 'ts',
22
20
  'cjs',
23
- 'cts',
24
21
  'mjs',
22
+ ];
23
+ // prettier-ignore
24
+ // biome-ignore format:
25
+ const extTs = [
26
+ 'ts',
27
+ 'cts',
25
28
  'mts',
26
29
  ];
30
+ const extJsOrTs = [...extJs, ...extTs];
27
31
  // prettier-ignore
28
32
  // biome-ignore format:
29
33
  const extJsx = [
30
34
  'jsx',
31
- 'tsx',
32
35
  'cjsx',
33
- 'ctsx',
34
36
  'mjsx',
35
- 'mtsx',
36
37
  ];
37
38
  // prettier-ignore
38
39
  // biome-ignore format:
40
+ const extTsx = [
41
+ 'tsx',
42
+ 'ctsx',
43
+ 'mtsx'
44
+ ];
45
+ const extJsxOrTsx = [...extJsx, ...extTsx];
46
+ // prettier-ignore
47
+ // biome-ignore format:
39
48
  const extTemplates = [
40
49
  'vue',
41
50
  'svelte',
@@ -43,21 +52,15 @@ const extTemplates = [
43
52
  'md',
44
53
  'mdx'
45
54
  ];
46
- const scriptFileExtensionList = [...extJavaScript, ...extJsx, ...extTemplates];
55
+ const scriptFileExtensionList = [...extJsOrTs, ...extJsxOrTsx, ...extTemplates];
47
56
  exports.scriptFileExtensionList = scriptFileExtensionList;
48
- const scriptFileExtensions = '(' + scriptFileExtensionList.join('|') + ')';
49
- exports.scriptFileExtensions = scriptFileExtensions;
57
+ const scriptFileExtensionPattern = '(' + scriptFileExtensionList.join('|') + ')';
58
+ exports.scriptFileExtensionPattern = scriptFileExtensionPattern;
50
59
  function isScriptFile(filePath) {
51
- const yes = scriptFileExtensionList.some((ext) => filePath.endsWith('.' + ext));
52
- if (isPlainJavaScriptFile(filePath))
53
- (0, assert_js_1.assert)(yes);
54
- return yes;
60
+ return scriptFileExtensionList.some((ext) => filePath.endsWith('.' + ext));
55
61
  }
56
- function isPlainJavaScriptFile(filePath) {
57
- const yes1 = /\.(c|m)?(j|t)s$/.test(filePath);
58
- const yes2 = extJavaScript.some((ext) => filePath.endsWith('.' + ext));
59
- (0, assert_js_1.assert)(yes1 === yes2);
60
- return yes1;
62
+ function isPlainScriptFile(filePath) {
63
+ return extJsOrTs.some((ext) => filePath.endsWith('.' + ext));
61
64
  }
62
65
  function isTemplateFile(filePath) {
63
66
  return extTemplates.some((ext) => filePath.endsWith('.' + ext));
@@ -4,6 +4,7 @@ exports.isImportPathNpmPackage = isImportPathNpmPackage;
4
4
  exports.isImportPathNpmPackageOrPathAlias = isImportPathNpmPackageOrPathAlias;
5
5
  exports.assertIsImportPathNpmPackage = assertIsImportPathNpmPackage;
6
6
  exports.isPathAliasRecommended = isPathAliasRecommended;
7
+ exports.getNpmPackageName = getNpmPackageName;
7
8
  exports.parseNpmPackage = parseNpmPackage;
8
9
  exports.isDistinguishable = isDistinguishable;
9
10
  const assert_js_1 = require("./assert.js");
@@ -21,6 +21,7 @@ import { setResolveClientEntriesDev } from '../runtime/renderPage/getPageAssets.
21
21
  import { resolveClientEntriesDev } from './shared/resolveClientEntriesDev.js';
22
22
  import { workaroundCssModuleHmr } from './plugins/workaroundCssModuleHmr.js';
23
23
  import { workaroundVite6HmrRegression } from './plugins/workaroundVite6HmrRegression.js';
24
+ import { replaceConstants } from './plugins/replaceConstants.js';
24
25
  // We don't call this in ./onLoad.ts to avoid a cyclic dependency with utils.ts
25
26
  setResolveClientEntriesDev(resolveClientEntriesDev);
26
27
  // Return `PluginInterop` instead of `Plugin` to avoid type mismatch upon different Vite versions
@@ -38,7 +39,8 @@ function plugin(vikeVitePluginOptions = {}) {
38
39
  envVarsPlugin(),
39
40
  fileEnv(),
40
41
  workaroundCssModuleHmr(),
41
- workaroundVite6HmrRegression()
42
+ workaroundVite6HmrRegression(),
43
+ replaceConstants()
42
44
  ];
43
45
  Object.assign(plugins, { __vikeVitePluginOptions: vikeVitePluginOptions });
44
46
  return plugins;
@@ -27,14 +27,14 @@ function pluginModuleBanner() {
27
27
  if (id.startsWith(config.root))
28
28
  id = id.slice(config.root.length + 1);
29
29
  id = id.replaceAll('*/', '*\\/'); // https://github.com/vikejs/vike/issues/2377
30
- const s = new MagicString(code);
30
+ const magicString = new MagicString(code);
31
31
  // Use legal comment so that esbuild doesn't remove it.
32
32
  // - Terser still removes the comment, but I guess users use terser to minify JavaScript so I guess it's a good thing that comment is removed.
33
33
  // - https://esbuild.github.io/api/#legal-comments
34
- s.prepend(`/*! ${id} [vike:pluginModuleBanner] */\n`);
34
+ magicString.prepend(`/*! ${id} [vike:pluginModuleBanner] */\n`);
35
35
  return {
36
- code: s.toString(),
37
- map: s.generateMap({ hires: true, source: id })
36
+ code: magicString.toString(),
37
+ map: magicString.generateMap({ hires: true, source: id })
38
38
  };
39
39
  }
40
40
  }
@@ -1,6 +1,6 @@
1
1
  export { determineOptimizeDeps };
2
2
  import { findPageFiles } from '../../shared/findPageFiles.js';
3
- import { assert, assertIsImportPathNpmPackage, createDebugger, isArray, unique } from '../../utils.js';
3
+ import { assert, assertIsImportPathNpmPackage, createDebugger, getNpmPackageName, isArray, unique } from '../../utils.js';
4
4
  import { getVikeConfig, isOverriden } from '../importUserCode/v1-design/getVikeConfig.js';
5
5
  import { analyzeClientEntries } from '../build/pluginBuildConfig.js';
6
6
  import { virtualFileIdImportUserCodeClientCR, virtualFileIdImportUserCodeClientSR } from '../../../shared/virtual-files/virtualFileImportUserCode.js';
@@ -55,6 +55,11 @@ async function getPageDeps(config, pageConfigs) {
55
55
  return;
56
56
  if (definedAt.definedBy)
57
57
  return;
58
+ if (definedAt.importPathAbsolute) {
59
+ const npmPackageName = getNpmPackageName(definedAt.importPathAbsolute);
60
+ if (npmPackageName && config.optimizeDeps.exclude?.includes(npmPackageName))
61
+ return;
62
+ }
58
63
  if (definedAt.filePathAbsoluteUserRootDir !== null) {
59
64
  // Vite expects entries to be filesystem absolute paths (surprisingly so).
60
65
  addEntry(definedAt.filePathAbsoluteFilesystem);
@@ -1,11 +1,12 @@
1
1
  export { envVarsPlugin };
2
2
  import MagicString from 'magic-string';
3
3
  import { loadEnv } from 'vite';
4
- import { assert, assertPosixPath, assertUsage, assertWarning, escapeRegex, isArray, lowerFirst } from '../utils.js';
4
+ import { assert, assertPosixPath, assertUsage, assertWarning, escapeRegex, isArray, isNotNullish, lowerFirst } from '../utils.js';
5
5
  import { getModuleFilePathAbsolute } from '../shared/getFilePath.js';
6
6
  import { normalizeId } from '../shared/normalizeId.js';
7
7
  import { isViteServerBuild_safe } from '../shared/isViteServerBuild.js';
8
- // TODO/enventually: (after we implemented vike.config.js)
8
+ import { applyRegExpWithMagicString } from '../shared/applyRegExWithMagicString.js';
9
+ // TODO/enventually:
9
10
  // - Make import.meta.env work inside +config.js
10
11
  // - For it to work, we'll probably need the user to define the settings (e.g. `envDir`) for loadEnv() inside vike.config.js instead of vite.config.js
11
12
  // - Or stop using Vite's `mode` implemention and have Vike implement its own `mode` feature? (So that the only dependencies are `$ vike build --mode staging` and `$ MODE=staging vike build`.)
@@ -22,7 +23,6 @@ function envVarsPlugin() {
22
23
  enforce: 'post',
23
24
  configResolved(config_) {
24
25
  config = config_;
25
- config.command;
26
26
  envsAll = loadEnv(config.mode, config.envDir || config.root, '');
27
27
  config.plugins.sort(lowerFirst((plugin) => (plugin.name === 'vite:define' ? 1 : 0)));
28
28
  },
@@ -38,21 +38,22 @@ function envVarsPlugin() {
38
38
  return;
39
39
  const isBuild = config.command === 'build';
40
40
  const isClientSide = !isViteServerBuild_safe(config, options);
41
- const s = new MagicString(code);
42
- Object.entries(envsAll)
41
+ const magicString = new MagicString(code);
42
+ // Find & check
43
+ const replacements = Object.entries(envsAll)
43
44
  .filter(([key]) => {
44
45
  // Already handled by Vite
45
46
  const envPrefix = !config.envPrefix ? [] : isArray(config.envPrefix) ? config.envPrefix : [config.envPrefix];
46
47
  return !envPrefix.some((prefix) => key.startsWith(prefix));
47
48
  })
48
- .forEach(([envName, envVal]) => {
49
+ .map(([envName, envVal]) => {
49
50
  const envStatement = `import.meta.env.${envName}`;
50
- const envStatementRegExStr = escapeRegex(envStatement) + '\\b';
51
+ const envStatementRegExpStr = escapeRegex(envStatement) + '\\b';
51
52
  // Security check
52
53
  {
53
54
  const isPrivate = !envName.startsWith(PUBLIC_ENV_PREFIX) && !PUBLIC_ENV_ALLOWLIST.includes(envName);
54
55
  if (isPrivate && isClientSide) {
55
- if (!new RegExp(envStatementRegExStr).test(code))
56
+ if (!new RegExp(envStatementRegExpStr).test(code))
56
57
  return;
57
58
  const modulePath = getModuleFilePathAbsolute(id, config);
58
59
  const errMsgAddendum = isBuild ? '' : ' (Vike will prevent your app from building for production)';
@@ -70,22 +71,19 @@ function envVarsPlugin() {
70
71
  // Double check
71
72
  assert(!(isPrivate && isClientSide) || !isBuild);
72
73
  }
73
- // Apply
74
- applyEnvVar(s, envStatementRegExStr, envVal);
74
+ return { regExpStr: envStatementRegExpStr, replacement: envVal };
75
+ })
76
+ .filter(isNotNullish);
77
+ // Apply
78
+ replacements.forEach(({ regExpStr, replacement }) => {
79
+ applyRegExpWithMagicString(magicString, regExpStr, replacement);
75
80
  });
76
- if (!s.hasChanged())
81
+ if (!magicString.hasChanged())
77
82
  return null;
78
83
  return {
79
- code: s.toString(),
80
- map: s.generateMap({ hires: true, source: id })
84
+ code: magicString.toString(),
85
+ map: magicString.generateMap({ hires: true, source: id })
81
86
  };
82
87
  }
83
88
  };
84
89
  }
85
- function applyEnvVar(s, envStatementRegExStr, envVal) {
86
- const envStatementRegEx = new RegExp(envStatementRegExStr, 'g');
87
- let match;
88
- while ((match = envStatementRegEx.exec(s.original))) {
89
- s.overwrite(match.index, match.index + match[0].length, JSON.stringify(envVal));
90
- }
91
- }
@@ -1,5 +1,5 @@
1
1
  export { getVirtualFileImportUserCode };
2
- import { assert, assertPosixPath, scriptFileExtensions, debugGlob, isVersionOrAbove, assertWarning } from '../../utils.js';
2
+ import { assert, assertPosixPath, scriptFileExtensionPattern, debugGlob, isVersionOrAbove, assertWarning } from '../../utils.js';
3
3
  import { isVirtualFileIdImportUserCode } from '../../../shared/virtual-files/virtualFileImportUserCode.js';
4
4
  import { version as viteVersion } from 'vite';
5
5
  import { fileTypes } from '../../../../shared/getPageFiles/fileTypes.js';
@@ -174,7 +174,9 @@ function getGlobRoots(config) {
174
174
  }
175
175
  function getGlobPath(globRootDir, fileType) {
176
176
  assertPosixPath(globRootDir);
177
- let globPath = [...globRootDir.split('/'), '**', `*${fileType}.${scriptFileExtensions}`].filter(Boolean).join('/');
177
+ let globPath = [...globRootDir.split('/'), '**', `*${fileType}.${scriptFileExtensionPattern}`]
178
+ .filter(Boolean)
179
+ .join('/');
178
180
  if (!globPath.startsWith('/')) {
179
181
  globPath = '/' + globPath;
180
182
  }
@@ -19,6 +19,7 @@ const configDefinitionsBuiltIn = {
19
19
  },
20
20
  onCreatePageContext: {
21
21
  env: { server: true, client: true },
22
+ // Required because `onCreatePageContext()` is called before routing
22
23
  global: true,
23
24
  cumulative: true
24
25
  },
@@ -1,7 +1,7 @@
1
1
  export { crawlPlusFiles };
2
2
  export { isPlusFile };
3
3
  export { getPlusFileValueConfigName };
4
- import { assertPosixPath, assert, scriptFileExtensions, assertIsSingleModuleInstance, assertIsNotProductionRuntime, isVersionOrAbove, isScriptFile, scriptFileExtensionList, createDebugger, deepEqual, assertUsage, assertFilePathAbsoluteFilesystem, assertWarning, hasProp, isNotNullish } from '../../../../utils.js';
4
+ import { assertPosixPath, assert, scriptFileExtensionPattern, assertIsSingleModuleInstance, assertIsNotProductionRuntime, isVersionOrAbove, isScriptFile, scriptFileExtensionList, createDebugger, deepEqual, assertUsage, assertFilePathAbsoluteFilesystem, assertWarning, hasProp, isNotNullish } from '../../../../utils.js';
5
5
  import path from 'path';
6
6
  import { glob } from 'tinyglobby';
7
7
  import { exec } from 'child_process';
@@ -115,7 +115,7 @@ async function gitLsFiles(userRootDir, ignorePatterns, ignoreMatchers) {
115
115
  }
116
116
  // Same as gitLsFiles() but using tinyglobby
117
117
  async function tinyglobby(userRootDir, ignorePatterns) {
118
- const pattern = `**/+*.${scriptFileExtensions}`;
118
+ const pattern = `**/+*.${scriptFileExtensionPattern}`;
119
119
  const options = {
120
120
  ignore: ignorePatterns,
121
121
  cwd: userRootDir,
@@ -7,7 +7,7 @@ import fs from 'fs';
7
7
  import path from 'path';
8
8
  import pc from '@brillout/picocolors';
9
9
  import { import_ } from '@brillout/import';
10
- import { assertPosixPath, getRandomId, assertIsNotProductionRuntime, assert, assertWarning, isObject, toPosixPath, assertUsage, isPlainJavaScriptFile, createDebugger, assertFilePathAbsoluteFilesystem, assertIsImportPathNpmPackage, genPromise, isVitest, isImportPathNpmPackageOrPathAlias, isImportPathRelative, requireResolveOptionalDir } from '../../../../utils.js';
10
+ import { assertPosixPath, getRandomId, assertIsNotProductionRuntime, assert, assertWarning, isObject, toPosixPath, assertUsage, isPlainScriptFile, createDebugger, assertFilePathAbsoluteFilesystem, assertIsImportPathNpmPackage, genPromise, isVitest, isImportPathNpmPackageOrPathAlias, isImportPathRelative, requireResolveOptionalDir } from '../../../../utils.js';
11
11
  import { transformPointerImports } from './pointerImports.js';
12
12
  import sourceMapSupport from 'source-map-support';
13
13
  import { getFilePathAbsoluteUserRootDir } from '../../../../shared/getFilePath.js';
@@ -26,7 +26,7 @@ async function transpileAndExecuteFile(filePath, userRootDir, isExtensionConfig,
26
26
  }
27
27
  const { promise, resolve } = genPromise();
28
28
  esbuildCache.transpileCache[filePathAbsoluteFilesystem] = promise;
29
- assertUsage(isPlainJavaScriptFile(filePathAbsoluteFilesystem), `${filePathToShowToUserResolved} has file extension .${fileExtension} but a config file can only be a JavaScript/TypeScript file`);
29
+ assertUsage(isPlainScriptFile(filePathAbsoluteFilesystem), `${filePathToShowToUserResolved} has file extension .${fileExtension} but a config file can only be a JavaScript/TypeScript file`);
30
30
  const isHeader = isHeaderFile(filePathAbsoluteFilesystem);
31
31
  if (isHeader) {
32
32
  assertWarning(false, `${pc.cyan('.h.js')} files are deprecated: simply renaming ${filePathToShowToUserResolved} to ${removeHeaderFileExtension(filePathToShowToUserResolved)} is usually enough, although you may occasionally need to use ${pc.cyan("with { type: 'pointer' }")} as explained at https://vike.dev/config#pointer-imports`, { onlyOnce: true });
@@ -152,7 +152,7 @@ async function transpileWithEsbuild(filePath, userRootDir, transformImports, esb
152
152
  const isVikeExtensionImport = (path.startsWith('vike-') && path.endsWith('/config')) || importPathResolved.endsWith('+config.js');
153
153
  const isPointerImport = transformImports === 'all' ||
154
154
  // .jsx, .vue, .svg, ... => obviously not config code => pointer import
155
- !isPlainJavaScriptFile(importPathResolved) ||
155
+ !isPlainScriptFile(importPathResolved) ||
156
156
  // Import of a Vike extension config => make it a pointer import because we want to show nice error messages (that can display whether a config has been set by the user or by a Vike extension).
157
157
  // - Should we stop doing this? (And instead let Node.js directly load Vike extensions.)
158
158
  // - In principle, we can use the setting 'name' value of Vike extensions.
@@ -0,0 +1,3 @@
1
+ export { replaceConstants };
2
+ import type { Plugin } from 'vite';
3
+ declare function replaceConstants(): Plugin;
@@ -0,0 +1,71 @@
1
+ export { replaceConstants };
2
+ import MagicString from 'magic-string';
3
+ import { assert, assertPosixPath } from '../utils.js';
4
+ import { normalizeId } from '../shared/normalizeId.js';
5
+ import { isViteServerBuild_safe } from '../shared/isViteServerBuild.js';
6
+ import { applyRegExpWithMagicString } from '../shared/applyRegExWithMagicString.js';
7
+ function replaceConstants() {
8
+ let config;
9
+ return {
10
+ name: 'vike:replaceConstants',
11
+ enforce: 'post',
12
+ apply: 'build',
13
+ configResolved(config_) {
14
+ config = config_;
15
+ },
16
+ transform(code, id, options) {
17
+ id = normalizeId(id);
18
+ assertPosixPath(id);
19
+ if (id.includes('/node_modules/'))
20
+ return;
21
+ assertPosixPath(config.root);
22
+ if (!id.startsWith(config.root))
23
+ return;
24
+ if (!code.includes('import.meta.env.'))
25
+ return;
26
+ const isBuild = config.command === 'build';
27
+ assert(isBuild);
28
+ // Used by vike.dev
29
+ // https://github.com/vikejs/vike/blob/08a1ff55c80ddca64ca6d4417fefd45fefeb4ffb/docs/vite.config.ts#L12
30
+ // @ts-expect-error
31
+ if (config._skipVikeReplaceConstants?.(id))
32
+ return;
33
+ const magicString = new MagicString(code);
34
+ const constantsMap = [];
35
+ constantsMap.push({
36
+ constants: ['pageContext.isClientSide', 'globalContext.isClientSide', 'pageContext.globalContext.isClientSide'],
37
+ replacement: !isViteServerBuild_safe(config, options)
38
+ });
39
+ constantsMap.forEach(({ constants, replacement }) => {
40
+ if (!constants.some((c) => code.includes(c)))
41
+ return;
42
+ const regExp = getConstantRegExp(constants);
43
+ applyRegExpWithMagicString(magicString, regExp, replacement);
44
+ });
45
+ if (!magicString.hasChanged())
46
+ return null;
47
+ return {
48
+ code: magicString.toString(),
49
+ map: magicString.generateMap({ hires: true, source: id })
50
+ };
51
+ }
52
+ };
53
+ }
54
+ // Copied & adapted from:
55
+ // https://github.com/rollup/plugins/blob/e1a5ef99f1578eb38a8c87563cb9651db228f3bd/packages/replace/src/index.js#L57-L67
56
+ function getConstantRegExp(constants) {
57
+ const keys = Object.values(constants).sort(longest).map(escape);
58
+ // const delimiters = ['\\b', '\\b(?!\\.)']
59
+ const delimiters = ['(?<!\\.)\\b', '\\b(?!\\.)']; // Improved version, to avoid replacing `globalContext.pageContext.isClientSide` with `globalContext.false`
60
+ const preventAssignment = false; // Let's try without it first, let's see if a user complains
61
+ const lookbehind = preventAssignment ? '(?<!\\b(?:const|let|var)\\s*)' : '';
62
+ const lookahead = preventAssignment ? '(?!\\s*=[^=])' : '';
63
+ const pattern = new RegExp(`${lookbehind}${delimiters[0]}(${keys.join('|')})${delimiters[1]}${lookahead}`, 'g');
64
+ return pattern;
65
+ }
66
+ function escape(str) {
67
+ return str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
68
+ }
69
+ function longest(a, b) {
70
+ return b.length - a.length;
71
+ }
@@ -0,0 +1,3 @@
1
+ export { applyRegExpWithMagicString };
2
+ import type MagicString from 'magic-string';
3
+ declare function applyRegExpWithMagicString(magicString: MagicString, regExp: string | RegExp, replacement: unknown): void;
@@ -0,0 +1,8 @@
1
+ export { applyRegExpWithMagicString };
2
+ function applyRegExpWithMagicString(magicString, regExp, replacement) {
3
+ const envStatementRegEx = typeof regExp === 'string' ? new RegExp(regExp, 'g') : regExp;
4
+ let match;
5
+ while ((match = envStatementRegEx.exec(magicString.original))) {
6
+ magicString.overwrite(match.index, match.index + match[0].length, JSON.stringify(replacement));
7
+ }
8
+ }
@@ -1,13 +1,13 @@
1
1
  export { findPageFiles };
2
2
  import { glob } from 'tinyglobby';
3
- import { assertWarning, toPosixPath, scriptFileExtensions } from '../utils.js';
3
+ import { assertWarning, toPosixPath, scriptFileExtensionPattern } from '../utils.js';
4
4
  import pc from '@brillout/picocolors';
5
5
  import { getOutDirs } from './getOutDirs.js';
6
6
  async function findPageFiles(config, fileTypes, isDev) {
7
7
  const cwd = config.root;
8
8
  const { outDirRoot } = getOutDirs(config);
9
9
  const timeBase = new Date().getTime();
10
- let pageFiles = await glob(fileTypes.map((fileType) => `**/*${fileType}.${scriptFileExtensions}`), { ignore: ['**/node_modules/**', `${outDirRoot}/**`], cwd, dot: false, expandDirectories: false });
10
+ let pageFiles = await glob(fileTypes.map((fileType) => `**/*${fileType}.${scriptFileExtensionPattern}`), { ignore: ['**/node_modules/**', `${outDirRoot}/**`], cwd, dot: false, expandDirectories: false });
11
11
  pageFiles = pageFiles.map((p) => '/' + toPosixPath(p));
12
12
  const time = new Date().getTime() - timeBase;
13
13
  if (isDev) {
@@ -71,7 +71,13 @@ async function renderHtmlStream(streamOriginal, injectString, pageContext, onErr
71
71
  return injectAtStreamAfterFirstChunk();
72
72
  };
73
73
  }
74
+ let makeClosableAgain = () => { };
75
+ if (isStreamFromReactStreamingPackage(streamOriginal)) {
76
+ // Make sure Vike injects its HTML fragments, such as `<script id="vike_pageContext" type="application/json">`, before the stream is closed
77
+ makeClosableAgain = streamOriginal.doNotClose();
78
+ }
74
79
  const streamWrapper = await processStream(streamOriginal, processStreamOptions);
80
+ makeClosableAgain();
75
81
  return streamWrapper;
76
82
  }
77
83
  function isTemplateWrapped(something) {
@@ -1 +1 @@
1
- export declare const PROJECT_VERSION: "0.4.228-commit-1bb55f1";
1
+ export declare const PROJECT_VERSION: "0.4.229-commit-2a06dcc";
@@ -1,2 +1,2 @@
1
1
  // Automatically updated by @brillout/release-me
2
- export const PROJECT_VERSION = '0.4.228-commit-1bb55f1';
2
+ export const PROJECT_VERSION = '0.4.229-commit-2a06dcc';
@@ -1,10 +1,10 @@
1
1
  export { isScriptFile };
2
- export { isPlainJavaScriptFile };
2
+ export { isPlainScriptFile };
3
3
  export { isTemplateFile };
4
- export { scriptFileExtensions };
4
+ export { scriptFileExtensionPattern };
5
5
  export { scriptFileExtensionList };
6
- declare const scriptFileExtensionList: readonly [...string[], "jsx", "tsx", "cjsx", "ctsx", "mjsx", "mtsx", "vue", "svelte", "marko", "md", "mdx"];
7
- declare const scriptFileExtensions: string;
6
+ declare const scriptFileExtensionList: readonly ["js", "cjs", "mjs", "ts", "cts", "mts", "jsx", "cjsx", "mjsx", "tsx", "ctsx", "mtsx", "vue", "svelte", "marko", "md", "mdx"];
7
+ declare const scriptFileExtensionPattern: string;
8
8
  declare function isScriptFile(filePath: string): boolean;
9
- declare function isPlainJavaScriptFile(filePath: string): boolean;
9
+ declare function isPlainScriptFile(filePath: string): boolean;
10
10
  declare function isTemplateFile(filePath: string): boolean;
@@ -1,9 +1,8 @@
1
1
  export { isScriptFile };
2
- export { isPlainJavaScriptFile };
2
+ export { isPlainScriptFile };
3
3
  export { isTemplateFile };
4
- export { scriptFileExtensions };
4
+ export { scriptFileExtensionPattern };
5
5
  export { scriptFileExtensionList };
6
- import { assert } from './assert.js';
7
6
  // We can't use a RegExp:
8
7
  // - Needs to work with Micromatch: https://github.com/micromatch/micromatch because:
9
8
  // - Vite's `import.meta.glob()` uses Micromatch
@@ -15,26 +14,36 @@ import { assert } from './assert.js';
15
14
  // - A post `import.meta.glob()` blocklist filtering doesn't work because Vite would still process the files (e.g. including them in the bundle).
16
15
  // prettier-ignore
17
16
  // biome-ignore format:
18
- const extJavaScript = [
17
+ const extJs = [
19
18
  'js',
20
- 'ts',
21
19
  'cjs',
22
- 'cts',
23
20
  'mjs',
21
+ ];
22
+ // prettier-ignore
23
+ // biome-ignore format:
24
+ const extTs = [
25
+ 'ts',
26
+ 'cts',
24
27
  'mts',
25
28
  ];
29
+ const extJsOrTs = [...extJs, ...extTs];
26
30
  // prettier-ignore
27
31
  // biome-ignore format:
28
32
  const extJsx = [
29
33
  'jsx',
30
- 'tsx',
31
34
  'cjsx',
32
- 'ctsx',
33
35
  'mjsx',
34
- 'mtsx',
35
36
  ];
36
37
  // prettier-ignore
37
38
  // biome-ignore format:
39
+ const extTsx = [
40
+ 'tsx',
41
+ 'ctsx',
42
+ 'mtsx'
43
+ ];
44
+ const extJsxOrTsx = [...extJsx, ...extTsx];
45
+ // prettier-ignore
46
+ // biome-ignore format:
38
47
  const extTemplates = [
39
48
  'vue',
40
49
  'svelte',
@@ -42,19 +51,13 @@ const extTemplates = [
42
51
  'md',
43
52
  'mdx'
44
53
  ];
45
- const scriptFileExtensionList = [...extJavaScript, ...extJsx, ...extTemplates];
46
- const scriptFileExtensions = '(' + scriptFileExtensionList.join('|') + ')';
54
+ const scriptFileExtensionList = [...extJsOrTs, ...extJsxOrTsx, ...extTemplates];
55
+ const scriptFileExtensionPattern = '(' + scriptFileExtensionList.join('|') + ')';
47
56
  function isScriptFile(filePath) {
48
- const yes = scriptFileExtensionList.some((ext) => filePath.endsWith('.' + ext));
49
- if (isPlainJavaScriptFile(filePath))
50
- assert(yes);
51
- return yes;
57
+ return scriptFileExtensionList.some((ext) => filePath.endsWith('.' + ext));
52
58
  }
53
- function isPlainJavaScriptFile(filePath) {
54
- const yes1 = /\.(c|m)?(j|t)s$/.test(filePath);
55
- const yes2 = extJavaScript.some((ext) => filePath.endsWith('.' + ext));
56
- assert(yes1 === yes2);
57
- return yes1;
59
+ function isPlainScriptFile(filePath) {
60
+ return extJsOrTs.some((ext) => filePath.endsWith('.' + ext));
58
61
  }
59
62
  function isTemplateFile(filePath) {
60
63
  return extTemplates.some((ext) => filePath.endsWith('.' + ext));
@@ -2,6 +2,7 @@ export { isImportPathNpmPackage };
2
2
  export { isImportPathNpmPackageOrPathAlias };
3
3
  export { assertIsImportPathNpmPackage };
4
4
  export { isPathAliasRecommended };
5
+ export { getNpmPackageName };
5
6
  export { parseNpmPackage };
6
7
  export { isDistinguishable };
7
8
  declare function isImportPathNpmPackage(str: string, { cannotBePathAlias }: {
@@ -9,6 +10,7 @@ declare function isImportPathNpmPackage(str: string, { cannotBePathAlias }: {
9
10
  }): boolean;
10
11
  declare function isImportPathNpmPackageOrPathAlias(str: string): boolean;
11
12
  declare function assertIsImportPathNpmPackage(str: string): void;
13
+ declare function getNpmPackageName(str: string): null | string;
12
14
  declare function isPathAliasRecommended(alias: string): boolean;
13
15
  declare function isDistinguishable(alias: string): boolean;
14
16
  declare function parseNpmPackage(str: string | undefined): null | {
@@ -2,9 +2,9 @@ export { isImportPathNpmPackage };
2
2
  export { isImportPathNpmPackageOrPathAlias };
3
3
  export { assertIsImportPathNpmPackage };
4
4
  export { isPathAliasRecommended };
5
+ export { getNpmPackageName };
5
6
  /* Currently not used
6
7
  export { isNpmPackageName }
7
- export { getNpmPackageName }
8
8
  export { getNpmPackageImportPath }
9
9
  */
10
10
  // For ./isNpmPackage.spec.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vike",
3
- "version": "0.4.228-commit-1bb55f1",
3
+ "version": "0.4.229-commit-2a06dcc",
4
4
  "repository": "https://github.com/vikejs/vike",
5
5
  "exports": {
6
6
  "./server": {