@pithyjs/ssr 0.0.0-stage → 0.1.2-beta.10
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.
- package/LICENSE +21 -0
- package/README.md +100 -2
- package/bin/pithy-ssg.mjs +23 -0
- package/dist/browser.d.ts +38 -0
- package/dist/browser.d.ts.map +1 -0
- package/dist/browser.js +40 -0
- package/dist/browser.js.map +1 -0
- package/dist/build/cli-args.d.ts +104 -0
- package/dist/build/cli-args.d.ts.map +1 -0
- package/dist/build/cli-args.js +88 -0
- package/dist/build/cli-args.js.map +1 -0
- package/dist/build/cli-exit.d.ts +95 -0
- package/dist/build/cli-exit.d.ts.map +1 -0
- package/dist/build/cli-exit.js +237 -0
- package/dist/build/cli-exit.js.map +1 -0
- package/dist/build/cli.d.ts +11 -0
- package/dist/build/cli.d.ts.map +1 -0
- package/dist/build/cli.js +93 -0
- package/dist/build/cli.js.map +1 -0
- package/dist/build/collect-css.d.ts +168 -0
- package/dist/build/collect-css.d.ts.map +1 -0
- package/dist/build/collect-css.js +479 -0
- package/dist/build/collect-css.js.map +1 -0
- package/dist/build/css-live-props.d.ts +89 -0
- package/dist/build/css-live-props.d.ts.map +1 -0
- package/dist/build/css-live-props.js +704 -0
- package/dist/build/css-live-props.js.map +1 -0
- package/dist/build/css-purge.d.ts +153 -0
- package/dist/build/css-purge.d.ts.map +1 -0
- package/dist/build/css-purge.js +463 -0
- package/dist/build/css-purge.js.map +1 -0
- package/dist/build/index.d.ts +24 -0
- package/dist/build/index.d.ts.map +1 -0
- package/dist/build/index.js +31 -0
- package/dist/build/index.js.map +1 -0
- package/dist/build/not-found.d.ts +94 -0
- package/dist/build/not-found.d.ts.map +1 -0
- package/dist/build/not-found.js +99 -0
- package/dist/build/not-found.js.map +1 -0
- package/dist/build/relative-links.d.ts +31 -0
- package/dist/build/relative-links.d.ts.map +1 -0
- package/dist/build/relative-links.js +79 -0
- package/dist/build/relative-links.js.map +1 -0
- package/dist/build/shell-head.d.ts +68 -0
- package/dist/build/shell-head.d.ts.map +1 -0
- package/dist/build/shell-head.js +236 -0
- package/dist/build/shell-head.js.map +1 -0
- package/dist/build/sprite-ssg.d.ts +61 -0
- package/dist/build/sprite-ssg.d.ts.map +1 -0
- package/dist/build/sprite-ssg.js +114 -0
- package/dist/build/sprite-ssg.js.map +1 -0
- package/dist/build/ssg.d.ts +117 -0
- package/dist/build/ssg.d.ts.map +1 -0
- package/dist/build/ssg.js +404 -0
- package/dist/build/ssg.js.map +1 -0
- package/dist/build/vite-ssg.d.ts +396 -0
- package/dist/build/vite-ssg.d.ts.map +1 -0
- package/dist/build/vite-ssg.js +1130 -0
- package/dist/build/vite-ssg.js.map +1 -0
- package/dist/client/bootstrap.d.ts +51 -0
- package/dist/client/bootstrap.d.ts.map +1 -0
- package/dist/client/bootstrap.js +121 -0
- package/dist/client/bootstrap.js.map +1 -0
- package/dist/client/hydrate.d.ts +60 -0
- package/dist/client/hydrate.d.ts.map +1 -0
- package/dist/client/hydrate.js +168 -0
- package/dist/client/hydrate.js.map +1 -0
- package/dist/client/index.d.ts +21 -0
- package/dist/client/index.d.ts.map +1 -0
- package/dist/client/index.js +16 -0
- package/dist/client/index.js.map +1 -0
- package/dist/index.d.ts +32 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +31 -0
- package/dist/index.js.map +1 -0
- package/dist/server/app.d.ts +166 -0
- package/dist/server/app.d.ts.map +1 -0
- package/dist/server/app.js +200 -0
- package/dist/server/app.js.map +1 -0
- package/dist/server/context.d.ts +238 -0
- package/dist/server/context.d.ts.map +1 -0
- package/dist/server/context.js +371 -0
- package/dist/server/context.js.map +1 -0
- package/dist/server/environment.d.ts +88 -0
- package/dist/server/environment.d.ts.map +1 -0
- package/dist/server/environment.js +261 -0
- package/dist/server/environment.js.map +1 -0
- package/dist/server/html-shell.d.ts +41 -0
- package/dist/server/html-shell.d.ts.map +1 -0
- package/dist/server/html-shell.js +208 -0
- package/dist/server/html-shell.js.map +1 -0
- package/dist/server/index.d.ts +26 -0
- package/dist/server/index.d.ts.map +1 -0
- package/dist/server/index.js +37 -0
- package/dist/server/index.js.map +1 -0
- package/dist/server/layout-taint.d.ts +62 -0
- package/dist/server/layout-taint.d.ts.map +1 -0
- package/dist/server/layout-taint.js +313 -0
- package/dist/server/layout-taint.js.map +1 -0
- package/dist/server/loaders.d.ts +194 -0
- package/dist/server/loaders.d.ts.map +1 -0
- package/dist/server/loaders.js +479 -0
- package/dist/server/loaders.js.map +1 -0
- package/dist/server/render-route.d.ts +102 -0
- package/dist/server/render-route.d.ts.map +1 -0
- package/dist/server/render-route.js +182 -0
- package/dist/server/render-route.js.map +1 -0
- package/dist/server/render.d.ts +80 -0
- package/dist/server/render.d.ts.map +1 -0
- package/dist/server/render.js +256 -0
- package/dist/server/render.js.map +1 -0
- package/dist/server/router-adapter.d.ts +134 -0
- package/dist/server/router-adapter.d.ts.map +1 -0
- package/dist/server/router-adapter.js +225 -0
- package/dist/server/router-adapter.js.map +1 -0
- package/dist/server/serialization.d.ts +54 -0
- package/dist/server/serialization.d.ts.map +1 -0
- package/dist/server/serialization.js +287 -0
- package/dist/server/serialization.js.map +1 -0
- package/dist/server/ssr-worker.d.ts +18 -0
- package/dist/server/ssr-worker.d.ts.map +1 -0
- package/dist/server/ssr-worker.js +118 -0
- package/dist/server/ssr-worker.js.map +1 -0
- package/dist/server/utils.d.ts +11 -0
- package/dist/server/utils.d.ts.map +1 -0
- package/dist/server/utils.js +14 -0
- package/dist/server/utils.js.map +1 -0
- package/dist/server/worker-pool.d.ts +153 -0
- package/dist/server/worker-pool.d.ts.map +1 -0
- package/dist/server/worker-pool.js +451 -0
- package/dist/server/worker-pool.js.map +1 -0
- package/dist/server/worker-protocol.d.ts +61 -0
- package/dist/server/worker-protocol.d.ts.map +1 -0
- package/dist/server/worker-protocol.js +9 -0
- package/dist/server/worker-protocol.js.map +1 -0
- package/dist/shared/css-purge.d.ts +71 -0
- package/dist/shared/css-purge.d.ts.map +1 -0
- package/dist/shared/css-purge.js +177 -0
- package/dist/shared/css-purge.js.map +1 -0
- package/dist/shared/entry-path.d.ts +41 -0
- package/dist/shared/entry-path.d.ts.map +1 -0
- package/dist/shared/entry-path.js +87 -0
- package/dist/shared/entry-path.js.map +1 -0
- package/dist/shared/head.d.ts +87 -0
- package/dist/shared/head.d.ts.map +1 -0
- package/dist/shared/head.js +412 -0
- package/dist/shared/head.js.map +1 -0
- package/dist/shared/shell-helpers.d.ts +69 -0
- package/dist/shared/shell-helpers.d.ts.map +1 -0
- package/dist/shared/shell-helpers.js +160 -0
- package/dist/shared/shell-helpers.js.map +1 -0
- package/dist/shared/types.d.ts +332 -0
- package/dist/shared/types.d.ts.map +1 -0
- package/dist/shared/types.js +27 -0
- package/dist/shared/types.js.map +1 -0
- package/package.json +84 -3
|
@@ -0,0 +1,463 @@
|
|
|
1
|
+
/** @codex { "id": "pithy.ssr.build.css-purge", "title": "Static Export CSS Purge (text)", "category": "feature", "risk": "high" } */
|
|
2
|
+
/**
|
|
3
|
+
* Drops CSS rules the rendered pages never use, from stylesheet TEXT.
|
|
4
|
+
*
|
|
5
|
+
* **Every kept rule is emitted as its ORIGINAL SOURCE SLICE**, never
|
|
6
|
+
* regenerated from a CSSOM. happy-dom's CSSOM empties any declaration it
|
|
7
|
+
* cannot model — `color-mix()`, `oklch()`, `oklch(… / α)` all serialize back
|
|
8
|
+
* as `.x { }` — and drops `@property` rules from the rule list entirely, so a
|
|
9
|
+
* purge that round-trips through it ships a stylesheet that renders unstyled.
|
|
10
|
+
* The same trap rules out "enumerate via CSSOM, slice text by rule index": the
|
|
11
|
+
* indices do not align, because CSSOM holds fewer rules than the text does.
|
|
12
|
+
* happy-dom is used here ONLY as a selector matcher, the part of it that is
|
|
13
|
+
* sound.
|
|
14
|
+
*
|
|
15
|
+
* Rule identification is therefore a brace/string/comment-aware scan of the
|
|
16
|
+
* text. Anything it cannot confidently classify is KEPT — fail-open end to end.
|
|
17
|
+
*/
|
|
18
|
+
import { atRuleName, holdsCascadeSlot, isRecursiveAtRule, isSelectorUsed, } from '../shared/css-purge.js';
|
|
19
|
+
// The SAME constant `htmlShell` defaults to, not a copy of its value: the
|
|
20
|
+
// wrapper this module stands up has to carry the id the shell will actually
|
|
21
|
+
// emit, and an app that never configures one is the common case.
|
|
22
|
+
import { DEFAULT_APP_ID } from '../shared/types.js';
|
|
23
|
+
/**
|
|
24
|
+
* Index of the closing quote of the string starting at `i`, or `to` when it is
|
|
25
|
+
* never closed. A `\` escapes the next character, so `'it\'s'` does not end early.
|
|
26
|
+
*/
|
|
27
|
+
/** @codexApi {"parent":"pithy.ssr.build.css-purge","name":"skipString","stability":"experimental","signature":"(css: string, i: number, to: number) => number"} */
|
|
28
|
+
export function skipString(css, i, to) {
|
|
29
|
+
const quote = css[i];
|
|
30
|
+
for (let j = i + 1; j < to; j++) {
|
|
31
|
+
const ch = css[j];
|
|
32
|
+
if (ch === '\\') {
|
|
33
|
+
j++;
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
if (ch === quote)
|
|
37
|
+
return j;
|
|
38
|
+
}
|
|
39
|
+
return to;
|
|
40
|
+
}
|
|
41
|
+
/** Index just past the end of the comment starting at `i`, or `to` if unclosed. */
|
|
42
|
+
/** @codexApi {"parent":"pithy.ssr.build.css-purge","name":"skipComment","stability":"experimental","signature":"(css: string, i: number, to: number) => number"} */
|
|
43
|
+
export function skipComment(css, i, to) {
|
|
44
|
+
const end = css.indexOf('*/', i + 2);
|
|
45
|
+
return end === -1 || end + 2 > to ? to : end + 2;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Split `css[from, to)` into its top-level nodes. Braces inside strings and
|
|
49
|
+
* comments must not move the depth, or a single `content: "}"` desynchronises
|
|
50
|
+
* every rule after it. Unterminated input ends the scan rather than looping.
|
|
51
|
+
*
|
|
52
|
+
* At-rule level only: inside a style-rule BODY its `;`-at-depth-0 branch emits
|
|
53
|
+
* `verbatim` nodes, so `css-live-props.ts` splits declarations itself and calls
|
|
54
|
+
* back here for the nested blocks it meets.
|
|
55
|
+
*
|
|
56
|
+
* `limit` stops after that many nodes. A caller that wants only the next one
|
|
57
|
+
* must pass it ({@link splitFirstRule}): scanning to `to` every time makes a
|
|
58
|
+
* per-block caller quadratic, measured at 4x per doubling of sheet size.
|
|
59
|
+
*/
|
|
60
|
+
/** @codexApi {"parent":"pithy.ssr.build.css-purge","name":"splitRules","stability":"experimental","signature":"(css: string, from: number, to: number, limit?: number) => CssNode[]"} */
|
|
61
|
+
export function splitRules(css, from, to, limit = Infinity) {
|
|
62
|
+
const nodes = [];
|
|
63
|
+
let i = from;
|
|
64
|
+
while (i < to && nodes.length < limit) {
|
|
65
|
+
while (i < to && /\s/.test(css[i]))
|
|
66
|
+
i++;
|
|
67
|
+
if (i >= to)
|
|
68
|
+
break;
|
|
69
|
+
// A comment between rules is its own node, so it never lands in the next
|
|
70
|
+
// rule's prelude and make an otherwise-testable selector unparseable.
|
|
71
|
+
if (css[i] === '/' && css[i + 1] === '*') {
|
|
72
|
+
const stop = skipComment(css, i, to);
|
|
73
|
+
nodes.push({ kind: 'comment', raw: css.slice(i, stop) });
|
|
74
|
+
i = stop;
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
const start = i;
|
|
78
|
+
let depth = 0;
|
|
79
|
+
let braceAt = -1;
|
|
80
|
+
let end = -1;
|
|
81
|
+
let parens = 0;
|
|
82
|
+
for (; i < to; i++) {
|
|
83
|
+
const ch = css[i];
|
|
84
|
+
// An escape outside a string. A Tailwind-style `.a\"b` or `.w-\{` would
|
|
85
|
+
// otherwise open a string or a block that never closes, and the rest of
|
|
86
|
+
// the sheet becomes one verbatim node.
|
|
87
|
+
if (ch === '\\') {
|
|
88
|
+
i++;
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
if (ch === '/' && css[i + 1] === '*') {
|
|
92
|
+
i = skipComment(css, i, to) - 1;
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
if (ch === '"' || ch === "'") {
|
|
96
|
+
i = skipString(css, i, to);
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
if (ch === '(') {
|
|
100
|
+
parens++;
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
if (ch === ')') {
|
|
104
|
+
if (parens > 0)
|
|
105
|
+
parens--;
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
// An unquoted `;` inside `url(…)` is ordinary — `url(data:image/png;
|
|
109
|
+
// base64,…)` is what Vite emits for an inlined image. Ending the node
|
|
110
|
+
// there split the prelude mid-token and emitted an UNTERMINATED at-rule
|
|
111
|
+
// that swallowed the rest of the sheet.
|
|
112
|
+
if (parens > 0)
|
|
113
|
+
continue;
|
|
114
|
+
if (ch === '{') {
|
|
115
|
+
if (depth === 0)
|
|
116
|
+
braceAt = i;
|
|
117
|
+
depth++;
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
if (ch === '}') {
|
|
121
|
+
depth--;
|
|
122
|
+
if (depth <= 0) {
|
|
123
|
+
end = i + 1;
|
|
124
|
+
break;
|
|
125
|
+
}
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
if (ch === ';' && depth === 0) {
|
|
129
|
+
end = i + 1;
|
|
130
|
+
break;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
// No terminator reached, or a stray `}` closed us below depth 0: neither is
|
|
134
|
+
// a rule we can reason about, so keep the text and move on.
|
|
135
|
+
if (end === -1 || braceAt === -1 || depth < 0) {
|
|
136
|
+
const stop = end === -1 ? to : end;
|
|
137
|
+
nodes.push({ kind: 'verbatim', raw: css.slice(start, stop) });
|
|
138
|
+
i = stop;
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
nodes.push({
|
|
142
|
+
kind: 'block',
|
|
143
|
+
raw: css.slice(start, end),
|
|
144
|
+
prelude: css.slice(start, braceAt),
|
|
145
|
+
bodyStart: braceAt + 1,
|
|
146
|
+
bodyEnd: end - 1,
|
|
147
|
+
});
|
|
148
|
+
i = end;
|
|
149
|
+
}
|
|
150
|
+
return nodes;
|
|
151
|
+
}
|
|
152
|
+
/** The next node of `css[from, to)`, without parsing what follows it. */
|
|
153
|
+
/** @codexApi {"parent":"pithy.ssr.build.css-purge","name":"splitFirstRule","stability":"experimental","signature":"(css: string, from: number, to: number) => CssNode | null"} */
|
|
154
|
+
export function splitFirstRule(css, from, to) {
|
|
155
|
+
return splitRules(css, from, to, 1)[0] ?? null;
|
|
156
|
+
}
|
|
157
|
+
/** The text to emit for one node, or `''` to drop it. */
|
|
158
|
+
function keepNode(css, node, root) {
|
|
159
|
+
if (node.kind === 'comment') {
|
|
160
|
+
// `/*!` is the conventional "preserve me" marker (licences); everything
|
|
161
|
+
// else is authoring noise that no rendering depends on.
|
|
162
|
+
return node.raw.startsWith('/*!') ? node.raw : '';
|
|
163
|
+
}
|
|
164
|
+
if (node.kind === 'verbatim')
|
|
165
|
+
return node.raw;
|
|
166
|
+
const at = atRuleName(node.prelude);
|
|
167
|
+
if (at === null) {
|
|
168
|
+
// A style rule. Nested children (CSS nesting) ride along verbatim: the
|
|
169
|
+
// outer selector decides, and `&:hover` is not a top-level selector.
|
|
170
|
+
return isSelectorUsed(node.prelude, root) ? node.raw : '';
|
|
171
|
+
}
|
|
172
|
+
if (!isRecursiveAtRule(at))
|
|
173
|
+
return node.raw;
|
|
174
|
+
const kept = purgeNodes(css, splitRules(css, node.bodyStart, node.bodyEnd), root);
|
|
175
|
+
if (kept)
|
|
176
|
+
return `${node.prelude.trim()}{\n${kept}\n}`;
|
|
177
|
+
const prelude = node.prelude.trim();
|
|
178
|
+
return holdsCascadeSlot(at, prelude) ? `${prelude}{}` : '';
|
|
179
|
+
}
|
|
180
|
+
function purgeNodes(css, nodes, root) {
|
|
181
|
+
const out = [];
|
|
182
|
+
for (const node of nodes) {
|
|
183
|
+
const text = keepNode(css, node, root);
|
|
184
|
+
if (text)
|
|
185
|
+
out.push(text);
|
|
186
|
+
}
|
|
187
|
+
return out.join('\n');
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Drop the rules in `css` that `root` proves unused, emitting every survivor as
|
|
191
|
+
* its original source slice.
|
|
192
|
+
*
|
|
193
|
+
* @param css - Stylesheet text.
|
|
194
|
+
* @param root - What the selectors are matched against.
|
|
195
|
+
* @returns The purged stylesheet.
|
|
196
|
+
*/
|
|
197
|
+
/** @codexApi {"parent":"pithy.ssr.build.css-purge","name":"purgeCssText","stability":"experimental","signature":"(css: string, root: SelectorMatchRoot) => string"} */
|
|
198
|
+
export function purgeCssText(css, root) {
|
|
199
|
+
if (!css)
|
|
200
|
+
return css;
|
|
201
|
+
return purgeNodes(css, splitRules(css, 0, css.length), root);
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Class/id tokens EVERY match of `selector` must carry, or `null` when the
|
|
205
|
+
* selector cannot be modelled exactly and the real engine must answer.
|
|
206
|
+
*/
|
|
207
|
+
function requiredTokens(selector) {
|
|
208
|
+
// Attribute selectors first: `[href="#top"]` and `[data-x=".y"]` carry `#`
|
|
209
|
+
// and `.` inside a string, and reading those as tokens would demand an id
|
|
210
|
+
// and a class that are not required at all — and drop a used rule.
|
|
211
|
+
//
|
|
212
|
+
// Escape pairs are consumed FIRST, so a `\[` inside a class name can neither
|
|
213
|
+
// open nor close an attribute selector. Without that, `.u-w-\[10px\]` strips
|
|
214
|
+
// to `.u-w-`, no element carries that class, and the index answers "absent"
|
|
215
|
+
// — deleting a rule that is used. That is the one path here that would fail
|
|
216
|
+
// CLOSED, and it breaks this module's precondition.
|
|
217
|
+
const bare = selector.replace(/\\.|\[[^\]]*\]/g, m => m[0] === '\\' ? m : ' ');
|
|
218
|
+
// A leftover paren is a functional construct this index cannot model: a
|
|
219
|
+
// pseudo `stripPseudos` could not unwrap (`:not(:is(.x))`), or a fragment of
|
|
220
|
+
// a selector list split mid-`:is(…)`. Its `.`/`#` tokens are NOT all
|
|
221
|
+
// required — and the engine may refuse the text outright, which is HOW such a
|
|
222
|
+
// rule gets kept. Answering "absent" here would delete it instead.
|
|
223
|
+
if (bare.includes('(') || bare.includes(')'))
|
|
224
|
+
return null;
|
|
225
|
+
const tokens = [];
|
|
226
|
+
for (const m of bare.matchAll(TOKEN_RE)) {
|
|
227
|
+
// A hex escape (`\3a `) means something other than the next character, so
|
|
228
|
+
// THIS name cannot be recovered by unescaping. Skipped, not fatal: the
|
|
229
|
+
// required set stays a subset of the truth, so an absent token that IS
|
|
230
|
+
// decodable still proves the selector cannot match — `.missing
|
|
231
|
+
// .\32xl\:p-4` is decided by `.missing`. Giving up on the whole selector
|
|
232
|
+
// instead shipped every unused digit-leading Tailwind variant.
|
|
233
|
+
if (HEX_ESCAPE_RE.test(m[2]))
|
|
234
|
+
continue;
|
|
235
|
+
tokens.push(m[1] + m[2].replace(/\\(.)/g, '$1'));
|
|
236
|
+
}
|
|
237
|
+
// All tokens undecodable: no required set, so the caller must delegate.
|
|
238
|
+
return tokens;
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* One `.class` or `#id`, consuming the WHOLE identifier.
|
|
242
|
+
*
|
|
243
|
+
* The CSS identifier grammar, not an ASCII approximation of it, because every
|
|
244
|
+
* character this stops short of turns the REST of one name into a second token
|
|
245
|
+
* the index then demands: `.\31 0\.5` is the single class `10.5`, and read as
|
|
246
|
+
* two it required a class `5` that nothing carries, so a matching rule was
|
|
247
|
+
* deleted. Covered here and each one reproduced: non-ASCII name characters
|
|
248
|
+
* (`.café`, which needs no escape at all), a hex escape and the one whitespace
|
|
249
|
+
* that may terminate it — `\r\n` counts as one, since CSS preprocesses it to a
|
|
250
|
+
* single newline — and a simple escape of any non-newline character, including
|
|
251
|
+
* an escaped space (`#\ a`) and an escaped backslash (`.a\\b`).
|
|
252
|
+
*/
|
|
253
|
+
const TOKEN_RE = /([.#])((?:[\w-]|[\u0080-\uffff]|\\[0-9a-f]{1,6}(?:\r\n|[ \t\n\r\f])?|\\[^\n\r\f0-9a-f])+)/gi;
|
|
254
|
+
/**
|
|
255
|
+
* A hex escape (`\\32`), which names a character the engine must DECODE.
|
|
256
|
+
* {@link requiredTokens} cannot recover that name, so the token it belongs to
|
|
257
|
+
* is left out of the required set.
|
|
258
|
+
*/
|
|
259
|
+
const HEX_ESCAPE_RE = /\\[0-9a-f]/i;
|
|
260
|
+
/**
|
|
261
|
+
* Selector text happy-dom gets WRONG, so "no match" from it is not evidence.
|
|
262
|
+
*
|
|
263
|
+
* Measured against happy-dom, one shape per class: a hex escape
|
|
264
|
+
* (`.\\32 xl\\:p-4`), any non-ASCII character (`.café`, `.a😀b` — no escape
|
|
265
|
+
* involved) and an escaped backslash (`.a\\\\b`) all return null for an
|
|
266
|
+
* element that carries the name. Escaped colons, dots, brackets, spaces and
|
|
267
|
+
* hashes match correctly and are deliberately NOT listed, so the purge keeps
|
|
268
|
+
* deciding them.
|
|
269
|
+
*
|
|
270
|
+
* Build-only: Studio runs against live CSSOM, which handles all of these.
|
|
271
|
+
*/
|
|
272
|
+
const ENGINE_BLIND_RE = /\\[0-9a-f]|\\\\|[\u0080-\uffff]/i;
|
|
273
|
+
/**
|
|
274
|
+
* Wraps the happy-dom root so a selector it cannot decide reads as "cannot
|
|
275
|
+
* tell" rather than "unused".
|
|
276
|
+
*
|
|
277
|
+
* happy-dom returns null — it does not throw — for `.\32xl\:p-4` and for
|
|
278
|
+
* `.café`, and the caller reads null as unused and DELETES the rule. Tailwind
|
|
279
|
+
* emits the first shape for every digit-leading variant and most arbitrary
|
|
280
|
+
* values; the second needs no escape at all, just a name outside ASCII. A real
|
|
281
|
+
* browser matches both, so this belongs to the Node ENGINE, not to the shared
|
|
282
|
+
* predicate: Studio runs the same purge against live CSSOM and must keep
|
|
283
|
+
* purging them. Wrapping the root rather than the predicate also keeps
|
|
284
|
+
* `indexedMatchRoot` a pure optimisation — it and the plain root still agree.
|
|
285
|
+
*/
|
|
286
|
+
function engineUndecidableRoot(root) {
|
|
287
|
+
return {
|
|
288
|
+
querySelector(selectors) {
|
|
289
|
+
const hit = root.querySelector(selectors);
|
|
290
|
+
if (hit)
|
|
291
|
+
return hit;
|
|
292
|
+
return ENGINE_BLIND_RE.test(selectors) ? UNDECIDABLE : null;
|
|
293
|
+
},
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
/** Truthy "keep", and not a node, so nothing can read properties off it. */
|
|
297
|
+
const UNDECIDABLE = Object.freeze({ undecidableSelector: true });
|
|
298
|
+
/**
|
|
299
|
+
* A match root that answers "definitely not present" from a precomputed index
|
|
300
|
+
* before falling back to a real `querySelector`.
|
|
301
|
+
*
|
|
302
|
+
* An optimisation, and a load-bearing one: a `querySelector` MISS walks the
|
|
303
|
+
* whole tree, and misses over a union of every rendered page cost ~8 ms each
|
|
304
|
+
* across ~15k elements (measured on `apps/basic-app`) — minutes over a real
|
|
305
|
+
* stylesheet. Tag-only selectors, attribute selectors and hex escapes it simply
|
|
306
|
+
* delegates.
|
|
307
|
+
*
|
|
308
|
+
* **The precondition is not "it only answers no".** Its "no" is consumed by
|
|
309
|
+
* {@link isSelectorUsed} as PROOF the rule is unused, so it may answer at all
|
|
310
|
+
* only where it would agree with the engine — including where the engine would
|
|
311
|
+
* REFUSE the selector, which is how a rule the purge cannot reason about stays
|
|
312
|
+
* in the sheet. So the index answers only for a plain compound/combinator chain
|
|
313
|
+
* whose every `.`/`#` token is genuinely required for a match; `requiredTokens`
|
|
314
|
+
* returns `null` for everything else, and a functional pseudo — whether
|
|
315
|
+
* `stripPseudos` left it whole or a selector-list split cut it in half — is
|
|
316
|
+
* exactly what "everything else" is for.
|
|
317
|
+
*
|
|
318
|
+
* @param root - The document or element to index and delegate to.
|
|
319
|
+
* @param elements - Every element under `root`.
|
|
320
|
+
*/
|
|
321
|
+
/** @codexApi {"parent":"pithy.ssr.build.css-purge","name":"indexedMatchRoot","stability":"experimental","signature":"(root: SelectorMatchRoot, elements: Iterable<IndexableElement>) => SelectorMatchRoot"} */
|
|
322
|
+
export function indexedMatchRoot(root, elements) {
|
|
323
|
+
const present = new Set();
|
|
324
|
+
for (const el of elements) {
|
|
325
|
+
for (const cls of el.classList)
|
|
326
|
+
present.add('.' + cls);
|
|
327
|
+
if (el.id)
|
|
328
|
+
present.add('#' + el.id);
|
|
329
|
+
}
|
|
330
|
+
// The DOM does not change during a purge, and a stylesheet asks the same
|
|
331
|
+
// selector once at the top level and again in every block that restyles it.
|
|
332
|
+
const answered = new Map();
|
|
333
|
+
return {
|
|
334
|
+
querySelector(selectors) {
|
|
335
|
+
const cached = answered.get(selectors);
|
|
336
|
+
if (cached !== undefined)
|
|
337
|
+
return cached;
|
|
338
|
+
const tokens = requiredTokens(selectors);
|
|
339
|
+
let hit = null;
|
|
340
|
+
if (tokens === null || tokens.every(t => present.has(t))) {
|
|
341
|
+
hit = root.querySelector(selectors);
|
|
342
|
+
}
|
|
343
|
+
answered.set(selectors, hit);
|
|
344
|
+
return hit;
|
|
345
|
+
},
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
/** Names a DOM `setAttribute` accepts; anything else would throw. */
|
|
349
|
+
const ATTR_NAME_RE = /^[A-Za-z_:][\w:.-]*$/;
|
|
350
|
+
function applyAttrs(el, attrs) {
|
|
351
|
+
for (const [name, value] of Object.entries(attrs ?? {})) {
|
|
352
|
+
if (ATTR_NAME_RE.test(name))
|
|
353
|
+
el.setAttribute(name, value);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
/**
|
|
357
|
+
* Purge `css` against the union of the rendered pages.
|
|
358
|
+
*
|
|
359
|
+
* happy-dom is an OPTIONAL peer dependency, so every failure path returns `css`
|
|
360
|
+
* unchanged: a larger stylesheet is correct, a missing one is not.
|
|
361
|
+
*
|
|
362
|
+
* Pass every document that will be served, the 404 included — a rule only that
|
|
363
|
+
* page uses is otherwise proven unused and dropped.
|
|
364
|
+
*
|
|
365
|
+
* @param css - The stylesheet the build is about to inline.
|
|
366
|
+
* @param pages - Every page in the output; see {@link PurgePage}.
|
|
367
|
+
*/
|
|
368
|
+
/** @codexApi {"parent":"pithy.ssr.build.css-purge","name":"purgeCssForPages","stability":"experimental","signature":"(css: string, pages: readonly PurgePage[]) => Promise<string>"} */
|
|
369
|
+
export async function purgeCssForPages(css, pages) {
|
|
370
|
+
// No pages proves nothing about what is used, so purging would empty the
|
|
371
|
+
// sheet rather than shrink it.
|
|
372
|
+
if (!css || pages.length === 0)
|
|
373
|
+
return css;
|
|
374
|
+
let Window;
|
|
375
|
+
try {
|
|
376
|
+
({ Window } = await import('happy-dom'));
|
|
377
|
+
}
|
|
378
|
+
catch (err) {
|
|
379
|
+
console.warn('[pithy:ssg] Could not load happy-dom, so unused CSS is not purged. ' +
|
|
380
|
+
'The full stylesheet ships, which renders correctly but larger.', err);
|
|
381
|
+
return css;
|
|
382
|
+
}
|
|
383
|
+
let win;
|
|
384
|
+
try {
|
|
385
|
+
// Nothing here needs scripts to run, and rendered markup is not trusted
|
|
386
|
+
// input to hand an evaluator.
|
|
387
|
+
win = new Window({
|
|
388
|
+
url: 'http://localhost/',
|
|
389
|
+
settings: { disableJavaScriptEvaluation: true },
|
|
390
|
+
});
|
|
391
|
+
// One document for every page, so a selector costs one tree walk rather
|
|
392
|
+
// than N. Each page keeps a wrapper so a descendant or sibling combinator
|
|
393
|
+
// cannot match across the boundary between two pages — and the wrapper
|
|
394
|
+
// TRIO stands in for the page's `<html>`/`<body>`/`<div id="{appId}">`, so
|
|
395
|
+
// an ancestor selector rooted at any of them still has something to match.
|
|
396
|
+
// The trio has to mirror `htmlShell` exactly: every element it inserts
|
|
397
|
+
// between `<body>` and the fragment is one a rule may legitimately hang
|
|
398
|
+
// off, and one this purge would otherwise prove unused.
|
|
399
|
+
const union = win.document.createElement('div');
|
|
400
|
+
const pageElements = [];
|
|
401
|
+
const shellElements = [];
|
|
402
|
+
for (const page of pages) {
|
|
403
|
+
const htmlEl = win.document.createElement('div');
|
|
404
|
+
applyAttrs(htmlEl, page.htmlAttrs);
|
|
405
|
+
const bodyEl = win.document.createElement('div');
|
|
406
|
+
applyAttrs(bodyEl, page.bodyAttrs);
|
|
407
|
+
const appEl = win.document.createElement('div');
|
|
408
|
+
appEl.id = page.appId || DEFAULT_APP_ID;
|
|
409
|
+
bodyEl.appendChild(appEl);
|
|
410
|
+
appEl.innerHTML = page.html;
|
|
411
|
+
// Neither `querySelectorAll` nor `querySelector` descends into
|
|
412
|
+
// `<template>.content`, so a class used only inside one is proven unused
|
|
413
|
+
// and deleted — this module's other fail-CLOSED path. Hoist each
|
|
414
|
+
// template's content beside it so both the index and the engine see it.
|
|
415
|
+
// Over-inclusive by a sibling's worth of context, which is the safe
|
|
416
|
+
// direction: the cost is keeping a rule, never dropping one.
|
|
417
|
+
//
|
|
418
|
+
// Looped, not a single pass: `querySelectorAll` returns a STATIC list and
|
|
419
|
+
// does not descend into `.content` either, so a template nested inside
|
|
420
|
+
// another template's content is invisible to the pass that hoists its
|
|
421
|
+
// parent. Each round makes the next depth reachable; `hoisted` stops the
|
|
422
|
+
// walk re-hoisting a template it has already expanded, so a page with no
|
|
423
|
+
// nesting costs exactly one extra empty query.
|
|
424
|
+
const hoisted = new Set();
|
|
425
|
+
for (;;) {
|
|
426
|
+
const pending = [...appEl.querySelectorAll('template')].filter(tpl => !hoisted.has(tpl));
|
|
427
|
+
if (pending.length === 0)
|
|
428
|
+
break;
|
|
429
|
+
for (const tpl of pending) {
|
|
430
|
+
hoisted.add(tpl);
|
|
431
|
+
const content = tpl.content;
|
|
432
|
+
if (content && tpl.parentNode) {
|
|
433
|
+
tpl.parentNode.appendChild(content.cloneNode(true));
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
htmlEl.appendChild(bodyEl);
|
|
438
|
+
union.appendChild(htmlEl);
|
|
439
|
+
shellElements.push(htmlEl, bodyEl, appEl);
|
|
440
|
+
// The page's own elements, not the wrappers — counting scaffolding would
|
|
441
|
+
// satisfy the empty-DOM guard below with nothing.
|
|
442
|
+
for (const el of appEl.querySelectorAll('*')) {
|
|
443
|
+
pageElements.push(el);
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
// Nothing parsed means nothing can be proven used, and purging against an
|
|
447
|
+
// empty document deletes the entire stylesheet. Ship it whole instead.
|
|
448
|
+
if (pageElements.length === 0) {
|
|
449
|
+
console.warn('[pithy:ssg] Rendered pages parsed to an empty DOM, so unused CSS is ' +
|
|
450
|
+
'not purged. The full stylesheet ships.');
|
|
451
|
+
return css;
|
|
452
|
+
}
|
|
453
|
+
return purgeCssText(css, indexedMatchRoot(engineUndecidableRoot(union), [...shellElements, ...pageElements]));
|
|
454
|
+
}
|
|
455
|
+
catch (err) {
|
|
456
|
+
console.warn('[pithy:ssg] CSS purge failed; shipping the full stylesheet.', err);
|
|
457
|
+
return css;
|
|
458
|
+
}
|
|
459
|
+
finally {
|
|
460
|
+
await win?.happyDOM?.close?.().catch(() => { });
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
//# sourceMappingURL=css-purge.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"css-purge.js","sourceRoot":"","sources":["../../src/build/css-purge.ts"],"names":[],"mappings":"AAAA,qIAAqI;AAErI;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,EACL,UAAU,EACV,gBAAgB,EAChB,iBAAiB,EACjB,cAAc,GAEf,MAAM,wBAAwB,CAAC;AAEhC,0EAA0E;AAC1E,4EAA4E;AAC5E,iEAAiE;AACjE,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAsBpD;;;GAGG;AACH,mKAAmK;AACnK,MAAM,UAAU,UAAU,CAAC,GAAW,EAAE,CAAS,EAAE,EAAU;IAC3D,MAAM,KAAK,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC;IACrB,KAAK,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC;QAChC,MAAM,EAAE,GA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AI,GAAG,CAAC,UAAU,EAAE,CAAC;wBAC9B,GAAG,CAAC,UAAU,CAAC,WAAW,CACxB,OAAO,CAAC,SAAS,CAAC,IAAI,CAElB,CACL,CAAC;oBACJ,CAAC;gBACH,CAAC;YACH,CAAC;YAED,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;YAC3B,KAAK,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;YAE1B,aAAa,CAAC,IAAI,CAChB,MAAqC,EACrC,MAAqC,EACrC,KAAoC,CACrC,CAAC;YACF,yEAAyE;YACzE,kDAAkD;YAClD,KAAK,MAAM,EAAE,IAAI,KAAK,CAAC,gBAAgB,CAAC,GAAG,CAAC,EAAE,CAAC;gBAC7C,YAAY,CAAC,IAAI,CAAC,EAAiC,CAAC,CAAC;YACvD,CAAC;QACH,CAAC;QAED,0EAA0E;QAC1E,uEAAuE;QACvE,IAAI,YAAY,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC9B,OAAO,CAAC,IAAI,CACV,sEAAsE;gBACpE,wCAAwC,CAC3C,CAAC;YACF,OAAO,GAAG,CAAC;QACb,CAAC;QAED,OAAO,YAAY,CACjB,GAAG,EACH,gBAAgB,CACd,qBAAqB,CAAC,KAAqC,CAAC,EAC5D,CAAC,GAAG,aAAa,EAAE,GAAG,YAAY,CAAC,CACpC,CACF,CAAC;IACJ,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,OAAO,CAAC,IAAI,CACV,6DAA6D,EAC7D,GAAG,CACJ,CAAC;QACF,OAAO,GAAG,CAAC;IACb,CAAC;YAAS,CAAC;QACT,MAAM,GAAG,EAAE,QAAQ,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;IACjD,CAAC;AACH,CAAC","sourcesContent":["/** @codex { \"id\": \"pithy.ssr.build.css-purge\", \"title\": \"Static Export CSS Purge (text)\", \"category\": \"feature\", \"risk\": \"high\" } */\n\n/**\n * Drops CSS rules the rendered pages never use, from stylesheet TEXT.\n *\n * **Every kept rule is emitted as its ORIGINAL SOURCE SLICE**, never\n * regenerated from a CSSOM. happy-dom's CSSOM empties any declaration it\n * cannot model — `color-mix()`, `oklch()`, `oklch(… / α)` all serialize back\n * as `.x { }` — and drops `@property` rules from the rule list entirely, so a\n * purge that round-trips through it ships a stylesheet that renders unstyled.\n * The same trap rules out \"enumerate via CSSOM, slice text by rule index\": the\n * indices do not align, because CSSOM holds fewer rules than the text does.\n * happy-dom is used here ONLY as a selector matcher, the part of it that is\n * sound.\n *\n * Rule identification is therefore a brace/string/comment-aware scan of the\n * text. Anything it cannot confidently classify is KEPT — fail-open end to end.\n */\n\nimport {\n atRuleName,\n holdsCascadeSlot,\n isRecursiveAtRule,\n isSelectorUsed,\n type SelectorMatchRoot,\n} from '../shared/css-purge.js';\n\n// The SAME constant `htmlShell` defaults to, not a copy of its value: the\n// wrapper this module stands up has to carry the id the shell will actually\n// emit, and an app that never configures one is the common case.\nimport { DEFAULT_APP_ID } from '../shared/types.js';\n\nexport type { SelectorMatchRoot };\n\n/**\n * One top-level item of a stylesheet (or of one at-rule body). `verbatim` is\n * anything with no selector to test — a statement at-rule, a stray brace, an\n * unterminated block. `block` records the ORIGINAL prelude slice and the\n * body's bounds, so a recursed at-rule re-emits from source text alone.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.build.css-purge\",\"name\":\"CssNode\",\"stability\":\"experimental\",\"signature\":\"{ kind: 'comment' | 'verbatim'; raw: string } | { kind: 'block'; raw: string; prelude: string; bodyStart: number; bodyEnd: number }\"} */\nexport type CssNode =\n | { kind: 'comment'; raw: string }\n | { kind: 'verbatim'; raw: string }\n | {\n kind: 'block';\n raw: string;\n prelude: string;\n bodyStart: number;\n bodyEnd: number;\n };\n\n/**\n * Index of the closing quote of the string starting at `i`, or `to` when it is\n * never closed. A `\\` escapes the next character, so `'it\\'s'` does not end early.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.build.css-purge\",\"name\":\"skipString\",\"stability\":\"experimental\",\"signature\":\"(css: string, i: number, to: number) => number\"} */\nexport function skipString(css: string, i: number, to: number): number {\n const quote = css[i];\n for (let j = i + 1; j < to; j++) {\n const ch = css[j];\n if (ch === '\\\\') {\n j++;\n continue;\n }\n if (ch === quote) return j;\n }\n return to;\n}\n\n/** Index just past the end of the comment starting at `i`, or `to` if unclosed. */\n/** @codexApi {\"parent\":\"pithy.ssr.build.css-purge\",\"name\":\"skipComment\",\"stability\":\"experimental\",\"signature\":\"(css: string, i: number, to: number) => number\"} */\nexport function skipComment(css: string, i: number, to: number): number {\n const end = css.indexOf('*/', i + 2);\n return end === -1 || end + 2 > to ? to : end + 2;\n}\n\n/**\n * Split `css[from, to)` into its top-level nodes. Braces inside strings and\n * comments must not move the depth, or a single `content: \"}\"` desynchronises\n * every rule after it. Unterminated input ends the scan rather than looping.\n *\n * At-rule level only: inside a style-rule BODY its `;`-at-depth-0 branch emits\n * `verbatim` nodes, so `css-live-props.ts` splits declarations itself and calls\n * back here for the nested blocks it meets.\n *\n * `limit` stops after that many nodes. A caller that wants only the next one\n * must pass it ({@link splitFirstRule}): scanning to `to` every time makes a\n * per-block caller quadratic, measured at 4x per doubling of sheet size.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.build.css-purge\",\"name\":\"splitRules\",\"stability\":\"experimental\",\"signature\":\"(css: string, from: number, to: number, limit?: number) => CssNode[]\"} */\nexport function splitRules(\n css: string,\n from: number,\n to: number,\n limit = Infinity\n): CssNode[] {\n const nodes: CssNode[] = [];\n let i = from;\n\n while (i < to && nodes.length < limit) {\n while (i < to && /\\s/.test(css[i])) i++;\n if (i >= to) break;\n\n // A comment between rules is its own node, so it never lands in the next\n // rule's prelude and make an otherwise-testable selector unparseable.\n if (css[i] === '/' && css[i + 1] === '*') {\n const stop = skipComment(css, i, to);\n nodes.push({ kind: 'comment', raw: css.slice(i, stop) });\n i = stop;\n continue;\n }\n\n const start = i;\n let depth = 0;\n let braceAt = -1;\n let end = -1;\n let parens = 0;\n\n for (; i < to; i++) {\n const ch = css[i];\n // An escape outside a string. A Tailwind-style `.a\\\"b` or `.w-\\{` would\n // otherwise open a string or a block that never closes, and the rest of\n // the sheet becomes one verbatim node.\n if (ch === '\\\\') {\n i++;\n continue;\n }\n if (ch === '/' && css[i + 1] === '*') {\n i = skipComment(css, i, to) - 1;\n continue;\n }\n if (ch === '\"' || ch === \"'\") {\n i = skipString(css, i, to);\n continue;\n }\n if (ch === '(') {\n parens++;\n continue;\n }\n if (ch === ')') {\n if (parens > 0) parens--;\n continue;\n }\n // An unquoted `;` inside `url(…)` is ordinary — `url(data:image/png;\n // base64,…)` is what Vite emits for an inlined image. Ending the node\n // there split the prelude mid-token and emitted an UNTERMINATED at-rule\n // that swallowed the rest of the sheet.\n if (parens > 0) continue;\n if (ch === '{') {\n if (depth === 0) braceAt = i;\n depth++;\n continue;\n }\n if (ch === '}') {\n depth--;\n if (depth <= 0) {\n end = i + 1;\n break;\n }\n continue;\n }\n if (ch === ';' && depth === 0) {\n end = i + 1;\n break;\n }\n }\n\n // No terminator reached, or a stray `}` closed us below depth 0: neither is\n // a rule we can reason about, so keep the text and move on.\n if (end === -1 || braceAt === -1 || depth < 0) {\n const stop = end === -1 ? to : end;\n nodes.push({ kind: 'verbatim', raw: css.slice(start, stop) });\n i = stop;\n continue;\n }\n\n nodes.push({\n kind: 'block',\n raw: css.slice(start, end),\n prelude: css.slice(start, braceAt),\n bodyStart: braceAt + 1,\n bodyEnd: end - 1,\n });\n i = end;\n }\n\n return nodes;\n}\n\n/** The next node of `css[from, to)`, without parsing what follows it. */\n/** @codexApi {\"parent\":\"pithy.ssr.build.css-purge\",\"name\":\"splitFirstRule\",\"stability\":\"experimental\",\"signature\":\"(css: string, from: number, to: number) => CssNode | null\"} */\nexport function splitFirstRule(\n css: string,\n from: number,\n to: number\n): CssNode | null {\n return splitRules(css, from, to, 1)[0] ?? null;\n}\n\n/** The text to emit for one node, or `''` to drop it. */\nfunction keepNode(css: string, node: CssNode, root: SelectorMatchRoot): string {\n if (node.kind === 'comment') {\n // `/*!` is the conventional \"preserve me\" marker (licences); everything\n // else is authoring noise that no rendering depends on.\n return node.raw.startsWith('/*!') ? node.raw : '';\n }\n if (node.kind === 'verbatim') return node.raw;\n\n const at = atRuleName(node.prelude);\n if (at === null) {\n // A style rule. Nested children (CSS nesting) ride along verbatim: the\n // outer selector decides, and `&:hover` is not a top-level selector.\n return isSelectorUsed(node.prelude, root) ? node.raw : '';\n }\n if (!isRecursiveAtRule(at)) return node.raw;\n\n const kept = purgeNodes(\n css,\n splitRules(css, node.bodyStart, node.bodyEnd),\n root\n );\n if (kept) return `${node.prelude.trim()}{\\n${kept}\\n}`;\n const prelude = node.prelude.trim();\n return holdsCascadeSlot(at, prelude) ? `${prelude}{}` : '';\n}\n\nfunction purgeNodes(\n css: string,\n nodes: CssNode[],\n root: SelectorMatchRoot\n): string {\n const out: string[] = [];\n for (const node of nodes) {\n const text = keepNode(css, node, root);\n if (text) out.push(text);\n }\n return out.join('\\n');\n}\n\n/**\n * Drop the rules in `css` that `root` proves unused, emitting every survivor as\n * its original source slice.\n *\n * @param css - Stylesheet text.\n * @param root - What the selectors are matched against.\n * @returns The purged stylesheet.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.build.css-purge\",\"name\":\"purgeCssText\",\"stability\":\"experimental\",\"signature\":\"(css: string, root: SelectorMatchRoot) => string\"} */\nexport function purgeCssText(css: string, root: SelectorMatchRoot): string {\n if (!css) return css;\n return purgeNodes(css, splitRules(css, 0, css.length), root);\n}\n\n/**\n * The element surface {@link indexedMatchRoot} indexes. Structural rather than\n * `Element`: happy-dom's `Element` is a different type from `lib.dom`'s.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.build.css-purge\",\"name\":\"IndexableElement\",\"stability\":\"experimental\",\"signature\":\"interface { classList: Iterable<string>; id: string }\"} */\nexport interface IndexableElement {\n classList: Iterable<string>;\n id: string;\n}\n\n/**\n * Class/id tokens EVERY match of `selector` must carry, or `null` when the\n * selector cannot be modelled exactly and the real engine must answer.\n */\nfunction requiredTokens(selector: string): string[] | null {\n // Attribute selectors first: `[href=\"#top\"]` and `[data-x=\".y\"]` carry `#`\n // and `.` inside a string, and reading those as tokens would demand an id\n // and a class that are not required at all — and drop a used rule.\n //\n // Escape pairs are consumed FIRST, so a `\\[` inside a class name can neither\n // open nor close an attribute selector. Without that, `.u-w-\\[10px\\]` strips\n // to `.u-w-`, no element carries that class, and the index answers \"absent\"\n // — deleting a rule that is used. That is the one path here that would fail\n // CLOSED, and it breaks this module's precondition.\n const bare = selector.replace(/\\\\.|\\[[^\\]]*\\]/g, m =>\n m[0] === '\\\\' ? m : ' '\n );\n\n // A leftover paren is a functional construct this index cannot model: a\n // pseudo `stripPseudos` could not unwrap (`:not(:is(.x))`), or a fragment of\n // a selector list split mid-`:is(…)`. Its `.`/`#` tokens are NOT all\n // required — and the engine may refuse the text outright, which is HOW such a\n // rule gets kept. Answering \"absent\" here would delete it instead.\n if (bare.includes('(') || bare.includes(')')) return null;\n\n const tokens: string[] = [];\n for (const m of bare.matchAll(TOKEN_RE)) {\n // A hex escape (`\\3a `) means something other than the next character, so\n // THIS name cannot be recovered by unescaping. Skipped, not fatal: the\n // required set stays a subset of the truth, so an absent token that IS\n // decodable still proves the selector cannot match — `.missing\n // .\\32xl\\:p-4` is decided by `.missing`. Giving up on the whole selector\n // instead shipped every unused digit-leading Tailwind variant.\n if (HEX_ESCAPE_RE.test(m[2])) continue;\n tokens.push(m[1] + m[2].replace(/\\\\(.)/g, '$1'));\n }\n // All tokens undecodable: no required set, so the caller must delegate.\n return tokens;\n}\n\n/**\n * One `.class` or `#id`, consuming the WHOLE identifier.\n *\n * The CSS identifier grammar, not an ASCII approximation of it, because every\n * character this stops short of turns the REST of one name into a second token\n * the index then demands: `.\\31 0\\.5` is the single class `10.5`, and read as\n * two it required a class `5` that nothing carries, so a matching rule was\n * deleted. Covered here and each one reproduced: non-ASCII name characters\n * (`.café`, which needs no escape at all), a hex escape and the one whitespace\n * that may terminate it — `\\r\\n` counts as one, since CSS preprocesses it to a\n * single newline — and a simple escape of any non-newline character, including\n * an escaped space (`#\\ a`) and an escaped backslash (`.a\\\\b`).\n */\nconst TOKEN_RE =\n /([.#])((?:[\\w-]|[\\u0080-\\uffff]|\\\\[0-9a-f]{1,6}(?:\\r\\n|[ \\t\\n\\r\\f])?|\\\\[^\\n\\r\\f0-9a-f])+)/gi;\n\n/**\n * A hex escape (`\\\\32`), which names a character the engine must DECODE.\n * {@link requiredTokens} cannot recover that name, so the token it belongs to\n * is left out of the required set.\n */\nconst HEX_ESCAPE_RE = /\\\\[0-9a-f]/i;\n\n/**\n * Selector text happy-dom gets WRONG, so \"no match\" from it is not evidence.\n *\n * Measured against happy-dom, one shape per class: a hex escape\n * (`.\\\\32 xl\\\\:p-4`), any non-ASCII character (`.café`, `.a😀b` — no escape\n * involved) and an escaped backslash (`.a\\\\\\\\b`) all return null for an\n * element that carries the name. Escaped colons, dots, brackets, spaces and\n * hashes match correctly and are deliberately NOT listed, so the purge keeps\n * deciding them.\n *\n * Build-only: Studio runs against live CSSOM, which handles all of these.\n */\nconst ENGINE_BLIND_RE = /\\\\[0-9a-f]|\\\\\\\\|[\\u0080-\\uffff]/i;\n\n/**\n * Wraps the happy-dom root so a selector it cannot decide reads as \"cannot\n * tell\" rather than \"unused\".\n *\n * happy-dom returns null — it does not throw — for `.\\32xl\\:p-4` and for\n * `.café`, and the caller reads null as unused and DELETES the rule. Tailwind\n * emits the first shape for every digit-leading variant and most arbitrary\n * values; the second needs no escape at all, just a name outside ASCII. A real\n * browser matches both, so this belongs to the Node ENGINE, not to the shared\n * predicate: Studio runs the same purge against live CSSOM and must keep\n * purging them. Wrapping the root rather than the predicate also keeps\n * `indexedMatchRoot` a pure optimisation — it and the plain root still agree.\n */\nfunction engineUndecidableRoot(root: SelectorMatchRoot): SelectorMatchRoot {\n return {\n querySelector(selectors: string): unknown {\n const hit = root.querySelector(selectors);\n if (hit) return hit;\n return ENGINE_BLIND_RE.test(selectors) ? UNDECIDABLE : null;\n },\n };\n}\n\n/** Truthy \"keep\", and not a node, so nothing can read properties off it. */\nconst UNDECIDABLE: unknown = Object.freeze({ undecidableSelector: true });\n\n/**\n * A match root that answers \"definitely not present\" from a precomputed index\n * before falling back to a real `querySelector`.\n *\n * An optimisation, and a load-bearing one: a `querySelector` MISS walks the\n * whole tree, and misses over a union of every rendered page cost ~8 ms each\n * across ~15k elements (measured on `apps/basic-app`) — minutes over a real\n * stylesheet. Tag-only selectors, attribute selectors and hex escapes it simply\n * delegates.\n *\n * **The precondition is not \"it only answers no\".** Its \"no\" is consumed by\n * {@link isSelectorUsed} as PROOF the rule is unused, so it may answer at all\n * only where it would agree with the engine — including where the engine would\n * REFUSE the selector, which is how a rule the purge cannot reason about stays\n * in the sheet. So the index answers only for a plain compound/combinator chain\n * whose every `.`/`#` token is genuinely required for a match; `requiredTokens`\n * returns `null` for everything else, and a functional pseudo — whether\n * `stripPseudos` left it whole or a selector-list split cut it in half — is\n * exactly what \"everything else\" is for.\n *\n * @param root - The document or element to index and delegate to.\n * @param elements - Every element under `root`.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.build.css-purge\",\"name\":\"indexedMatchRoot\",\"stability\":\"experimental\",\"signature\":\"(root: SelectorMatchRoot, elements: Iterable<IndexableElement>) => SelectorMatchRoot\"} */\nexport function indexedMatchRoot(\n root: SelectorMatchRoot,\n elements: Iterable<IndexableElement>\n): SelectorMatchRoot {\n const present = new Set<string>();\n for (const el of elements) {\n for (const cls of el.classList) present.add('.' + cls);\n if (el.id) present.add('#' + el.id);\n }\n\n // The DOM does not change during a purge, and a stylesheet asks the same\n // selector once at the top level and again in every block that restyles it.\n const answered = new Map<string, unknown>();\n\n return {\n querySelector(selectors: string): unknown {\n const cached = answered.get(selectors);\n if (cached !== undefined) return cached;\n\n const tokens = requiredTokens(selectors);\n let hit: unknown = null;\n if (tokens === null || tokens.every(t => present.has(t))) {\n hit = root.querySelector(selectors);\n }\n answered.set(selectors, hit);\n return hit;\n },\n };\n}\n\n/**\n * One rendered page, as the purge sees it.\n *\n * `html` is the BODY FRAGMENT the shell will inject — `<html>`/`<body>` do not\n * exist yet at purge time and cannot be reconstructed by handing over a whole\n * document either, since assigning one to `innerHTML` strips those very tags.\n * So the attributes the shell is going to put on them come separately: an app\n * that themes with `head({ bodyAttrs: { class: 'dark' } })` has a `.dark .x`\n * rule that is genuinely used, and without these it is proven unused.\n *\n * `appId` is the same problem one level further in, and it is not an attribute\n * but a whole element: `htmlShell` wraps the fragment in `<div id=\"{appId}\">`\n * AFTER this runs, so every `#app …` rule is otherwise proven unused — with no\n * fail-open to catch it, because the id is simply not in the DOM.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.build.css-purge\",\"name\":\"PurgePage\",\"stability\":\"experimental\",\"signature\":\"interface { html: string; appId?: string; htmlAttrs?: Record<string, string>; bodyAttrs?: Record<string, string> }\"} */\nexport interface PurgePage {\n html: string;\n /**\n * The app-root id `htmlShell` wraps `html` in. Omitted, it falls back to\n * {@link DEFAULT_APP_ID} exactly as the shell does — an app that never sets\n * `appId` still ships `<div id=\"app\">`, so defaulting to \"no id\" here would\n * leave `#app` rules dropped in the ONE case that is most common.\n */\n appId?: string;\n htmlAttrs?: Readonly<Record<string, string>>;\n bodyAttrs?: Readonly<Record<string, string>>;\n}\n\n/** Names a DOM `setAttribute` accepts; anything else would throw. */\nconst ATTR_NAME_RE = /^[A-Za-z_:][\\w:.-]*$/;\n\nfunction applyAttrs(\n el: { setAttribute(name: string, value: string): void },\n attrs: Readonly<Record<string, string>> | undefined\n): void {\n for (const [name, value] of Object.entries(attrs ?? {})) {\n if (ATTR_NAME_RE.test(name)) el.setAttribute(name, value);\n }\n}\n\n/**\n * Purge `css` against the union of the rendered pages.\n *\n * happy-dom is an OPTIONAL peer dependency, so every failure path returns `css`\n * unchanged: a larger stylesheet is correct, a missing one is not.\n *\n * Pass every document that will be served, the 404 included — a rule only that\n * page uses is otherwise proven unused and dropped.\n *\n * @param css - The stylesheet the build is about to inline.\n * @param pages - Every page in the output; see {@link PurgePage}.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.build.css-purge\",\"name\":\"purgeCssForPages\",\"stability\":\"experimental\",\"signature\":\"(css: string, pages: readonly PurgePage[]) => Promise<string>\"} */\nexport async function purgeCssForPages(\n css: string,\n pages: readonly PurgePage[]\n): Promise<string> {\n // No pages proves nothing about what is used, so purging would empty the\n // sheet rather than shrink it.\n if (!css || pages.length === 0) return css;\n\n let Window: typeof import('happy-dom').Window;\n try {\n ({ Window } = await import('happy-dom'));\n } catch (err) {\n console.warn(\n '[pithy:ssg] Could not load happy-dom, so unused CSS is not purged. ' +\n 'The full stylesheet ships, which renders correctly but larger.',\n err\n );\n return css;\n }\n\n let win: InstanceType<typeof Window> | undefined;\n try {\n // Nothing here needs scripts to run, and rendered markup is not trusted\n // input to hand an evaluator.\n win = new Window({\n url: 'http://localhost/',\n settings: { disableJavaScriptEvaluation: true },\n });\n // One document for every page, so a selector costs one tree walk rather\n // than N. Each page keeps a wrapper so a descendant or sibling combinator\n // cannot match across the boundary between two pages — and the wrapper\n // TRIO stands in for the page's `<html>`/`<body>`/`<div id=\"{appId}\">`, so\n // an ancestor selector rooted at any of them still has something to match.\n // The trio has to mirror `htmlShell` exactly: every element it inserts\n // between `<body>` and the fragment is one a rule may legitimately hang\n // off, and one this purge would otherwise prove unused.\n const union = win.document.createElement('div');\n const pageElements: IndexableElement[] = [];\n const shellElements: IndexableElement[] = [];\n\n for (const page of pages) {\n const htmlEl = win.document.createElement('div');\n applyAttrs(htmlEl, page.htmlAttrs);\n const bodyEl = win.document.createElement('div');\n applyAttrs(bodyEl, page.bodyAttrs);\n const appEl = win.document.createElement('div');\n appEl.id = page.appId || DEFAULT_APP_ID;\n bodyEl.appendChild(appEl);\n appEl.innerHTML = page.html;\n\n // Neither `querySelectorAll` nor `querySelector` descends into\n // `<template>.content`, so a class used only inside one is proven unused\n // and deleted — this module's other fail-CLOSED path. Hoist each\n // template's content beside it so both the index and the engine see it.\n // Over-inclusive by a sibling's worth of context, which is the safe\n // direction: the cost is keeping a rule, never dropping one.\n //\n // Looped, not a single pass: `querySelectorAll` returns a STATIC list and\n // does not descend into `.content` either, so a template nested inside\n // another template's content is invisible to the pass that hoists its\n // parent. Each round makes the next depth reachable; `hoisted` stops the\n // walk re-hoisting a template it has already expanded, so a page with no\n // nesting costs exactly one extra empty query.\n const hoisted = new Set<unknown>();\n for (;;) {\n const pending = [...appEl.querySelectorAll('template')].filter(\n tpl => !hoisted.has(tpl)\n );\n if (pending.length === 0) break;\n for (const tpl of pending) {\n hoisted.add(tpl);\n const content = (\n tpl as unknown as {\n content?: { cloneNode(deep: boolean): unknown };\n }\n ).content;\n if (content && tpl.parentNode) {\n tpl.parentNode.appendChild(\n content.cloneNode(true) as Parameters<\n typeof tpl.parentNode.appendChild\n >[0]\n );\n }\n }\n }\n\n htmlEl.appendChild(bodyEl);\n union.appendChild(htmlEl);\n\n shellElements.push(\n htmlEl as unknown as IndexableElement,\n bodyEl as unknown as IndexableElement,\n appEl as unknown as IndexableElement\n );\n // The page's own elements, not the wrappers — counting scaffolding would\n // satisfy the empty-DOM guard below with nothing.\n for (const el of appEl.querySelectorAll('*')) {\n pageElements.push(el as unknown as IndexableElement);\n }\n }\n\n // Nothing parsed means nothing can be proven used, and purging against an\n // empty document deletes the entire stylesheet. Ship it whole instead.\n if (pageElements.length === 0) {\n console.warn(\n '[pithy:ssg] Rendered pages parsed to an empty DOM, so unused CSS is ' +\n 'not purged. The full stylesheet ships.'\n );\n return css;\n }\n\n return purgeCssText(\n css,\n indexedMatchRoot(\n engineUndecidableRoot(union as unknown as SelectorMatchRoot),\n [...shellElements, ...pageElements]\n )\n );\n } catch (err) {\n console.warn(\n '[pithy:ssg] CSS purge failed; shipping the full stylesheet.',\n err\n );\n return css;\n } finally {\n await win?.happyDOM?.close?.().catch(() => {});\n }\n}\n"]}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** @codex
|
|
2
|
+
{
|
|
3
|
+
"id": "pithy.ssr.build",
|
|
4
|
+
"title": "SSG Build Entry Point",
|
|
5
|
+
"category": "feature",
|
|
6
|
+
"risk": "medium"
|
|
7
|
+
}
|
|
8
|
+
*/
|
|
9
|
+
/**
|
|
10
|
+
* @pithyjs/ssr/build - SSG build-time exports
|
|
11
|
+
*
|
|
12
|
+
* Import from '@pithyjs/ssr/build' for build scripts.
|
|
13
|
+
* Requires Vite as a peer dependency.
|
|
14
|
+
*
|
|
15
|
+
* For the low-level generateStaticSite() (no Vite dependency),
|
|
16
|
+
* import from '@pithyjs/ssr/server' instead.
|
|
17
|
+
*
|
|
18
|
+
* @module ssr/build
|
|
19
|
+
*/
|
|
20
|
+
export { buildSSG, type BuildSSGOptions, planRenderJobs, type RenderJob, NOT_FOUND_OUTPUT, finalizeForOutput, type FinalizePageOptions, type FinalizePageResult, } from './vite-ssg.js';
|
|
21
|
+
export { collectStaticPaths, findRootCatchAllRoute } from './ssg.js';
|
|
22
|
+
export { makeLinksRelative, type MakeLinksRelativeOptions, } from './relative-links.js';
|
|
23
|
+
export { collectCss, type CollectCssOptions } from './collect-css.js';
|
|
24
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/build/index.ts"],"names":[],"mappings":"AAAA;;;;;;;EAOE;AAEF;;;;;;;;;;GAUG;AAEH,OAAO,EACL,QAAQ,EACR,KAAK,eAAe,EACpB,cAAc,EACd,KAAK,SAAS,EACd,gBAAgB,EAChB,iBAAiB,EACjB,KAAK,mBAAmB,EACxB,KAAK,kBAAkB,GACxB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,MAAM,UAAU,CAAC;AACrE,OAAO,EACL,iBAAiB,EACjB,KAAK,wBAAwB,GAC9B,MAAM,qBAAqB,CAAC;AAQ7B,OAAO,EAAE,UAAU,EAAE,KAAK,iBAAiB,EAAE,MAAM,kBAAkB,CAAC"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/** @codex
|
|
2
|
+
{
|
|
3
|
+
"id": "pithy.ssr.build",
|
|
4
|
+
"title": "SSG Build Entry Point",
|
|
5
|
+
"category": "feature",
|
|
6
|
+
"risk": "medium"
|
|
7
|
+
}
|
|
8
|
+
*/
|
|
9
|
+
/**
|
|
10
|
+
* @pithyjs/ssr/build - SSG build-time exports
|
|
11
|
+
*
|
|
12
|
+
* Import from '@pithyjs/ssr/build' for build scripts.
|
|
13
|
+
* Requires Vite as a peer dependency.
|
|
14
|
+
*
|
|
15
|
+
* For the low-level generateStaticSite() (no Vite dependency),
|
|
16
|
+
* import from '@pithyjs/ssr/server' instead.
|
|
17
|
+
*
|
|
18
|
+
* @module ssr/build
|
|
19
|
+
*/
|
|
20
|
+
export { buildSSG, planRenderJobs, NOT_FOUND_OUTPUT, finalizeForOutput, } from './vite-ssg.js';
|
|
21
|
+
export { collectStaticPaths, findRootCatchAllRoute } from './ssg.js';
|
|
22
|
+
export { makeLinksRelative, } from './relative-links.js';
|
|
23
|
+
// Nothing from `./cli-args.ts` or `./cli-exit.ts` is re-exported. They are the
|
|
24
|
+
// CLI's own seams, nothing in the repo imports them from here, and they reach
|
|
25
|
+
// for the process itself — `endCliProcess` sets `process.exitCode` and calls
|
|
26
|
+
// `process.exit()`, `guardAppScheduledErrors` installs process-wide error
|
|
27
|
+
// handlers. Neither is a side effect a library consumer should reach by
|
|
28
|
+
// accident. `cli.ts` imports them by relative path; make them public when
|
|
29
|
+
// something actually needs them.
|
|
30
|
+
export { collectCss } from './collect-css.js';
|
|
31
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/build/index.ts"],"names":[],"mappings":"AAAA;;;;;;;EAOE;AAEF;;;;;;;;;;GAUG;AAEH,OAAO,EACL,QAAQ,EAER,cAAc,EAEd,gBAAgB,EAChB,iBAAiB,GAGlB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,MAAM,UAAU,CAAC;AACrE,OAAO,EACL,iBAAiB,GAElB,MAAM,qBAAqB,CAAC;AAC7B,+EAA+E;AAC/E,8EAA8E;AAC9E,6EAA6E;AAC7E,0EAA0E;AAC1E,wEAAwE;AACxE,0EAA0E;AAC1E,iCAAiC;AACjC,OAAO,EAAE,UAAU,EAA0B,MAAM,kBAAkB,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.ssr.build\",\n \"title\": \"SSG Build Entry Point\",\n \"category\": \"feature\",\n \"risk\": \"medium\"\n}\n*/\n\n/**\n * @pithyjs/ssr/build - SSG build-time exports\n *\n * Import from '@pithyjs/ssr/build' for build scripts.\n * Requires Vite as a peer dependency.\n *\n * For the low-level generateStaticSite() (no Vite dependency),\n * import from '@pithyjs/ssr/server' instead.\n *\n * @module ssr/build\n */\n\nexport {\n buildSSG,\n type BuildSSGOptions,\n planRenderJobs,\n type RenderJob,\n NOT_FOUND_OUTPUT,\n finalizeForOutput,\n type FinalizePageOptions,\n type FinalizePageResult,\n} from './vite-ssg.js';\nexport { collectStaticPaths, findRootCatchAllRoute } from './ssg.js';\nexport {\n makeLinksRelative,\n type MakeLinksRelativeOptions,\n} from './relative-links.js';\n// Nothing from `./cli-args.ts` or `./cli-exit.ts` is re-exported. They are the\n// CLI's own seams, nothing in the repo imports them from here, and they reach\n// for the process itself — `endCliProcess` sets `process.exitCode` and calls\n// `process.exit()`, `guardAppScheduledErrors` installs process-wide error\n// handlers. Neither is a side effect a library consumer should reach by\n// accident. `cli.ts` imports them by relative path; make them public when\n// something actually needs them.\nexport { collectCss, type CollectCssOptions } from './collect-css.js';\n"]}
|