vike 0.4.163 → 0.4.165-commit-74b18b0

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 (61) hide show
  1. package/dist/cjs/__internal/index.js +1 -1
  2. package/dist/cjs/node/plugin/index.js +6 -18
  3. package/dist/cjs/node/plugin/plugins/autoFullBuild.js +7 -4
  4. package/dist/cjs/node/plugin/plugins/buildConfig/fixServerAssets.js +8 -4
  5. package/dist/cjs/node/plugin/plugins/buildConfig.js +7 -8
  6. package/dist/cjs/node/plugin/plugins/distFileNames.js +4 -9
  7. package/dist/cjs/node/plugin/shared/getAssetsDir.js +11 -0
  8. package/dist/cjs/node/plugin/shared/getHttpRequestAsyncStore.js +15 -23
  9. package/dist/cjs/node/plugin/shared/loggerNotProd/errorWithCodeSnippet/fixture-errors/{errMdx.js → errMdx1.js} +2 -2
  10. package/dist/cjs/node/plugin/shared/loggerNotProd/errorWithCodeSnippet/fixture-errors/errMdx2.js +85 -0
  11. package/dist/cjs/node/plugin/shared/loggerNotProd.js +15 -11
  12. package/dist/cjs/node/plugin/shared/loggerVite.js +12 -18
  13. package/dist/cjs/node/plugin/utils.js +1 -1
  14. package/dist/cjs/node/prerender/runPrerender.js +1 -8
  15. package/dist/cjs/node/runtime/globalContext.js +1 -13
  16. package/dist/cjs/node/runtime/renderPage/logErrorHint.js +2 -13
  17. package/dist/cjs/node/runtime/renderPage/loggerProd.js +5 -1
  18. package/dist/cjs/node/runtime/renderPage.js +2 -4
  19. package/dist/cjs/shared/route/resolveRouteString.js +0 -1
  20. package/dist/cjs/utils/assertNodeEnv.js +65 -10
  21. package/dist/cjs/utils/assertNodeVersion.js +3 -4
  22. package/dist/cjs/utils/{isVersionOrAbove.js → assertVersion.js} +5 -1
  23. package/dist/cjs/utils/projectInfo.js +1 -1
  24. package/dist/esm/__internal/index.js +2 -2
  25. package/dist/esm/node/plugin/index.js +7 -19
  26. package/dist/esm/node/plugin/plugins/autoFullBuild.js +7 -4
  27. package/dist/esm/node/plugin/plugins/buildConfig/fixServerAssets.d.ts +2 -2
  28. package/dist/esm/node/plugin/plugins/buildConfig/fixServerAssets.js +9 -5
  29. package/dist/esm/node/plugin/plugins/buildConfig.js +8 -9
  30. package/dist/esm/node/plugin/plugins/distFileNames.js +1 -6
  31. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVikeConfig.d.ts +3 -3
  32. package/dist/esm/node/plugin/shared/getAssetsDir.d.ts +3 -0
  33. package/dist/esm/node/plugin/shared/getAssetsDir.js +8 -0
  34. package/dist/esm/node/plugin/shared/getHttpRequestAsyncStore.d.ts +0 -1
  35. package/dist/esm/node/plugin/shared/getHttpRequestAsyncStore.js +16 -24
  36. package/dist/esm/node/plugin/shared/loggerNotProd/errorWithCodeSnippet/fixture-errors/{errMdx.d.ts → errMdx1.d.ts} +1 -1
  37. package/dist/esm/node/plugin/shared/loggerNotProd/errorWithCodeSnippet/fixture-errors/{errMdx.js → errMdx1.js} +1 -1
  38. package/dist/esm/node/plugin/shared/loggerNotProd/errorWithCodeSnippet/fixture-errors/errMdx2.d.ts +44 -0
  39. package/dist/esm/node/plugin/shared/loggerNotProd/errorWithCodeSnippet/fixture-errors/errMdx2.js +82 -0
  40. package/dist/esm/node/plugin/shared/loggerNotProd.d.ts +3 -6
  41. package/dist/esm/node/plugin/shared/loggerNotProd.js +14 -10
  42. package/dist/esm/node/plugin/shared/loggerVite.js +13 -19
  43. package/dist/esm/node/plugin/utils.d.ts +1 -1
  44. package/dist/esm/node/plugin/utils.js +1 -1
  45. package/dist/esm/node/prerender/runPrerender.js +2 -9
  46. package/dist/esm/node/runtime/globalContext.js +2 -14
  47. package/dist/esm/node/runtime/renderPage/logErrorHint.js +3 -11
  48. package/dist/esm/node/runtime/renderPage/loggerProd.js +5 -1
  49. package/dist/esm/node/runtime/renderPage.d.ts +0 -1
  50. package/dist/esm/node/runtime/renderPage.js +2 -4
  51. package/dist/esm/shared/page-configs/Config/PageContextConfig.d.ts +1 -1
  52. package/dist/esm/shared/route/resolveRouteString.js +0 -1
  53. package/dist/esm/utils/assertNodeEnv.d.ts +10 -10
  54. package/dist/esm/utils/assertNodeEnv.js +67 -10
  55. package/dist/esm/utils/assertNodeVersion.js +3 -4
  56. package/dist/esm/utils/assertVersion.d.ts +4 -0
  57. package/dist/esm/utils/{isVersionOrAbove.js → assertVersion.js} +5 -1
  58. package/dist/esm/utils/projectInfo.d.ts +2 -2
  59. package/dist/esm/utils/projectInfo.js +1 -1
  60. package/package.json +3 -2
  61. package/dist/esm/utils/isVersionOrAbove.d.ts +0 -2
