@ikas/component-cli 1.4.0-beta.19 → 1.4.0-beta.190

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 (176) hide show
  1. package/dist/build-tools.d.ts +37 -0
  2. package/dist/build-tools.d.ts.map +1 -0
  3. package/dist/build-tools.js +36 -0
  4. package/dist/build-tools.js.map +1 -0
  5. package/dist/commands/add-sections-to-page.d.ts +3 -0
  6. package/dist/commands/add-sections-to-page.d.ts.map +1 -0
  7. package/dist/commands/add-sections-to-page.js +39 -0
  8. package/dist/commands/add-sections-to-page.js.map +1 -0
  9. package/dist/commands/add.d.ts.map +1 -1
  10. package/dist/commands/add.js +11 -2
  11. package/dist/commands/add.js.map +1 -1
  12. package/dist/commands/build.d.ts.map +1 -1
  13. package/dist/commands/build.js +5 -165
  14. package/dist/commands/build.js.map +1 -1
  15. package/dist/commands/config.d.ts +35 -0
  16. package/dist/commands/config.d.ts.map +1 -1
  17. package/dist/commands/config.js +1021 -122
  18. package/dist/commands/config.js.map +1 -1
  19. package/dist/commands/create-design-tokens.d.ts +24 -0
  20. package/dist/commands/create-design-tokens.d.ts.map +1 -0
  21. package/dist/commands/create-design-tokens.js +327 -0
  22. package/dist/commands/create-design-tokens.js.map +1 -0
  23. package/dist/commands/create-global-variable.d.ts +3 -0
  24. package/dist/commands/create-global-variable.d.ts.map +1 -0
  25. package/dist/commands/create-global-variable.js +53 -0
  26. package/dist/commands/create-global-variable.js.map +1 -0
  27. package/dist/commands/create-page.d.ts +3 -0
  28. package/dist/commands/create-page.d.ts.map +1 -0
  29. package/dist/commands/create-page.js +31 -0
  30. package/dist/commands/create-page.js.map +1 -0
  31. package/dist/commands/delete-page.d.ts +3 -0
  32. package/dist/commands/delete-page.d.ts.map +1 -0
  33. package/dist/commands/delete-page.js +28 -0
  34. package/dist/commands/delete-page.js.map +1 -0
  35. package/dist/commands/delete-theme-globals.d.ts +4 -0
  36. package/dist/commands/delete-theme-globals.d.ts.map +1 -0
  37. package/dist/commands/delete-theme-globals.js +48 -0
  38. package/dist/commands/delete-theme-globals.js.map +1 -0
  39. package/dist/commands/dev.d.ts.map +1 -1
  40. package/dist/commands/dev.js +208 -31
  41. package/dist/commands/dev.js.map +1 -1
  42. package/dist/commands/enable-builtin-pages.d.ts +3 -0
  43. package/dist/commands/enable-builtin-pages.d.ts.map +1 -0
  44. package/dist/commands/enable-builtin-pages.js +27 -0
  45. package/dist/commands/enable-builtin-pages.js.map +1 -0
  46. package/dist/commands/get-component-props.d.ts +3 -0
  47. package/dist/commands/get-component-props.d.ts.map +1 -0
  48. package/dist/commands/get-component-props.js +32 -0
  49. package/dist/commands/get-component-props.js.map +1 -0
  50. package/dist/commands/get-page-by-type.d.ts +3 -0
  51. package/dist/commands/get-page-by-type.d.ts.map +1 -0
  52. package/dist/commands/get-page-by-type.js +25 -0
  53. package/dist/commands/get-page-by-type.js.map +1 -0
  54. package/dist/commands/get-section-values.d.ts +3 -0
  55. package/dist/commands/get-section-values.d.ts.map +1 -0
  56. package/dist/commands/get-section-values.js +39 -0
  57. package/dist/commands/get-section-values.js.map +1 -0
  58. package/dist/commands/list-builtin-pages.d.ts +3 -0
  59. package/dist/commands/list-builtin-pages.d.ts.map +1 -0
  60. package/dist/commands/list-builtin-pages.js +28 -0
  61. package/dist/commands/list-builtin-pages.js.map +1 -0
  62. package/dist/commands/list-entities.d.ts +3 -0
  63. package/dist/commands/list-entities.d.ts.map +1 -0
  64. package/dist/commands/list-entities.js +32 -0
  65. package/dist/commands/list-entities.js.map +1 -0
  66. package/dist/commands/list-page-sections.d.ts.map +1 -1
  67. package/dist/commands/list-page-sections.js +8 -2
  68. package/dist/commands/list-page-sections.js.map +1 -1
  69. package/dist/commands/list-theme-globals.d.ts +3 -0
  70. package/dist/commands/list-theme-globals.d.ts.map +1 -0
  71. package/dist/commands/list-theme-globals.js +22 -0
  72. package/dist/commands/list-theme-globals.js.map +1 -0
  73. package/dist/commands/move-page-section.d.ts +3 -0
  74. package/dist/commands/move-page-section.d.ts.map +1 -0
  75. package/dist/commands/move-page-section.js +62 -0
  76. package/dist/commands/move-page-section.js.map +1 -0
  77. package/dist/commands/publish-theme.d.ts +3 -0
  78. package/dist/commands/publish-theme.d.ts.map +1 -0
  79. package/dist/commands/publish-theme.js +29 -0
  80. package/dist/commands/publish-theme.js.map +1 -0
  81. package/dist/commands/publish.d.ts.map +1 -1
  82. package/dist/commands/publish.js +54 -3
  83. package/dist/commands/publish.js.map +1 -1
  84. package/dist/commands/remove-page-section.d.ts +3 -0
  85. package/dist/commands/remove-page-section.d.ts.map +1 -0
  86. package/dist/commands/remove-page-section.js +40 -0
  87. package/dist/commands/remove-page-section.js.map +1 -0
  88. package/dist/commands/search-products.d.ts +3 -0
  89. package/dist/commands/search-products.d.ts.map +1 -0
  90. package/dist/commands/search-products.js +40 -0
  91. package/dist/commands/search-products.js.map +1 -0
  92. package/dist/commands/update-builtin-page-prop.d.ts +3 -0
  93. package/dist/commands/update-builtin-page-prop.d.ts.map +1 -0
  94. package/dist/commands/update-builtin-page-prop.js +49 -0
  95. package/dist/commands/update-builtin-page-prop.js.map +1 -0
  96. package/dist/commands/update-global-variable.d.ts +3 -0
  97. package/dist/commands/update-global-variable.d.ts.map +1 -0
  98. package/dist/commands/update-global-variable.js +47 -0
  99. package/dist/commands/update-global-variable.js.map +1 -0
  100. package/dist/commands/update-page-sections.d.ts +3 -0
  101. package/dist/commands/update-page-sections.d.ts.map +1 -0
  102. package/dist/commands/update-page-sections.js +39 -0
  103. package/dist/commands/update-page-sections.js.map +1 -0
  104. package/dist/commands/update-section-prop.d.ts.map +1 -1
  105. package/dist/commands/update-section-prop.js +27 -9
  106. package/dist/commands/update-section-prop.js.map +1 -1
  107. package/dist/commands/upload-image.d.ts.map +1 -1
  108. package/dist/commands/upload-image.js +5 -46
  109. package/dist/commands/upload-image.js.map +1 -1
  110. package/dist/commands/upload-images.d.ts +3 -0
  111. package/dist/commands/upload-images.d.ts.map +1 -0
  112. package/dist/commands/upload-images.js +48 -0
  113. package/dist/commands/upload-images.js.map +1 -0
  114. package/dist/index.d.ts.map +1 -1
  115. package/dist/index.js +54 -1
  116. package/dist/index.js.map +1 -1
  117. package/dist/types.d.ts +45 -0
  118. package/dist/types.d.ts.map +1 -1
  119. package/dist/utils/archive-project.d.ts +56 -0
  120. package/dist/utils/archive-project.d.ts.map +1 -0
  121. package/dist/utils/archive-project.js +136 -0
  122. package/dist/utils/archive-project.js.map +1 -0
  123. package/dist/utils/compile.d.ts +17 -2
  124. package/dist/utils/compile.d.ts.map +1 -1
  125. package/dist/utils/compile.js +746 -117
  126. package/dist/utils/compile.js.map +1 -1
  127. package/dist/utils/component-helpers.d.ts +128 -2
  128. package/dist/utils/component-helpers.d.ts.map +1 -1
  129. package/dist/utils/component-helpers.js +330 -27
  130. package/dist/utils/component-helpers.js.map +1 -1
  131. package/dist/utils/css-import-resolver.d.ts +4 -1
  132. package/dist/utils/css-import-resolver.d.ts.map +1 -1
  133. package/dist/utils/css-import-resolver.js +9 -1
  134. package/dist/utils/css-import-resolver.js.map +1 -1
  135. package/dist/utils/editor-action-client.d.ts +4 -3
  136. package/dist/utils/editor-action-client.d.ts.map +1 -1
  137. package/dist/utils/editor-action-client.js +55 -19
  138. package/dist/utils/editor-action-client.js.map +1 -1
  139. package/dist/utils/esm-transform.d.ts +30 -0
  140. package/dist/utils/esm-transform.d.ts.map +1 -1
  141. package/dist/utils/esm-transform.js +169 -2
  142. package/dist/utils/esm-transform.js.map +1 -1
  143. package/dist/utils/find-component-for-file.d.ts +12 -0
  144. package/dist/utils/find-component-for-file.d.ts.map +1 -0
  145. package/dist/utils/find-component-for-file.js +24 -0
  146. package/dist/utils/find-component-for-file.js.map +1 -0
  147. package/dist/utils/forbid-deep-imports.d.ts +3 -0
  148. package/dist/utils/forbid-deep-imports.d.ts.map +1 -0
  149. package/dist/utils/forbid-deep-imports.js +54 -0
  150. package/dist/utils/forbid-deep-imports.js.map +1 -0
  151. package/dist/utils/forbid-external-packages.d.ts +26 -0
  152. package/dist/utils/forbid-external-packages.d.ts.map +1 -0
  153. package/dist/utils/forbid-external-packages.js +99 -0
  154. package/dist/utils/forbid-external-packages.js.map +1 -0
  155. package/dist/utils/load-image.d.ts +16 -0
  156. package/dist/utils/load-image.d.ts.map +1 -0
  157. package/dist/utils/load-image.js +50 -0
  158. package/dist/utils/load-image.js.map +1 -0
  159. package/dist/utils/vendor-storefront.d.ts +13 -0
  160. package/dist/utils/vendor-storefront.d.ts.map +1 -0
  161. package/dist/utils/vendor-storefront.js +91 -0
  162. package/dist/utils/vendor-storefront.js.map +1 -0
  163. package/dist/utils/websocket-server.d.ts +113 -5
  164. package/dist/utils/websocket-server.d.ts.map +1 -1
  165. package/dist/utils/websocket-server.js +247 -43
  166. package/dist/utils/websocket-server.js.map +1 -1
  167. package/package.json +19 -2
  168. package/templates/add/section.css +11 -0
  169. package/dist/commands/create.d.ts +0 -4
  170. package/dist/commands/create.d.ts.map +0 -1
  171. package/dist/commands/create.js +0 -228
  172. package/dist/commands/create.js.map +0 -1
  173. package/dist/commands/proxy.d.ts +0 -39
  174. package/dist/commands/proxy.d.ts.map +0 -1
  175. package/dist/commands/proxy.js +0 -210
  176. package/dist/commands/proxy.js.map +0 -1
