@shopify/hydrogen 1.3.1 → 1.3.2

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 (60) hide show
  1. package/dist/esnext/entry-client.js +1 -1
  2. package/dist/esnext/entry-server.js +20 -25
  3. package/dist/esnext/foundation/HydrogenResponse/HydrogenResponse.server.d.ts +4 -0
  4. package/dist/esnext/foundation/HydrogenResponse/HydrogenResponse.server.js +16 -1
  5. package/dist/esnext/foundation/fetchSync/ResponseSync.d.ts +2 -1
  6. package/dist/esnext/foundation/fetchSync/ResponseSync.js +14 -2
  7. package/dist/esnext/framework/plugin.js +2 -2
  8. package/dist/esnext/framework/plugins/vite-plugin-assets-version.js +4 -0
  9. package/dist/esnext/framework/plugins/vite-plugin-client-imports.js +6 -3
  10. package/dist/esnext/framework/plugins/vite-plugin-css-modules-rsc.js +3 -0
  11. package/dist/esnext/framework/plugins/vite-plugin-css-rsc.js +8 -0
  12. package/dist/esnext/framework/plugins/vite-plugin-hydration-auto-import.js +7 -1
  13. package/dist/esnext/framework/plugins/vite-plugin-hydrogen-client-components-cache.d.ts +3 -0
  14. package/dist/esnext/framework/plugins/{vite-plugin-hydrogen-client-middleware.js → vite-plugin-hydrogen-client-components-cache.js} +2 -2
  15. package/dist/esnext/framework/plugins/vite-plugin-hydrogen-config.js +101 -91
  16. package/dist/esnext/framework/plugins/vite-plugin-hydrogen-middleware.js +6 -6
  17. package/dist/esnext/framework/plugins/vite-plugin-hydrogen-suppress-warnings.js +5 -0
  18. package/dist/esnext/framework/plugins/vite-plugin-hydrogen-virtual-files.js +21 -1
  19. package/dist/esnext/framework/plugins/vite-plugin-platform-entry.js +14 -1
  20. package/dist/esnext/framework/plugins/vite-plugin-ssr-interop.js +5 -1
  21. package/dist/esnext/framework/viteception.js +7 -1
  22. package/dist/esnext/types.d.ts +2 -1
  23. package/dist/esnext/utilities/apiRoutes.d.ts +2 -0
  24. package/dist/esnext/utilities/apiRoutes.js +1 -0
  25. package/dist/esnext/utilities/log/log.js +12 -3
  26. package/dist/esnext/utilities/template.d.ts +7 -6
  27. package/dist/esnext/utilities/template.js +39 -1
  28. package/dist/esnext/utilities/vite.d.ts +1 -0
  29. package/dist/esnext/utilities/vite.js +4 -0
  30. package/dist/esnext/version.d.ts +1 -1
  31. package/dist/esnext/version.js +1 -1
  32. package/dist/node/framework/plugin.js +2 -2
  33. package/dist/node/framework/plugins/vite-plugin-assets-version.js +4 -0
  34. package/dist/node/framework/plugins/vite-plugin-client-imports.js +6 -3
  35. package/dist/node/framework/plugins/vite-plugin-css-modules-rsc.js +3 -0
  36. package/dist/node/framework/plugins/vite-plugin-css-rsc.js +8 -0
  37. package/dist/node/framework/plugins/vite-plugin-hydration-auto-import.js +7 -1
  38. package/dist/node/framework/plugins/vite-plugin-hydrogen-client-components-cache.d.ts +3 -0
  39. package/dist/node/framework/plugins/{vite-plugin-hydrogen-client-middleware.js → vite-plugin-hydrogen-client-components-cache.js} +2 -2
  40. package/dist/node/framework/plugins/vite-plugin-hydrogen-config.js +101 -91
  41. package/dist/node/framework/plugins/vite-plugin-hydrogen-middleware.js +6 -6
  42. package/dist/node/framework/plugins/vite-plugin-hydrogen-suppress-warnings.js +5 -0
  43. package/dist/node/framework/plugins/vite-plugin-hydrogen-virtual-files.js +21 -1
  44. package/dist/node/framework/plugins/vite-plugin-platform-entry.js +14 -1
  45. package/dist/node/framework/plugins/vite-plugin-ssr-interop.js +5 -1
  46. package/dist/node/framework/viteception.js +7 -1
  47. package/dist/node/utilities/vite.d.ts +1 -0
  48. package/dist/node/utilities/vite.js +30 -0
  49. package/package.json +3 -3
  50. package/vendor/react-server-dom-vite/cjs/react-server-dom-vite-plugin.js +31 -21
  51. package/vendor/react-server-dom-vite/cjs/react-server-dom-vite-writer.browser.development.server.js +105 -29
  52. package/vendor/react-server-dom-vite/cjs/react-server-dom-vite-writer.browser.production.min.server.js +30 -29
  53. package/vendor/react-server-dom-vite/cjs/react-server-dom-vite-writer.node.development.server.js +92 -29
  54. package/vendor/react-server-dom-vite/cjs/react-server-dom-vite-writer.node.production.min.server.js +31 -29
  55. package/vendor/react-server-dom-vite/esm/react-server-dom-vite-plugin.js +24 -14
  56. package/vendor/react-server-dom-vite/esm/react-server-dom-vite-writer.browser.server.js +105 -29
  57. package/vendor/react-server-dom-vite/esm/react-server-dom-vite-writer.node.server.js +92 -29
  58. package/vendor/react-server-dom-vite/package.json +2 -2
  59. package/dist/esnext/framework/plugins/vite-plugin-hydrogen-client-middleware.d.ts +0 -9
  60. package/dist/node/framework/plugins/vite-plugin-hydrogen-client-middleware.d.ts +0 -9
