@salesforce/storefront-next-dev 0.2.0 → 0.3.0-alpha.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 (49) hide show
  1. package/dist/cartridge-services/index.d.ts.map +1 -1
  2. package/dist/cartridge-services/index.js +171 -50
  3. package/dist/cartridge-services/index.js.map +1 -1
  4. package/dist/commands/create-bundle.js +12 -11
  5. package/dist/commands/create-instructions.js +7 -5
  6. package/dist/commands/create-storefront.js +18 -22
  7. package/dist/commands/deploy-cartridge.js +67 -26
  8. package/dist/commands/dev.js +6 -4
  9. package/dist/commands/extensions/create.js +2 -0
  10. package/dist/commands/extensions/install.js +3 -7
  11. package/dist/commands/extensions/list.js +2 -0
  12. package/dist/commands/extensions/remove.js +3 -7
  13. package/dist/commands/generate-cartridge.js +23 -2
  14. package/dist/commands/preview.js +15 -10
  15. package/dist/commands/push.js +25 -19
  16. package/dist/commands/validate-cartridge.js +51 -0
  17. package/dist/config.js +74 -47
  18. package/dist/configs/react-router.config.d.ts.map +1 -1
  19. package/dist/configs/react-router.config.js +36 -0
  20. package/dist/configs/react-router.config.js.map +1 -1
  21. package/dist/dependency-utils.js +14 -16
  22. package/dist/entry/server.d.ts.map +1 -1
  23. package/dist/entry/server.js +221 -11
  24. package/dist/entry/server.js.map +1 -1
  25. package/dist/generate-cartridge.js +106 -50
  26. package/dist/index.d.ts +127 -13
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +1147 -167
  29. package/dist/index.js.map +1 -1
  30. package/dist/local-dev-setup.js +13 -13
  31. package/dist/logger/index.d.ts +20 -0
  32. package/dist/logger/index.d.ts.map +1 -0
  33. package/dist/logger/index.js +69 -0
  34. package/dist/logger/index.js.map +1 -0
  35. package/dist/logger.js +79 -33
  36. package/dist/logger2.js +1 -0
  37. package/dist/manage-extensions.js +7 -13
  38. package/dist/mrt/ssr.mjs +60 -72
  39. package/dist/mrt/ssr.mjs.map +1 -1
  40. package/dist/mrt/streamingHandler.mjs +66 -78
  41. package/dist/mrt/streamingHandler.mjs.map +1 -1
  42. package/dist/react-router/Scripts.d.ts +1 -1
  43. package/dist/react-router/Scripts.d.ts.map +1 -1
  44. package/dist/react-router/Scripts.js +38 -2
  45. package/dist/react-router/Scripts.js.map +1 -1
  46. package/dist/server.js +296 -16
  47. package/dist/utils.js +4 -4
  48. package/dist/validate-cartridge.js +45 -0
  49. package/package.json +22 -5
@@ -4,7 +4,7 @@ import * as react_jsx_runtime0 from "react/jsx-runtime";
4
4
  //#region src/react-router/Scripts.d.ts
5
5
 
