@shopify/hydrogen 0.8.3 → 0.9.0

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 (53) hide show
  1. package/dist/esnext/components/ProductProvider/ProductProvider.client.d.ts +3 -2
  2. package/dist/esnext/entry-server.js +14 -4
  3. package/dist/esnext/foundation/Router/DefaultRoutes.d.ts +2 -2
  4. package/dist/esnext/foundation/Router/DefaultRoutes.js +6 -2
  5. package/dist/esnext/foundation/useQuery/hooks.js +2 -1
  6. package/dist/esnext/framework/Hydration/ServerComponentRequest.server.js +3 -0
  7. package/dist/esnext/framework/middleware.js +20 -22
  8. package/dist/esnext/framework/plugin.d.ts +1 -1
  9. package/dist/esnext/framework/plugin.js +3 -1
  10. package/dist/esnext/framework/plugins/vite-plugin-hydrogen-middleware.js +2 -0
  11. package/dist/esnext/framework/plugins/vite-plugin-purge-query-cache.d.ts +3 -0
  12. package/dist/esnext/framework/plugins/vite-plugin-purge-query-cache.js +11 -0
  13. package/dist/esnext/handle-event.js +12 -2
  14. package/dist/esnext/types.d.ts +9 -4
  15. package/dist/esnext/utilities/apiRoutes.d.ts +21 -0
  16. package/dist/esnext/utilities/apiRoutes.js +73 -0
  17. package/dist/esnext/utilities/flattenConnection/flattenConnection.d.ts +1 -1
  18. package/dist/esnext/utilities/flattenConnection/flattenConnection.js +1 -1
  19. package/dist/esnext/utilities/log/log.d.ts +1 -1
  20. package/dist/esnext/utilities/log/log.js +6 -5
  21. package/dist/esnext/utilities/matchPath.d.ts +10 -0
  22. package/dist/esnext/utilities/matchPath.js +54 -0
  23. package/dist/esnext/version.d.ts +1 -1
  24. package/dist/esnext/version.js +1 -1
  25. package/dist/node/framework/Hydration/ServerComponentRequest.server.js +3 -0
  26. package/dist/node/framework/middleware.js +20 -22
  27. package/dist/node/framework/plugin.d.ts +1 -1
  28. package/dist/node/framework/plugin.js +3 -1
  29. package/dist/node/framework/plugins/vite-plugin-hydrogen-middleware.js +2 -0
  30. package/dist/node/framework/plugins/vite-plugin-purge-query-cache.d.ts +3 -0
  31. package/dist/node/framework/plugins/vite-plugin-purge-query-cache.js +16 -0
  32. package/dist/node/handle-event.js +12 -2
  33. package/dist/node/types.d.ts +9 -4
  34. package/dist/node/utilities/apiRoutes.d.ts +21 -0
  35. package/dist/node/utilities/apiRoutes.js +79 -0
  36. package/dist/node/utilities/flattenConnection/flattenConnection.d.ts +1 -1
  37. package/dist/node/utilities/flattenConnection/flattenConnection.js +1 -1
  38. package/dist/node/utilities/log/log.d.ts +17 -0
  39. package/dist/node/utilities/log/log.js +83 -0
  40. package/dist/node/utilities/matchPath.d.ts +10 -0
  41. package/dist/node/utilities/matchPath.js +58 -0
  42. package/dist/node/version.d.ts +1 -1
  43. package/dist/node/version.js +1 -1
  44. package/dist/worker/framework/Hydration/ServerComponentRequest.server.js +3 -0
  45. package/dist/worker/handle-event.js +12 -2
  46. package/dist/worker/types.d.ts +9 -4
  47. package/dist/worker/utilities/apiRoutes.d.ts +21 -0
  48. package/dist/worker/utilities/apiRoutes.js +73 -0
  49. package/dist/worker/utilities/log/log.d.ts +17 -0
  50. package/dist/worker/utilities/log/log.js +76 -0
  51. package/dist/worker/utilities/matchPath.d.ts +10 -0
  52. package/dist/worker/utilities/matchPath.js +54 -0
  53. package/package.json +10 -3