@@ -1,29 +1,84 @@
1
1
  "use strict";
2
- // Utils to manage process.env.NODE_ENV and, most notably, to assert correct usage, which is crucial:
3
- // - https://github.com/vikejs/vike/issues/1469#issuecomment-1919518096
4
- // - https://github.com/vitejs/vite/blob/76f30ae23b92f9af910ec02d98e2baaefa12141f/packages/vite/src/node/config.ts#L567
2
+ // This file serves the following three purposes:
3
+ // 1. Upon building the app, we ensure the right NODE_ENV value is set.
4
+ // - Both Vue and React use NODE_ENV for enabling production-specific features:
5
+ // - Vue: https://github.com/vuejs/core/blob/f66a75ea75c8aece065b61e2126b4c5b2338aa6e/packages/vue/index.js
6
+ // - React: https://github.com/facebook/react/blob/01ab35a9a731dec69995fbd28f3ac7eaad11e183/packages/react/npm/index.js
7
+ // - Setting NODE_ENV to 'production' doesn't seem to make any sense in development.
8
+ // - With React upon building the app, setting NODE_ENV to a value other than 'production' triggers an error: https://github.com/vikejs/vike/issues/1469#issuecomment-1969301797
9
+ // - With Vue upon building the app, NODE_ENV can be set to a value other than 'production', e.g. 'development'.
10
+ // 2. Ensure Vite isn't loaded in production.
11
+ // - We currently only check whether Vite's development middleware is instantiated (i.e. whether Vite's `createServer()` was called). Is there a way to detect whether Vite's code is loaded?
12
+ // 3. Ensure NODE_ENV isn't mistakenly set to a wrong value.
5
13
  var __importDefault = (this && this.__importDefault) || function (mod) {
6
14
  return (mod && mod.__esModule) ? mod : { "default": mod };
7
15
  };
8
16
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.assertNodeEnvIsNotDev = exports.getNodeEnvDesc = exports.isNodeEnvDev = exports.setNodeEnvToProduction = exports.getNodeEnv = void 0;
17
+ exports.handleNodeEnv_vitePluginVercel = exports.handleNodeEnv_prerender = exports.assertNodeEnv_onVikePluginLoad = exports.assertNodeEnv_runtime = exports.assertNodeEnv_build = void 0;
10
18
  const picocolors_1 = __importDefault(require("@brillout/picocolors"));
11
19
  const assertIsNotBrowser_js_1 = require("./assertIsNotBrowser.js");
12
20
  const assert_js_1 = require("./assert.js");
21
+ const assertIsNotProductionRuntime_js_1 = require("./assertIsNotProductionRuntime.js");
13
22
  (0, assertIsNotBrowser_js_1.assertIsNotBrowser)();
23
+ function assertNodeEnv_build() {
24
+ assertNodeEnvIsNotDev('building');
25
+ }
26
+ exports.assertNodeEnv_build = assertNodeEnv_build;
27
+ function assertNodeEnv_runtime(viteDevServerExists) {
28
+ const nodeEnv = getNodeEnv();
29
+ if (nodeEnv === null || nodeEnv === 'test')
30
+ return;
31
+ const isDev = isNodeEnvDev();
32
+ // Calling Vite's createServer() is enough for hasViteDevServer to be true, even without actually adding Vite's development middleware to the server: https://github.com/vikejs/vike/issues/792#issuecomment-1516830759
33
+ if (viteDevServerExists === isDev)
34
+ return;
35
+ const nodeEnvDesc = getNodeEnvDesc();
36
+ // TODO: make it assertUsage() again once #1528 is implemented.
37
+ (0, assert_js_1.assertWarning)(false, `Vite's development server was${viteDevServerExists ? '' : "n't"} instantiated while the ${nodeEnvDesc} which is contradictory, see https://vike.dev/NODE_ENV`, { onlyOnce: true });
38
+ }
39
+ exports.assertNodeEnv_runtime = assertNodeEnv_runtime;
40
+ function assertNodeEnv_onVikePluginLoad() {
41
+ const nodeEnv = getNodeEnv();
42
+ if (nodeEnv === 'test')
43
+ return;
44
+ // TODO: make it assertUsage() again once #1528 is implemented.
45
+ (0, assert_js_1.assertWarning)(
46
+ /* 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`).
47
+ isNodeEnvDev() || isVikeCliBuild(),
48
+ /*/
49
+ isNodeEnvDev() || true,
50
+ ///*/
51
+ [
52
+ picocolors_1.default.cyan(`process.env.NODE_ENV === ${JSON.stringify(nodeEnv)}`),
53
+ '(which Vike interprets as a non-development environment https://vike.dev/NODE_ENV)',
54
+ 'while the vike/plugin module is loaded.',
55
+ assertIsNotProductionRuntime_js_1.vikeVitePluginLoadedInProductionError
56
+ ].join(' '), { onlyOnce: true });
57
+ }
58
+ exports.assertNodeEnv_onVikePluginLoad = assertNodeEnv_onVikePluginLoad;
59
+ function handleNodeEnv_prerender() {
60
+ const assertNodeEnv = () => assertNodeEnvIsNotDev('pre-rendering');
61
+ if (getNodeEnv())
62
+ assertNodeEnv();
63
+ setNodeEnvToProduction();
64
+ assertNodeEnv();
65
+ }
66
+ exports.handleNodeEnv_prerender = handleNodeEnv_prerender;
67
+ function handleNodeEnv_vitePluginVercel() {
68
+ setNodeEnvToProduction();
69
+ }
70
+ exports.handleNodeEnv_vitePluginVercel = handleNodeEnv_vitePluginVercel;
14
71
  function getNodeEnv() {
15
72
  if (typeof process === 'undefined')
16
73
  return null;
17
74
  return process.env.NODE_ENV;
18
75
  }
