vike 0.4.162 → 0.4.163-commit-2305d5b

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 (41) hide show
  1. package/dist/cjs/node/plugin/plugins/autoFullBuild.js +7 -4
  2. package/dist/cjs/node/plugin/plugins/buildConfig.js +21 -17
  3. package/dist/cjs/node/plugin/plugins/commonConfig.js +8 -2
  4. package/dist/cjs/node/plugin/plugins/importBuild/index.js +2 -3
  5. package/dist/cjs/node/plugin/plugins/importUserCode/v1-design/getVikeConfig.js +6 -1
  6. package/dist/cjs/node/runtime/globalContext/loadImportBuild.js +3 -3
  7. package/dist/cjs/node/runtime/globalContext.js +47 -6
  8. package/dist/cjs/node/runtime/index-common.js +4 -1
  9. package/dist/cjs/node/runtime/renderPage/getPageAssets/getManifestEntry.js +19 -19
  10. package/dist/cjs/node/runtime/renderPage/getPageAssets/retrieveAssetsProd.js +12 -12
  11. package/dist/cjs/node/runtime/renderPage/getPageAssets.js +5 -5
  12. package/dist/cjs/node/runtime/renderPage/logErrorHint.js +9 -13
  13. package/dist/cjs/node/runtime/renderPage.js +3 -0
  14. package/dist/cjs/shared/page-configs/serialize/serializeConfigValue.js +4 -11
  15. package/dist/cjs/utils/projectInfo.js +1 -1
  16. package/dist/esm/client/client-routing-runtime/renderPageClientSide.js +20 -14
  17. package/dist/esm/client/shared/getPageContextProxyForUser.js +19 -2
  18. package/dist/esm/node/plugin/plugins/autoFullBuild.js +7 -4
  19. package/dist/esm/node/plugin/plugins/buildConfig.js +21 -17
  20. package/dist/esm/node/plugin/plugins/commonConfig.js +9 -3
  21. package/dist/esm/node/plugin/plugins/importBuild/index.js +2 -3
  22. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVikeConfig.d.ts +3 -3
  23. package/dist/esm/node/plugin/plugins/importUserCode/v1-design/getVikeConfig.js +6 -1
  24. package/dist/esm/node/runtime/globalContext/loadImportBuild.d.ts +2 -2
  25. package/dist/esm/node/runtime/globalContext/loadImportBuild.js +3 -3
  26. package/dist/esm/node/runtime/globalContext.d.ts +11 -2
  27. package/dist/esm/node/runtime/globalContext.js +49 -6
  28. package/dist/esm/node/runtime/index-common.d.ts +1 -0
  29. package/dist/esm/node/runtime/index-common.js +1 -0
  30. package/dist/esm/node/runtime/renderPage/getPageAssets/getManifestEntry.d.ts +1 -1
  31. package/dist/esm/node/runtime/renderPage/getPageAssets/getManifestEntry.js +19 -19
  32. package/dist/esm/node/runtime/renderPage/getPageAssets/retrieveAssetsProd.d.ts +1 -1
  33. package/dist/esm/node/runtime/renderPage/getPageAssets/retrieveAssetsProd.js +12 -12
  34. package/dist/esm/node/runtime/renderPage/getPageAssets.js +5 -5
  35. package/dist/esm/node/runtime/renderPage/logErrorHint.js +10 -11
  36. package/dist/esm/node/runtime/renderPage.js +3 -0
  37. package/dist/esm/shared/page-configs/PageConfig.d.ts +1 -0
  38. package/dist/esm/shared/page-configs/serialize/serializeConfigValue.js +5 -9
  39. package/dist/esm/utils/projectInfo.d.ts +2 -2
  40. package/dist/esm/utils/projectInfo.js +1 -1
  41. package/package.json +2 -1
@@ -308,35 +308,41 @@ async function renderPageClientSide(renderArgs) {
308
308
  }
309
309
  }
310
310
  };
