vike 0.4.156 → 0.4.158

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 (70) hide show
  1. package/dist/cjs/node/plugin/plugins/commonConfig.js +21 -2
  2. package/dist/cjs/node/plugin/plugins/distFileNames.js +3 -3
  3. package/dist/cjs/node/plugin/plugins/importBuild/index.js +1 -1
  4. package/dist/cjs/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/crawlPlusFiles.js +3 -1
  5. package/dist/cjs/node/plugin/plugins/importUserCode/v1-design/getVikeConfig.js +2 -0
  6. package/dist/cjs/node/plugin/plugins/importUserCode/v1-design/getVirtualFilePageConfigs.js +2 -0
  7. package/dist/cjs/node/plugin/shared/loggerNotProd/errorWithCodeSnippet/fixture-errors/errMdx.js +1 -1
  8. package/dist/cjs/node/prerender/runPrerender.js +2 -0
  9. package/dist/cjs/node/runtime/html/injectAssets/getHtmlTags.js +2 -2
  10. package/dist/cjs/node/runtime/html/injectAssets/inferHtmlTags.js +1 -1
  11. package/dist/cjs/node/runtime/html/serializePageContextClientSide.js +2 -2
  12. package/dist/cjs/node/runtime/renderPage/getHttpResponseBody.js +8 -1
  13. package/dist/cjs/node/runtime/renderPage/isNewError.js +3 -1
  14. package/dist/cjs/node/runtime/renderPage/renderPageAlreadyRouted.js +3 -3
  15. package/dist/cjs/node/runtime/renderPage.js +8 -10
  16. package/dist/cjs/node/shared/extractAssetsQuery.js +7 -6
  17. package/dist/cjs/shared/addUrlComputedProps.js +22 -2
  18. package/dist/cjs/shared/hooks/executeHook.js +1 -1
  19. package/dist/cjs/shared/misc/isServerSideError.js +4 -0
  20. package/dist/cjs/shared/route/abort.js +19 -8
  21. package/dist/cjs/shared/route/index.js +3 -1
  22. package/dist/cjs/shared/route/resolveRedirects.js +2 -3
  23. package/dist/cjs/utils/assert.js +1 -1
  24. package/dist/cjs/utils/debug.js +2 -1
  25. package/dist/cjs/utils/parseUrl-extras.js +1 -6
  26. package/dist/cjs/utils/parseUrl.js +6 -1
  27. package/dist/cjs/utils/projectInfo.js +1 -1
  28. package/dist/esm/client/client-routing-runtime/getPageContextFromHooks.d.ts +12 -11
  29. package/dist/esm/client/client-routing-runtime/getPageContextFromHooks.js +16 -32
  30. package/dist/esm/client/client-routing-runtime/prefetch.js +1 -1
  31. package/dist/esm/client/client-routing-runtime/renderPageClientSide.js +65 -60
  32. package/dist/esm/client/shared/loadUserFilesClientSide.js +3 -1
  33. package/dist/esm/node/plugin/plugins/commonConfig.js +21 -2
  34. package/dist/esm/node/plugin/plugins/distFileNames.js +3 -3
  35. package/dist/esm/node/plugin/plugins/importBuild/index.js +1 -1
  36. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/crawlPlusFiles.js +3 -1
  37. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVikeConfig.js +2 -0
  38. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVirtualFilePageConfigs.js +2 -0
  39. package/dist/esm/node/plugin/shared/loggerNotProd/errorWithCodeSnippet/fixture-errors/errMdx.js +1 -1
  40. package/dist/esm/node/prerender/runPrerender.js +2 -0
  41. package/dist/esm/node/runtime/html/injectAssets/getHtmlTags.js +2 -2
  42. package/dist/esm/node/runtime/html/injectAssets/inferHtmlTags.js +1 -1
  43. package/dist/esm/node/runtime/html/serializePageContextClientSide.js +2 -2
  44. package/dist/esm/node/runtime/renderPage/getHttpResponseBody.d.ts +1 -0
  45. package/dist/esm/node/runtime/renderPage/getHttpResponseBody.js +8 -1
  46. package/dist/esm/node/runtime/renderPage/isNewError.js +3 -1
  47. package/dist/esm/node/runtime/renderPage/renderPageAlreadyRouted.js +3 -3
  48. package/dist/esm/node/runtime/renderPage.js +8 -10
  49. package/dist/esm/node/shared/extractAssetsQuery.js +7 -6
  50. package/dist/esm/shared/addUrlComputedProps.js +22 -2
  51. package/dist/esm/shared/hooks/executeHook.js +1 -1
  52. package/dist/esm/shared/misc/isServerSideError.d.ts +1 -0
  53. package/dist/esm/shared/misc/isServerSideError.js +1 -0
  54. package/dist/esm/shared/page-configs/Config.d.ts +2 -2
  55. package/dist/esm/shared/route/abort.d.ts +6 -1
  56. package/dist/esm/shared/route/abort.js +20 -9
  57. package/dist/esm/shared/route/index.js +3 -1
  58. package/dist/esm/shared/route/resolveRedirects.js +1 -2
  59. package/dist/esm/utils/assert.js +1 -1
  60. package/dist/esm/utils/debug.js +2 -1
  61. package/dist/esm/utils/parseUrl-extras.d.ts +0 -2
  62. package/dist/esm/utils/parseUrl-extras.js +0 -5
  63. package/dist/esm/utils/parseUrl.d.ts +2 -0
  64. package/dist/esm/utils/parseUrl.js +5 -0
  65. package/dist/esm/utils/projectInfo.d.ts +2 -2
  66. package/dist/esm/utils/projectInfo.js +1 -1
  67. package/package.json +2 -2
  68. package/dist/cjs/shared/misc/isRenderFailure.js +0 -4
  69. package/dist/esm/shared/misc/isRenderFailure.d.ts +0 -1
  70. package/dist/esm/shared/misc/isRenderFailure.js +0 -1