@@ -4,34 +4,65 @@ import * as os from "os";
4
4
  import * as path from "path";
5
5
  import { resolveCssImports } from "./css-import-resolver.js";
6
6
  import { ikasComponentUtilsPlugin } from "./observer-runtime.js";
7
+ import { forbidDeepStorefrontImportsPlugin } from "./forbid-deep-imports.js";
8
+ import { forbidExternalPackagesPlugin } from "./forbid-external-packages.js";
9
+ import { isVendoredDependencyFile, vendorStorefrontPlugin } from "./vendor-storefront.js";
7
10
  /**
8
- * Shim file that tells esbuild `h` and `Fragment` are reserved identifiers.
9
- * Unlike `banner` (which is appended after minification), `inject` is processed
10
- * during compilation so the minifier will never reuse these names.
11
+ * Shim that provides the JSX factory/fragment under collision-proof names.
12
+ *
13
+ * The classic JSX pragma must be a bare identifier in scope. Using `h`/`Fragment`
14
+ * directly means any user-authored local named `h` or `Fragment` (e.g. a `.map`
15
+ * callback param) shadows the factory, so JSX in that scope compiles to a call on
16
+ * the local value → runtime "x is not a function". Aliasing to `__ikas_h` /
17
+ * `__ikas_Fragment` (names users won't write) eliminates that shadowing footgun.
18
+ *
19
+ * Unlike `banner` (appended after minification), `inject` is processed during
20
+ * compilation so the minifier will never reuse these names. The bundled import
21
+ * still references preact's `h`/`Fragment`, so the canvas esm-transform keying off
22
+ * those source export names is unaffected.
11
23
  */
12
24
  const PREACT_JSX_SHIM = path.join(os.tmpdir(), "ikas-preact-jsx-shim.mjs");
13
- fs.writeFileSync(PREACT_JSX_SHIM, 'export{h,Fragment}from"preact";\n');
25
+ fs.writeFileSync(PREACT_JSX_SHIM, 'export{h as __ikas_h,Fragment as __ikas_Fragment}from"preact";\n');
14
26
  /**
15
- * External dependencies - these will be provided by the generated storefront
27
+ * External dependencies - these will be provided by the generated storefront.
28
+ *
29
+ * The `@ikas/bp-storefront*` packages are intentionally NOT listed here: they are externalized
30
+ * by `forbidDeepStorefrontImportsPlugin()` instead, which externalizes the allowed ROOT import
31
+ * and rejects private deep subpaths. (esbuild applies this `external` array before plugin
32
+ * onResolve, so keeping them here would let `/dist/...` deep imports slip through unchecked.)
16
33
  */
17
34
  const SERVER_EXTERNALS = [
18
35
  "preact",
19
36
  "preact/hooks",
20
37
  "preact-render-to-string",
21
- "mobx",
22
- "@ikas/bp-storefront",
23
- "@ikas/bp-storefront-models",
24
- "@ikas/bp-storefront-config",
25
- "@ikas/bp-storefront-api"
38
+ "mobx"
26
39
  ];
27
40
  const CLIENT_EXTERNALS = [
28
41
  "preact",
29
42
  "preact/hooks",
30
- "mobx",
31
- "@ikas/bp-storefront",
32
- "@ikas/bp-storefront-models",
33
- "@ikas/bp-storefront-config"
43
+ "mobx"
34
44
  ];
45
+ /**
46
+ * The server and client builds MUST compile with the SAME esbuild `target` so
47
+ * syntax is lowered identically and code-split shared chunks come out
48
+ * byte-identical (same content hash) on both sides.
49
+ *
50
+ * If the targets diverge (previously server=node18 vs client=es2020), esbuild
51
+ * lowers modern syntax differently: e.g. a class field (`x = 1`, ES2022) stays
52
+ * native on node18 but is down-leveled into a `__publicField` helper on es2020.
53
+ * That helper lands in the shared runtime-helper chunk, so the helper chunk's
54
+ * hash differs between builds — and every chunk that imports it by hashed name
55
+ * (`./chunk-<hash>.js`) diverges too. The result is "server-only" shared chunks
56
+ * with no client twin, which the client-derived `usedSharedModuleIds` never
57
+ * lists, so they get pruned/dropped downstream ("Could not resolve
58
+ * ./chunk-XXXX.js" at SSR build).
59
+ *
60
+ * es2020 is the floor the browser build needs; node18 executes es2020 fine, so
61
+ * both builds use es2020 and produce identical shared chunks. Keep this the
62
+ * single source of truth for both `platform: node` and `platform: browser`
63
+ * builds — do not set per-build `target` overrides.
64
+ */
65
+ const SHARED_BUILD_TARGET = "es2020";
35
66
  /**
36
67
  * Compile a single component's TSX and CSS
37
68
  */
