vike 0.4.160 → 0.4.161

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 (121) hide show
  1. package/dist/cjs/node/cli/bin.js +5 -0
  2. package/dist/cjs/node/client/router.js +4 -2
  3. package/dist/cjs/node/plugin/plugins/autoFullBuild.js +2 -2
  4. package/dist/cjs/node/plugin/plugins/buildConfig/fixServerAssets.js +148 -0
  5. package/dist/cjs/node/plugin/plugins/buildConfig.js +42 -15
  6. package/dist/cjs/node/plugin/plugins/commonConfig.js +5 -13
  7. package/dist/cjs/node/plugin/plugins/config/stemUtils.js +1 -1
  8. package/dist/cjs/node/plugin/plugins/distFileNames.js +9 -1
  9. package/dist/cjs/node/plugin/plugins/extractAssetsPlugin.js +7 -2
  10. package/dist/cjs/node/plugin/plugins/importBuild/index.js +4 -7
  11. package/dist/cjs/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/crawlPlusFiles.js +1 -5
  12. package/dist/cjs/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/filesystemRouting.js +28 -46
  13. package/dist/cjs/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/{loadFileConfigEnv.js → loadFileAtConfigTime.js} +5 -5
  14. package/dist/cjs/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/resolveFilePath.js +33 -0
  15. package/dist/cjs/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/resolveImportPath.js +2 -2
  16. package/dist/cjs/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/{transformImports.js → transformFileImports.js} +7 -7
  17. package/dist/cjs/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/transpileAndExecuteFile.js +21 -27
  18. package/dist/cjs/node/plugin/plugins/importUserCode/v1-design/getVikeConfig.js +155 -111
  19. package/dist/cjs/node/plugin/plugins/importUserCode/v1-design/getVirtualFilePageConfigValuesAll.js +2 -1
  20. package/dist/cjs/node/plugin/utils.js +3 -2
  21. package/dist/cjs/node/prerender/runPrerender.js +12 -5
  22. package/dist/cjs/node/runtime/globalContext.js +7 -4
  23. package/dist/cjs/node/runtime/html/injectAssets/getHtmlTags.js +2 -2
  24. package/dist/cjs/node/runtime/html/renderHtml.js +1 -1
  25. package/dist/cjs/node/runtime/html/stream.js +2 -2
  26. package/dist/cjs/node/runtime/renderPage/executeOnRenderHtmlHook.js +2 -2
  27. package/dist/cjs/node/runtime/renderPage/getHttpResponseBody.js +39 -39
  28. package/dist/cjs/node/runtime/renderPage/loadUserFilesServerSide.js +1 -1
  29. package/dist/cjs/node/runtime/renderPage/{logHintForCjsEsmError.js → logErrorHint.js} +81 -43
  30. package/dist/cjs/node/runtime/renderPage/loggerProd.js +3 -3
  31. package/dist/cjs/node/runtime/utils.js +1 -1
  32. package/dist/cjs/shared/page-configs/serialize/parseConfigValuesImported.js +53 -26
  33. package/dist/cjs/shared/route/executeGuardHook.js +3 -2
  34. package/dist/cjs/shared/utils.js +0 -1
  35. package/dist/cjs/utils/assertNodeVersion.js +2 -2
  36. package/dist/cjs/utils/{findUserPackageJsonPath.js → findFile.js} +11 -8
  37. package/dist/cjs/utils/isVersionOrAbove.js +29 -0
  38. package/dist/cjs/utils/nodeEnv.js +23 -1
  39. package/dist/cjs/utils/objectKeys.js +19 -3
  40. package/dist/cjs/utils/projectInfo.js +1 -1
  41. package/dist/cjs/utils/sorter.js +62 -1
  42. package/dist/esm/client/client-routing-runtime/index.d.ts +1 -1
  43. package/dist/esm/client/client-routing-runtime/index.js +1 -1
  44. package/dist/esm/node/cli/bin.js +3 -1
  45. package/dist/esm/node/client/router.d.ts +2 -0
  46. package/dist/esm/node/client/router.js +3 -1
  47. package/dist/esm/node/plugin/plugins/autoFullBuild.js +2 -2
  48. package/dist/esm/node/plugin/plugins/buildConfig/fixServerAssets.d.ts +13 -0
  49. package/dist/esm/node/plugin/plugins/buildConfig/fixServerAssets.js +142 -0
  50. package/dist/esm/node/plugin/plugins/buildConfig.d.ts +2 -0
  51. package/dist/esm/node/plugin/plugins/buildConfig.js +43 -16
  52. package/dist/esm/node/plugin/plugins/commonConfig.js +6 -14
  53. package/dist/esm/node/plugin/plugins/config/stemUtils.js +2 -2
  54. package/dist/esm/node/plugin/plugins/distFileNames.js +9 -1
  55. package/dist/esm/node/plugin/plugins/extractAssetsPlugin.js +8 -3
  56. package/dist/esm/node/plugin/plugins/importBuild/index.d.ts +6 -1
  57. package/dist/esm/node/plugin/plugins/importBuild/index.js +4 -7
  58. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/configDefinitionsBuiltIn.d.ts +2 -0
  59. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/crawlPlusFiles.d.ts +0 -1
  60. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/crawlPlusFiles.js +1 -5
  61. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/filesystemRouting.d.ts +39 -12
  62. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/filesystemRouting.js +29 -47
  63. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/{loadFileConfigEnv.js → loadFileAtConfigTime.js} +4 -4
  64. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/resolveFilePath.d.ts +5 -0
  65. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/resolveFilePath.js +27 -0
  66. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/resolveImportPath.d.ts +1 -1
  67. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/resolveImportPath.js +1 -1
  68. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/{transformImports.d.ts → transformFileImports.d.ts} +2 -2
  69. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/{transformImports.js → transformFileImports.js} +6 -6
  70. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/transpileAndExecuteFile.d.ts +1 -1
  71. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/transpileAndExecuteFile.js +20 -26
  72. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVikeConfig.d.ts +4 -0
  73. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVikeConfig.js +153 -109
  74. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVirtualFilePageConfigValuesAll.js +2 -1
  75. package/dist/esm/node/plugin/utils.d.ts +3 -2
  76. package/dist/esm/node/plugin/utils.js +3 -2
  77. package/dist/esm/node/prerender/runPrerender.js +13 -6
  78. package/dist/esm/node/runtime/globalContext.js +8 -5
  79. package/dist/esm/node/runtime/html/injectAssets/getHtmlTags.js +2 -2
  80. package/dist/esm/node/runtime/html/renderHtml.js +1 -1
  81. package/dist/esm/node/runtime/html/stream.js +2 -2
  82. package/dist/esm/node/runtime/renderPage/executeOnRenderHtmlHook.js +2 -2
  83. package/dist/esm/node/runtime/renderPage/getHttpResponseBody.d.ts +6 -5
  84. package/dist/esm/node/runtime/renderPage/getHttpResponseBody.js +39 -39
  85. package/dist/esm/node/runtime/renderPage/loadUserFilesServerSide.js +1 -1
  86. package/dist/esm/node/runtime/renderPage/logErrorHint.d.ts +8 -0
  87. package/dist/esm/node/runtime/renderPage/{logHintForCjsEsmError.js → logErrorHint.js} +80 -42
  88. package/dist/esm/node/runtime/renderPage/loggerProd.js +3 -3
  89. package/dist/esm/node/runtime/utils.d.ts +1 -1
  90. package/dist/esm/node/runtime/utils.js +1 -1
  91. package/dist/esm/shared/page-configs/Config.d.ts +1 -1
  92. package/dist/esm/shared/page-configs/PageConfig.d.ts +2 -0
  93. package/dist/esm/shared/page-configs/serialize/parseConfigValuesImported.js +53 -26
  94. package/dist/esm/shared/route/executeGuardHook.js +3 -2
  95. package/dist/esm/shared/utils.d.ts +0 -1
  96. package/dist/esm/shared/utils.js +0 -1
  97. package/dist/esm/utils/assertNodeVersion.js +2 -2
  98. package/dist/esm/utils/findFile.d.ts +3 -0
  99. package/dist/esm/utils/findFile.js +21 -0
  100. package/dist/esm/utils/getOutDirs.d.ts +1 -0
  101. package/dist/esm/utils/isVersionOrAbove.d.ts +2 -0
  102. package/dist/esm/utils/isVersionOrAbove.js +26 -0
  103. package/dist/esm/utils/nodeEnv.d.ts +4 -0
  104. package/dist/esm/utils/nodeEnv.js +19 -0
  105. package/dist/esm/utils/objectKeys.d.ts +10 -1
  106. package/dist/esm/utils/objectKeys.js +20 -3
  107. package/dist/esm/utils/projectInfo.d.ts +2 -2
  108. package/dist/esm/utils/projectInfo.js +1 -1
  109. package/dist/esm/utils/sorter.d.ts +59 -0
  110. package/dist/esm/utils/sorter.js +61 -0
  111. package/package.json +1 -1
  112. package/dist/cjs/utils/objectEntries.js +0 -8
  113. package/dist/esm/node/runtime/renderPage/logHintForCjsEsmError.d.ts +0 -13
  114. package/dist/esm/utils/findUserPackageJsonPath.d.ts +0 -2
  115. package/dist/esm/utils/findUserPackageJsonPath.js +0 -18
  116. package/dist/esm/utils/objectEntries.d.ts +0 -4
  117. package/dist/esm/utils/objectEntries.js +0 -5
  118. /package/dist/cjs/node/runtime/renderPage/{logHintForCjsEsmError → logErrorHint}/errors.js +0 -0
  119. /package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVikeConfig/{loadFileConfigEnv.d.ts → loadFileAtConfigTime.d.ts} +0 -0
  120. /package/dist/esm/node/runtime/renderPage/{logHintForCjsEsmError → logErrorHint}/errors.d.ts +0 -0
  121. /package/dist/esm/node/runtime/renderPage/{logHintForCjsEsmError → logErrorHint}/errors.js +0 -0