@@ -4,10 +4,23 @@ import MagicString from 'magic-string';
4
4
  import path from 'path';
5
5
  import fs from 'fs';
6
6
  import fastGlob from 'fast-glob';
7
+ import { isVite3 } from '../../utilities/vite.js';
7
8
  const SSR_BUNDLE_NAME = 'index.js';
8
9
  // Keep this in the outer scope to share it
9
10
  // across client <> server builds.
10
11
  let clientBuildPath;
12
+ /* -- Plugin notes:
13
+ * This plugin simplifies the way a platform entry file imports user files. This is
14
+ * needed to write generic integrations with different platform providers.
15
+ *
16
+ * Instead of using relative paths:
17
+ * `import handleRequest from '../../<arbitrary_path>/src/App.server';`
18
+ * `import indexTemplate from '../../<arbitrary_path>/dist/client/index.html?raw';`
19
+ *
20
+ * It allows importing from a known static path which dynamically resolves the user files:
21
+ * `import {handleRequest, indexTemplate} from '@shopify/hydrogen/platforms';`
22
+ *
23
+ */
11
24
  export default () => {
12
25
  let config;
13
26
  let isESM;
@@ -18,7 +31,7 @@ export default () => {
18
31
  config = _config;
19
32
  if (config.build.ssr) {
20
33
  const { output = {} } = config.build.rollupOptions || {};
21
- const { format = '' } = (Array.isArray(output) ? output[0] : output) || {};
34
+ const { format = isVite3 ? 'es' : '' } = (Array.isArray(output) ? output[0] : output) || {};
22
35
  isESM = Boolean(process.env.WORKER) || ['es', 'esm'].includes(format);
23
36
  }
24
37
  },
@@ -1,6 +1,10 @@
1
+ /* -- Plugin notes:
2
+ * This plugin makes sure we don't leak server logic to the browser when importing
3
+ * the `useEnvContext` utility.
4
+ */
1
5
  export default () => {
2
6
  return {
3
- name: 'vite-plugin-ssr-interop',
7
+ name: 'hydrogen:ssr-interop',
4
8
  enforce: 'pre',
5
9
  transform(code, id, options = {}) {
6
10
  if (options.ssr && id.includes('foundation/ssr-interop')) {
@@ -1,10 +1,16 @@
1
1
  import { createServer } from 'vite';
2
+ import { isVite3 } from '../utilities/vite.js';
2
3
  export async function viteception(paths, options) {
3
4
  const isWorker = process.env.WORKER;
4
5
  delete process.env.WORKER;
5
6
  const server = await createServer({
6
7
  clearScreen: false,
7
- server: { middlewareMode: 'ssr' },
8
+ server: {
9
+ middlewareMode: isVite3 ? true : 'ssr',
10
+ hmr: false,
11
+ },
12
+ // @ts-ignore
13
+ appType: 'custom',
8
14
  ...options,
9
15
  });
10
16
  if (isWorker) {
@@ -8,6 +8,7 @@ import type { HydrogenResponse } from './foundation/HydrogenResponse/HydrogenRes
8
8
  import type { Metafield } from './storefront-api-types.js';
9
9
  import type { SessionStorageAdapter } from './foundation/session/session-types.js';
10
10
  import type { PartialDeep, JsonValue } from 'type-fest';
11
+ import type { TemplateParts } from './utilities/template.js';
11
12
  export declare type AssembleHtmlParams = {
12
13
  ssrHtml: string;
13
14
  rscPayload?: string;
@@ -26,7 +27,7 @@ export declare type RunSsrParams = {
26
27
  response: HydrogenResponse;
27
28
  log: Logger;
28
29
  dev?: boolean;
29
- template: string;
30
+ template: TemplateParts;
30
31
  nonce?: string;
31
32
  nodeResponse?: ServerResponse;
32
33
  revalidate?: Boolean;
@@ -1,9 +1,11 @@
1
1
  import { ResolvedHydrogenConfig, ResolvedHydrogenRoutes } from '../types.js';
2
+ import { Logger } from '../utilities/log/index.js';
2
3
  import type { HydrogenRequest } from '../foundation/HydrogenRequest/HydrogenRequest.server.js';
3
4
  import type { SessionApi, SessionStorageAdapter } from '../foundation/session/session-types.js';
4
5
  import { UseShopQueryResponse } from '../hooks/useShopQuery/hooks.js';
5
6
  declare type RouteParams = Record<string, string>;
6
7
  export declare type RequestOptions = {
8
+ log: Logger;
7
9
  params: RouteParams;
8
10
  queryShop: <T>(args: QueryShopArgs) => Promise<UseShopQueryResponse<T>>;
9
11
  session: SessionApi | null;
@@ -104,6 +104,7 @@ export async function renderApiRoute(request, route, hydrogenConfig, { session,
104
104
  let cookieToSet = '';
105
105
  try {
106
106
  response = await route.resource(request, {
107
+ log,
107
108
  params: route.params,
108
109
  queryShop: queryShopBuilder(hydrogenConfig.shopify, request),
109
110
  hydrogenConfig,
@@ -28,9 +28,18 @@ const defaultLogger = {
28
28
  };
29
29
  let currentLogger = defaultLogger;
30
30
  function doLog(method, request, ...args) {
31
- const maybePromise = currentLogger[method](request, ...args);
32
- if (maybePromise instanceof Promise) {
33
- request?.ctx?.runtime?.waitUntil?.(maybePromise);
31
+ try {
32
+ const maybePromise = currentLogger[method](request, ...args);
33
+ if (maybePromise instanceof Promise) {
34
+ request?.ctx?.runtime?.waitUntil?.(maybePromise.catch((e) => {
35
+ const message = e instanceof Error ? e.stack : e;
36
+ defaultLogger.error(`Promise error from the custom logging implementation for logger.${method} failed:\n${message}`);
37
+ }));
38
+ }
39
+ }
40
+ catch (e) {
41
+ const message = e instanceof Error ? e.stack : e;
42
+ defaultLogger.error(`The custom logging implementation for logger.${method} failed:\n${message}`);
34
43
  }
35
44
  }
36
45
  export function getLoggerWithContext(context) {
@@ -1,9 +1,10 @@
1
- /**
2
- * Strip out script `src` values from <script> tags in a given HTML template.
3
- * Returns two lists of scripts, split based on whether they are `type="module"`.
4
- */
5
- export declare function stripScriptsFromTemplate(template: string): {
1
+ export declare function getTemplate(indexTemplate: string | ((url: string) => Promise<string | {
2
+ default: string;
3
+ }>), url?: URL): Promise<{
6
4
  noScriptTemplate: string;
7
5
  bootstrapScripts: string[];
8
6
  bootstrapModules: string[];
9
- };
7
+ raw: string;
8
+ linkHeader: string;
9
+ }>;
10
+ export declare type TemplateParts = Awaited<ReturnType<typeof getTemplate>>;
@@ -2,7 +2,7 @@
2
2
  * Strip out script `src` values from <script> tags in a given HTML template.
3
3
  * Returns two lists of scripts, split based on whether they are `type="module"`.
4
4
  */
5
- export function stripScriptsFromTemplate(template) {
5
+ function stripScriptsFromTemplate(template) {
6
6
  const bootstrapScripts = [];
7
7
  const bootstrapModules = [];
8
8
  const scripts = template.matchAll(/<script\n*?.+?src="(?<script>([^"]+?))"\n*.*?><\/script>/g);
@@ -20,3 +20,41 @@ export function stripScriptsFromTemplate(template) {
20
20
  }
21
21
  return { noScriptTemplate: template, bootstrapScripts, bootstrapModules };
22
22
  }
23
+ function extractAttributes(string) {
24
+ const attributes = {};
25
+ for (const [, attr, value] of string.matchAll(/\s([\w-]+)="([^"]*?)"/gm)) {
26
+ attributes[attr] = value;
27
+ }
28
+ return attributes;
29
+ }
30
+ export async function getTemplate(indexTemplate, url) {
31
+ let raw = typeof indexTemplate === 'function'
32
+ ? await indexTemplate(url?.toString() || '')
33
+ : indexTemplate;
34
+ if (raw && typeof raw !== 'string') {
35
+ raw = raw.default;
36
+ }
37
+ return {
38
+ raw,
39
+ linkHeader: createLinkHeader(raw),
40
+ ...stripScriptsFromTemplate(raw),
41
+ };
42
+ }
43
+ const ALLOWED_REL_ATTRS = ['stylesheet', 'preconnect', 'preload'];
44
+ function createLinkHeader(template) {
45
+ const assets = (template.match(/\s*<link[^<>]+?>/gim) || []).map(extractAttributes);
46
+ const links = [];
47
+ for (const { href, rel = '', ...attrs } of assets) {
48
+ if (href && ALLOWED_REL_ATTRS.includes(rel)) {
49
+ const isStyle = rel === 'stylesheet';
50
+ if (isStyle && !attrs.as)
51
+ attrs.as = 'style';
52
+ links.push([
53
+ `<${encodeURI(href.replace(/^https?:/i, ''))}>`,
54
+ `rel=${isStyle ? 'preload' : rel}`,
55
+ ...Object.entries(attrs).map((entry) => entry.join('=')),
56
+ ].join('; '));
57
+ }
58
+ }
59
+ return links.join(', ');
60
+ }
@@ -0,0 +1 @@
1
+ export declare const isVite3: any;
@@ -0,0 +1,4 @@
1
+ // `version` is only exported in Vite 3
2
+ import * as vite from 'vite';
3
+ // @ts-ignore
4
+ export const isVite3 = vite.version?.startsWith('3.');
@@ -1 +1 @@
1
- export declare const LIB_VERSION = "1.3.1";
1
+ export declare const LIB_VERSION = "1.3.2";
@@ -1 +1 @@
1
- export const LIB_VERSION = '1.3.1';
1
+ export const LIB_VERSION = '1.3.2';
@@ -4,7 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  const vite_plugin_hydrogen_config_js_1 = __importDefault(require("./plugins/vite-plugin-hydrogen-config.js"));
6
6
  const vite_plugin_hydrogen_middleware_js_1 = __importDefault(require("./plugins/vite-plugin-hydrogen-middleware.js"));
7
- const vite_plugin_hydrogen_client_middleware_js_1 = __importDefault(require("./plugins/vite-plugin-hydrogen-client-middleware.js"));
7
+ const vite_plugin_hydrogen_client_components_cache_js_1 = __importDefault(require("./plugins/vite-plugin-hydrogen-client-components-cache.js"));
8
8
  const vite_plugin_hydrogen_virtual_files_js_1 = __importDefault(require("./plugins/vite-plugin-hydrogen-virtual-files.js"));
9
9
  const vite_plugin_platform_entry_js_1 = __importDefault(require("./plugins/vite-plugin-platform-entry.js"));
10
10
  const vite_plugin_hydrogen_rsc_js_1 = __importDefault(require("./plugins/vite-plugin-hydrogen-rsc.js"));
@@ -21,7 +21,7 @@ const hydrogenPlugin = (pluginOptions = {}) => {
21
21
  return [
22
22
  process.env.VITE_INSPECT && (0, vite_plugin_inspect_1.default)(),
23
23
  (0, vite_plugin_hydrogen_config_js_1.default)(pluginOptions),
24
- (0, vite_plugin_hydrogen_client_middleware_js_1.default)(),
24
+ (0, vite_plugin_hydrogen_client_components_cache_js_1.default)(),
25
25
  (0, vite_plugin_client_imports_js_1.default)(),
26
26
  (0, vite_plugin_hydrogen_middleware_js_1.default)(pluginOptions),
27
27
  (0, vite_plugin_hydrogen_virtual_files_js_1.default)(pluginOptions),
@@ -1,5 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ /* -- Plugin notes:
4
+ * Used to manually change the hash of output chunks (`index.k12dw5q.js`)
5
+ * when their content have not been updated.
6
+ */
3
7
  function assetsVersion(version) {
4
8
  return {
5
9
  name: 'hydrogen:augment-with-version',
@@ -1,5 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ /* -- Plugin notes:
4
+ * This plugin allows to import always from '@shopify/hydrogen' path, instead of
5
+ * using '@shopify/hydrogen/client' in browser files. It does this by redirecting
6
+ * the server path to the browser path if the importer file is a client component.
7
+ */
3
8
  function clientImports() {
4
9
  return {
5
10
  name: 'hydrogen:client-imports',
@@ -16,9 +21,7 @@ function clientImports() {
16
21
  return;
17
22
  if ('@shopify/hydrogen' !== source)
18
23
  return;
19
- const resolution = await this.resolve('@shopify/hydrogen/client', importer, {
20
- skipSelf: true,
21
- });
24
+ const resolution = await this.resolve('@shopify/hydrogen/client', importer, { skipSelf: true });
22
25
  if (resolution) {
23
26
  return resolution.id;
24
27
  }
@@ -6,6 +6,9 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  const vite_plugin_hydrogen_middleware_js_1 = require("./vite-plugin-hydrogen-middleware.js");
7
7
  const magic_string_1 = __importDefault(require("magic-string"));
8
8
  const path_1 = __importDefault(require("path"));
9
+ /* -- Plugin notes:
10
+ * Old approach to inlining CSS inside server components. This is deprecated.
11
+ */
9
12
  const cssModuleRE = /\.module\.(s?css|sass|less|stylus)/;
10
13
  function cssModulesRsc() {
11
14
  // 1. Original CSS module: `.myStyle { color: red; }`
@@ -11,6 +11,14 @@ const INJECT_STYLES_COMMENT = '<!--__INJECT_STYLES__-->';
11
11
  // Keep this in the outer scope to share it
12
12
  // across client <> server builds.
13
13
  let clientBuildPath;
14
+ /* -- Plugin notes:
15
+ * This plugin collects all the CSS imported in both client and server components and
16
+ * extracts it in a single stylesheet that is added to the <head>. It does this by:
17
+ * 1. Removing all the CSS generated during the client build. The client build CSS is a sub-set of the
18
+ * server build CSS because it can only find CSS imported in client components. This avoids duplicates.
19
+ * 2. Force Vite to collect CSS in every file during the server build, and emit it as a chunk.
20
+ * 3. Move the generated CSS chunk in the server build to the client build output as an asset, and link to it in `index.html`.
21
+ */
14
22
  function cssRsc() {
15
23
  let config;
16
24
  return {
@@ -7,10 +7,16 @@ const vite_1 = require("vite");
7
7
  const path_1 = __importDefault(require("path"));
8
8
  const magic_string_1 = __importDefault(require("magic-string"));
9
9
  const HYDROGEN_ENTRY_FILE = 'hydrogen-entry-client.jsx';
10
+ /* -- Plugin notes:
11
+ * Originally, every Hydrogen app required a `src/entry-client.jsx` file. However, this file
12
+ * was rarely modified by the user. This plugin provides a virtual file with the same content of
13
+ * that file, which allows to remove it by default from the file system.
14
+ * The virtual file created here is imported in `index.html` in a script tag.
15
+ */
10
16
  exports.default = () => {
11
17
  let config;
12
18
  return {
13
- name: 'vite-plugin-hydration-auto-import',
19
+ name: 'hydrogen:client-hydration-auto-import',
14
20
  enforce: 'pre',
15
21
  configResolved(_config) {
16
22
  config = _config;
@@ -0,0 +1,3 @@
1
+ import { type Plugin } from 'vite';
2
+ declare const _default: () => Plugin;
3
+ export default _default;
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const vite_1 = require("vite");
4
- /**
4
+ /* -- Plugin notes:
5
5
  * This dev server middleware prevents Vite from applying immutable cache control headers to client
6
6
  * components. These client components are part of the user's local source, but since they are
7
7
  * referenced via import globs in the `react-dom-server-vite` NPM package, Vite assumes they
@@ -9,7 +9,7 @@ const vite_1 = require("vite");
9
9
  */
10
10
  exports.default = () => {
11
11
  return {
12
- name: 'vite-plugin-hydrogen-client-middleware',
12
+ name: 'hydrogen:client-components-cache',
13
13
  enforce: 'pre',
14
14
  configureServer(server) {
15
15
  server.middlewares.use(async (req, res, next) => {
@@ -4,108 +4,118 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  const crypto_1 = __importDefault(require("crypto"));
7
+ /* -- Plugin notes:
8
+ * Provide configuration options to Vite to ensure Hydrogen is built correctly
9
+ * for worker environments, using latest ES syntax, and some other requirements.
10
+ */
7
11
  exports.default = (pluginOptions) => {
8
12
  const rollupOptions = {
9
13
  output: {},
10
14
  };
11
15
  const isWorker = Boolean(process.env.WORKER) && process.env.WORKER !== 'undefined';
12
- if (isWorker) {
13
- /**
14
- * By default, SSR dedupe logic gets bundled which runs `require('module')`.
15
- * We don't want this in our workers runtime, because `require` is not supported.
16
- */
17
- rollupOptions.output = {
18
- format: 'es',
19
- };
20
- }
21
- if (process.env.NODE_ENV !== 'development' && !process.env.LOCAL_DEV) {
22
- /**
23
- * Ofuscate production asset name - To prevent ad blocker logics that blocks
24
- * certain files due to how it is named.
25
- */
26
- rollupOptions.output = {
27
- ...rollupOptions.output,
28
- chunkFileNames: 'assets/[hash].js',
29
- };
30
- }
31
16
  return {
32
17
  name: 'hydrogen:config',
33
- config: async (config, env) => ({
34
- resolve: {
35
- alias: {
36
- // This library is currently included as a compiled vendor lib, not published yet to NPM
37
- 'react-server-dom-vite/client-proxy': require.resolve('@shopify/hydrogen/vendor/react-server-dom-vite/esm/react-server-dom-vite-client-proxy.js'),
38
- },
39
- },
40
- build: {
41
- minify: config.build?.minify ?? (process.env.LOCAL_DEV ? false : 'esbuild'),
42
- sourcemap: true,
43
- rollupOptions: config.build?.rollupOptions
44
- ? Object.assign(rollupOptions, config.build.rollupOptions)
45
- : rollupOptions,
46
- target: config.build?.ssr
47
- ? isWorker
48
- ? 'es2022' // CFW (Updates weekly to latest V8)
49
- : 'es2020' // Node (Support for v14.19 used in SB)
50
- : 'modules', // Browsers (Vite default value)
51
- },
52
- ssr: {
18
+ config: async (config, env) => {
19
+ // @ts-ignore
20
+ const isSsrBuild = env.ssrBuild ?? !!config.build?.ssr;
21
+ /**
22
+ * By default, SSR dedupe logic gets bundled which runs `require('module')`.
23
+ * We don't want this in our workers runtime, because `require` is not supported.
24
+ */
25
+ rollupOptions.output = {
26
+ format: isWorker || !isSsrBuild ? 'es' : 'cjs',
27
+ inlineDynamicImports: isSsrBuild ? true : undefined,
28
+ };
29
+ if (process.env.NODE_ENV !== 'development' && !process.env.LOCAL_DEV) {
53
30
  /**
54
- * Tell Vite to bundle everything when we're building for Workers.
55
- * Otherwise, bundle RSC plugin as a workaround to apply the vendor alias above.
31
+ * Ofuscate production asset name - To prevent ad blocker logics that blocks
32
+ * certain files due to how it is named.
56
33
  */
57
- noExternal: isWorker || [/react-server-dom-vite/, /@shopify\/hydrogen/],
58
- target: isWorker ? 'webworker' : 'node',
59
- },
60
- // Reload when updating local Hydrogen lib
61
- server: process.env.LOCAL_DEV && {
62
- watch: {
63
- ignored: [
64
- '!**/node_modules/@shopify/hydrogen/**',
65
- '!**/node_modules/@shopify/hydrogen-ui/**',
66
- ],
34
+ rollupOptions.output = {
35
+ ...rollupOptions.output,
36
+ chunkFileNames: 'assets/[hash].js',
37
+ };
38
+ }
39
+ return {
40
+ resolve: {
41
+ alias: {
42
+ // This library is currently included as a compiled vendor lib, not published yet to NPM
43
+ 'react-server-dom-vite/client-proxy': require.resolve('@shopify/hydrogen/vendor/react-server-dom-vite/esm/react-server-dom-vite-client-proxy.js'),
44
+ },
67
45
  },
68
- },
69
- optimizeDeps: {
70
- exclude: [
71
- '@shopify/hydrogen',
72
- '@shopify/hydrogen/client',
73
- '@shopify/hydrogen/entry-client',
74
- '@shopify/hydrogen-ui',
75
- ],
76
- include: [
77
- /**
78
- * Additionally, the following dependencies have trouble loading the
79
- * correct version of the dependency (server vs client). This tells Vite to take the
80
- * server versions and optimize them for ESM.
81
- */
82
- 'react-helmet-async',
83
- 'react-error-boundary',
46
+ build: {
47
+ minify: config.build?.minify ?? (process.env.LOCAL_DEV ? false : 'esbuild'),
48
+ sourcemap: true,
49
+ rollupOptions: config.build?.rollupOptions
50
+ ? Object.assign(rollupOptions, config.build.rollupOptions)
51
+ : rollupOptions,
52
+ target: config.build?.ssr
53
+ ? isWorker
54
+ ? 'es2022' // CFW (Updates weekly to latest V8)
55
+ : 'es2020' // Node (Support for v14.19 used in SB)
56
+ : 'modules', // Browsers (Vite default value)
57
+ },
58
+ ssr: {
84
59
  /**
85
- * Vite cannot find the following dependencies since they might be
86
- * required in RSC asynchronously. This tells Vite to optimize them
87
- * at server start to avoid posterior page reloads and issues (#429 #430).
60
+ * Tell Vite to bundle everything when we're building for Workers.
61
+ * Otherwise, bundle RSC plugin as a workaround to apply the vendor alias above.
88
62
  */
89
- 'react',
90
- 'react-dom/client',
91
- 'react-server-dom-vite/client-proxy',
92
- // https://github.com/vitejs/vite/issues/6215
93
- 'react/jsx-runtime',
94
- // https://github.com/nfriedly/set-cookie-parser/issues/50
95
- 'set-cookie-parser',
96
- 'undici',
97
- ],
98
- },
99
- define: {
100
- __HYDROGEN_DEV__: env.mode !== 'production',
101
- __HYDROGEN_WORKER__: isWorker,
102
- __HYDROGEN_TEST__: false,
103
- __HYDROGEN_CACHE_ID__: pluginOptions.purgeQueryCacheOnBuild
104
- ? `"${crypto_1.default.randomBytes(8).toString('hex').slice(0, 8)}"`
105
- : '"__QUERY_CACHE_ID__"',
106
- },
107
- envPrefix: ['VITE_', 'PUBLIC_'],
108
- base: process.env.HYDROGEN_ASSET_BASE_URL,
109
- }),
63
+ noExternal: isWorker || [
64
+ /react-server-dom-vite/,
65
+ /@shopify\/hydrogen/,
66
+ ],
67
+ target: isWorker ? 'webworker' : 'node',
68
+ },
69
+ // Reload when updating local Hydrogen lib
70
+ server: process.env.LOCAL_DEV && {
71
+ watch: {
72
+ ignored: [
73
+ '!**/node_modules/@shopify/hydrogen/**',
74
+ '!**/node_modules/@shopify/hydrogen-ui/**',
75
+ ],
76
+ },
77
+ },
78
+ optimizeDeps: {
79
+ exclude: [
80
+ '@shopify/hydrogen',
81
+ '@shopify/hydrogen/client',
82
+ '@shopify/hydrogen/entry-client',
83
+ '@shopify/hydrogen-ui',
84
+ ],
85
+ include: [
86
+ /**
87
+ * Additionally, the following dependencies have trouble loading the
88
+ * correct version of the dependency (server vs client). This tells Vite to take the
89
+ * server versions and optimize them for ESM.
90
+ */
91
+ 'react-helmet-async',
92
+ 'react-error-boundary',
93
+ /**
94
+ * Vite cannot find the following dependencies since they might be
95
+ * required in RSC asynchronously. This tells Vite to optimize them
96
+ * at server start to avoid posterior page reloads and issues (#429 #430).
97
+ */
98
+ 'react',
99
+ 'react-dom/client',
100
+ 'react-server-dom-vite/client-proxy',
101
+ // https://github.com/vitejs/vite/issues/6215
102
+ 'react/jsx-runtime',
103
+ // https://github.com/nfriedly/set-cookie-parser/issues/50
104
+ 'set-cookie-parser',
105
+ 'undici',
106
+ ],
107
+ },
108
+ define: {
109
+ __HYDROGEN_DEV__: env.mode !== 'production',
110
+ __HYDROGEN_WORKER__: isWorker,
111
+ __HYDROGEN_TEST__: false,
112
+ __HYDROGEN_CACHE_ID__: pluginOptions.purgeQueryCacheOnBuild
113
+ ? `"${crypto_1.default.randomBytes(8).toString('hex').slice(0, 8)}"`
114
+ : '"__QUERY_CACHE_ID__"',
115
+ },
116
+ envPrefix: ['VITE_', 'PUBLIC_'],
117
+ base: process.env.HYDROGEN_ASSET_BASE_URL,
118
+ };
119
+ },
110
120
  };
111
121
  };
@@ -12,15 +12,15 @@ const middleware_js_1 = require("../middleware.js");
12
12
  const in_memory_js_1 = require("../cache/in-memory.js");
13
13
  const vite_plugin_hydrogen_virtual_files_js_1 = require("./vite-plugin-hydrogen-virtual-files.js");
14
14
  exports.HYDROGEN_DEFAULT_SERVER_ENTRY = process.env.HYDROGEN_SERVER_ENTRY || '/src/App.server';
15
+ /* -- Plugin notes:
16
+ * By adding a middleware to the Vite dev server, we can handle SSR without needing
17
+ * a custom node script. It works by handling any requests for `text/html` documents,
18
+ * loading them in an SSR context, rendering them using the `entry-server` endpoint in the
19
+ * user's project, and injecting the static HTML into the template.
20
+ */
15
21
  exports.default = (pluginOptions) => {
16
22
  return {
17
23
  name: 'hydrogen:middleware',
18
- /**
19
- * By adding a middleware to the Vite dev server, we can handle SSR without needing
20
- * a custom node script. It works by handling any requests for `text/html` documents,
21
- * loading them in an SSR context, rendering them using the `entry-server` endpoint in the
22
- * user's project, and injecting the static HTML into the template.
23
- */
24
24
  async configureServer(server) {
25
25
  const resolve = (p) => path_1.default.resolve(server.config.root, p);
26
26
  async function getIndexTemplate(url) {
@@ -1,5 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ /* -- Plugin notes:
4
+ * Vite prints some warnings automatically are not important and
5
+ * not actionable. We hide them here to prevent confusing devs when
6
+ * real warnings or errors appear.
7
+ */
3
8
  exports.default = () => {
4
9
  return {
5
10
  name: 'hydrogen:suppress-warnings',
@@ -9,6 +9,14 @@ const path_1 = __importDefault(require("path"));
9
9
  const fs_1 = require("fs");
10
10
  const viteception_js_1 = require("../viteception.js");
11
11
  const magic_string_1 = __importDefault(require("magic-string"));
12
+ const vite_js_1 = require("../../utilities/vite.js");
13
+ /* -- Plugin notes:
14
+ * The Hydrogen framework needs to import certain files from the user app, such as
15
+ * routes and config. A priori, we can't import these files from the framework
16
+ * because we don't know the user path to write it in an `import * from '...'` statement.
17
+ * Instead, we import "virtual files" that are resolved by Vite in this plugin.
18
+ * These virtual files can include the user path and re-export the in-app files.
19
+ */
12
20
  exports.HYDROGEN_DEFAULT_SERVER_ENTRY = process.env.HYDROGEN_SERVER_ENTRY || '/src/App.server';
13
21
  // The character ":" breaks Vite with Node >= 16.15. Use "_" instead
14
22
  const VIRTUAL_PREFIX = 'virtual__';
@@ -21,6 +29,7 @@ exports.VIRTUAL_PROXY_HYDROGEN_CONFIG_ID = VIRTUAL_PREFIX + PROXY_PREFIX + HYDRO
21
29
  const HYDROGEN_ROUTES_ID = 'hydrogen-routes.server.jsx';
22
30
  const VIRTUAL_HYDROGEN_ROUTES_ID = VIRTUAL_PREFIX + HYDROGEN_ROUTES_ID;
23
31
  exports.VIRTUAL_PROXY_HYDROGEN_ROUTES_ID = VIRTUAL_PREFIX + PROXY_PREFIX + HYDROGEN_ROUTES_ID;
32
+ const VIRTUAL_STREAM_ID = 'virtual__stream';
24
33
  exports.default = (pluginOptions) => {
25
34
  let config;
26
35
  let server;
@@ -47,6 +56,7 @@ exports.default = (pluginOptions) => {
47
56
  exports.VIRTUAL_PROXY_HYDROGEN_ROUTES_ID,
48
57
  VIRTUAL_HYDROGEN_ROUTES_ID,
49
58
  VIRTUAL_ERROR_FILE,
59
+ VIRTUAL_STREAM_ID,
50
60
  ].includes(source)) {
51
61
  // Virtual modules convention
52
62
  // https://vitejs.dev/guide/api-plugin.html#virtual-modules-convention
@@ -54,6 +64,13 @@ exports.default = (pluginOptions) => {
54
64
  }
55
65
  },
56
66
  load(id) {
67
+ if (id === '\0' + VIRTUAL_STREAM_ID) {
68
+ return {
69
+ code: process.env.WORKER
70
+ ? `export default {};`
71
+ : `export {default} from 'stream';`,
72
+ };
73
+ }
57
74
  // Likely due to a bug in Vite, but virtual modules cannot be loaded
58
75
  // directly using ssrLoadModule from a Vite plugin. It needs to be proxied as follows:
59
76
  if (id === '\0' + exports.VIRTUAL_PROXY_HYDROGEN_CONFIG_ID) {
@@ -76,7 +93,10 @@ exports.default = (pluginOptions) => {
76
93
  routesPath += '**/*.server.[jt](s|sx)';
77
94
  }
78
95
  const [dirPrefix] = routesPath.split('/*');
79
- let code = `export default {\n dirPrefix: '${dirPrefix}',\n basePath: '${hc.routes?.basePath ?? ''}',\n files: import.meta.globEager('${routesPath}')\n};`;
96
+ const importGlob = vite_js_1.isVite3
97
+ ? `import.meta.glob('${routesPath}', {eager: true})`
98
+ : `import.meta.globEager('${routesPath}')`;
99
+ let code = `export default {\n dirPrefix: '${dirPrefix}',\n basePath: '${hc.routes?.basePath ?? ''}',\n files: ${importGlob}\n};`;
80
100
  if (config.command === 'serve') {
81
101
  // Add dependency on Hydrogen config for HMR
82
102
  code += `\nimport '${VIRTUAL_HYDROGEN_CONFIG_ID}';`;