@@ -42,32 +42,24 @@ exports.graphiqlMiddleware = graphiqlMiddleware;
42
42
  function hydrogenMiddleware({ dev, cache, indexTemplate, getServerEntrypoint, devServer, }) {
43
43
  return async function (request, response, next) {
44
44
  const url = new URL('http://' + request.headers.host + request.originalUrl);
45
- const isReactHydrationRequest = url.pathname === '/react';
46
- /**
47
- * If it's a dev environment, it's assumed that Vite's dev server is handling
48
- * any static or JS requests, so we need to ensure that we don't try to handle them.
49
- *
50
- * If it's a product environment, it's assumed that the developer is handling
51
- * static requests with e.g. static middleware.
52
- */
53
- if (dev && !shouldInterceptRequest(request, isReactHydrationRequest)) {
54
- return next();
55
- }
56
45
  try {
57
46
  /**
58
47
  * We're running in the Node.js runtime without access to `fetch`,
59
48
  * which is needed for proxy requests and server-side API requests.
60
49
  */
61
50
  if (!globalThis.fetch) {
62
- const fetch = await Promise.resolve().then(() => __importStar(require('node-fetch')));
51
+ const { fetch, Request, Response, Headers } = await Promise.resolve().then(() => __importStar(require('undici')));
52
+ const { default: AbortController } = await Promise.resolve().then(() => __importStar(require('abort-controller')));
53
+ // @ts-ignore
54
+ globalThis.fetch = fetch;
63
55
  // @ts-ignore
64
- globalThis.fetch = fetch.default;
56
+ globalThis.Request = Request;
65
57
  // @ts-ignore
66
- globalThis.Request = fetch.Request;
58
+ globalThis.Response = Response;
67
59
  // @ts-ignore
68
- globalThis.Response = fetch.Response;
60
+ globalThis.Headers = Headers;
69
61
  // @ts-ignore
70
- globalThis.Headers = fetch.Headers;
62
+ globalThis.AbortController = AbortController;
71
63
  }
72
64
  /**
73
65
  * Dynamically import ServerComponentResponse after the `fetch`
@@ -95,7 +87,18 @@ function hydrogenMiddleware({ dev, cache, indexTemplate, getServerEntrypoint, de
95
87
  response.setHeader(key, value);
96
88
  });
97
89
  response.statusCode = eventResponse.status;
98
- response.end(eventResponse.body);
90
+ if (eventResponse.body) {
91
+ const reader = eventResponse.body.getReader();
92
+ while (true) {
93
+ const { done, value } = await reader.read();
94
+ if (done)
95
+ return response.end();
96
+ response.write(value);
97
+ }
98
+ }
99
+ else {
100
+ response.end();
101
+ }
99
102
  }
100
103
  }
101
104
  catch (e) {
@@ -126,11 +129,6 @@ function hydrogenMiddleware({ dev, cache, indexTemplate, getServerEntrypoint, de
126
129
  };
127
130
  }
128
131
  exports.hydrogenMiddleware = hydrogenMiddleware;
129
- function shouldInterceptRequest(request, isReactHydrationRequest) {
130
- var _a;
131
- return (/text\/html|application\/hydrogen/.test((_a = request.headers['accept']) !== null && _a !== void 0 ? _a : '') ||
132
- isReactHydrationRequest);
133
- }
134
132
  /**
135
133
  * /graphiql and /___graphql are supported
136
134
  */
@@ -1,3 +1,3 @@
1
1
  import type { HydrogenVitePluginOptions, ShopifyConfig } from '../types';
2
- declare const _default: (shopifyConfig: ShopifyConfig, pluginOptions: HydrogenVitePluginOptions) => ("" | import("vite").Plugin | import("vite").PluginOption[] | undefined)[];
2
+ declare const _default: (shopifyConfig: ShopifyConfig, pluginOptions?: HydrogenVitePluginOptions) => (false | "" | import("vite").Plugin | import("vite").PluginOption[] | undefined)[];
3
3
  export default _default;
@@ -6,14 +6,16 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  const vite_plugin_hydrogen_config_1 = __importDefault(require("./plugins/vite-plugin-hydrogen-config"));
7
7
  const vite_plugin_hydrogen_middleware_1 = __importDefault(require("./plugins/vite-plugin-hydrogen-middleware"));
8
8
  const vite_plugin_react_server_components_shim_1 = __importDefault(require("./plugins/vite-plugin-react-server-components-shim"));
9
+ const vite_plugin_purge_query_cache_1 = __importDefault(require("./plugins/vite-plugin-purge-query-cache"));
9
10
  const vite_plugin_inspect_1 = __importDefault(require("vite-plugin-inspect"));
10
11
  const plugin_react_1 = __importDefault(require("@vitejs/plugin-react"));
11
- exports.default = (shopifyConfig, pluginOptions) => {
12
+ exports.default = (shopifyConfig, pluginOptions = {}) => {
12
13
  return [
13
14
  process.env.VITE_INSPECT && (0, vite_plugin_inspect_1.default)(),
14
15
  (0, vite_plugin_hydrogen_config_1.default)(),
15
16
  (0, vite_plugin_hydrogen_middleware_1.default)(shopifyConfig, pluginOptions),
16
17
  (0, vite_plugin_react_server_components_shim_1.default)(),
17
18
  (0, plugin_react_1.default)(),
19
+ pluginOptions.purgeQueryCacheOnBuild && (0, vite_plugin_purge_query_cache_1.default)(),
18
20
  ];
19
21
  };
@@ -4,6 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  const vite_1 = require("vite");
7
+ const body_parser_1 = __importDefault(require("body-parser"));
7
8
  const path_1 = __importDefault(require("path"));
8
9
  const fs_1 = require("fs");
9
10
  const middleware_1 = require("../middleware");
@@ -30,6 +31,7 @@ exports.default = (shopifyConfig, pluginOptions) => {
30
31
  shopifyConfig,
31
32
  dev: true,
32
33
  }));
34
+ server.middlewares.use(body_parser_1.default.raw({ type: '*/*' }));
33
35
  return () => server.middlewares.use((0, middleware_1.hydrogenMiddleware)({
34
36
  dev: true,
35
37
  shopifyConfig,
@@ -0,0 +1,3 @@
1
+ import type { Plugin } from 'vite';
2
+ declare const _default: () => Plugin;
3
+ export default _default;
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const crypto_1 = __importDefault(require("crypto"));
7
+ exports.default = () => {
8
+ const buildCacheId = crypto_1.default.randomBytes(8).toString('hex').slice(0, 8);
9
+ return {
10
+ name: 'vite-plugin-purge-query-cache',
11
+ enforce: 'pre',
12
+ transform(code) {
13
+ return code.replace('__QUERY_CACHE_ID__', buildCacheId);
14
+ },
15
+ };
16
+ };
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const cache_1 = require("./framework/cache");
4
4
  const runtime_1 = require("./framework/runtime");
5
5
  const config_1 = require("./framework/config");
6
+ const apiRoutes_1 = require("./utilities/apiRoutes");
6
7
  async function handleEvent(event, { request, entrypoint, indexTemplate, assetHandler, streamableResponse, dev, cache, context, }) {
7
8
  var _a, _b, _c, _d, _e;
8
9
  const url = new URL(request.url);
@@ -23,12 +24,21 @@ async function handleEvent(event, { request, entrypoint, indexTemplate, assetHan
23
24
  assetHandler) {
24
25
  return assetHandler(event, url);
25
26
  }
26
- const { render, hydrate, stream } = entrypoint.default || entrypoint;
27
+ const { render, hydrate, stream, getApiRoute, log } = entrypoint.default || entrypoint;
27
28
  // @ts-ignore
28
- if (dev && !(render && hydrate && stream)) {
29
+ if (dev && !(render && hydrate && stream && getApiRoute)) {
29
30
  throw new Error(`entry-server.jsx could not be loaded. This likely occurred because of a Vite compilation error.\n` +
30
31
  `Please check your server logs for more information.`);
31
32
  }
33
+ if (!isReactHydrationRequest) {
34
+ const apiRoute = getApiRoute(url);
35
+ // The API Route might have a default export, making it also a server component
36
+ // If it does, only render the API route if the request method is GET
37
+ if (apiRoute &&
38
+ (!apiRoute.hasServerComponent || request.method !== 'GET')) {
39
+ return (0, apiRoutes_1.renderApiRoute)(request, apiRoute, log);
40
+ }
41
+ }
32
42
  const userAgent = request.headers.get('user-agent');
33
43
  const isStreamable = streamableResponse && !isBotUA(url, userAgent);
34
44
  /**
@@ -3,6 +3,8 @@ import { ServerResponse } from 'http';
3
3
  import type { ServerComponentResponse } from './framework/Hydration/ServerComponentResponse.server';
4
4
  import type { ServerComponentRequest } from './framework/Hydration/ServerComponentRequest.server';
5
5
  import type { Metafield, Image, MediaContentType } from './graphql/types/types';
6
+ import { ApiRouteMatch } from './utilities/apiRoutes';
7
+ import { Logger } from './utilities/log/log';
6
8
  export declare type Renderer = (url: URL, options: {
7
9
  request: ServerComponentRequest;
8
10
  context?: Record<string, any>;
@@ -29,6 +31,8 @@ export declare type EntryServerHandler = {
29
31
  render: Renderer;
30
32
  stream: Streamer;
31
33
  hydrate: Hydrator;
34
+ getApiRoute: (url: URL) => ApiRouteMatch | null;
35
+ log: Logger;
32
36
  };
33
37
  export declare type ShopifyConfig = {
34
38
  locale?: string;
@@ -39,11 +43,11 @@ export declare type ShopifyConfig = {
39
43
  export declare type Hook = (params: {
40
44
  url: URL;
41
45
  } & Record<string, any>) => any | Promise<any>;
42
- export declare type ServerHandler = (App: any, hook?: Hook) => {
43
- render: Renderer;
44
- stream: Streamer;
45
- hydrate: Hydrator;
46
+ export declare type ImportGlobEagerOutput = Record<string, Record<'default' | 'api', any>>;
47
+ export declare type ServerHandlerConfig = {
48
+ pages?: ImportGlobEagerOutput;
46
49
  };
50
+ export declare type ServerHandler = (App: any, config?: ServerHandlerConfig, hook?: Hook) => EntryServerHandler;
47
51
  export declare type ClientHandler = (App: any, hook?: Hook) => Promise<void>;
48
52
  export interface GraphQLConnection<T> {
49
53
  edges?: {
@@ -87,5 +91,6 @@ export interface CacheOptions {
87
91
  }
88
92
  export interface HydrogenVitePluginOptions {
89
93
  devCache?: boolean;
94
+ purgeQueryCacheOnBuild?: boolean;
90
95
  }
91
96
  export {};
@@ -0,0 +1,21 @@
1
+ import { ImportGlobEagerOutput } from '../types';
2
+ import { Logger } from '../utilities/log/log';
3
+ declare type RouteParams = Record<string, string>;
4
+ declare type RequestOptions = {
5
+ params: RouteParams;
6
+ };
7
+ declare type ResourceGetter = (request: Request, requestOptions: RequestOptions) => Promise<Response>;
8
+ interface HydrogenApiRoute {
9
+ path: string;
10
+ resource: ResourceGetter;
11
+ hasServerComponent: boolean;
12
+ }
13
+ export declare type ApiRouteMatch = {
14
+ resource: ResourceGetter;
15
+ hasServerComponent: boolean;
16
+ params: RouteParams;
17
+ };
18
+ export declare function getApiRoutesFromPages(pages: ImportGlobEagerOutput | undefined, topLevelPath?: string): Array<HydrogenApiRoute>;
19
+ export declare function getApiRouteFromURL(url: URL, routes: Array<HydrogenApiRoute>): ApiRouteMatch | null;
20
+ export declare function renderApiRoute(request: Request, route: ApiRouteMatch, log: Logger): Promise<Response>;
21
+ export {};
@@ -0,0 +1,79 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.renderApiRoute = exports.getApiRouteFromURL = exports.getApiRoutesFromPages = void 0;
4
+ const matchPath_1 = require("./matchPath");
5
+ const log_1 = require("../utilities/log/log");
6
+ let cachedRoutes = [];
7
+ function getApiRoutesFromPages(pages, topLevelPath = '*') {
8
+ if ((cachedRoutes === null || cachedRoutes === void 0 ? void 0 : cachedRoutes.length) || !pages)
9
+ return cachedRoutes;
10
+ const topLevelPrefix = topLevelPath.replace('*', '').replace(/\/$/, '');
11
+ const routes = Object.keys(pages)
12
+ .filter((key) => pages[key].api)
13
+ .map((key) => {
14
+ const path = key
15
+ .replace('./pages', '')
16
+ .replace(/\.server\.(t|j)sx?$/, '')
17
+ /**
18
+ * Replace /index with /
19
+ */
20
+ .replace(/\/index$/i, '/')
21
+ /**
22
+ * Only lowercase the first letter. This allows the developer to use camelCase
23
+ * dynamic paths while ensuring their standard routes are normalized to lowercase.
24
+ */
25
+ .replace(/\b[A-Z]/, (firstLetter) => firstLetter.toLowerCase())
26
+ /**
27
+ * Convert /[handle].jsx and /[...handle].jsx to /:handle.jsx for react-router-dom
28
+ */
29
+ .replace(/\[(?:[.]{3})?(\w+?)\]/g, (_match, param) => `:${param}`);
30
+ /**
31
+ * Catch-all routes [...handle].jsx don't need an exact match
32
+ * https://reactrouter.com/core/api/Route/exact-bool
33
+ */
34
+ const exact = !/\[(?:[.]{3})(\w+?)\]/.test(key);
35
+ return {
36
+ path: topLevelPrefix + path,
37
+ resource: pages[key].api,
38
+ hasServerComponent: !!pages[key].default,
39
+ exact,
40
+ };
41
+ });
42
+ cachedRoutes = [
43
+ ...routes.filter((route) => !route.path.includes(':')),
44
+ ...routes.filter((route) => route.path.includes(':')),
45
+ ];
46
+ return cachedRoutes;
47
+ }
48
+ exports.getApiRoutesFromPages = getApiRoutesFromPages;
49
+ function getApiRouteFromURL(url, routes) {
50
+ let foundRoute, foundRouteDetails;
51
+ for (let i = 0; i < routes.length; i++) {
52
+ foundRouteDetails = (0, matchPath_1.matchPath)(url.pathname, routes[i]);
53
+ if (foundRouteDetails) {
54
+ foundRoute = routes[i];
55
+ break;
56
+ }
57
+ }
58
+ if (!foundRoute)
59
+ return null;
60
+ return {
61
+ resource: foundRoute.resource,
62
+ params: foundRouteDetails.params,
63
+ hasServerComponent: foundRoute.hasServerComponent,
64
+ };
65
+ }
66
+ exports.getApiRouteFromURL = getApiRouteFromURL;
67
+ async function renderApiRoute(request, route, log) {
68
+ let response;
69
+ try {
70
+ response = await route.resource(request, { params: route.params });
71
+ }
72
+ catch (e) {
73
+ log.error(e);
74
+ response = new Response('Error processing: ' + request.url, { status: 500 });
75
+ }
76
+ (0, log_1.logServerResponse)('api', log, request, response.status);
77
+ return response;
78
+ }
79
+ exports.renderApiRoute = renderApiRoute;
@@ -1,5 +1,5 @@
1
1
  import { GraphQLConnection } from '../../types';
2
2
  /**
3
- * The `flattenConnection` utility transforms a connection object from the Storefront API (for example, [Product-related connections](api/storefront/reference/products/product#connections)) into a flat array of nodes.
3
+ * The `flattenConnection` utility transforms a connection object from the Storefront API (for example, [Product-related connections](/api/storefront/reference/products/product)) into a flat array of nodes.
4
4
  */
5
5
  export declare function flattenConnection<T>(connection: GraphQLConnection<T>): T[];
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.flattenConnection = void 0;
4
4
  /**
5
- * The `flattenConnection` utility transforms a connection object from the Storefront API (for example, [Product-related connections](api/storefront/reference/products/product#connections)) into a flat array of nodes.
5
+ * The `flattenConnection` utility transforms a connection object from the Storefront API (for example, [Product-related connections](/api/storefront/reference/products/product)) into a flat array of nodes.
6
6
  */
7
7
  function flattenConnection(connection) {
8
8
  var _a;
@@ -0,0 +1,17 @@
1
+ import { ServerComponentRequest } from '../../framework/Hydration/ServerComponentRequest.server';
2
+ /** A utility for logging debugging, warning, and error information about the application.
3
+ * Use by importing `log` `@shopify/hydrogen` or by using a `log` prop passed to each page
4
+ * component. Using the latter is ideal, because it will ty your log to the current request in progress.
5
+ */
6
+ export interface Logger {
7
+ trace: (...args: Array<any>) => void;
8
+ debug: (...args: Array<any>) => void;
9
+ warn: (...args: Array<any>) => void;
10
+ error: (...args: Array<any>) => void;
11
+ fatal: (...args: Array<any>) => void;
12
+ }
13
+ export declare function getLoggerFromContext(context: any): Logger;
14
+ export declare function setLogger(newLogger: Logger): void;
15
+ export declare function resetLogger(): void;
16
+ export declare const log: Logger;
17
+ export declare function logServerResponse(type: 'str' | 'rsc' | 'ssr' | 'api', log: Logger, request: ServerComponentRequest, responseStatus: number): void;
@@ -0,0 +1,83 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.logServerResponse = exports.log = exports.resetLogger = exports.setLogger = exports.getLoggerFromContext = void 0;
4
+ const kolorist_1 = require("kolorist");
5
+ const timing_1 = require("../timing");
6
+ const defaultLogger = {
7
+ trace(context, ...args) {
8
+ console.log(...args);
9
+ },
10
+ debug(context, ...args) {
11
+ console.log(...args);
12
+ },
13
+ warn(context, ...args) {
14
+ console.warn((0, kolorist_1.yellow)('WARN: '), ...args);
15
+ },
16
+ error(context, ...args) {
17
+ console.error((0, kolorist_1.red)('ERROR: '), ...args);
18
+ },
19
+ fatal(context, ...args) {
20
+ console.error((0, kolorist_1.red)('FATAL: '), ...args);
21
+ },
22
+ };
23
+ let logger = defaultLogger;
24
+ function getLoggerFromContext(context) {
25
+ return {
26
+ trace: (...args) => logger.trace(context, ...args),
27
+ debug: (...args) => logger.debug(context, ...args),
28
+ warn: (...args) => logger.warn(context, ...args),
29
+ error: (...args) => logger.error(context, ...args),
30
+ fatal: (...args) => logger.fatal(context, ...args),
31
+ };
32
+ }
33
+ exports.getLoggerFromContext = getLoggerFromContext;
34
+ function setLogger(newLogger) {
35
+ logger = newLogger;
36
+ }
37
+ exports.setLogger = setLogger;
38
+ function resetLogger() {
39
+ logger = defaultLogger;
40
+ }
41
+ exports.resetLogger = resetLogger;
42
+ exports.log = {
43
+ trace(...args) {
44
+ return logger.trace({}, ...args);
45
+ },
46
+ debug(...args) {
47
+ return logger.debug({}, ...args);
48
+ },
49
+ warn(...args) {
50
+ return logger.warn({}, ...args);
51
+ },
52
+ error(...args) {
53
+ return logger.error({}, ...args);
54
+ },
55
+ fatal(...args) {
56
+ return logger.fatal({}, ...args);
57
+ },
58
+ };
59
+ const SERVER_RESPONSE_MAP = {
60
+ str: 'streaming SSR',
61
+ rsc: 'server Components',
62
+ ssr: 'buffered SSR',
63
+ };
64
+ function logServerResponse(type, log, request, responseStatus) {
65
+ const coloredResponseStatus = responseStatus >= 500
66
+ ? (0, kolorist_1.red)(responseStatus)
67
+ : responseStatus >= 400
68
+ ? (0, kolorist_1.yellow)(responseStatus)
69
+ : responseStatus >= 300
70
+ ? (0, kolorist_1.lightBlue)(responseStatus)
71
+ : (0, kolorist_1.green)(responseStatus);
72
+ const fullType = SERVER_RESPONSE_MAP[type] || type;
73
+ const styledType = (0, kolorist_1.italic)(pad(fullType, ' '));
74
+ const paddedTiming = pad(((0, timing_1.getTime)() - request.time).toFixed(2) + ' ms', ' ');
75
+ const url = type === 'rsc'
76
+ ? decodeURIComponent(request.url.substring(request.url.indexOf('=') + 1))
77
+ : request.url;
78
+ log.debug(`${request.method} ${styledType} ${coloredResponseStatus} ${paddedTiming} ${url}`);
79
+ }
80
+ exports.logServerResponse = logServerResponse;
81
+ function pad(str, _pad) {
82
+ return (str + _pad).substring(0, _pad.length);
83
+ }
@@ -0,0 +1,10 @@
1
+ import { TokensToRegexpOptions } from 'path-to-regexp';
2
+ interface MatchPathOptions extends TokensToRegexpOptions {
3
+ path?: string;
4
+ exact?: boolean;
5
+ }
6
+ /**
7
+ * Public API for matching a URL pathname to a path.
8
+ */
9
+ export declare function matchPath(pathname: string, options?: MatchPathOptions): any;
10
+ export {};
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.matchPath = void 0;
4
+ const path_to_regexp_1 = require("path-to-regexp");
5
+ // Modified from React Router v5
6
+ // https://github.com/remix-run/react-router/blob/v5/packages/react-router/modules/matchPath.js
7
+ const cache = {};
8
+ const cacheLimit = 10000;
9
+ let cacheCount = 0;
10
+ function compilePath(path, options) {
11
+ const cacheKey = `${options.end}${options.strict}${options.sensitive}`;
12
+ const pathCache = cache[cacheKey] || (cache[cacheKey] = {});
13
+ if (pathCache[path])
14
+ return pathCache[path];
15
+ const keys = [];
16
+ const regexp = (0, path_to_regexp_1.pathToRegexp)(path, keys, options);
17
+ const result = { regexp, keys };
18
+ if (cacheCount < cacheLimit) {
19
+ pathCache[path] = result;
20
+ cacheCount++;
21
+ }
22
+ return result;
23
+ }
24
+ /**
25
+ * Public API for matching a URL pathname to a path.
26
+ */
27
+ function matchPath(pathname, options = {}) {
28
+ const { path, exact = false, strict = false, sensitive = false } = options;
29
+ const paths = [].concat(path);
30
+ return paths.reduce((matched, path) => {
31
+ if (!path && path !== '')
32
+ return null;
33
+ if (matched)
34
+ return matched;
35
+ const { regexp, keys } = compilePath(path, {
36
+ end: exact,
37
+ strict,
38
+ sensitive,
39
+ });
40
+ const match = regexp.exec(pathname);
41
+ if (!match)
42
+ return null;
43
+ const [url, ...values] = match;
44
+ const isExact = pathname === url;
45
+ if (exact && !isExact)
46
+ return null;
47
+ return {
48
+ path,
49
+ url: path === '/' && url === '' ? '/' : url,
50
+ isExact,
51
+ params: keys.reduce((memo, key, index) => {
52
+ memo[key.name] = values[index];
53
+ return memo;
54
+ }, {}),
55
+ };
56
+ }, null);
57
+ }
58
+ exports.matchPath = matchPath;
@@ -1 +1 @@
1
- export declare const LIB_VERSION = "0.8.3";
1
+ export declare const LIB_VERSION = "0.9.0";
@@ -1,4 +1,4 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.LIB_VERSION = void 0;
4
- exports.LIB_VERSION = '0.8.3';
4
+ exports.LIB_VERSION = '0.9.0';
@@ -15,6 +15,9 @@ export class ServerComponentRequest extends Request {
15
15
  super(getUrlFromNodeRequest(input), {
16
16
  headers: new Headers(input.headers),
17
17
  method: input.method,
18
+ body: input.method !== 'GET' && input.method !== 'HEAD'
19
+ ? input.body
20
+ : undefined,
18
21
  });
19
22
  }
20
23
  this.time = getTime();
@@ -1,6 +1,7 @@
1
1
  import { getCacheControlHeader } from './framework/cache';
2
2
  import { setContext, setCache } from './framework/runtime';
3
3
  import { setConfig } from './framework/config';
4
+ import { renderApiRoute } from './utilities/apiRoutes';
4
5
  export default async function handleEvent(event, { request, entrypoint, indexTemplate, assetHandler, streamableResponse, dev, cache, context, }) {
5
6
  var _a, _b, _c, _d, _e;
6
7
  const url = new URL(request.url);
@@ -21,12 +22,21 @@ export default async function handleEvent(event, { request, entrypoint, indexTem
21
22
  assetHandler) {
22
23
  return assetHandler(event, url);
23
24
  }
24
- const { render, hydrate, stream } = entrypoint.default || entrypoint;
25
+ const { render, hydrate, stream, getApiRoute, log } = entrypoint.default || entrypoint;
25
26
  // @ts-ignore
26
- if (dev && !(render && hydrate && stream)) {
27
+ if (dev && !(render && hydrate && stream && getApiRoute)) {
27
28
  throw new Error(`entry-server.jsx could not be loaded. This likely occurred because of a Vite compilation error.\n` +
28
29
  `Please check your server logs for more information.`);
29
30
  }
31
+ if (!isReactHydrationRequest) {
32
+ const apiRoute = getApiRoute(url);
33
+ // The API Route might have a default export, making it also a server component
34
+ // If it does, only render the API route if the request method is GET
35
+ if (apiRoute &&
36
+ (!apiRoute.hasServerComponent || request.method !== 'GET')) {
37
+ return renderApiRoute(request, apiRoute, log);
38
+ }
39
+ }
30
40
  const userAgent = request.headers.get('user-agent');
31
41
  const isStreamable = streamableResponse && !isBotUA(url, userAgent);
32
42
  /**
@@ -3,6 +3,8 @@ import { ServerResponse } from 'http';
3
3
  import type { ServerComponentResponse } from './framework/Hydration/ServerComponentResponse.server';
4
4
  import type { ServerComponentRequest } from './framework/Hydration/ServerComponentRequest.server';
5
5
  import type { Metafield, Image, MediaContentType } from './graphql/types/types';
6
+ import { ApiRouteMatch } from './utilities/apiRoutes';
7
+ import { Logger } from './utilities/log/log';
6
8
  export declare type Renderer = (url: URL, options: {
7
9
  request: ServerComponentRequest;
8
10
  context?: Record<string, any>;
@@ -29,6 +31,8 @@ export declare type EntryServerHandler = {
29
31
  render: Renderer;
30
32
  stream: Streamer;
31
33
  hydrate: Hydrator;
34
+ getApiRoute: (url: URL) => ApiRouteMatch | null;
35
+ log: Logger;
32
36
  };
33
37
  export declare type ShopifyConfig = {
34
38
  locale?: string;
@@ -39,11 +43,11 @@ export declare type ShopifyConfig = {
39
43
  export declare type Hook = (params: {
40
44
  url: URL;
41
45
  } & Record<string, any>) => any | Promise<any>;
42
- export declare type ServerHandler = (App: any, hook?: Hook) => {
43
- render: Renderer;
44
- stream: Streamer;
45
- hydrate: Hydrator;
46
+ export declare type ImportGlobEagerOutput = Record<string, Record<'default' | 'api', any>>;
47
+ export declare type ServerHandlerConfig = {
48
+ pages?: ImportGlobEagerOutput;
46
49
  };
50
+ export declare type ServerHandler = (App: any, config?: ServerHandlerConfig, hook?: Hook) => EntryServerHandler;
47
51
  export declare type ClientHandler = (App: any, hook?: Hook) => Promise<void>;
48
52
  export interface GraphQLConnection<T> {
49
53
  edges?: {
@@ -87,5 +91,6 @@ export interface CacheOptions {
87
91
  }
88
92
  export interface HydrogenVitePluginOptions {
89
93
  devCache?: boolean;
94
+ purgeQueryCacheOnBuild?: boolean;
90
95
  }
91
96
  export {};
@@ -0,0 +1,21 @@
1
+ import { ImportGlobEagerOutput } from '../types';
2
+ import { Logger } from '../utilities/log/log';
3
+ declare type RouteParams = Record<string, string>;
4
+ declare type RequestOptions = {
5
+ params: RouteParams;
6
+ };
7
+ declare type ResourceGetter = (request: Request, requestOptions: RequestOptions) => Promise<Response>;
8
+ interface HydrogenApiRoute {
9
+ path: string;
10
+ resource: ResourceGetter;
11
+ hasServerComponent: boolean;
12
+ }
13
+ export declare type ApiRouteMatch = {
14
+ resource: ResourceGetter;
15
+ hasServerComponent: boolean;
16
+ params: RouteParams;
17
+ };
18
+ export declare function getApiRoutesFromPages(pages: ImportGlobEagerOutput | undefined, topLevelPath?: string): Array<HydrogenApiRoute>;
19
+ export declare function getApiRouteFromURL(url: URL, routes: Array<HydrogenApiRoute>): ApiRouteMatch | null;
20
+ export declare function renderApiRoute(request: Request, route: ApiRouteMatch, log: Logger): Promise<Response>;
21
+ export {};