@@ -43,10 +74,14 @@ export async function compileComponent(entryPath, stylesPath, componentId) {
43
74
  entryPoints: [path.resolve(process.cwd(), entryPath)],
44
75
  format: "esm",
45
76
  platform: "node",
46
- target: "node18",
77
+ target: SHARED_BUILD_TARGET,
47
78
  write: false,
48
79
  external: SERVER_EXTERNALS,
49
- plugins: [ikasComponentUtilsPlugin()],
80
+ plugins: [
81
+ forbidDeepStorefrontImportsPlugin(),
82
+ forbidExternalPackagesPlugin(),
83
+ ikasComponentUtilsPlugin(),
84
+ ],
50
85
  });
51
86
  // Build client bundle (for hydration)
52
87
  const clientResult = await esbuild.build({
@@ -54,17 +89,36 @@ export async function compileComponent(entryPath, stylesPath, componentId) {
54
89
  entryPoints: [path.resolve(process.cwd(), entryPath)],
55
90
  format: "esm",
56
91
  platform: "browser",
57
- target: "es2020",
92
+ target: SHARED_BUILD_TARGET,
58
93
  write: false,
59
94
  external: CLIENT_EXTERNALS,
60
- plugins: [ikasComponentUtilsPlugin()],
95
+ // Needed for the sibling-CSS collection below: the input list tells us which
96
+ // sub-component directories this entry actually pulled in.
97
+ metafile: true,
98
+ plugins: [
99
+ forbidDeepStorefrontImportsPlugin(),
100
+ forbidExternalPackagesPlugin(),
101
+ ikasComponentUtilsPlugin(),
102
+ ],
61
103
  });
62
- // Read CSS (with import resolution)
104
+ // Read CSS (with import resolution). Track what the @imports inlined so the
105
+ // sibling pass below cannot append the same file twice.
63
106
  const cssPath = path.resolve(process.cwd(), stylesPath);
107
+ const inlinedCssPaths = new Set();
64
108
  let css = "";
65
109
  if (fs.existsSync(cssPath)) {
66
110
  const rawCss = fs.readFileSync(cssPath, "utf-8");
67
- css = resolveCssImports(rawCss, cssPath);
111
+ css = resolveCssImports(rawCss, cssPath, inlinedCssPaths);
112
+ }
113
+ // Collect each bundled sub-component's sibling styles.css, the same way the
114
+ // multi-component pipeline (`dev`/`publish`) does. Without this, CSS that works
115
+ // under `dev` silently vanishes from a `build` artifact.
116
+ const entryDir = path.dirname(path.resolve(process.cwd(), entryPath));
117
+ for (const depCssPath of collectSourceCssFiles(Object.keys(clientResult.metafile.inputs), entryDir)) {
118
+ if (inlinedCssPaths.has(path.resolve(depCssPath)))
119
+ continue;
120
+ const rawDepCss = fs.readFileSync(depCssPath, "utf-8");
121
+ css += "\n" + resolveCssImports(rawDepCss, depCssPath, inlinedCssPaths);
68
122
  }
69
123
  // Scope CSS
70
124
  const scopedCss = scopeCSS(css, componentId);
@@ -81,16 +135,32 @@ export async function compileComponent(entryPath, stylesPath, componentId) {
81
135
  serverJs: "",
82
136
  clientJs: "",
83
137
  scopedCss: "",
84
- error: error.message || String(error)
138
+ error: withCssImportHint(error.message || String(error))
85
139
  };
86
140
  }
87
141
  }
142
+ // esbuild's raw message when a TSX file does `import "./styles.css"` gives no clue about the
143
+ // ikas conventions; append a hint pointing at the two supported CSS paths.
144
+ function withCssImportHint(message) {
145
+ if (/Cannot import "[^"]*\.css"/.test(message) || /No loader is configured for "\.css" files/.test(message)) {
146
+ return (message +
147
+ "\n\nHint: do not import CSS from TSX. A sub-component's sibling styles.css is collected " +
148
+ "automatically by every command (`dev`, `publish`, `build`) — just leave it next to the " +
149
+ "sub-component. To pull in CSS that has no sibling source file, @import it from the " +
150
+ "parent component's styles.css.");
151
+ }
152
+ return message;
153
+ }
88
154
  /**
89
- * Scope CSS selectors with a component-specific class prefix
155
+ * Scope CSS selectors with a component-specific class prefix, then namespace any
156
+ * document-global CSS identifiers (`@keyframes`, `@font-face` font-family,
157
+ * `@counter-style`) DEFINED in this component so two components — or the host theme —
158
+ * declaring the same name can't collide in the page's global namespace.
90
159
  */
91
160
  export function scopeCSS(css, componentId) {
92
161
  const scopeClass = `cc_${componentId.replace(/[^a-zA-Z0-9]/g, "_")}`;
93
- return scopeCSSWithClasses(css, [scopeClass]);
162
+ const scoped = scopeCSSWithClasses(css, [scopeClass]);
163
+ return renameCollidingGlobals(scoped, `${scopeClass}_`);
94
164
  }
95
165
  /**
96
166
  * Scope CSS selectors with multiple class prefixes (for shared chunks).
@@ -100,63 +170,519 @@ export function scopeCSSMulti(css, componentIds) {
100
170
  const scopeClasses = componentIds.map(id => `cc_${id.replace(/[^a-zA-Z0-9]/g, "_")}`);
101
171
  return scopeCSSWithClasses(css, scopeClasses);
102
172
  }
173
+ // Conditional group at-rules whose blocks nest normal style rules and must be
174
+ // scoped recursively. This is an ALLOWLIST on purpose: at-rules NOT listed here
175
+ // (@keyframes, @font-face, @page, @property, @counter-style, ...) have non-selector
176
+ // bodies — e.g. @keyframes contains `0%`/`from` keyframe selectors that must NOT be
177
+ // prefixed — so their bodies are copied through untouched. Vendor-prefixed conditional
178
+ // rules (@-moz-document) match via the optional prefix group; @-webkit-keyframes does
179
+ // NOT match (the alternation excludes "keyframes"), which is what we want.
180
+ //
181
+ // NOTE: This scoper is duplicated in editor-models/src/helpers/code-component-css-scope.ts
182
+ // (the editor-preview / code-generator path). The CLI ships standalone to npm and cannot
183
+ // import that private package, so the two intentionally diverge. Keep parsing fixes in sync.
184
+ const NESTING_AT_RULES = /^@(?:-\w+-)?(media|supports|container|layer|document|scope|starting-style)\b/i;
103
185
  /**
104
- * Internal: scope CSS selectors with one or more scope class prefixes
186
+ * Internal: scope CSS selectors with one or more scope class prefixes.
187
+ *
188
+ * Character-based walker, NOT line-based: a rule's selector list is everything up
189
+ * to its opening `{`, so lists written across multiple lines (`.a,\n.b { ... }`)
190
+ * are scoped as a whole. The previous line-based implementation only scoped the
191
+ * selector fragment sharing a line with `{`, leaving the other selectors unscoped
192
+ * (they either lost the cascade to scoped rules or leaked into other components).
193
+ *
194
+ * Comments, string literals, and `\` escapes are treated as inert spans (via
195
+ * `skipInertSpan`) by every structural scanner, so a `{`, `}`, `;`, or `,` that
196
+ * appears inside a comment / string / escape can never be mistaken for real
197
+ * structure (which would otherwise drop the scope prefix and leak styles globally).
105
198
  */
