@stacksjs/stx 0.2.193 → 0.2.194

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.
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Lift inline blobs that repeat across pages, whatever they are.
3
+ *
4
+ * `build-externalize` handles the three blobs stx knows by name — the signals
5
+ * runtime, the router, and the generated stylesheet. Everything else it emits
6
+ * inline stays inline, and on a real multi-page site that is where the bytes
7
+ * actually are: the ts-cloud dashboard ships 54 pages at 12.5MB, of which
8
+ * 10.3MB is byte-identical `<script data-stx-scoped>` and unattributed
9
+ * `<style>` blocks repeated page after page. None of it is cacheable across a
10
+ * navigation, and it is 4x the size of the three named blobs combined.
11
+ *
12
+ * The rule here needs no allowlist: a blob that appears byte-for-byte on two
13
+ * or more pages is shared by construction, so hoisting it into one
14
+ * content-addressed file is a pure win — every page that referenced it now
15
+ * downloads it once for the whole site instead of once per page. A blob that
16
+ * appears on exactly one page is left alone, because turning it into a second
17
+ * request would make that page slower, not smaller.
18
+ *
19
+ * Requires the whole output directory, which is why it is a separate pass from
20
+ * the pure per-document `externalizeHtml`: "does this appear elsewhere" is not
21
+ * a question one document can answer, and SSR (which shares that function) has
22
+ * no elsewhere to look at.
23
+ *
24
+ * @module build-externalize-repeated
25
+ */
26
+ import { type ExternalizeResult } from './build-externalize';
27
+ /**
28
+ * Hoist every inline script/style body that appears on more than one page.
29
+ *
30
+ * Runs after {@link externalizeSharedAssets}, over the same directory, and is
31
+ * equally safe to run twice: the second pass sees `src`/`href` references with
32
+ * no inline body and matches nothing.
33
+ */
34
+ export declare function externalizeRepeatedAssets(outDir: string): ExternalizeResult;
@@ -0,0 +1,101 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { EXTERNALIZED_ASSET_DIR } from "./build-externalize.js";
4
+ const MIN_BLOB_BYTES = 1024, INLINE_BLOB = /<(script|style)\b([^>]*)>([\s\S]*?)<\/\1>/gi, JS_TYPES = new Set(["", "module", "text/javascript", "application/javascript", "module/javascript"]);
5
+ function contentHash(source) {
6
+ return Bun.hash(source).toString(16).slice(0, 8);
7
+ }
8
+ function listHtmlFiles(dir) {
9
+ const found = [], walk = (current) => {
10
+ for (const entry of fs.readdirSync(current, { withFileTypes: !0 })) {
11
+ const full = path.join(current, entry.name);
12
+ if (entry.isDirectory())
13
+ walk(full);
14
+ else if (entry.isFile() && full.endsWith(".html"))
15
+ found.push(full);
16
+ }
17
+ };
18
+ if (fs.existsSync(dir))
19
+ walk(dir);
20
+ return found;
21
+ }
22
+ function attrValue(attrs, name) {
23
+ const match = attrs.match(new RegExp(`\\b${name}\\s*=\\s*("([^"]*)"|'([^']*)'|([^\\s>]+))`, "i"));
24
+ if (!match)
25
+ return;
26
+ return match[2] ?? match[3] ?? match[4] ?? "";
27
+ }
28
+ function isExternalizable(tag, attrs, body) {
29
+ if (body.length < MIN_BLOB_BYTES)
30
+ return !1;
31
+ if (/\b(?:src|href)\s*=/i.test(attrs))
32
+ return !1;
33
+ if (tag.toLowerCase() === "script") {
34
+ if (!JS_TYPES.has((attrValue(attrs, "type") ?? "").trim().toLowerCase()))
35
+ return !1;
36
+ return !0;
37
+ }
38
+ return !0;
39
+ }
40
+ function templateRanges(html) {
41
+ const ranges = [];
42
+ for (const match of html.matchAll(/<template\b[^>]*>[\s\S]*?<\/template>/gi))
43
+ ranges.push([match.index, match.index + match[0].length]);
44
+ return ranges;
45
+ }
46
+ export function externalizeRepeatedAssets(outDir) {
47
+ const result = { pages: 0, assets: 0, bytesInlined: 0 }, files = listHtmlFiles(outDir);
48
+ if (files.length < 2)
49
+ return result;
50
+ const sources = new Map, occurrences = new Map;
51
+ for (const file of files) {
52
+ const html = fs.readFileSync(file, "utf8");
53
+ sources.set(file, html);
54
+ const templates = templateRanges(html);
55
+ for (const match of html.matchAll(INLINE_BLOB)) {
56
+ const [whole, tag, attrs, body] = match;
57
+ if (!isExternalizable(tag, attrs, body))
58
+ continue;
59
+ if (templates.some(([start, end]) => match.index >= start && match.index < end))
60
+ continue;
61
+ const key = `${tag.toLowerCase()}\x00${body}`, list = occurrences.get(key);
62
+ if (list)
63
+ list.push({ file, whole, tag, attrs, body });
64
+ else
65
+ occurrences.set(key, [{ file, whole, tag, attrs, body }]);
66
+ }
67
+ }
68
+ const shared = [...occurrences.values()].filter((list) => new Set(list.map((o) => o.file)).size > 1);
69
+ if (shared.length === 0)
70
+ return result;
71
+ const assetDir = path.join(outDir, EXTERNALIZED_ASSET_DIR), rewrites = new Map(sources), bytesPerFile = new Map, assets = [];
72
+ for (const list of shared) {
73
+ const { tag, body } = list[0], isScript = tag.toLowerCase() === "script", filename = `${isScript ? "chunk" : "style"}.${contentHash(body)}.${isScript ? "js" : "css"}`;
74
+ assets.push({
75
+ filename,
76
+ contents: body,
77
+ contentType: isScript ? "text/javascript; charset=utf-8" : "text/css; charset=utf-8"
78
+ });
79
+ const href = `/${EXTERNALIZED_ASSET_DIR}/${filename}`;
80
+ for (const occurrence of list) {
81
+ const replacement = isScript ? `<script${occurrence.attrs} src="${href}"></script>` : `<link${occurrence.attrs} rel="stylesheet" href="${href}">`, current = rewrites.get(occurrence.file), next = current.replace(occurrence.whole, () => replacement);
82
+ if (next === current)
83
+ continue;
84
+ rewrites.set(occurrence.file, next);
85
+ bytesPerFile.set(occurrence.file, (bytesPerFile.get(occurrence.file) ?? 0) + occurrence.body.length);
86
+ }
87
+ }
88
+ fs.mkdirSync(assetDir, { recursive: !0 });
89
+ for (const asset of assets) {
90
+ fs.writeFileSync(path.join(assetDir, asset.filename), asset.contents);
91
+ result.assets++;
92
+ }
93
+ for (const [file, html] of rewrites) {
94
+ if (html === sources.get(file))
95
+ continue;
96
+ fs.writeFileSync(file, html);
97
+ result.pages++;
98
+ result.bytesInlined += bytesPerFile.get(file) ?? 0;
99
+ }
100
+ return result;
101
+ }