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

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,237 @@
1
+ /** @codex
2
+ {
3
+ "id": "pithy.ssr.build.cli-exit",
4
+ "title": "SSG CLI Process Termination",
5
+ "category": "runtime",
6
+ "risk": "medium"
7
+ }
8
+ */
9
+ /**
10
+ * Deterministic process termination for the `pithy-ssg` CLI.
11
+ *
12
+ * A static export is **finished when the files are written**. Before this
13
+ * seam existed the CLI fell off the end of its top-level `await`, so Node kept
14
+ * the process alive until the event loop drained — handing control to whatever
15
+ * the *application* had scheduled during rendering. A single stray
16
+ * `setTimeout` whose callback threw then became an uncaught exception that
17
+ * killed the process with a non-zero status **after** a complete, correct
18
+ * export (BACKLOG #15b: `apps/basic-app` reported `Rendered: 73/73, Failed: 0`
19
+ * and still exited 1).
20
+ *
21
+ * The fix belongs here, in the CLI, and deliberately **not** in `buildSSG()`:
22
+ * `buildSSG` is a public library export (`@pithyjs/ssr/build`) that a caller
23
+ * may legitimately invoke mid-process and carry on afterwards. Terminating from
24
+ * inside a library function would be a far worse bug than the one being fixed.
25
+ * Process lifetime is the CLI's business alone.
26
+ *
27
+ * {@link guardAppScheduledErrors} covers the same failure DURING the export.
28
+ * That window is not a constant: it grew when the CSS purge landed, and a timer
29
+ * `apps/basic-app` had always scheduled (`AsyncBrokenComponent`, 2s) began
30
+ * firing before the pages were written — killing a build that had rendered
31
+ * every route. Whether an app's stray timer lands inside or outside the export
32
+ * is an accident of build duration, so both windows need the same answer.
33
+ *
34
+ * @module ssr/build/cli-exit
35
+ */
36
+ /**
37
+ * Milliseconds to wait for a stdio flush before giving up and exiting anyway.
38
+ *
39
+ * The flush can legitimately never complete — a reader that has gone away
40
+ * leaves the write callback pending forever (`EPIPE`). Hanging the build to
41
+ * protect output nobody is reading is the worse trade, so the wait is bounded.
42
+ */
43
+ const FLUSH_TIMEOUT_MS = 2000;
44
+ /**
45
+ * Resolve once everything queued on `stream` has been handed to the OS.
46
+ *
47
+ * A zero-length write's callback fires after all previously-queued writes have
48
+ * been processed, which is what makes this a flush rather than a guess. This
49
+ * matters because `process.exit()` **discards** anything still buffered on a
50
+ * pipe or file — the classic way a CI log loses its final lines. On a TTY the
51
+ * writes are already synchronous and this resolves immediately.
52
+ */
53
+ function flushStream(stream) {
54
+ if (stream.writableEnded || stream.destroyed)
55
+ return Promise.resolve();
56
+ return new Promise(resolve => {
57
+ let settled = false;
58
+ const done = () => {
59
+ if (settled)
60
+ return;
61
+ settled = true;
62
+ resolve();
63
+ };
64
+ // `unref()` so this safety net cannot itself hold the process open.
65
+ const timer = setTimeout(done, FLUSH_TIMEOUT_MS);
66
+ timer.unref?.();
67
+ stream.write('', () => {
68
+ clearTimeout(timer);
69
+ done();
70
+ });
71
+ });
72
+ }
73
+ /**
74
+ * Count timers/immediates still scheduled on the event loop.
75
+ *
76
+ * Reported rather than silently discarded: an app that schedules work during a
77
+ * static export is a real smell, and the next person deserves to see it.
78
+ */
79
+ function countPendingTimers() {
80
+ if (typeof process.getActiveResourcesInfo !== 'function')
81
+ return 0;
82
+ return process
83
+ .getActiveResourcesInfo()
84
+ .filter(resource => resource === 'Timeout' || resource === 'Immediate')
85
+ .length;
86
+ }
87
+ /** The message of an unknown throwable, for a one-line warning. */
88
+ function messageOf(error) {
89
+ return error instanceof Error ? error.message : String(error);
90
+ }
91
+ /**
92
+ * Run `body` with ownerless async errors downgraded to warnings.
93
+ *
94
+ * An error reaches a process-level handler only when nothing on the stack owns
95
+ * it — a `setTimeout` an app component scheduled while rendering, say. Node's
96
+ * default prints a stack and exits 1, which would let such a callback decide
97
+ * the fate of an export it has nothing to do with. Anything `body` itself
98
+ * throws or rejects is owned, and propagates untouched.
99
+ *
100
+ * Both windows the CLI has — the export, and the stdio flush after it — need
101
+ * exactly this, so it lives in one place.
102
+ *
103
+ * @param note - Builds the warning line for one downgraded error.
104
+ * @param body - The work to run.
105
+ * @returns What `body` resolved to, plus how many REJECTIONS were downgraded.
106
+ * A rejection's origin is not knowable from here — it may be the app's timer
107
+ * or the export's own unawaited promise — so what it costs is the caller's
108
+ * call, not this helper's.
109
+ */
110
+ async function withOwnerlessErrorsDowngraded(note, body) {
111
+ let rejections = 0;
112
+ const onThrow = (error) => {
113
+ console.warn(note('uncaughtException', error));
114
+ };
115
+ const onReject = (error) => {
116
+ rejections++;
117
+ console.warn(note('unhandledRejection', error));
118
+ };
119
+ process.on('uncaughtException', onThrow);
120
+ process.on('unhandledRejection', onReject);
121
+ try {
122
+ return { value: await body(), rejections };
123
+ }
124
+ finally {
125
+ process.off('uncaughtException', onThrow);
126
+ process.off('unhandledRejection', onReject);
127
+ }
128
+ }
129
+ /**
130
+ * End the CLI process once the export is complete.
131
+ *
132
+ * Sets an honest exit status, reports any leftover app timers in one line,
133
+ * flushes stdio so nothing is truncated, then terminates rather than waiting
134
+ * for the event loop to drain.
135
+ *
136
+ * **This only cuts short work scheduled after the export finished.** Anything
137
+ * that throws while rendering is still in progress rejects `buildSSG()`'s
138
+ * promise (or is collected into `failed`) and never reaches this function, so
139
+ * genuine build failures are unaffected.
140
+ *
141
+ * @param failedCount - Number of routes that failed to render. Non-zero exits 1
142
+ * unless `options.allowPartial` is set.
143
+ * @param options - Exit-status policy. Omitted entirely, the behaviour is the
144
+ * original strict one, so existing callers are unaffected.
145
+ */
146
+ /** @codexApi {"parent":"pithy.ssr.build.cli-exit","name":"endCliProcess","stability":"experimental","signature":"(failedCount: number, options?: EndCliProcessOptions) => Promise<void>"} */
147
+ export async function endCliProcess(failedCount, options) {
148
+ const allowPartial = options?.allowPartial ?? false;
149
+ const fatalCount = options?.fatalCount ?? 0;
150
+ // Two independent reasons to fail, and only the first is waivable.
151
+ const routesFailedTheBuild = failedCount > 0 && !allowPartial;
152
+ const code = routesFailedTheBuild || fatalCount > 0 ? 1 : 0;
153
+ // The two halves of the same fact, and never both. `buildSSG()` cannot print
154
+ // either — it is a library API that cannot see whether the flag was passed,
155
+ // and an unconditional "pass --allow-partial" hint contradicted the note
156
+ // below whenever it HAD been passed.
157
+ if (failedCount > 0 && allowPartial && fatalCount === 0) {
158
+ // Said out loud so a green CI run on a partial export is never a surprise:
159
+ // the flag was passed, and it is why this is a success.
160
+ console.log(` Note: ${failedCount} route(s) failed but --allow-partial was passed — ` +
161
+ `exiting 0. The pages that rendered are written; the ones that failed are not.`);
162
+ }
163
+ else if (routesFailedTheBuild && fatalCount === 0) {
164
+ // Offered only where it would actually change the outcome. Suppressed when
165
+ // a build-level failure is also present, because the flag would not help.
166
+ console.log(' (pass --allow-partial to exit 0 with the pages that did render)');
167
+ }
168
+ else if (failedCount > 0 && allowPartial && fatalCount > 0) {
169
+ // The combination whose exit status is easiest to misread, and the one that
170
+ // used to get no line at all: the author passed the flag, watched the route
171
+ // failures scroll past, and got exit 1 with nothing saying why the flag did
172
+ // not apply. It was honoured — for routes. A build-level failure is not
173
+ // waivable because it affects every page, not one.
174
+ console.log(` Note: --allow-partial waived ${failedCount} route failure(s), but ` +
175
+ `${fatalCount} build-level failure(s) cannot be waived — exiting 1. ` +
176
+ 'A build-level failure affects every page that was written.');
177
+ }
178
+ // Set before exiting so the status is already correct if anything below
179
+ // throws, and so a `process.exit()` with no argument would still be honest.
180
+ process.exitCode = code;
181
+ const pending = countPendingTimers();
182
+ if (pending > 0) {
183
+ // Printed before the flush so it cannot be the thing that gets truncated.
184
+ console.log(` Note: ${pending} timer(s) still pending at exit — the export is complete and unaffected, but an app scheduling timers during static export is worth a look.`);
185
+ }
186
+ // Awaiting the flush hands control back to the event loop, so a pending app
187
+ // timer can fire *inside* this window. If it throws, Node's default handler
188
+ // would print a stack and exit 1 — turning a completed export into a failure
189
+ // at the last possible moment, and only when output is slow enough to make
190
+ // the flush actually yield. The decision is already made by this point, so
191
+ // for the duration of the flush nothing is allowed to change it — a rejection
192
+ // included, which is why the count this returns is discarded here and not in
193
+ // {@link guardAppScheduledErrors}.
194
+ await withOwnerlessErrorsDowngraded((_kind, error) => ` Note: an app callback threw after the export completed — ignored, exit status unchanged (${messageOf(error)})`, async () => {
195
+ await flushStream(process.stdout);
196
+ await flushStream(process.stderr);
197
+ });
198
+ process.exit(code);
199
+ }
200
+ /**
201
+ * Run an export with ownerless async errors downgraded, so a stray callback
202
+ * cannot kill a build that is rendering every route correctly.
203
+ *
204
+ * The two events are treated differently, and this is a POLICY CHOICE rather
205
+ * than something derived — neither event carries its origin:
206
+ *
207
+ * - An **uncaught throw** is the timer case this guard exists for
208
+ * (`apps/basic-app`'s `AsyncBrokenComponent`). The export is unaffected, and
209
+ * so is the exit status.
210
+ * - A **rejection** is counted, so the build does not get to pass. Still
211
+ * downgraded, so the pages that rendered are written.
212
+ *
213
+ * The honest asymmetry: a throw is ALSO unattributable. One raised inside a
214
+ * framework-owned `fs` callback reaches the same handler and exits 0, so a
215
+ * framework bug shows up only as the warning above. Making throws fatal would
216
+ * fail every build of an app that schedules a timer — the case this exists for
217
+ * — so the trade was taken deliberately, not deduced. Two known costs, tracked
218
+ * as BACKLOG #62 rather than settled here: that blind spot, and the fact that
219
+ * handling `uncaughtException` suspends Node's crash-on-error for the export
220
+ * window, so a throw inside `buildSSG`'s own async flow can leave its promise
221
+ * unsettled and hang where it used to crash.
222
+ *
223
+ * Only the CLI may install this. A library caller has its own handlers and its
224
+ * own view of which errors matter; {@link endCliProcess} carries the same
225
+ * reasoning for process lifetime.
226
+ *
227
+ * @param body - The export to run.
228
+ * @returns What `body` resolved to, and how many rejections were downgraded.
229
+ */
230
+ /** @codexApi {"parent":"pithy.ssr.build.cli-exit","name":"guardAppScheduledErrors","stability":"experimental","signature":"<T>(body: () => Promise<T>) => Promise<{ value: T; rejections: number }>"} */
231
+ export async function guardAppScheduledErrors(body) {
232
+ return withOwnerlessErrorsDowngraded((kind, error) => kind === 'uncaughtException'
233
+ ? ` Note: a callback threw during the export — ignored, and the exit status is unchanged (${messageOf(error)}). Usually a component scheduling timers during a static export, which is worth a look; it can also be a framework bug, and this note is the only sign of one.`
234
+ : ` Note: a promise rejected with no owner during the export (${messageOf(error)}). The export carries on, but this counts as a build-level failure — ` +
235
+ "it may be the app's, or the export's own unawaited promise, and nothing here can tell.", body);
236
+ }
237
+ //# sourceMappingURL=cli-exit.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli-exit.js","sourceRoot":"","sources":["../../src/build/cli-exit.ts"],"names":[],"mappings":"AAAA;;;;;;;EAOE;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH;;;;;;GAMG;AACH,MAAM,gBAAgB,GAAG,IAAI,CAAC;AAE9B;;;;;;;;GAQG;AACH,SAAS,WAAW,CAAC,MAA0B;IAC7C,IAAI,MAA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;;;;;;;;;;;;;;GA6BG;AACH,yMAAyM;AACzM,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAC3C,IAAsB;IAEtB,OAAO,6BAA6B,CAClC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CACd,IAAI,KAAK,mBAAmB;QAC1B,CAAC,CAAC,2FAA2F,SAAS,CAClG,KAAK,CACN,gKAAgK;QACnK,CAAC,CAAC,+DAA+D,SAAS,CACtE,KAAK,CACN,uEAAuE;YACxE,wFAAwF,EAC9F,IAAI,CACL,CAAC;AACJ,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.ssr.build.cli-exit\",\n \"title\": \"SSG CLI Process Termination\",\n \"category\": \"runtime\",\n \"risk\": \"medium\"\n}\n*/\n\n/**\n * Deterministic process termination for the `pithy-ssg` CLI.\n *\n * A static export is **finished when the files are written**. Before this\n * seam existed the CLI fell off the end of its top-level `await`, so Node kept\n * the process alive until the event loop drained — handing control to whatever\n * the *application* had scheduled during rendering. A single stray\n * `setTimeout` whose callback threw then became an uncaught exception that\n * killed the process with a non-zero status **after** a complete, correct\n * export (BACKLOG #15b: `apps/basic-app` reported `Rendered: 73/73, Failed: 0`\n * and still exited 1).\n *\n * The fix belongs here, in the CLI, and deliberately **not** in `buildSSG()`:\n * `buildSSG` is a public library export (`@pithyjs/ssr/build`) that a caller\n * may legitimately invoke mid-process and carry on afterwards. Terminating from\n * inside a library function would be a far worse bug than the one being fixed.\n * Process lifetime is the CLI's business alone.\n *\n * {@link guardAppScheduledErrors} covers the same failure DURING the export.\n * That window is not a constant: it grew when the CSS purge landed, and a timer\n * `apps/basic-app` had always scheduled (`AsyncBrokenComponent`, 2s) began\n * firing before the pages were written — killing a build that had rendered\n * every route. Whether an app's stray timer lands inside or outside the export\n * is an accident of build duration, so both windows need the same answer.\n *\n * @module ssr/build/cli-exit\n */\n\n/**\n * Milliseconds to wait for a stdio flush before giving up and exiting anyway.\n *\n * The flush can legitimately never complete — a reader that has gone away\n * leaves the write callback pending forever (`EPIPE`). Hanging the build to\n * protect output nobody is reading is the worse trade, so the wait is bounded.\n */\nconst FLUSH_TIMEOUT_MS = 2000;\n\n/**\n * Resolve once everything queued on `stream` has been handed to the OS.\n *\n * A zero-length write's callback fires after all previously-queued writes have\n * been processed, which is what makes this a flush rather than a guess. This\n * matters because `process.exit()` **discards** anything still buffered on a\n * pipe or file — the classic way a CI log loses its final lines. On a TTY the\n * writes are already synchronous and this resolves immediately.\n */\nfunction flushStream(stream: NodeJS.WriteStream): Promise<void> {\n if (stream.writableEnded || stream.destroyed) return Promise.resolve();\n\n return new Promise<void>(resolve => {\n let settled = false;\n const done = (): void => {\n if (settled) return;\n settled = true;\n resolve();\n };\n\n // `unref()` so this safety net cannot itself hold the process open.\n const timer = setTimeout(done, FLUSH_TIMEOUT_MS);\n timer.unref?.();\n\n stream.write('', () => {\n clearTimeout(timer);\n done();\n });\n });\n}\n\n/**\n * Count timers/immediates still scheduled on the event loop.\n *\n * Reported rather than silently discarded: an app that schedules work during a\n * static export is a real smell, and the next person deserves to see it.\n */\nfunction countPendingTimers(): number {\n if (typeof process.getActiveResourcesInfo !== 'function') return 0;\n return process\n .getActiveResourcesInfo()\n .filter(resource => resource === 'Timeout' || resource === 'Immediate')\n .length;\n}\n\n/** Which process event a downgraded error arrived on. */\ntype OwnerlessErrorKind = 'uncaughtException' | 'unhandledRejection';\n\n/** The message of an unknown throwable, for a one-line warning. */\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/**\n * Run `body` with ownerless async errors downgraded to warnings.\n *\n * An error reaches a process-level handler only when nothing on the stack owns\n * it — a `setTimeout` an app component scheduled while rendering, say. Node's\n * default prints a stack and exits 1, which would let such a callback decide\n * the fate of an export it has nothing to do with. Anything `body` itself\n * throws or rejects is owned, and propagates untouched.\n *\n * Both windows the CLI has — the export, and the stdio flush after it — need\n * exactly this, so it lives in one place.\n *\n * @param note - Builds the warning line for one downgraded error.\n * @param body - The work to run.\n * @returns What `body` resolved to, plus how many REJECTIONS were downgraded.\n * A rejection's origin is not knowable from here — it may be the app's timer\n * or the export's own unawaited promise — so what it costs is the caller's\n * call, not this helper's.\n */\nasync function withOwnerlessErrorsDowngraded<T>(\n note: (kind: OwnerlessErrorKind, error: unknown) => string,\n body: () => Promise<T>\n): Promise<{ value: T; rejections: number }> {\n let rejections = 0;\n const onThrow = (error: unknown): void => {\n console.warn(note('uncaughtException', error));\n };\n const onReject = (error: unknown): void => {\n rejections++;\n console.warn(note('unhandledRejection', error));\n };\n\n process.on('uncaughtException', onThrow);\n process.on('unhandledRejection', onReject);\n try {\n return { value: await body(), rejections };\n } finally {\n process.off('uncaughtException', onThrow);\n process.off('unhandledRejection', onReject);\n }\n}\n\n/**\n * How the caller wants failures translated into an exit status.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.build.cli-exit\",\"name\":\"EndCliProcessOptions\",\"stability\":\"experimental\",\"signature\":\"interface EndCliProcessOptions { allowPartial?: boolean; fatalCount?: number }\"} */\nexport interface EndCliProcessOptions {\n /**\n * Treat failed routes as a warning rather than a build failure\n * (`--allow-partial`; default `false`).\n *\n * The pages that rendered were already written before this function runs —\n * the export loop collects a throwing route into `failed` and carries on, and\n * page writing happens afterwards. So this flag changes the exit status and\n * nothing else. It exists because a single unexportable route used to make\n * the whole command exit 1 with no way to say \"I know, show me the rest\".\n */\n allowPartial?: boolean;\n /**\n * Failures no `--allow-partial` can excuse — the export as a whole, rather\n * than one route.\n *\n * Two shapes, both non-waivable for the same reason. The export RAN and\n * something spoiled every page: a failed design-system stylesheet unstyles\n * all of them, and for a static export \"unstyled\" is the finished artifact —\n * no JavaScript arrives later to fix it. Or the export never started at all,\n * because the arguments were rejected; there is no partial result to allow.\n *\n * A flag whose name promises a *partial* result must not be readable as\n * permission to ship a whole broken one, nor as permission to ignore a\n * command line the CLI refused.\n */\n fatalCount?: number;\n}\n\n/**\n * End the CLI process once the export is complete.\n *\n * Sets an honest exit status, reports any leftover app timers in one line,\n * flushes stdio so nothing is truncated, then terminates rather than waiting\n * for the event loop to drain.\n *\n * **This only cuts short work scheduled after the export finished.** Anything\n * that throws while rendering is still in progress rejects `buildSSG()`'s\n * promise (or is collected into `failed`) and never reaches this function, so\n * genuine build failures are unaffected.\n *\n * @param failedCount - Number of routes that failed to render. Non-zero exits 1\n * unless `options.allowPartial` is set.\n * @param options - Exit-status policy. Omitted entirely, the behaviour is the\n * original strict one, so existing callers are unaffected.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.build.cli-exit\",\"name\":\"endCliProcess\",\"stability\":\"experimental\",\"signature\":\"(failedCount: number, options?: EndCliProcessOptions) => Promise<void>\"} */\nexport async function endCliProcess(\n failedCount: number,\n options?: EndCliProcessOptions\n): Promise<void> {\n const allowPartial = options?.allowPartial ?? false;\n const fatalCount = options?.fatalCount ?? 0;\n\n // Two independent reasons to fail, and only the first is waivable.\n const routesFailedTheBuild = failedCount > 0 && !allowPartial;\n const code = routesFailedTheBuild || fatalCount > 0 ? 1 : 0;\n\n // The two halves of the same fact, and never both. `buildSSG()` cannot print\n // either — it is a library API that cannot see whether the flag was passed,\n // and an unconditional \"pass --allow-partial\" hint contradicted the note\n // below whenever it HAD been passed.\n if (failedCount > 0 && allowPartial && fatalCount === 0) {\n // Said out loud so a green CI run on a partial export is never a surprise:\n // the flag was passed, and it is why this is a success.\n console.log(\n ` Note: ${failedCount} route(s) failed but --allow-partial was passed — ` +\n `exiting 0. The pages that rendered are written; the ones that failed are not.`\n );\n } else if (routesFailedTheBuild && fatalCount === 0) {\n // Offered only where it would actually change the outcome. Suppressed when\n // a build-level failure is also present, because the flag would not help.\n console.log(\n ' (pass --allow-partial to exit 0 with the pages that did render)'\n );\n } else if (failedCount > 0 && allowPartial && fatalCount > 0) {\n // The combination whose exit status is easiest to misread, and the one that\n // used to get no line at all: the author passed the flag, watched the route\n // failures scroll past, and got exit 1 with nothing saying why the flag did\n // not apply. It was honoured — for routes. A build-level failure is not\n // waivable because it affects every page, not one.\n console.log(\n ` Note: --allow-partial waived ${failedCount} route failure(s), but ` +\n `${fatalCount} build-level failure(s) cannot be waived — exiting 1. ` +\n 'A build-level failure affects every page that was written.'\n );\n }\n\n // Set before exiting so the status is already correct if anything below\n // throws, and so a `process.exit()` with no argument would still be honest.\n process.exitCode = code;\n\n const pending = countPendingTimers();\n if (pending > 0) {\n // Printed before the flush so it cannot be the thing that gets truncated.\n console.log(\n ` Note: ${pending} timer(s) still pending at exit — the export is complete and unaffected, but an app scheduling timers during static export is worth a look.`\n );\n }\n\n // Awaiting the flush hands control back to the event loop, so a pending app\n // timer can fire *inside* this window. If it throws, Node's default handler\n // would print a stack and exit 1 — turning a completed export into a failure\n // at the last possible moment, and only when output is slow enough to make\n // the flush actually yield. The decision is already made by this point, so\n // for the duration of the flush nothing is allowed to change it — a rejection\n // included, which is why the count this returns is discarded here and not in\n // {@link guardAppScheduledErrors}.\n await withOwnerlessErrorsDowngraded(\n (_kind, error) =>\n ` Note: an app callback threw after the export completed — ignored, exit status unchanged (${messageOf(\n error\n )})`,\n async () => {\n await flushStream(process.stdout);\n await flushStream(process.stderr);\n }\n );\n\n process.exit(code);\n}\n\n/**\n * Run an export with ownerless async errors downgraded, so a stray callback\n * cannot kill a build that is rendering every route correctly.\n *\n * The two events are treated differently, and this is a POLICY CHOICE rather\n * than something derived — neither event carries its origin:\n *\n * - An **uncaught throw** is the timer case this guard exists for\n * (`apps/basic-app`'s `AsyncBrokenComponent`). The export is unaffected, and\n * so is the exit status.\n * - A **rejection** is counted, so the build does not get to pass. Still\n * downgraded, so the pages that rendered are written.\n *\n * The honest asymmetry: a throw is ALSO unattributable. One raised inside a\n * framework-owned `fs` callback reaches the same handler and exits 0, so a\n * framework bug shows up only as the warning above. Making throws fatal would\n * fail every build of an app that schedules a timer — the case this exists for\n * — so the trade was taken deliberately, not deduced. Two known costs, tracked\n * as BACKLOG #62 rather than settled here: that blind spot, and the fact that\n * handling `uncaughtException` suspends Node's crash-on-error for the export\n * window, so a throw inside `buildSSG`'s own async flow can leave its promise\n * unsettled and hang where it used to crash.\n *\n * Only the CLI may install this. A library caller has its own handlers and its\n * own view of which errors matter; {@link endCliProcess} carries the same\n * reasoning for process lifetime.\n *\n * @param body - The export to run.\n * @returns What `body` resolved to, and how many rejections were downgraded.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.build.cli-exit\",\"name\":\"guardAppScheduledErrors\",\"stability\":\"experimental\",\"signature\":\"<T>(body: () => Promise<T>) => Promise<{ value: T; rejections: number }>\"} */\nexport async function guardAppScheduledErrors<T>(\n body: () => Promise<T>\n): Promise<{ value: T; rejections: number }> {\n return withOwnerlessErrorsDowngraded(\n (kind, error) =>\n kind === 'uncaughtException'\n ? ` Note: a callback threw during the export — ignored, and the exit status is unchanged (${messageOf(\n error\n )}). Usually a component scheduling timers during a static export, which is worth a look; it can also be a framework bug, and this note is the only sign of one.`\n : ` Note: a promise rejected with no owner during the export (${messageOf(\n error\n )}). The export carries on, but this counts as a build-level failure — ` +\n \"it may be the app's, or the export's own unawaited promise, and nothing here can tell.\",\n body\n );\n}\n"]}
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+ /** @codex
3
+ {
4
+ "id": "pithy.ssr.build.cli",
5
+ "title": "pithy-ssg CLI Entry",
6
+ "category": "runtime",
7
+ "risk": "medium"
8
+ }
9
+ */
10
+ export {};
11
+ //# sourceMappingURL=cli.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../../src/build/cli.ts"],"names":[],"mappings":";AACA;;;;;;;EAOE"}
@@ -0,0 +1,93 @@
1
+ #!/usr/bin/env node
2
+ /** @codex
3
+ {
4
+ "id": "pithy.ssr.build.cli",
5
+ "title": "pithy-ssg CLI Entry",
6
+ "category": "runtime",
7
+ "risk": "medium"
8
+ }
9
+ */
10
+ /**
11
+ * pithy-ssg CLI
12
+ *
13
+ * Usage:
14
+ * pithy-ssg — static HTML only (no JS)
15
+ * pithy-ssg --hydrate — static HTML + client JS (interactive after hydration)
16
+ * pithy-ssg --allow-partial — exit 0 even if some routes failed to render
17
+ * pithy-ssg --help — print usage and exit
18
+ *
19
+ * This file is an executable script: importing it runs a build. Everything that
20
+ * can be tested without doing that lives in `./cli-args.ts` and `./cli-exit.ts`.
21
+ *
22
+ * @module ssr/build/cli
23
+ */
24
+ import { buildSSG } from './vite-ssg.js';
25
+ import { endCliProcess, guardAppScheduledErrors } from './cli-exit.js';
26
+ import { parseSsgArgs, SSG_USAGE } from './cli-args.js';
27
+ const options = parseSsgArgs(process.argv.slice(2));
28
+ if (options.help) {
29
+ // Checked before anything else, and before the unknown-argument warning: a
30
+ // reader who typed `--help` wants the usage block, not a static export of
31
+ // whatever directory they happened to be standing in.
32
+ // Through `endCliProcess`, not a bare `process.exit(0)`: pipes are
33
+ // asynchronous on macOS and Linux, so exiting straight after a write can
34
+ // discard it. `pithy-ssg --help | cat`, or `--help` captured by a CI log
35
+ // collector, printed truncated output or nothing at all.
36
+ console.log(SSG_USAGE);
37
+ await endCliProcess(0, { allowPartial: false, fatalCount: 0 });
38
+ }
39
+ if (options.invalid.length > 0) {
40
+ // Fatal, unlike an unrecognised flag. Every flag here is boolean, so
41
+ // `--hydrate=true` is not a typo that errs toward strictness — it silently
42
+ // produced a static export for an author who asked for a hydrating one.
43
+ console.error(` Error: this CLI takes no --flag=value arguments: ${options.invalid.join(', ')}\n` +
44
+ ' All flags are boolean; pass the flag alone, or omit it.');
45
+ await endCliProcess(0, { allowPartial: false, fatalCount: 1 });
46
+ }
47
+ if (options.unknown.length > 0) {
48
+ // Not fatal — ignoring extra arguments is the behaviour every existing caller
49
+ // relies on — but never silent: an unrecognised `--allow-partials` would
50
+ // otherwise produce a strict build the author believes is permissive.
51
+ console.warn(` Warning: ignoring unrecognised argument(s): ${options.unknown.join(', ')}`);
52
+ }
53
+ // Guarded, so a throwing export still reports through the one path that owns
54
+ // exit status. Unguarded, a plugin error skipped `endCliProcess` entirely:
55
+ // `--allow-partial` was silently inert, and stderr carried the raw error object
56
+ // — ~89 lines including the full source of the offending module in
57
+ // `pluginCode`. The status was already 1; what was missing was the reporting.
58
+ let result;
59
+ // Ownerless REJECTIONS during the export, which the guard cannot attribute to
60
+ // the app rather than to `buildSSG` itself. Counted as build-level failures so
61
+ // a framework bug cannot be printed as the app's fault and exit 0 anyway.
62
+ let ownerlessRejections = 0;
63
+ try {
64
+ // Guarded for the same reason `endCliProcess` guards the flush: a throw from
65
+ // an app's own timer must not decide the fate of an export that is rendering
66
+ // every route correctly. See ./cli-exit.ts.
67
+ const guarded = await guardAppScheduledErrors(() => buildSSG({
68
+ hydrate: options.hydrate,
69
+ }));
70
+ result = guarded.value;
71
+ ownerlessRejections = guarded.rejections;
72
+ }
73
+ catch (err) {
74
+ const error = err instanceof Error ? err : new Error(String(err));
75
+ console.error(`\n Build failed: ${error.message}`);
76
+ if (error.stack)
77
+ console.error(error.stack.split('\n').slice(1, 4).join('\n'));
78
+ await endCliProcess(0, { allowPartial: false, fatalCount: 1 });
79
+ throw error; // unreachable — endCliProcess exits — but keeps `result` defined
80
+ }
81
+ // The export is complete here — every page has been written. Terminate on that
82
+ // fact rather than waiting for the event loop to drain, which would hand the
83
+ // build's exit status to whatever timers the app happened to leave behind.
84
+ // See ./cli-exit.ts for why this lives in the CLI and not in buildSSG().
85
+ //
86
+ // `--allow-partial` waives failed ROUTES only. A build-level failure (the
87
+ // design system producing no CSS, say) affects every page that was just
88
+ // written, so it is counted separately and cannot be waived.
89
+ await endCliProcess(result.failed.length, {
90
+ allowPartial: options.allowPartial,
91
+ fatalCount: result.buildFailures.length + ownerlessRejections,
92
+ });
93
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.js","sourceRoot":"","sources":["../../src/build/cli.ts"],"names":[],"mappings":";AACA;;;;;;;EAOE;AAEF;;;;;;;;;;;;;GAaG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,aAA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** @codex\n{\n \"id\": \"pithy.ssr.build.cli\",\n \"title\": \"pithy-ssg CLI Entry\",\n \"category\": \"runtime\",\n \"risk\": \"medium\"\n}\n*/\n\n/**\n * pithy-ssg CLI\n *\n * Usage:\n * pithy-ssg — static HTML only (no JS)\n * pithy-ssg --hydrate — static HTML + client JS (interactive after hydration)\n * pithy-ssg --allow-partial — exit 0 even if some routes failed to render\n * pithy-ssg --help — print usage and exit\n *\n * This file is an executable script: importing it runs a build. Everything that\n * can be tested without doing that lives in `./cli-args.ts` and `./cli-exit.ts`.\n *\n * @module ssr/build/cli\n */\nimport { buildSSG } from './vite-ssg.js';\nimport { endCliProcess, guardAppScheduledErrors } from './cli-exit.js';\nimport { parseSsgArgs, SSG_USAGE } from './cli-args.js';\n\nconst options = parseSsgArgs(process.argv.slice(2));\n\nif (options.help) {\n // Checked before anything else, and before the unknown-argument warning: a\n // reader who typed `--help` wants the usage block, not a static export of\n // whatever directory they happened to be standing in.\n // Through `endCliProcess`, not a bare `process.exit(0)`: pipes are\n // asynchronous on macOS and Linux, so exiting straight after a write can\n // discard it. `pithy-ssg --help | cat`, or `--help` captured by a CI log\n // collector, printed truncated output or nothing at all.\n console.log(SSG_USAGE);\n await endCliProcess(0, { allowPartial: false, fatalCount: 0 });\n}\n\nif (options.invalid.length > 0) {\n // Fatal, unlike an unrecognised flag. Every flag here is boolean, so\n // `--hydrate=true` is not a typo that errs toward strictness — it silently\n // produced a static export for an author who asked for a hydrating one.\n console.error(\n ` Error: this CLI takes no --flag=value arguments: ${options.invalid.join(', ')}\\n` +\n ' All flags are boolean; pass the flag alone, or omit it.'\n );\n await endCliProcess(0, { allowPartial: false, fatalCount: 1 });\n}\n\nif (options.unknown.length > 0) {\n // Not fatal — ignoring extra arguments is the behaviour every existing caller\n // relies on — but never silent: an unrecognised `--allow-partials` would\n // otherwise produce a strict build the author believes is permissive.\n console.warn(\n ` Warning: ignoring unrecognised argument(s): ${options.unknown.join(', ')}`\n );\n}\n\n// Guarded, so a throwing export still reports through the one path that owns\n// exit status. Unguarded, a plugin error skipped `endCliProcess` entirely:\n// `--allow-partial` was silently inert, and stderr carried the raw error object\n// — ~89 lines including the full source of the offending module in\n// `pluginCode`. The status was already 1; what was missing was the reporting.\nlet result;\n// Ownerless REJECTIONS during the export, which the guard cannot attribute to\n// the app rather than to `buildSSG` itself. Counted as build-level failures so\n// a framework bug cannot be printed as the app's fault and exit 0 anyway.\nlet ownerlessRejections = 0;\ntry {\n // Guarded for the same reason `endCliProcess` guards the flush: a throw from\n // an app's own timer must not decide the fate of an export that is rendering\n // every route correctly. See ./cli-exit.ts.\n const guarded = await guardAppScheduledErrors(() =>\n buildSSG({\n hydrate: options.hydrate,\n })\n );\n result = guarded.value;\n ownerlessRejections = guarded.rejections;\n} catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n console.error(`\\n Build failed: ${error.message}`);\n if (error.stack)\n console.error(error.stack.split('\\n').slice(1, 4).join('\\n'));\n await endCliProcess(0, { allowPartial: false, fatalCount: 1 });\n throw error; // unreachable — endCliProcess exits — but keeps `result` defined\n}\n\n// The export is complete here — every page has been written. Terminate on that\n// fact rather than waiting for the event loop to drain, which would hand the\n// build's exit status to whatever timers the app happened to leave behind.\n// See ./cli-exit.ts for why this lives in the CLI and not in buildSSG().\n//\n// `--allow-partial` waives failed ROUTES only. A build-level failure (the\n// design system producing no CSS, say) affects every page that was just\n// written, so it is counted separately and cannot be waived.\nawait endCliProcess(result.failed.length, {\n allowPartial: options.allowPartial,\n fatalCount: result.buildFailures.length + ownerlessRejections,\n});\n"]}
@@ -0,0 +1,168 @@
1
+ /** @codex
2
+ {
3
+ "id": "pithy.ssr.build.collect-css",
4
+ "title": "SSG CSS Collector",
5
+ "category": "feature",
6
+ "risk": "critical"
7
+ }
8
+ */
9
+ import type { ViteDevServer } from 'vite';
10
+ /**
11
+ * Extract CSS string from a Vite-transformed JS module.
12
+ *
13
+ * Vite wraps CSS as JS exports like:
14
+ * const __vite__css = "..."
15
+ * export default "..."
16
+ * __vite_ssr_export_default__("...")
17
+ *
18
+ * This regex matches the quoted CSS content from any of those forms.
19
+ */
20
+ /** @internal Exported for testing */
21
+ export declare const CSS_JS_RE: RegExp;
22
+ export declare function looksLikeJs(code: string): boolean;
23
+ /** @internal Exported for testing */
24
+ export declare function unescapeCssString(raw: string): string;
25
+ /**
26
+ * Extract CSS from a Vite-transformed JS module string.
27
+ * Returns the unescaped CSS or null if no CSS pattern is found.
28
+ * @internal Exported for testing
29
+ */
30
+ export declare function extractCssFromJs(code: string): string | null;
31
+ /**
32
+ * Normalize a root-relative client entry path to a Vite request URL.
33
+ *
34
+ * `entryClient` arrives as a path relative to the app root (`src/main.ts`),
35
+ * but `transformRequest` expects a root-absolute URL (`/src/main.ts`).
36
+ * @internal Exported for testing
37
+ */
38
+ export declare function entryToUrl(entryClient: string): string;
39
+ /**
40
+ * Virtual module id for the design-system CSS, collected explicitly up front.
41
+ *
42
+ * The canonical definition is `VIRTUAL_MODULE_ID` in
43
+ * `packages/vitePlugins/src/designSystemPlugin/types.ts`. It is copied rather
44
+ * than imported on purpose: `@pithyjs/vite-plugin` is a build tool and is
45
+ * deliberately not a dependency of `@pithyjs/ssr`, and taking one on so two
46
+ * modules could share a string would couple the runtime package to the plugin
47
+ * package for nothing. `collect-css.test.ts` asserts the two are equal, so the
48
+ * copy cannot drift.
49
+ *
50
+ * @internal Exported for testing
51
+ */
52
+ /** @codexApi {"parent":"pithy.ssr.build.collect-css","name":"DS_VIRTUAL_ID","stability":"experimental","signature":"'virtual:pithy-design-system'"} */
53
+ export declare const DS_VIRTUAL_ID = "virtual:pithy-design-system";
54
+ /**
55
+ * Whether a module URL is the design-system virtual module.
56
+ *
57
+ * Once the client entry is warmed, this module is in the graph with `id` and
58
+ * `file` set to `\0virtual:pithy-design-system.css` — but its `url` is the bare
59
+ * `virtual:pithy-design-system`, with NO `.css`. Keying the walk on `url`
60
+ * therefore failed the stylesheet filter and made the recovery unreachable,
61
+ * so a transient failure of the explicit fetch became a false, non-waivable
62
+ * exit 1 on an otherwise healthy export. Key on {@link moduleKey}. It is
63
+ * already collected explicitly at the top of {@link collectCss}, and emitting
64
+ * it again duplicates the entire design system, palette included.
65
+ * @internal Exported for testing
66
+ */
67
+ export declare function isDesignSystemVirtualModule(url: string): boolean;
68
+ /** @internal Exported for testing */
69
+ export declare function isStylesheetUrl(url: string): boolean;
70
+ /**
71
+ * Collapse the spellings Vite uses for the same module into one key.
72
+ *
73
+ * The same file appears in the graph as both `/@fs/Users/…` and `/@fs//Users/…`
74
+ * depending on how it was resolved. Left unnormalized, each spelling is treated
75
+ * as a distinct module and its CSS is emitted twice.
76
+ *
77
+ * Only the `/@fs/` prefix is collapsed — never repeated slashes elsewhere in the
78
+ * string, which would merge distinct modules whose query values contain a URL
79
+ * (`a.css?url=//cdn/x` vs `a.css?url=/cdn/x`).
80
+ *
81
+ * Prefer {@link moduleKey} where a `ModuleNode` is available.
82
+ * @internal Exported for testing
83
+ */
84
+ export declare function normalizeModuleUrl(url: string): string;
85
+ /**
86
+ * Key for a module known only by its URL.
87
+ *
88
+ * `/@fs/` is Vite's browser-facing spelling of an absolute path, while the graph
89
+ * keys the same module on `id`/`file`, which carry the bare path. Both have to
90
+ * produce one key: an entry-reached sheet whose module the graph cannot resolve
91
+ * yet is recorded from its URL, and is emitted a second time when the graph walk
92
+ * later finds it under the bare path.
93
+ * @internal Exported for testing
94
+ */
95
+ export declare function moduleKeyFromUrl(url: string): string;
96
+ /**
97
+ * Stable identity for a module in the graph.
98
+ *
99
+ * Vite already knows what a module *is*, so no regex has to guess at the URL.
100
+ *
101
+ * `id` first, not `file`: `id` is the key `idToModuleMap` itself uses, so it is
102
+ * unique per module by construction. `file` is the query-stripped path, which
103
+ * two genuinely distinct modules can share — `a.css` and `a.css?theme=dark`
104
+ * resolve to one `file`, so keying on it drops one of them and its rules never
105
+ * reach the output.
106
+ * @internal Exported for testing
107
+ */
108
+ export declare function moduleKey(mod: {
109
+ file?: string | null;
110
+ id?: string | null;
111
+ url: string;
112
+ }): string;
113
+ /** The subset of a Vite plugin container this module needs. */
114
+ /**
115
+ * Diagnostics {@link collectCss} reports rather than throwing.
116
+ */
117
+ /** @codexApi {"parent":"pithy.ssr.build.collect-css","name":"CollectCssOptions","stability":"experimental","signature":"interface CollectCssOptions { onDesignSystemFailure?: (error: Error) => void }"} */
118
+ export interface CollectCssOptions {
119
+ /**
120
+ * Called once when a **registered** design-system plugin produced no CSS.
121
+ *
122
+ * This is the failure that ships an entire static site unstyled, so the
123
+ * caller is expected to turn it into a build failure. It is reported through
124
+ * a callback rather than a `throw` for a specific reason: `collectCss()` runs
125
+ * before the exporter has written a single page, so throwing would turn a CSS
126
+ * problem into zero output for the whole build — strictly worse than the
127
+ * partial-output behaviour it is meant to improve on.
128
+ *
129
+ * Not called when no design-system plugin is registered at all. That app has
130
+ * no tokens to lose, and failing its build would be failing it for a
131
+ * different, separately-tracked gap.
132
+ */
133
+ onDesignSystemFailure?: (error: Error) => void;
134
+ /**
135
+ * Whether the app DECLARED a design system (`config.designSystem`).
136
+ *
137
+ * The declaration is the right signal, and plugin registration was the wrong
138
+ * one. BUG-028's actual state was: `pithy.config.ts` declared a design system
139
+ * and `vite.config.ts` registered no plugin to serve it — so a
140
+ * registration probe answered "false", took the lenient branch, and shipped
141
+ * five unstyled pages at exit 0. The bug the gate exists to catch was the one
142
+ * case it could not see.
143
+ *
144
+ * Asking the config also removes a probe with side effects: Vite's
145
+ * `resolveId` runs `buildStart()` if the container has not started, which for
146
+ * `designSystemPlugin` means a full source rescan fired from a "cheap
147
+ * read-only check" — and it answers from the client environment on Vite 6 and
148
+ * SSR on Vite 7, so the same code gave opposite verdicts by major version.
149
+ */
150
+ designSystemDeclared?: boolean;
151
+ }
152
+ /**
153
+ * Collect CSS from:
154
+ * 1. The design system virtual module (utility classes like u-grid, u-flex, etc.)
155
+ * 2. The client entry's import tree (see {@link warmClientEntry})
156
+ * 3. Any .css/.scss modules in Vite's module graph
157
+ *
158
+ * @param vite - Dev server whose module graph is inspected.
159
+ * @param entryClient - Client entry relative to the app root (e.g. `src/main.ts`).
160
+ * Omit only when the app genuinely has no client entry; omitting it for an app
161
+ * that has one silently drops every stylesheet the entry imports.
162
+ * @param options - Diagnostic sinks. See {@link CollectCssOptions}.
163
+ * @returns Every stylesheet found, concatenated. Never throws for a
164
+ * design-system problem — see {@link CollectCssOptions.onDesignSystemFailure}.
165
+ */
166
+ /** @codexApi {"parent":"pithy.ssr.build.collect-css","name":"collectCss","stability":"experimental","signature":"(vite: ViteDevServer, entryClient?: string, options?: CollectCssOptions) => Promise<string>"} */
167
+ export declare function collectCss(vite: ViteDevServer, entryClient?: string, options?: CollectCssOptions): Promise<string>;
168
+ //# sourceMappingURL=collect-css.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"collect-css.d.ts","sourceRoot":"","sources":["../../src/build/collect-css.ts"],"names":[],"mappings":"AAAA;;;;;;;EAOE;AAiBF,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,MAAM,CAAC;AAE1C;;;;;;;;;GASG;AACH,qCAAqC;AACrC,eAAO,MAAM,SAAS,QAC6E,CAAC;AAepG,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAMjD;AAED,qCAAqC;AACrC,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAMrD;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAI5D;AAED;;;;;;GAMG;AACH,wBAAgB,UAAU,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,CAGtD;AAKD;;;;;;;;;;;;GAYG;AACH,uJAAuJ;AACvJ,eAAO,MAAM,aAAa,gCAAgC,CAAC;AAE3D;;;;;;;;;;;;GAYG;AACH,wBAAgB,2BAA2B,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAOhE;AAED,qCAAqC;AACrC,wBAAgB,eAAe,C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