@pithyjs/ssr 0.0.0-stage → 0.1.2-beta.8

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 (156) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +100 -2
  3. package/bin/pithy-ssg.mjs +23 -0
  4. package/dist/browser.d.ts +38 -0
  5. package/dist/browser.d.ts.map +1 -0
  6. package/dist/browser.js +40 -0
  7. package/dist/browser.js.map +1 -0
  8. package/dist/build/cli-args.d.ts +104 -0
  9. package/dist/build/cli-args.d.ts.map +1 -0
  10. package/dist/build/cli-args.js +88 -0
  11. package/dist/build/cli-args.js.map +1 -0
  12. package/dist/build/cli-exit.d.ts +95 -0
  13. package/dist/build/cli-exit.d.ts.map +1 -0
  14. package/dist/build/cli-exit.js +237 -0
  15. package/dist/build/cli-exit.js.map +1 -0
  16. package/dist/build/cli.d.ts +11 -0
  17. package/dist/build/cli.d.ts.map +1 -0
  18. package/dist/build/cli.js +93 -0
  19. package/dist/build/cli.js.map +1 -0
  20. package/dist/build/collect-css.d.ts +168 -0
  21. package/dist/build/collect-css.d.ts.map +1 -0
  22. package/dist/build/collect-css.js +479 -0
  23. package/dist/build/collect-css.js.map +1 -0
  24. package/dist/build/css-live-props.d.ts +89 -0
  25. package/dist/build/css-live-props.d.ts.map +1 -0
  26. package/dist/build/css-live-props.js +704 -0
  27. package/dist/build/css-live-props.js.map +1 -0
  28. package/dist/build/css-purge.d.ts +153 -0
  29. package/dist/build/css-purge.d.ts.map +1 -0
  30. package/dist/build/css-purge.js +463 -0
  31. package/dist/build/css-purge.js.map +1 -0
  32. package/dist/build/index.d.ts +24 -0
  33. package/dist/build/index.d.ts.map +1 -0
  34. package/dist/build/index.js +31 -0
  35. package/dist/build/index.js.map +1 -0
  36. package/dist/build/not-found.d.ts +94 -0
  37. package/dist/build/not-found.d.ts.map +1 -0
  38. package/dist/build/not-found.js +99 -0
  39. package/dist/build/not-found.js.map +1 -0
  40. package/dist/build/relative-links.d.ts +31 -0
  41. package/dist/build/relative-links.d.ts.map +1 -0
  42. package/dist/build/relative-links.js +79 -0
  43. package/dist/build/relative-links.js.map +1 -0
  44. package/dist/build/shell-head.d.ts +68 -0
  45. package/dist/build/shell-head.d.ts.map +1 -0
  46. package/dist/build/shell-head.js +236 -0
  47. package/dist/build/shell-head.js.map +1 -0
  48. package/dist/build/sprite-ssg.d.ts +61 -0
  49. package/dist/build/sprite-ssg.d.ts.map +1 -0
  50. package/dist/build/sprite-ssg.js +114 -0
  51. package/dist/build/sprite-ssg.js.map +1 -0
  52. package/dist/build/ssg.d.ts +117 -0
  53. package/dist/build/ssg.d.ts.map +1 -0
  54. package/dist/build/ssg.js +404 -0
  55. package/dist/build/ssg.js.map +1 -0
  56. package/dist/build/vite-ssg.d.ts +396 -0
  57. package/dist/build/vite-ssg.d.ts.map +1 -0
  58. package/dist/build/vite-ssg.js +1130 -0
  59. package/dist/build/vite-ssg.js.map +1 -0
  60. package/dist/client/bootstrap.d.ts +51 -0
  61. package/dist/client/bootstrap.d.ts.map +1 -0
  62. package/dist/client/bootstrap.js +121 -0
  63. package/dist/client/bootstrap.js.map +1 -0
  64. package/dist/client/hydrate.d.ts +60 -0
  65. package/dist/client/hydrate.d.ts.map +1 -0
  66. package/dist/client/hydrate.js +168 -0
  67. package/dist/client/hydrate.js.map +1 -0
  68. package/dist/client/index.d.ts +21 -0
  69. package/dist/client/index.d.ts.map +1 -0
  70. package/dist/client/index.js +16 -0
  71. package/dist/client/index.js.map +1 -0
  72. package/dist/index.d.ts +32 -0
  73. package/dist/index.d.ts.map +1 -0
  74. package/dist/index.js +31 -0
  75. package/dist/index.js.map +1 -0
  76. package/dist/server/app.d.ts +166 -0
  77. package/dist/server/app.d.ts.map +1 -0
  78. package/dist/server/app.js +200 -0
  79. package/dist/server/app.js.map +1 -0
  80. package/dist/server/context.d.ts +238 -0
  81. package/dist/server/context.d.ts.map +1 -0
  82. package/dist/server/context.js +371 -0
  83. package/dist/server/context.js.map +1 -0
  84. package/dist/server/environment.d.ts +88 -0
  85. package/dist/server/environment.d.ts.map +1 -0
  86. package/dist/server/environment.js +261 -0
  87. package/dist/server/environment.js.map +1 -0
  88. package/dist/server/html-shell.d.ts +41 -0
  89. package/dist/server/html-shell.d.ts.map +1 -0
  90. package/dist/server/html-shell.js +208 -0
  91. package/dist/server/html-shell.js.map +1 -0
  92. package/dist/server/index.d.ts +26 -0
  93. package/dist/server/index.d.ts.map +1 -0
  94. package/dist/server/index.js +37 -0
  95. package/dist/server/index.js.map +1 -0
  96. package/dist/server/layout-taint.d.ts +62 -0
  97. package/dist/server/layout-taint.d.ts.map +1 -0
  98. package/dist/server/layout-taint.js +313 -0
  99. package/dist/server/layout-taint.js.map +1 -0
  100. package/dist/server/loaders.d.ts +194 -0
  101. package/dist/server/loaders.d.ts.map +1 -0
  102. package/dist/server/loaders.js +479 -0
  103. package/dist/server/loaders.js.map +1 -0
  104. package/dist/server/render-route.d.ts +102 -0
  105. package/dist/server/render-route.d.ts.map +1 -0
  106. package/dist/server/render-route.js +182 -0
  107. package/dist/server/render-route.js.map +1 -0
  108. package/dist/server/render.d.ts +80 -0
  109. package/dist/server/render.d.ts.map +1 -0
  110. package/dist/server/render.js +256 -0
  111. package/dist/server/render.js.map +1 -0
  112. package/dist/server/router-adapter.d.ts +134 -0
  113. package/dist/server/router-adapter.d.ts.map +1 -0
  114. package/dist/server/router-adapter.js +225 -0
  115. package/dist/server/router-adapter.js.map +1 -0
  116. package/dist/server/serialization.d.ts +54 -0
  117. package/dist/server/serialization.d.ts.map +1 -0
  118. package/dist/server/serialization.js +287 -0
  119. package/dist/server/serialization.js.map +1 -0
  120. package/dist/server/ssr-worker.d.ts +18 -0
  121. package/dist/server/ssr-worker.d.ts.map +1 -0
  122. package/dist/server/ssr-worker.js +118 -0
  123. package/dist/server/ssr-worker.js.map +1 -0
  124. package/dist/server/utils.d.ts +11 -0
  125. package/dist/server/utils.d.ts.map +1 -0
  126. package/dist/server/utils.js +14 -0
  127. package/dist/server/utils.js.map +1 -0
  128. package/dist/server/worker-pool.d.ts +153 -0
  129. package/dist/server/worker-pool.d.ts.map +1 -0
  130. package/dist/server/worker-pool.js +451 -0
  131. package/dist/server/worker-pool.js.map +1 -0
  132. package/dist/server/worker-protocol.d.ts +61 -0
  133. package/dist/server/worker-protocol.d.ts.map +1 -0
  134. package/dist/server/worker-protocol.js +9 -0
  135. package/dist/server/worker-protocol.js.map +1 -0
  136. package/dist/shared/css-purge.d.ts +71 -0
  137. package/dist/shared/css-purge.d.ts.map +1 -0
  138. package/dist/shared/css-purge.js +177 -0
  139. package/dist/shared/css-purge.js.map +1 -0
  140. package/dist/shared/entry-path.d.ts +41 -0
  141. package/dist/shared/entry-path.d.ts.map +1 -0
  142. package/dist/shared/entry-path.js +87 -0
  143. package/dist/shared/entry-path.js.map +1 -0
  144. package/dist/shared/head.d.ts +87 -0
  145. package/dist/shared/head.d.ts.map +1 -0
  146. package/dist/shared/head.js +412 -0
  147. package/dist/shared/head.js.map +1 -0
  148. package/dist/shared/shell-helpers.d.ts +69 -0
  149. package/dist/shared/shell-helpers.d.ts.map +1 -0
  150. package/dist/shared/shell-helpers.js +160 -0
  151. package/dist/shared/shell-helpers.js.map +1 -0
  152. package/dist/shared/types.d.ts +332 -0
  153. package/dist/shared/types.d.ts.map +1 -0
  154. package/dist/shared/types.js +27 -0
  155. package/dist/shared/types.js.map +1 -0
  156. package/package.json +84 -3
