@tenphi/tasty 3.5.0 → 3.6.0
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/dist/{astro-ib7E7V4Y.js → astro-CzY4LCpr.js} +192 -62
- package/dist/astro-CzY4LCpr.js.map +1 -0
- package/dist/ssr/astro-middleware-extract-static.js +1 -1
- package/dist/ssr/astro-middleware-extract.js +1 -1
- package/dist/ssr/astro-middleware-static.js +1 -1
- package/dist/ssr/astro-middleware.js +1 -1
- package/dist/ssr/astro.d.ts +9 -1
- package/dist/ssr/astro.js +1 -1
- package/docs/ssr.md +38 -13
- package/package.json +1 -1
- package/dist/astro-ib7E7V4Y.js.map +0 -1
|
@@ -50,84 +50,208 @@ async function findHTMLFiles(dir) {
|
|
|
50
50
|
}
|
|
51
51
|
return paths;
|
|
52
52
|
}
|
|
53
|
-
function
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
53
|
+
function skipCSSString(css, start, quote) {
|
|
54
|
+
for (let index = start + 1; index < css.length; index++) if (css[index] === "\\") index++;
|
|
55
|
+
else if (css[index] === quote) return index + 1;
|
|
56
|
+
return css.length;
|
|
57
|
+
}
|
|
58
|
+
function decodeCSSEscapes(value) {
|
|
59
|
+
return value.replace(/\\(?:([\da-f]{1,6})\s?|\r\n|[\n\r\f]|(.))/gi, (_match, hex, escaped) => {
|
|
60
|
+
if (hex) {
|
|
61
|
+
const codePoint = Number.parseInt(hex, 16);
|
|
62
|
+
return codePoint === 0 || codePoint > 1114111 ? "�" : String.fromCodePoint(codePoint);
|
|
63
|
+
}
|
|
64
|
+
return escaped ?? "";
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
function readCSSIdentifier(css, start) {
|
|
68
|
+
let name = "";
|
|
69
|
+
let index = start;
|
|
70
|
+
while (index < css.length) {
|
|
71
|
+
const char = css[index];
|
|
72
|
+
if (/[-_a-z\d]/i.test(char) || char.charCodeAt(0) >= 128) {
|
|
73
|
+
name += char;
|
|
74
|
+
index++;
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
if (char !== "\\" || index + 1 >= css.length) break;
|
|
78
|
+
const hex = css.slice(index + 1).match(/^[\da-f]{1,6}/i)?.[0];
|
|
79
|
+
if (hex) {
|
|
80
|
+
name += decodeCSSEscapes(`\\${hex}`);
|
|
81
|
+
index += hex.length + 1;
|
|
82
|
+
if (/\s/.test(css[index] ?? "")) index++;
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
if (/\r|\n|\f/.test(css[index + 1])) break;
|
|
86
|
+
name += css[index + 1];
|
|
87
|
+
index += 2;
|
|
58
88
|
}
|
|
59
|
-
return
|
|
89
|
+
return index === start ? null : {
|
|
90
|
+
name,
|
|
91
|
+
end: index
|
|
92
|
+
};
|
|
60
93
|
}
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
94
|
+
function skipCSSWhitespaceAndComments(css, start) {
|
|
95
|
+
let index = start;
|
|
96
|
+
for (;;) {
|
|
97
|
+
while (/\s/.test(css[index] ?? "")) index++;
|
|
98
|
+
if (css[index] !== "/" || css[index + 1] !== "*") return index;
|
|
99
|
+
const commentEnd = css.indexOf("*/", index + 2);
|
|
100
|
+
if (commentEnd === -1) return css.length;
|
|
101
|
+
index = commentEnd + 2;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
function classifyCSSResource(rawURL, rejectRootRelative) {
|
|
105
|
+
const url = decodeCSSEscapes(rawURL).trim();
|
|
106
|
+
if (!url || url.startsWith("//") || /^[a-z][a-z\d+.-]*:/i.test(url)) return null;
|
|
107
|
+
if (url.startsWith("/")) return rejectRootRelative ? {
|
|
108
|
+
url: rawURL,
|
|
109
|
+
rootRelative: true
|
|
110
|
+
} : null;
|
|
111
|
+
return {
|
|
112
|
+
url: rawURL,
|
|
113
|
+
rootRelative: false
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
function findUnsafeCSSResource(css, rejectRootRelative) {
|
|
117
|
+
const functionStack = [];
|
|
118
|
+
const stringResourceFunctions = new Set([
|
|
119
|
+
"image",
|
|
120
|
+
"image-set",
|
|
121
|
+
"-webkit-image-set",
|
|
122
|
+
"src"
|
|
123
|
+
]);
|
|
124
|
+
for (let index = 0; index < css.length; index++) {
|
|
125
|
+
if (css[index] === "/" && css[index + 1] === "*") {
|
|
126
|
+
const commentEnd = css.indexOf("*/", index + 2);
|
|
127
|
+
index = commentEnd === -1 ? css.length : commentEnd + 1;
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
const quote = css[index];
|
|
131
|
+
if (quote === "\"" || quote === "'") {
|
|
132
|
+
const stringEnd = skipCSSString(css, index, quote);
|
|
133
|
+
if (stringResourceFunctions.has(functionStack.at(-1) ?? "")) {
|
|
134
|
+
const unsafe = classifyCSSResource(css.slice(index + 1, stringEnd - 1), rejectRootRelative);
|
|
135
|
+
if (unsafe) return unsafe;
|
|
78
136
|
}
|
|
79
|
-
|
|
80
|
-
|
|
137
|
+
index = stringEnd - 1;
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
if (css[index] === ")") {
|
|
141
|
+
functionStack.pop();
|
|
142
|
+
continue;
|
|
81
143
|
}
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
best = candidate;
|
|
86
|
-
bestBytes = bytes;
|
|
144
|
+
if (css[index] === "(") {
|
|
145
|
+
functionStack.push(null);
|
|
146
|
+
continue;
|
|
87
147
|
}
|
|
148
|
+
if (css[index] === "@") {
|
|
149
|
+
const atRule = readCSSIdentifier(css, index + 1);
|
|
150
|
+
if (atRule?.name.toLowerCase() === "import") {
|
|
151
|
+
const valueStart = skipCSSWhitespaceAndComments(css, atRule.end);
|
|
152
|
+
const importQuote = css[valueStart];
|
|
153
|
+
if (importQuote === "\"" || importQuote === "'") {
|
|
154
|
+
const valueEnd = skipCSSString(css, valueStart, importQuote);
|
|
155
|
+
const unsafe = classifyCSSResource(css.slice(valueStart + 1, valueEnd - 1), rejectRootRelative);
|
|
156
|
+
if (unsafe) return unsafe;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
const identifier = readCSSIdentifier(css, index);
|
|
162
|
+
if (!identifier || css[identifier.end] !== "(") continue;
|
|
163
|
+
const functionName = identifier.name.toLowerCase();
|
|
164
|
+
if (functionName !== "url") {
|
|
165
|
+
functionStack.push(functionName);
|
|
166
|
+
index = identifier.end;
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
169
|
+
const valueStart = skipCSSWhitespaceAndComments(css, identifier.end + 1);
|
|
170
|
+
const urlQuote = css[valueStart];
|
|
171
|
+
const quoted = urlQuote === "\"" || urlQuote === "'";
|
|
172
|
+
let valueEnd;
|
|
173
|
+
if (quoted) {
|
|
174
|
+
valueEnd = skipCSSString(css, valueStart, urlQuote) - 1;
|
|
175
|
+
index = css.indexOf(")", valueEnd + 1);
|
|
176
|
+
} else {
|
|
177
|
+
valueEnd = valueStart;
|
|
178
|
+
while (valueEnd < css.length && css[valueEnd] !== ")") {
|
|
179
|
+
if (css[valueEnd] === "\\") valueEnd++;
|
|
180
|
+
valueEnd++;
|
|
181
|
+
}
|
|
182
|
+
index = valueEnd;
|
|
183
|
+
}
|
|
184
|
+
if (index === -1) return null;
|
|
185
|
+
const unsafe = classifyCSSResource(css.slice(valueStart + (quoted ? 1 : 0), valueEnd), rejectRootRelative);
|
|
186
|
+
if (unsafe) return unsafe;
|
|
88
187
|
}
|
|
89
|
-
return
|
|
90
|
-
}
|
|
91
|
-
function stylesheetHref(base, assets, filename) {
|
|
92
|
-
return `${base === "/" ? "" : `/${base.replace(/^\/+|\/+$/g, "")}`}/${assets.replace(/^\/+|\/+$/g, "")}/${filename}`;
|
|
188
|
+
return null;
|
|
93
189
|
}
|
|
94
|
-
function
|
|
95
|
-
if (
|
|
96
|
-
|
|
190
|
+
function crossOriginAssetsPrefix(assetsPrefix, site) {
|
|
191
|
+
if (!assetsPrefix) return null;
|
|
192
|
+
const prefix = typeof assetsPrefix === "string" ? assetsPrefix : assetsPrefix.css || assetsPrefix.fallback;
|
|
193
|
+
if (!/^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(prefix)) return null;
|
|
194
|
+
if (!site) return prefix;
|
|
195
|
+
try {
|
|
196
|
+
return (prefix.startsWith("//") ? new URL(`${site.protocol}${prefix}`) : new URL(prefix)).origin === site.origin ? null : prefix;
|
|
197
|
+
} catch {
|
|
198
|
+
return prefix;
|
|
199
|
+
}
|
|
97
200
|
}
|
|
98
|
-
function
|
|
99
|
-
const
|
|
100
|
-
const
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
201
|
+
function validateExtractedURLs(pages, assetsPrefix, site) {
|
|
202
|
+
const externalPrefix = crossOriginAssetsPrefix(assetsPrefix, site);
|
|
203
|
+
for (const page of pages) for (const artifact of page.artifacts) {
|
|
204
|
+
const unsafe = findUnsafeCSSResource(artifact.css, externalPrefix !== null);
|
|
205
|
+
if (unsafe) {
|
|
206
|
+
const reason = unsafe.rootRelative ? `root-relative CSS URL "${unsafe.url}" would resolve against the external assetsPrefix "${externalPrefix}" instead of the page origin` : `page-relative CSS URL "${unsafe.url}" cannot preserve its target`;
|
|
207
|
+
throw new Error(`[Tasty] Astro CSS extraction cannot preserve ${reason} in ${page.path} (${artifact.kind} artifact ${artifact.id}). Use an absolute URL or a data URL${externalPrefix ? "" : ", or a root-relative URL such as url(/path/to/asset)"}.`);
|
|
208
|
+
}
|
|
104
209
|
}
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
210
|
+
}
|
|
211
|
+
/** Find artifacts emitted by every styled page, in the first page's order. */
|
|
212
|
+
function selectSharedArtifacts(pages) {
|
|
213
|
+
if (pages.length < 2) return [];
|
|
214
|
+
const source = pages[0].artifacts;
|
|
215
|
+
const otherIds = pages.slice(1).map((page) => new Set(page.artifacts.map(({ id }) => id)));
|
|
216
|
+
return source.filter(({ id }) => otherIds.every((ids) => ids.has(id)));
|
|
217
|
+
}
|
|
218
|
+
function stylesheetHref(base, assets, filename, assetsPrefix) {
|
|
219
|
+
const assetsPath = assets.replace(/^\/+|\/+$/g, "");
|
|
220
|
+
if (assetsPrefix) return `${(typeof assetsPrefix === "string" ? assetsPrefix : assetsPrefix.css || assetsPrefix.fallback).replace(/\/+$/g, "")}/${assetsPath}/${filename}`;
|
|
221
|
+
return `${base === "/" ? "" : `/${base.replace(/^\/+|\/+$/g, "")}`}/${assetsPath}/${filename}`;
|
|
222
|
+
}
|
|
223
|
+
function stylesheetLink(page, href) {
|
|
224
|
+
return `<link rel="stylesheet" href="${href}" data-tasty-ssr${page.styleOpen.match(/\snonce="[^"]*"/)?.[0] ?? ""}>`;
|
|
225
|
+
}
|
|
226
|
+
function transformPage(page, hrefs) {
|
|
227
|
+
const replacement = hrefs.map((href) => stylesheetLink(page, href)).join("");
|
|
109
228
|
return page.html.slice(0, page.styleStart) + replacement + page.html.slice(page.replacementEnd);
|
|
110
229
|
}
|
|
230
|
+
async function writeStylesheet(assetDir, scope, artifacts) {
|
|
231
|
+
if (artifacts.length === 0) return null;
|
|
232
|
+
const css = artifacts.map(({ css }) => css).join("\n");
|
|
233
|
+
const filename = `tasty.${scope}.${createHash("sha256").update(css).digest("hex").slice(0, 12)}.css`;
|
|
234
|
+
await writeFile(join(assetDir, filename), css);
|
|
235
|
+
return filename;
|
|
236
|
+
}
|
|
111
237
|
async function extractAstroCSS(options) {
|
|
112
238
|
const outputDir = fileURLToPath(options.dir);
|
|
113
239
|
const paths = await findHTMLFiles(outputDir);
|
|
114
240
|
const pages = (await Promise.all(paths.map(async (path) => parseExtractablePage(path, await readFile(path, "utf8"))))).filter((page) => page !== null);
|
|
115
241
|
if (pages.length === 0) return;
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
for (const page of pages) {
|
|
119
|
-
const metadataStart = page.html.indexOf(METADATA_START, page.styleStart);
|
|
120
|
-
await writeFile(page.path, page.html.slice(0, metadataStart) + page.html.slice(page.replacementEnd));
|
|
121
|
-
}
|
|
122
|
-
return;
|
|
123
|
-
}
|
|
124
|
-
const css = selected.map(({ css }) => css).join("\n");
|
|
125
|
-
const filename = `tasty.${createHash("sha256").update(css).digest("hex").slice(0, 12)}.css`;
|
|
242
|
+
validateExtractedURLs(pages, options.assetsPrefix, options.site);
|
|
243
|
+
const shared = selectSharedArtifacts(pages);
|
|
126
244
|
const assetDir = join(outputDir, options.assets);
|
|
127
245
|
await mkdir(assetDir, { recursive: true });
|
|
128
|
-
await
|
|
129
|
-
const
|
|
130
|
-
|
|
246
|
+
const sharedFilename = await writeStylesheet(assetDir, "shared", shared);
|
|
247
|
+
const sharedHref = sharedFilename ? stylesheetHref(options.base, options.assets, sharedFilename, options.assetsPrefix) : null;
|
|
248
|
+
const sharedIds = new Set(shared.map(({ id }) => id));
|
|
249
|
+
for (const page of pages) {
|
|
250
|
+
const pageFilename = await writeStylesheet(assetDir, "page", page.artifacts.filter(({ id }) => !sharedIds.has(id)));
|
|
251
|
+
const hrefs = sharedHref ? [sharedHref] : [];
|
|
252
|
+
if (pageFilename) hrefs.push(stylesheetHref(options.base, options.assets, pageFilename, options.assetsPrefix));
|
|
253
|
+
await writeFile(page.path, transformPage(page, hrefs));
|
|
254
|
+
}
|
|
131
255
|
}
|
|
132
256
|
//#endregion
|
|
133
257
|
//#region src/ssr/astro.ts
|
|
@@ -276,6 +400,8 @@ function tastyIntegration(options) {
|
|
|
276
400
|
const cssMode = options?.css?.mode ?? "inline";
|
|
277
401
|
let base = "/";
|
|
278
402
|
let assets = "_astro";
|
|
403
|
+
let assetsPrefix;
|
|
404
|
+
let site;
|
|
279
405
|
return {
|
|
280
406
|
name: "@tenphi/tasty",
|
|
281
407
|
hooks: {
|
|
@@ -289,13 +415,17 @@ function tastyIntegration(options) {
|
|
|
289
415
|
"astro:config:done": ({ config }) => {
|
|
290
416
|
base = config.base ?? "/";
|
|
291
417
|
assets = config.build?.assets ?? "_astro";
|
|
418
|
+
assetsPrefix = config.build?.assetsPrefix;
|
|
419
|
+
site = config.site;
|
|
292
420
|
},
|
|
293
421
|
"astro:build:done": async ({ dir }) => {
|
|
294
422
|
if (cssMode !== "extract") return;
|
|
295
423
|
await extractAstroCSS({
|
|
296
424
|
dir,
|
|
297
425
|
base,
|
|
298
|
-
assets
|
|
426
|
+
assets,
|
|
427
|
+
assetsPrefix,
|
|
428
|
+
site
|
|
299
429
|
});
|
|
300
430
|
}
|
|
301
431
|
}
|
|
@@ -304,4 +434,4 @@ function tastyIntegration(options) {
|
|
|
304
434
|
//#endregion
|
|
305
435
|
export { tastyMiddleware as n, tastyIntegration as t };
|
|
306
436
|
|
|
307
|
-
//# sourceMappingURL=astro-
|
|
437
|
+
//# sourceMappingURL=astro-CzY4LCpr.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"astro-CzY4LCpr.js","names":[],"sources":["../src/ssr/astro-extraction.ts","../src/ssr/astro.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { readdir, readFile, writeFile, mkdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport type { ServerStyleArtifact } from './collector';\n\nconst METADATA_START = '<template data-tasty-extract>';\nconst METADATA_END = '</template>';\n\ninterface ExtractablePage {\n path: string;\n html: string;\n artifacts: ServerStyleArtifact[];\n styleStart: number;\n replacementEnd: number;\n styleOpen: string;\n}\n\nexport function createExtractionMetadata(\n artifacts: ServerStyleArtifact[],\n): string {\n const encoded = Buffer.from(JSON.stringify(artifacts), 'utf8').toString(\n 'base64',\n );\n return `${METADATA_START}${encoded}${METADATA_END}`;\n}\n\nfunction parseExtractablePage(\n path: string,\n html: string,\n): ExtractablePage | null {\n const metadataStart = html.indexOf(METADATA_START);\n if (metadataStart === -1) return null;\n\n const metadataContentStart = metadataStart + METADATA_START.length;\n const metadataEnd = html.indexOf(METADATA_END, metadataContentStart);\n if (metadataEnd === -1) return null;\n\n const encoded = html.slice(metadataContentStart, metadataEnd);\n let artifacts: ServerStyleArtifact[];\n try {\n artifacts = JSON.parse(\n Buffer.from(encoded, 'base64').toString('utf8'),\n ) as ServerStyleArtifact[];\n } catch {\n return null;\n }\n\n const styleStart = html.lastIndexOf('<style data-tasty-ssr', metadataStart);\n if (styleStart === -1) return null;\n const styleOpenEnd = html.indexOf('>', styleStart);\n const styleEnd = html.indexOf('</style>', styleOpenEnd + 1);\n if (\n styleOpenEnd === -1 ||\n styleEnd === -1 ||\n styleEnd + '</style>'.length !== metadataStart\n ) {\n return null;\n }\n\n return {\n path,\n html,\n artifacts,\n styleStart,\n replacementEnd: metadataEnd + METADATA_END.length,\n styleOpen: html.slice(styleStart, styleOpenEnd + 1),\n };\n}\n\nasync function findHTMLFiles(dir: string): Promise<string[]> {\n const paths: string[] = [];\n const entries = await readdir(dir, { withFileTypes: true });\n entries.sort((a, b) => a.name.localeCompare(b.name));\n for (const entry of entries) {\n const path = join(dir, entry.name);\n if (entry.isDirectory()) {\n paths.push(...(await findHTMLFiles(path)));\n } else if (entry.isFile() && entry.name.endsWith('.html')) {\n paths.push(path);\n }\n }\n return paths;\n}\n\nfunction skipCSSString(css: string, start: number, quote: string): number {\n for (let index = start + 1; index < css.length; index++) {\n if (css[index] === '\\\\') {\n index++;\n } else if (css[index] === quote) {\n return index + 1;\n }\n }\n return css.length;\n}\n\nfunction decodeCSSEscapes(value: string): string {\n return value.replace(\n /\\\\(?:([\\da-f]{1,6})\\s?|\\r\\n|[\\n\\r\\f]|(.))/gi,\n (_match, hex: string | undefined, escaped: string | undefined) => {\n if (hex) {\n const codePoint = Number.parseInt(hex, 16);\n return codePoint === 0 || codePoint > 0x10ffff\n ? '\\ufffd'\n : String.fromCodePoint(codePoint);\n }\n return escaped ?? '';\n },\n );\n}\n\nfunction readCSSIdentifier(\n css: string,\n start: number,\n): { name: string; end: number } | null {\n let name = '';\n let index = start;\n\n while (index < css.length) {\n const char = css[index];\n if (/[-_a-z\\d]/i.test(char) || char.charCodeAt(0) >= 0x80) {\n name += char;\n index++;\n continue;\n }\n if (char !== '\\\\' || index + 1 >= css.length) break;\n\n const hex = css.slice(index + 1).match(/^[\\da-f]{1,6}/i)?.[0];\n if (hex) {\n name += decodeCSSEscapes(`\\\\${hex}`);\n index += hex.length + 1;\n if (/\\s/.test(css[index] ?? '')) index++;\n continue;\n }\n\n if (/\\r|\\n|\\f/.test(css[index + 1])) break;\n name += css[index + 1];\n index += 2;\n }\n\n return index === start ? null : { name, end: index };\n}\n\nfunction skipCSSWhitespaceAndComments(css: string, start: number): number {\n let index = start;\n for (;;) {\n while (/\\s/.test(css[index] ?? '')) index++;\n if (css[index] !== '/' || css[index + 1] !== '*') return index;\n const commentEnd = css.indexOf('*/', index + 2);\n if (commentEnd === -1) return css.length;\n index = commentEnd + 2;\n }\n}\n\ninterface UnsafeCSSResource {\n url: string;\n rootRelative: boolean;\n}\n\nfunction classifyCSSResource(\n rawURL: string,\n rejectRootRelative: boolean,\n): UnsafeCSSResource | null {\n const url = decodeCSSEscapes(rawURL).trim();\n if (!url || url.startsWith('//') || /^[a-z][a-z\\d+.-]*:/i.test(url)) {\n return null;\n }\n if (url.startsWith('/')) {\n return rejectRootRelative ? { url: rawURL, rootRelative: true } : null;\n }\n return { url: rawURL, rootRelative: false };\n}\n\nfunction findUnsafeCSSResource(\n css: string,\n rejectRootRelative: boolean,\n): UnsafeCSSResource | null {\n const functionStack: (string | null)[] = [];\n const stringResourceFunctions = new Set([\n 'image',\n 'image-set',\n '-webkit-image-set',\n 'src',\n ]);\n\n for (let index = 0; index < css.length; index++) {\n if (css[index] === '/' && css[index + 1] === '*') {\n const commentEnd = css.indexOf('*/', index + 2);\n index = commentEnd === -1 ? css.length : commentEnd + 1;\n continue;\n }\n\n const quote = css[index];\n if (quote === '\"' || quote === \"'\") {\n const stringEnd = skipCSSString(css, index, quote);\n if (stringResourceFunctions.has(functionStack.at(-1) ?? '')) {\n const unsafe = classifyCSSResource(\n css.slice(index + 1, stringEnd - 1),\n rejectRootRelative,\n );\n if (unsafe) return unsafe;\n }\n index = stringEnd - 1;\n continue;\n }\n\n if (css[index] === ')') {\n functionStack.pop();\n continue;\n }\n\n if (css[index] === '(') {\n functionStack.push(null);\n continue;\n }\n\n if (css[index] === '@') {\n const atRule = readCSSIdentifier(css, index + 1);\n if (atRule?.name.toLowerCase() === 'import') {\n const valueStart = skipCSSWhitespaceAndComments(css, atRule.end);\n const importQuote = css[valueStart];\n if (importQuote === '\"' || importQuote === \"'\") {\n const valueEnd = skipCSSString(css, valueStart, importQuote);\n const unsafe = classifyCSSResource(\n css.slice(valueStart + 1, valueEnd - 1),\n rejectRootRelative,\n );\n if (unsafe) return unsafe;\n }\n }\n continue;\n }\n\n const identifier = readCSSIdentifier(css, index);\n if (!identifier || css[identifier.end] !== '(') continue;\n\n const functionName = identifier.name.toLowerCase();\n if (functionName !== 'url') {\n functionStack.push(functionName);\n index = identifier.end;\n continue;\n }\n\n const valueStart = skipCSSWhitespaceAndComments(css, identifier.end + 1);\n const urlQuote = css[valueStart];\n const quoted = urlQuote === '\"' || urlQuote === \"'\";\n let valueEnd: number;\n if (quoted) {\n valueEnd = skipCSSString(css, valueStart, urlQuote) - 1;\n index = css.indexOf(')', valueEnd + 1);\n } else {\n valueEnd = valueStart;\n while (valueEnd < css.length && css[valueEnd] !== ')') {\n if (css[valueEnd] === '\\\\') valueEnd++;\n valueEnd++;\n }\n index = valueEnd;\n }\n\n if (index === -1) return null;\n const unsafe = classifyCSSResource(\n css.slice(valueStart + (quoted ? 1 : 0), valueEnd),\n rejectRootRelative,\n );\n if (unsafe) return unsafe;\n }\n\n return null;\n}\n\nfunction crossOriginAssetsPrefix(\n assetsPrefix?: string | Record<string, string>,\n site?: URL,\n): string | null {\n if (!assetsPrefix) return null;\n const prefix =\n typeof assetsPrefix === 'string'\n ? assetsPrefix\n : assetsPrefix.css || assetsPrefix.fallback;\n if (!/^(?:[a-z][a-z\\d+.-]*:|\\/\\/)/i.test(prefix)) return null;\n if (!site) return prefix;\n\n try {\n const prefixURL = prefix.startsWith('//')\n ? new URL(`${site.protocol}${prefix}`)\n : new URL(prefix);\n return prefixURL.origin === site.origin ? null : prefix;\n } catch {\n return prefix;\n }\n}\n\nfunction validateExtractedURLs(\n pages: ExtractablePage[],\n assetsPrefix?: string | Record<string, string>,\n site?: URL,\n): void {\n const externalPrefix = crossOriginAssetsPrefix(assetsPrefix, site);\n for (const page of pages) {\n for (const artifact of page.artifacts) {\n const unsafe = findUnsafeCSSResource(\n artifact.css,\n externalPrefix !== null,\n );\n if (unsafe) {\n const reason = unsafe.rootRelative\n ? `root-relative CSS URL \"${unsafe.url}\" would resolve against the external assetsPrefix \"${externalPrefix}\" instead of the page origin`\n : `page-relative CSS URL \"${unsafe.url}\" cannot preserve its target`;\n throw new Error(\n `[Tasty] Astro CSS extraction cannot preserve ${reason} in ${page.path} (${artifact.kind} artifact ${artifact.id}). Use an absolute URL or a data URL${externalPrefix ? '' : ', or a root-relative URL such as url(/path/to/asset)'}.`,\n );\n }\n }\n }\n}\n\n/** Find artifacts emitted by every styled page, in the first page's order. */\nfunction selectSharedArtifacts(\n pages: ExtractablePage[],\n): ServerStyleArtifact[] {\n if (pages.length < 2) return [];\n\n const source = pages[0].artifacts;\n const otherIds = pages\n .slice(1)\n .map((page) => new Set(page.artifacts.map(({ id }) => id)));\n\n return source.filter(({ id }) => otherIds.every((ids) => ids.has(id)));\n}\n\nfunction stylesheetHref(\n base: string,\n assets: string,\n filename: string,\n assetsPrefix?: string | Record<string, string>,\n): string {\n const assetsPath = assets.replace(/^\\/+|\\/+$/g, '');\n if (assetsPrefix) {\n const prefix =\n typeof assetsPrefix === 'string'\n ? assetsPrefix\n : assetsPrefix.css || assetsPrefix.fallback;\n return `${prefix.replace(/\\/+$/g, '')}/${assetsPath}/${filename}`;\n }\n\n const basePath = base === '/' ? '' : `/${base.replace(/^\\/+|\\/+$/g, '')}`;\n return `${basePath}/${assetsPath}/${filename}`;\n}\n\nfunction stylesheetLink(page: ExtractablePage, href: string): string {\n const nonceAttr = page.styleOpen.match(/\\snonce=\"[^\"]*\"/)?.[0] ?? '';\n return `<link rel=\"stylesheet\" href=\"${href}\" data-tasty-ssr${nonceAttr}>`;\n}\n\nfunction transformPage(page: ExtractablePage, hrefs: string[]): string {\n const replacement = hrefs.map((href) => stylesheetLink(page, href)).join('');\n\n return (\n page.html.slice(0, page.styleStart) +\n replacement +\n page.html.slice(page.replacementEnd)\n );\n}\n\nasync function writeStylesheet(\n assetDir: string,\n scope: 'shared' | 'page',\n artifacts: ServerStyleArtifact[],\n): Promise<string | null> {\n if (artifacts.length === 0) return null;\n\n const css = artifacts.map(({ css }) => css).join('\\n');\n const hash = createHash('sha256').update(css).digest('hex').slice(0, 12);\n const filename = `tasty.${scope}.${hash}.css`;\n await writeFile(join(assetDir, filename), css);\n return filename;\n}\n\nexport async function extractAstroCSS(options: {\n dir: URL;\n base: string;\n assets: string;\n assetsPrefix?: string | Record<string, string>;\n site?: URL;\n}): Promise<void> {\n const outputDir = fileURLToPath(options.dir);\n const paths = await findHTMLFiles(outputDir);\n const pages = (\n await Promise.all(\n paths.map(async (path) =>\n parseExtractablePage(path, await readFile(path, 'utf8')),\n ),\n )\n ).filter((page): page is ExtractablePage => page !== null);\n if (pages.length === 0) return;\n validateExtractedURLs(pages, options.assetsPrefix, options.site);\n\n const shared = selectSharedArtifacts(pages);\n const assetDir = join(outputDir, options.assets);\n await mkdir(assetDir, { recursive: true });\n const sharedFilename = await writeStylesheet(assetDir, 'shared', shared);\n const sharedHref = sharedFilename\n ? stylesheetHref(\n options.base,\n options.assets,\n sharedFilename,\n options.assetsPrefix,\n )\n : null;\n const sharedIds = new Set(shared.map(({ id }) => id));\n\n for (const page of pages) {\n const remainder = page.artifacts.filter(({ id }) => !sharedIds.has(id));\n const pageFilename = await writeStylesheet(assetDir, 'page', remainder);\n const hrefs = sharedHref ? [sharedHref] : [];\n if (pageFilename) {\n hrefs.push(\n stylesheetHref(\n options.base,\n options.assets,\n pageFilename,\n options.assetsPrefix,\n ),\n );\n }\n await writeFile(page.path, transformPage(page, hrefs));\n }\n}\n","/**\n * Astro integration for Tasty SSR.\n *\n * Provides:\n * - tastyIntegration() — Astro Integration API (recommended)\n * - tastyMiddleware() — manual middleware for advanced composition\n *\n * Import from '@tenphi/tasty/ssr/astro'.\n */\n\nimport { getConfig } from '../config';\nimport { getSSRCollector, runWithCollector } from './async-storage';\nimport { createExtractionMetadata, extractAstroCSS } from './astro-extraction';\nimport { ServerStyleCollector } from './collector';\nimport { registerSSRCollectorGetterGlobal } from './ssr-collector-ref';\n\n// Wire up ALS-based collector discovery so computeStyles() can find\n// the collector set by tastyMiddleware's runWithCollector().\n// Uses globalThis so the getter is visible across Astro's separate\n// module graphs (middleware vs page components).\nregisterSSRCollectorGetterGlobal(getSSRCollector);\n\nexport interface TastyMiddlewareOptions {\n /**\n * Whether to embed the class-list script for client hydration.\n * Set to false to skip class transfer (e.g. for CSP restrictions).\n * Without it, client components may re-inject CSS that already exists\n * in server-rendered `<style>` tags. Default: true.\n */\n transferCache?: boolean;\n}\n\ninterface InternalTastyMiddlewareOptions extends TastyMiddlewareOptions {\n extractionMetadata?: boolean;\n}\n\n/**\n * Create an Astro middleware that collects Tasty styles during SSR.\n *\n * All React components rendered during the request will have their\n * computeStyles() calls captured by the collector via AsyncLocalStorage.\n * After rendering, the middleware injects the collected CSS into </head>.\n *\n * @example Manual middleware setup\n * ```ts\n * // src/middleware.ts\n * import { tastyMiddleware } from '@tenphi/tasty/ssr/astro';\n * export const onRequest = tastyMiddleware();\n * ```\n *\n * @example Composing with other middleware\n * ```ts\n * // src/middleware.ts\n * import { sequence } from 'astro:middleware';\n * import { tastyMiddleware } from '@tenphi/tasty/ssr/astro';\n *\n * export const onRequest = sequence(\n * tastyMiddleware(),\n * myOtherMiddleware,\n * );\n * ```\n */\nexport function tastyMiddleware(options?: TastyMiddlewareOptions) {\n const internalOptions = options as InternalTastyMiddlewareOptions | undefined;\n return async (\n context: { isPrerendered?: boolean },\n next: () => Promise<Response>,\n ): Promise<Response> => {\n const transferCache = options?.transferCache ?? true;\n const extractionMetadata =\n internalOptions?.extractionMetadata === true &&\n context.isPrerendered === true;\n const collector = new ServerStyleCollector();\n\n // Run the entire request — including body stream consumption — inside\n // the ALS context so that components rendering lazily during stream\n // reads can still find the collector via getSSRCollector().\n type Rendered =\n | { response: Response }\n | { html: string | null; status: number; headers: Headers };\n\n const rendered = await runWithCollector<Promise<Rendered>>(\n collector,\n async (): Promise<Rendered> => {\n const response = await next();\n const body = response.body;\n\n // Only process HTML responses. Reading a non-HTML body (e.g. an\n // image, font, or JSON endpoint) as UTF-8 text corrupts binary\n // payloads: every byte >= 0x80 is decoded to U+FFFD and re-encoded\n // as EF BF BD. Pass anything that isn't HTML straight through.\n const contentType = response.headers.get('content-type') ?? '';\n if (!body || !contentType.includes('text/html')) {\n return { response };\n }\n\n const reader = body.pipeThrough(new TextDecoderStream()).getReader();\n const parts: string[] = [];\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n parts.push(value);\n }\n return {\n html: parts.join(''),\n status: response.status,\n headers: response.headers,\n };\n },\n );\n\n // Non-HTML responses are returned untouched to avoid corrupting\n // binary payloads.\n if ('response' in rendered) {\n return rendered.response;\n }\n\n if (!rendered.html) {\n return new Response(null, {\n status: rendered.status,\n headers: rendered.headers,\n });\n }\n\n let { html } = rendered;\n\n const css = collector.getCSS();\n if (!css) {\n return new Response(html, {\n status: rendered.status,\n headers: rendered.headers,\n });\n }\n\n const nonce = getConfig().nonce;\n const nonceAttr = nonce ? ` nonce=\"${nonce}\"` : '';\n const styleTag = `<style data-tasty-ssr${nonceAttr}>${css}</style>`;\n const metadataTag = extractionMetadata\n ? createExtractionMetadata(collector.getArtifacts())\n : '';\n\n let cacheTag = '';\n if (transferCache) {\n const classNames = collector.getRenderedClassNames();\n if (classNames.length > 0) {\n const classListJSON = classNames.map((n) => `\"${n}\"`).join(',');\n cacheTag = `<script${nonceAttr}>(window.__TASTY__=window.__TASTY__||[]).push(${classListJSON})</script>`;\n }\n }\n\n const injection = styleTag + metadataTag + cacheTag;\n const idx = html.indexOf('</head>');\n if (idx !== -1) {\n html = html.slice(0, idx) + injection + html.slice(idx);\n } else {\n html = injection + html;\n }\n\n const headers = new Headers(rendered.headers);\n headers.delete('content-length');\n\n return new Response(html, {\n status: rendered.status,\n headers,\n });\n };\n}\n\n// ============================================================================\n// Astro Integration API\n// ============================================================================\n\n/**\n * Package subpaths of the middleware entrypoints registered by\n * `tastyIntegration()`.\n *\n * These must be bare specifiers rather than\n * `new URL('./astro-middleware.js', import.meta.url)`. The bundler is free to\n * hoist `tastyIntegration` into a shared chunk at a different directory depth\n * than `dist/ssr/`, which makes a relative URL resolve to a file that does not\n * exist and breaks the build for every consumer. A package subpath is resolved\n * by the consumer through our `exports` map, so it never depends on the\n * chunk layout.\n *\n * There are separate entrypoints instead of one parameterised entrypoint because\n * `addMiddleware()` cannot pass options: the integration runs when the Astro\n * config is loaded, while the middleware module is evaluated in the server\n * runtime — a different process for built output — so module-level state set\n * by the integration is not visible to the middleware.\n */\nconst MIDDLEWARE_ENTRYPOINT = '@tenphi/tasty/ssr/astro-middleware';\nconst MIDDLEWARE_ENTRYPOINT_STATIC =\n '@tenphi/tasty/ssr/astro-middleware-static';\nconst MIDDLEWARE_ENTRYPOINT_EXTRACT =\n '@tenphi/tasty/ssr/astro-middleware-extract';\nconst MIDDLEWARE_ENTRYPOINT_EXTRACT_STATIC =\n '@tenphi/tasty/ssr/astro-middleware-extract-static';\n\nexport interface TastyIntegrationCSSOptions {\n /**\n * CSS delivery mode. Extraction only applies to prerendered builds.\n * Extracted CSS preserves resource URLs verbatim, so use absolute URLs or\n * data URLs. Root-relative URLs are also supported unless `assetsPrefix`\n * sends CSS to an external origin. The build rejects resource URLs whose\n * targets would change after extraction.\n */\n mode?: 'inline' | 'extract';\n}\n\nexport interface TastyIntegrationOptions {\n /**\n * Enable island hydration support.\n *\n * When `true` (default): injects a client hydration script via\n * `injectScript('before-hydration')` and sets `transferCache: true`\n * on the middleware. Islands skip the style pipeline during hydration.\n *\n * When `false`: no client JS is shipped and `transferCache` is set\n * to `false`. Use this for fully static sites without `client:*`\n * directives.\n */\n islands?: boolean;\n /** Configure inline or build-wide extracted CSS delivery. */\n css?: TastyIntegrationCSSOptions;\n}\n\n/**\n * Astro integration that automatically sets up Tasty SSR.\n *\n * Registers middleware for cross-component CSS deduplication and\n * optionally injects a client hydration script for island support.\n *\n * @example Basic setup (with islands)\n * ```ts\n * // astro.config.mjs\n * import { tastyIntegration } from '@tenphi/tasty/ssr/astro';\n *\n * export default defineConfig({\n * integrations: [tastyIntegration()],\n * });\n * ```\n *\n * @example Static-only (no client JS)\n * ```ts\n * // astro.config.mjs\n * import { tastyIntegration } from '@tenphi/tasty/ssr/astro';\n *\n * export default defineConfig({\n * integrations: [tastyIntegration({ islands: false })],\n * });\n * ```\n */\nexport function tastyIntegration(options?: TastyIntegrationOptions) {\n const { islands = true } = options ?? {};\n const cssMode = options?.css?.mode ?? 'inline';\n let base = '/';\n let assets = '_astro';\n let assetsPrefix: string | Record<string, string> | undefined;\n let site: URL | undefined;\n\n return {\n name: '@tenphi/tasty',\n hooks: {\n 'astro:config:setup': ({\n addMiddleware,\n injectScript,\n }: {\n addMiddleware: (middleware: {\n entrypoint: string | URL;\n order: 'pre' | 'post';\n }) => void;\n injectScript: (\n stage: 'head-inline' | 'before-hydration' | 'page' | 'page-ssr',\n content: string,\n ) => void;\n }) => {\n addMiddleware({\n entrypoint:\n cssMode === 'extract'\n ? islands\n ? MIDDLEWARE_ENTRYPOINT_EXTRACT\n : MIDDLEWARE_ENTRYPOINT_EXTRACT_STATIC\n : islands\n ? MIDDLEWARE_ENTRYPOINT\n : MIDDLEWARE_ENTRYPOINT_STATIC,\n order: 'pre',\n });\n\n if (islands) {\n injectScript(\n 'before-hydration',\n `import \"@tenphi/tasty/ssr/astro-client\";`,\n );\n }\n },\n 'astro:config:done': ({\n config,\n }: {\n config: {\n base?: string;\n site?: URL;\n build?: {\n assets?: string;\n assetsPrefix?: string | Record<string, string>;\n };\n };\n }) => {\n base = config.base ?? '/';\n assets = config.build?.assets ?? '_astro';\n assetsPrefix = config.build?.assetsPrefix;\n site = config.site;\n },\n 'astro:build:done': async ({ dir }: { dir: URL }) => {\n if (cssMode !== 'extract') return;\n await extractAstroCSS({ dir, base, assets, assetsPrefix, site });\n },\n },\n };\n}\n"],"mappings":";;;;;;;;;AAOA,MAAM,iBAAiB;AACvB,MAAM,eAAe;AAWrB,SAAgB,yBACd,WACQ;CAIR,OAAO,GAAG,iBAHM,OAAO,KAAK,KAAK,UAAU,SAAS,GAAG,MAAM,CAAC,CAAC,SAC7D,QAE+B,IAAI;AACvC;AAEA,SAAS,qBACP,MACA,MACwB;CACxB,MAAM,gBAAgB,KAAK,QAAQ,cAAc;CACjD,IAAI,kBAAkB,IAAI,OAAO;CAEjC,MAAM,uBAAuB,gBAAgB;CAC7C,MAAM,cAAc,KAAK,QAAQ,cAAc,oBAAoB;CACnE,IAAI,gBAAgB,IAAI,OAAO;CAE/B,MAAM,UAAU,KAAK,MAAM,sBAAsB,WAAW;CAC5D,IAAI;CACJ,IAAI;EACF,YAAY,KAAK,MACf,OAAO,KAAK,SAAS,QAAQ,CAAC,CAAC,SAAS,MAAM,CAChD;CACF,QAAQ;EACN,OAAO;CACT;CAEA,MAAM,aAAa,KAAK,YAAY,yBAAyB,aAAa;CAC1E,IAAI,eAAe,IAAI,OAAO;CAC9B,MAAM,eAAe,KAAK,QAAQ,KAAK,UAAU;CACjD,MAAM,WAAW,KAAK,QAAQ,YAAY,eAAe,CAAC;CAC1D,IACE,iBAAiB,MACjB,aAAa,MACb,WAAW,MA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{
|
|
|
47
47
|
isPrerendered?: boolean;
|
|
48
48
|
}, next: () => Promise<Response>) => Promise<Response>;
|
|
49
49
|
interface TastyIntegrationCSSOptions {
|
|
50
|
-
/**
|
|
50
|
+
/**
|
|
51
|
+
* CSS delivery mode. Extraction only applies to prerendered builds.
|
|
52
|
+
* Extracted CSS preserves resource URLs verbatim, so use absolute URLs or
|
|
53
|
+
* data URLs. Root-relative URLs are also supported unless `assetsPrefix`
|
|
54
|
+
* sends CSS to an external origin. The build rejects resource URLs whose
|
|
55
|
+
* targets would change after extraction.
|
|
56
|
+
*/
|
|
51
57
|
mode?: 'inline' | 'extract';
|
|
52
58
|
}
|
|
53
59
|
interface TastyIntegrationOptions {
|
|
@@ -110,8 +116,10 @@ declare function tastyIntegration(options?: TastyIntegrationOptions): {
|
|
|
110
116
|
}: {
|
|
111
117
|
config: {
|
|
112
118
|
base?: string;
|
|
119
|
+
site?: URL;
|
|
113
120
|
build?: {
|
|
114
121
|
assets?: string;
|
|
122
|
+
assetsPrefix?: string | Record<string, string>;
|
|
115
123
|
};
|
|
116
124
|
};
|
|
117
125
|
}) => void;
|
package/dist/ssr/astro.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as tastyMiddleware, t as tastyIntegration } from "../astro-
|
|
1
|
+
import { n as tastyMiddleware, t as tastyIntegration } from "../astro-CzY4LCpr.js";
|
|
2
2
|
export { tastyIntegration, tastyMiddleware };
|
package/docs/ssr.md
CHANGED
|
@@ -235,8 +235,8 @@ This gives the same middleware deduplication and hook support, but ships zero cl
|
|
|
235
235
|
|
|
236
236
|
#### Build-wide CSS extraction
|
|
237
237
|
|
|
238
|
-
Static Astro builds can move
|
|
239
|
-
|
|
238
|
+
Static Astro builds can move Tasty CSS into content-hashed, browser-cacheable
|
|
239
|
+
shared and page assets:
|
|
240
240
|
|
|
241
241
|
```ts
|
|
242
242
|
export default defineConfig({
|
|
@@ -257,14 +257,38 @@ output. Extraction requires Astro 5 or newer and only applies to prerendered
|
|
|
257
257
|
production pages. Development, preview-time SSR, and on-demand routes continue
|
|
258
258
|
to receive the normal inline `<style data-tasty-ssr>` output.
|
|
259
259
|
|
|
260
|
-
Extraction
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
260
|
+
Extraction writes every artifact emitted by all styled pages to a shared
|
|
261
|
+
stylesheet. Each page's strict set difference is written to a separate page
|
|
262
|
+
stylesheet. The shared link comes first and the page link follows, so shared
|
|
263
|
+
styles form the base cascade and page-only styles can override them. A fully
|
|
264
|
+
shared page omits the empty page stylesheet. If generated pages have no common
|
|
265
|
+
artifacts, each page receives only its page stylesheet.
|
|
266
|
+
|
|
267
|
+
The shared-base/page-override order is the extraction-mode cascade contract.
|
|
268
|
+
It does not preserve an inline artifact order where a page-only rule originally
|
|
269
|
+
appeared before a shared rule. Use shared styles for defaults and page-only
|
|
270
|
+
styles for overrides.
|
|
271
|
+
|
|
272
|
+
Extracted CSS preserves resource URLs verbatim. Relative URLs in an inline
|
|
273
|
+
style resolve from the page, but in an extracted stylesheet they resolve from
|
|
274
|
+
the asset directory. Use absolute URLs or data URLs when extraction is enabled.
|
|
275
|
+
Root-relative URLs such as `url(/fonts/brand.woff2)` are also safe while the
|
|
276
|
+
stylesheet stays on the page's origin. The build fails with a clear error if an
|
|
277
|
+
artifact contains a page-relative or fragment-only URL, including URL strings
|
|
278
|
+
in `image-set()`, `image()`, `src()`, and `@import`.
|
|
279
|
+
|
|
280
|
+
Assets are written under Astro's configured `build.assets` directory (for
|
|
281
|
+
example, `/_astro/tasty.shared.a1b2c3.css` and
|
|
282
|
+
`/_astro/tasty.page.d4e5f6.css`). Links include the configured Astro `base`, so
|
|
283
|
+
nested routes do not need relative-path handling. Content hashes and output are
|
|
284
|
+
deterministic for identical builds. If `build.assetsPrefix` is configured,
|
|
285
|
+
Tasty uses its CSS-specific prefix (or `fallback`) just like Astro-generated
|
|
286
|
+
stylesheets. When that prefix points to a different origin, root-relative
|
|
287
|
+
resources would resolve against the asset origin rather than the page's origin,
|
|
288
|
+
so the build rejects them as well. Tasty compares the prefix with Astro's `site`
|
|
289
|
+
when it is configured; without `site`, an absolute or protocol-relative prefix
|
|
290
|
+
is treated conservatively as cross-origin. Use a fully absolute resource URL in
|
|
291
|
+
that configuration.
|
|
268
292
|
|
|
269
293
|
### Manual middleware (advanced)
|
|
270
294
|
|
|
@@ -300,12 +324,13 @@ Astro's `@astrojs/react` renderer calls `renderToString()` for each React compon
|
|
|
300
324
|
- The middleware reads the full response body, then injects the collected CSS into `</head>` before sending the final HTML.
|
|
301
325
|
- In extraction mode, prerendered responses also carry temporary structured
|
|
302
326
|
artifact metadata. `astro:build:done` uses those collector-provided
|
|
303
|
-
boundaries to write
|
|
304
|
-
the metadata.
|
|
327
|
+
boundaries to write shared and page assets and rewrite generated HTML, then
|
|
328
|
+
removes the metadata. Artifact boundaries are never inferred by splitting or
|
|
329
|
+
reparsing the generated CSS.
|
|
305
330
|
|
|
306
331
|
### CSP nonce
|
|
307
332
|
|
|
308
|
-
Call `configure({ nonce: '...' })` before any rendering happens. The middleware reads the nonce and applies it to injected `<style>` and `<script>` tags. In extraction mode,
|
|
333
|
+
Call `configure({ nonce: '...' })` before any rendering happens. The middleware reads the nonce and applies it to injected `<style>` and `<script>` tags. In extraction mode, the external stylesheet links retain the nonce.
|
|
309
334
|
|
|
310
335
|
---
|
|
311
336
|
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"astro-ib7E7V4Y.js","names":[],"sources":["../src/ssr/astro-extraction.ts","../src/ssr/astro.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { readdir, readFile, writeFile, mkdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport type { ServerStyleArtifact } from './collector';\n\nconst METADATA_START = '<template data-tasty-extract>';\nconst METADATA_END = '</template>';\n\ninterface ExtractablePage {\n path: string;\n html: string;\n artifacts: ServerStyleArtifact[];\n styleStart: number;\n replacementEnd: number;\n styleOpen: string;\n}\n\nexport function createExtractionMetadata(\n artifacts: ServerStyleArtifact[],\n): string {\n const encoded = Buffer.from(JSON.stringify(artifacts), 'utf8').toString(\n 'base64',\n );\n return `${METADATA_START}${encoded}${METADATA_END}`;\n}\n\nfunction parseExtractablePage(\n path: string,\n html: string,\n): ExtractablePage | null {\n const metadataStart = html.indexOf(METADATA_START);\n if (metadataStart === -1) return null;\n\n const metadataContentStart = metadataStart + METADATA_START.length;\n const metadataEnd = html.indexOf(METADATA_END, metadataContentStart);\n if (metadataEnd === -1) return null;\n\n const encoded = html.slice(metadataContentStart, metadataEnd);\n let artifacts: ServerStyleArtifact[];\n try {\n artifacts = JSON.parse(\n Buffer.from(encoded, 'base64').toString('utf8'),\n ) as ServerStyleArtifact[];\n } catch {\n return null;\n }\n\n const styleStart = html.lastIndexOf('<style data-tasty-ssr', metadataStart);\n if (styleStart === -1) return null;\n const styleOpenEnd = html.indexOf('>', styleStart);\n const styleEnd = html.indexOf('</style>', styleOpenEnd + 1);\n if (\n styleOpenEnd === -1 ||\n styleEnd === -1 ||\n styleEnd + '</style>'.length !== metadataStart\n ) {\n return null;\n }\n\n return {\n path,\n html,\n artifacts,\n styleStart,\n replacementEnd: metadataEnd + METADATA_END.length,\n styleOpen: html.slice(styleStart, styleOpenEnd + 1),\n };\n}\n\nasync function findHTMLFiles(dir: string): Promise<string[]> {\n const paths: string[] = [];\n const entries = await readdir(dir, { withFileTypes: true });\n entries.sort((a, b) => a.name.localeCompare(b.name));\n for (const entry of entries) {\n const path = join(dir, entry.name);\n if (entry.isDirectory()) {\n paths.push(...(await findHTMLFiles(path)));\n } else if (entry.isFile() && entry.name.endsWith('.html')) {\n paths.push(path);\n }\n }\n return paths;\n}\n\nfunction findSequence(haystack: string[], needle: string[]): number {\n if (needle.length === 0) return -1;\n outer: for (let i = 0; i <= haystack.length - needle.length; i++) {\n for (let j = 0; j < needle.length; j++) {\n if (haystack[i + j] !== needle[j]) continue outer;\n }\n return i;\n }\n return -1;\n}\n\n/** Find the largest byte-sized artifact block that is contiguous on every page. */\nfunction selectSharedArtifacts(\n pages: ExtractablePage[],\n): ServerStyleArtifact[] {\n if (pages.length < 2) return [];\n\n const source = pages.reduce((shortest, page) =>\n page.artifacts.length < shortest.artifacts.length ? page : shortest,\n );\n const otherIds = pages\n .filter((page) => page !== source)\n .map((page) => page.artifacts.map(({ id }) => id));\n const sourceIds = source.artifacts.map(({ id }) => id);\n\n let best: ServerStyleArtifact[] = [];\n let bestBytes = 0;\n for (let start = 0; start < source.artifacts.length; start++) {\n let length = source.artifacts.length - start;\n for (const pageIds of otherIds) {\n let pageLength = 0;\n for (let pageStart = 0; pageStart < pageIds.length; pageStart++) {\n if (pageIds[pageStart] !== sourceIds[start]) continue;\n let matchLength = 1;\n while (\n start + matchLength < sourceIds.length &&\n pageStart + matchLength < pageIds.length &&\n sourceIds[start + matchLength] === pageIds[pageStart + matchLength]\n ) {\n matchLength++;\n }\n pageLength = Math.max(pageLength, matchLength);\n }\n length = Math.min(length, pageLength);\n if (length === 0) break;\n }\n\n const candidate = source.artifacts.slice(start, start + length);\n const bytes = candidate.reduce((total, item) => total + item.css.length, 0);\n if (bytes > bestBytes) {\n best = candidate;\n bestBytes = bytes;\n }\n }\n\n return best;\n}\n\nfunction stylesheetHref(\n base: string,\n assets: string,\n filename: string,\n): string {\n const basePath = base === '/' ? '' : `/${base.replace(/^\\/+|\\/+$/g, '')}`;\n const assetsPath = assets.replace(/^\\/+|\\/+$/g, '');\n return `${basePath}/${assetsPath}/${filename}`;\n}\n\nfunction styleTag(styleOpen: string, artifacts: ServerStyleArtifact[]): string {\n if (artifacts.length === 0) return '';\n return `${styleOpen}${artifacts.map(({ css }) => css).join('\\n')}</style>`;\n}\n\nfunction transformPage(\n page: ExtractablePage,\n selected: ServerStyleArtifact[],\n href: string,\n): string {\n const selectedIds = selected.map(({ id }) => id);\n const pageIds = page.artifacts.map(({ id }) => id);\n const first = findSequence(pageIds, selectedIds);\n if (first === -1) {\n const metadataStart = page.html.indexOf(METADATA_START, page.styleStart);\n return (\n page.html.slice(0, metadataStart) + page.html.slice(page.replacementEnd)\n );\n }\n\n const before = page.artifacts.slice(0, first);\n const after = page.artifacts.slice(first + selected.length);\n const nonceAttr = page.styleOpen.match(/\\snonce=\"[^\"]*\"/)?.[0] ?? '';\n const link = `<link rel=\"stylesheet\" href=\"${href}\" data-tasty-ssr${nonceAttr}>`;\n const replacement =\n styleTag(page.styleOpen, before) + link + styleTag(page.styleOpen, after);\n\n return (\n page.html.slice(0, page.styleStart) +\n replacement +\n page.html.slice(page.replacementEnd)\n );\n}\n\nexport async function extractAstroCSS(options: {\n dir: URL;\n base: string;\n assets: string;\n}): Promise<void> {\n const outputDir = fileURLToPath(options.dir);\n const paths = await findHTMLFiles(outputDir);\n const pages = (\n await Promise.all(\n paths.map(async (path) =>\n parseExtractablePage(path, await readFile(path, 'utf8')),\n ),\n )\n ).filter((page): page is ExtractablePage => page !== null);\n if (pages.length === 0) return;\n\n const selected = selectSharedArtifacts(pages);\n if (selected.length === 0) {\n for (const page of pages) {\n const metadataStart = page.html.indexOf(METADATA_START, page.styleStart);\n await writeFile(\n page.path,\n page.html.slice(0, metadataStart) +\n page.html.slice(page.replacementEnd),\n );\n }\n return;\n }\n\n const css = selected.map(({ css }) => css).join('\\n');\n const hash = createHash('sha256').update(css).digest('hex').slice(0, 12);\n const filename = `tasty.${hash}.css`;\n const assetDir = join(outputDir, options.assets);\n await mkdir(assetDir, { recursive: true });\n await writeFile(join(assetDir, filename), css);\n\n const href = stylesheetHref(options.base, options.assets, filename);\n for (const page of pages) {\n await writeFile(page.path, transformPage(page, selected, href));\n }\n}\n","/**\n * Astro integration for Tasty SSR.\n *\n * Provides:\n * - tastyIntegration() — Astro Integration API (recommended)\n * - tastyMiddleware() — manual middleware for advanced composition\n *\n * Import from '@tenphi/tasty/ssr/astro'.\n */\n\nimport { getConfig } from '../config';\nimport { getSSRCollector, runWithCollector } from './async-storage';\nimport { createExtractionMetadata, extractAstroCSS } from './astro-extraction';\nimport { ServerStyleCollector } from './collector';\nimport { registerSSRCollectorGetterGlobal } from './ssr-collector-ref';\n\n// Wire up ALS-based collector discovery so computeStyles() can find\n// the collector set by tastyMiddleware's runWithCollector().\n// Uses globalThis so the getter is visible across Astro's separate\n// module graphs (middleware vs page components).\nregisterSSRCollectorGetterGlobal(getSSRCollector);\n\nexport interface TastyMiddlewareOptions {\n /**\n * Whether to embed the class-list script for client hydration.\n * Set to false to skip class transfer (e.g. for CSP restrictions).\n * Without it, client components may re-inject CSS that already exists\n * in server-rendered `<style>` tags. Default: true.\n */\n transferCache?: boolean;\n}\n\ninterface InternalTastyMiddlewareOptions extends TastyMiddlewareOptions {\n extractionMetadata?: boolean;\n}\n\n/**\n * Create an Astro middleware that collects Tasty styles during SSR.\n *\n * All React components rendered during the request will have their\n * computeStyles() calls captured by the collector via AsyncLocalStorage.\n * After rendering, the middleware injects the collected CSS into </head>.\n *\n * @example Manual middleware setup\n * ```ts\n * // src/middleware.ts\n * import { tastyMiddleware } from '@tenphi/tasty/ssr/astro';\n * export const onRequest = tastyMiddleware();\n * ```\n *\n * @example Composing with other middleware\n * ```ts\n * // src/middleware.ts\n * import { sequence } from 'astro:middleware';\n * import { tastyMiddleware } from '@tenphi/tasty/ssr/astro';\n *\n * export const onRequest = sequence(\n * tastyMiddleware(),\n * myOtherMiddleware,\n * );\n * ```\n */\nexport function tastyMiddleware(options?: TastyMiddlewareOptions) {\n const internalOptions = options as InternalTastyMiddlewareOptions | undefined;\n return async (\n context: { isPrerendered?: boolean },\n next: () => Promise<Response>,\n ): Promise<Response> => {\n const transferCache = options?.transferCache ?? true;\n const extractionMetadata =\n internalOptions?.extractionMetadata === true &&\n context.isPrerendered === true;\n const collector = new ServerStyleCollector();\n\n // Run the entire request — including body stream consumption — inside\n // the ALS context so that components rendering lazily during stream\n // reads can still find the collector via getSSRCollector().\n type Rendered =\n | { response: Response }\n | { html: string | null; status: number; headers: Headers };\n\n const rendered = await runWithCollector<Promise<Rendered>>(\n collector,\n async (): Promise<Rendered> => {\n const response = await next();\n const body = response.body;\n\n // Only process HTML responses. Reading a non-HTML body (e.g. an\n // image, font, or JSON endpoint) as UTF-8 text corrupts binary\n // payloads: every byte >= 0x80 is decoded to U+FFFD and re-encoded\n // as EF BF BD. Pass anything that isn't HTML straight through.\n const contentType = response.headers.get('content-type') ?? '';\n if (!body || !contentType.includes('text/html')) {\n return { response };\n }\n\n const reader = body.pipeThrough(new TextDecoderStream()).getReader();\n const parts: string[] = [];\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n parts.push(value);\n }\n return {\n html: parts.join(''),\n status: response.status,\n headers: response.headers,\n };\n },\n );\n\n // Non-HTML responses are returned untouched to avoid corrupting\n // binary payloads.\n if ('response' in rendered) {\n return rendered.response;\n }\n\n if (!rendered.html) {\n return new Response(null, {\n status: rendered.status,\n headers: rendered.headers,\n });\n }\n\n let { html } = rendered;\n\n const css = collector.getCSS();\n if (!css) {\n return new Response(html, {\n status: rendered.status,\n headers: rendered.headers,\n });\n }\n\n const nonce = getConfig().nonce;\n const nonceAttr = nonce ? ` nonce=\"${nonce}\"` : '';\n const styleTag = `<style data-tasty-ssr${nonceAttr}>${css}</style>`;\n const metadataTag = extractionMetadata\n ? createExtractionMetadata(collector.getArtifacts())\n : '';\n\n let cacheTag = '';\n if (transferCache) {\n const classNames = collector.getRenderedClassNames();\n if (classNames.length > 0) {\n const classListJSON = classNames.map((n) => `\"${n}\"`).join(',');\n cacheTag = `<script${nonceAttr}>(window.__TASTY__=window.__TASTY__||[]).push(${classListJSON})</script>`;\n }\n }\n\n const injection = styleTag + metadataTag + cacheTag;\n const idx = html.indexOf('</head>');\n if (idx !== -1) {\n html = html.slice(0, idx) + injection + html.slice(idx);\n } else {\n html = injection + html;\n }\n\n const headers = new Headers(rendered.headers);\n headers.delete('content-length');\n\n return new Response(html, {\n status: rendered.status,\n headers,\n });\n };\n}\n\n// ============================================================================\n// Astro Integration API\n// ============================================================================\n\n/**\n * Package subpaths of the middleware entrypoints registered by\n * `tastyIntegration()`.\n *\n * These must be bare specifiers rather than\n * `new URL('./astro-middleware.js', import.meta.url)`. The bundler is free to\n * hoist `tastyIntegration` into a shared chunk at a different directory depth\n * than `dist/ssr/`, which makes a relative URL resolve to a file that does not\n * exist and breaks the build for every consumer. A package subpath is resolved\n * by the consumer through our `exports` map, so it never depends on the\n * chunk layout.\n *\n * There are separate entrypoints instead of one parameterised entrypoint because\n * `addMiddleware()` cannot pass options: the integration runs when the Astro\n * config is loaded, while the middleware module is evaluated in the server\n * runtime — a different process for built output — so module-level state set\n * by the integration is not visible to the middleware.\n */\nconst MIDDLEWARE_ENTRYPOINT = '@tenphi/tasty/ssr/astro-middleware';\nconst MIDDLEWARE_ENTRYPOINT_STATIC =\n '@tenphi/tasty/ssr/astro-middleware-static';\nconst MIDDLEWARE_ENTRYPOINT_EXTRACT =\n '@tenphi/tasty/ssr/astro-middleware-extract';\nconst MIDDLEWARE_ENTRYPOINT_EXTRACT_STATIC =\n '@tenphi/tasty/ssr/astro-middleware-extract-static';\n\nexport interface TastyIntegrationCSSOptions {\n /** CSS delivery mode. Extraction only applies to prerendered builds. */\n mode?: 'inline' | 'extract';\n}\n\nexport interface TastyIntegrationOptions {\n /**\n * Enable island hydration support.\n *\n * When `true` (default): injects a client hydration script via\n * `injectScript('before-hydration')` and sets `transferCache: true`\n * on the middleware. Islands skip the style pipeline during hydration.\n *\n * When `false`: no client JS is shipped and `transferCache` is set\n * to `false`. Use this for fully static sites without `client:*`\n * directives.\n */\n islands?: boolean;\n /** Configure inline or build-wide extracted CSS delivery. */\n css?: TastyIntegrationCSSOptions;\n}\n\n/**\n * Astro integration that automatically sets up Tasty SSR.\n *\n * Registers middleware for cross-component CSS deduplication and\n * optionally injects a client hydration script for island support.\n *\n * @example Basic setup (with islands)\n * ```ts\n * // astro.config.mjs\n * import { tastyIntegration } from '@tenphi/tasty/ssr/astro';\n *\n * export default defineConfig({\n * integrations: [tastyIntegration()],\n * });\n * ```\n *\n * @example Static-only (no client JS)\n * ```ts\n * // astro.config.mjs\n * import { tastyIntegration } from '@tenphi/tasty/ssr/astro';\n *\n * export default defineConfig({\n * integrations: [tastyIntegration({ islands: false })],\n * });\n * ```\n */\nexport function tastyIntegration(options?: TastyIntegrationOptions) {\n const { islands = true } = options ?? {};\n const cssMode = options?.css?.mode ?? 'inline';\n let base = '/';\n let assets = '_astro';\n\n return {\n name: '@tenphi/tasty',\n hooks: {\n 'astro:config:setup': ({\n addMiddleware,\n injectScript,\n }: {\n addMiddleware: (middleware: {\n entrypoint: string | URL;\n order: 'pre' | 'post';\n }) => void;\n injectScript: (\n stage: 'head-inline' | 'before-hydration' | 'page' | 'page-ssr',\n content: string,\n ) => void;\n }) => {\n addMiddleware({\n entrypoint:\n cssMode === 'extract'\n ? islands\n ? MIDDLEWARE_ENTRYPOINT_EXTRACT\n : MIDDLEWARE_ENTRYPOINT_EXTRACT_STATIC\n : islands\n ? MIDDLEWARE_ENTRYPOINT\n : MIDDLEWARE_ENTRYPOINT_STATIC,\n order: 'pre',\n });\n\n if (islands) {\n injectScript(\n 'before-hydration',\n `import \"@tenphi/tasty/ssr/astro-client\";`,\n );\n }\n },\n 'astro:config:done': ({\n config,\n }: {\n config: { base?: string; build?: { assets?: string } };\n }) => {\n base = config.base ?? '/';\n assets = config.build?.assets ?? '_astro';\n },\n 'astro:build:done': async ({ dir }: { dir: URL }) => {\n if (cssMode !== 'extract') return;\n await extractAstroCSS({ dir, base, assets });\n },\n },\n };\n}\n"],"mappings":";;;;;;;;;AAOA,MAAM,iBAAiB;AACvB,MAAM,eAAe;AAWrB,SAAgB,yBACd,WACQ;CAIR,OAAO,GAAG,iBAHM,OAAO,KAAK,KAAK,UAAU,SAAS,GAAG,MAAM,CAAC,CAAC,SAC7D,QAE+B,IAAI;AACvC;AAEA,SAAS,qBACP,MACA,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