vike 0.4.159 → 0.4.160-commit-a1101c1

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 (72) hide show
  1. package/dist/cjs/node/plugin/index.js +20 -1
  2. package/dist/cjs/node/plugin/plugins/devConfig/index.js +1 -1
  3. package/dist/cjs/node/plugin/plugins/importBuild/index.js +1 -1
  4. package/dist/cjs/node/plugin/plugins/importUserCode/v1-design/getConfigFileExport.js +18 -0
  5. package/dist/cjs/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/loadFileConfigEnv.js +129 -0
  6. package/dist/cjs/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/resolveImportPath.js +139 -0
  7. package/dist/cjs/node/plugin/plugins/importUserCode/v1-design/{replaceImportStatements.js → getVikeConfig/transformImports.js} +44 -13
  8. package/dist/cjs/node/plugin/plugins/importUserCode/v1-design/{transpileAndExecuteFile.js → getVikeConfig/transpileAndExecuteFile.js} +110 -77
  9. package/dist/cjs/node/plugin/plugins/importUserCode/v1-design/getVikeConfig.js +58 -279
  10. package/dist/cjs/node/plugin/plugins/previewConfig.js +1 -1
  11. package/dist/cjs/node/plugin/shared/getHttpRequestAsyncStore.js +1 -1
  12. package/dist/cjs/node/plugin/shared/loggerNotProd/log.js +3 -3
  13. package/dist/cjs/node/plugin/shared/loggerNotProd.js +1 -1
  14. package/dist/cjs/node/runtime/globalContext.js +4 -3
  15. package/dist/cjs/node/runtime/html/injectAssets/getHtmlTags.js +1 -1
  16. package/dist/cjs/node/runtime/html/renderHtml.js +1 -1
  17. package/dist/cjs/node/runtime/html/stream.js +2 -2
  18. package/dist/cjs/node/runtime/renderPage/executeOnRenderHtmlHook.js +2 -2
  19. package/dist/cjs/node/runtime/renderPage/getHttpResponseBody.js +1 -1
  20. package/dist/cjs/node/runtime/renderPage/loadUserFilesServerSide.js +1 -1
  21. package/dist/cjs/shared/page-configs/assertPlusFileExport.js +44 -0
  22. package/dist/cjs/shared/page-configs/serialize/parseConfigValuesImported.js +2 -2
  23. package/dist/cjs/shared/route/abort.js +1 -1
  24. package/dist/cjs/utils/assert.js +5 -6
  25. package/dist/cjs/utils/assertIsNotProductionRuntime.js +35 -17
  26. package/dist/cjs/utils/nodeEnv.js +11 -1
  27. package/dist/cjs/utils/projectInfo.js +2 -4
  28. package/dist/esm/node/plugin/index.js +21 -2
  29. package/dist/esm/node/plugin/plugins/devConfig/index.js +2 -2
  30. package/dist/esm/node/plugin/plugins/importBuild/index.js +2 -2
  31. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getConfigFileExport.d.ts +2 -0
  32. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getConfigFileExport.js +12 -0
  33. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/configDefinitionsBuiltIn.d.ts +6 -1
  34. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/loadFileConfigEnv.d.ts +21 -0
  35. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/loadFileConfigEnv.js +123 -0
  36. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/resolveImportPath.d.ts +12 -0
  37. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/resolveImportPath.js +133 -0
  38. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/{replaceImportStatements.d.ts → getVikeConfig/transformImports.d.ts} +5 -5
  39. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/{replaceImportStatements.js → getVikeConfig/transformImports.js} +43 -12
  40. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/{transpileAndExecuteFile.d.ts → getVikeConfig/transpileAndExecuteFile.d.ts} +3 -3
  41. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/{transpileAndExecuteFile.js → getVikeConfig/transpileAndExecuteFile.js} +110 -77
  42. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVikeConfig.d.ts +14 -1
  43. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVikeConfig.js +55 -276
  44. package/dist/esm/node/plugin/plugins/previewConfig.js +2 -2
  45. package/dist/esm/node/plugin/shared/getHttpRequestAsyncStore.js +1 -1
  46. package/dist/esm/node/plugin/shared/loggerNotProd/log.js +3 -3
  47. package/dist/esm/node/plugin/shared/loggerNotProd.js +1 -1
  48. package/dist/esm/node/runtime/globalContext.js +5 -4
  49. package/dist/esm/node/runtime/html/injectAssets/getHtmlTags.js +1 -1
  50. package/dist/esm/node/runtime/html/renderHtml.js +1 -1
  51. package/dist/esm/node/runtime/html/stream.js +2 -2
  52. package/dist/esm/node/runtime/renderPage/executeOnRenderHtmlHook.js +2 -2
  53. package/dist/esm/node/runtime/renderPage/getHttpResponseBody.js +1 -1
  54. package/dist/esm/node/runtime/renderPage/loadUserFilesServerSide.js +1 -1
  55. package/dist/esm/shared/page-configs/Config.d.ts +1 -1
  56. package/dist/esm/shared/page-configs/PageConfig.d.ts +4 -0
  57. package/dist/esm/shared/page-configs/assertPlusFileExport.d.ts +2 -0
  58. package/dist/esm/shared/page-configs/assertPlusFileExport.js +38 -0
  59. package/dist/esm/shared/page-configs/serialize/parseConfigValuesImported.js +2 -2
  60. package/dist/esm/shared/route/abort.js +2 -2
  61. package/dist/esm/utils/assert.js +5 -6
  62. package/dist/esm/utils/assertIsNotProductionRuntime.d.ts +8 -6
  63. package/dist/esm/utils/assertIsNotProductionRuntime.js +35 -17
  64. package/dist/esm/utils/debug.d.ts +1 -1
  65. package/dist/esm/utils/nodeEnv.d.ts +2 -0
  66. package/dist/esm/utils/nodeEnv.js +10 -0
  67. package/dist/esm/utils/projectInfo.d.ts +2 -8
  68. package/dist/esm/utils/projectInfo.js +2 -4
  69. package/package.json +1 -1
  70. package/dist/cjs/shared/page-configs/assertExports.js +0 -67
  71. package/dist/esm/shared/page-configs/assertExports.d.ts +0 -6
  72. package/dist/esm/shared/page-configs/assertExports.js +0 -61