6
6
  /**
7
- * Enhanced Scripts component that wraps React Router's Scripts component with Odyssey-specific functionality.
7
+ * Enhanced Scripts component that wraps React Router's Scripts component with Storefront Next-specific functionality.
8
8
  *
9
9
  * This component extends the standard React Router Scripts component by injecting additional
10
10
  * bundle configuration scripts during server-side rendering. It ensures that bundle metadata
@@ -1 +1 @@
1
- {"version":3,"file":"Scripts.d.ts","names":[],"sources":["../../src/react-router/Scripts.tsx"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAoFgB,OAAA,QAAe,KAAA,CAAM,sBAAsB,aAAmB,kBAAA,CAAA,GAAA,CAAA"}
1
+ {"version":3,"file":"Scripts.d.ts","names":[],"sources":["../../src/react-router/Scripts.tsx"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAuFgB,OAAA,QAAe,KAAA,CAAM,sBAAsB,aAAmB,kBAAA,CAAA,GAAA,CAAA"}
@@ -1,6 +1,40 @@
1
1
  import { Scripts as Scripts$1 } from "react-router";
2
2
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
3
3
 
4
+ //#region src/utils/paths.ts
5
+ /**
6
+ * Get the configurable base path for the application.
7
+ * Reads from MRT_ENV_BASE_PATH environment variable.
8
+ *
9
+ * The base path is used for CDN routing to the correct MRT environment.
10
+ * It is prepended to all URLs: page routes, /mobify/bundle/ assets, and /mobify/proxy/api.
11
+ *
12
+ * Validation rules:
13
+ * - Must be a single path segment starting with '/'
14
+ * - Max 63 characters after the leading slash
15
+ * - Only URL-safe characters allowed
16
+ * - Returns empty string if not set
17
+ *
18
+ * @returns The sanitized base path (e.g., '/site-a' or '')
19
+ *
20
+ * @example
21
+ * // No base path configured
22
+ * getBasePath() // → ''
23
+ *
24
+ * // With base path '/storefront'
25
+ * getBasePath() // → '/storefront'
26
+ *
27
+ * // Automatically sanitizes
28
+ * // MRT_ENV_BASE_PATH='storefront/' → '/storefront'
29
+ */
30
+ function getBasePath() {
31
+ const basePath = process.env.MRT_ENV_BASE_PATH?.trim();
32
+ if (!basePath) return "";
33
+ if (!/^\/[a-zA-Z0-9_.+$~"'@:-]{1,63}$/.test(basePath)) throw new Error(`Invalid base path: "${basePath}". Base path must be a single segment starting with '/' (e.g., '/site-a'), contain only URL-safe characters, and be at most 63 characters after the leading slash.`);
34
+ return basePath;
35
+ }
36
+
37
+ //#endregion
4
38
  //#region src/react-router/Scripts.tsx
5
39
  /**
6
40
  * Determines if the code is running in a server-side rendering (SSR) environment.
@@ -23,17 +57,19 @@ const isSSR = typeof window === "undefined";
23
57
  const InternalServerScripts = () => {
24
58
  if (!isSSR) return null;
25
59
  const bundleId = process.env.BUNDLE_ID || "local";
26
- const bundlePath = `/mobify/bundle/${bundleId}/client/`;
60
+ const basePath = getBasePath();
61
+ const bundlePath = `${basePath}/mobify/bundle/${bundleId}/client/`;
27
62
  return /* @__PURE__ */ jsx("script", {
28
63
  id: "sf-next-bundle-config",
29
64
  dangerouslySetInnerHTML: { __html: `
30
65
  window._BUNDLE_ID = ${JSON.stringify(bundleId)};
31
66
  window._BUNDLE_PATH = ${JSON.stringify(bundlePath)};
67
+ window._BASE_PATH = ${JSON.stringify(basePath)};
32
68
  ` }
33
69
  });
34
70
  };
35
71
  /**
36
- * Enhanced Scripts component that wraps React Router's Scripts component with Odyssey-specific functionality.
72
+ * Enhanced Scripts component that wraps React Router's Scripts component with Storefront Next-specific functionality.
37
73
  *
38
74
  * This component extends the standard React Router Scripts component by injecting additional
39
75
  * bundle configuration scripts during server-side rendering. It ensures that bundle metadata
@@ -1 +1 @@
1
- {"version":3,"file":"Scripts.js","names":["ReactRouterScripts"],"sources":["../../src/react-router/Scripts.tsx"],"sourcesContent":["/**\n * Copyright 2026 Salesforce, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Scripts as ReactRouterScripts } from 'react-router';\n\n/**\n * Determines if the code is running in a server-side rendering (SSR) environment.\n * Returns true when window is undefined (server), false otherwise (client).\n */\nconst isSSR = typeof window === 'undefined';\n\n/**\n * Internal component that injects bundle configuration scripts during server-side rendering.\n *\n * This component renders a script tag that sets up global bundle variables on the window object,\n * which are used by the client-side application to locate and load the correct bundle assets.\n *\n * The script defines:\n * - `window._BUNDLE_ID`: The unique identifier for the current bundle (from BUNDLE_ID env var, defaults to 'local')\n * - `window._BUNDLE_PATH`: The path to the client bundle assets (e.g., `/mobify/bundle/{bundleId}/client/`)\n *\n * @returns A script element during SSR, or null during client-side rendering\n * @internal\n */\nconst InternalServerScripts = () => {\n if (!isSSR) {\n return null;\n }\n\n const bundleId = process.env.BUNDLE_ID || 'local';\n const bundlePath = `/mobify/bundle/${bundleId}/client/`;\n return (\n <script\n id=\"sf-next-bundle-config\"\n // eslint-disable-next-line react/no-danger\n dangerouslySetInnerHTML={{\n __html: `\n window._BUNDLE_ID = ${JSON.stringify(bundleId)};\n window._BUNDLE_PATH = ${JSON.stringify(bundlePath)};\n `,\n }}\n />\n );\n};\n\n/**\n * Enhanced Scripts component that wraps React Router's Scripts component with Odyssey-specific functionality.\n *\n * This component extends the standard React Router Scripts component by injecting additional\n * bundle configuration scripts during server-side rendering. It ensures that bundle metadata\n * (ID and path) are available on the client before any other scripts execute.\n *\n * Usage:\n * ```tsx\n * import { Outlet, Scripts } from 'react-router';\n *\n * export default function Root() {\n * return (\n * <html>\n * <head>...</head>\n * <body>\n * <Outlet />\n * <Scripts />\n * </body>\n * </html>\n * );\n * }\n * ```\n *\n * @param props - Props passed through to the underlying React Router Scripts component\n * @returns A fragment containing internal bundle scripts and React Router scripts\n */\nexport function Scripts(props: React.ComponentProps<typeof ReactRouterScripts>) {\n return (\n <>\n <InternalServerScripts />\n <ReactRouterScripts {...props} />\n </>\n );\n}\n"],"mappings":";;;;;;;;AAqBA,MAAM,QAAQ,OAAO,WAAW;;;;;;;;;;;;;;AAehC,MAAM,8BAA8B;AAChC,KAAI,CAAC,MACD,QAAO;CAGX,MAAM,WAAW,QAAQ,IAAI,aAAa;CAC1C,MAAM,aAAa,kBAAkB,SAAS;AAC9C,QACI,oBAAC;EACG,IAAG;EAEH,yBAAyB,EACrB,QAAQ;8BACM,KAAK,UAAU,SAAS,CAAC;gCACvB,KAAK,UAAU,WAAW,CAAC;OAE9C;GACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BV,SAAgB,QAAQ,OAAwD;AAC5E,QACI,4CACI,oBAAC,0BAAwB,EACzB,oBAACA,aAAmB,GAAI,QAAS,IAClC"}
1
+ {"version":3,"file":"Scripts.js","names":["ReactRouterScripts"],"sources":["../../src/utils/paths.ts","../../src/react-router/Scripts.tsx"],"sourcesContent":["/**\n * Copyright 2026 Salesforce, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Normalize a file path to use forward slashes.\n * On Windows, Node APIs return backslash-separated paths, but ESM import\n * specifiers and Vite module IDs require forward slashes.\n */\nexport function toPosixPath(filePath: string): string {\n return filePath.replace(/\\\\/g, '/');\n}\n\n/**\n * Get the Commerce Cloud API URL from a short code\n */\nexport function getCommerceCloudApiUrl(shortCode: string, proxyHost?: string): string {\n return proxyHost || `https://${shortCode}.api.commercecloud.salesforce.com`;\n}\n\n/**\n * Get the configurable base path for the application.\n * Reads from MRT_ENV_BASE_PATH environment variable.\n *\n * The base path is used for CDN routing to the correct MRT environment.\n * It is prepended to all URLs: page routes, /mobify/bundle/ assets, and /mobify/proxy/api.\n *\n * Validation rules:\n * - Must be a single path segment starting with '/'\n * - Max 63 characters after the leading slash\n * - Only URL-safe characters allowed\n * - Returns empty string if not set\n *\n * @returns The sanitized base path (e.g., '/site-a' or '')\n *\n * @example\n * // No base path configured\n * getBasePath() // → ''\n *\n * // With base path '/storefront'\n * getBasePath() // → '/storefront'\n *\n * // Automatically sanitizes\n * // MRT_ENV_BASE_PATH='storefront/' → '/storefront'\n */\nexport function getBasePath(): string {\n const basePath = process.env.MRT_ENV_BASE_PATH?.trim();\n\n // Return empty string if not set or empty\n if (!basePath) {\n return '';\n }\n\n // Base path prefix must be a single path segment starting with '/', max 63 chars,\n // using only URL-safe characters (alphanumeric, hyphens, underscores, dots, and other safe symbols)\n // This aligns with the regex used by MRT\n if (!/^\\/[a-zA-Z0-9_.+$~\"'@:-]{1,63}$/.test(basePath)) {\n throw new Error(\n `Invalid base path: \"${basePath}\". ` +\n \"Base path must be a single segment starting with '/' (e.g., '/site-a'), \" +\n 'contain only URL-safe characters, and be at most 63 characters after the leading slash.'\n );\n }\n\n return basePath;\n}\n\n/**\n * Get the bundle path for static assets\n */\nexport function getBundlePath(bundleId: string): string {\n const basePath = getBasePath();\n return `${basePath}/mobify/bundle/${bundleId}/client/`;\n}\n","/**\n * Copyright 2026 Salesforce, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Scripts as ReactRouterScripts } from 'react-router';\nimport { getBasePath } from '../utils/paths';\n\n/**\n * Determines if the code is running in a server-side rendering (SSR) environment.\n * Returns true when window is undefined (server), false otherwise (client).\n */\nconst isSSR = typeof window === 'undefined';\n\n/**\n * Internal component that injects bundle configuration scripts during server-side rendering.\n *\n * This component renders a script tag that sets up global bundle variables on the window object,\n * which are used by the client-side application to locate and load the correct bundle assets.\n *\n * The script defines:\n * - `window._BUNDLE_ID`: The unique identifier for the current bundle (from BUNDLE_ID env var, defaults to 'local')\n * - `window._BUNDLE_PATH`: The path to the client bundle assets (e.g., `/mobify/bundle/{bundleId}/client/`)\n *\n * @returns A script element during SSR, or null during client-side rendering\n * @internal\n */\nconst InternalServerScripts = () => {\n if (!isSSR) {\n return null;\n }\n\n const bundleId = process.env.BUNDLE_ID || 'local';\n const basePath = getBasePath();\n const bundlePath = `${basePath}/mobify/bundle/${bundleId}/client/`;\n return (\n <script\n id=\"sf-next-bundle-config\"\n // eslint-disable-next-line react/no-danger\n dangerouslySetInnerHTML={{\n __html: `\n window._BUNDLE_ID = ${JSON.stringify(bundleId)};\n window._BUNDLE_PATH = ${JSON.stringify(bundlePath)};\n window._BASE_PATH = ${JSON.stringify(basePath)};\n `,\n }}\n />\n );\n};\n\n/**\n * Enhanced Scripts component that wraps React Router's Scripts component with Storefront Next-specific functionality.\n *\n * This component extends the standard React Router Scripts component by injecting additional\n * bundle configuration scripts during server-side rendering. It ensures that bundle metadata\n * (ID and path) are available on the client before any other scripts execute.\n *\n * Usage:\n * ```tsx\n * import { Outlet, Scripts } from 'react-router';\n *\n * export default function Root() {\n * return (\n * <html>\n * <head>...</head>\n * <body>\n * <Outlet />\n * <Scripts />\n * </body>\n * </html>\n * );\n * }\n * ```\n *\n * @param props - Props passed through to the underlying React Router Scripts component\n * @returns A fragment containing internal bundle scripts and React Router scripts\n */\nexport function Scripts(props: React.ComponentProps<typeof ReactRouterScripts>) {\n return (\n <>\n <InternalServerScripts />\n <ReactRouterScripts {...props} />\n </>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,SAAgB,cAAsB;CAClC,MAAM,WAAW,QAAQ,IAAI,mBAAmB,MAAM;AAGtD,KAAI,CAAC,SACD,QAAO;AAMX,KAAI,CAAC,kCAAkC,KAAK,SAAS,CACjD,OAAM,IAAI,MACN,uBAAuB,SAAS,oKAGnC;AAGL,QAAO;;;;;;;;;ACrDX,MAAM,QAAQ,OAAO,WAAW;;;;;;;;;;;;;;AAehC,MAAM,8BAA8B;AAChC,KAAI,CAAC,MACD,QAAO;CAGX,MAAM,WAAW,QAAQ,IAAI,aAAa;CAC1C,MAAM,WAAW,aAAa;CAC9B,MAAM,aAAa,GAAG,SAAS,iBAAiB,SAAS;AACzD,QACI,oBAAC;EACG,IAAG;EAEH,yBAAyB,EACrB,QAAQ;8BACM,KAAK,UAAU,SAAS,CAAC;gCACvB,KAAK,UAAU,WAAW,CAAC;8BAC7B,KAAK,UAAU,SAAS,CAAC;OAE1C;GACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BV,SAAgB,QAAQ,OAAwD;AAC5E,QACI,4CACI,oBAAC,0BAAwB,EACzB,oBAACA,aAAmB,GAAI,QAAS,IAClC"}
package/dist/server.js CHANGED
@@ -1,4 +1,5 @@
1
- import { c as warn, r as info } from "./logger.js";
1
+ import { t as logger } from "./logger.js";
2
+ import { o as loadRuntimeConfig } from "./config.js";
2
3
  import path from "path";
3
4
  import chalk from "chalk";
4
5
  import express from "express";
@@ -11,6 +12,14 @@ import compression from "compression";
11
12
  import zlib from "node:zlib";
12
13
  import morgan from "morgan";
13
14
  import { minimatch } from "minimatch";
15
+ import { SpanStatusCode, context, trace } from "@opentelemetry/api";
16
+ import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
17
+ import { ConsoleSpanExporter, SimpleSpanProcessor } from "@opentelemetry/sdk-trace-base";
18
+ import { ExportResultCode, hrTimeToTimeStamp } from "@opentelemetry/core";
19
+ import { Resource } from "@opentelemetry/resources";
20
+ import { ATTR_SERVICE_NAME } from "@opentelemetry/semantic-conventions";
21
+ import { registerInstrumentations } from "@opentelemetry/instrumentation";
22
+ import { UndiciInstrumentation } from "@opentelemetry/instrumentation-undici";
14
23
 
15
24
  //#region src/server/ts-import.ts
16
25
  /**
@@ -78,18 +87,15 @@ function loadConfigFromEnv() {
78
87
  const shortCode = process.env.PUBLIC__app__commerce__api__shortCode;
79
88
  const organizationId = process.env.PUBLIC__app__commerce__api__organizationId;
80
89
  const clientId = process.env.PUBLIC__app__commerce__api__clientId;
81
- const siteId = process.env.PUBLIC__app__commerce__api__siteId;
82
90
  const proxy = process.env.PUBLIC__app__commerce__api__proxy || "/mobify/proxy/api";
83
91
  const proxyHost = process.env.SCAPI_PROXY_HOST;
84
92
  if (!shortCode && !proxyHost) throw new Error("Missing PUBLIC__app__commerce__api__shortCode environment variable.\nPlease set it in your .env file or environment.");
85
93
  if (!organizationId) throw new Error("Missing PUBLIC__app__commerce__api__organizationId environment variable.\nPlease set it in your .env file or environment.");
86
94
  if (!clientId) throw new Error("Missing PUBLIC__app__commerce__api__clientId environment variable.\nPlease set it in your .env file or environment.");
87
- if (!siteId) throw new Error("Missing PUBLIC__app__commerce__api__siteId environment variable.\nPlease set it in your .env file or environment.");
88
95
  return { commerce: { api: {
89
96
  shortCode: shortCode || "",
90
97
  organizationId,
91
98
  clientId,
92
- siteId,
93
99
  proxy,
94
100
  proxyHost
95
101
  } } };
@@ -115,12 +121,10 @@ async function loadProjectConfig(projectDirectory) {
115
121
  if (!api.shortCode && !proxyHost) throw new Error("Missing shortCode in config.server.ts commerce.api configuration");
116
122
  if (!api.organizationId) throw new Error("Missing organizationId in config.server.ts commerce.api configuration");
117
123
  if (!api.clientId) throw new Error("Missing clientId in config.server.ts commerce.api configuration");
118
- if (!api.siteId) throw new Error("Missing siteId in config.server.ts commerce.api configuration");
119
124
  return { commerce: { api: {
120
125
  shortCode: api.shortCode || "",
121
126
  organizationId: api.organizationId,
122
127
  clientId: api.clientId,
123
- siteId: api.siteId,
124
128
  proxy: api.proxy || "/mobify/proxy/api",
125
129
  proxyHost
126
130
  } } };
@@ -135,10 +139,41 @@ function getCommerceCloudApiUrl(shortCode, proxyHost) {
135
139
  return proxyHost || `https://${shortCode}.api.commercecloud.salesforce.com`;
136
140
  }
137
141
  /**
142
+ * Get the configurable base path for the application.
143
+ * Reads from MRT_ENV_BASE_PATH environment variable.
144
+ *
145
+ * The base path is used for CDN routing to the correct MRT environment.
146
+ * It is prepended to all URLs: page routes, /mobify/bundle/ assets, and /mobify/proxy/api.
147
+ *
148
+ * Validation rules:
149
+ * - Must be a single path segment starting with '/'
150
+ * - Max 63 characters after the leading slash
151
+ * - Only URL-safe characters allowed
152
+ * - Returns empty string if not set
153
+ *
154
+ * @returns The sanitized base path (e.g., '/site-a' or '')
155
+ *
156
+ * @example
157
+ * // No base path configured
158
+ * getBasePath() // → ''
159
+ *
160
+ * // With base path '/storefront'
161
+ * getBasePath() // → '/storefront'
162
+ *
163
+ * // Automatically sanitizes
164
+ * // MRT_ENV_BASE_PATH='storefront/' → '/storefront'
165
+ */
166
+ function getBasePath() {
167
+ const basePath = process.env.MRT_ENV_BASE_PATH?.trim();
168
+ if (!basePath) return "";
169
+ if (!/^\/[a-zA-Z0-9_.+$~"'@:-]{1,63}$/.test(basePath)) throw new Error(`Invalid base path: "${basePath}". Base path must be a single segment starting with '/' (e.g., '/site-a'), contain only URL-safe characters, and be at most 63 characters after the leading slash.`);
170
+ return basePath;
171
+ }
172
+ /**
138
173
  * Get the bundle path for static assets
139
174
  */
140
175
  function getBundlePath(bundleId) {
141
- return `/mobify/bundle/${bundleId}/client/`;
176
+ return `${getBasePath()}/mobify/bundle/${bundleId}/client/`;
142
177
  }
143
178
 
144
179
  //#endregion
@@ -164,7 +199,7 @@ function createCommerceProxyMiddleware(config) {
164
199
  function createStaticMiddleware(bundleId, projectDirectory) {
165
200
  const bundlePath = getBundlePath(bundleId);
166
201
  const clientBuildDir = path.join(projectDirectory, "build", "client");
167
- info(`Serving static assets from ${clientBuildDir} at ${bundlePath}`);
202
+ logger.info(`Serving static assets from ${clientBuildDir} at ${bundlePath}`);
168
203
  return express.static(clientBuildDir, { setHeaders: (res) => {
169
204
  res.setHeader("Cache-Control", "public, max-age=31536000, immutable");
170
205
  res.setHeader("x-local-static-cache-control", "1");
@@ -183,7 +218,7 @@ function getCompressionLevel() {
183
218
  if (raw == null || raw.trim() === "") return DEFAULT;
184
219
  const level = Number(raw);
185
220
  if (!(Number.isInteger(level) && level >= 0 && level <= 9)) {
186
- warn(`[compression] Invalid COMPRESSION_LEVEL="${raw}". Using default (${DEFAULT}).`);
221
+ logger.warn(`[compression] Invalid COMPRESSION_LEVEL="${raw}". Using default (${DEFAULT}).`);
187
222
  return DEFAULT;
188
223
  }
189
224
  return level;
@@ -247,9 +282,7 @@ function createLoggingMiddleware() {
247
282
  });
248
283
  return morgan((tokens, req, res) => {
249
284
  return [
250
- chalk.gray("["),
251
285
  tokens["method-colored"](req, res),
252
- chalk.gray("]"),
253
286
  tokens.url(req, res),
254
287
  "-",
255
288
  tokens["status-colored"](req, res),
@@ -301,11 +334,13 @@ function createHostHeaderMiddleware() {
301
334
  */
302
335
  function patchReactRouterBuild(build, bundleId) {
303
336
  const bundlePath = getBundlePath(bundleId);
337
+ const basePath = getBasePath();
304
338
  const patchedAssetsJson = JSON.stringify(build.assets).replace(/"\/assets\//g, `"${bundlePath}assets/`);
305
339
  const newAssets = JSON.parse(patchedAssetsJson);
306
340
  return Object.assign({}, build, {
307
341
  publicPath: bundlePath,
308
- assets: newAssets
342
+ assets: newAssets,
343
+ ...basePath && { basename: basePath }
309
344
  });
310
345
  }
311
346
 
@@ -338,6 +373,225 @@ const ServerModeFeatureMap = {
338
373
  }
339
374
  };
340
375
 
376
+ //#endregion
377
+ //#region src/otel/mrt-console-span-exporter.ts
378
+ var MrtConsoleSpanExporter = class extends ConsoleSpanExporter {
379
+ export(spans, resultCallback) {
380
+ for (const span of spans) try {
381
+ const ctx = span.spanContext();
382
+ const spanData = {
383
+ traceId: ctx.traceId,
384
+ parentId: span.parentSpanId,
385
+ name: span.name,
386
+ id: ctx.spanId,
387
+ kind: span.kind,
388
+ timestamp: hrTimeToTimeStamp(span.startTime),
389
+ duration: span.duration,
390
+ attributes: span.attributes,
391
+ status: span.status,
392
+ events: span.events,
393
+ links: span.links,
394
+ start_time: span.startTime,
395
+ end_time: span.endTime,
396
+ forwardTrace: process.env.SFNEXT_OTEL_ENABLED === "true"
397
+ };
398
+ console.info(JSON.stringify(spanData));
399
+ } catch {}
400
+ resultCallback({ code: ExportResultCode.SUCCESS });
401
+ }
402
+ };
403
+
404
+ //#endregion
405
+ //#region src/otel/setup.ts
406
+ const SERVICE_NAME = "storefront-next";
407
+ /**
408
+ * Initializes OpenTelemetry and returns a Tracer from the provider directly.
409
+ *
410
+ * Returns the tracer via `provider.getTracer()` instead of the global
411
+ * `trace.getTracer()` API. In the Vite SSR module runner, the built
412
+ * dist/entry/server.js and the externalized @opentelemetry/sdk-trace-node
413
+ * resolve @opentelemetry/api to different module instances (different paths
414
+ * through pnpm's strict node_modules). Each instance has its own
415
+ * ProxyTracerProvider singleton, so `provider.register()` sets the delegate
416
+ * on sdk-trace-node's API instance while our code's `trace.getTracer()`
417
+ * reads from a separate API instance with no delegate — returning a tracer
418
+ * backed by a bare BasicTracerProvider with NoopSpanProcessor.
419
+ *
420
+ * Getting the tracer directly from the provider bypasses the global registry
421
+ * entirely, guaranteeing the tracer uses our configured span processors.
422
+ */
423
+ let cachedTracer = null;
424
+ const UNDICI_REGISTERED_KEY = Symbol.for("sfnext.otel.undici_registered");
425
+ function initTelemetry() {
426
+ if (cachedTracer) return cachedTracer;
427
+ try {
428
+ const provider = new NodeTracerProvider({ resource: new Resource({ [ATTR_SERVICE_NAME]: SERVICE_NAME }) });
429
+ provider.addSpanProcessor(new SimpleSpanProcessor(new MrtConsoleSpanExporter()));
430
+ provider.register();
431
+ if (!globalThis[UNDICI_REGISTERED_KEY]) {
432
+ globalThis[UNDICI_REGISTERED_KEY] = true;
433
+ registerInstrumentations({
434
+ tracerProvider: provider,
435
+ instrumentations: [new UndiciInstrumentation({ requestHook(span, request) {
436
+ try {
437
+ const method = request.method.toUpperCase();
438
+ const url = `${request.origin}${request.path}`;
439
+ span.updateName(`${method} ${url}`);
440
+ } catch {}
441
+ } })]
442
+ });
443
+ }
444
+ cachedTracer = provider.getTracer(SERVICE_NAME);
445
+ return cachedTracer;
446
+ } catch (error) {
447
+ logger.error("[otel] Failed to initialize OpenTelemetry:", error);
448
+ return null;
449
+ }
450
+ }
451
+
452
+ //#endregion
453
+ //#region src/otel/express/middleware.ts
454
+ function createOtelExpressMiddleware() {
455
+ const maybeTracer = initTelemetry();
456
+ if (!maybeTracer) return (_req, _res, next) => next();
457
+ const tracer = maybeTracer;
458
+ return (req, res, next) => {
459
+ try {
460
+ const url = new URL(req.originalUrl || req.url, "http://localhost").pathname;
461
+ const method = req.method;
462
+ tracer.startActiveSpan(`[sfnext] server ${method} ${url}`, { attributes: {
463
+ "http.request.method": method,
464
+ "url.path": url
465
+ } }, (serverSpan) => {
466
+ try {
467
+ const spanContext = trace.getSpan(context.active())?.spanContext();
468
+ if (spanContext) {
469
+ const flags = spanContext.traceFlags.toString(16).padStart(2, "0");
470
+ const traceparent = `00-${spanContext.traceId}-${spanContext.spanId}-${flags}`;
471
+ res.setHeader("traceparent", traceparent);
472
+ }
473
+ } catch {}
474
+ const serverCtx = context.active();
475
+ const startTime = performance.now();
476
+ let streamingSpan = null;
477
+ let ttfbMs = 0;
478
+ let ended = false;
479
+ function recordTTFB() {
480
+ if (streamingSpan) return;
481
+ try {
482
+ ttfbMs = Math.round(performance.now() - startTime);
483
+ serverSpan.setAttribute("sfnext.ttfb_ms", ttfbMs);
484
+ streamingSpan = tracer.startSpan(`[sfnext] response streaming ${method} ${url}`, { attributes: {
485
+ "http.request.method": method,
486
+ "url.path": url,
487
+ "sfnext.ttfb_ms": ttfbMs
488
+ } }, serverCtx);
489
+ } catch {}
490
+ }
491
+ const origWriteHead = res.writeHead.bind(res);
492
+ res.writeHead = ((...args) => {
493
+ recordTTFB();
494
+ return origWriteHead(...args);
495
+ });
496
+ const origWrite = res.write.bind(res);
497
+ res.write = ((...args) => {
498
+ recordTTFB();
499
+ return origWrite(...args);
500
+ });
501
+ function endSpans() {
502
+ if (ended) return;
503
+ ended = true;
504
+ try {
505
+ const totalMs = Math.round(performance.now() - startTime);
506
+ const statusCode = res.statusCode;
507
+ if (streamingSpan) {
508
+ streamingSpan.setAttribute("http.streaming_duration_ms", totalMs - ttfbMs);
509
+ streamingSpan.setAttribute("http.response.status_code", statusCode);
510
+ if (statusCode >= 500) streamingSpan.setStatus({ code: SpanStatusCode.ERROR });
511
+ streamingSpan.end();
512
+ }
513
+ serverSpan.setAttribute("http.response.status_code", statusCode);
514
+ serverSpan.setAttribute("http.total_duration_ms", totalMs);
515
+ if (statusCode >= 500) serverSpan.setStatus({ code: SpanStatusCode.ERROR });
516
+ serverSpan.end();
517
+ } catch {}
518
+ }
519
+ res.once("close", endSpans);
520
+ res.once("finish", endSpans);
521
+ next();
522
+ });
523
+ } catch {
524
+ next();
525
+ }
526
+ };
527
+ }
528
+
529
+ //#endregion
530
+ //#region src/server/handlers/health-check.ts
531
+ const DEFAULT_HEALTH_DESCRIPTION = "storefront-next-dev server health";
532
+ const PACKAGE_JSON_NAME = "package.json";
533
+ const RUNTIME_PACKAGE_NAME = "@salesforce/storefront-next-runtime";
534
+ const DEV_PACKAGE_NAME = "@salesforce/storefront-next-dev";
535
+ const BUILD_FOLDER_NAME = "build";
536
+ const LOCAL_BUNDLE_ID = "local";
537
+ const HEALTH_ENDPOINT_PATH = "/sfdc-health";
538
+ /**
539
+ * Reads a package.json file and returns selected metadata.
540
+ *
541
+ * @param path - Absolute path to a package.json file
542
+ * @returns Parsed metadata, or null if missing/unreadable
543
+ *
544
+ * @example
545
+ * ```ts
546
+ * const metadata = readPackageMetadata('/app/package.json');
547
+ * console.log(metadata?.version);
548
+ * ```
549
+ */
550
+ function readPackageMetadata(path$1) {
551
+ if (!existsSync(path$1)) return null;
552
+ try {
553
+ return JSON.parse(readFileSync(path$1, "utf8"));
554
+ } catch (error) {
555
+ logger.debug(`Health check: failed to parse package.json at ${path$1}`, error);
556
+ return null;
557
+ }
558
+ }
559
+ /**
560
+ * Creates an Express handler that returns Health+JSON for the project.
561
+ *
562
+ * @param options - Handler options
563
+ * @returns Express request handler for the health endpoint
564
+ *
565
+ * @example
566
+ * ```ts
567
+ * app.get(HEALTH_ENDPOINT_PATH, createHealthCheckHandler({
568
+ * projectDirectory: process.cwd(),
569
+ * bundleId: LOCAL_BUNDLE_ID,
570
+ * }));
571
+ * ```
572
+ */
573
+ function createHealthCheckHandler(options) {
574
+ const { projectDirectory, bundleId } = options;
575
+ const projectPackage = readPackageMetadata(bundleId === LOCAL_BUNDLE_ID ? resolve(projectDirectory, PACKAGE_JSON_NAME) : resolve(projectDirectory, BUILD_FOLDER_NAME, PACKAGE_JSON_NAME));
576
+ const allDependencies = {
577
+ ...projectPackage?.dependencies,
578
+ ...projectPackage?.devDependencies
579
+ };
580
+ const devVersion = allDependencies?.[DEV_PACKAGE_NAME];
581
+ const runtimeVersion = allDependencies?.[RUNTIME_PACKAGE_NAME];
582
+ const notes = [devVersion ? `Built using ${DEV_PACKAGE_NAME}@${devVersion}.` : null, runtimeVersion ? `Running ${RUNTIME_PACKAGE_NAME}@${runtimeVersion}.` : null].filter(Boolean);
583
+ return (_req, res) => {
584
+ const healthResponse = {
585
+ status: "pass",
586
+ version: projectPackage?.version,
587
+ bundleId,
588
+ description: projectPackage?.description ?? DEFAULT_HEALTH_DESCRIPTION,
589
+ notes: notes.length > 0 ? notes : void 0
590
+ };
591
+ res.status(200).type("application/health+json").json(healthResponse);
592
+ };
593
+ }
594
+
341
595
  //#endregion
342
596
  //#region src/server/index.ts
343
597
  /** Relative path to the middleware registry TypeScript source (development). Must match appDirectory + server dir + filename used by buildMiddlewareRegistry plugin. */
@@ -350,6 +604,20 @@ const MIDDLEWARE_REGISTRY_BUILT_EXTENSIONS = [
350
604
  ];
351
605
  /** All paths to try when loading the built middlewares (base + extension). */
352
606
  const RELATIVE_MIDDLEWARE_REGISTRY_BUILT_PATHS = ["bld/server/middleware-registry", "build/server/middleware-registry"].flatMap((base) => MIDDLEWARE_REGISTRY_BUILT_EXTENSIONS.map((ext) => `${base}${ext}`));
607
+ const DEFAULT_BUNDLE_ID = "local";
608
+ /**
609
+ * Load MRT_ENV_BASE_PATH from config.server.ts so getBasePath() works in local dev/preview.
610
+ * On MRT production, this env var is already set by the Lambda from ssrParameters.envBasePath.
611
+ *
612
+ * In dev mode this must be called before Vite starts, since the React Router preset
613
+ * reads getBasePath() at config time to set the basename.
614
+ *
615
+ * @param projectDirectory - Project root directory
616
+ */
617
+ async function initBasePathEnv(projectDirectory) {
618
+ const runtimeConfig = await loadRuntimeConfig(projectDirectory);
619
+ if (runtimeConfig?.ssrParameters?.envBasePath) process.env.MRT_ENV_BASE_PATH = String(runtimeConfig.ssrParameters.envBasePath);
620
+ }
353
621
  /**
354
622
  * Create a unified Express server for development, preview, or production mode
355
623
  */
@@ -358,9 +626,14 @@ async function createServer(options) {
358
626
  if (mode === "development" && !vite) throw new Error("Vite dev server instance is required for development mode");
359
627
  if ((mode === "preview" || mode === "production") && !build) throw new Error("React Router server build is required for preview/production mode");
360
628
  const config = providedConfig ?? loadConfigFromEnv();
361
- const bundleId = process.env.BUNDLE_ID ?? "local";
629
+ const bundleId = process.env.BUNDLE_ID ?? DEFAULT_BUNDLE_ID;
362
630
  const app = express();
363
631
  app.disable("x-powered-by");
632
+ if (process.env.SFNEXT_OTEL_ENABLED === "true") app.use(createOtelExpressMiddleware());
633
+ app.get(HEALTH_ENDPOINT_PATH, createHealthCheckHandler({
634
+ projectDirectory,
635
+ bundleId
636
+ }));
364
637
  if (enableLogging) app.use(createLoggingMiddleware());
365
638
  if (enableCompression && !streaming) app.use(createCompressionMiddleware());
366
639
  if (enableStaticServing && build) {
@@ -385,8 +658,14 @@ async function createServer(options) {
385
658
  });
386
659
  if (mode === "development" && vite) app.use(vite.middlewares);
387
660
  if (enableProxy) app.use(config.commerce.api.proxy, createCommerceProxyMiddleware(config));
661
+ const basePath = getBasePath();
662
+ if (basePath) app.use((req, res, next) => {
663
+ if (req.path.startsWith(`${basePath}/`) || req.path === basePath) return next();
664
+ if (req.path.startsWith("/mobify/")) return next();
665
+ res.redirect(`${basePath}${req.originalUrl}`);
666
+ });
388
667
  app.use(createHostHeaderMiddleware());
389
- app.all("*", await createSSRHandler(mode, bundleId, vite, build, enableAssetUrlPatching));
668
+ app.all("*splat", await createSSRHandler(mode, bundleId, vite, build, enableAssetUrlPatching));
390
669
  return app;
391
670
  }
392
671
  /**
@@ -414,12 +693,13 @@ async function createSSRHandler(mode, bundleId, vite, build, enableAssetUrlPatch
414
693
  } else if (build) {
415
694
  let patchedBuild = build;
416
695
  if (enableAssetUrlPatching) patchedBuild = patchReactRouterBuild(build, bundleId);
696
+ const requestHandlerMode = process.env.NODE_OPTIONS?.includes("--enable-source-maps") ? "development" : process.env.NODE_ENV;
417
697
  return createRequestHandler({
418
698
  build: patchedBuild,
419
- mode: process.env.NODE_ENV
699
+ mode: requestHandlerMode
420
700
  });
421
701
  } else throw new Error("Invalid server configuration: no vite or build provided");
422
702
  }
423
703
 
424
704
  //#endregion
425
- export { getCommerceCloudApiUrl as n, loadProjectConfig as r, createServer as t };
705
+ export { loadProjectConfig as i, initBasePathEnv as n, getCommerceCloudApiUrl as r, createServer as t };
package/dist/utils.js CHANGED
@@ -1,4 +1,4 @@
1
- import { c as warn, t as debug } from "./logger.js";
1
+ import { t as logger } from "./logger.js";
2
2
  import { execSync } from "child_process";
3
3
  import os from "os";
4
4
  import path from "path";
@@ -25,7 +25,7 @@ const getProjectPkg = (projectDir) => {
25
25
  const loadEnvFile = (projectDir) => {
26
26
  const envPath = path.join(projectDir, ".env");
27
27
  if (fs.existsSync(envPath)) dotenv.config({ path: envPath });
28
- else warn("No .env file found");
28
+ else logger.warn("No .env file found");
29
29
  };
30
30
  /**
31
31
  * Get MRT configuration with priority logic: .env -> package.json -> defaults
@@ -36,7 +36,7 @@ const getMrtConfig = (projectDir) => {
36
36
  const defaultMrtProject = process.env.MRT_PROJECT ?? pkg.name;
37
37
  if (!defaultMrtProject || defaultMrtProject.trim() === "") throw new Error("Project name couldn't be determined. Do one of these options:\n 1. Set MRT_PROJECT in your .env file, or\n 2. Ensure package.json has a valid \"name\" field.");
38
38
  const defaultMrtTarget = process.env.MRT_TARGET ?? void 0;
39
- debug("MRT configuration resolved", {
39
+ logger.debug("MRT configuration resolved", {
40
40
  projectDir,
41
41
  envMrtProject: process.env.MRT_PROJECT,
42
42
  envMrtTarget: process.env.MRT_TARGET,
@@ -95,7 +95,7 @@ const getDefaultMessage = (projectDir) => {
95
95
  cwd: projectDir
96
96
  }).trim()}`;
97
97
  } catch {
98
- debug("Using default bundle message as no message was provided and not in a Git repo.");
98
+ logger.debug("Using default bundle message as no message was provided and not in a Git repo.");
99
99
  return "PWA Kit Bundle";
100
100
  }
101
101
  };
@@ -0,0 +1,45 @@
1
+ import path from "path";
2
+ import { glob } from "glob";
3
+ import { MetaDefinitionDetectionError, validateMetaDefinitionFile } from "@salesforce/b2c-tooling-sdk/operations/content";
4
+
5
+ //#region src/cartridge-services/validate-cartridge.ts
6
+ /**
7
+ * Validate all Page Designer metadata JSON files in a directory.
8
+ *
9
+ * Globs for `**\/*.json` in `metadataDir`, validates each file against
10
+ * the appropriate metadefinition schema, and returns a summary.
11
+ *
12
+ * Files whose schema type cannot be detected are skipped and reported
13
+ * in `skippedFiles`.
14
+ */
15
+ async function validateCartridgeMetadata(metadataDir) {
16
+ const filePaths = await glob("**/*.json", {
17
+ cwd: metadataDir,
18
+ absolute: true,
19
+ nodir: true
20
+ });
21
+ const results = [];
22
+ const skippedFiles = [];
23
+ for (const filePath of filePaths) try {
24
+ const result = validateMetaDefinitionFile(filePath);
25
+ results.push(result);
26
+ } catch (error) {
27
+ if (error instanceof MetaDefinitionDetectionError) {
28
+ skippedFiles.push(path.relative(metadataDir, filePath));
29
+ continue;
30
+ }
31
+ throw error;
32
+ }
33
+ const totalErrors = results.reduce((sum, r) => sum + r.errors.length, 0);
34
+ const validFiles = results.filter((r) => r.valid).length;
35
+ return {
36
+ results,
37
+ totalFiles: results.length,
38
+ validFiles,
39
+ totalErrors,
40
+ skippedFiles
41
+ };
42
+ }
43
+
44
+ //#endregion
45
+ export { validateCartridgeMetadata as t };