@@ -0,0 +1,479 @@
1
+ /** @codex
2
+ {
3
+ "id": "pithy.ssr.build.collect-css",
4
+ "title": "SSG CSS Collector",
5
+ "category": "feature",
6
+ "risk": "critical"
7
+ }
8
+ */
9
+ /**
10
+ * Collect CSS from a Vite dev server's module graph.
11
+ *
12
+ * Used during static-only SSG (no hydration) to inline all CSS
13
+ * since there's no client build to extract it.
14
+ *
15
+ * In hydrate mode this is skipped — the client build extracts CSS
16
+ * into a separate file linked via <link rel="stylesheet">.
17
+ *
18
+ * @module ssr/build/collect-css
19
+ */
20
+ import { existsSync } from 'node:fs';
21
+ import { resolve } from 'node:path';
22
+ /**
23
+ * Extract CSS string from a Vite-transformed JS module.
24
+ *
25
+ * Vite wraps CSS as JS exports like:
26
+ * const __vite__css = "..."
27
+ * export default "..."
28
+ * __vite_ssr_export_default__("...")
29
+ *
30
+ * This regex matches the quoted CSS content from any of those forms.
31
+ */
32
+ /** @internal Exported for testing */
33
+ export const CSS_JS_RE = /(?:const __vite__css\s*=\s*|__vite_ssr_export_default__\(|export default\s*)"([\s\S]*?)(?<!\\)"/;
34
+ /**
35
+ * Detect whether a string looks like JavaScript rather than CSS.
36
+ * Used to prevent Vite HMR wrapper code from leaking into CSS output.
37
+ *
38
+ * Matches JS keywords only at line start (with optional whitespace) followed
39
+ * by whitespace, so CSS constructs like `var(--x)` and `@import` don't match.
40
+ * @internal Exported for testing
41
+ */
42
+ const JS_KEYWORD_LINE_RE = /^\s*(import|export|const|let|var|function)\s+/m;
43
+ const IMPORT_META_RE = /\bimport\.meta\b/;
44
+ const VITE_WRAPPER_RE = /\b(__vite_ssr_export_default__|__vite__css|updateStyle)\b/;
45
+ export function looksLikeJs(code) {
46
+ return (JS_KEYWORD_LINE_RE.test(code) ||
47
+ IMPORT_META_RE.test(code) ||
48
+ VITE_WRAPPER_RE.test(code));
49
+ }
50
+ /** @internal Exported for testing */
51
+ export function unescapeCssString(raw) {
52
+ return raw
53
+ .replace(/\\n/g, '\n')
54
+ .replace(/\\t/g, '\t')
55
+ .replace(/\\"/g, '"')
56
+ .replace(/\\\\/g, '\\');
57
+ }
58
+ /**
59
+ * Extract CSS from a Vite-transformed JS module string.
60
+ * Returns the unescaped CSS or null if no CSS pattern is found.
61
+ * @internal Exported for testing
62
+ */
63
+ export function extractCssFromJs(code) {
64
+ const match = code.match(CSS_JS_RE);
65
+ if (!match)
66
+ return null;
67
+ return unescapeCssString(match[1]);
68
+ }
69
+ /**
70
+ * Normalize a root-relative client entry path to a Vite request URL.
71
+ *
72
+ * `entryClient` arrives as a path relative to the app root (`src/main.ts`),
73
+ * but `transformRequest` expects a root-absolute URL (`/src/main.ts`).
74
+ * @internal Exported for testing
75
+ */
76
+ export function entryToUrl(entryClient) {
77
+ const normalized = entryClient.replace(/\\/g, '/').replace(/^\.\//, '');
78
+ return normalized.startsWith('/') ? normalized : `/${normalized}`;
79
+ }
80
+ /** Matches the stylesheet extensions the collector understands. */
81
+ const STYLESHEET_RE = /\.(css|scss|sass|less)($|\?)/;
82
+ /**
83
+ * Virtual module id for the design-system CSS, collected explicitly up front.
84
+ *
85
+ * The canonical definition is `VIRTUAL_MODULE_ID` in
86
+ * `packages/vitePlugins/src/designSystemPlugin/types.ts`. It is copied rather
87
+ * than imported on purpose: `@pithyjs/vite-plugin` is a build tool and is
88
+ * deliberately not a dependency of `@pithyjs/ssr`, and taking one on so two
89
+ * modules could share a string would couple the runtime package to the plugin
90
+ * package for nothing. `collect-css.test.ts` asserts the two are equal, so the
91
+ * copy cannot drift.
92
+ *
93
+ * @internal Exported for testing
94
+ */
95
+ /** @codexApi {"parent":"pithy.ssr.build.collect-css","name":"DS_VIRTUAL_ID","stability":"experimental","signature":"'virtual:pithy-design-system'"} */
96
+ export const DS_VIRTUAL_ID = 'virtual:pithy-design-system';
97
+ /**
98
+ * Whether a module URL is the design-system virtual module.
99
+ *
100
+ * Once the client entry is warmed, this module is in the graph with `id` and
101
+ * `file` set to `\0virtual:pithy-design-system.css` — but its `url` is the bare
102
+ * `virtual:pithy-design-system`, with NO `.css`. Keying the walk on `url`
103
+ * therefore failed the stylesheet filter and made the recovery unreachable,
104
+ * so a transient failure of the explicit fetch became a false, non-waivable
105
+ * exit 1 on an otherwise healthy export. Key on {@link moduleKey}. It is
106
+ * already collected explicitly at the top of {@link collectCss}, and emitting
107
+ * it again duplicates the entire design system, palette included.
108
+ * @internal Exported for testing
109
+ */
110
+ export function isDesignSystemVirtualModule(url) {
111
+ // ANCHORED, not a substring test. This gates the whole verdict below, so a
112
+ // false positive exits 0 on a genuinely token-less export. `includes()` was
113
+ // safe only by accident — it goes wrong the day any prefixed id exists, e.g.
114
+ // `virtual:pithy-design-system-print.css`.
115
+ const bare = url.replace(/\0/g, '').split('?')[0];
116
+ return bare === DS_VIRTUAL_ID || bare === `${DS_VIRTUAL_ID}.css`;
117
+ }
118
+ /** @internal Exported for testing */
119
+ export function isStylesheetUrl(url) {
120
+ return STYLESHEET_RE.test(url);
121
+ }
122
+ /**
123
+ * Collapse the spellings Vite uses for the same module into one key.
124
+ *
125
+ * The same file appears in the graph as both `/@fs/Users/…` and `/@fs//Users/…`
126
+ * depending on how it was resolved. Left unnormalized, each spelling is treated
127
+ * as a distinct module and its CSS is emitted twice.
128
+ *
129
+ * Only the `/@fs/` prefix is collapsed — never repeated slashes elsewhere in the
130
+ * string, which would merge distinct modules whose query values contain a URL
131
+ * (`a.css?url=//cdn/x` vs `a.css?url=/cdn/x`).
132
+ *
133
+ * Prefer {@link moduleKey} where a `ModuleNode` is available.
134
+ * @internal Exported for testing
135
+ */
136
+ export function normalizeModuleUrl(url) {
137
+ return url.replace(/^(\/@fs)\/+/, '$1/');
138
+ }
139
+ /**
140
+ * Key for a module known only by its URL.
141
+ *
142
+ * `/@fs/` is Vite's browser-facing spelling of an absolute path, while the graph
143
+ * keys the same module on `id`/`file`, which carry the bare path. Both have to
144
+ * produce one key: an entry-reached sheet whose module the graph cannot resolve
145
+ * yet is recorded from its URL, and is emitted a second time when the graph walk
146
+ * later finds it under the bare path.
147
+ * @internal Exported for testing
148
+ */
149
+ export function moduleKeyFromUrl(url) {
150
+ return normalizeModuleUrl(url).replace(/^\/@fs/, '');
151
+ }
152
+ /**
153
+ * Stable identity for a module in the graph.
154
+ *
155
+ * Vite already knows what a module *is*, so no regex has to guess at the URL.
156
+ *
157
+ * `id` first, not `file`: `id` is the key `idToModuleMap` itself uses, so it is
158
+ * unique per module by construction. `file` is the query-stripped path, which
159
+ * two genuinely distinct modules can share — `a.css` and `a.css?theme=dark`
160
+ * resolve to one `file`, so keying on it drops one of them and its rules never
161
+ * reach the output.
162
+ * @internal Exported for testing
163
+ */
164
+ export function moduleKey(mod) {
165
+ return mod.id ?? mod.file ?? moduleKeyFromUrl(mod.url);
166
+ }
167
+ /**
168
+ * Pull the client entry and everything it imports into the module graph, and
169
+ * report the stylesheets it reaches **in import order**.
170
+ *
171
+ * SSG renders through SSR, which never executes the client entry — so the
172
+ * entry's side-effect CSS imports (`import '@pithyjs/ui-kit/styles'`, an app's
173
+ * own `styles.css`) are absent from the graph and would be silently dropped.
174
+ * Walking the entry's import tree registers them.
175
+ *
176
+ * The returned order matters as much as the registration. In a real client
177
+ * bundle the entry's imports are evaluated before any component's, so
178
+ * `@pithyjs/ui-kit/styles` lands before a component stylesheet that overrides
179
+ * it. The module graph is keyed by insertion, and SSR rendering has already
180
+ * inserted component stylesheets by the time this runs, so iterating the graph
181
+ * alone would emit those overrides *before* the rules they override — every
182
+ * equal-specificity app override would win in `pnpm dev` and lose in the
183
+ * exported HTML. Emitting the entry-reachable sheets in BFS order restores the
184
+ * invariant the bundler used to provide.
185
+ *
186
+ * This is a genuine second compile pass, not a cache hit: the SSG render path
187
+ * uses `ssrLoadModule`, which fills `ModuleNode.ssrTransformResult`, whereas
188
+ * `transformRequest` without `{ ssr: true }` consults and fills the separate
189
+ * client `transformResult`. Nothing here is free. The walk is bounded to
190
+ * modules reachable from the entry, which is the price of knowing the order.
191
+ *
192
+ * Failures are non-fatal — an app may legitimately have no client entry
193
+ * (`pithy.config.ts`-only apps) — but a failure of the **entry itself** is
194
+ * reported, because it means no app CSS at all was registered and the build
195
+ * would otherwise succeed while shipping unstyled HTML.
196
+ *
197
+ * @returns Stylesheets reachable from the entry, in import order, each paired
198
+ * with the same identity key the graph walk uses so neither can emit a sheet
199
+ * the other already did.
200
+ */
201
+ async function warmClientEntry(vite, entryClient) {
202
+ const entryUrl = entryToUrl(entryClient);
203
+ const queue = [entryUrl];
204
+ const visited = new Set();
205
+ const stylesheets = [];
206
+ /**
207
+ * Whether the configured client entry is actually on disk.
208
+ *
209
+ * Defensive on both sides: no root means no answer, and the caller treats an
210
+ * unknown as present so a real failure still surfaces.
211
+ */
212
+ const entryFileExists = () => {
213
+ const root = vite.config?.root;
214
+ if (!root)
215
+ return true;
216
+ try {
217
+ return existsSync(resolve(root, entryClient));
218
+ }
219
+ catch {
220
+ return true;
221
+ }
222
+ };
223
+ /**
224
+ * Report a failure that hit the entry itself.
225
+ *
226
+ * A failure anywhere else costs one subtree; a failure on the entry costs
227
+ * everything, because nothing downstream is ever enqueued. The graph walk
228
+ * then finds no app stylesheets and the build emits styleless HTML and exits
229
+ * 0 — the exact failure this warming exists to prevent, so it must be loud.
230
+ */
231
+ const warnEntryFailure = (stage, err) => {
232
+ // An app may legitimately have no client entry, and `entryClient` defaults
233
+ // to "src/main.ts" whether or not one exists — so a missing file is the
234
+ // documented case, not a fault, and warning about it is noise no config can
235
+ // silence. Only a file that IS there and still failed indicates the
236
+ // styleless-HTML failure this warning exists for. If the root cannot be
237
+ // determined, warn: a missed warning costs a silently unstyled build.
238
+ if (!entryFileExists())
239
+ return;
240
+ console.log(` Warning: could not ${stage} the client entry "${entryUrl}": ` +
241
+ `${err instanceof Error ? err.message : err}\n` +
242
+ ` Static output will be missing every stylesheet the entry imports. ` +
243
+ `Check the \`entryClient\` build option (default "src/main.ts").`);
244
+ };
245
+ while (queue.length > 0) {
246
+ const url = queue.shift();
247
+ const key = moduleKeyFromUrl(url);
248
+ if (visited.has(key))
249
+ continue;
250
+ visited.add(key);
251
+ try {
252
+ await vite.transformRequest(url);
253
+ }
254
+ catch (err) {
255
+ if (url === entryUrl)
256
+ warnEntryFailure('transform', err);
257
+ continue;
258
+ }
259
+ // `getModuleByUrl` resolves through the plugin container, so a plugin that
260
+ // throws on an unusual specifier would reject here. Keep it inside a catch:
261
+ // collection runs after every route has rendered, so an escaping rejection
262
+ // would fail the whole build having written nothing. Collection must only
263
+ // ever mean *missing* CSS, never a failed build.
264
+ let mod;
265
+ try {
266
+ mod = await vite.moduleGraph.getModuleByUrl(url);
267
+ }
268
+ catch (err) {
269
+ // On the entry this ends the walk before a single import is enqueued
270
+ // (`if (!mod) continue` below), so it carries the same stakes as a failed
271
+ // transform.
272
+ if (url === entryUrl)
273
+ warnEntryFailure('resolve', err);
274
+ mod = undefined;
275
+ }
276
+ if (isStylesheetUrl(url)) {
277
+ // Record the same identity the graph walk keys on, so a sheet found here
278
+ // is not emitted a second time there.
279
+ stylesheets.push({ url, key: mod ? moduleKey(mod) : key });
280
+ // Do NOT descend into a stylesheet's imports. Sass has already inlined
281
+ // every `@use`d partial into this module's compiled output; the partials
282
+ // remain in the graph only for HMR tracking. Registering them too would
283
+ // make the collector emit the same rules twice — once from the aggregate,
284
+ // once per partial.
285
+ continue;
286
+ }
287
+ // Transforming a module registers its direct imports. Follow them so CSS
288
+ // that sits deeper than the entry (entry -> theme/index.ts -> theme.scss)
289
+ // is reached too.
290
+ if (!mod)
291
+ continue;
292
+ for (const imported of mod.importedModules) {
293
+ // Same derivation `visited` is keyed with above — `normalizeModuleUrl`
294
+ // keeps the `/@fs/` prefix, so using it here would never match a key that
295
+ // was stored stripped and every `/@fs/` import would be re-enqueued.
296
+ if (imported.url && !visited.has(moduleKeyFromUrl(imported.url))) {
297
+ queue.push(imported.url);
298
+ }
299
+ }
300
+ }
301
+ return stylesheets;
302
+ }
303
+ /**
304
+ * Collect CSS from:
305
+ * 1. The design system virtual module (utility classes like u-grid, u-flex, etc.)
306
+ * 2. The client entry's import tree (see {@link warmClientEntry})
307
+ * 3. Any .css/.scss modules in Vite's module graph
308
+ *
309
+ * @param vite - Dev server whose module graph is inspected.
310
+ * @param entryClient - Client entry relative to the app root (e.g. `src/main.ts`).
311
+ * Omit only when the app genuinely has no client entry; omitting it for an app
312
+ * that has one silently drops every stylesheet the entry imports.
313
+ * @param options - Diagnostic sinks. See {@link CollectCssOptions}.
314
+ * @returns Every stylesheet found, concatenated. Never throws for a
315
+ * design-system problem — see {@link CollectCssOptions.onDesignSystemFailure}.
316
+ */
317
+ /** @codexApi {"parent":"pithy.ssr.build.collect-css","name":"collectCss","stability":"experimental","signature":"(vite: ViteDevServer, entryClient?: string, options?: CollectCssOptions) => Promise<string>"} */
318
+ export async function collectCss(vite, entryClient, options) {
319
+ const chunks = [];
320
+ // Stylesheets the entry reaches, in import order — emitted before anything
321
+ // discovered by the graph walk so the cascade matches the client bundle.
322
+ const entryStylesheets = entryClient
323
+ ? await warmClientEntry(vite, entryClient)
324
+ : [];
325
+ // --- Design system utility CSS (virtual:pithy-design-system) ---
326
+ // Tracks whether the explicit collection below actually produced a chunk.
327
+ // The graph walk skips this module only when it did — otherwise a failure
328
+ // here (wrapper format change, transient transform error) would be
329
+ // compounded by the walk skipping the one copy that could still be recovered
330
+ // from the graph, and the design system would vanish from the output.
331
+ let collectedDesignSystem = false;
332
+ /**
333
+ * Why the explicit fetch produced nothing, kept for the final report.
334
+ *
335
+ * Recorded rather than reported on the spot: the graph walk below can still
336
+ * recover this module, and announcing a failure the artifact does not have
337
+ * is how a build warning becomes noise everyone scrolls past.
338
+ */
339
+ let designSystemFailure = null;
340
+ try {
341
+ const dsResult = await vite.transformRequest(DS_VIRTUAL_ID);
342
+ if (!dsResult?.code) {
343
+ designSystemFailure = new Error(`${DS_VIRTUAL_ID} resolved but produced no module content.`);
344
+ }
345
+ if (dsResult?.code) {
346
+ const css = extractCssFromJs(dsResult.code);
347
+ if (css !== null && css.trim().length === 0) {
348
+ // The wrapper was found and was EMPTY. Distinct from "no wrapper", and
349
+ // worth saying so: otherwise the report read "produced no CSS: no CSS
350
+ // was produced", which tells the reader nothing they did not already
351
+ // have. Reachable when a third-party plugin claims the id.
352
+ designSystemFailure = new Error(`${DS_VIRTUAL_ID} returned an empty stylesheet — ` +
353
+ 'a plugin claims this id but emitted no rules.');
354
+ }
355
+ else if (css && css.trim().length > 0) {
356
+ chunks.push(`/* design-system utilities */\n${css}`);
357
+ collectedDesignSystem = true;
358
+ }
359
+ else if (css === null && dsResult.code.trim().length > 0) {
360
+ // Only use raw code if it looks like plain CSS, not JS wrapper code.
361
+ // Vite transforms CSS into JS modules with HMR boilerplate — pushing
362
+ // that raw JS as CSS silently breaks styles.
363
+ if (!looksLikeJs(dsResult.code)) {
364
+ chunks.push(`/* design-system utilities */\n${dsResult.code}`);
365
+ collectedDesignSystem = true;
366
+ }
367
+ else {
368
+ designSystemFailure = new Error(`Could not extract CSS from ${DS_VIRTUAL_ID}. ` +
369
+ 'The Vite wrapper format may have changed.');
370
+ }
371
+ }
372
+ }
373
+ }
374
+ catch (err) {
375
+ designSystemFailure = err instanceof Error ? err : new Error(String(err));
376
+ }
377
+ // --- Stylesheets, entry-reachable ones first ---
378
+ //
379
+ // Order is load-bearing: the entry's sheets must precede component sheets so
380
+ // an equal-specificity app override still wins, exactly as it does in the
381
+ // client bundle. The graph walk then picks up anything the entry does not
382
+ // reach — component styles pulled in during SSR rendering, for instance.
383
+ const seen = new Set();
384
+ // `key` is what the module is IDENTIFIED by (`mod.id`, which carries `.css`);
385
+ // `url` is what it is FETCHED by. They differ for virtual modules, and
386
+ // conflating them is what made the design-system recovery unreachable.
387
+ const collectStylesheet = async (url, key = url) => {
388
+ if (!isStylesheetUrl(key))
389
+ return;
390
+ // Skip only if it was genuinely collected above. If that failed, fall
391
+ // through and take it from the graph rather than emitting nothing.
392
+ if (collectedDesignSystem && isDesignSystemVirtualModule(key))
393
+ return;
394
+ try {
395
+ const result = await vite.transformRequest(url);
396
+ if (!result?.code)
397
+ return;
398
+ const css = extractCssFromJs(result.code);
399
+ if (css && css.trim().length > 0) {
400
+ chunks.push(`/* ${url} */\n${css}`);
401
+ // The explicit fetch above is not the only way this module reaches the
402
+ // output. If the walk recovered it, the artifact has its tokens and
403
+ // there is nothing left to report.
404
+ if (isDesignSystemVirtualModule(key))
405
+ collectedDesignSystem = true;
406
+ return;
407
+ }
408
+ if (css !== null || result.code.trim().length === 0)
409
+ return;
410
+ // No recognized wrapper. If it does not look like JS it *is* CSS — a
411
+ // plugin returning CSS directly, a `?inline`/`?raw` variant — so take it
412
+ // rather than dropping it. Mirrors the design-system branch above.
413
+ if (!looksLikeJs(result.code)) {
414
+ chunks.push(`/* ${url} */\n${result.code}`);
415
+ // Same recovery as the wrapped branch above, and it has to be recorded
416
+ // on BOTH. A design system recovered as unwrapped CSS lands correctly
417
+ // in the artifact; forgetting to say so here reported a build failure —
418
+ // and exited 1 — for an export that was completely fine.
419
+ if (isDesignSystemVirtualModule(key))
420
+ collectedDesignSystem = true;
421
+ }
422
+ else {
423
+ console.log(`[collect-css] Could not extract CSS from ${url}. ` +
424
+ 'The Vite wrapper format may have changed — CSS from this module will be missing.');
425
+ }
426
+ }
427
+ catch {
428
+ // Skip modules that can't be transformed
429
+ }
430
+ };
431
+ for (const { url, key } of entryStylesheets) {
432
+ if (seen.has(key))
433
+ continue;
434
+ seen.add(key);
435
+ await collectStylesheet(url, key);
436
+ }
437
+ for (const mod of vite.moduleGraph.idToModuleMap.values()) {
438
+ // Key on Vite's own identity for the module: `file`/`id` collapse the
439
+ // `/@fs/` spellings by construction, where a URL regex could merge two
440
+ // genuinely distinct modules whose query values contain a URL.
441
+ const key = moduleKey(mod);
442
+ if (seen.has(key))
443
+ continue;
444
+ seen.add(key);
445
+ await collectStylesheet(mod.url, key);
446
+ }
447
+ // --- Design-system verdict, once, with everything known ---
448
+ //
449
+ // Deferred to here rather than reported at the point of failure because the
450
+ // graph walk above is a second chance at the same module. What matters is
451
+ // whether the ARTIFACT ended up with the tokens, not whether one particular
452
+ // fetch of them succeeded.
453
+ if (!collectedDesignSystem) {
454
+ const reason = designSystemFailure?.message ?? 'no CSS was produced';
455
+ if (options?.designSystemDeclared) {
456
+ // The app asked for a design system and did not get one. Every page in
457
+ // this export is about to ship with undefined `var(--color-*)` references
458
+ // and no way to recover — that is a build failure, not a warning.
459
+ console.error(` ERROR: this app declares a design system but ${DS_VIRTUAL_ID} ` +
460
+ `produced no CSS: ${reason}\n` +
461
+ ' Every page would ship with undefined design tokens. ' +
462
+ 'This is a build failure.');
463
+ options?.onDesignSystemFailure?.(designSystemFailure ??
464
+ new Error(`${DS_VIRTUAL_ID} produced no CSS: ${reason}`));
465
+ }
466
+ else {
467
+ // Nothing registers the module. The app has no design system — a real
468
+ // choice, and not this build's business to veto. Say so clearly enough
469
+ // that an app which *meant* to have one recognises the omission.
470
+ console.warn(` Warning: no design-system plugin is registered, so ${DS_VIRTUAL_ID} ` +
471
+ 'resolved to nothing and no design tokens were inlined.\n' +
472
+ ' Pages will render with whatever CSS the app supplies ' +
473
+ 'itself. Add designSystemPlugin() to vite.config.ts if that is not ' +
474
+ 'what you wanted.');
475
+ }
476
+ }
477
+ return chunks.join('\n\n');
478
+ }
479
+ //# sourceMappingURL=collect-css.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"collect-css.js","sourceRoot":"","sources":["../../src/build/collect-css.ts"],"names":[],"mappings":"AAAA;;;;;;;EAOE;AAEF;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAIpC;;;;;;;;;GASG;AACH,qCAAqC;AACrC,MAAM,CAAC,MAAM,SAAS,GACpB,iGAAiG,CAAC;AAEpG;;;;;;;GAOG;AACH,MAAM,kBAAkB,GAAG,gDAAgD,CAAC;AAC5E,MAAM,cAAc,GAAG,kBAAkB,CAAC;AAC1C,MAAM,eAAe,GACnB,2DAA2D,CAAC;AAE9D,MAAM,UAAU,WAAW,CAAC,IAAY;IACtC,OAAO,CACL,kBAAkB,CAAC,IAAI,CAAC,IAAI,CAAC;QAC7B,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC;QACzB,eAAe,CAAC,IAAI,CAAC,IAAI,CAAC,CAC3B,CAAC;AACJ,CAAC;AAED,qCAAqC;AACrC,MAAM,UAAU,iBAAiB,CAAC,GAAW;IAC3C,OAAO,GAAG;SACP,OAAO,CAAC,MAAM,EAAE,IAAI,CAA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AAG,CAAC,CAAC;IACxC,CAAC;IAED,6DAA6D;IAC7D,EAAE;IACF,4EAA4E;IAC5E,0EAA0E;IAC1E,4EAA4E;IAC5E,2BAA2B;IAC3B,IAAI,CAAC,qBAAqB,EAAE,CAAC;QAC3B,MAAM,MAAM,GAAG,mBAAmB,EAAE,OAAO,IAAI,qBAAqB,CAAC;QACrE,IAAI,OAAO,EAAE,oBAAoB,EAAE,CAAC;YAClC,uEAAuE;YACvE,0EAA0E;YAC1E,kEAAkE;YAClE,OAAO,CAAC,KAAK,CACX,kDAAkD,aAAa,GAAG;gBAChE,oBAAoB,MAAM,IAAI;gBAC9B,+DAA+D;gBAC/D,0BAA0B,CAC7B,CAAC;YACF,OAAO,EAAE,qBAAqB,EAAE,CAC9B,mBAAmB;gBACjB,IAAI,KAAK,CAAC,GAAG,aAAa,qBAAqB,MAAM,EAAE,CAAC,CAC3D,CAAC;QACJ,CAAC;aAAM,CAAC;YACN,sEAAsE;YACtE,uEAAuE;YACvE,iEAAiE;YACjE,OAAO,CAAC,IAAI,CACV,wDAAwD,aAAa,GAAG;gBACtE,0DAA0D;gBAC1D,kEAAkE;gBAClE,oEAAoE;gBACpE,kBAAkB,CACrB,CAAC;QACJ,CAAC;IACH,CAAC;IAED,OAAO,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AAC7B,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.ssr.build.collect-css\",\n \"title\": \"SSG CSS Collector\",\n \"category\": \"feature\",\n \"risk\": \"critical\"\n}\n*/\n\n/**\n * Collect CSS from a Vite dev server's module graph.\n *\n * Used during static-only SSG (no hydration) to inline all CSS\n * since there's no client build to extract it.\n *\n * In hydrate mode this is skipped — the client build extracts CSS\n * into a separate file linked via <link rel=\"stylesheet\">.\n *\n * @module ssr/build/collect-css\n */\n\nimport { existsSync } from 'node:fs';\nimport { resolve } from 'node:path';\n\nimport type { ViteDevServer } from 'vite';\n\n/**\n * Extract CSS string from a Vite-transformed JS module.\n *\n * Vite wraps CSS as JS exports like:\n * const __vite__css = \"...\"\n * export default \"...\"\n * __vite_ssr_export_default__(\"...\")\n *\n * This regex matches the quoted CSS content from any of those forms.\n */\n/** @internal Exported for testing */\nexport const CSS_JS_RE =\n /(?:const __vite__css\\s*=\\s*|__vite_ssr_export_default__\\(|export default\\s*)\"([\\s\\S]*?)(?<!\\\\)\"/;\n\n/**\n * Detect whether a string looks like JavaScript rather than CSS.\n * Used to prevent Vite HMR wrapper code from leaking into CSS output.\n *\n * Matches JS keywords only at line start (with optional whitespace) followed\n * by whitespace, so CSS constructs like `var(--x)` and `@import` don't match.\n * @internal Exported for testing\n */\nconst JS_KEYWORD_LINE_RE = /^\\s*(import|export|const|let|var|function)\\s+/m;\nconst IMPORT_META_RE = /\\bimport\\.meta\\b/;\nconst VITE_WRAPPER_RE =\n /\\b(__vite_ssr_export_default__|__vite__css|updateStyle)\\b/;\n\nexport function looksLikeJs(code: string): boolean {\n return (\n JS_KEYWORD_LINE_RE.test(code) ||\n IMPORT_META_RE.test(code) ||\n VITE_WRAPPER_RE.test(code)\n );\n}\n\n/** @internal Exported for testing */\nexport function unescapeCssString(raw: string): string {\n return raw\n .replace(/\\\\n/g, '\\n')\n .replace(/\\\\t/g, '\\t')\n .replace(/\\\\\"/g, '\"')\n .replace(/\\\\\\\\/g, '\\\\');\n}\n\n/**\n * Extract CSS from a Vite-transformed JS module string.\n * Returns the unescaped CSS or null if no CSS pattern is found.\n * @internal Exported for testing\n */\nexport function extractCssFromJs(code: string): string | null {\n const match = code.match(CSS_JS_RE);\n if (!match) return null;\n return unescapeCssString(match[1]);\n}\n\n/**\n * Normalize a root-relative client entry path to a Vite request URL.\n *\n * `entryClient` arrives as a path relative to the app root (`src/main.ts`),\n * but `transformRequest` expects a root-absolute URL (`/src/main.ts`).\n * @internal Exported for testing\n */\nexport function entryToUrl(entryClient: string): string {\n const normalized = entryClient.replace(/\\\\/g, '/').replace(/^\\.\\//, '');\n return normalized.startsWith('/') ? normalized : `/${normalized}`;\n}\n\n/** Matches the stylesheet extensions the collector understands. */\nconst STYLESHEET_RE = /\\.(css|scss|sass|less)($|\\?)/;\n\n/**\n * Virtual module id for the design-system CSS, collected explicitly up front.\n *\n * The canonical definition is `VIRTUAL_MODULE_ID` in\n * `packages/vitePlugins/src/designSystemPlugin/types.ts`. It is copied rather\n * than imported on purpose: `@pithyjs/vite-plugin` is a build tool and is\n * deliberately not a dependency of `@pithyjs/ssr`, and taking one on so two\n * modules could share a string would couple the runtime package to the plugin\n * package for nothing. `collect-css.test.ts` asserts the two are equal, so the\n * copy cannot drift.\n *\n * @internal Exported for testing\n */\n/** @codexApi {\"parent\":\"pithy.ssr.build.collect-css\",\"name\":\"DS_VIRTUAL_ID\",\"stability\":\"experimental\",\"signature\":\"'virtual:pithy-design-system'\"} */\nexport const DS_VIRTUAL_ID = 'virtual:pithy-design-system';\n\n/**\n * Whether a module URL is the design-system virtual module.\n *\n * Once the client entry is warmed, this module is in the graph with `id` and\n * `file` set to `\\0virtual:pithy-design-system.css` — but its `url` is the bare\n * `virtual:pithy-design-system`, with NO `.css`. Keying the walk on `url`\n * therefore failed the stylesheet filter and made the recovery unreachable,\n * so a transient failure of the explicit fetch became a false, non-waivable\n * exit 1 on an otherwise healthy export. Key on {@link moduleKey}. It is\n * already collected explicitly at the top of {@link collectCss}, and emitting\n * it again duplicates the entire design system, palette included.\n * @internal Exported for testing\n */\nexport function isDesignSystemVirtualModule(url: string): boolean {\n // ANCHORED, not a substring test. This gates the whole verdict below, so a\n // false positive exits 0 on a genuinely token-less export. `includes()` was\n // safe only by accident — it goes wrong the day any prefixed id exists, e.g.\n // `virtual:pithy-design-system-print.css`.\n const bare = url.replace(/\\0/g, '').split('?')[0];\n return bare === DS_VIRTUAL_ID || bare === `${DS_VIRTUAL_ID}.css`;\n}\n\n/** @internal Exported for testing */\nexport function isStylesheetUrl(url: string): boolean {\n return STYLESHEET_RE.test(url);\n}\n\n/**\n * Collapse the spellings Vite uses for the same module into one key.\n *\n * The same file appears in the graph as both `/@fs/Users/…` and `/@fs//Users/…`\n * depending on how it was resolved. Left unnormalized, each spelling is treated\n * as a distinct module and its CSS is emitted twice.\n *\n * Only the `/@fs/` prefix is collapsed — never repeated slashes elsewhere in the\n * string, which would merge distinct modules whose query values contain a URL\n * (`a.css?url=//cdn/x` vs `a.css?url=/cdn/x`).\n *\n * Prefer {@link moduleKey} where a `ModuleNode` is available.\n * @internal Exported for testing\n */\nexport function normalizeModuleUrl(url: string): string {\n return url.replace(/^(\\/@fs)\\/+/, '$1/');\n}\n\n/**\n * Key for a module known only by its URL.\n *\n * `/@fs/` is Vite's browser-facing spelling of an absolute path, while the graph\n * keys the same module on `id`/`file`, which carry the bare path. Both have to\n * produce one key: an entry-reached sheet whose module the graph cannot resolve\n * yet is recorded from its URL, and is emitted a second time when the graph walk\n * later finds it under the bare path.\n * @internal Exported for testing\n */\nexport function moduleKeyFromUrl(url: string): string {\n return normalizeModuleUrl(url).replace(/^\\/@fs/, '');\n}\n\n/**\n * Stable identity for a module in the graph.\n *\n * Vite already knows what a module *is*, so no regex has to guess at the URL.\n *\n * `id` first, not `file`: `id` is the key `idToModuleMap` itself uses, so it is\n * unique per module by construction. `file` is the query-stripped path, which\n * two genuinely distinct modules can share — `a.css` and `a.css?theme=dark`\n * resolve to one `file`, so keying on it drops one of them and its rules never\n * reach the output.\n * @internal Exported for testing\n */\nexport function moduleKey(mod: {\n file?: string | null;\n id?: string | null;\n url: string;\n}): string {\n return mod.id ?? mod.file ?? moduleKeyFromUrl(mod.url);\n}\n\n/**\n * Pull the client entry and everything it imports into the module graph, and\n * report the stylesheets it reaches **in import order**.\n *\n * SSG renders through SSR, which never executes the client entry — so the\n * entry's side-effect CSS imports (`import '@pithyjs/ui-kit/styles'`, an app's\n * own `styles.css`) are absent from the graph and would be silently dropped.\n * Walking the entry's import tree registers them.\n *\n * The returned order matters as much as the registration. In a real client\n * bundle the entry's imports are evaluated before any component's, so\n * `@pithyjs/ui-kit/styles` lands before a component stylesheet that overrides\n * it. The module graph is keyed by insertion, and SSR rendering has already\n * inserted component stylesheets by the time this runs, so iterating the graph\n * alone would emit those overrides *before* the rules they override — every\n * equal-specificity app override would win in `pnpm dev` and lose in the\n * exported HTML. Emitting the entry-reachable sheets in BFS order restores the\n * invariant the bundler used to provide.\n *\n * This is a genuine second compile pass, not a cache hit: the SSG render path\n * uses `ssrLoadModule`, which fills `ModuleNode.ssrTransformResult`, whereas\n * `transformRequest` without `{ ssr: true }` consults and fills the separate\n * client `transformResult`. Nothing here is free. The walk is bounded to\n * modules reachable from the entry, which is the price of knowing the order.\n *\n * Failures are non-fatal — an app may legitimately have no client entry\n * (`pithy.config.ts`-only apps) — but a failure of the **entry itself** is\n * reported, because it means no app CSS at all was registered and the build\n * would otherwise succeed while shipping unstyled HTML.\n *\n * @returns Stylesheets reachable from the entry, in import order, each paired\n * with the same identity key the graph walk uses so neither can emit a sheet\n * the other already did.\n */\nasync function warmClientEntry(\n vite: ViteDevServer,\n entryClient: string\n): Promise<Array<{ url: string; key: string }>> {\n const entryUrl = entryToUrl(entryClient);\n const queue: string[] = [entryUrl];\n const visited = new Set<string>();\n const stylesheets: Array<{ url: string; key: string }> = [];\n\n /**\n * Whether the configured client entry is actually on disk.\n *\n * Defensive on both sides: no root means no answer, and the caller treats an\n * unknown as present so a real failure still surfaces.\n */\n const entryFileExists = (): boolean => {\n const root = vite.config?.root;\n if (!root) return true;\n try {\n return existsSync(resolve(root, entryClient));\n } catch {\n return true;\n }\n };\n\n /**\n * Report a failure that hit the entry itself.\n *\n * A failure anywhere else costs one subtree; a failure on the entry costs\n * everything, because nothing downstream is ever enqueued. The graph walk\n * then finds no app stylesheets and the build emits styleless HTML and exits\n * 0 — the exact failure this warming exists to prevent, so it must be loud.\n */\n const warnEntryFailure = (stage: string, err: unknown): void => {\n // An app may legitimately have no client entry, and `entryClient` defaults\n // to \"src/main.ts\" whether or not one exists — so a missing file is the\n // documented case, not a fault, and warning about it is noise no config can\n // silence. Only a file that IS there and still failed indicates the\n // styleless-HTML failure this warning exists for. If the root cannot be\n // determined, warn: a missed warning costs a silently unstyled build.\n if (!entryFileExists()) return;\n console.log(\n ` Warning: could not ${stage} the client entry \"${entryUrl}\": ` +\n `${err instanceof Error ? err.message : err}\\n` +\n ` Static output will be missing every stylesheet the entry imports. ` +\n `Check the \\`entryClient\\` build option (default \"src/main.ts\").`\n );\n };\n\n while (queue.length > 0) {\n const url = queue.shift() as string;\n const key = moduleKeyFromUrl(url);\n if (visited.has(key)) continue;\n visited.add(key);\n\n try {\n await vite.transformRequest(url);\n } catch (err) {\n if (url === entryUrl) warnEntryFailure('transform', err);\n continue;\n }\n\n // `getModuleByUrl` resolves through the plugin container, so a plugin that\n // throws on an unusual specifier would reject here. Keep it inside a catch:\n // collection runs after every route has rendered, so an escaping rejection\n // would fail the whole build having written nothing. Collection must only\n // ever mean *missing* CSS, never a failed build.\n let mod;\n try {\n mod = await vite.moduleGraph.getModuleByUrl(url);\n } catch (err) {\n // On the entry this ends the walk before a single import is enqueued\n // (`if (!mod) continue` below), so it carries the same stakes as a failed\n // transform.\n if (url === entryUrl) warnEntryFailure('resolve', err);\n mod = undefined;\n }\n\n if (isStylesheetUrl(url)) {\n // Record the same identity the graph walk keys on, so a sheet found here\n // is not emitted a second time there.\n stylesheets.push({ url, key: mod ? moduleKey(mod) : key });\n // Do NOT descend into a stylesheet's imports. Sass has already inlined\n // every `@use`d partial into this module's compiled output; the partials\n // remain in the graph only for HMR tracking. Registering them too would\n // make the collector emit the same rules twice — once from the aggregate,\n // once per partial.\n continue;\n }\n\n // Transforming a module registers its direct imports. Follow them so CSS\n // that sits deeper than the entry (entry -> theme/index.ts -> theme.scss)\n // is reached too.\n if (!mod) continue;\n for (const imported of mod.importedModules) {\n // Same derivation `visited` is keyed with above — `normalizeModuleUrl`\n // keeps the `/@fs/` prefix, so using it here would never match a key that\n // was stored stripped and every `/@fs/` import would be re-enqueued.\n if (imported.url && !visited.has(moduleKeyFromUrl(imported.url))) {\n queue.push(imported.url);\n }\n }\n }\n\n return stylesheets;\n}\n\n/** The subset of a Vite plugin container this module needs. */\n\n/**\n * Diagnostics {@link collectCss} reports rather than throwing.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.build.collect-css\",\"name\":\"CollectCssOptions\",\"stability\":\"experimental\",\"signature\":\"interface CollectCssOptions { onDesignSystemFailure?: (error: Error) => void }\"} */\nexport interface CollectCssOptions {\n /**\n * Called once when a **registered** design-system plugin produced no CSS.\n *\n * This is the failure that ships an entire static site unstyled, so the\n * caller is expected to turn it into a build failure. It is reported through\n * a callback rather than a `throw` for a specific reason: `collectCss()` runs\n * before the exporter has written a single page, so throwing would turn a CSS\n * problem into zero output for the whole build — strictly worse than the\n * partial-output behaviour it is meant to improve on.\n *\n * Not called when no design-system plugin is registered at all. That app has\n * no tokens to lose, and failing its build would be failing it for a\n * different, separately-tracked gap.\n */\n onDesignSystemFailure?: (error: Error) => void;\n /**\n * Whether the app DECLARED a design system (`config.designSystem`).\n *\n * The declaration is the right signal, and plugin registration was the wrong\n * one. BUG-028's actual state was: `pithy.config.ts` declared a design system\n * and `vite.config.ts` registered no plugin to serve it — so a\n * registration probe answered \"false\", took the lenient branch, and shipped\n * five unstyled pages at exit 0. The bug the gate exists to catch was the one\n * case it could not see.\n *\n * Asking the config also removes a probe with side effects: Vite's\n * `resolveId` runs `buildStart()` if the container has not started, which for\n * `designSystemPlugin` means a full source rescan fired from a \"cheap\n * read-only check\" — and it answers from the client environment on Vite 6 and\n * SSR on Vite 7, so the same code gave opposite verdicts by major version.\n */\n designSystemDeclared?: boolean;\n}\n\n/**\n * Collect CSS from:\n * 1. The design system virtual module (utility classes like u-grid, u-flex, etc.)\n * 2. The client entry's import tree (see {@link warmClientEntry})\n * 3. Any .css/.scss modules in Vite's module graph\n *\n * @param vite - Dev server whose module graph is inspected.\n * @param entryClient - Client entry relative to the app root (e.g. `src/main.ts`).\n * Omit only when the app genuinely has no client entry; omitting it for an app\n * that has one silently drops every stylesheet the entry imports.\n * @param options - Diagnostic sinks. See {@link CollectCssOptions}.\n * @returns Every stylesheet found, concatenated. Never throws for a\n * design-system problem — see {@link CollectCssOptions.onDesignSystemFailure}.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.build.collect-css\",\"name\":\"collectCss\",\"stability\":\"experimental\",\"signature\":\"(vite: ViteDevServer, entryClient?: string, options?: CollectCssOptions) => Promise<string>\"} */\nexport async function collectCss(\n vite: ViteDevServer,\n entryClient?: string,\n options?: CollectCssOptions\n): Promise<string> {\n const chunks: string[] = [];\n\n // Stylesheets the entry reaches, in import order — emitted before anything\n // discovered by the graph walk so the cascade matches the client bundle.\n const entryStylesheets = entryClient\n ? await warmClientEntry(vite, entryClient)\n : [];\n\n // --- Design system utility CSS (virtual:pithy-design-system) ---\n // Tracks whether the explicit collection below actually produced a chunk.\n // The graph walk skips this module only when it did — otherwise a failure\n // here (wrapper format change, transient transform error) would be\n // compounded by the walk skipping the one copy that could still be recovered\n // from the graph, and the design system would vanish from the output.\n let collectedDesignSystem = false;\n\n /**\n * Why the explicit fetch produced nothing, kept for the final report.\n *\n * Recorded rather than reported on the spot: the graph walk below can still\n * recover this module, and announcing a failure the artifact does not have\n * is how a build warning becomes noise everyone scrolls past.\n */\n let designSystemFailure: Error | null = null;\n\n try {\n const dsResult = await vite.transformRequest(DS_VIRTUAL_ID);\n if (!dsResult?.code) {\n designSystemFailure = new Error(\n `${DS_VIRTUAL_ID} resolved but produced no module content.`\n );\n }\n if (dsResult?.code) {\n const css = extractCssFromJs(dsResult.code);\n if (css !== null && css.trim().length === 0) {\n // The wrapper was found and was EMPTY. Distinct from \"no wrapper\", and\n // worth saying so: otherwise the report read \"produced no CSS: no CSS\n // was produced\", which tells the reader nothing they did not already\n // have. Reachable when a third-party plugin claims the id.\n designSystemFailure = new Error(\n `${DS_VIRTUAL_ID} returned an empty stylesheet — ` +\n 'a plugin claims this id but emitted no rules.'\n );\n } else if (css && css.trim().length > 0) {\n chunks.push(`/* design-system utilities */\\n${css}`);\n collectedDesignSystem = true;\n } else if (css === null && dsResult.code.trim().length > 0) {\n // Only use raw code if it looks like plain CSS, not JS wrapper code.\n // Vite transforms CSS into JS modules with HMR boilerplate — pushing\n // that raw JS as CSS silently breaks styles.\n if (!looksLikeJs(dsResult.code)) {\n chunks.push(`/* design-system utilities */\\n${dsResult.code}`);\n collectedDesignSystem = true;\n } else {\n designSystemFailure = new Error(\n `Could not extract CSS from ${DS_VIRTUAL_ID}. ` +\n 'The Vite wrapper format may have changed.'\n );\n }\n }\n }\n } catch (err) {\n designSystemFailure = err instanceof Error ? err : new Error(String(err));\n }\n\n // --- Stylesheets, entry-reachable ones first ---\n //\n // Order is load-bearing: the entry's sheets must precede component sheets so\n // an equal-specificity app override still wins, exactly as it does in the\n // client bundle. The graph walk then picks up anything the entry does not\n // reach — component styles pulled in during SSR rendering, for instance.\n const seen = new Set<string>();\n\n // `key` is what the module is IDENTIFIED by (`mod.id`, which carries `.css`);\n // `url` is what it is FETCHED by. They differ for virtual modules, and\n // conflating them is what made the design-system recovery unreachable.\n const collectStylesheet = async (url: string, key = url): Promise<void> => {\n if (!isStylesheetUrl(key)) return;\n // Skip only if it was genuinely collected above. If that failed, fall\n // through and take it from the graph rather than emitting nothing.\n if (collectedDesignSystem && isDesignSystemVirtualModule(key)) return;\n\n try {\n const result = await vite.transformRequest(url);\n if (!result?.code) return;\n\n const css = extractCssFromJs(result.code);\n if (css && css.trim().length > 0) {\n chunks.push(`/* ${url} */\\n${css}`);\n // The explicit fetch above is not the only way this module reaches the\n // output. If the walk recovered it, the artifact has its tokens and\n // there is nothing left to report.\n if (isDesignSystemVirtualModule(key)) collectedDesignSystem = true;\n return;\n }\n if (css !== null || result.code.trim().length === 0) return;\n\n // No recognized wrapper. If it does not look like JS it *is* CSS — a\n // plugin returning CSS directly, a `?inline`/`?raw` variant — so take it\n // rather than dropping it. Mirrors the design-system branch above.\n if (!looksLikeJs(result.code)) {\n chunks.push(`/* ${url} */\\n${result.code}`);\n // Same recovery as the wrapped branch above, and it has to be recorded\n // on BOTH. A design system recovered as unwrapped CSS lands correctly\n // in the artifact; forgetting to say so here reported a build failure —\n // and exited 1 — for an export that was completely fine.\n if (isDesignSystemVirtualModule(key)) collectedDesignSystem = true;\n } else {\n console.log(\n `[collect-css] Could not extract CSS from ${url}. ` +\n 'The Vite wrapper format may have changed — CSS from this module will be missing.'\n );\n }\n } catch {\n // Skip modules that can't be transformed\n }\n };\n\n for (const { url, key } of entryStylesheets) {\n if (seen.has(key)) continue;\n seen.add(key);\n await collectStylesheet(url, key);\n }\n\n for (const mod of vite.moduleGraph.idToModuleMap.values()) {\n // Key on Vite's own identity for the module: `file`/`id` collapse the\n // `/@fs/` spellings by construction, where a URL regex could merge two\n // genuinely distinct modules whose query values contain a URL.\n const key = moduleKey(mod);\n if (seen.has(key)) continue;\n seen.add(key);\n await collectStylesheet(mod.url, key);\n }\n\n // --- Design-system verdict, once, with everything known ---\n //\n // Deferred to here rather than reported at the point of failure because the\n // graph walk above is a second chance at the same module. What matters is\n // whether the ARTIFACT ended up with the tokens, not whether one particular\n // fetch of them succeeded.\n if (!collectedDesignSystem) {\n const reason = designSystemFailure?.message ?? 'no CSS was produced';\n if (options?.designSystemDeclared) {\n // The app asked for a design system and did not get one. Every page in\n // this export is about to ship with undefined `var(--color-*)` references\n // and no way to recover — that is a build failure, not a warning.\n console.error(\n ` ERROR: this app declares a design system but ${DS_VIRTUAL_ID} ` +\n `produced no CSS: ${reason}\\n` +\n ' Every page would ship with undefined design tokens. ' +\n 'This is a build failure.'\n );\n options?.onDesignSystemFailure?.(\n designSystemFailure ??\n new Error(`${DS_VIRTUAL_ID} produced no CSS: ${reason}`)\n );\n } else {\n // Nothing registers the module. The app has no design system — a real\n // choice, and not this build's business to veto. Say so clearly enough\n // that an app which *meant* to have one recognises the omission.\n console.warn(\n ` Warning: no design-system plugin is registered, so ${DS_VIRTUAL_ID} ` +\n 'resolved to nothing and no design tokens were inlined.\\n' +\n ' Pages will render with whatever CSS the app supplies ' +\n 'itself. Add designSystemPlugin() to vite.config.ts if that is not ' +\n 'what you wanted.'\n );\n }\n }\n\n return chunks.join('\\n\\n');\n}\n"]}
@@ -0,0 +1,89 @@
1
+ /** @codex { "id": "pithy.ssr.build.css-live-props", "title": "Static Export Dead Custom-Property Purge", "category": "feature", "risk": "high" } */
2
+ /**
3
+ * Names kept however the CSS reads, because JavaScript composes them from a
4
+ * string at runtime and no scan of any kind can see the reference.
5
+ *
6
+ * Static export ships no framework JS, but it does still carry whatever
7
+ * `scripts` the caller configured, so these stay. Anything else a static page's
8
+ * own JS reads through `getComputedStyle` belongs in {@link DeadPropOptions}'s
9
+ * `safelist` — in particular `getDefaultTheme(true)`, which bootstraps a theme
10
+ * by READING `--color-*` off the sheet before anything has written it.
11
+ */
12
+ /** @codexApi {"parent":"pithy.ssr.build.css-live-props","name":"DEFAULT_LIVE_PROP_SAFELIST","stability":"experimental","signature":"readonly string[]"} */
13
+ export declare const DEFAULT_LIVE_PROP_SAFELIST: readonly string[];
14
+ /** @codexApi {"parent":"pithy.ssr.build.css-live-props","name":"DeadPropOptions","stability":"experimental","signature":"interface { safelist?: Iterable<string | RegExp>; htmlSources?: readonly string[] }"} */
15
+ export interface DeadPropOptions {
16
+ /**
17
+ * Extra names to keep, on top of {@link DEFAULT_LIVE_PROP_SAFELIST}. A
18
+ * trailing `*` makes the entry a prefix pattern (`--brand-*`); a `RegExp`
19
+ * is tested against the whole name.
20
+ *
21
+ * `RegExp` is accepted so the design-system plugin's `channelVarSafelist`,
22
+ * which this pass is given, can be forwarded without losing entries.
23
+ */
24
+ safelist?: Iterable<string | RegExp>;
25
+ /**
26
+ * Every rendered page's HTML. An inline `style="color:var(--x)"` is invisible
27
+ * to a CSS-only scan, and omitting this is how such a page loses its colour.
28
+ */
29
+ htmlSources?: readonly string[];
30
+ }
31
+ /**
32
+ * `keepCustomProperties`, coerced to an array BEFORE anything spreads it.
33
+ *
34
+ * A plain string is iterable, so `keepCustomProperties: '--brand'` spread into
35
+ * characters and produced one "ignoring \"-\"" warning per letter, none of
36
+ * which said the option takes an array — while the name itself was purged. A
37
+ * number or object is not iterable at all and threw.
38
+ *
39
+ * Exported because every caller that assembles the safelist must coerce first;
40
+ * `livePropSafelist` spread the raw option and hit both of those.
41
+ */
42
+ /** @codexApi {"parent":"pithy.ssr.build.css-live-props","name":"asSafelistArray","stability":"experimental","signature":"(value: unknown) => readonly (string | RegExp)[]"} */
43
+ export declare function asSafelistArray(value: unknown): readonly (string | RegExp)[];
44
+ /**
45
+ * Drop the custom-property declarations in `css` that nothing live references.
46
+ *
47
+ * Run it on the output of `purgeCssForPages` in `css-purge.ts`, not on the
48
+ * collected sheet: the rule purge is what makes a channel variable dead in the
49
+ * first place, by removing the unused utility rule that referenced it.
50
+ *
51
+ * @param css - Stylesheet text, already rule-purged.
52
+ * @param options - Safelist and the rendered HTML to read roots from.
53
+ * @returns The stylesheet with dead declarations spliced out.
54
+ */
55
+ /** @codexApi {"parent":"pithy.ssr.build.css-live-props","name":"purgeDeadCustomProps","stability":"experimental","signature":"(css: string, options?: DeadPropOptions) => string"} */
56
+ export declare function purgeDeadCustomProps(css: string, options?: DeadPropOptions): string;
57
+ /**
58
+ * Everything in a rendered page that can reference a custom property outside
59
+ * the stylesheet: the body fragment, the shell's `html`/`body` attribute values
60
+ * (`style="color:var(--x)"`), and inline `script` bodies, which ship in the
61
+ * page and can write a style string.
62
+ *
63
+ * Extracted and exported because the assembly in `runBuildSSG` is otherwise
64
+ * unreachable from a test — gutting it to `[]` reddened nothing, so a refactor
65
+ * could drop a source silently and every affected page would lose its colour.
66
+ */
67
+ /** @codexApi {"parent":"pithy.ssr.build.css-live-props","name":"collectHtmlSources","stability":"experimental","signature":"(pages: readonly LivePropPageSource[], sprite?: LivePropSpriteSource) => string[]"} */
68
+ export declare function collectHtmlSources(pages: readonly LivePropPageSource[], sprite?: LivePropSpriteSource): string[];
69
+ /** The shape {@link collectHtmlSources} needs from a sprite bundle. */
70
+ /** @codexApi {"parent":"pithy.ssr.build.css-live-props","name":"LivePropSpriteSource","stability":"experimental","signature":"interface { symbols?: ReadonlyMap<string, { inner?: string; presentation?: Record<string, string> }> }"} */
71
+ export interface LivePropSpriteSource {
72
+ symbols?: ReadonlyMap<string, {
73
+ inner?: string;
74
+ presentation?: Record<string, string>;
75
+ }>;
76
+ }
77
+ /** The shape {@link collectHtmlSources} needs from a rendered page. */
78
+ /** @codexApi {"parent":"pithy.ssr.build.css-live-props","name":"LivePropPageSource","stability":"experimental","signature":"interface { html?: string; head?: { htmlAttrs?: Record<string, string>; bodyAttrs?: Record<string, string>; script?: readonly { content?: string }[] } }"} */
79
+ export interface LivePropPageSource {
80
+ html?: string;
81
+ head?: {
82
+ htmlAttrs?: Record<string, string>;
83
+ bodyAttrs?: Record<string, string>;
84
+ script?: readonly {
85
+ content?: string;
86
+ }[];
87
+ };
88
+ }
89
+ //# sourceMappingURL=css-live-props.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"css-live-props.d.ts","sourceRoot":"","sources":["../../src/build/css-live-props.ts"],"names":[],"mappings":"AAAA,oJAAoJ;AAqCpJ;;;;;;;;;GASG;AACH,2JAA2J;AAC3J,eAAO,MAAM,0BAA0B,EAAE,SAAS,MAAM,EAUvD,CAAC;AAEF,kNAAkN;AAClN,MAAM,WAAW,eAAe;IAC9B;;;;;;;OAOG;IACH,QAAQ,CAAC,EAAE,QAAQ,CAAC,MAAM,GAAG,MAAM,CAAC,CAAC;IACrC;;;OAGG;IACH,WAAW,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CACjC;AAglBD;;;;;;;;;;GAUG;AACH,+KAA+K;AAC/K,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,GAAG,SAAS,CAAC,MAAM,GAAG,MAAM,CAAC,EAAE,CAoB5E;AAqDD;;;;;;;;;;GAUG;AACH,sLAAsL;AACtL,wBAAgB,oBAAoB,CAClC,GAAG,EAAE,MAAM,EACX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