@@ -1,10 +1,25 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.makeLast = exports.makeFirst = exports.lowerFirst = exports.higherFirst = void 0;
3
+ exports.reverse = exports.makeLast = exports.makeFirst = exports.lowerFirst = exports.higherFirst = void 0;
4
4
  const assert_js_1 = require("./assert.js");
5
5
  // -1 => element1 first (i.e. `indexOf(element1) < indexOf(element2)`)
6
6
  // +1 => element2 first (i.e. `indexOf(element2) < indexOf(element1)`)
7
7
  // 0 => keep original order of element1 and element2
8
+ /**
9
+ * ```js
10
+ * let arr = [
11
+ * { price: 10 },
12
+ * { price: 1000 },
13
+ * { price: 100 }
14
+ * ]
15
+ * arr = arr.sort(higherFirst(el => el.price))
16
+ * isEqual(arr, [
17
+ * { price: 1000 },
18
+ * { price: 100 },
19
+ * { price: 10 }
20
+ * ])
21
+ * ```
22
+ */
8
23
  function higherFirst(getValue) {
9
24
  return (element1, element2) => {
10
25
  const val1 = getValue(element1);
@@ -16,6 +31,21 @@ function higherFirst(getValue) {
16
31
  };
17
32
  }
18
33
  exports.higherFirst = higherFirst;
34
+ /**
35
+ * ```js
36
+ * let arr = [
37
+ * { price: 10 },
38
+ * { price: 1000 },
39
+ * { price: 100 }
40
+ * ]
41
+ * arr = arr.sort(lowerFirst(el => el.price))
42
+ * isEqual(arr, [
43
+ * { price: 10 },
44
+ * { price: 100 },
45
+ * { price: 1000 }
46
+ * ])
47
+ * ```
48
+ */
19
49
  function lowerFirst(getValue) {
20
50
  return (element1, element2) => {
21
51
  const val1 = getValue(element1);
@@ -27,6 +57,19 @@ function lowerFirst(getValue) {
27
57
  };
28
58
  }
29
59
  exports.lowerFirst = lowerFirst;
60
+ /**
61
+ * ```js
62
+ * let arr = [
63
+ * { name: 'iphone', isRocket: false },
64
+ * { name: 'starship', isRocket: true }
65
+ * ]
66
+ * arr = arr.sort(makeFirst(el => el.isRocket))
67
+ * isEqual(arr, [
68
+ * { name: 'starship', isRocket: true },
69
+ * { name: 'iphone', isRocket: false }
70
+ * ])
71
+ * ```
72
+ */
30
73
  function makeFirst(getValue) {
31
74
  return (element1, element2) => {
32
75
  const val1 = getValue(element1);
@@ -46,6 +89,19 @@ function makeFirst(getValue) {
46
89
  };
47
90
  }
48
91
  exports.makeFirst = makeFirst;
92
+ /**
93
+ * ```js
94
+ * let arr = [
95
+ * { name: 'starship', isRocket: true },
96
+ * { name: 'iphone', isRocket: false }
97
+ * ]
98
+ * arr = arr.sort(makeLast(el => el.isRocket))
99
+ * isEqual(arr, [
100
+ * { name: 'iphone', isRocket: false },
101
+ * { name: 'starship', isRocket: true }
102
+ * ])
103
+ * ```
104
+ */
49
105
  function makeLast(getValue) {
50
106
  return makeFirst((element) => {
51
107
  const val = getValue(element);
@@ -58,3 +114,8 @@ function makeLast(getValue) {
58
114
  });
59
115
  }
60
116
  exports.makeLast = makeLast;
117
+ /** Reverse order result. */
118
+ function reverse(sortKey) {
119
+ return (-1 * sortKey);
120
+ }
121
+ exports.reverse = reverse;
@@ -1,6 +1,6 @@
1
1
  export { navigate, reload } from './navigate.js';
2
2
  export { prefetch } from './prefetch.js';
3
- export { PROJECT_VERSION } from './utils.js';
3
+ export { PROJECT_VERSION as version } from './utils.js';
4
4
  import type { PageContextBuiltInClientWithClientRouting } from '../../shared/types.js';
5
5
  /** @deprecated
6
6
  * Replace:
@@ -5,4 +5,4 @@
5
5
  // Use package.json#exports to make the imports isomorphic.
6
6
  export { navigate, reload } from './navigate.js';
7
7
  export { prefetch } from './prefetch.js';
8
- export { PROJECT_VERSION } from './utils.js';
8
+ export { PROJECT_VERSION as version } from './utils.js';
@@ -1,7 +1,8 @@
1
1
  import { cac } from 'cac';
2
2
  import { resolve } from 'path';
3
3
  import { runPrerenderFromCLI, runPrerender_forceExit } from '../prerender/runPrerender.js';
4
- import { projectInfo, assertUsage } from './utils.js';
4
+ import { projectInfo, assertUsage, assertWarning } from './utils.js';
5
+ import pc from '@brillout/picocolors';
5
6
  const cli = cac(projectInfo.projectName);
6
7
  cli
7
8
  .command('prerender', 'Pre-render the HTML of your pages', { allowUnknownOptions: true })
@@ -28,6 +29,7 @@ function assertOptions() {
28
29
  '--outDir',
29
30
  '--configFile'
30
31
  ].includes(option), 'Unknown option: ' + option);
32
+ assertWarning(false, `You set ${pc.cyan(option)}, but passing options to ${pc.cyan('$ vike prerender')} is deprecated: use the config file instead. See https://vike.dev/command-prerender.`, { onlyOnce: true });
31
33
  });
32
34
  }
33
35
  // Listen to unknown commands
@@ -1,4 +1,6 @@
1
1
  export { navigate };
2
2
  export { reload };
3
+ export { prefetch };
3
4
  declare const navigate: never;
4
5
  declare const reload: never;
6
+ declare const prefetch: never;
@@ -1,11 +1,13 @@
1
1
  export { navigate };
2
2
  export { reload };
3
+ export { prefetch };
3
4
  import { assertWarning } from '../../utils/assert.js';
4
5
  // `never` to ensure package.json#exports["./client/router"].types points to type defined by the client-side code
5
6
  const navigate = (() => warnNoEffect('navigate'));
6
7
  const reload = (() => warnNoEffect('reload'));
8
+ const prefetch = (() => warnNoEffect('prefetch'));
7
9
  function warnNoEffect(caller) {
8
- assertWarning(false, `Calling ${caller} on the server-side has no effect`, {
10
+ assertWarning(false, `Calling ${caller}() on the server-side has no effect`, {
9
11
  showStackTrace: true,
10
12
  onlyOnce: false
11
13
  });
@@ -5,7 +5,7 @@ import { runPrerenderFromAutoFullBuild, runPrerender_forceExit } from '../../pre
5
5
  import { getConfigVike } from '../../shared/getConfigVike.js';
6
6
  import { isViteCliCall, getViteConfigFromCli } from '../shared/isViteCliCall.js';
7
7
  import pc from '@brillout/picocolors';
8
- import { logHintForCjsEsmError } from '../../runtime/renderPage/logHintForCjsEsmError.js';
8
+ import { logErrorHint } from '../../runtime/renderPage/logErrorHint.js';
9
9
  let forceExit = false;
10
10
  function autoFullBuild() {
11
11
  let config;
@@ -82,7 +82,7 @@ async function triggerFullBuild(config, configVike, bundle) {
82
82
  }
83
83
  catch (err) {
84
84
  console.error(err);
85
- logHintForCjsEsmError(err);
85
+ logErrorHint(err);
86
86
  process.exit(1);
87
87
  }
88
88
  if (configVike.prerender && !configVike.prerender.disableAutoRun) {
@@ -0,0 +1,13 @@
1
+ export { fixServerAssets };
2
+ export { fixServerAssets_isEnabled };
3
+ import { ViteManifest } from '../../../shared/ViteManifest.js';
4
+ import { OutDirs } from '../../utils.js';
5
+ /**
6
+ * true => use workaround config.build.ssrEmitAssets
7
+ * false => use workaround extractAssets plugin
8
+ *
9
+ * Only used by V1 design.
10
+ */
11
+ declare function fixServerAssets_isEnabled(): boolean;
12
+ /** https://github.com/vikejs/vike/issues/1339 */
13
+ declare function fixServerAssets(outDirs: OutDirs): Promise<ViteManifest>;
@@ -0,0 +1,142 @@
1
+ export { fixServerAssets };
2
+ export { fixServerAssets_isEnabled };
3
+ import fs from 'fs/promises';
4
+ import path from 'path';
5
+ import { existsSync } from 'fs';
6
+ import { assert, pLimit, unique } from '../../utils.js';
7
+ import { isVirtualFileIdPageConfigValuesAll } from '../../../shared/virtual-files/virtualFilePageConfigValuesAll.js';
8
+ import { manifestTempFile } from '../buildConfig.js';
9
+ /**
10
+ * true => use workaround config.build.ssrEmitAssets
11
+ * false => use workaround extractAssets plugin
12
+ *
13
+ * Only used by V1 design.
14
+ */
15
+ function fixServerAssets_isEnabled() {
16
+ // We currently apply the workaround iff V1 design.
17
+ // Shall we allow the user to toggle between the two workarounds? E.g. based on https://vike.dev/includeAssetsImportedByServer.
18
+ return true;
19
+ }
20
+ /** https://github.com/vikejs/vike/issues/1339 */
21
+ async function fixServerAssets(outDirs) {
22
+ const clientManifest = await loadManifest(outDirs.outDirClient);
23
+ const serverManifest = await loadManifest(outDirs.outDirServer);
24
+ const { clientManifestMod, filesToCopy } = addServerAssets(clientManifest, serverManifest);
25
+ await copyAssets(filesToCopy, outDirs);
26
+ return clientManifestMod;
27
+ }
28
+ async function loadManifest(outDir) {
29
+ const manifestFilePath = path.posix.join(outDir, manifestTempFile);
30
+ const manifestFileContent = await fs.readFile(manifestFilePath, 'utf-8');
31
+ assert(manifestFileContent);
32
+ const manifest = JSON.parse(manifestFileContent);
33
+ assert(manifest);
34
+ return manifest;
35
+ }
36
+ async function copyAssets(filesToCopy, { outDirClient, outDirServer }) {
37
+ const assetsDirServer = path.posix.join(outDirServer, 'assets');
38
+ if (!filesToCopy.length)
39
+ return;
40
+ assert(existsSync(assetsDirServer));
41
+ const concurrencyLimit = pLimit(10);
42
+ await Promise.all(filesToCopy.map((file) => concurrencyLimit(() => fs.cp(path.posix.join(outDirServer, file), path.posix.join(outDirClient, file), {
43
+ recursive: true
44
+ }))));
45
+ await fs.rm(assetsDirServer, { recursive: true });
46
+ }
47
+ // Add serverManifest resources to clientManifest
48
+ function addServerAssets(clientManifest, serverManifest) {
49
+ var _a, _b;
50
+ const entriesClient = new Map();
51
+ const entriesServer = new Map();
52
+ for (const [key, entry] of Object.entries(clientManifest)) {
53
+ const pageId = getPageId(key);
54
+ if (!pageId)
55
+ continue;
56
+ const resources = collectResources(entry, clientManifest);
57
+ assert(!entriesClient.has(pageId));
58
+ entriesClient.set(pageId, { key, ...resources });
59
+ }
60
+ for (const [key, entry] of Object.entries(serverManifest)) {
61
+ const pageId = getPageId(key);
62
+ if (!pageId)
63
+ continue;
64
+ const resources = collectResources(entry, serverManifest);
65
+ assert(!entriesServer.has(pageId));
66
+ entriesServer.set(pageId, resources);
67
+ }
68
+ let filesToCopy = [];
69
+ for (const [pageId, entryClient] of entriesClient.entries()) {
70
+ const cssToAdd = [];
71
+ const assetsToAdd = [];
72
+ const entryServer = entriesServer.get(pageId);
73
+ if (entryServer) {
74
+ cssToAdd.push(...entryServer.css
75
+ .filter((cssServer) => !entryClient.css.some((cssClient) => cssServer.hash === cssClient.hash))
76
+ .map((css) => css.src));
77
+ assetsToAdd.push(...entryServer.assets
78
+ .filter((assertServer) => !entryClient.assets.some((assetClient) => assertServer.hash === assetClient.hash))
79
+ .map((asset) => asset.src));
80
+ }
81
+ const { key } = entryClient;
82
+ if (cssToAdd.length) {
83
+ filesToCopy.push(...cssToAdd);
84
+ (_a = clientManifest[key]).css ?? (_a.css = []);
85
+ clientManifest[key].css?.push(...cssToAdd);
86
+ }
87
+ if (assetsToAdd.length) {
88
+ filesToCopy.push(...assetsToAdd);
89
+ (_b = clientManifest[key]).assets ?? (_b.assets = []);
90
+ clientManifest[key].assets?.push(...assetsToAdd);
91
+ }
92
+ }
93
+ const clientManifestMod = clientManifest;
94
+ filesToCopy = unique(filesToCopy);
95
+ return { clientManifestMod, filesToCopy };
96
+ }
97
+ function getPageId(key) {
98
+ // Normalize from:
99
+ // ../../virtual:vike:pageConfigValuesAll:client:/pages/index
100
+ // to:
101
+ // virtual:vike:pageConfigValuesAll:client:/pages/index
102
+ // (This seems to be needed only for vitest tests that use Vite's build() API with an inline config.)
103
+ key = key.substring(key.indexOf('virtual:vike'));
104
+ const result = isVirtualFileIdPageConfigValuesAll(key);
105
+ return result && result.pageId;
106
+ }
107
+ function collectResources(entryRoot, manifest) {
108
+ const css = [];
109
+ const assets = [];
110
+ const entries = new Set([entryRoot]);
111
+ for (const entry of entries) {
112
+ for (const entryImport of entry.imports ?? []) {
113
+ entries.add(manifest[entryImport]);
114
+ }
115
+ const entryCss = entry.css ?? [];
116
+ if (entry.file.endsWith('.css'))
117
+ entryCss.push(entry.file);
118
+ for (const src of entryCss) {
119
+ const hash = getHash(src);
120
+ css.push({ src, hash });
121
+ }
122
+ const entryAssets = entry.assets ?? [];
123
+ for (const src of entryAssets) {
124
+ const hash = getHash(src);
125
+ assets.push({ src, hash });
126
+ }
127
+ }
128
+ return { css, assets };
129
+ }
130
+ // Use the hash of resources to determine whether they are equal. We need this, otherwise we get:
131
+ // ```html
132
+ // <head>
133
+ // <link rel="stylesheet" type="text/css" href="/assets/static/onRenderClient.2j6TxKIB.css">
134
+ // <link rel="stylesheet" type="text/css" href="/assets/static/onRenderHtml.2j6TxKIB.css">
135
+ // </head>
136
+ // ```
137
+ function getHash(src) {
138
+ // src is guarenteed to end with `.[hash][extname]`, see distFileNames.ts
139
+ const hash = src.split('.').at(-2);
140
+ assert(hash);
141
+ return hash;
142
+ }
@@ -1,8 +1,10 @@
1
1
  export { buildConfig };
2
2
  export { assertRollupInput };
3
3
  export { analyzeClientEntries };
4
+ export { manifestTempFile };
4
5
  import type { ResolvedConfig, Plugin } from 'vite';
5
6
  import type { PageConfigBuildTime } from '../../../shared/page-configs/PageConfig.js';
7
+ declare const manifestTempFile = "_temp_manifest.json";
6
8
  declare function buildConfig(): Plugin;
7
9
  declare function analyzeClientEntries(pageConfigs: PageConfigBuildTime[], config: ResolvedConfig): {
8
10
  hasClientRouting: boolean;
@@ -1,8 +1,9 @@
1
1
  export { buildConfig };
2
2
  export { assertRollupInput };
3
3
  export { analyzeClientEntries };
4
- import { assert, resolveOutDir, viteIsSSR, getFilePathAbsolute, addOnBeforeLogHook, removeFileExtention, unique, assertPosixPath, assertUsage, injectRollupInputs, normalizeRollupInput } from '../utils.js';
5
- import { getVikeConfig } from './importUserCode/v1-design/getVikeConfig.js';
4
+ export { manifestTempFile };
5
+ import { assert, resolveOutDir, viteIsSSR, getFilePathAbsolute, addOnBeforeLogHook, removeFileExtention, unique, assertPosixPath, assertUsage, injectRollupInputs, normalizeRollupInput, assertNodeEnvIsNotDev, getOutDirs } from '../utils.js';
6
+ import { getVikeConfig, isV1Design } from './importUserCode/v1-design/getVikeConfig.js';
6
7
  import { getConfigValue } from '../../../shared/page-configs/helpers.js';
7
8
  import { findPageFiles } from '../shared/findPageFiles.js';
8
9
  import { getConfigVike } from '../../shared/getConfigVike.js';
@@ -12,12 +13,16 @@ import { createRequire } from 'module';
12
13
  import { getClientEntryFilePath } from '../../shared/getClientEntryFilePath.js';
13
14
  import fs from 'fs/promises';
14
15
  import path from 'path';
16
+ import { fixServerAssets, fixServerAssets_isEnabled } from './buildConfig/fixServerAssets.js';
17
+ import { set_constant_ASSETS_MAP } from './importBuild/index.js';
15
18
  // @ts-ignore Shimmed by dist-cjs-fixup.js for CJS build.
16
19
  const importMetaUrl = import.meta.url;
17
20
  const require_ = createRequire(importMetaUrl);
18
21
  const manifestTempFile = '_temp_manifest.json';
19
22
  function buildConfig() {
20
- let generateManifest;
23
+ let isServerAssetsFixEnabled;
24
+ let isSsrBuild;
25
+ let outDirs;
21
26
  return {
22
27
  name: 'vike:buildConfig',
23
28
  apply: 'build',
@@ -25,37 +30,56 @@ function buildConfig() {
25
30
  configResolved: {
26
31
  order: 'post',
27
32
  async handler(config) {
33
+ assertNodeEnv();
28
34
  assertRollupInput(config);
29
35
  const entries = await getEntries(config);
30
36
  assert(Object.keys(entries).length > 0);
31
37
  config.build.rollupOptions.input = injectRollupInputs(entries, config);
32
38
  addLogHook();
39
+ outDirs = getOutDirs(config);
40
+ {
41
+ isServerAssetsFixEnabled = fixServerAssets_isEnabled() && (await isV1Design(config, false));
42
+ if (isServerAssetsFixEnabled) {
43
+ // https://github.com/vikejs/vike/issues/1339
44
+ config.build.ssrEmitAssets = true;
45
+ // Required if `ssrEmitAssets: true`, see https://github.com/vitejs/vite/pull/11430#issuecomment-1454800934
46
+ config.build.cssMinify = 'esbuild';
47
+ }
48
+ }
33
49
  }
34
50
  },
35
51
  config(config) {
36
- generateManifest = !viteIsSSR(config);
52
+ assertNodeEnv();
53
+ isSsrBuild = viteIsSSR(config);
37
54
  return {
38
55
  build: {
39
56
  outDir: resolveOutDir(config),
40
- manifest: generateManifest ? manifestTempFile : false,
41
- copyPublicDir: !viteIsSSR(config)
57
+ manifest: manifestTempFile,
58
+ copyPublicDir: !isSsrBuild
42
59
  }
43
60
  };
44
61
  },
62
+ buildStart() {
63
+ assertNodeEnv();
64
+ },
45
65
  async writeBundle(options, bundle) {
46
- const manifestEntry = bundle[manifestTempFile];
47
- /* Fails with @vitejs/plugin-legacy because writeBundle() is called twice during the client build (once for normal client assets and a second time for legacy assets), see reproduction at https://github.com/vikejs/vike/issues/1154
48
- assert(generateManifest === !!manifestEntry)
49
- */
50
- if (manifestEntry) {
51
- const { dir } = options;
52
- assert(dir);
53
- const manifestFilePathOld = path.join(dir, manifestEntry.fileName);
66
+ if (isSsrBuild) {
54
67
  // Ideally we'd move dist/_temp_manifest.json to dist/server/client-assets.json instead of dist/assets.json
55
68
  // - But we can't because there is no guarentee whether dist/server/ is generated before or after dist/client/ (generating dist/server/ after dist/client/ erases dist/server/client-assets.json)
56
69
  // - We'll able to do so once we replace `$ vite build` with `$ vike build`
57
- const manifestFilePathNew = path.join(dir, '..', 'assets.json');
58
- await fs.rename(manifestFilePathOld, manifestFilePathNew);
70
+ const assetsJsonFilePath = path.posix.join(outDirs.outDirRoot, 'assets.json');
71
+ const clientManifestFilePath = path.posix.join(outDirs.outDirClient, manifestTempFile);
72
+ const serverManifestFilePath = path.posix.join(outDirs.outDirServer, manifestTempFile);
73
+ if (!isServerAssetsFixEnabled) {
74
+ await fs.copyFile(clientManifestFilePath, assetsJsonFilePath);
75
+ }
76
+ else {
77
+ const clientManifestMod = await fixServerAssets(outDirs);
78
+ await fs.writeFile(assetsJsonFilePath, JSON.stringify(clientManifestMod, null, 2), 'utf-8');
79
+ }
80
+ await fs.rm(clientManifestFilePath);
81
+ await fs.rm(serverManifestFilePath);
82
+ await set_constant_ASSETS_MAP(options, bundle);
59
83
  }
60
84
  }
61
85
  };
@@ -224,3 +248,6 @@ function assertRollupInput(config) {
224
248
  const htmlInput = htmlInputs[0];
225
249
  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`);
226
250
  }
251
+ function assertNodeEnv() {
252
+ assertNodeEnvIsNotDev('building');
253
+ }
@@ -1,5 +1,5 @@
1
1
  export { commonConfig };
2
- import { assert, assertWarning, findUserPackageJsonPath } from '../utils.js';
2
+ import { assert, assertWarning, findFile } from '../utils.js';
3
3
  import { assertRollupInput } from './buildConfig.js';
4
4
  import { installRequireShim_setUserRootDir } from '@brillout/require-shim';
5
5
  import pc from '@brillout/picocolors';
@@ -26,7 +26,7 @@ function commonConfig() {
26
26
  overrideViteDefaultPort(config);
27
27
  /* TODO: do this after implementing vike.config.js and new setting transformLinkedDependencies (or probably a better name like transpileLinkedDependencies/bundleLinkedDependencies or something else)
28
28
  overrideViteDefaultSsrExternal(config)
29
- */
29
+ //*/
30
30
  workaroundCI(config);
31
31
  assertRollupInput(config);
32
32
  assertResolveAlias(config);
@@ -46,21 +46,13 @@ function overrideViteDefaultPort(config) {
46
46
  (_b = config.preview).port ?? (_b.port = 3000);
47
47
  }
48
48
  /*
49
+ import { version } from 'vite'
49
50
  function overrideViteDefaultSsrExternal(config: ResolvedConfig) {
50
- if (!isViteVersionWithSsrExternalTrue()) return
51
+ if (!isVersionOrAbove(version, '5.0.12')) return
51
52
  // @ts-ignore Not released yet: https://github.com/vitejs/vite/pull/10939/files#diff-5a3d42620df2c6b17e25f440ffdb67683dee7ef57317674d19f41d5f30502310L5
52
53
  config.ssr.external ??= true
53
54
  }
54
- import { version } from 'vite'
55
- function isViteVersionWithSsrExternalTrue(): boolean {
56
- const versionParts = version.split('.').map((s) => parseInt(s, 10)) as [number, number, number]
57
- assert(versionParts.length === 3)
58
- if (versionParts[0] > 5) return true
59
- if (versionParts[1] > 0) return true
60
- if (versionParts[2] >= 12) return true
61
- return false
62
- }
63
- */
55
+ //*/
64
56
  // Workaround GitHub Action failing to access the server
65
57
  function workaroundCI(config) {
66
58
  var _a, _b;
@@ -70,7 +62,7 @@ function workaroundCI(config) {
70
62
  }
71
63
  }
72
64
  function assertEsm(userViteRoot) {
73
- const packageJsonPath = findUserPackageJsonPath(userViteRoot);
65
+ const packageJsonPath = findFile('package.json', userViteRoot);
74
66
  if (!packageJsonPath)
75
67
  return;
76
68
  const packageJson = require_(packageJsonPath);
@@ -1,7 +1,7 @@
1
1
  // Move to standalone package? E.g. https://www.npmjs.com/package/stem
2
2
  export { getStemPackages };
3
3
  import path from 'path';
4
- import { assert, assertUsage, assertWarning, toPosixPath, assertPosixPath, getDependencyRootDir, findUserPackageJsonPath } from '../../utils.js';
4
+ import { assert, assertUsage, assertWarning, toPosixPath, assertPosixPath, getDependencyRootDir, findFile } from '../../utils.js';
5
5
  import { import_ } from '@brillout/import';
6
6
  import { createRequire } from 'module';
7
7
  // @ts-ignore Shimmed by dist-cjs-fixup.js for CJS build.
@@ -48,7 +48,7 @@ async function getStemPackages(userAppRootDir) {
48
48
  return stemPackages;
49
49
  }
50
50
  function findUserRootDir(userAppRootDir) {
51
- const userPkgJsonPath = findUserPackageJsonPath(userAppRootDir);
51
+ const userPkgJsonPath = findFile('package.json', userAppRootDir);
52
52
  assertUsage(userPkgJsonPath, `Couldn't find package.json in any parent directory starting from ${userAppRootDir}`);
53
53
  return toPosixPath(path.dirname(userPkgJsonPath));
54
54
  }
@@ -19,9 +19,17 @@ function distFileNames() {
19
19
  if (!('chunkFileNames' in rollupOutput)) {
20
20
  rollupOutput.chunkFileNames = (chunkInfo) => getChunkFileName(chunkInfo, config);
21
21
  }
22
- if (!('assertUsage' in rollupOutput)) {
22
+ if (!('assetFileNames' in rollupOutput)) {
23
23
  rollupOutput.assetFileNames = (chunkInfo) => getAssetFileName(chunkInfo, config);
24
24
  }
25
+ else {
26
+ // If a user needs this:
27
+ // - assertUsage() that the naming provided by the user ends with `.[hash][extname]`
28
+ // - It's needed for getHash() of fixServerAssets()
29
+ // - Asset URLs should always contain a hash: it's paramount for caching assets.
30
+ // - If rollupOutput.assetFileNames is a function then use a wrapper function to apply the assertUsage()
31
+ assertUsage(false, "Setting config.build.rollupOptions.output.assetFileNames is currently forbidden. (It's possible to support, thus contact a maintainer if you need this.)");
32
+ }
25
33
  });
26
34
  }
27
35
  };
@@ -1,6 +1,6 @@
1
- // Alternative: use `ssrEmitAssets: true`
2
- // - See https://github.com/vitejs/vite/pull/11430
3
- // This plugin makes client-side bundles include the CSS imports living in server-side-only code.
1
+ // Remove this workaround if the other workaround config.build.ssrEmitAssets turns out to be reliable.
2
+ // - Remove this file then revert this commit: https://github.com/vikejs/vike/commit/805a18974f13420a78fcc30fdd676696e405c3ca
3
+ // Workaround to make client-side bundles include the CSS imports living in server-side-only code.
4
4
  // - This is needed for HTML-only pages, and React Server Components.
5
5
  // - We recommend using the debug flag to get an idea of how this plugin works: `$ DEBUG=vike:extractAssets pnpm exec vite build`. Then have a look at `dist/client/manifest.json` and see how `.page.server.js` entries have zero JavaScript but only CSS.
6
6
  // - This appraoch supports import path aliases `vite.config.js#resolve.alias` https://vitejs.dev/config/#resolve-alias
@@ -13,6 +13,8 @@ import { isAsset } from '../shared/isAsset.js';
13
13
  import { getImportStatements } from '../shared/parseEsModule.js';
14
14
  import { removeSourceMap } from '../shared/removeSourceMap.js';
15
15
  import pc from '@brillout/picocolors';
16
+ import { fixServerAssets_isEnabled } from './buildConfig/fixServerAssets.js';
17
+ import { isV1Design } from './importUserCode/v1-design/getVikeConfig.js';
16
18
  const extractAssetsRE = /(\?|&)extractAssets(?:&|$)/;
17
19
  const rawRE = /(\?|&)raw(?:&|$)/;
18
20
  const urlRE = /(\?|&)url(?:&|$)/;
@@ -23,6 +25,7 @@ const debugEnabled = isDebugEnabled(debugNamespace);
23
25
  function extractAssetsPlugin() {
24
26
  let config;
25
27
  let configVike;
28
+ let isServerAssetsFixEnabled;
26
29
  return [
27
30
  // This plugin removes all JavaScript from server-side only code, so that only CSS imports remains. (And also satic files imports e.g. `import logoURL from './logo.svg.js'`).
28
31
  {
@@ -34,6 +37,7 @@ function extractAssetsPlugin() {
34
37
  if (!extractAssetsRE.test(id)) {
35
38
  return;
36
39
  }
40
+ assert(!isServerAssetsFixEnabled);
37
41
  assert(configVike.includeAssetsImportedByServer);
38
42
  assert(!viteIsSSR_options(options));
39
43
  const importStatements = await getImportStatements(src);
@@ -131,6 +135,7 @@ function extractAssetsPlugin() {
131
135
  async configResolved(config_) {
132
136
  configVike = await getConfigVike(config_);
133
137
  config = config_;
138
+ isServerAssetsFixEnabled = fixServerAssets_isEnabled() && (await isV1Design(config, false));
134
139
  },
135
140
  load(id) {
136
141
  if (!isVirtualFileId(id))
@@ -1,3 +1,8 @@
1
1
  export { importBuild };
2
- import type { Plugin } from 'vite';
2
+ export { set_constant_ASSETS_MAP };
3
+ import type { Plugin, Rollup } from 'vite';
4
+ type Bundle = Rollup.OutputBundle;
5
+ type Options = Rollup.NormalizedOutputOptions;
3
6
  declare function importBuild(): Plugin[];
7
+ /** Set the value of the ASSETS_MAP constant inside dist/server/entry.js (or dist/server/index.js) */
8
+ declare function set_constant_ASSETS_MAP(options: Options, bundle: Bundle): Promise<void>;
@@ -1,6 +1,7 @@
1
1
  export { importBuild };
2
+ export { set_constant_ASSETS_MAP };
2
3
  import { serverEntryPlugin, findServerEntry } from '@brillout/vite-plugin-server-entry/plugin.js';
3
- import { assert, getOutDirs, toPosixPath, viteIsSSR } from '../../utils.js';
4
+ import { assert, getOutDirs, toPosixPath } from '../../utils.js';
4
5
  import path from 'path';
5
6
  import { createRequire } from 'module';
6
7
  import { getConfigVike } from '../../../shared/getConfigVike.js';
@@ -21,11 +22,6 @@ function importBuild() {
21
22
  async configResolved(config_) {
22
23
  config = config_;
23
24
  configVike = await getConfigVike(config);
24
- },
25
- async writeBundle(options, bundle) {
26
- if (!viteIsSSR(config))
27
- return;
28
- await replace_ASSETS_MAP(options, bundle);
29
25
  }
30
26
  },
31
27
  ...serverEntryPlugin({
@@ -58,7 +54,8 @@ function getEntryCode(config, configVike) {
58
54
  ].join('\n');
59
55
  return importerCode;
60
56
  }
61
- async function replace_ASSETS_MAP(options, bundle) {
57
+ /** Set the value of the ASSETS_MAP constant inside dist/server/entry.js (or dist/server/index.js) */
58
+ async function set_constant_ASSETS_MAP(options, bundle) {
62
59
  const { dir } = options;
63
60
  assert(dir);
64
61
  // This will probably fail with @vitejs/plugin-legacy
@@ -1,6 +1,7 @@
1
1
  export { configDefinitionsBuiltIn };
2
2
  export { configDefinitionsBuiltInGlobal };
3
3
  export type { ConfigDefinition };
4
+ export type { ConfigDefinitions };
4
5
  export type { ConfigDefinitionInternal };
5
6
  export type { ConfigNameGlobal };
6
7
  export type { ConfigEffect };
@@ -54,6 +55,7 @@ type ConfigDefinitionInternal = Omit<ConfigDefinition, 'env'> & {
54
55
  _userEffectDefinedAt?: DefinedAtFileFullInfo;
55
56
  env: ConfigEnvInternal;
56
57
  };
58
+ type ConfigDefinitions = Record<string, ConfigDefinitionInternal>;
57
59
  type ConfigDefinitionsBuiltIn = Record<ConfigNameBuiltIn, ConfigDefinitionInternal>;
58
60
  declare const configDefinitionsBuiltIn: ConfigDefinitionsBuiltIn;
59
61
  type ConfigNameGlobal = 'onPrerenderStart' | 'onBeforeRoute' | 'prerender' | 'extensions' | 'disableAutoFullBuild' | 'includeAssetsImportedByServer' | 'baseAssets' | 'baseServer' | 'redirects' | 'trailingSlash' | 'disableUrlNormalization';
@@ -1,5 +1,4 @@
1
1
  export { crawlPlusFiles };
2
2
  declare function crawlPlusFiles(userRootDir: string, outDirAbsoluteFilesystem: string, isDev: boolean): Promise<{
3
3
  filePathRelativeToUserRootDir: string;
4
- filePathAbsoluteFilesystem: string;
5
4
  }[]>;