19
- exports.getNodeEnv = getNodeEnv;
20
76
  function setNodeEnvToProduction() {
21
77
  // The statement `process.env['NODE_ENV'] = 'production'` chokes webpack v4
22
78
  const proc = process;
23
79
  const { env } = proc;
24
80
  env.NODE_ENV = 'production';
25
81
  }
26
- exports.setNodeEnvToProduction = setNodeEnvToProduction;
27
82
  function isNodeEnvDev() {
28
83
  const nodeEnv = getNodeEnv();
29
84
  if (!nodeEnv)
@@ -33,19 +88,19 @@ function isNodeEnvDev() {
33
88
  // That's quite aggressive, let's see if some user complains
34
89
  return false;
35
90
  }
36
- exports.isNodeEnvDev = isNodeEnvDev;
37
91
  function getNodeEnvDesc() {
38
92
  const nodeEnv = getNodeEnv();
39
93
  const isDev = isNodeEnvDev();
40
94
  const nodeEnvDesc = `environment is set to be a ${(isDev ? 'development' : 'production')} environment by ${picocolors_1.default.cyan(`process.env.NODE_ENV === ${JSON.stringify(nodeEnv)}`)}`;
41
95
  return nodeEnvDesc;
42
96
  }
43
- exports.getNodeEnvDesc = getNodeEnvDesc;
44
97
  function assertNodeEnvIsNotDev(operation) {
45
98
  const isDev = isNodeEnvDev();
46
99
  if (!isDev)
47
100
  return;
48
101
  const nodeEnvDesc = getNodeEnvDesc();
49
- (0, assert_js_1.assertUsage)(false, `The ${nodeEnvDesc} which is forbidden upon ${operation}, see https://vike.dev/NODE_ENV`);
102
+ // TODO: make it assertUsage() again once #1528 is implemented.
103
+ (0, assert_js_1.assertWarning)(false, `The ${nodeEnvDesc} which is forbidden upon ${operation}, see https://vike.dev/NODE_ENV`, {
104
+ onlyOnce: true
105
+ });
50
106
  }
51
- exports.assertNodeEnvIsNotDev = assertNodeEnvIsNotDev;
@@ -1,14 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.assertNodeVersion = void 0;
4
- const assert_js_1 = require("./assert.js");
5
4
  const isNodeJS_js_1 = require("./isNodeJS.js");
6
- const isVersionOrAbove_js_1 = require("./isVersionOrAbove.js");
7
- // package.json#engines.node isn't enough as users can ignore it
5
+ const assertVersion_js_1 = require("./assertVersion.js");
6
+ // node_modules/vike/package.json#engines.node isn't enough as users can ignore it
8
7
  function assertNodeVersion() {
9
8
  if (!(0, isNodeJS_js_1.isNodeJS)())
10
9
  return;
11
10
  const version = process.versions.node;
12
- (0, assert_js_1.assertUsage)((0, isVersionOrAbove_js_1.isVersionOrAbove)(version, '16.0.0'), `Node.js ${version} isn't supported, use Node.js >=16.0.0 instead.`);
11
+ (0, assertVersion_js_1.assertVersion)('Node.js', version, '16.0.0');
13
12
  }
14
13
  exports.assertNodeVersion = assertNodeVersion;
@@ -1,7 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isVersionOrAbove = void 0;
3
+ exports.isVersionOrAbove = exports.assertVersion = void 0;
4
4
  const assert_js_1 = require("./assert.js");
5
+ function assertVersion(dependencyName, versionActual, versionExpected) {
6
+ (0, assert_js_1.assertUsage)(isVersionOrAbove(versionActual, versionExpected), `${dependencyName} ${versionActual} isn't supported, use ${dependencyName} >= ${versionExpected} instead.`);
7
+ }
8
+ exports.assertVersion = assertVersion;
5
9
  function isVersionOrAbove(versionActual, versionExpected) {
6
10
  const p1 = parseVersion(versionActual);
7
11
  const p2 = parseVersion(versionExpected);
@@ -2,7 +2,7 @@
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.163';
5
+ const PROJECT_VERSION = '0.4.165-commit-74b18b0';
6
6
  exports.PROJECT_VERSION = PROJECT_VERSION;
7
7
  const projectInfo = {
8
8
  projectName: 'Vike',
@@ -2,7 +2,7 @@
2
2
  export { route, getPagesAndRoutes };
3
3
  import { route as routeInternal } from '../shared/route/index.js';
4
4
  import { getGlobalContext, initGlobalContext } from '../node/runtime/globalContext.js';
5
- import { setNodeEnvToProduction } from '../utils/assertNodeEnv.js';
5
+ import { handleNodeEnv_vitePluginVercel } from '../utils/assertNodeEnv.js';
6
6
  import { assert } from '../utils/assert.js';
7
7
  import { getRenderContext } from '../node/runtime/renderPage/renderPageAlreadyRouted.js';
8
8
  /**
@@ -12,7 +12,7 @@ import { getRenderContext } from '../node/runtime/renderPage/renderPageAlreadyRo
12
12
  * @param config
13
13
  */
14
14
  async function getPagesAndRoutes() {
15
- setNodeEnvToProduction();
15
+ handleNodeEnv_vitePluginVercel();
16
16
  await initGlobalContext(true);
17
17
  const globalContext = getGlobalContext();
18
18
  assert(globalContext.isProduction === true);
@@ -3,7 +3,8 @@ 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, getNodeEnv, isNodeEnvDev, markEnvAsVikePluginLoaded, vikeVitePluginLoadedInProductionError } from './utils.js';
6
+ import { version } from 'vite';
7
+ import { assertNodeEnv_onVikePluginLoad, assertUsage, assertVersion, markEnvAsVikePluginLoaded } from './utils.js';
7
8
  import { buildConfig } from './plugins/buildConfig.js';
8
9
  import { previewConfig } from './plugins/previewConfig.js';
9
10
  import { autoFullBuild } from './plugins/autoFullBuild.js';
@@ -23,8 +24,9 @@ import { baseUrls } from './plugins/baseUrls.js';
23
24
  import { envVarsPlugin } from './plugins/envVars.js';
24
25
  import pc from '@brillout/picocolors';
25
26
  import { fileEnv } from './plugins/fileEnv.js';
26
- assertNodeEnv();
27
+ assertNodeEnv_onVikePluginLoad();
27
28
  markEnvAsVikePluginLoaded();
29
+ assertViteVersion();
28
30
  // Return as `any` to avoid Plugin type mismatches when there are multiple Vite versions installed
29
31
  function plugin(vikeConfig) {
30
32
  const plugins = [
@@ -63,21 +65,7 @@ Object.defineProperty(plugin, 'apply', {
63
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 });
64
66
  }
65
67
  });
66
- function assertNodeEnv() {
67
- const nodeEnv = getNodeEnv();
68
- if (nodeEnv === 'test')
69
- return;
70
- // 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).
71
- assertUsage(
72
- /* 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`).
73
- isNodeEnvDev() || isVikeCliBuild(),
74
- /*/
75
- isNodeEnvDev() || true,
76
- ///*/
77
- [
78
- pc.cyan(`process.env.NODE_ENV === ${JSON.stringify(nodeEnv)}`),
79
- '(which Vike interprets as a non-development environment https://vike.dev/NODE_ENV)',
80
- 'while the vike/plugin module is loaded.',
81
- vikeVitePluginLoadedInProductionError
82
- ].join(' '));
68
+ // node_modules/vike/package.json#peerDependencies.vite isn't enough as users can ignore it
69
+ function assertViteVersion() {
70
+ assertVersion('Vite', version, '4.4.0');
83
71
  }
@@ -6,6 +6,7 @@ import { getConfigVike } from '../../shared/getConfigVike.js';
6
6
  import { isViteCliCall, getViteConfigFromCli } from '../shared/isViteCliCall.js';
7
7
  import pc from '@brillout/picocolors';
8
8
  import { logErrorHint } from '../../runtime/renderPage/logErrorHint.js';
9
+ import { manifestTempFile } from './buildConfig.js';
9
10
  let forceExit = false;
10
11
  function autoFullBuild() {
11
12
  let config;
@@ -58,10 +59,12 @@ async function triggerFullBuild(config, configVike, bundle) {
58
59
  return; // already triggered
59
60
  if (isDisabled(configVike))
60
61
  return;
61
- /* Is this @vitejs/plugin-legacy workaround still needed? Should we re-implement it?
62
- // vike.json missing => it isn't a `$ vite build` call (e.g. @vitejs/plugin-legacy calls Vite's build() API) => skip
63
- if (!bundle['vike.json']) return
64
- */
62
+ // Workaround for @vitejs/plugin-legacy
63
+ // - The legacy plugin triggers its own Rollup build for the client-side.
64
+ // - The legacy plugin doesn't generate a manifest => we can use that to detect the legacy plugin build.
65
+ // - Issue & reproduction: https://github.com/vikejs/vike/issues/1154#issuecomment-1965954636
66
+ if (!bundle[manifestTempFile])
67
+ return;
65
68
  const configFromCli = !isViteCliCall() ? null : getViteConfigFromCli();
66
69
  const configInline = {
67
70
  ...configFromCli,
@@ -1,7 +1,7 @@
1
1
  export { fixServerAssets };
2
2
  export { fixServerAssets_isEnabled };
3
3
  import { ViteManifest } from '../../../shared/ViteManifest.js';
4
- import { OutDirs } from '../../utils.js';
4
+ import { ResolvedConfig } from 'vite';
5
5
  /**
6
6
  * true => use workaround config.build.ssrEmitAssets
7
7
  * false => use workaround extractAssets plugin
@@ -10,4 +10,4 @@ import { OutDirs } from '../../utils.js';
10
10
  */
11
11
  declare function fixServerAssets_isEnabled(): boolean;
12
12
  /** https://github.com/vikejs/vike/issues/1339 */
13
- declare function fixServerAssets(outDirs: OutDirs): Promise<ViteManifest>;
13
+ declare function fixServerAssets(config: ResolvedConfig): Promise<ViteManifest>;
@@ -3,9 +3,10 @@ export { fixServerAssets_isEnabled };
3
3
  import fs from 'fs/promises';
4
4
  import path from 'path';
5
5
  import { existsSync } from 'fs';
6
- import { assert, pLimit, unique } from '../../utils.js';
6
+ import { assert, getOutDirs, pLimit, unique } from '../../utils.js';
7
7
  import { isVirtualFileIdPageConfigValuesAll } from '../../../shared/virtual-files/virtualFilePageConfigValuesAll.js';
8
8
  import { manifestTempFile } from '../buildConfig.js';
9
+ import { getAssetsDir } from '../../shared/getAssetsDir.js';
9
10
  /**
10
11
  * true => use workaround config.build.ssrEmitAssets
11
12
  * false => use workaround extractAssets plugin
@@ -18,11 +19,12 @@ function fixServerAssets_isEnabled() {
18
19
  return true;
19
20
  }
20
21
  /** https://github.com/vikejs/vike/issues/1339 */
21
- async function fixServerAssets(outDirs) {
22
+ async function fixServerAssets(config) {
23
+ const outDirs = getOutDirs(config);
22
24
  const clientManifest = await loadManifest(outDirs.outDirClient);
23
25
  const serverManifest = await loadManifest(outDirs.outDirServer);
24
26
  const { clientManifestMod, filesToCopy } = addServerAssets(clientManifest, serverManifest);
25
- await copyAssets(filesToCopy, outDirs);
27
+ await copyAssets(filesToCopy, config);
26
28
  return clientManifestMod;
27
29
  }
28
30
  async function loadManifest(outDir) {
@@ -33,8 +35,10 @@ async function loadManifest(outDir) {
33
35
  assert(manifest);
34
36
  return manifest;
35
37
  }
36
- async function copyAssets(filesToCopy, { outDirClient, outDirServer }) {
37
- const assetsDirServer = path.posix.join(outDirServer, 'assets');
38
+ async function copyAssets(filesToCopy, config) {
39
+ const { outDirClient, outDirServer } = getOutDirs(config);
40
+ const assetsDir = getAssetsDir(config);
41
+ const assetsDirServer = path.posix.join(outDirServer, assetsDir);
38
42
  if (!filesToCopy.length)
39
43
  return;
40
44
  assert(existsSync(assetsDirServer));
@@ -2,7 +2,7 @@ export { buildConfig };
2
2
  export { assertRollupInput };
3
3
  export { analyzeClientEntries };
4
4
  export { manifestTempFile };
5
- import { assert, resolveOutDir, viteIsSSR, getFilePathAbsolute, addOnBeforeLogHook, removeFileExtention, unique, assertPosixPath, assertUsage, injectRollupInputs, normalizeRollupInput, assertNodeEnvIsNotDev, getOutDirs, isNpmPackageImport } from '../utils.js';
5
+ import { assert, resolveOutDir, viteIsSSR, getFilePathAbsolute, addOnBeforeLogHook, removeFileExtention, unique, assertPosixPath, assertUsage, injectRollupInputs, normalizeRollupInput, getOutDirs, isNpmPackageImport, assertNodeEnv_build } from '../utils.js';
6
6
  import { getVikeConfig, isV1Design } from './importUserCode/v1-design/getVikeConfig.js';
7
7
  import { getConfigValue } from '../../../shared/page-configs/helpers.js';
8
8
  import { findPageFiles } from '../shared/findPageFiles.js';
@@ -24,14 +24,16 @@ function buildConfig() {
24
24
  let isServerAssetsFixEnabled;
25
25
  let isSsrBuild;
26
26
  let outDirs;
27
+ let config;
27
28
  return {
28
29
  name: 'vike:buildConfig',
29
30
  apply: 'build',
30
31
  enforce: 'post',
31
32
  configResolved: {
32
33
  order: 'post',
33
- async handler(config) {
34
- assertNodeEnv();
34
+ async handler(config_) {
35
+ config = config_;
36
+ assertNodeEnv_build();
35
37
  assertRollupInput(config);
36
38
  const entries = await getEntries(config);
37
39
  assert(Object.keys(entries).length > 0);
@@ -50,7 +52,7 @@ function buildConfig() {
50
52
  }
51
53
  },
52
54
  config(config) {
53
- assertNodeEnv();
55
+ assertNodeEnv_build();
54
56
  isSsrBuild = viteIsSSR(config);
55
57
  return {
56
58
  build: {
@@ -61,7 +63,7 @@ function buildConfig() {
61
63
  };
62
64
  },
63
65
  buildStart() {
64
- assertNodeEnv();
66
+ assertNodeEnv_build();
65
67
  },
66
68
  writeBundle: {
67
69
  order: 'post',
@@ -78,7 +80,7 @@ function buildConfig() {
78
80
  await fs.copyFile(clientManifestFilePath, assetsJsonFilePath);
79
81
  }
80
82
  else {
81
- const clientManifestMod = await fixServerAssets(outDirs);
83
+ const clientManifestMod = await fixServerAssets(config);
82
84
  await fs.writeFile(assetsJsonFilePath, JSON.stringify(clientManifestMod, null, 2), 'utf-8');
83
85
  }
84
86
  await fs.rm(clientManifestFilePath);
@@ -252,6 +254,3 @@ function assertRollupInput(config) {
252
254
  const htmlInput = htmlInputs[0];
253
255
  assertUsage(htmlInput === undefined, `The entry ${htmlInput} of config build.rollupOptions.input is an HTML entry which is forbidden when using Vike, instead follow https://vike.dev/add`);
254
256
  }
255
- function assertNodeEnv() {
256
- assertNodeEnvIsNotDev('building');
257
- }
@@ -4,6 +4,7 @@ export { distFileNames };
4
4
  // - Blocker: https://github.com/rollup/rollup/issues/4724
5
5
  import { assertPosixPath, assert, assertUsage } from '../utils.js';
6
6
  import path from 'path';
7
+ import { getAssetsDir } from '../shared/getAssetsDir.js';
7
8
  function distFileNames() {
8
9
  return {
9
10
  name: 'vike:distFileNames',
@@ -163,9 +164,3 @@ function getRollupOutputs(config) {
163
164
  }
164
165
  return output;
165
166
  }
166
- function getAssetsDir(config) {
167
- let { assetsDir } = config.build;
168
- assertUsage(assetsDir, `${assetsDir} cannot be an empty string`);
169
- assetsDir = assetsDir.split(/\/|\\/).filter(Boolean).join('/');
170
- return assetsDir;
171
- }
@@ -3,7 +3,7 @@ export { reloadVikeConfig };
3
3
  export { vikeConfigDependencies };
4
4
  export { isVikeConfigFile };
5
5
  export { isV1Design };
6
- export type { VikeConfig };
6
+ export type { VikeConfigObject };
7
7
  export type { InterfaceValueFile };
8
8
  import type { PageConfigGlobalBuildTime, PageConfigBuildTime, FilePathResolved } from '../../../../../shared/page-configs/PageConfig.js';
9
9
  import { type LocationId } from './getVikeConfig/filesystemRouting.js';
@@ -21,13 +21,13 @@ type InterfaceValueFile = InterfaceFileCommons & {
21
21
  configName: string;
22
22
  };
23
23
  type ConfigName = string;
24
- type VikeConfig = {
24
+ type VikeConfigObject = {
25
25
  pageConfigs: PageConfigBuildTime[];
26
26
  pageConfigGlobal: PageConfigGlobalBuildTime;
27
27
  globalVikeConfig: Record<string, unknown>;
28
28
  };
29
29
  declare const vikeConfigDependencies: Set<string>;
30
30
  declare function reloadVikeConfig(userRootDir: string, outDirRoot: string): void;
31
- declare function getVikeConfig(config: ResolvedConfig, isDev: boolean, tolerateInvalidConfig?: boolean): Promise<VikeConfig>;
31
+ declare function getVikeConfig(config: ResolvedConfig, isDev: boolean, tolerateInvalidConfig?: boolean): Promise<VikeConfigObject>;
32
32
  declare function isV1Design(config: ResolvedConfig, isDev: boolean): Promise<boolean>;
33
33
  declare function isVikeConfigFile(filePath: string): boolean;
@@ -0,0 +1,3 @@
1
+ export { getAssetsDir };
2
+ import type { ResolvedConfig } from 'vite';
3
+ declare function getAssetsDir(config: ResolvedConfig): string;
@@ -0,0 +1,8 @@
1
+ export { getAssetsDir };
2
+ import { assertUsage } from '../utils.js';
3
+ function getAssetsDir(config) {
4
+ let { assetsDir } = config.build;
5
+ assertUsage(assetsDir, `${assetsDir} cannot be an empty string`);
6
+ assetsDir = assetsDir.split(/\/|\\/).filter(Boolean).join('/');
7
+ return assetsDir;
8
+ }
@@ -4,7 +4,6 @@ type HttpRequestAsyncStore = {
4
4
  httpRequestId: number;
5
5
  shouldErrorBeSwallowed: (err: unknown) => boolean;
6
6
  markErrorAsLogged: (err: unknown) => void;
7
- markErrorMessageAsLogged: (errMsg: string) => void;
8
7
  errorDebugNoteAlreadyShown: boolean;
9
8
  };
10
9
  declare function installHttpRequestAsyncStore(): Promise<void>;
@@ -11,10 +11,11 @@
11
11
  export { getHttpRequestAsyncStore };
12
12
  export { installHttpRequestAsyncStore };
13
13
  import { renderPage_addWrapper } from '../../runtime/renderPage.js';
14
- import { assert, assertIsNotProductionRuntime, isObject } from '../utils.js';
14
+ import { assert, assertIsNotProductionRuntime, isObject, unique } from '../utils.js';
15
15
  import { getConfigBuildErrorFormatted } from '../plugins/importUserCode/v1-design/getVikeConfig/transpileAndExecuteFile.js';
16
16
  import { logErrorDebugNote } from './loggerNotProd.js';
17
17
  import { isEquivalentErrorWithCodeSnippet } from './loggerNotProd/errorWithCodeSnippet.js';
18
+ import { isDeepStrictEqual } from 'node:util';
18
19
  assertIsNotProductionRuntime();
19
20
  let asyncLocalStorage = null;
20
21
  async function installHttpRequestAsyncStore() {
@@ -44,29 +45,14 @@ async function installHttpRequestAsyncStore() {
44
45
  return false;
45
46
  }
46
47
  };
47
- // Remove once https://github.com/vitejs/vite/pull/13495 is released
48
- const swallowedErrorMessages = new Set();
49
- const markErrorMessageAsLogged = (errMsg) => {
50
- swallowedErrorMessages.add(errMsg);
51
- };
52
- const onRequestDone = () => {
53
- swallowedErrorMessages.forEach((errMsg) => {
54
- if (!Array.from(loggedErrors).some((err) => String(err).includes(errMsg))) {
55
- console.error('loggedErrors', loggedErrors);
56
- console.error('swallowedErrorMessages', swallowedErrorMessages);
57
- assert(false);
58
- }
59
- });
60
- };
61
48
  const store = {
62
49
  httpRequestId,
63
50
  markErrorAsLogged,
64
- markErrorMessageAsLogged,
65
51
  shouldErrorBeSwallowed,
66
52
  errorDebugNoteAlreadyShown: false
67
53
  };
68
54
  const pageContextReturn = await asyncLocalStorage.run(store, renderPage);
69
- return { pageContextReturn, onRequestDone };
55
+ return { pageContextReturn };
70
56
  });
71
57
  return;
72
58
  }
@@ -90,14 +76,20 @@ function isEquivalent(err1, err2) {
90
76
  }
91
77
  if (isEquivalentErrorWithCodeSnippet(err1, err2))
92
78
  return true;
93
- if (err1.constructor === Error &&
94
- Object.keys(err1).length === 0 &&
95
- isDefinedAndSame(err1.message, err2.message) &&
96
- isDefinedAndSame(err1.stack, err2.stack)) {
79
+ if (unique([
80
+ // error.message and error.stack aren't enumerable and therefore not listed by Object.keys()
81
+ 'message',
82
+ 'stack',
83
+ ...Object.keys(err1),
84
+ ...Object.keys(err2)
85
+ ]).every((k) => {
86
+ // isDeepStrictEqual() need to compare error.position wich is an object.
87
+ if (isDeepStrictEqual(err1[k], err2[k]))
88
+ return true;
89
+ // console.log('diff', k)
90
+ return false;
91
+ })) {
97
92
  return true;
98
93
  }
99
94
  return false;
100
95
  }
101
- function isDefinedAndSame(val1, val2) {
102
- return val1 && val1 === val2;
103
- }
@@ -1,4 +1,4 @@
1
- export declare const errMdx: {
1
+ export declare const errMdx1: {
2
2
  name: string;
3
3
  message: string;
4
4
  reason: string;
@@ -1,4 +1,4 @@
1
- export const errMdx = {
1
+ export const errMdx1 = {
2
2
  name: '5:5-5:6',
3
3
  message: 'Unexpected closing slash `/` in tag, expected an open tag first',
4
4
  reason: 'Unexpected closing slash `/` in tag, expected an open tag first',
@@ -0,0 +1,44 @@
1
+ export declare const errMdx2: {
2
+ reason: string;
3
+ line: number;
4
+ column: number;
5
+ position: {
6
+ start: {
7
+ line: number;
8
+ column: number;
9
+ offset: number;
10
+ _index: number;
11
+ _bufferIndex: number;
12
+ };
13
+ end: {
14
+ line: number;
15
+ column: number;
16
+ offset: number;
17
+ _index: number;
18
+ _bufferIndex: number;
19
+ };
20
+ };
21
+ source: string;
22
+ ruleId: string;
23
+ plugin: string;
24
+ id: string;
25
+ pluginCode: string;
26
+ loc: {
27
+ file: string;
28
+ start: {
29
+ line: number;
30
+ column: number;
31
+ offset: number;
32
+ _index: number;
33
+ _bufferIndex: number;
34
+ };
35
+ end: {
36
+ line: number;
37
+ column: number;
38
+ offset: number;
39
+ _index: number;
40
+ _bufferIndex: number;
41
+ };
42
+ };
43
+ frame: string;
44
+ };
@@ -0,0 +1,82 @@
1
+ export const errMdx2 = {
2
+ reason: 'Unexpected closing slash `/` in tag, expected an open tag first',
3
+ line: 23,
4
+ column: 450,
5
+ position: {
6
+ start: {
7
+ line: 23,
8
+ column: 450,
9
+ offset: 1967,
10
+ _index: 0,
11
+ _bufferIndex: 444
12
+ },
13
+ end: {
14
+ line: 23,
15
+ column: 451,
16
+ offset: 1968,
17
+ _index: 0,
18
+ _bufferIndex: 445
19
+ }
20
+ },
21
+ source: 'mdast-util-mdx-jsx',
22
+ ruleId: 'unexpected-closing-slash',
23
+ plugin: '@mdx-js/rollup',
24
+ id: '/home/rom/code/vike/docs/pages/abort/+Page.mdx',
25
+ pluginCode: "import { Link } from '@brillout/docpress'\n" +
26
+ '\n' +
27
+ 'By using <Link href="/render" text={<code>throw render()</code>}></Link> or <Link href="/redirect" text={<code>throw redirect()</code>}></Link> you abort the rendering of the current page and render something else instead.\n' +
28
+ '\n' +
29
+ `<h2 id="throw-redirect-vs-throw-render"><code>{'throw redirect()'}</code>{' VS '}<code>{'throw render()'}</code></h2>\n` +
30
+ '\n' +
31
+ 'While `throw redirect()` changes the URL, `throw render()` preserves it:\n' +
32
+ " - If a user goes to `/admin` and `throw redirect('/login')` is called, then the user will see the new URL `/login` in the browser's address bar.\n" +
33
+ " - If a user goes to `/admin` and `throw render('/login')` is called, then the user keeps seeing the same URL `/admin` in the browser's address bar.\n" +
34
+ '\n' +
35
+ "In general, we recommend using `throw render('/login')` instead of `throw redirect('/login')` as it preserves the URL and, therefore, the user's intention. We further explain this techniue at <Link href=\"/auth#login-flow\" />.\n" +
36
+ '\n' +
37
+ '\n' +
38
+ `<h2 id="debug">{'Debug'}</h2>\n` +
39
+ '\n' +
40
+ "If `throw redirect()` or `throw render()` doesn't work:\n" +
41
+ " - **Make sure `throw redirect()` / `throw render()` isn't intercepted.** \n" +
42
+ " In developement, check your server logs for the following log. If this log is missing then it means that Vike didn't catch the `throw redirect()` / `throw render()` exception: some other code is intercepting it preventing Vike from catching it.\n" +
43
+ ' ```\n' +
44
+ " 10:00:00 AM [vike][request(42)] throw redirect('/some-url') intercepted while\n" +
45
+ ' rendering /some-other-url\n' +
46
+ ' ```\n' +
47
+ ' > Most notably, using `throw redirect()` / `throw render()` inside a UI component usually doesn\'t work because most <Link href="/ui-framework">UI framework</Link> will intercept the execption and thus Vike won\'t be able to catch it. Instead, consider using `throw redirect()` / `throw render()` in a Vike hook such as <Link href="/guard">guard()</Link> or <Link href="/data">data()</Link>, or consider using <Link href="/navigate" />`navigate()`</Link>.\n' +
48
+ ' - **Make sure to use `throw redirect()` / `throw render()` within a Vike hook.** \n' +
49
+ " If you use `throw redirect()` / `throw render()` outside of Vike hooks, for example in some server middleware code then Vike won't be able to intercept it.\n" +
50
+ '\n' +
51
+ "If `throw redirect()` doesn't work:\n" +
52
+ ' - **Make sure to add `pageContext.httpResponse.headers` to the HTTP response.** \n' +
53
+ ' If you\'ve embedded Vike into your server using <Link text={<code>renderPage()</code>} href="/renderPage" />, then insepct whether `pageContext.httpResponse.headers` contains the `Location` header and double check that you\'re correctly adding all the headers defined by `pageContext.httpResponse.headers` to the HTTP response.\n' +
54
+ '\n' +
55
+ '\n' +
56
+ `<h2 id="see-also">{'See also'}</h2>\n` +
57
+ '\n' +
58
+ ' - <Link href="/redirect" />\n' +
59
+ ' - <Link href="/render" />\n' +
60
+ ' - <Link href="/navigate" />\n' +
61
+ '\n' +
62
+ '\n' +
63
+ 'export const headings = [{"headingId":"throw-redirect-vs-throw-render","headingLevel":2,"title":"`throw redirect()` VS `throw render()`"}, {"headingId":"debug","headingLevel":2,"title":"Debug"}, {"headingId":"see-also","headingLevel":2,"title":"See also"}];\n',
64
+ loc: {
65
+ file: '/home/rom/code/vike/docs/pages/abort/+Page.mdx',
66
+ start: {
67
+ line: 23,
68
+ column: 450,
69
+ offset: 1967,
70
+ _index: 0,
71
+ _bufferIndex: 444
72
+ },
73
+ end: {
74
+ line: 23,
75
+ column: 451,
76
+ offset: 1968,
77
+ _index: 0,
78
+ _bufferIndex: 445
79
+ }
80
+ },
81
+ frame: ''
82
+ };