311
- // We use globalObject.renderPromise in order to ensure that there is never two concurrent onRenderClient() calls
312
- if (globalObject.renderPromise) {
311
+ // We use globalObject.onRenderClientPromise in order to ensure that there is never two concurrent onRenderClient() calls
312
+ if (globalObject.onRenderClientPromise) {
313
313
  // Make sure that the previous render has finished
314
- await globalObject.renderPromise;
315
- assert(globalObject.renderPromise === undefined);
314
+ await globalObject.onRenderClientPromise;
315
+ assert(globalObject.onRenderClientPromise === undefined);
316
316
  if (isRenderOutdated())
317
317
  return;
318
318
  }
319
319
  changeUrl(urlOriginal, overwriteLastHistoryEntry);
320
320
  globalObject.previousPageContext = pageContext;
321
- assert(globalObject.renderPromise === undefined);
322
- globalObject.renderPromise = (async () => {
321
+ assert(globalObject.onRenderClientPromise === undefined);
322
+ globalObject.onRenderClientPromise = (async () => {
323
+ let onRenderClientError;
323
324
  try {
324
325
  await executeOnRenderClientHook(pageContext, true);
325
326
  }
326
327
  catch (err) {
327
- await onError(err);
328
- return;
328
+ onRenderClientError = err;
329
329
  }
330
- addLinkPrefetchHandlers(pageContext);
331
- globalObject.renderPromise = undefined;
330
+ globalObject.onRenderClientPromise = undefined;
331
+ return onRenderClientError;
332
332
  })();
333
- await globalObject.renderPromise;
334
- assert(globalObject.renderPromise === undefined);
333
+ const onRenderClientError = await globalObject.onRenderClientPromise;
334
+ assert(globalObject.onRenderClientPromise === undefined);
335
+ if (onRenderClientError) {
336
+ await onError(onRenderClientError);
337
+ if (!isErrorPage)
338
+ return;
339
+ }
335
340
  /* We don't abort in order to ensure that onHydrationEnd() is called: we abort only after onHydrationEnd() is called.
336
341
  if (isRenderOutdated(true)) return
337
342
  */
343
+ addLinkPrefetchHandlers(pageContext);
338
344
  // onHydrationEnd()
339
- if (isHydrationRender) {
345
+ if (isHydrationRender && !onRenderClientError) {
340
346
  assertHook(pageContext, 'onHydrationEnd');
341
347
  const hook = getHook(pageContext, 'onHydrationEnd');
342
348
  if (hook) {
@@ -353,7 +359,7 @@ async function renderPageClientSide(renderArgs) {
353
359
  return;
354
360
  }
355
361
  }
356
- // We abort *after* onHydrationEnd() is called
362
+ // We purposely abort *after* onHydrationEnd() is called (see comment above).
357
363
  if (isRenderOutdated(true))
358
364
  return;
359
365
  // onPageTransitionEnd()
@@ -1,5 +1,5 @@
1
1
  export { getPageContextProxyForUser };
2
- import { assert, assertUsage, getGlobalObject } from '../server-routing-runtime/utils.js';
2
+ import { assert, assertUsage, assertWarning, getGlobalObject } from '../server-routing-runtime/utils.js';
3
3
  import { notSerializable } from '../../shared/notSerializable.js';
4
4
  const globalObject = getGlobalObject('getPageContextProxyForUser.ts', {});
5
5
  /**
@@ -30,6 +30,10 @@ function assertIsDefined(pageContext, prop) {
30
30
  return;
31
31
  if (isExpected(prop))
32
32
  return;
33
+ // - If no pageContext was fetchd from the server, then adding props to passToClient is useless.
34
+ // - Showing a warning, even though no pageContext was fetched from the server, is actually erroneous as the client runtime cannot deduce the passToClient list.
35
+ if (!pageContext._hasPageContextFromServer)
36
+ return;
33
37
  const propName = JSON.stringify(prop);
34
38
  /* This handling would be the clearest but, unfortunately, it's fundamentally problematic:
35
39
  * - It would force the pageContext value consumer to be synchronized with the pageContext value provider. For example, if vike-react wants to conditionally do something dependening on wehther some optional pageContext value was provided by some optional vike-react-* integration package.
@@ -37,7 +41,7 @@ function assertIsDefined(pageContext, prop) {
37
41
  const errMsg = `pageContext[${propName}] is \`undefined\` on the client-side. If it's defined on the server-side then add ${propName} to passToClient (https://vike.dev/passToClient), otherwise make sure your client-side hooks always define it (e.g. set it to \`null\` instead of \`undefined\`).`
38
42
  assertUsage(false, errMsg)
39
43
  */
40
- if (pageContext._hasPageContextFromServer && !pageContext._hasPageContextFromClient) {
44
+ if (!pageContext._hasPageContextFromClient) {
41
45
  // We can safely assume that the property is missing in passToClient, because the server-side defines all passToClient properties even if they have an undefined value:
42
46
  // ```
43
47
  // <script id="vike_pageContext" type="application/json">{"_pageId":"/pages/admin","user":"!undefined","pageProps":"!undefined","title":"!undefined","abortReason":"!undefined","_urlRewrite":null}</script>
@@ -47,6 +51,19 @@ function assertIsDefined(pageContext, prop) {
47
51
  }
48
52
  else {
49
53
  // Do nothing, not even a warning, because we don't know whether the user expects that the pageContext value can be undefined. (E.g. a pageContext value that is defined by an optional hook.)
54
+ // TODO/next-major-release make it an assertUsage()
55
+ assertWarning(false, [
56
+ `pageContext[${propName}] isn't defined on the client-side:`,
57
+ `1. if it's defined by the server-side then add ${propName} to passToClient (https://vike.dev/passToClient), or`,
58
+ `2. if it's expected that it may not be defined:`,
59
+ ' ```js',
60
+ ' // ❌ Replace code like this:',
61
+ ` const val = pageContext[${propName}] ?? someDefaultValue`,
62
+ ' // ✅ With that:',
63
+ ` const val = ${propName} in pageContext ? pageContext[${propName}] : someDefaultValue`,
64
+ ' ```',
65
+ `See stack track below to find where pageContext[${propName}] is being accessed.`
66
+ ].join('\n'), { showStackTrace: true, onlyOnce: false });
50
67
  }
51
68
  }
52
69
  const IGNORE_LIST = [
@@ -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,
@@ -63,24 +63,28 @@ function buildConfig() {
63
63
  buildStart() {
64
64
  assertNodeEnv();
65
65
  },
66
- async writeBundle(options, bundle) {
67
- if (isSsrBuild) {
68
- // Ideally we'd move dist/_temp_manifest.json to dist/server/client-assets.json instead of dist/assets.json
69
- // - 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)
70
- // - We'll able to do so once we replace `$ vite build` with `$ vike build`
71
- const assetsJsonFilePath = path.posix.join(outDirs.outDirRoot, 'assets.json');
72
- const clientManifestFilePath = path.posix.join(outDirs.outDirClient, manifestTempFile);
73
- const serverManifestFilePath = path.posix.join(outDirs.outDirServer, manifestTempFile);
74
- if (!isServerAssetsFixEnabled) {
75
- await fs.copyFile(clientManifestFilePath, assetsJsonFilePath);
76
- }
77
- else {
78
- const clientManifestMod = await fixServerAssets(outDirs);
79
- await fs.writeFile(assetsJsonFilePath, JSON.stringify(clientManifestMod, null, 2), 'utf-8');
66
+ writeBundle: {
67
+ order: 'post',
68
+ sequential: true,
69
+ async handler(options, bundle) {
70
+ if (isSsrBuild) {
71
+ // Ideally we'd move dist/_temp_manifest.json to dist/server/client-assets.json instead of dist/assets.json
72
+ // - 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)
73
+ // - We'll able to do so once we replace `$ vite build` with `$ vike build`
74
+ const assetsJsonFilePath = path.posix.join(outDirs.outDirRoot, 'assets.json');
75
+ const clientManifestFilePath = path.posix.join(outDirs.outDirClient, manifestTempFile);
76
+ const serverManifestFilePath = path.posix.join(outDirs.outDirServer, manifestTempFile);
77
+ if (!isServerAssetsFixEnabled) {
78
+ await fs.copyFile(clientManifestFilePath, assetsJsonFilePath);
79
+ }
80
+ else {
81
+ const clientManifestMod = await fixServerAssets(outDirs);
82
+ await fs.writeFile(assetsJsonFilePath, JSON.stringify(clientManifestMod, null, 2), 'utf-8');
83
+ }
84
+ await fs.rm(clientManifestFilePath);
85
+ await fs.rm(serverManifestFilePath);
86
+ await set_constant_ASSETS_MAP(options, bundle);
80
87
  }
81
- await fs.rm(clientManifestFilePath);
82
- await fs.rm(serverManifestFilePath);
83
- await set_constant_ASSETS_MAP(options, bundle);
84
88
  }
85
89
  }
86
90
  };
@@ -1,5 +1,5 @@
1
1
  export { commonConfig };
2
- import { assert, assertWarning, findFile } from '../utils.js';
2
+ import { assert, assertUsage, 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';
@@ -9,16 +9,18 @@ import { assertResolveAlias } from './commonConfig/assertResolveAlias.js';
9
9
  // @ts-ignore Shimmed by dist-cjs-fixup.js for CJS build.
10
10
  const importMetaUrl = import.meta.url;
11
11
  const require_ = createRequire(importMetaUrl);
12
+ const pluginName = 'vike:commonConfig-1';
12
13
  function commonConfig() {
13
14
  return [
14
15
  {
15
- name: 'vike-commonConfig-1',
16
+ name: pluginName,
16
17
  configResolved(config) {
18
+ assertSingleInstance(config);
17
19
  installRequireShim_setUserRootDir(config.root);
18
20
  }
19
21
  },
20
22
  {
21
- name: 'vike-.commonConfig-2',
23
+ name: 'vike:commonConfig-2',
22
24
  enforce: 'post',
23
25
  configResolved: {
24
26
  order: 'post',
@@ -75,3 +77,7 @@ function assertEsm(userViteRoot) {
75
77
  dir = pc.dim(dir);
76
78
  assertWarning(packageJson.type === 'module', `We recommend setting ${dir}package.json#type to "module", see https://vike.dev/CJS`, { onlyOnce: true });
77
79
  }
80
+ function assertSingleInstance(config) {
81
+ const numberOfInstances = config.plugins.filter((o) => o.name === pluginName).length;
82
+ assertUsage(numberOfInstances === 1, `Vike's Vite plugin (${pc.cyan("import vike from 'vike/plugin'")}) is being added ${numberOfInstances} times to the list of Vite plugins. Make sure to add it only once instead.`);
83
+ }
@@ -40,12 +40,11 @@ function getEntryCode(config, configVike) {
40
40
  ` import * as pageFiles from '${virtualFileIdImportUserCodeServer}';`,
41
41
  ` {`,
42
42
  // We first set the values to a variable because of a Rollup bug, and this workaround doesn't work: https://github.com/vikejs/vike/commit/d5f3a4f7aae5a8bc44192e6cbb2bcb9007be188d
43
- ` const clientManifest = ${ASSETS_MAP};`,
43
+ ` const assetsManifest = ${ASSETS_MAP};`,
44
44
  ` const pluginManifest = ${JSON.stringify(vikeManifest, null, 2)};`,
45
45
  ' setImportBuildGetters({',
46
46
  ` pageFiles: () => pageFiles,`,
47
- // TODO: rename clientManifest -> assetManifest
48
- ` clientManifest: () => clientManifest,`,
47
+ ` getAssetsManifest: () => assetsManifest,`,
49
48
  // TODO: rename pluginManifest -> vikeManifest
50
49
  ` pluginManifest: () => pluginManifest,`,
51
50
  ' });',
@@ -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;
@@ -469,7 +469,8 @@ function warnOverridenConfigValues(interfaceFileWinner, interfaceFilesOverriden,
469
469
  interfaceFilesOverriden.forEach((interfaceFileLoser) => {
470
470
  const loserFilePath = interfaceFileLoser.filePath.filePathToShowToUser;
471
471
  const winnerFilePath = interfaceFileWinner.filePath.filePathToShowToUser;
472
- assertWarning(false, `Config ${configName} defined at ${loserFilePath} is always overwritten by ${configName} defined at ${winnerFilePath}, remove the superfluous ${configName} value defined at ${interfaceFileLoser}`, { onlyOnce: false });
472
+ const confName = pc.cyan(configName);
473
+ assertWarning(false, `The value of the config ${confName} defined at ${loserFilePath} is always overwritten by the value defined at ${winnerFilePath}, remove the superfluous value defined at ${loserFilePath}`, { onlyOnce: true });
473
474
  });
474
475
  }
475
476
  function isInterfaceFileUserLand(interfaceFile) {
@@ -510,6 +511,7 @@ async function getConfigValueSource(configName, interfaceFile, configDef, userRo
510
511
  valueIsFilePath: true,
511
512
  configEnv,
512
513
  valueIsImportedAtRuntime: true,
514
+ valueIsDefinedByValueFile: false,
513
515
  definedAt
514
516
  };
515
517
  return configValueSource;
@@ -525,6 +527,7 @@ async function getConfigValueSource(configName, interfaceFile, configDef, userRo
525
527
  locationId,
526
528
  configEnv,
527
529
  valueIsImportedAtRuntime: true,
530
+ valueIsDefinedByValueFile: false,
528
531
  definedAt: import_
529
532
  };
530
533
  // Load fake import
@@ -549,6 +552,7 @@ async function getConfigValueSource(configName, interfaceFile, configDef, userRo
549
552
  value: configValue,
550
553
  configEnv,
551
554
  valueIsImportedAtRuntime: false,
555
+ valueIsDefinedByValueFile: false,
552
556
  definedAt: definedAtConfigFile
553
557
  };
554
558
  return configValueSource;
@@ -561,6 +565,7 @@ async function getConfigValueSource(configName, interfaceFile, configDef, userRo
561
565
  locationId,
562
566
  configEnv,
563
567
  valueIsImportedAtRuntime: !valueAlreadyLoaded,
568
+ valueIsDefinedByValueFile: true,
564
569
  definedAt: {
565
570
  ...interfaceFile.filePath,
566
571
  fileExportPathToShowToUser: configName === interfaceFile.configName
@@ -2,13 +2,13 @@ export { loadImportBuild };
2
2
  export { setImportBuildGetters };
3
3
  type BuildGetters = null | {
4
4
  pageFiles: () => Promise<Record<string, unknown>>;
5
- clientManifest: () => Promise<Record<string, unknown>>;
5
+ getAssetsManifest: () => Promise<Record<string, unknown>>;
6
6
  pluginManifest: () => Promise<Record<string, unknown>>;
7
7
  };
8
8
  declare function setImportBuildGetters(getters: BuildGetters): void;
9
9
  declare function loadImportBuild(outDir?: string): Promise<{
10
10
  pageFiles: Record<string, unknown>;
11
- clientManifest: Record<string, unknown>;
11
+ assetsManifest: Record<string, unknown>;
12
12
  pluginManifest: Record<string, unknown>;
13
13
  }>;
14
14
  declare global {
@@ -13,11 +13,11 @@ async function loadImportBuild(outDir) {
13
13
  await importServerEntry(outDir);
14
14
  assert(buildGetters.getters);
15
15
  }
16
- const [pageFiles, clientManifest, pluginManifest] = await Promise.all([
16
+ const [pageFiles, assetsManifest, pluginManifest] = await Promise.all([
17
17
  buildGetters.getters.pageFiles(),
18
- buildGetters.getters.clientManifest(),
18
+ buildGetters.getters.getAssetsManifest(),
19
19
  buildGetters.getters.pluginManifest()
20
20
  ]);
21
- const buildEntries = { pageFiles, clientManifest, pluginManifest };
21
+ const buildEntries = { pageFiles, assetsManifest, pluginManifest };
22
22
  return buildEntries;
23
23
  }
@@ -1,3 +1,5 @@
1
+ export { getGlobalContextSync };
2
+ export { getGlobalContextAsync };
1
3
  export { initGlobalContext };
2
4
  export { getGlobalContext };
3
5
  export { getViteDevServer };
@@ -10,6 +12,9 @@ import type { ResolvedConfig, ViteDevServer } from 'vite';
10
12
  import { PluginManifest } from '../shared/assertPluginManifest.js';
11
13
  import type { ConfigVikeResolved } from '../../shared/ConfigVike.js';
12
14
  import { type RuntimeManifest } from '../shared/assertRuntimeManifest.js';
15
+ type GlobalContextPublic = {
16
+ assetsManifest: null | ViteManifest;
17
+ };
13
18
  type GlobalContext = {
14
19
  baseServer: string;
15
20
  baseAssets: null | string;
@@ -22,11 +27,11 @@ type GlobalContext = {
22
27
  isPrerendering: false;
23
28
  viteConfig: ResolvedConfig;
24
29
  viteDevServer: ViteDevServer;
25
- clientManifest: null;
30
+ assetsManifest: null;
26
31
  pluginManifest: null;
27
32
  } | ({
28
33
  isProduction: true;
29
- clientManifest: ViteManifest;
34
+ assetsManifest: ViteManifest;
30
35
  pluginManifest: PluginManifest;
31
36
  viteDevServer: null;
32
37
  } & ({
@@ -37,6 +42,10 @@ type GlobalContext = {
37
42
  viteConfig: ResolvedConfig;
38
43
  })));
39
44
  declare function getGlobalContext(): GlobalContext;
45
+ /** @experimental https://vike.dev/getGlobalContext */
46
+ declare function getGlobalContextSync(): GlobalContextPublic;
47
+ /** @experimental https://vike.dev/getGlobalContext */
48
+ declare function getGlobalContextAsync(): Promise<GlobalContextPublic>;
40
49
  declare function setGlobalContext_viteDevServer(viteDevServer: ViteDevServer): void;
41
50
  declare function getViteDevServer(): ViteDevServer | null;
42
51
  declare function setGlobalContext_prerender(viteConfig: ResolvedConfig): void;
@@ -1,3 +1,7 @@
1
+ // Public use
2
+ export { getGlobalContextSync };
3
+ export { getGlobalContextAsync };
4
+ // Internal use
1
5
  export { initGlobalContext };
2
6
  export { getGlobalContext };
3
7
  export { getViteDevServer };
@@ -5,18 +9,56 @@ export { getViteConfig };
5
9
  export { setGlobalContext_viteDevServer };
6
10
  export { setGlobalContext_prerender };
7
11
  export { getRuntimeManifest };
8
- import { assert, assertUsage, getGlobalObject, getNodeEnv, getNodeEnvDesc, isNodeEnvDev, isPlainObject, objectAssign } from './utils.js';
12
+ import { assert, assertUsage, assertWarning, getGlobalObject, getNodeEnv, getNodeEnvDesc, isNodeEnvDev, isPlainObject, objectAssign, objectKeys } from './utils.js';
9
13
  import { loadImportBuild } from './globalContext/loadImportBuild.js';
10
14
  import { setPageFiles } from '../../shared/getPageFiles.js';
11
15
  import { assertPluginManifest } from '../shared/assertPluginManifest.js';
12
16
  import { getConfigVike } from '../shared/getConfigVike.js';
13
17
  import { assertRuntimeManifest } from '../shared/assertRuntimeManifest.js';
14
18
  import pc from '@brillout/picocolors';
15
- const globalObject = getGlobalObject('globalContext.ts', {});
19
+ let resolveGlobalContext;
20
+ const globalObject = getGlobalObject('globalContext.ts', {
21
+ globalContextPromise: new Promise((r) => (resolveGlobalContext = r))
22
+ });
16
23
  function getGlobalContext() {
17
24
  assert(globalObject.globalContext);
18
25
  return globalObject.globalContext;
19
26
  }
27
+ /** @experimental https://vike.dev/getGlobalContext */
28
+ function getGlobalContextSync() {
29
+ assertUsage(globalObject.globalContext, "The global context isn't set yet, call getGlobalContextSync() later or use getGlobalContextAsync() instead.");
30
+ return makePublic(globalObject.globalContext);
31
+ }
32
+ /** @experimental https://vike.dev/getGlobalContext */
33
+ async function getGlobalContextAsync() {
34
+ await globalObject.globalContextPromise;
35
+ assert(globalObject.globalContext);
36
+ return makePublic(globalObject.globalContext);
37
+ }
38
+ function makePublic(globalContext) {
39
+ const globalContextPublic = {
40
+ assetsManifest: globalContext.assetsManifest
41
+ };
42
+ // Add internals (and prepended _ prefix to their keys)
43
+ {
44
+ const publicKeys = Object.keys(globalContextPublic);
45
+ objectKeys(globalContext)
46
+ .filter((key) => !publicKeys.includes(key))
47
+ .forEach((key) => {
48
+ const keyPublic = `_${key}`;
49
+ Object.defineProperty(globalContextPublic, keyPublic, {
50
+ enumerable: true,
51
+ get() {
52
+ assertWarning(false, `Using internal globalContext.${keyPublic} which is discouraged: it may break in any minor version update. Instead, reach out on GitHub and elaborate your use case.`, {
53
+ onlyOnce: true
54
+ });
55
+ return globalContext[key];
56
+ }
57
+ });
58
+ });
59
+ }
60
+ return globalContextPublic;
61
+ }
20
62
  function setGlobalContext_viteDevServer(viteDevServer) {
21
63
  if (globalObject.viteDevServer)
22
64
  return;
@@ -51,7 +93,7 @@ async function initGlobalContext(isPrerendering = false, outDir) {
51
93
  globalObject.globalContext = {
52
94
  isProduction: false,
53
95
  isPrerendering: false,
54
- clientManifest: null,
96
+ assetsManifest: null,
55
97
  pluginManifest: null,
56
98
  viteDevServer,
57
99
  viteConfig,
@@ -66,13 +108,13 @@ async function initGlobalContext(isPrerendering = false, outDir) {
66
108
  else {
67
109
  const buildEntries = await loadImportBuild(outDir);
68
110
  assertBuildEntries(buildEntries, isPrerendering ?? false);
69
- const { pageFiles, clientManifest, pluginManifest } = buildEntries;
111
+ const { pageFiles, assetsManifest, pluginManifest } = buildEntries;
70
112
  setPageFiles(pageFiles);
71
- assertViteManifest(clientManifest);
113
+ assertViteManifest(assetsManifest);
72
114
  assertPluginManifest(pluginManifest);
73
115
  const globalContext = {
74
116
  isProduction: true,
75
- clientManifest,
117
+ assetsManifest,
76
118
  pluginManifest,
77
119
  viteDevServer: null,
78
120
  baseServer: pluginManifest.baseServer,
@@ -100,6 +142,7 @@ async function initGlobalContext(isPrerendering = false, outDir) {
100
142
  globalObject.globalContext = globalContext;
101
143
  }
102
144
  }
145
+ resolveGlobalContext(globalObject.globalContext);
103
146
  }
104
147
  function getRuntimeManifest(configVike) {
105
148
  const { includeAssetsImportedByServer, baseServer, baseAssets, redirects, trailingSlash, disableUrlNormalization } = configVike;
@@ -2,6 +2,7 @@ export { renderPage } from './renderPage.js';
2
2
  export { escapeInject, dangerouslySkipEscape } from './html/renderHtml.js';
3
3
  export { pipeWebStream, pipeNodeStream, pipeStream, stampPipe } from './html/stream.js';
4
4
  export { PROJECT_VERSION as version } from './utils.js';
5
+ export { getGlobalContextSync, getGlobalContextAsync } from './globalContext.js';
5
6
  export { injectAssets__public as _injectAssets } from './html/injectAssets/injectAssets__public.js';
6
7
  export { createPageRenderer } from '../createPageRenderer.js';
7
8
  declare global {
@@ -2,6 +2,7 @@ export { renderPage } from './renderPage.js';
2
2
  export { escapeInject, dangerouslySkipEscape } from './html/renderHtml.js';
3
3
  export { pipeWebStream, pipeNodeStream, pipeStream, stampPipe } from './html/stream.js';
4
4
  export { PROJECT_VERSION as version } from './utils.js';
5
+ export { getGlobalContextSync, getGlobalContextAsync } from './globalContext.js';
5
6
  // TODO/v1-release: remove
6
7
  export { injectAssets__public as _injectAssets } from './html/injectAssets/injectAssets__public.js';
7
8
  // TODO/v1-release: remove
@@ -1,6 +1,6 @@
1
1
  export { getManifestEntry };
2
2
  import type { ViteManifest, ViteManifestEntry } from '../../../shared/ViteManifest.js';
3
- declare function getManifestEntry(id: string, clientManifest: ViteManifest): {
3
+ declare function getManifestEntry(id: string, assetsManifest: ViteManifest): {
4
4
  manifestKey: string;
5
5
  manifestEntry: ViteManifestEntry;
6
6
  };
@@ -3,13 +3,13 @@ import { assert, slice, isNpmPackageImport } from '../../utils.js';
3
3
  import { assertClientEntryId } from './assertClientEntryId.js';
4
4
  import { isVirtualFileIdPageConfigValuesAll } from '../../../shared/virtual-files/virtualFilePageConfigValuesAll.js';
5
5
  import { prependEntriesDir } from '../../../shared/prependEntriesDir.js';
6
- function getManifestEntry(id, clientManifest) {
6
+ function getManifestEntry(id, assetsManifest) {
7
7
  assertClientEntryId(id);
8
- const debugInfo = getDebugInfo(id, clientManifest);
8
+ const debugInfo = getDebugInfo(id, assetsManifest);
9
9
  // Vike client entry
10
10
  if (id.startsWith('@@vike/')) {
11
11
  const manifestKeyEnd = slice(id, '@@vike'.length, 0);
12
- const { manifestKey, manifestEntry } = findEntryWithKeyEnd(manifestKeyEnd, clientManifest, id);
12
+ const { manifestKey, manifestEntry } = findEntryWithKeyEnd(manifestKeyEnd, assetsManifest, id);
13
13
  assert(manifestEntry && manifestKey, debugInfo);
14
14
  return { manifestEntry, manifestKey };
15
15
  }
@@ -17,7 +17,7 @@ function getManifestEntry(id, clientManifest) {
17
17
  if (isVirtualFileIdPageConfigValuesAll(id)) {
18
18
  {
19
19
  const manifestKey = id;
20
- const manifestEntry = clientManifest[manifestKey];
20
+ const manifestEntry = assetsManifest[manifestKey];
21
21
  if (manifestEntry) {
22
22
  return { manifestEntry, manifestKey };
23
23
  }
@@ -30,20 +30,20 @@ function getManifestEntry(id, clientManifest) {
30
30
  // - This workaround was implemented to support Vitest runnung /tests/*
31
31
  // - I don't know whether end users actually need this workaround? (I'm not sure what the bug actually is.)
32
32
  const manifestKeyEnd = id;
33
- const { manifestKey, manifestEntry } = getEntryWithKeyEnd(manifestKeyEnd, clientManifest, id);
33
+ const { manifestKey, manifestEntry } = getEntryWithKeyEnd(manifestKeyEnd, assetsManifest, id);
34
34
  assert(manifestEntry, debugInfo);
35
35
  return { manifestEntry, manifestKey };
36
36
  }
37
37
  // User files
38
38
  if (id.startsWith('/')) {
39
39
  const manifestKey = id.slice(1);
40
- let manifestEntry = clientManifest[manifestKey];
40
+ let manifestEntry = assetsManifest[manifestKey];
41
41
  assert(manifestEntry, debugInfo);
42
42
  return { manifestEntry, manifestKey };
43
43
  }
44
44
  // npm package import
45
45
  if (isNpmPackageImport(id)) {
46
- const found = Object.entries(clientManifest).find(([, e]) => e.name === prependEntriesDir(id));
46
+ const found = Object.entries(assetsManifest).find(([, e]) => e.name === prependEntriesDir(id));
47
47
  assert(found);
48
48
  const [manifestKey, manifestEntry] = found;
49
49
  return { manifestEntry, manifestKey };
@@ -55,7 +55,7 @@ function getManifestEntry(id, clientManifest) {
55
55
  assert(!manifestKeyEnd.startsWith('/'), debugInfo);
56
56
  manifestKeyEnd = '/' + manifestKeyEnd;
57
57
  {
58
- const { manifestEntry, manifestKey } = findEntryWithKeyEnd(manifestKeyEnd, clientManifest, id);
58
+ const { manifestEntry, manifestKey } = findEntryWithKeyEnd(manifestKeyEnd, assetsManifest, id);
59
59
  if (manifestEntry) {
60
60
  assert(manifestKey, debugInfo);
61
61
  return { manifestEntry, manifestKey };
@@ -69,7 +69,7 @@ function getManifestEntry(id, clientManifest) {
69
69
  assert(manifestKeyEnd.startsWith('/'), debugInfo);
70
70
  }
71
71
  {
72
- const { manifestEntry, manifestKey } = findEntryWithKeyEnd(manifestKeyEnd, clientManifest, id);
72
+ const { manifestEntry, manifestKey } = findEntryWithKeyEnd(manifestKeyEnd, assetsManifest, id);
73
73
  if (manifestEntry) {
74
74
  assert(manifestKey, debugInfo);
75
75
  return { manifestEntry, manifestKey };
@@ -79,11 +79,11 @@ function getManifestEntry(id, clientManifest) {
79
79
  }
80
80
  assert(false, debugInfo);
81
81
  }
82
- function findEntryWithKeyEnd(manifestKeyEnd, clientManifest, id) {
83
- const debugInfo = getDebugInfo(id, clientManifest, manifestKeyEnd);
82
+ function findEntryWithKeyEnd(manifestKeyEnd, assetsManifest, id) {
83
+ const debugInfo = getDebugInfo(id, assetsManifest, manifestKeyEnd);
84
84
  assert(manifestKeyEnd.startsWith('/'), debugInfo);
85
85
  const manifestKeys = [];
86
- for (const manifestKey in clientManifest) {
86
+ for (const manifestKey in assetsManifest) {
87
87
  if (manifestKey.endsWith(manifestKeyEnd)) {
88
88
  manifestKeys.push(manifestKey);
89
89
  }
@@ -94,13 +94,13 @@ function findEntryWithKeyEnd(manifestKeyEnd, clientManifest, id) {
94
94
  if (!manifestKey) {
95
95
  return { manifestEntry: null, manifestKey: null };
96
96
  }
97
- const manifestEntry = clientManifest[manifestKey];
97
+ const manifestEntry = assetsManifest[manifestKey];
98
98
  return { manifestEntry, manifestKey };
99
99
  }
100
- function getEntryWithKeyEnd(manifestKeyEnd, clientManifest, id) {
101
- const debugInfo = getDebugInfo(id, clientManifest, manifestKeyEnd);
100
+ function getEntryWithKeyEnd(manifestKeyEnd, assetsManifest, id) {
101
+ const debugInfo = getDebugInfo(id, assetsManifest, manifestKeyEnd);
102
102
  const manifestKeys = [];
103
- for (const manifestKey in clientManifest) {
103
+ for (const manifestKey in assetsManifest) {
104
104
  if (manifestKey.endsWith(manifestKeyEnd)) {
105
105
  manifestKeys.push(manifestKey);
106
106
  }
@@ -110,11 +110,11 @@ function getEntryWithKeyEnd(manifestKeyEnd, clientManifest, id) {
110
110
  if (!manifestKey) {
111
111
  return { manifestEntry: null, manifestKey: null };
112
112
  }
113
- const manifestEntry = clientManifest[manifestKey];
113
+ const manifestEntry = assetsManifest[manifestKey];
114
114
  return { manifestEntry, manifestKey };
115
115
  }
116
- function getDebugInfo(id, clientManifest, manifestKeyEnd) {
117
- const manifestKeys = Object.keys(clientManifest);
116
+ function getDebugInfo(id, assetsManifest, manifestKeyEnd) {
117
+ const manifestKeys = Object.keys(assetsManifest);
118
118
  if (manifestKeyEnd === undefined) {
119
119
  return { manifestKeys, id };
120
120
  }
@@ -1,4 +1,4 @@
1
1
  export { retrieveAssetsProd };
2
2
  import type { ViteManifest } from '../../../shared/ViteManifest.js';
3
3
  import type { ClientDependency } from '../../../../shared/getPageFiles/analyzePageClientSide/ClientDependency.js';
4
- declare function retrieveAssetsProd(clientDependencies: ClientDependency[], clientManifest: ViteManifest, includeAssetsImportedByServer: boolean): string[];
4
+ declare function retrieveAssetsProd(clientDependencies: ClientDependency[], assetsManifest: ViteManifest, includeAssetsImportedByServer: boolean): string[];