106
199
  function scopeCSSWithClasses(css, scopeClasses) {
107
- const lines = css.split("\n");
108
- const scopedLines = [];
109
- let inMediaQuery = false;
110
- let keyframesDepth = 0;
111
- for (const line of lines) {
112
- const trimmed = line.trim();
113
- if (!trimmed) {
114
- scopedLines.push(line);
200
+ let out = "";
201
+ for (let i = 0; i < css.length;) {
202
+ const ch = css[i];
203
+ // Copy comments verbatim
204
+ if (ch === "/" && css[i + 1] === "*") {
205
+ const end = css.indexOf("*/", i + 2);
206
+ if (end === -1)
207
+ return out + css.slice(i);
208
+ out += css.slice(i, end + 2);
209
+ i = end + 2;
115
210
  continue;
116
211
  }
117
- if (trimmed.startsWith("@media")) {
118
- inMediaQuery = true;
119
- scopedLines.push(line);
212
+ // Copy whitespace and stray closing braces
213
+ if (/\s/.test(ch) || ch === "}") {
214
+ out += ch;
215
+ i++;
120
216
  continue;
121
217
  }
122
- if (trimmed.startsWith("@keyframes") || trimmed.startsWith("@-webkit-keyframes")) {
123
- keyframesDepth = 1;
124
- scopedLines.push(line);
218
+ if (ch === "@") {
219
+ const headerEnd = findAtRuleHeaderEnd(css, i);
220
+ // Block-less at-rule (@import, @charset, @layer a;, ...) — copy through
221
+ if (headerEnd >= css.length || css[headerEnd] === ";") {
222
+ out += css.slice(i, Math.min(headerEnd + 1, css.length));
223
+ i = headerEnd + 1;
224
+ continue;
225
+ }
226
+ const header = css.slice(i, headerEnd);
227
+ const blockEnd = findBlockEnd(css, headerEnd + 1);
228
+ const body = css.slice(headerEnd + 1, blockEnd);
229
+ const transformed = NESTING_AT_RULES.test(header.trim())
230
+ ? scopeCSSWithClasses(body, scopeClasses)
231
+ : body;
232
+ // Always emit the closing brace: when the source block is unterminated
233
+ // (blockEnd === css.length) this repairs it, so concatenated component CSS
234
+ // can't leak one component's block over the next.
235
+ out += `${header}{${transformed}}`;
236
+ i = blockEnd + 1;
237
+ continue;
238
+ }
239
+ // Normal style rule: selector list runs up to the rule's opening `{`
240
+ const selEnd = findSelectorListEnd(css, i);
241
+ if (selEnd >= css.length) {
242
+ // Trailing content with no block (e.g. a dangling declaration at EOF) — copy through
243
+ out += css.slice(i);
244
+ break;
245
+ }
246
+ if (css[selEnd] === ";") {
247
+ // A stray top-level `;` (or a stray declaration fragment ending in `;`) — not a rule.
248
+ // DROP it. Copying it through is not enough: per the CSS syntax spec a browser folds a
249
+ // stray `;` into the NEXT rule's prelude when consuming a qualified rule, which makes
250
+ // that selector invalid and drops the whole following rule. Dropping the stray token
251
+ // keeps the next rule valid and correctly scoped.
252
+ i = selEnd + 1;
125
253
  continue;
126
254
  }
127
- // Inside @keyframes: track brace depth, pass lines through unscoped
128
- if (keyframesDepth > 0) {
129
- for (const ch of trimmed) {
130
- if (ch === "{")
131
- keyframesDepth++;
132
- else if (ch === "}")
133
- keyframesDepth--;
255
+ if (css[selEnd] === "}") {
256
+ // Content before a stray closing brace — copy through verbatim and let the main loop
257
+ // emit the `}`.
258
+ out += css.slice(i, selEnd);
259
+ i = selEnd;
260
+ continue;
261
+ }
262
+ const selectorList = css.slice(i, selEnd);
263
+ const blockEnd = findBlockEnd(css, selEnd + 1);
264
+ const body = css.slice(selEnd + 1, blockEnd);
265
+ const scopedSelector = splitSelectorList(selectorList)
266
+ .map(s => s.trim())
267
+ .filter(Boolean)
268
+ .flatMap(s => scopeClasses.map(cls => `.${cls} ${s}`))
269
+ .join(", ");
270
+ // Always emit the closing brace (see at-rule branch above for rationale).
271
+ out += `${scopedSelector} {${body}}`;
272
+ i = blockEnd + 1;
273
+ }
274
+ return out;
275
+ }
276
+ /**
277
+ * If an inert span — a `/* ... *\/` comment, a `"..."` / `'...'` string literal, an
278
+ * unquoted `url(...)` token, or a `\x` escape — starts at `s[i]`, return the index just
279
+ * past it; otherwise return -1.
280
+ *
281
+ * Every structural scanner below funnels through this so that delimiters (`{ } ; , ( )`)
282
+ * living inside comments, strings, urls, or escapes are never treated as structure. String
283
+ * scanning honors `\` escapes and stops at a raw newline, matching CSS "bad-string" error
284
+ * recovery (an unterminated string ends at the line break) so a missing quote can't
285
+ * swallow every rule that follows it.
286
+ */
287
+ function skipInertSpan(s, i) {
288
+ const c = s[i];
289
+ if (c === "/" && s[i + 1] === "*") {
290
+ const end = s.indexOf("*/", i + 2);
291
+ return end === -1 ? s.length : end + 2;
292
+ }
293
+ if (c === '"' || c === "'") {
294
+ for (let j = i + 1; j < s.length; j++) {
295
+ const d = s[j];
296
+ if (d === "\\") {
297
+ j++; // escape: skip the next char
298
+ continue;
299
+ }
300
+ if (d === c)
301
+ return j + 1; // closing quote
302
+ if (d === "\n" || d === "\r" || d === "\f")
303
+ return j; // bad-string ends at newline
304
+ }
305
+ return s.length;
306
+ }
307
+ // Unquoted url(...) token: per the CSS tokenizer its content is opaque, so braces,
308
+ // semicolons, and parens inside it must NOT be read as structure (an unbalanced `}` in
309
+ // `url(x}y.png)` or `{` in an inline SVG data-uri would otherwise mis-terminate the
310
+ // enclosing block). A QUOTED url (`url("...")`) is a normal function + string and is left
311
+ // to the string branch above. `url` must be a standalone ident, not the tail of a longer
312
+ // identifier like `myurl(`.
313
+ if ((c === "u" || c === "U") && /^url\(/i.test(s.slice(i, i + 4))) {
314
+ const prev = i > 0 ? s[i - 1] : "";
315
+ if (!/[A-Za-z0-9_-]/.test(prev)) {
316
+ let j = i + 4;
317
+ while (j < s.length && /\s/.test(s[j]))
318
+ j++; // optional leading whitespace
319
+ if (s[j] !== '"' && s[j] !== "'") {
320
+ for (; j < s.length; j++) {
321
+ if (s[j] === "\\") {
322
+ j++; // escaped char inside the url (e.g. `url(foo\)bar)`)
323
+ continue;
324
+ }
325
+ if (s[j] === ")")
326
+ return j + 1; // end of url token
327
+ }
328
+ return s.length; // unterminated url() — consume to EOF (bad-url)
329
+ }
330
+ }
331
+ }
332
+ if (c === "\\")
333
+ return i + 2; // escaped char outside a string (e.g. `.a\,b`)
334
+ return -1;
335
+ }
336
+ /** Find the first top-level `{` or `;` that ends an at-rule's header. Respects `()` / `[]`
337
+ * and inert spans (strings/comments/escapes). */
338
+ function findAtRuleHeaderEnd(css, start) {
339
+ let pDepth = 0;
340
+ for (let j = start; j < css.length;) {
341
+ const skip = skipInertSpan(css, j);
342
+ if (skip !== -1) {
343
+ j = skip;
344
+ continue;
345
+ }
346
+ const c = css[j];
347
+ if (c === "(" || c === "[")
348
+ pDepth++;
349
+ else if (c === ")" || c === "]")
350
+ pDepth--;
351
+ else if (pDepth === 0 && (c === "{" || c === ";"))
352
+ return j;
353
+ j++;
354
+ }
355
+ return css.length;
356
+ }
357
+ /**
358
+ * Find the matching `}` for the block whose body starts at `blockStart` (char after `{`).
359
+ * Inert spans are skipped so braces inside `content: "}"`, comments, or escapes don't
360
+ * terminate the block early.
361
+ */
362
+ function findBlockEnd(css, blockStart) {
363
+ let depth = 1;
364
+ for (let j = blockStart; j < css.length;) {
365
+ const skip = skipInertSpan(css, j);
366
+ if (skip !== -1) {
367
+ j = skip;
368
+ continue;
369
+ }
370
+ const c = css[j];
371
+ if (c === "{")
372
+ depth++;
373
+ else if (c === "}") {
374
+ depth--;
375
+ if (depth === 0)
376
+ return j;
377
+ }
378
+ j++;
379
+ }
380
+ return css.length;
381
+ }
382
+ /** Find the `{`, `}`, or `;` that terminates a selector list. A `}` or `;` here means the
383
+ * run was not a real style rule. Respects `()` / `[]` and inert spans. */
384
+ function findSelectorListEnd(css, start) {
385
+ let pDepth = 0;
386
+ for (let j = start; j < css.length;) {
387
+ const skip = skipInertSpan(css, j);
388
+ if (skip !== -1) {
389
+ j = skip;
390
+ continue;
391
+ }
392
+ const c = css[j];
393
+ if (c === "(" || c === "[")
394
+ pDepth++;
395
+ else if (c === ")" || c === "]")
396
+ pDepth--;
397
+ else if (pDepth === 0 && (c === "{" || c === "}" || c === ";"))
398
+ return j;
399
+ j++;
400
+ }
401
+ return css.length;
402
+ }
403
+ /** Split a selector list on top-level commas. Respects `()` / `[]` and inert spans, so a
404
+ * comma inside a comment, string, or `\` escape (e.g. `.a\,b`) does not split the list. */
405
+ function splitSelectorList(s) {
406
+ const result = [];
407
+ let depth = 0;
408
+ let start = 0;
409
+ for (let i = 0; i < s.length;) {
410
+ const skip = skipInertSpan(s, i);
411
+ if (skip !== -1) {
412
+ i = skip;
413
+ continue;
414
+ }
415
+ const ch = s[i];
416
+ if (ch === "(" || ch === "[")
417
+ depth++;
418
+ else if (ch === ")" || ch === "]")
419
+ depth--;
420
+ else if (ch === "," && depth === 0) {
421
+ result.push(s.slice(start, i));
422
+ start = i + 1;
423
+ }
424
+ i++;
425
+ }
426
+ result.push(s.slice(start));
427
+ return result;
428
+ }
429
+ /* ============================================================================
430
+ * Global-identifier namespacing.
431
+ *
432
+ * `@keyframes`, `@font-face` font-family names, and `@counter-style` names live in a
433
+ * DOCUMENT-GLOBAL namespace — scoping selectors with `.cc_<id>` does not isolate them, so
434
+ * two components (or the theme) defining the same name would collide (last definition wins
435
+ * document-wide). `renameCollidingGlobals` prefixes every such name DEFINED in this CSS,
436
+ * plus its references within the SAME CSS, with the component's scope prefix.
437
+ *
438
+ * Only names defined in THIS css are renamed — a reference to a name defined elsewhere
439
+ * (global.css, a shared chunk, the theme) is left untouched, so cross-file references keep
440
+ * resolving. Shared-chunk CSS (scopeCSSMulti) is intentionally NOT renamed, to avoid
441
+ * breaking a chunk-defined keyframe referenced from a consuming component's own CSS.
442
+ *
443
+ * NOTE: ported from packages/editor-models/src/helpers/code-component-css-scope.ts
444
+ * (renameCollidingGlobals + helpers, the global.css path's `cc_<projectId>_` variant).
445
+ * Keep parsing/rename fixes in sync between the two.
446
+ * ============================================================================ */
447
+ // Declarations whose VALUE may reference a global identifier of the given type.
448
+ const KEYFRAME_REF_PROPS = new Set(["animation", "animation-name"]);
449
+ const FONT_FAMILY_REF_PROPS = new Set(["font", "font-family"]);
450
+ const COUNTER_STYLE_REF_PROPS = new Set(["list-style", "list-style-type"]);
451
+ function renameCollidingGlobals(css, prefix) {
452
+ // Comment/string/url-masked copy: defining-site regex scans run against this so a name
453
+ // inside a comment or `content: "..."` string can't contribute a rename or be rewritten.
454
+ const scanCss = maskInertSpans(css);
455
+ const keyframeNames = new Set();
456
+ const fontFamilyNames = new Set();
457
+ const counterStyleNames = new Set();
458
+ let out = css;
459
+ out = out.replace(/@keyframes(\s+)([\w-]+)/g, (m, ws, name, offset) => {
460
+ if (scanCss.substr(offset, 10) !== "@keyframes")
461
+ return m;
462
+ keyframeNames.add(name);
463
+ return `@keyframes${ws}${prefix}${name}`;
464
+ });
465
+ out = out.replace(/@counter-style(\s+)([\w-]+)/g, (m, ws, name, offset) => {
466
+ if (scanCss.substr(offset, 14) !== "@counter-style")
467
+ return m;
468
+ counterStyleNames.add(name);
469
+ return `@counter-style${ws}${prefix}${name}`;
470
+ });
471
+ out = rewriteFontFaceBlocks(out, fontFamilyNames, prefix);
472
+ if (keyframeNames.size === 0 && fontFamilyNames.size === 0 && counterStyleNames.size === 0) {
473
+ return out;
474
+ }
475
+ return rewriteDeclarationReferences(out, keyframeNames, fontFamilyNames, counterStyleNames, prefix);
476
+ }
477
+ /** Replace every inert span (comment / string / url() / escape) with equal-length spaces so
478
+ * position-based regex scans still align but can't match tokens hidden inside them. */
479
+ function maskInertSpans(css) {
480
+ let out = "";
481
+ for (let i = 0; i < css.length;) {
482
+ const skip = skipInertSpan(css, i);
483
+ if (skip !== -1) {
484
+ out += " ".repeat(skip - i);
485
+ i = skip;
486
+ continue;
487
+ }
488
+ out += css[i];
489
+ i++;
490
+ }
491
+ return out;
492
+ }
493
+ function rewriteFontFaceBlocks(css, collect, prefix) {
494
+ const matches = [];
495
+ css.replace(/@font-face\s*\{/g, (m, offset) => {
496
+ matches.push({ index: offset, length: m.length });
497
+ return m;
498
+ });
499
+ if (matches.length === 0)
500
+ return css;
501
+ let out = "";
502
+ let lastIdx = 0;
503
+ for (const match of matches) {
504
+ const openBraceIdx = match.index + match.length - 1;
505
+ if (openBraceIdx < lastIdx)
506
+ continue;
507
+ const endIdx = findBlockEnd(css, openBraceIdx + 1);
508
+ const before = css.slice(lastIdx, openBraceIdx + 1);
509
+ const body = css.slice(openBraceIdx + 1, endIdx);
510
+ const rewrittenBody = body.replace(/(font-family\s*:\s*)(?:"([^"]+)"|'([^']+)'|([\w-]+))/i, (_m, pre, dq, sq, bare) => {
511
+ const name = dq || sq || bare;
512
+ if (!name)
513
+ return _m;
514
+ collect.add(name);
515
+ const prefixed = `${prefix}${name}`;
516
+ if (dq)
517
+ return `${pre}"${prefixed}"`;
518
+ if (sq)
519
+ return `${pre}'${prefixed}'`;
520
+ return `${pre}${prefixed}`;
521
+ });
522
+ out += before + rewrittenBody + "}";
523
+ lastIdx = endIdx + 1;
524
+ }
525
+ out += css.slice(lastIdx);
526
+ return out;
527
+ }
528
+ function rewriteDeclarationReferences(css, keyframeNames, fontFamilyNames, counterStyleNames, prefix) {
529
+ const keyframeRe = buildBareIdentRegex(keyframeNames);
530
+ const fontFamilyRe = buildFontFamilyValueRegex(fontFamilyNames);
531
+ const counterStyleRe = buildBareIdentRegex(counterStyleNames);
532
+ // counter(<name>, <style>?) / counters(<name>, <string>, <style>?) — the counter-style
533
+ // identifier, when present, is always the LAST optional argument.
534
+ const counterFnRe = counterStyleNames.size > 0
535
+ ? new RegExp(`(\\bcounters?\\([^)]*?,\\s*)(${bareUnion(counterStyleNames)})(\\s*\\))`, "gi")
536
+ : null;
537
+ return mapRuleBlocks(css, block => {
538
+ return mapDeclarations(block, (prop, value) => {
539
+ let v = value;
540
+ const lower = prop.toLowerCase();
541
+ if (keyframeRe && KEYFRAME_REF_PROPS.has(lower)) {
542
+ v = v.replace(keyframeRe, m => `${prefix}${m}`);
543
+ }
544
+ if (fontFamilyRe && FONT_FAMILY_REF_PROPS.has(lower)) {
545
+ v = v.replace(fontFamilyRe, (m, dq, sq, bare) => {
546
+ const name = dq || sq || bare;
547
+ if (!name || !fontFamilyNames.has(name))
548
+ return m;
549
+ if (dq !== undefined)
550
+ return `"${prefix}${name}"`;
551
+ if (sq !== undefined)
552
+ return `'${prefix}${name}'`;
553
+ return `${prefix}${name}`;
554
+ });
555
+ }
556
+ if (counterStyleRe && COUNTER_STYLE_REF_PROPS.has(lower)) {
557
+ v = v.replace(counterStyleRe, m => `${prefix}${m}`);
134
558
  }
135
- scopedLines.push(line);
559
+ if (counterFnRe) {
560
+ v = v.replace(counterFnRe, (_m, pre, name, post) => `${pre}${prefix}${name}${post}`);
561
+ }
562
+ return v;
563
+ });
564
+ });
565
+ }
566
+ function bareUnion(names) {
567
+ return Array.from(names).map(escapeRegex).join("|");
568
+ }
569
+ function buildBareIdentRegex(names) {
570
+ if (names.size === 0)
571
+ return null;
572
+ return new RegExp(`(?<![\\w-])(?:${bareUnion(names)})(?![\\w-])`, "g");
573
+ }
574
+ function buildFontFamilyValueRegex(names) {
575
+ if (names.size === 0)
576
+ return null;
577
+ const u = bareUnion(names);
578
+ return new RegExp(`"(${u})"|'(${u})'|(?<![\\w-])(${u})(?![\\w-])`, "g");
579
+ }
580
+ function escapeRegex(s) {
581
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
582
+ }
583
+ /**
584
+ * Walk every top-level rule block `{ ... }` (recursing into nested at-rule contents) and
585
+ * pass the block body through `transform`. Inert spans are skipped so a `{` inside a string
586
+ * or `url(a{b)` is not mistaken for a block. At-rule preambles and inter-rule whitespace
587
+ * are left untouched.
588
+ */
589
+ function mapRuleBlocks(css, transform) {
590
+ let out = "";
591
+ for (let i = 0; i < css.length;) {
592
+ const skip = skipInertSpan(css, i);
593
+ if (skip !== -1) {
594
+ out += css.slice(i, skip);
595
+ i = skip;
136
596
  continue;
137
597
  }
138
- if (trimmed === "}" && inMediaQuery) {
139
- inMediaQuery = false;
140
- scopedLines.push(line);
598
+ if (css[i] === "{") {
599
+ const blockEnd = findBlockEnd(css, i + 1);
600
+ const body = css.slice(i + 1, blockEnd);
601
+ const processed = hasTopLevelBrace(body) ? mapRuleBlocks(body, transform) : transform(body);
602
+ out += "{" + processed + "}";
603
+ i = blockEnd + 1;
141
604
  continue;
142
605
  }
143
- if (!trimmed.includes("{") || trimmed.startsWith("@")) {
144
- scopedLines.push(line);
606
+ out += css[i];
607
+ i++;
608
+ }
609
+ return out;
610
+ }
611
+ /** Inert-span-aware: true iff a real `{` appears outside comments/strings/url()/escapes. */
612
+ function hasTopLevelBrace(s) {
613
+ for (let i = 0; i < s.length;) {
614
+ const skip = skipInertSpan(s, i);
615
+ if (skip !== -1) {
616
+ i = skip;
145
617
  continue;
146
618
  }
147
- const [selector, rest] = line.split("{");
148
- if (selector && rest !== undefined) {
149
- const scopedSelector = selector
150
- .split(",")
151
- .flatMap((s) => scopeClasses.map(cls => `.${cls} ${s.trim()}`))
152
- .join(", ");
153
- scopedLines.push(`${scopedSelector} {${rest}`);
619
+ if (s[i] === "{")
620
+ return true;
621
+ i++;
622
+ }
623
+ return false;
624
+ }
625
+ /**
626
+ * Split a rule block body into `prop: value` declarations on top-level `;`, apply
627
+ * `transform(prop, value)` to each, and rejoin preserving separators. Inert spans are
628
+ * skipped so a `;` inside a string or `url(a;b)` doesn't split a declaration.
629
+ */
630
+ function mapDeclarations(body, transform) {
631
+ const parts = [];
632
+ let start = 0;
633
+ let pDepth = 0;
634
+ for (let i = 0; i < body.length;) {
635
+ const skip = skipInertSpan(body, i);
636
+ if (skip !== -1) {
637
+ i = skip;
638
+ continue;
639
+ }
640
+ const c = body[i];
641
+ if (c === "(" || c === "[" || c === "{")
642
+ pDepth++;
643
+ else if (c === ")" || c === "]" || c === "}")
644
+ pDepth--;
645
+ else if (c === ";" && pDepth === 0) {
646
+ parts.push(body.slice(start, i));
647
+ start = i + 1;
154
648
  }
155
- else {
156
- scopedLines.push(line);
649
+ i++;
650
+ }
651
+ parts.push(body.slice(start));
652
+ return parts
653
+ .map((part, idx) => {
654
+ const isLast = idx === parts.length - 1;
655
+ const colonIdx = findTopLevelColon(part);
656
+ if (colonIdx === -1)
657
+ return part + (isLast ? "" : ";");
658
+ const valueRaw = part.slice(colonIdx + 1);
659
+ const leading = valueRaw.match(/^\s*/)?.[0] ?? "";
660
+ const trailing = valueRaw.match(/\s*$/)?.[0] ?? "";
661
+ const prop = part.slice(0, colonIdx).trim();
662
+ const value = valueRaw.slice(leading.length, valueRaw.length - trailing.length);
663
+ const transformed = transform(prop, value);
664
+ return part.slice(0, colonIdx) + ":" + leading + transformed + trailing + (isLast ? "" : ";");
665
+ })
666
+ .join("");
667
+ }
668
+ function findTopLevelColon(s) {
669
+ let pDepth = 0;
670
+ for (let i = 0; i < s.length;) {
671
+ const skip = skipInertSpan(s, i);
672
+ if (skip !== -1) {
673
+ i = skip;
674
+ continue;
157
675
  }
676
+ const c = s[i];
677
+ if (c === "(" || c === "[")
678
+ pDepth++;
679
+ else if (c === ")" || c === "]")
680
+ pDepth--;
681
+ else if (c === ":" && pDepth === 0)
682
+ return i;
683
+ i++;
158
684
  }
159
- return scopedLines.join("\n");
685
+ return -1;
160
686
  }
161
687
  /**
162
688
  * Common esbuild options shared between server and client builds
@@ -165,26 +691,60 @@ function commonBuildOptions() {
165
691
  return {
166
692
  bundle: true,
167
693
  jsx: "transform",
168
- jsxFactory: "h",
169
- jsxFragment: "Fragment",
694
+ jsxFactory: "__ikas_h",
695
+ jsxFragment: "__ikas_Fragment",
170
696
  inject: [PREACT_JSX_SHIM],
171
697
  tsconfigRaw: {
172
698
  compilerOptions: {
173
699
  jsx: "react",
174
- jsxFactory: "h",
175
- jsxFragmentFactory: "Fragment"
700
+ jsxFactory: "__ikas_h",
701
+ jsxFragmentFactory: "__ikas_Fragment"
176
702
  }
177
703
  },
178
704
  minify: true,
179
705
  sourcemap: false,
180
706
  };
181
707
  }
708
+ /**
709
+ * What `import.meta.env` becomes in a vendored build.
710
+ *
711
+ * The SDK reads Vite variables (`VITE_BASE_URL`, `VITE_PUBLIC_ANALYTICS_URL`, `VITE_ENV`). While it
712
+ * was external, the theme's own Vite build substituted them. Vendoring compiles it with esbuild
713
+ * instead, and `import.meta` is illegal inside the `new Function` the evaluator uses anyway.
714
+ *
715
+ * They are NOT baked in at publish time, even though that would be simpler. `VITE_BASE_URL` names
716
+ * the ikas API the *theme* talks to; a built-in login that authenticated against a different one
717
+ * would hand back a token the rest of the page cannot use. It has to be whatever the host says it
718
+ * is, so it is read from the host at evaluation time — configuration from the host, code from the
719
+ * build, which is the same line every other decision here follows.
720
+ *
721
+ * A host that never sets this gets a thrown TypeError on first evaluation, caught and reported per
722
+ * component. That is deliberate: the alternative, defaulting to `{}`, would silently produce
723
+ * `undefined/ms/google/login/authenticate` and fail as a confusing 404 much later.
724
+ */
725
+ const VENDORED_IMPORT_META_ENV = "globalThis.__ikasBuiltinEnv";
726
+ /**
727
+ * Build the resolution plugins shared by the server and client passes.
728
+ *
729
+ * The storefront plugin is either/or, never both: `forbidDeepStorefrontImportsPlugin` externalizes
730
+ * the SDK root, `vendorStorefrontPlugin` lets it resolve so it gets bundled. Running both would
731
+ * mean whichever registered its `onResolve` first decides, which is not a contract worth having.
732
+ */
733
+ function resolutionPlugins(vendorStorefront) {
734
+ return vendorStorefront
735
+ ? [
736
+ vendorStorefrontPlugin(),
737
+ forbidExternalPackagesPlugin({ allowFrom: isVendoredDependencyFile }),
738
+ ikasComponentUtilsPlugin(),
739
+ ]
740
+ : [forbidDeepStorefrontImportsPlugin(), forbidExternalPackagesPlugin(), ikasComponentUtilsPlugin()];
741
+ }
182
742
  /**
183
743
  * Compile all components together with esbuild code splitting.
184
744
  * Shared code is automatically extracted into chunk files.
185
745
  * When there's no shared code, output is identical to per-component compilation.
186
746
  */
187
- export async function compileAllComponents(components, globalStylesPath) {
747
+ export async function compileAllComponents(components, globalStylesPath, options) {
188
748
  if (components.length === 0) {
189
749
  return {
190
750
  success: true,
@@ -206,19 +766,33 @@ export async function compileAllComponents(components, globalStylesPath) {
206
766
  entryPoints[comp.id] = path.resolve(process.cwd(), comp.entryPath);
207
767
  }
208
768
  try {
209
- // Server build with code splitting
210
- await esbuild.build({
769
+ // Server build with code splitting (metafile enabled for dependency tracking)
770
+ const serverBuildResult = await esbuild.build({
211
771
  ...commonBuildOptions(),
212
772
  entryPoints,
213
773
  format: "esm",
214
- platform: "node",
215
- target: "node18",
774
+ // Vendoring flips the SSR build to browser resolution. Two reasons, both load-bearing:
775
+ //
776
+ // 1. `platform: "node"` picks the node flavour of a vendored dependency, which reaches for
777
+ // node builtins (`uuid` → `crypto`) that no storefront can hand a published artifact.
778
+ // The browser flavour uses `globalThis.crypto`, which SSR on Node 18+ has anyway.
779
+ // 2. esbuild escapes `</script` in string literals on browser and not on node. That single
780
+ // byte changes a chunk's content hash, so the two builds emitted different chunk names
781
+ // for identical code and every importer inherited the split — 154 of 251 chunks had no
782
+ // twin. Same platform, same hashes, one chunk graph.
783
+ //
784
+ // The build is still consumed by `preact-render-to-string` in Node; only module resolution
785
+ // changes, and SERVER_EXTERNALS keeps the SSR renderer external either way.
786
+ platform: options?.vendorStorefront ? "browser" : "node",
787
+ target: SHARED_BUILD_TARGET,
216
788
  external: SERVER_EXTERNALS,
217
- plugins: [ikasComponentUtilsPlugin()],
789
+ ...(options?.vendorStorefront ? { define: { "import.meta.env": VENDORED_IMPORT_META_ENV } } : {}),
790
+ plugins: resolutionPlugins(!!options?.vendorStorefront),
218
791
  splitting: true,
219
792
  outdir: serverDir,
220
793
  entryNames: "[name]",
221
794
  chunkNames: "chunk-[hash]",
795
+ metafile: true,
222
796
  });
223
797
  // Client build with code splitting (metafile enabled for dependency tracking)
224
798
  const clientBuildResult = await esbuild.build({
@@ -226,9 +800,10 @@ export async function compileAllComponents(components, globalStylesPath) {
226
800
  entryPoints,
227
801
  format: "esm",
228
802
  platform: "browser",
229
- target: "es2020",
803
+ target: SHARED_BUILD_TARGET,
230
804
  external: CLIENT_EXTERNALS,
231
- plugins: [ikasComponentUtilsPlugin()],
805
+ ...(options?.vendorStorefront ? { define: { "import.meta.env": VENDORED_IMPORT_META_ENV } } : {}),
806
+ plugins: resolutionPlugins(!!options?.vendorStorefront),
232
807
  splitting: true,
233
808
  outdir: clientDir,
234
809
  entryNames: "[name]",
@@ -269,17 +844,29 @@ export async function compileAllComponents(components, globalStylesPath) {
269
844
  chunks.set(key, { serverJs, clientJs });
270
845
  }
271
846
  }
272
- // Build dependency maps from metafile
273
- const metafile = clientBuildResult.metafile;
847
+ // Build dependency maps from BOTH the server and client metafiles.
848
+ //
849
+ // Only the client metafile used to be consulted here. But SERVER_EXTERNALS
850
+ // differs from CLIENT_EXTERNALS (e.g. preact-render-to-string is external on
851
+ // the server only), so esbuild splits the two builds differently and emits
852
+ // server-only shared chunks whose names have no client twin. Those chunks are
853
+ // written to disk and captured in `chunks` above, yet — with a client-only
854
+ // graph — they never entered any component's chunk closure, so publish pruned
855
+ // them as orphaned. The result: `compiledServerJs` went missing on the shared
856
+ // module and the server bundle imported a `./chunk-XXXX.js` that was never
857
+ // emitted ("Could not resolve ./chunk-XXXX.js"). Merging both graphs keeps
858
+ // server and client chunk closures symmetric.
859
+ const clientMetafile = clientBuildResult.metafile;
860
+ const serverMetafile = serverBuildResult.metafile;
274
861
  const entryDirSet = new Map(); // entryId → absolute dir of entry file
275
862
  for (const comp of components) {
276
863
  entryDirSet.set(comp.id, path.dirname(path.resolve(process.cwd(), comp.entryPath)));
277
864
  }
278
- // Map each output to its input source files
865
+ // CSS is a browser-only concern, so entry/chunk input source maps are derived
866
+ // from the CLIENT metafile only (they feed the CSS collection passes below).
279
867
  const entryInputs = new Map(); // entryId → list of input paths
280
868
  const chunkInputs = new Map(); // chunkId → list of input paths
281
- const chunkConsumers = new Map(); // chunkId → list of entry IDs that import it
282
- for (const [outputPath, outputMeta] of Object.entries(metafile.outputs)) {
869
+ for (const [outputPath, outputMeta] of Object.entries(clientMetafile.outputs)) {
283
870
  const baseName = path.basename(outputPath, ".js");
284
871
  const inputPaths = Object.keys(outputMeta.inputs || {});
285
872
  if (entryIds.has(baseName)) {
@@ -289,40 +876,49 @@ export async function compileAllComponents(components, globalStylesPath) {
289
876
  chunkInputs.set(baseName, inputPaths);
290
877
  }
291
878
  }
292
- // Determine chunk→consumers: which entries import each chunk
293
- for (const [outputPath, outputMeta] of Object.entries(metafile.outputs)) {
294
- const baseName = path.basename(outputPath, ".js");
295
- if (!entryIds.has(baseName))
296
- continue;
297
- const imports = outputMeta.imports || [];
298
- for (const imp of imports) {
299
- const impBaseName = path.basename(imp.path, ".js");
300
- if (chunkInputs.has(impBaseName)) {
301
- if (!chunkConsumers.has(impBaseName)) {
302
- chunkConsumers.set(impBaseName, []);
303
- }
304
- chunkConsumers.get(impBaseName).push(baseName);
305
- }
306
- }
307
- }
308
- // Build chunk→chunk dependency graph and topologically sort chunks
309
- // so that chunks are evaluated in dependency-first order
879
+ // Recognize any emitted chunk — server OR client — by its output basename.
880
+ // `chunks` was populated above from both the server and client output dirs.
881
+ const allChunkIds = new Set(chunks.keys());
882
+ const chunkConsumers = new Map(); // chunkId → list of entry IDs that import it
310
883
  const chunkDeps = new Map(); // chunkId → list of chunk IDs it depends on
311
- for (const chunkId of chunkInputs.keys()) {
884
+ for (const chunkId of allChunkIds) {
312
885
  chunkDeps.set(chunkId, []);
313
886
  }
314
- for (const [outputPath, outputMeta] of Object.entries(metafile.outputs)) {
315
- const baseName = path.basename(outputPath, ".js");
316
- if (!chunkInputs.has(baseName))
317
- continue;
318
- const imports = outputMeta.imports || [];
319
- for (const imp of imports) {
320
- const impBaseName = path.basename(imp.path, ".js");
321
- if (chunkInputs.has(impBaseName) && impBaseName !== baseName) {
322
- chunkDeps.get(baseName).push(impBaseName);
887
+ // Fold one metafile's output graph into the shared consumer/dependency maps.
888
+ // Called for both builds so server-only chunks are tracked alongside client ones.
889
+ const ingestMetafile = (mf) => {
890
+ for (const [outputPath, outputMeta] of Object.entries(mf.outputs)) {
891
+ const baseName = path.basename(outputPath, ".js");
892
+ const imports = outputMeta.imports || [];
893
+ if (entryIds.has(baseName)) {
894
+ // entry → chunk consumer edges
895
+ for (const imp of imports) {
896
+ const impBaseName = path.basename(imp.path, ".js");
897
+ if (!allChunkIds.has(impBaseName))
898
+ continue;
899
+ if (!chunkConsumers.has(impBaseName)) {
900
+ chunkConsumers.set(impBaseName, []);
901
+ }
902
+ const consumers = chunkConsumers.get(impBaseName);
903
+ if (!consumers.includes(baseName))
904
+ consumers.push(baseName);
905
+ }
906
+ }
907
+ else if (allChunkIds.has(baseName)) {
908
+ // chunk → chunk dependency edges
909
+ for (const imp of imports) {
910
+ const impBaseName = path.basename(imp.path, ".js");
911
+ if (allChunkIds.has(impBaseName) && impBaseName !== baseName) {
912
+ const deps = chunkDeps.get(baseName);
913
+ if (!deps.includes(impBaseName))
914
+ deps.push(impBaseName);
915
+ }
916
+ }
323
917
  }
324
918
  }
325
- }
919
+ };
920
+ ingestMetafile(clientMetafile);
921
+ ingestMetafile(serverMetafile);
326
922
  // Kahn's algorithm for topological sort
327
923
  const inDegree = new Map();
328
924
  for (const chunkId of chunkDeps.keys()) {
@@ -381,7 +977,29 @@ export async function compileAllComponents(components, globalStylesPath) {
381
977
  // Resolve CSS: entry CSS + entry-only dependency CSS + chunk CSS
382
978
  const css = new Map();
383
979
  const chunkCss = new Map();
980
+ // CSS files each consumed chunk will emit (same collection the chunk-CSS pass below uses).
981
+ // The entry pass needs these up front: a parent styles.css that `@import`s a SHARED
982
+ // sub-component's styles.css (the documented convention) would otherwise inline a copy of
983
+ // CSS the chunk already carries for every consumer — duplicating each rule per consumer.
984
+ const chunkExcludeDirs = Array.from(entryDirSet.values());
985
+ const chunkCssFileSets = new Map();
986
+ for (const [chunkId, inputPaths] of chunkInputs) {
987
+ if ((chunkConsumers.get(chunkId) || []).length === 0)
988
+ continue;
989
+ const files = collectSourceCssFiles(inputPaths, undefined, chunkExcludeDirs);
990
+ chunkCssFileSets.set(chunkId, new Set(files.map(f => path.resolve(f))));
991
+ }
384
992
  for (const comp of components) {
993
+ // CSS files already covered for this entry by the chunks it consumes. Only direct
994
+ // consumers count: a chunk this entry does not consume is scoped to other components,
995
+ // so its files must still be inlined here when @imported.
996
+ const chunkCoveredCssPaths = new Set();
997
+ for (const [chunkId, consumers] of chunkConsumers) {
998
+ if (!consumers.includes(comp.id))
999
+ continue;
1000
+ for (const f of chunkCssFileSets.get(chunkId) ?? [])
1001
+ chunkCoveredCssPaths.add(f);
1002
+ }
385
1003
  // 1. Read entry's own styles.css + resolve @imports.
386
1004
  // Track every file inlined here so step 2's source-tree collection doesn't append them again
387
1005
  // (which previously emitted each @imported file twice in compiledCss).
@@ -390,7 +1008,7 @@ export async function compileAllComponents(components, globalStylesPath) {
390
1008
  let cssContent = "";
391
1009
  if (fs.existsSync(cssPath)) {
392
1010
  const rawCss = fs.readFileSync(cssPath, "utf-8");
393
- cssContent = resolveCssImports(rawCss, cssPath, alreadyInlinedPaths);
1011
+ cssContent = resolveCssImports(rawCss, cssPath, alreadyInlinedPaths, chunkCoveredCssPaths);
394
1012
  }
395
1013
  // 2. Collect CSS from entry-only dependencies (source files in entry inputs, not in any chunk)
396
1014
  const allChunkInputPaths = new Set();
@@ -403,20 +1021,23 @@ export async function compileAllComponents(components, globalStylesPath) {
403
1021
  for (const depCssPath of depCss) {
404
1022
  if (alreadyInlinedPaths.has(path.resolve(depCssPath)))
405
1023
  continue;
1024
+ // A sibling CSS can surface here even when its directory is chunk-covered (an
1025
+ // entry-only source file living in a shared sub-component's folder) — the chunk
1026
+ // already carries it, so inlining it again would duplicate every rule.
1027
+ if (chunkCoveredCssPaths.has(path.resolve(depCssPath)))
1028
+ continue;
406
1029
  const rawDepCss = fs.readFileSync(depCssPath, "utf-8");
407
- cssContent += "\n" + resolveCssImports(rawDepCss, depCssPath, alreadyInlinedPaths);
1030
+ cssContent += "\n" + resolveCssImports(rawDepCss, depCssPath, alreadyInlinedPaths, chunkCoveredCssPaths);
408
1031
  }
409
1032
  // 3. Scope combined CSS with entry ID
410
1033
  css.set(comp.id, scopeCSS(cssContent, comp.id));
411
1034
  }
412
- // Process chunk CSS
413
- for (const [chunkId, inputPaths] of chunkInputs) {
1035
+ // Process chunk CSS (file sets were collected above, before the entry pass)
1036
+ for (const chunkId of chunkInputs.keys()) {
414
1037
  const consumers = chunkConsumers.get(chunkId) || [];
415
1038
  if (consumers.length === 0)
416
1039
  continue;
417
- // Collect CSS from all entry dirs to exclude (we only exclude entry file dirs)
418
- const excludeDirs = Array.from(entryDirSet.values());
419
- const chunkCssFiles = collectSourceCssFiles(inputPaths, undefined, excludeDirs);
1040
+ const chunkCssFiles = Array.from(chunkCssFileSets.get(chunkId) ?? []);
420
1041
  if (chunkCssFiles.length === 0)
421
1042
  continue;
422
1043
  let combinedCss = "";
@@ -476,12 +1097,20 @@ export async function compileAllComponents(components, globalStylesPath) {
476
1097
  css: new Map(),
477
1098
  chunkCss: new Map(),
478
1099
  entryChunkIds: new Map(),
479
- error: error.message || String(error)
1100
+ error: withCssImportHint(error.message || String(error))
480
1101
  };
481
1102
  }
482
1103
  finally {
483
- // Clean up temp directory
484
- fs.rmSync(tmpBase, { recursive: true, force: true });
1104
+ // Clean up temp directory. Best-effort: on Windows an antivirus/indexer can briefly hold
1105
+ // handles on the freshly written output files, making rmSync throw EBUSY/EPERM — and a
1106
+ // throw here (inside finally) would replace a successful compilation result with an error.
1107
+ // A leaked tmp dir is harmless; retry a few times, then give up silently.
1108
+ try {
1109
+ fs.rmSync(tmpBase, { recursive: true, force: true, maxRetries: 3 });
1110
+ }
1111
+ catch {
1112
+ // ignore — never fail the build over tmp cleanup
1113
+ }
485
1114
  }
486
1115
  }
487
1116
  /**