@@ -44,7 +44,7 @@ async function loadUserFilesServerSide(pageContext) {
44
44
  // TODO/v1-release: remove
45
45
  Object.assign(pageContextAddendum, {
46
46
  _getPageAssets: async () => {
47
- (0, utils_js_1.assertWarning)(false, 'pageContext._getPageAssets() deprecated, see https://vike.dev/preload', {
47
+ (0, utils_js_1.assertWarning)(false, 'pageContext._getPageAssets() deprecated, see https://vike.dev/preloading', {
48
48
  onlyOnce: true,
49
49
  showStackTrace: true
50
50
  });
@@ -0,0 +1,44 @@
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.assertPlusFileExport = void 0;
7
+ const utils_js_1 = require("../utils.js");
8
+ const picocolors_1 = __importDefault(require("@brillout/picocolors"));
9
+ const EXPORTS_IGNORE = [
10
+ // vite-plugin-solid adds `export { $$registrations }`
11
+ '$$registrations',
12
+ // @vitejs/plugin-vue adds `export { _rerender_only }`
13
+ '_rerender_only'
14
+ ];
15
+ // Tolerate `export { frontmatter }` in .mdx files
16
+ const TOLERATE_SIDE_EXPORTS = ['.md', '.mdx'];
17
+ function assertPlusFileExport(fileExports, filePathToShowToUser, configName) {
18
+ const exportsAll = Object.keys(fileExports).filter((exportName) => !EXPORTS_IGNORE.includes(exportName));
19
+ const exportsInvalid = exportsAll.filter((e) => e !== 'default' && e !== configName);
20
+ if (exportsInvalid.length === 0) {
21
+ if (exportsAll.length === 1) {
22
+ return;
23
+ }
24
+ const exportDefault = picocolors_1.default.cyan('export default');
25
+ const exportNamed = picocolors_1.default.cyan(`export { ${configName} }`);
26
+ if (exportsAll.length === 0) {
27
+ (0, utils_js_1.assertUsage)(false, `${filePathToShowToUser} doesn't export any value, but it should have a ${exportNamed} or ${exportDefault}`);
28
+ }
29
+ else {
30
+ (0, utils_js_1.assert)(exportsAll.length === 2); // because `exportsInvalid.length === 0`
31
+ (0, utils_js_1.assertWarning)(false, `${filePathToShowToUser} remove ${exportNamed} or ${exportDefault}`, {
32
+ onlyOnce: true
33
+ });
34
+ }
35
+ }
36
+ else {
37
+ if (TOLERATE_SIDE_EXPORTS.some((ext) => filePathToShowToUser.endsWith(ext)))
38
+ return;
39
+ exportsInvalid.forEach((exportInvalid) => {
40
+ (0, utils_js_1.assertWarning)(false, `${filePathToShowToUser} should have only one export: move ${picocolors_1.default.cyan(`export { ${exportInvalid} }`)} to its own +${exportsInvalid}.js file`, { onlyOnce: true });
41
+ });
42
+ }
43
+ }
44
+ exports.assertPlusFileExport = assertPlusFileExport;
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.parseConfigValuesImported = void 0;
4
4
  const utils_js_1 = require("../../utils.js");
5
- const assertExports_js_1 = require("../assertExports.js");
5
+ const assertPlusFileExport_js_1 = require("../assertPlusFileExport.js");
6
6
  function parseConfigValuesImported(configValuesImported) {
7
7
  const configValues = {};
8
8
  const addConfigValue = (configName, value, importPath, exportName) => {
@@ -23,7 +23,7 @@ function parseConfigValuesImported(configValuesImported) {
23
23
  if (configValueLoaded.isValueFile) {
24
24
  const { exportValues, importPath, configName } = configValueLoaded;
25
25
  if (configName !== 'client') {
26
- (0, assertExports_js_1.assertExportsOfValueFile)(exportValues, importPath, configName);
26
+ (0, assertPlusFileExport_js_1.assertPlusFileExport)(exportValues, importPath, configName);
27
27
  }
28
28
  Object.entries(exportValues).forEach(([exportName, exportValue]) => {
29
29
  const isSideExport = exportName !== 'default'; // .md files may have "side-exports" such as `export { frontmatter }`
@@ -136,7 +136,7 @@ function logAbortErrorHandled(err, isProduction, pageContext) {
136
136
  exports.logAbortErrorHandled = logAbortErrorHandled;
137
137
  function assertStatusCode(statusCode, expected, caller) {
138
138
  const expectedEnglish = (0, utils_js_1.joinEnglish)(expected.map((s) => s.toString()), 'or');
139
- (0, utils_js_1.assertWarning)(expected.includes(statusCode), `Unepexected status code ${statusCode} passed to ${caller}(), we recommend ${expectedEnglish} instead. (Or reach out at ${utils_js_1.projectInfo.githubRepository}/issues/1008 if you believe ${statusCode} should be added.)`, { onlyOnce: true });
139
+ (0, utils_js_1.assertWarning)(expected.includes(statusCode), `Unepexected status code ${statusCode} passed to ${caller}(), we recommend ${expectedEnglish} instead. (Or reach out at https://github.com/vikejs/vike/issues/1008 if you believe ${statusCode} should be added.)`, { onlyOnce: true });
140
140
  }
141
141
  function getPageContextFromAllRewrites(pageContextsFromRewrite) {
142
142
  assertNoInfiniteLoop(pageContextsFromRewrite);
@@ -22,8 +22,8 @@ const globalObject = (0, getGlobalObject_js_1.getGlobalObject)('utils/assert.ts'
22
22
  },
23
23
  showStackTraceList: new WeakSet()
24
24
  });
25
- const projectTag = `[${projectInfo_js_1.projectInfo.npmPackageName}]`;
26
- const projectTagWithVersion = `[${projectInfo_js_1.projectInfo.npmPackageName}@${projectInfo_js_1.projectInfo.projectVersion}]`;
25
+ const projectTag = `[vike]`;
26
+ const projectTagWithVersion = `[vike@${projectInfo_js_1.projectInfo.projectVersion}]`;
27
27
  const numberOfStackTraceLinesToRemove = 2;
28
28
  function assert(condition, debugInfo) {
29
29
  if (condition)
@@ -33,12 +33,11 @@ function assert(condition, debugInfo) {
33
33
  return null;
34
34
  }
35
35
  const debugInfoSerialized = typeof debugInfo === 'string' ? debugInfo : JSON.stringify(debugInfo);
36
- return picocolors_1.default.dim(`Debug info (for ${projectInfo_js_1.projectInfo.projectName} maintainers; you can ignore this): ${debugInfoSerialized}`);
36
+ return picocolors_1.default.dim(`Debug info (for Vike maintainers; you can ignore this): ${debugInfoSerialized}`);
37
37
  })();
38
- const link = `${projectInfo_js_1.projectInfo.githubRepository}/issues/new`;
39
38
  let errMsg = [
40
- `You stumbled upon a bug in ${projectInfo_js_1.projectInfo.projectName}'s source code.`,
41
- `Go to ${picocolors_1.default.blue(link)} and copy-paste this error. A maintainer will fix the bug (usually under 24 hours).`,
39
+ `You stumbled upon a Vike bug.`,
40
+ `Go to ${picocolors_1.default.blue('https://github.com/vikejs/vike/issues/new')} and copy-paste this error. A maintainer will fix the bug (usually under 24 hours).`,
42
41
  debugStr
43
42
  ]
44
43
  .filter(Boolean)
@@ -1,44 +1,62 @@
1
1
  "use strict";
2
2
  // Mechanism to ensure code isn't loaded by production runtime
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.assertEnv = exports.markEnvAsVite = exports.markEnvAsPreview = exports.markEnvAsDev = exports.assertIsNotProductionRuntime = void 0;
4
+ exports.vikeVitePluginLoadedInProductionError = exports.assertEnv = exports.markEnvAsVikePluginLoaded = exports.markEnvAsVitePreview = exports.markEnvAsViteDev = exports.assertIsNotProductionRuntime = void 0;
5
5
  const assert_js_1 = require("./assert.js");
6
6
  const assertIsNotBrowser_js_1 = require("./assertIsNotBrowser.js");
7
+ const debug_js_1 = require("./debug.js");
7
8
  const getGlobalObject_js_1 = require("./getGlobalObject.js");
8
9
  const isVitest_js_1 = require("./isVitest.js");
9
10
  (0, assertIsNotBrowser_js_1.assertIsNotBrowser)();
11
+ const debug = (0, debug_js_1.createDebugger)('vike:setup');
12
+ const vikeVitePluginLoadedInProductionError = `Loading Vike's Vite plugin (the vike/plugin module) is prohibited in production.`;
13
+ exports.vikeVitePluginLoadedInProductionError = vikeVitePluginLoadedInProductionError;
10
14
  const env = (0, getGlobalObject_js_1.getGlobalObject)('utils/assertIsNotProductionRuntime.ts', {});
11
- // Called by *.ts that want to ensure that they aren't loaded by the server runtime in production
15
+ // Called by Vike modules that want to ensure that they aren't loaded by the server runtime in production
12
16
  function assertIsNotProductionRuntime() {
13
- env.shouldBeVite = true;
17
+ if (debug.isEnabled)
18
+ debug('assertIsNotProductionRuntime()', new Error().stack);
19
+ env.shouldNotBeProduction = true;
14
20
  }
15
21
  exports.assertIsNotProductionRuntime = assertIsNotProductionRuntime;
16
22
  // Called by Vite hook configureServer()
17
- function markEnvAsDev() {
18
- env.isDev = true;
23
+ function markEnvAsViteDev() {
24
+ if (debug.isEnabled)
25
+ debug('markEnvAsViteDev()', new Error().stack);
26
+ env.isViteDev = true;
19
27
  }
20
- exports.markEnvAsDev = markEnvAsDev;
28
+ exports.markEnvAsViteDev = markEnvAsViteDev;
21
29
  // Called by Vite hook configurePreviewServer()
22
- function markEnvAsPreview() {
23
- env.isPreview = true;
30
+ function markEnvAsVitePreview() {
31
+ if (debug.isEnabled)
32
+ debug('markEnvAsVitePreview()', new Error().stack);
33
+ env.isVitePreview = true;
24
34
  }
25
- exports.markEnvAsPreview = markEnvAsPreview;
35
+ exports.markEnvAsVitePreview = markEnvAsVitePreview;
26
36
  // Called by ../node/plugin/index.ts
27
- function markEnvAsVite() {
28
- env.isVite = true;
37
+ function markEnvAsVikePluginLoaded() {
38
+ if (debug.isEnabled)
39
+ debug('markEnvAsVikePluginLoaded()', new Error().stack);
40
+ env.isVikePluginLoaded = true;
29
41
  }
30
- exports.markEnvAsVite = markEnvAsVite;
42
+ exports.markEnvAsVikePluginLoaded = markEnvAsVikePluginLoaded;
31
43
  // Called by ../node/runtime/index.ts
32
44
  function assertEnv() {
45
+ if (debug.isEnabled)
46
+ debug('assertEnv()', new Error().stack);
33
47
  if ((0, isVitest_js_1.isVitest)())
34
48
  return;
35
- if (env.isDev || env.isPreview) {
36
- (0, assert_js_1.assert)(env.isVite);
37
- (0, assert_js_1.assert)(env.shouldBeVite);
49
+ const isProduction = !env.isViteDev && !env.isVitePreview;
50
+ if (isProduction) {
51
+ // Seems to be the only reliable way to assert that the user doesn't load Vike's Vite plugin in production. (The other assert() that uses process.env.NODE_ENV doesn't work if the user sets the process.env.NODE_ENV value later.)
52
+ (0, assert_js_1.assertUsage)(!env.isVikePluginLoaded, vikeVitePluginLoadedInProductionError);
53
+ // This assert() is the main goal of this file: it ensures assertIsNotProductionRuntime()
54
+ (0, assert_js_1.assert)(!env.shouldNotBeProduction);
38
55
  }
39
56
  else {
40
- (0, assert_js_1.assert)(!env.isVite);
41
- (0, assert_js_1.assert)(!env.shouldBeVite);
57
+ // This assert() is obious and boring
58
+ (0, assert_js_1.assert)(env.shouldNotBeProduction);
59
+ (0, assert_js_1.assert)(env.isVikePluginLoaded);
42
60
  }
43
61
  }
44
62
  exports.assertEnv = assertEnv;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.setNodeEnvToProduction = exports.getNodeEnv = void 0;
3
+ exports.isNodeEnvDev = exports.setNodeEnvToProduction = exports.getNodeEnv = void 0;
4
4
  function getNodeEnv() {
5
5
  if (typeof process === 'undefined')
6
6
  return null;
@@ -14,3 +14,13 @@ function setNodeEnvToProduction() {
14
14
  env.NODE_ENV = 'production';
15
15
  }
16
16
  exports.setNodeEnvToProduction = setNodeEnvToProduction;
17
+ function isNodeEnvDev() {
18
+ const nodeEnv = getNodeEnv();
19
+ if (!nodeEnv)
20
+ return true;
21
+ if (['development', 'dev'].includes(nodeEnv))
22
+ return true;
23
+ // That's quite aggressive, let's see if some user complains
24
+ return false;
25
+ }
26
+ exports.isNodeEnvDev = isNodeEnvDev;
@@ -2,13 +2,11 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.PROJECT_VERSION = exports.projectInfo = void 0;
4
4
  const assertSingleInstance_js_1 = require("./assertSingleInstance.js");
5
- const PROJECT_VERSION = '0.4.159';
5
+ const PROJECT_VERSION = '0.4.160-commit-a1101c1';
6
6
  exports.PROJECT_VERSION = PROJECT_VERSION;
7
7
  const projectInfo = {
8
8
  projectName: 'Vike',
9
- projectVersion: PROJECT_VERSION,
10
- npmPackageName: 'vike',
11
- githubRepository: 'https://github.com/vikejs/vike'
9
+ projectVersion: PROJECT_VERSION
12
10
  };
13
11
  exports.projectInfo = projectInfo;
14
12
  // Trick: since `utils/asserts.ts` depends on this file (`utils/projectInfo.ts`), we can have confidence that this file is always instantiated. So that we don't have to initialize this code snippet at every possible entry. (There are a *lot* of entries: `client/router/`, `client/`, `node/`, `node/plugin/`, `node/cli`, etc.)
@@ -3,7 +3,7 @@ export { plugin };
3
3
  // TODO/v1-release: remove
4
4
  export { plugin as ssr };
5
5
  export { PROJECT_VERSION as version } from './utils.js';
6
- import { assertUsage, markEnvAsVite } from './utils.js';
6
+ import { assertUsage, getNodeEnv, isNodeEnvDev, markEnvAsVikePluginLoaded, vikeVitePluginLoadedInProductionError } from './utils.js';
7
7
  import { buildConfig } from './plugins/buildConfig.js';
8
8
  import { previewConfig } from './plugins/previewConfig.js';
9
9
  import { autoFullBuild } from './plugins/autoFullBuild.js';
@@ -24,7 +24,8 @@ import { baseUrls } from './plugins/baseUrls.js';
24
24
  import { envVarsPlugin } from './plugins/envVars.js';
25
25
  import pc from '@brillout/picocolors';
26
26
  import { fileEnv } from './plugins/fileEnv.js';
27
- markEnvAsVite();
27
+ assertNodeEnv();
28
+ markEnvAsVikePluginLoaded();
28
29
  // Return as `any` to avoid Plugin type mismatches when there are multiple Vite versions installed
29
30
  function plugin(vikeConfig) {
30
31
  const plugins = [
@@ -64,3 +65,21 @@ Object.defineProperty(plugin, 'apply', {
64
65
  assertUsage(false, `Add ${pc.cyan('vike()')} instead of ${pc.cyan('vike')} to vite.config.js#plugins (i.e. call the function and add the return value instead of adding the function itself)`, { showStackTrace: true });
65
66
  }
66
67
  });
68
+ function assertNodeEnv() {
69
+ const nodeEnv = getNodeEnv();
70
+ if (nodeEnv === 'test')
71
+ return;
72
+ // We should change this to be a warning if it blocks users (e.g. if a bad-citizen tool sets a wrong process.env.NODE_ENV value).
73
+ assertUsage(
74
+ /* We can enable this assertion after Vike's CLI is implemented and using Vite's CLI is deprecated (we can then check whether the context is a `$ vike build`).
75
+ isNodeEnvDev() || isVikeCliBuild(),
76
+ /*/
77
+ isNodeEnvDev() || true,
78
+ ///*/
79
+ [
80
+ pc.cyan(`process.env.NODE_ENV === ${JSON.stringify(nodeEnv)}`),
81
+ '(which Vike interprets as a non-development environment https://vike.dev/NODE_ENV)',
82
+ 'while the vike/plugin module is loaded.',
83
+ vikeVitePluginLoadedInProductionError
84
+ ].join(' '));
85
+ }
@@ -3,7 +3,7 @@ import { determineOptimizeDeps } from './determineOptimizeDeps.js';
3
3
  import { determineFsAllowList } from './determineFsAllowList.js';
4
4
  import { getConfigVike } from '../../../shared/getConfigVike.js';
5
5
  import { addSsrMiddleware } from '../../shared/addSsrMiddleware.js';
6
- import { markEnvAsDev } from '../../utils.js';
6
+ import { markEnvAsViteDev } from '../../utils.js';
7
7
  import { improveViteLogs } from '../../shared/loggerVite.js';
8
8
  import { isErrorDebug } from '../../shared/isErrorDebug.js';
9
9
  import { installHttpRequestAsyncStore } from '../../shared/getHttpRequestAsyncStore.js';
@@ -64,7 +64,7 @@ function devConfig() {
64
64
  }
65
65
  },
66
66
  configureServer() {
67
- markEnvAsDev();
67
+ markEnvAsViteDev();
68
68
  }
69
69
  },
70
70
  {
@@ -1,6 +1,6 @@
1
1
  export { importBuild };
2
2
  import { serverEntryPlugin, findServerEntry } from '@brillout/vite-plugin-server-entry/plugin.js';
3
- import { assert, getOutDirs, projectInfo, toPosixPath, viteIsSSR } from '../../utils.js';
3
+ import { assert, getOutDirs, toPosixPath, viteIsSSR } from '../../utils.js';
4
4
  import path from 'path';
5
5
  import { createRequire } from 'module';
6
6
  import { getConfigVike } from '../../../shared/getConfigVike.js';
@@ -32,7 +32,7 @@ function importBuild() {
32
32
  getImporterCode: () => {
33
33
  return getEntryCode(config, configVike);
34
34
  },
35
- libraryName: projectInfo.projectName
35
+ libraryName: 'Vike'
36
36
  })
37
37
  ];
38
38
  }
@@ -0,0 +1,2 @@
1
+ export { getConfigFileExport };
2
+ declare function getConfigFileExport(fileExports: Record<string, unknown>, filePathToShowToUser: string): Record<string, unknown>;
@@ -0,0 +1,12 @@
1
+ export { getConfigFileExport };
2
+ import pc from '@brillout/picocolors';
3
+ import { assertPlusFileExport } from '../../../../../shared/page-configs/assertPlusFileExport.js';
4
+ import { assert, assertUsage, isObject } from '../../../utils.js';
5
+ function getConfigFileExport(fileExports, filePathToShowToUser) {
6
+ assertPlusFileExport(fileExports, filePathToShowToUser, 'config');
7
+ const fileExport = fileExports.default || fileExports.config;
8
+ assert('default' in fileExports !== 'config' in fileExports);
9
+ const exportName = pc.cyan('default' in fileExports ? 'export default' : 'export { config }');
10
+ assertUsage(isObject(fileExport), `The ${exportName} of ${filePathToShowToUser} should be an object (but it's ${pc.cyan(`typeof exportedValue === ${JSON.stringify(typeof fileExport)}`)} instead)`);
11
+ return fileExport;
12
+ }
@@ -24,12 +24,17 @@ type ConfigDefinition = {
24
24
  */
25
25
  cumulative?: boolean;
26
26
  /**
27
- * Define a so-called "Shortcut Config".
27
+ * Function called when the config value is defined.
28
28
  *
29
29
  * https://vike.dev/meta
30
30
  */
31
31
  effect?: ConfigEffect;
32
32
  };
33
+ /**
34
+ * Function called when the config value is defined.
35
+ *
36
+ * https://vike.dev/meta
37
+ */
33
38
  type ConfigEffect = (config: {
34
39
  /** The config value.
35
40
  *
@@ -0,0 +1,21 @@
1
+ export { loadImportedFile };
2
+ export { loadValueFile };
3
+ export { loadConfigFile };
4
+ export type { ImportedFilesLoaded };
5
+ export type { ConfigFile };
6
+ import type { FilePathResolved } from '../../../../../../shared/page-configs/PageConfig.js';
7
+ import type { InterfaceValueFile } from '../getVikeConfig.js';
8
+ type ImportedFilesLoaded = Record<string, Promise<Record<string, unknown>>>;
9
+ type ConfigFile = {
10
+ fileExports: Record<string, unknown>;
11
+ filePath: FilePathResolved;
12
+ extendsFilePaths: string[];
13
+ };
14
+ declare function loadImportedFile(import_: FilePathResolved & {
15
+ fileExportName: string;
16
+ }, userRootDir: string, importedFilesLoaded: ImportedFilesLoaded): Promise<unknown>;
17
+ declare function loadValueFile(interfaceValueFile: InterfaceValueFile, configName: string, userRootDir: string): Promise<void>;
18
+ declare function loadConfigFile(configFilePath: FilePathResolved, userRootDir: string, visited: string[], isConfigOfExtension: boolean): Promise<{
19
+ configFile: ConfigFile;
20
+ extendsConfigs: ConfigFile[];
21
+ }>;
@@ -0,0 +1,123 @@
1
+ // Files loadded at config time:
2
+ export { loadImportedFile };
3
+ export { loadValueFile };
4
+ export { loadConfigFile };
5
+ import { assertPosixPath, assert, assertUsage, assertWarning, hasProp, assertIsNotProductionRuntime, isNpmPackageImport } from '../../../../utils.js';
6
+ import { transpileAndExecuteFile } from './transpileAndExecuteFile.js';
7
+ import { assertPlusFileExport } from '../../../../../../shared/page-configs/assertPlusFileExport.js';
8
+ import pc from '@brillout/picocolors';
9
+ import { parseImportData } from './transformImports.js';
10
+ import { getConfigFileExport } from '../getConfigFileExport.js';
11
+ import { assertImportPath, resolveImportPath } from './resolveImportPath.js';
12
+ assertIsNotProductionRuntime();
13
+ // Load fake import
14
+ async function loadImportedFile(import_, userRootDir, importedFilesLoaded) {
15
+ const f = import_.filePathAbsoluteFilesystem;
16
+ if (!importedFilesLoaded[f]) {
17
+ importedFilesLoaded[f] = transpileAndExecuteFile(import_, true, userRootDir).then((r) => r.fileExports);
18
+ }
19
+ const fileExports = await importedFilesLoaded[f];
20
+ const fileExport = fileExports[import_.fileExportName];
21
+ return fileExport;
22
+ }
23
+ // Load +{configName}.js
24
+ async function loadValueFile(interfaceValueFile, configName, userRootDir) {
25
+ const { fileExports } = await transpileAndExecuteFile(interfaceValueFile.filePath, true, userRootDir);
26
+ const { filePathToShowToUser } = interfaceValueFile.filePath;
27
+ assertPlusFileExport(fileExports, filePathToShowToUser, configName);
28
+ Object.entries(fileExports).forEach(([exportName, configValue]) => {
29
+ const configName_ = exportName === 'default' ? configName : exportName;
30
+ interfaceValueFile.fileExportsByConfigName[configName_] = { configValue };
31
+ });
32
+ }
33
+ // Load +config.js, including all its extends fake imports
34
+ async function loadConfigFile(configFilePath, userRootDir, visited, isConfigOfExtension) {
35
+ const { filePathAbsoluteFilesystem } = configFilePath;
36
+ assertNoInfiniteLoop(visited, filePathAbsoluteFilesystem);
37
+ const { fileExports } = await transpileAndExecuteFile(configFilePath, false, userRootDir, isConfigOfExtension);
38
+ const { extendsConfigs, extendsFilePaths } = await loadExtendsConfigs(fileExports, configFilePath, userRootDir, [
39
+ ...visited,
40
+ filePathAbsoluteFilesystem
41
+ ]);
42
+ const configFile = {
43
+ fileExports,
44
+ filePath: configFilePath,
45
+ extendsFilePaths
46
+ };
47
+ return { configFile, extendsConfigs };
48
+ }
49
+ function assertNoInfiniteLoop(visited, filePathAbsoluteFilesystem) {
50
+ const idx = visited.indexOf(filePathAbsoluteFilesystem);
51
+ if (idx === -1)
52
+ return;
53
+ const loop = visited.slice(idx);
54
+ assert(loop[0] === filePathAbsoluteFilesystem);
55
+ assertUsage(idx === -1, `Infinite extends loop ${[...loop, filePathAbsoluteFilesystem].join('>')}`);
56
+ }
57
+ async function loadExtendsConfigs(configFileExports, configFilePath, userRootDir, visited) {
58
+ const extendsImportData = getExtendsImportData(configFileExports, configFilePath);
59
+ const extendsConfigFiles = [];
60
+ extendsImportData.map((importData) => {
61
+ const { importPath: importPath } = importData;
62
+ const filePathAbsoluteFilesystem = resolveImportPath(importData, configFilePath);
63
+ assertImportPath(filePathAbsoluteFilesystem, importData, configFilePath);
64
+ warnUserLandExtension(importPath, configFilePath);
65
+ // - filePathRelativeToUserRootDir has no functionality beyond nicer error messages for user
66
+ // - Using importPath would be visually nicer but it's ambigous => we rather pick filePathAbsoluteFilesystem for added clarity
67
+ const filePathRelativeToUserRootDir = determineFilePathRelativeToUserDir(filePathAbsoluteFilesystem, userRootDir);
68
+ const filePathAbsoluteVite = filePathRelativeToUserRootDir ?? importPath;
69
+ extendsConfigFiles.push({
70
+ filePathAbsoluteFilesystem,
71
+ filePathAbsoluteVite,
72
+ filePathRelativeToUserRootDir,
73
+ filePathToShowToUser: filePathAbsoluteVite,
74
+ importPathAbsolute: importPath
75
+ });
76
+ });
77
+ const extendsConfigs = [];
78
+ await Promise.all(extendsConfigFiles.map(async (configFilePath) => {
79
+ const result = await loadConfigFile(configFilePath, userRootDir, visited, true);
80
+ extendsConfigs.push(result.configFile);
81
+ extendsConfigs.push(...result.extendsConfigs);
82
+ }));
83
+ const extendsFilePaths = extendsConfigFiles.map((f) => f.filePathAbsoluteFilesystem);
84
+ return { extendsConfigs, extendsFilePaths };
85
+ }
86
+ function determineFilePathRelativeToUserDir(filePathAbsoluteFilesystem, userRootDir) {
87
+ assertPosixPath(filePathAbsoluteFilesystem);
88
+ assertPosixPath(userRootDir);
89
+ if (!filePathAbsoluteFilesystem.startsWith(userRootDir)) {
90
+ return null;
91
+ }
92
+ let filePathRelativeToUserRootDir = filePathAbsoluteFilesystem.slice(userRootDir.length);
93
+ if (!filePathRelativeToUserRootDir.startsWith('/'))
94
+ filePathRelativeToUserRootDir = '/' + filePathRelativeToUserRootDir;
95
+ return filePathRelativeToUserRootDir;
96
+ }
97
+ function warnUserLandExtension(importPath, configFilePath) {
98
+ assertWarning(isNpmPackageImport(importPath), `${configFilePath.filePathToShowToUser} uses ${pc.cyan('extends')} to inherit from ${pc.cyan(importPath)} which is a user-land file: this is experimental and may be remove at any time. Reach out to a maintainer if you need this.`, { onlyOnce: true });
99
+ }
100
+ function getExtendsImportData(configFileExports, configFilePath) {
101
+ const { filePathToShowToUser } = configFilePath;
102
+ const configFileExport = getConfigFileExport(configFileExports, filePathToShowToUser);
103
+ const wrongUsage = `${filePathToShowToUser} sets the config ${pc.cyan('extends')} to an invalid value, see https://vike.dev/extends`;
104
+ let extendList;
105
+ if (!('extends' in configFileExport)) {
106
+ return [];
107
+ }
108
+ else if (hasProp(configFileExport, 'extends', 'string')) {
109
+ extendList = [configFileExport.extends];
110
+ }
111
+ else if (hasProp(configFileExport, 'extends', 'string[]')) {
112
+ extendList = configFileExport.extends;
113
+ }
114
+ else {
115
+ assertUsage(false, wrongUsage);
116
+ }
117
+ const extendsImportData = extendList.map((importDataSerialized) => {
118
+ const importData = parseImportData(importDataSerialized);
119
+ assertUsage(importData, wrongUsage);
120
+ return importData;
121
+ });
122
+ return extendsImportData;
123
+ }
@@ -0,0 +1,12 @@
1
+ export { resolveImport };
2
+ export { resolveImportPath };
3
+ export { assertImportPath };
4
+ export { clearFilesEnvMap };
5
+ import type { ConfigEnvInternal, DefinedAtFileFullInfo, FilePathResolved } from '../../../../../../shared/page-configs/PageConfig.js';
6
+ import { type ImportData } from './transformImports.js';
7
+ declare function resolveImport(configValue: unknown, importerFilePath: FilePathResolved, userRootDir: string, configEnv: ConfigEnvInternal, configName: string): null | (DefinedAtFileFullInfo & {
8
+ fileExportName: string;
9
+ });
10
+ declare function resolveImportPath(importData: ImportData, importerFilePath: FilePathResolved): string | null;
11
+ declare function assertImportPath(filePathAbsoluteFilesystem: string | null, importData: ImportData, importerFilePath: FilePathResolved): asserts filePathAbsoluteFilesystem is string;
12
+ declare function clearFilesEnvMap(): void;
@@ -0,0 +1,133 @@
1
+ export { resolveImport };
2
+ export { resolveImportPath };
3
+ export { assertImportPath };
4
+ export { clearFilesEnvMap };
5
+ import pc from '@brillout/picocolors';
6
+ import { assert, assertPosixPath, assertUsage, deepEqual, requireResolve } from '../../../../utils.js';
7
+ import { parseImportData } from './transformImports.js';
8
+ import path from 'path';
9
+ const filesEnvMap = new Map();
10
+ function resolveImport(configValue, importerFilePath, userRootDir, configEnv, configName) {
11
+ if (typeof configValue !== 'string')
12
+ return null;
13
+ const importData = parseImportData(configValue);
14
+ if (!importData)
15
+ return null;
16
+ const { importPath, exportName } = importData;
17
+ const filePathAbsoluteFilesystem = resolveImportPath(importData, importerFilePath);
18
+ assertFileEnv(filePathAbsoluteFilesystem ?? importPath, configEnv, configName);
19
+ const fileExportPathToShowToUser = exportName === 'default' || exportName === configName ? [] : [exportName];
20
+ if (importPath.startsWith('.')) {
21
+ // We need to resolve relative paths into absolute paths. Because the import paths are included in virtual files:
22
+ // ```
23
+ // [vite] Internal server error: Failed to resolve import "./onPageTransitionHooks" from "virtual:vike:pageConfigValuesAll:client:/pages/index". Does the file exist?
24
+ // ```
25
+ assertImportPath(filePathAbsoluteFilesystem, importData, importerFilePath);
26
+ const filePathRelativeToUserRootDir = resolveImportPath_relativeToUserRootDir(filePathAbsoluteFilesystem, importData, importerFilePath, userRootDir);
27
+ const filePath = {
28
+ filePathAbsoluteFilesystem,
29
+ filePathRelativeToUserRootDir,
30
+ filePathAbsoluteVite: filePathRelativeToUserRootDir,
31
+ filePathToShowToUser: filePathRelativeToUserRootDir,
32
+ importPathAbsolute: null
33
+ };
34
+ return {
35
+ ...filePath,
36
+ fileExportName: exportName,
37
+ fileExportPathToShowToUser
38
+ };
39
+ }
40
+ else {
41
+ // importPath can be:
42
+ // - an npm package import
43
+ // - a path alias
44
+ const filePath = {
45
+ filePathAbsoluteFilesystem,
46
+ filePathRelativeToUserRootDir: null,
47
+ filePathAbsoluteVite: importPath,
48
+ filePathToShowToUser: importPath,
49
+ importPathAbsolute: importPath
50
+ };
51
+ return {
52
+ ...filePath,
53
+ fileExportName: exportName,
54
+ fileExportPathToShowToUser
55
+ };
56
+ }
57
+ }
58
+ function resolveImportPath_relativeToUserRootDir(filePathAbsoluteFilesystem, importData, configFilePath, userRootDir) {
59
+ assertPosixPath(userRootDir);
60
+ let filePathRelativeToUserRootDir;
61
+ if (filePathAbsoluteFilesystem.startsWith(userRootDir)) {
62
+ filePathRelativeToUserRootDir = getVitePathFromAbsolutePath(filePathAbsoluteFilesystem, userRootDir);
63
+ }
64
+ else {
65
+ assertUsage(false, `${configFilePath.filePathToShowToUser} imports from a relative path ${pc.cyan(importData.importPath)} outside of ${userRootDir} which is forbidden: import from a relative path inside ${userRootDir}, or import from a dependency's package.json#exports entry instead`);
66
+ // None of the following works. Seems to be a Vite bug?
67
+ // /*
68
+ // assert(filePathAbsoluteFilesystem.startsWith('/'))
69
+ // filePath = `/@fs${filePathAbsoluteFilesystem}`
70
+ // /*/
71
+ // filePathRelativeToUserRootDir = path.posix.relative(userRootDir, filePathAbsoluteFilesystem)
72
+ // assert(filePathRelativeToUserRootDir.startsWith('../'))
73
+ // filePathRelativeToUserRootDir = '/' + filePathRelativeToUserRootDir
74
+ // //*/
75
+ }
76
+ assertPosixPath(filePathRelativeToUserRootDir);
77
+ assert(filePathRelativeToUserRootDir.startsWith('/'));
78
+ return filePathRelativeToUserRootDir;
79
+ }
80
+ function resolveImportPath(importData, importerFilePath) {
81
+ const importerFilePathAbsolute = importerFilePath.filePathAbsoluteFilesystem;
82
+ assertPosixPath(importerFilePathAbsolute);
83
+ const cwd = path.posix.dirname(importerFilePathAbsolute);
84
+ // We can't use import.meta.resolve() as of Junary 2023 (and probably for a lot longer): https://stackoverflow.com/questions/54977743/do-require-resolve-for-es-modules#comment137174954_62272600:~:text=But%20the%20argument%20parent%20(aka%20cwd)%20still%20requires%20a%20flag
85
+ // filePathAbsoluteFilesystem is expected to be null when importData.importPath is a Vite path alias
86
+ const filePathAbsoluteFilesystem = requireResolve(importData.importPath, cwd);
87
+ return filePathAbsoluteFilesystem;
88
+ }
89
+ function assertImportPath(filePathAbsoluteFilesystem, importData, importerFilePath) {
90
+ const { importPath: importPath, importStringWasGenerated, importString } = importData;
91
+ const { filePathToShowToUser } = importerFilePath;
92
+ if (!filePathAbsoluteFilesystem) {
93
+ const importPathString = pc.cyan(`'${importPath}'`);
94
+ const errIntro = importStringWasGenerated
95
+ ? `The import path ${importPathString} in ${filePathToShowToUser}`
96
+ : `The import ${pc.cyan(importString)} defined in ${filePathToShowToUser}`;
97
+ const errIntro2 = `${errIntro} couldn't be resolved: does ${importPathString}`;
98
+ if (importPath.startsWith('.')) {
99
+ assertUsage(false, `${errIntro2} point to an existing file?`);
100
+ }
101
+ else {
102
+ assertUsage(false, `${errIntro2} exist?`);
103
+ }
104
+ }
105
+ }
106
+ function assertFileEnv(filePathForEnvCheck, configEnv, configName) {
107
+ assertPosixPath(filePathForEnvCheck);
108
+ if (!filesEnvMap.has(filePathForEnvCheck)) {
109
+ filesEnvMap.set(filePathForEnvCheck, []);
110
+ }
111
+ const fileEnv = filesEnvMap.get(filePathForEnvCheck);
112
+ fileEnv.push({ configEnv, configName });
113
+ const configDifferentEnv = fileEnv.filter((c) => !deepEqual(c.configEnv, configEnv))[0];
114
+ if (configDifferentEnv) {
115
+ assertUsage(false, [
116
+ `${filePathForEnvCheck} defines the value of configs living in different environments:`,
117
+ ...[configDifferentEnv, { configName, configEnv }].map((c) => ` - config ${pc.cyan(c.configName)} which value lives in environment ${pc.cyan(JSON.stringify(c.configEnv))}`),
118
+ 'Defining config values in the same file is allowed only if they live in the same environment, see https://vike.dev/header-file'
119
+ ].join('\n'));
120
+ }
121
+ }
122
+ function clearFilesEnvMap() {
123
+ filesEnvMap.clear();
124
+ }
125
+ function getVitePathFromAbsolutePath(filePathAbsoluteFilesystem, root) {
126
+ assertPosixPath(filePathAbsoluteFilesystem);
127
+ assertPosixPath(root);
128
+ assert(filePathAbsoluteFilesystem.startsWith(root));
129
+ let vitePath = path.posix.relative(root, filePathAbsoluteFilesystem);
130
+ assert(!vitePath.startsWith('/') && !vitePath.startsWith('.'));
131
+ vitePath = '/' + vitePath;
132
+ return vitePath;
133
+ }