@@ -28,7 +28,10 @@ function commonConfig() {
28
28
  configResolved: {
29
29
  order: 'post',
30
30
  handler(config) {
31
- setDefaultPort(config);
31
+ overrideViteDefaultPort(config);
32
+ /* TODO: do this after implementing vike.config.js and new setting transformLinkedDependencies (or probably a better name like transpileLinkedDependencies/bundleLinkedDependencies or something else)
33
+ overrideViteDefaultSsrExternal(config)
34
+ */
32
35
  workaroundCI(config);
33
36
  (0, buildConfig_js_1.assertRollupInput)(config);
34
37
  (0, assertResolveAlias_js_1.assertResolveAlias)(config);
@@ -39,7 +42,7 @@ function commonConfig() {
39
42
  ];
40
43
  }
41
44
  exports.commonConfig = commonConfig;
42
- function setDefaultPort(config) {
45
+ function overrideViteDefaultPort(config) {
43
46
  var _a, _b;
44
47
  // @ts-ignore
45
48
  config.server ?? (config.server = {});
@@ -48,6 +51,22 @@ function setDefaultPort(config) {
48
51
  config.preview ?? (config.preview = {});
49
52
  (_b = config.preview).port ?? (_b.port = 3000);
50
53
  }
54
+ /*
55
+ function overrideViteDefaultSsrExternal(config: ResolvedConfig) {
56
+ if (!isViteVersionWithSsrExternalTrue()) return
57
+ // @ts-ignore Not released yet: https://github.com/vitejs/vite/pull/10939/files#diff-5a3d42620df2c6b17e25f440ffdb67683dee7ef57317674d19f41d5f30502310L5
58
+ config.ssr.external ??= true
59
+ }
60
+ import { version } from 'vite'
61
+ function isViteVersionWithSsrExternalTrue(): boolean {
62
+ const versionParts = version.split('.').map((s) => parseInt(s, 10)) as [number, number, number]
63
+ assert(versionParts.length === 3)
64
+ if (versionParts[0] > 5) return true
65
+ if (versionParts[1] > 0) return true
66
+ if (versionParts[2] >= 12) return true
67
+ return false
68
+ }
69
+ */
51
70
  // Workaround GitHub Action failing to access the server
52
71
  function workaroundCI(config) {
53
72
  var _a, _b;
@@ -18,13 +18,13 @@ function distFileNames() {
18
18
  const rollupOutputs = getRollupOutputs(config);
19
19
  // We need to support multiple outputs: @vite/plugin-legacy adds an ouput, see https://github.com/vikejs/vike/issues/477#issuecomment-1406434802
20
20
  rollupOutputs.forEach((rollupOutput) => {
21
- if (!rollupOutput.entryFileNames) {
21
+ if (!('entryFileNames' in rollupOutput)) {
22
22
  rollupOutput.entryFileNames = (chunkInfo) => getEntryFileName(chunkInfo, config, true);
23
23
  }
24
- if (!rollupOutput.chunkFileNames) {
24
+ if (!('chunkFileNames' in rollupOutput)) {
25
25
  rollupOutput.chunkFileNames = (chunkInfo) => getChunkFileName(chunkInfo, config);
26
26
  }
27
- if (!rollupOutput.assetFileNames) {
27
+ if (!('assertUsage' in rollupOutput)) {
28
28
  rollupOutput.assetFileNames = (chunkInfo) => getAssetFileName(chunkInfo, config);
29
29
  }
30
30
  });
@@ -33,7 +33,7 @@ function importBuild() {
33
33
  await replace_ASSETS_MAP(options, bundle);
34
34
  }
35
35
  },
36
- (0, plugin_js_1.serverEntryPlugin)({
36
+ ...(0, plugin_js_1.serverEntryPlugin)({
37
37
  getImporterCode: () => {
38
38
  return getEntryCode(config, configVike);
39
39
  },
@@ -145,6 +145,8 @@ async function isGitMissing(userRootDir) {
145
145
  }
146
146
  async function runCmd(cmd, cwd) {
147
147
  const res = await execA(cmd, { cwd });
148
- (0, utils_js_1.assert)(res.stderr === '');
148
+ /* Not always true: https://github.com/vikejs/vike/issues/1440#issuecomment-1892831303
149
+ assert(res.stderr === '')
150
+ */
149
151
  return res.stdout.toString().split('\n').filter(Boolean);
150
152
  }
@@ -841,6 +841,7 @@ function getConfigName(filePath) {
841
841
  }
842
842
  else {
843
843
  const configName = basename.slice(1);
844
+ (0, utils_js_1.assertUsage)(configName !== '', `${filePath} Invalid filename ${fileName}`);
844
845
  return configName;
845
846
  }
846
847
  }
@@ -1033,6 +1034,7 @@ function resolveImportPath(importData, importerFilePath) {
1033
1034
  const importerFilePathAbsolute = importerFilePath.filePathAbsoluteFilesystem;
1034
1035
  (0, utils_js_1.assertPosixPath)(importerFilePathAbsolute);
1035
1036
  const cwd = path_1.default.posix.dirname(importerFilePathAbsolute);
1037
+ // 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
1036
1038
  // filePathAbsoluteFilesystem is expected to be null when importData.importPath is a Vite path alias
1037
1039
  const filePathAbsoluteFilesystem = (0, utils_js_1.requireResolve)(importData.importPath, cwd);
1038
1040
  return filePathAbsoluteFilesystem;
@@ -52,6 +52,8 @@ function getCodePageConfigsSerialized(pageConfigs, isForClientSide, isClientRout
52
52
  (0, utils_js_1.assert)(configValueSource);
53
53
  if (!configValueSource.configEnv.eager)
54
54
  return;
55
+ if (!(0, isRuntimeEnvMatch_js_1.isRuntimeEnvMatch)(configValueSource.configEnv, { isForClientSide, isClientRouting, isEager: true }))
56
+ return;
55
57
  lines.push(...(0, serializeConfigValue_js_1.serializeConfigValueImported)(configValueSource, configName, whitespace, varCounterContainer, importStatements));
56
58
  });
57
59
  lines.push(`${whitespace}],`);
@@ -15,7 +15,7 @@ exports.errMdx = {
15
15
  ruleId: 'unexpected-closing-slash',
16
16
  plugin: '@mdx-js/rollup',
17
17
  id: '/home/rom/code/vike/docs/pages/dynamic-import.page.server.mdx',
18
- pluginCode: 'import { Link, Note } from \'@brillout/docpress\'\n\nPage moved to <Link href="/client-only-components" />.\n\n </Note>\n\n\nexport const headings = [];\n',
18
+ pluginCode: 'import { Link, Note } from \'@brillout/docpress\'\n\nPage moved to <Link href="/ClientOnly" />.\n\n </Note>\n\n\nexport const headings = [];\n',
19
19
  loc: {
20
20
  file: '/home/rom/code/vike/docs/pages/dynamic-import.page.server.mdx',
21
21
  start: { line: 5, column: 5, offset: 109, _index: 6, _bufferIndex: 4 },
@@ -54,6 +54,8 @@ const getVikeConfig_js_1 = require("../plugin/plugins/importUserCode/v1-design/g
54
54
  const logHintForCjsEsmError_js_1 = require("../runtime/renderPage/logHintForCjsEsmError.js");
55
55
  async function runPrerenderFromAPI(options = {}) {
56
56
  await runPrerender(options, 'prerender()');
57
+ // - We purposely propagate the error to the user land, so that the error interrupts the user land. It's also, I guess, a nice-to-have that the user has control over the error.
58
+ // - We don't use logHintForCjsEsmError() because we don't have control over what happens with the error. For example, if the user land purposely swallows the error then the hint shouldn't be logged. Also, it's best if the hint is shown to the user *after* the error, but we cannot do/guarentee that.
57
59
  }
58
60
  exports.runPrerenderFromAPI = runPrerenderFromAPI;
59
61
  async function runPrerenderFromCLI(options) {
@@ -90,12 +90,12 @@ async function getHtmlTags(pageContext, injectToStream, injectFilter) {
90
90
  // See https://github.com/vikejs/vike/pull/1271
91
91
  const positionJavaScriptEntry = (() => {
92
92
  if (pageContext._pageContextPromise) {
93
- (0, utils_js_1.assertWarning)(!injectToStream, "[getHtmlTags()] We recommend against using streaming and a pageContext promise at the same time as partial hydration won't work", { onlyOnce: true });
93
+ (0, utils_js_1.assertWarning)(!injectToStream, "[getHtmlTags()] We recommend against using streaming and a pageContext promise at the same time as progressive hydration won't work", { onlyOnce: true });
94
94
  // If there is a pageContext._pageContextPromise (which is resolved after the stream has ended) then the pageContext JSON data needs to await for it: https://vike.dev/stream#initial-data-after-stream-end
95
95
  return 'HTML_END';
96
96
  }
97
97
  if (injectToStream) {
98
- // If there is a stream then, in order to support partial hydration, inject the JavaScript during the stream after React(/Vue/Solid/...) resolved the first suspense boundary
98
+ // If there is a stream then, in order to support progressive hydration, inject the JavaScript during the stream after React(/Vue/Solid/...) resolved the first suspense boundary
99
99
  return 'STREAM';
100
100
  }
101
101
  else {
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.scriptAttrs = exports.inferEarlyHintLink = exports.inferPreloadTag = exports.inferAssetTag = void 0;
4
4
  const utils_js_1 = require("../../utils.js");
5
- // We can't use `defer` here. With `defer`, the entry script won't start before `</body>` has been parsed, preventing partial hydration during SSR streaming, see https://github.com/vikejs/vike/pull/1271
5
+ // We can't use `defer` here. With `defer`, the entry script won't start before `</body>` has been parsed, preventing progressive hydration during SSR streaming, see https://github.com/vikejs/vike/pull/1271
6
6
  const scriptAttrs = 'type="module" async';
7
7
  exports.scriptAttrs = scriptAttrs;
8
8
  function inferPreloadTag(pageAsset) {
@@ -11,7 +11,7 @@ const addIs404ToPageProps_js_1 = require("../../../shared/addIs404ToPageProps.js
11
11
  const picocolors_1 = __importDefault(require("@brillout/picocolors"));
12
12
  const notSerializable_js_1 = require("../../../shared/notSerializable.js");
13
13
  const pageContextInitIsPassedToClient_js_1 = require("../../../shared/misc/pageContextInitIsPassedToClient.js");
14
- const isRenderFailure_js_1 = require("../../../shared/misc/isRenderFailure.js");
14
+ const isServerSideError_js_1 = require("../../../shared/misc/isServerSideError.js");
15
15
  const PASS_TO_CLIENT = [
16
16
  'abortReason',
17
17
  '_urlRewrite',
@@ -25,7 +25,7 @@ const PASS_TO_CLIENT = [
25
25
  '_pageId',
26
26
  'data' // for data() hook
27
27
  ];
28
- const PASS_TO_CLIENT_ERROR_PAGE = ['pageProps', 'is404', isRenderFailure_js_1.isRenderFailure];
28
+ const PASS_TO_CLIENT_ERROR_PAGE = ['pageProps', 'is404', isServerSideError_js_1.isServerSideError];
29
29
  function serializePageContextClientSide(pageContext) {
30
30
  const passToClient = getPassToClient(pageContext);
31
31
  const pageContextClient = {};
@@ -25,7 +25,7 @@ function getHttpResponseBodyStreamHandlers(htmlRender, renderHook) {
25
25
  },
26
26
  // TODO/v1-release: remove
27
27
  async getNodeStream() {
28
- (0, utils_js_1.assertWarning)(false, '`pageContext.httpResponse.getNodeStream()` is outdated, use `pageContext.httpResponse.pipe()` instead. ' +
28
+ (0, utils_js_1.assertWarning)(false, '`pageContext.httpResponse.getNodeStream()` is outdated, use `pageContext.httpResponse.getReadableNodeStream()` instead. ' +
29
29
  streamDocs, { onlyOnce: true, showStackTrace: true });
30
30
  const nodeStream = await (0, stream_js_1.getStreamReadableNode)(htmlRender);
31
31
  if (nodeStream === null) {
@@ -43,6 +43,13 @@ function getHttpResponseBodyStreamHandlers(htmlRender, renderHook) {
43
43
  }
44
44
  return webStream;
45
45
  },
46
+ async getReadableNodeStream() {
47
+ const nodeStream = await (0, stream_js_1.getStreamReadableNode)(htmlRender);
48
+ if (nodeStream === null) {
49
+ (0, utils_js_1.assertUsage)(false, getErrMsg(htmlRender, renderHook, 'getReadableNodeStream()', getFixMsg('readable', 'node')));
50
+ }
51
+ return nodeStream;
52
+ },
46
53
  getReadableWebStream() {
47
54
  const webStream = (0, stream_js_1.getStreamReadableWeb)(htmlRender);
48
55
  if (webStream === null) {
@@ -7,7 +7,9 @@ const globalObject = (0, utils_js_1.getGlobalObject)('runtime/renderPage/isNewEr
7
7
  });
8
8
  function isNewError(errErrorPage, errNominalPage) {
9
9
  (0, utils_js_1.warnIfErrorIsNotObject)(errErrorPage);
10
- return !(0, utils_js_1.isSameErrorMessage)(errNominalPage, errErrorPage) || !hasAlreadyLogged(errNominalPage);
10
+ return (!(0, utils_js_1.isSameErrorMessage)(errNominalPage, errErrorPage) ||
11
+ // Isn't this redudant/superfluous? I think we can remove this entire file and only use isSameErrorMessage() instead.
12
+ !hasAlreadyLogged(errNominalPage));
11
13
  }
12
14
  exports.isNewError = isNewError;
13
15
  function hasAlreadyLogged(err) {
@@ -22,7 +22,7 @@ const executeGuardHook_js_1 = require("../../../shared/route/executeGuardHook.js
22
22
  const loadPageRoutes_js_1 = require("../../../shared/route/loadPageRoutes.js");
23
23
  const picocolors_1 = __importDefault(require("@brillout/picocolors"));
24
24
  const helpers_js_1 = require("../../../shared/page-configs/helpers.js");
25
- const isRenderFailure_js_1 = require("../../../shared/misc/isRenderFailure.js");
25
+ const isServerSideError_js_1 = require("../../../shared/misc/isServerSideError.js");
26
26
  async function renderPageAlreadyRouted(pageContext) {
27
27
  // pageContext._pageId can either be the:
28
28
  // - ID of the page matching the routing, or the
@@ -49,7 +49,7 @@ async function renderPageAlreadyRouted(pageContext) {
49
49
  }
50
50
  if (pageContext.isClientSideNavigation) {
51
51
  if (isError) {
52
- (0, utils_js_1.objectAssign)(pageContext, { [isRenderFailure_js_1.isRenderFailure]: true });
52
+ (0, utils_js_1.objectAssign)(pageContext, { [isServerSideError_js_1.isServerSideError]: true });
53
53
  }
54
54
  const pageContextSerialized = (0, serializePageContextClientSide_js_1.serializePageContextClientSide)(pageContext);
55
55
  const httpResponse = await (0, createHttpResponseObject_js_1.createHttpResponsePageContextJson)(pageContextSerialized);
@@ -187,5 +187,5 @@ function assertV1Design(pageFilesAll, pageConfigs) {
187
187
  ...pageFilesAll.map((p) => indent + p.filePath)
188
188
  ].join('\n'));
189
189
  }
190
- (0, utils_js_1.assertWarning)(!isDesignOld, 'You are using the old deprecated design, update to the new V1 design, see https://vike.dev/migration/v1-design', { onlyOnce: true });
190
+ (0, utils_js_1.assertWarning)(!isDesignOld, "You are using Vike's deprecated design. Update to the new V1 design, see https://vike.dev/migration/v1-design for how to migrate.", { onlyOnce: true });
191
191
  }
@@ -151,6 +151,7 @@ async function renderPageAlreadyPrepared(pageContextInit, httpRequestId, renderC
151
151
  (0, utils_js_1.assert)(pageContextNominalPageInit);
152
152
  (0, utils_js_1.assert)((0, utils_js_1.hasProp)(pageContextNominalPageInit, 'urlOriginal', 'string'));
153
153
  const pageContextErrorPageInit = await getPageContextErrorPageInit(pageContextInit, errNominalPage, pageContextNominalPageInit, renderContext, httpRequestId);
154
+ // Handle `throw redirect()` and `throw render()` while rendering nominal page
154
155
  if ((0, abort_js_1.isAbortError)(errNominalPage)) {
155
156
  const handled = await handleAbortError(errNominalPage, pageContextsFromRewrite, pageContextInit, pageContextNominalPageInit, httpRequestId, renderContext, pageContextErrorPageInit);
156
157
  if (handled.pageContextReturn) {
@@ -179,6 +180,7 @@ async function renderPageAlreadyPrepared(pageContextInit, httpRequestId, renderC
179
180
  pageContextErrorPage = await (0, renderPageAlreadyRouted_js_1.renderPageAlreadyRouted)(pageContextErrorPageInit);
180
181
  }
181
182
  catch (errErrorPage) {
183
+ // Handle `throw redirect()` and `throw render()` while rendering error page
182
184
  if ((0, abort_js_1.isAbortError)(errErrorPage)) {
183
185
  const handled = await handleAbortError(errErrorPage, pageContextsFromRewrite, pageContextInit, pageContextNominalPageInit, httpRequestId, renderContext, pageContextErrorPageInit);
184
186
  // throw render(abortStatusCode)
@@ -289,7 +291,7 @@ async function getPageContextErrorPageInit(pageContextInit, errNominalPage, page
289
291
  return pageContext;
290
292
  }
291
293
  function getPageContextInitEnhancedSSR(pageContextInit, renderContext, urlRewrite, httpRequestId) {
292
- const { isClientSideNavigation, _urlHandler } = handleUrl(pageContextInit.urlOriginal, urlRewrite);
294
+ const { isClientSideNavigation, _urlHandler } = handlePageContextUrl(pageContextInit.urlOriginal);
293
295
  const pageContextInitEnhanced = (0, renderPageAlreadyRouted_js_1.getPageContextInitEnhanced)(pageContextInit, renderContext, {
294
296
  ssr: {
295
297
  urlRewrite,
@@ -300,18 +302,12 @@ function getPageContextInitEnhancedSSR(pageContextInit, renderContext, urlRewrit
300
302
  (0, utils_js_1.objectAssign)(pageContextInitEnhanced, { _httpRequestId: httpRequestId });
301
303
  return pageContextInitEnhanced;
302
304
  }
303
- function handleUrl(urlOriginal, urlRewrite) {
304
- (0, utils_js_1.assert)(isUrlValid(urlOriginal));
305
- (0, utils_js_1.assert)(urlRewrite === null || isUrlValid(urlRewrite));
305
+ function handlePageContextUrl(urlOriginal) {
306
306
  const { isPageContextRequest } = (0, handlePageContextRequestUrl_js_1.handlePageContextRequestUrl)(urlOriginal);
307
- const pageContextAddendum = {
307
+ return {
308
308
  isClientSideNavigation: isPageContextRequest,
309
309
  _urlHandler: (url) => (0, handlePageContextRequestUrl_js_1.handlePageContextRequestUrl)(url).urlWithoutPageContextRequestSuffix
310
310
  };
311
- return pageContextAddendum;
312
- }
313
- function isUrlValid(url) {
314
- return url.startsWith('/') || url.startsWith('http');
315
311
  }
316
312
  function getRequestId() {
317
313
  const httpRequestId = ++globalObject.httpRequestsCount;
@@ -374,7 +370,9 @@ function getPermanentRedirect(pageContextInit, httpRequestId) {
374
370
  const pageContextHttpResponse = { ...pageContextInit, httpResponse };
375
371
  return pageContextHttpResponse;
376
372
  }
377
- async function handleAbortError(errAbort, pageContextsFromRewrite, pageContextInit, pageContextNominalPageInit, httpRequestId, renderContext, pageContextErrorPageInit) {
373
+ async function handleAbortError(errAbort, pageContextsFromRewrite, pageContextInit,
374
+ // handleAbortError() creates a new pageContext object and we don't merge pageContextNominalPageInit to it: we only use some pageContextNominalPageInit information.
375
+ pageContextNominalPageInit, httpRequestId, renderContext, pageContextErrorPageInit) {
378
376
  (0, abort_js_1.logAbortErrorHandled)(errAbort, (0, globalContext_js_1.getGlobalContext)().isProduction, pageContextNominalPageInit);
379
377
  const pageContextAbort = errAbort._pageContextAbort;
380
378
  let pageContextSerialized;
@@ -6,16 +6,17 @@ const utils_js_1 = require("./utils.js");
6
6
  const query = 'extractAssets';
7
7
  function extractAssetsAddQuery(id) {
8
8
  const fileExtension = (0, utils_js_1.getFileExtension)(id);
9
- (0, utils_js_1.assert)(fileExtension || id.includes('virtual:vike:'));
10
- if (!fileExtension)
9
+ if (!fileExtension || id.includes('virtual:vike:')) {
11
10
  return `${id}?${query}`;
12
- if (id.includes('?')) {
13
- id = id.replace('?', `?${query}&`);
14
11
  }
15
12
  else {
16
- id = `${id}?${query}&lang.${fileExtension}`;
13
+ if (!id.includes('?')) {
14
+ return `${id}?${query}&lang.${fileExtension}`;
15
+ }
16
+ else {
17
+ return id.replace('?', `?${query}&`);
18
+ }
17
19
  }
18
- return id;
19
20
  }
20
21
  exports.extractAssetsAddQuery = extractAssetsAddQuery;
21
22
  function extractAssetsRemoveQuery(id) {
@@ -7,7 +7,7 @@ function addUrlComputedProps(pageContext, enumerable = true) {
7
7
  (0, utils_js_1.assert)(pageContext.urlOriginal);
8
8
  if ('urlPathname' in pageContext) {
9
9
  (0, utils_js_1.assert)(typeof pageContext.urlPathname === 'string');
10
- /* If this assert() fails then it's most likely because Object.assign() was used instead of objectAssign(), i.e.:
10
+ /* If the following assert() fails then it's most likely because Object.assign() was used instead of objectAssign(), i.e.:
11
11
  ```js
12
12
  // Add property getters such as pageContext.urlPathname to pageContext
13
13
  addUrlComputedProps(pageContext)
@@ -49,8 +49,28 @@ function getUrlParsed(pageContext) {
49
49
  if (!urlHandler) {
50
50
  urlHandler = (url) => url;
51
51
  }
52
- let urlResolved = pageContext._urlRewrite ?? pageContext.urlLogical ?? pageContext.urlOriginal;
52
+ // Example of i18n app using `throw render()`:
53
+ // 1. User goes to '/fr-FR/admin'.
54
+ // 2. The first onBeforeRoute() call accesses pageContext.urlPathname (its value is '/fr-FR/admin': the pathname of pageContext.urlOriginal, since both pageContext.urlLogical and pageContext._urlRewrite are undefined) and sets pageContext.urlLogical to '/admin'.
55
+ // 3. A guard() hooks accesses pageContext.urlPathname (its value is '/admin': the pathname of pageContext.urlLogical) and calls `throw render('/fr-FR/login')`
56
+ // 4. Vike create a new pageContext object (pageContext.urlLogical is erased) and sets pageContext._urlRewrite to '/fr-FR/login'. (While pageContext.urlOriginal is still '/fr-FR/admin'.)
57
+ // 5. The second onBeforeRoute() call accesses pageContext.urlPathname (its value is '/fr-FR/login': the pathname of pageContext._urlRewrite, since pageContext.urlLogical is undefined) and sets pageContext.urlLogical to '/login'.
58
+ // 6. The value of pageContext.urlPathname is now '/login': the pathname of `pageContext.urlLogical`. (While pageContext.urlOriginal is still '/fr-FR/admin'.)
59
+ // Reproduction: https://github.com/vikejs/vike/discussions/1436#discussioncomment-8142023
60
+ let urlResolved =
61
+ // Set by onBeforeRoute()
62
+ pageContext.urlLogical ??
63
+ // Set by `throw render()`
64
+ pageContext._urlRewrite ??
65
+ // Set by renderPage()
66
+ pageContext.urlOriginal;
53
67
  urlResolved = urlHandler(urlResolved);
68
+ /*
69
+ console.log('pageContext.urlLogical', pageContext.urlLogical)
70
+ console.log('pageContext._urlRewrite', pageContext._urlRewrite)
71
+ console.log('pageContext.urlOriginal', pageContext.urlOriginal)
72
+ console.log()
73
+ //*/
54
74
  const baseServer = pageContext._baseServer;
55
75
  (0, utils_js_1.assert)(urlResolved && typeof urlResolved === 'string');
56
76
  (0, utils_js_1.assert)(baseServer.startsWith('/'));
@@ -6,7 +6,7 @@ const getGlobalObject_js_1 = require("../../utils/getGlobalObject.js");
6
6
  const humanizeTime_js_1 = require("../../utils/humanizeTime.js");
7
7
  const isObject_js_1 = require("../../utils/isObject.js");
8
8
  const globalObject = (0, getGlobalObject_js_1.getGlobalObject)('utils/executeHook.ts', {
9
- userHookErrors: new Map()
9
+ userHookErrors: new WeakMap()
10
10
  });
11
11
  function isUserHookError(err) {
12
12
  if (!(0, isObject_js_1.isObject)(err))
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isServerSideError = void 0;
4
+ exports.isServerSideError = '_isServerSideError';
@@ -16,6 +16,7 @@ const picocolors_1 = __importDefault(require("@brillout/picocolors"));
16
16
  */
17
17
  function redirect(url, statusCode) {
18
18
  const abortCaller = 'throw redirect()';
19
+ assertUrl(url, abortCaller, true);
19
20
  const args = [JSON.stringify(url)];
20
21
  if (!statusCode) {
21
22
  statusCode = 302;
@@ -36,16 +37,16 @@ function redirect(url, statusCode) {
36
37
  return AbortRender(pageContextAbort);
37
38
  }
38
39
  exports.redirect = redirect;
39
- function render(value, abortReason) {
40
- const args = [typeof value === 'number' ? String(value) : JSON.stringify(value)];
40
+ function render(urlOrStatusCode, abortReason) {
41
+ const args = [typeof urlOrStatusCode === 'number' ? String(urlOrStatusCode) : JSON.stringify(urlOrStatusCode)];
41
42
  if (abortReason !== undefined)
42
43
  args.push((0, utils_js_1.truncateString)(JSON.stringify(abortReason), 30));
43
44
  const abortCaller = 'throw render()';
44
45
  const abortCall = `render(${args.join(', ')})`;
45
- return render_(value, abortReason, abortCall, abortCaller);
46
+ return render_(urlOrStatusCode, abortReason, abortCall, abortCaller);
46
47
  }
47
48
  exports.render = render;
48
- function render_(value, abortReason, abortCall, abortCaller, pageContextAddendum) {
49
+ function render_(urlOrStatusCode, abortReason, abortCall, abortCaller, pageContextAddendum) {
49
50
  const pageContextAbort = {
50
51
  abortReason,
51
52
  _abortCaller: abortCaller,
@@ -55,16 +56,17 @@ function render_(value, abortReason, abortCall, abortCaller, pageContextAddendum
55
56
  (0, utils_js_1.assert)(pageContextAddendum._isLegacyRenderErrorPage === true);
56
57
  (0, utils_js_1.objectAssign)(pageContextAbort, pageContextAddendum);
57
58
  }
58
- if (typeof value === 'string') {
59
- const url = value;
59
+ if (typeof urlOrStatusCode === 'string') {
60
+ const url = urlOrStatusCode;
61
+ assertUrl(url, abortCaller);
60
62
  (0, utils_js_1.objectAssign)(pageContextAbort, {
61
63
  _urlRewrite: url
62
64
  });
63
65
  return AbortRender(pageContextAbort);
64
66
  }
65
67
  else {
66
- const abortStatusCode = value;
67
- assertStatusCode(value, [401, 403, 404, 410, 429, 500, 503], 'render');
68
+ const abortStatusCode = urlOrStatusCode;
69
+ assertStatusCode(urlOrStatusCode, [401, 403, 404, 410, 429, 500, 503], 'render');
68
70
  (0, utils_js_1.objectAssign)(pageContextAbort, {
69
71
  abortStatusCode,
70
72
  is404: abortStatusCode === 404
@@ -170,3 +172,12 @@ function assertNoInfiniteAbortLoop(rewriteCount, redirectCount) {
170
172
  (0, utils_js_1.assertUsage)(rewriteCount + redirectCount <= 7, `Maximum chain length of 7 ${abortCalls} exceeded. Did you define an infinite loop of ${abortCalls}?`);
171
173
  }
172
174
  exports.assertNoInfiniteAbortLoop = assertNoInfiniteAbortLoop;
175
+ function assertUrl(url, abortCaller, allowAbsoluteUrl) {
176
+ (0, utils_js_1.assertUsage)(url.startsWith('/') || (allowAbsoluteUrl && (0, utils_js_1.isUriWithProtocol)(url)), [
177
+ `Invalid URL ${picocolors_1.default.cyan(url)} passed to ${picocolors_1.default.cyan(abortCaller)}:`,
178
+ `the URL should start with ${picocolors_1.default.cyan('/')}`,
179
+ allowAbsoluteUrl && `or a valid protocol (${picocolors_1.default.cyan('https:')}, ${picocolors_1.default.cyan('ipfs:')}, ...)`
180
+ ]
181
+ .filter(Boolean)
182
+ .join(' '));
183
+ }
@@ -86,9 +86,11 @@ async function route(pageContextForRoute) {
86
86
  (0, utils_js_1.assert)(false);
87
87
  }));
88
88
  (0, resolvePrecedence_js_1.resolvePrecendence)(routeMatches);
89
- const winner = routeMatches[0];
89
+ const winner = routeMatches[0] ?? null;
90
90
  (0, debug_js_1.debug)(`Route matches for URL ${picocolors_1.default.cyan(urlPathname)} (in precedence order):`, routeMatches);
91
91
  (0, utils_js_1.objectAssign)(pageContextFromRoute, { _debugRouteMatches: routeMatches });
92
+ // For vite-plugin-vercel https://github.com/magne4000/vite-plugin-vercel/blob/main/packages/vike-integration/vike.ts#L173
93
+ (0, utils_js_1.objectAssign)(pageContextFromRoute, { _routeMatch: winner });
92
94
  if (!winner) {
93
95
  (0, utils_js_1.objectAssign)(pageContextFromRoute, {
94
96
  _pageId: null,
@@ -5,7 +5,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.resolveRouteStringRedirect = exports.resolveRedirects = void 0;
7
7
  const assertIsNotBrowser_js_1 = require("../../utils/assertIsNotBrowser.js");
8
- const parseUrl_extras_js_1 = require("../../utils/parseUrl-extras.js");
9
8
  const utils_js_1 = require("../utils.js");
10
9
  const resolveUrlPathname_js_1 = require("./resolveUrlPathname.js");
11
10
  const resolveRouteString_js_1 = require("./resolveRouteString.js");
@@ -26,7 +25,7 @@ function resolveRouteStringRedirect(urlSource, urlTarget, urlPathname) {
26
25
  (0, resolveRouteString_js_1.assertRouteString)(urlSource, `${configSrc} Invalid`);
27
26
  (0, utils_js_1.assertUsage)(urlTarget.startsWith('/') ||
28
27
  // Is allowing any protocol a safety issue? https://github.com/vikejs/vike/pull/1292#issuecomment-1828043917
29
- (0, parseUrl_extras_js_1.isUriWithProtocol)(urlTarget) ||
28
+ (0, utils_js_1.isUriWithProtocol)(urlTarget) ||
30
29
  urlTarget === '*', `${configSrc} Invalid redirection target URL ${picocolors_1.default.cyan(urlTarget)}: the target URL should start with ${picocolors_1.default.cyan('/')}, a valid protocol (${picocolors_1.default.cyan('https:')}, ${picocolors_1.default.cyan('http:')}, ${picocolors_1.default.cyan('mailto:')}, ${picocolors_1.default.cyan('ipfs:')}, ${picocolors_1.default.cyan('magnet:')}, ...), or be ${picocolors_1.default.cyan('*')}`);
31
30
  assertParams(urlSource, urlTarget);
32
31
  const match = (0, resolveRouteString_js_1.resolveRouteString)(urlSource, urlPathname);
@@ -35,7 +34,7 @@ function resolveRouteStringRedirect(urlSource, urlTarget, urlPathname) {
35
34
  const urlResolved = (0, resolveUrlPathname_js_1.resolveUrlPathname)(urlTarget, match.routeParams);
36
35
  if (urlResolved === urlPathname)
37
36
  return null;
38
- (0, utils_js_1.assert)(urlResolved.startsWith('/') || (0, parseUrl_extras_js_1.isUriWithProtocol)(urlResolved));
37
+ (0, utils_js_1.assert)(urlResolved.startsWith('/') || (0, utils_js_1.isUriWithProtocol)(urlResolved));
39
38
  return urlResolved;
40
39
  }
41
40
  exports.resolveRouteStringRedirect = resolveRouteStringRedirect;
@@ -38,7 +38,7 @@ function assert(condition, debugInfo) {
38
38
  const link = `${projectInfo_js_1.projectInfo.githubRepository}/issues/new`;
39
39
  let errMsg = [
40
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).`,
41
+ `Go to ${picocolors_1.default.blue(link)} and copy-paste this error. A maintainer will fix the bug (usually under 24 hours).`,
42
42
  debugStr
43
43
  ]
44
44
  .filter(Boolean)
@@ -58,7 +58,8 @@ function isDebugEnabled(flag) {
58
58
  DEBUG = process.env.DEBUG;
59
59
  }
60
60
  catch { }
61
- return DEBUG?.includes(flag) ?? false;
61
+ const isEnabled = DEBUG?.includes(flag) ?? false;
62
+ return isEnabled;
62
63
  }
63
64
  exports.isDebugEnabled = isDebugEnabled;
64
65
  function formatMsg(info, options, padding, position) {
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isUriWithProtocol = exports.addUrlOrigin = exports.removeUrlOrigin = exports.modifyUrlPathname = exports.removeBaseServer = exports.normalizeUrlPathname = exports.isBaseAssets = exports.prependBase = void 0;
3
+ exports.addUrlOrigin = exports.removeUrlOrigin = exports.modifyUrlPathname = exports.removeBaseServer = exports.normalizeUrlPathname = exports.isBaseAssets = exports.prependBase = void 0;
4
4
  const parseUrl_js_1 = require("./parseUrl.js");
5
5
  const assert_js_1 = require("./assert.js");
6
6
  const slice_js_1 = require("./slice.js");
@@ -103,8 +103,3 @@ function addUrlOrigin(url, origin) {
103
103
  return urlModified;
104
104
  }
105
105
  exports.addUrlOrigin = addUrlOrigin;
106
- function isUriWithProtocol(uri) {
107
- // https://en.wikipedia.org/wiki/List_of_URI_schemes
108
- return /^[a-z0-9][a-z0-9\.\+\-]*:/i.test(uri);
109
- }
110
- exports.isUriWithProtocol = isUriWithProtocol;
@@ -6,7 +6,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
6
6
  return (mod && mod.__esModule) ? mod : { "default": mod };
7
7
  };
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.createUrlFromComponents = exports.assertUrlComponents = exports.isBaseServer = exports.assertUsageUrl = exports.isParsable = exports.parseUrl = void 0;
9
+ exports.isUriWithProtocol = exports.createUrlFromComponents = exports.assertUrlComponents = exports.isBaseServer = exports.assertUsageUrl = exports.isParsable = exports.parseUrl = void 0;
10
10
  const slice_js_1 = require("./slice.js");
11
11
  const assert_js_1 = require("./assert.js");
12
12
  const picocolors_1 = __importDefault(require("@brillout/picocolors"));
@@ -232,3 +232,8 @@ function createUrlFromComponents(origin, pathname, searchOriginal, hashOriginal)
232
232
  return urlRecreated;
233
233
  }
234
234
  exports.createUrlFromComponents = createUrlFromComponents;
235
+ function isUriWithProtocol(uri) {
236
+ // https://en.wikipedia.org/wiki/List_of_URI_schemes
237
+ return /^[a-z0-9][a-z0-9\.\+\-]*:/i.test(uri);
238
+ }
239
+ exports.isUriWithProtocol = isUriWithProtocol;
@@ -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.156';
5
+ const PROJECT_VERSION = '0.4.158';
6
6
  exports.PROJECT_VERSION = PROJECT_VERSION;
7
7
  const projectInfo = {
8
8
  projectName: 'Vike',
@@ -1,7 +1,6 @@
1
1
  export { getPageContextFromHooks_isHydration };
2
2
  export { getPageContextFromHooks_isNotHydration };
3
3
  export { getPageContextFromHooks_serialized };
4
- export { isServerSideRouted };
5
4
  import type { PageContextExports, PageFile } from '../../shared/getPageFiles.js';
6
5
  import type { PageConfigRuntime } from '../../shared/page-configs/PageConfig.js';
7
6
  type PageContext = {
@@ -22,13 +21,15 @@ declare function getPageContextFromHooks_isHydration(pageContext: PageContextSer
22
21
  }>;
23
22
  declare function getPageContextFromHooks_isNotHydration(pageContext: {
24
23
  _pageId: string;
25
- } & PageContext & PageContextExports, isErrorPage: boolean): Promise<(Record<string, unknown> & Record<"_pageId", string> & Record<"is404", boolean> & Record<"pageProps", Record<string, unknown>> & {
26
- _hasPageContextFromServer: true;
27
- _hasPageContextFromClient: false;
28
- }) | ({
29
- isHydration: false;
30
- _hasPageContextFromClient: boolean;
31
- } & {
32
- _hasPageContextFromServer: boolean;
33
- })>;
34
- declare function isServerSideRouted(err: unknown): boolean;
24
+ } & PageContext & PageContextExports, isErrorPage: boolean): Promise<{
25
+ is404ServerSideRouted: boolean;
26
+ pageContextFromHooks?: undefined;
27
+ } | {
28
+ pageContextFromHooks: {
29
+ isHydration: false;
30
+ _hasPageContextFromClient: boolean;
31
+ } & {
32
+ _hasPageContextFromServer: boolean;
33
+ };
34
+ is404ServerSideRouted?: undefined;
35
+ }>;