@tenphi/tasty 0.0.0-snapshot.27b6708 → 0.0.0-snapshot.28eb83c

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/README.md +38 -54
  2. package/dist/{babel-BUQGeOXA.d.ts → babel-D6lOuSwk.d.ts} +2 -2
  3. package/dist/chunks/async-storage-DKK-wTD4.js.map +1 -0
  4. package/dist/chunks/build-config-BBThSdlo.js +45 -0
  5. package/dist/chunks/build-config-BBThSdlo.js.map +1 -0
  6. package/dist/{collector-DTahQUiV.js → chunks/collector-DcViW2ZQ.js} +28 -14
  7. package/dist/chunks/collector-DcViW2ZQ.js.map +1 -0
  8. package/dist/chunks/config-engine-DQVQK4NU.js +403 -0
  9. package/dist/chunks/config-engine-DQVQK4NU.js.map +1 -0
  10. package/dist/chunks/css-definitions-BZ9vm0ci.js +1284 -0
  11. package/dist/chunks/css-definitions-BZ9vm0ci.js.map +1 -0
  12. package/dist/chunks/css-resources-Cyl_axbI.js +149 -0
  13. package/dist/chunks/css-resources-Cyl_axbI.js.map +1 -0
  14. package/dist/chunks/debug-Vyauml7U.js +583 -0
  15. package/dist/chunks/debug-Vyauml7U.js.map +1 -0
  16. package/dist/chunks/dsl-CXvoaLnj.js +2097 -0
  17. package/dist/chunks/dsl-CXvoaLnj.js.map +1 -0
  18. package/dist/chunks/hydration-CLdVKcH2.js +59 -0
  19. package/dist/chunks/hydration-CLdVKcH2.js.map +1 -0
  20. package/dist/chunks/react-runtime-so_X_yMo.js +1526 -0
  21. package/dist/chunks/react-runtime-so_X_yMo.js.map +1 -0
  22. package/dist/chunks/runtime-engine-DQ5laRou.js +3056 -0
  23. package/dist/chunks/runtime-engine-DQ5laRou.js.map +1 -0
  24. package/dist/{merge-styles-oklji0KB.js → chunks/shared-utils-OIg0N_dp.js} +42 -3
  25. package/dist/chunks/shared-utils-OIg0N_dp.js.map +1 -0
  26. package/dist/{config-B5kHzuNz.js → chunks/style-engine-CBuOt1e4.js} +2387 -7442
  27. package/dist/chunks/style-engine-CBuOt1e4.js.map +1 -0
  28. package/dist/{css-writer-B-J87ncv.js → chunks/zero-engine-BFh7gKbK.js} +3 -3
  29. package/dist/chunks/zero-engine-BFh7gKbK.js.map +1 -0
  30. package/dist/{collector-DUaHCcTS.d.ts → collector-CAmndLXe.d.ts} +23 -3
  31. package/dist/{config-YsxGv4tq.d.ts → config-BWYrv_Aa.d.ts} +141 -37
  32. package/dist/core/index.d.ts +5 -5
  33. package/dist/core/index.js +9 -6
  34. package/dist/{index-Cd45t5NM.d.ts → index-BzAC3p06.d.ts} +118 -23
  35. package/dist/{index-PqN-DIpn.d.ts → index-D4kRLj2o.d.ts} +128 -68
  36. package/dist/index.d.ts +5 -5
  37. package/dist/index.js +10 -922
  38. package/dist/{merge-styles-CU7JbEwg.d.ts → merge-styles-BFktNP8J.d.ts} +2 -2
  39. package/dist/ssr/astro-client.js +1 -1
  40. package/dist/ssr/astro-middleware-extract-static.d.ts +11 -0
  41. package/dist/ssr/astro-middleware-extract-static.js +9 -0
  42. package/dist/ssr/astro-middleware-extract-static.js.map +1 -0
  43. package/dist/ssr/astro-middleware-extract.d.ts +11 -0
  44. package/dist/ssr/astro-middleware-extract.js +9 -0
  45. package/dist/ssr/astro-middleware-extract.js.map +1 -0
  46. package/dist/ssr/astro-middleware-static.d.ts +3 -1
  47. package/dist/ssr/astro-middleware.d.ts +3 -1
  48. package/dist/ssr/astro.d.ts +45 -3
  49. package/dist/ssr/astro.js +157 -14
  50. package/dist/ssr/astro.js.map +1 -1
  51. package/dist/ssr/index.d.ts +7 -7
  52. package/dist/ssr/index.js +4 -4
  53. package/dist/ssr/index.js.map +1 -1
  54. package/dist/ssr/next-config.d.ts +66 -0
  55. package/dist/ssr/next-config.js +135 -0
  56. package/dist/ssr/next-config.js.map +1 -0
  57. package/dist/ssr/next.d.ts +9 -2
  58. package/dist/ssr/next.js +26 -10
  59. package/dist/ssr/next.js.map +1 -1
  60. package/dist/static/index.d.ts +2 -2
  61. package/dist/static/index.js +1 -1
  62. package/dist/zero/babel.d.ts +1 -1
  63. package/dist/zero/babel.js +25 -24
  64. package/dist/zero/babel.js.map +1 -1
  65. package/dist/zero/index.d.ts +1 -1
  66. package/dist/zero/index.js +1 -1
  67. package/dist/zero/next.d.ts +1 -1
  68. package/docs/README.md +5 -3
  69. package/docs/adoption.md +3 -3
  70. package/docs/ai-agents.md +83 -78
  71. package/docs/comparison.md +12 -12
  72. package/docs/configuration.md +47 -47
  73. package/docs/debug.md +19 -7
  74. package/docs/dsl.md +3 -3
  75. package/docs/getting-started.md +10 -10
  76. package/docs/injector.md +62 -25
  77. package/docs/methodology.md +3 -3
  78. package/docs/migration-v3.md +49 -49
  79. package/docs/plugins.md +37 -33
  80. package/docs/react-api.md +2 -2
  81. package/docs/runtime-benchmarks.md +351 -0
  82. package/docs/ssr.md +219 -61
  83. package/docs/styles.md +43 -11
  84. package/docs/tasty-static.md +136 -103
  85. package/package.json +80 -11
  86. package/dist/async-storage-DKK-wTD4.js.map +0 -1
  87. package/dist/collector-DTahQUiV.js.map +0 -1
  88. package/dist/config-B5kHzuNz.js.map +0 -1
  89. package/dist/context-CA8YKeMn.js +0 -24
  90. package/dist/context-CA8YKeMn.js.map +0 -1
  91. package/dist/core-Dr4u1NVD.js +0 -1566
  92. package/dist/core-Dr4u1NVD.js.map +0 -1
  93. package/dist/css-writer-B-J87ncv.js.map +0 -1
  94. package/dist/format-global-rules-DklyaXv-.js +0 -22
  95. package/dist/format-global-rules-DklyaXv-.js.map +0 -1
  96. package/dist/format-rules-DKOA-6qu.js +0 -130
  97. package/dist/format-rules-DKOA-6qu.js.map +0 -1
  98. package/dist/hydrate-OeMX99We.js +0 -37
  99. package/dist/hydrate-OeMX99We.js.map +0 -1
  100. package/dist/index.js.map +0 -1
  101. package/dist/keyframes-CV8azJf3.js +0 -493
  102. package/dist/keyframes-CV8azJf3.js.map +0 -1
  103. package/dist/merge-styles-oklji0KB.js.map +0 -1
  104. package/dist/resolve-recipes-DTG81rzl.js +0 -144
  105. package/dist/resolve-recipes-DTG81rzl.js.map +0 -1
  106. /package/dist/{async-storage-DKK-wTD4.js → chunks/async-storage-DKK-wTD4.js} +0 -0
@@ -1,7 +1,7 @@
1
- import { b as Styles } from "./index-Cd45t5NM.js";
1
+ import { b as Styles } from "./index-BzAC3p06.js";
2
2
 
3
3
  //#region src/utils/merge-styles.d.ts
4
4
  declare function mergeStyles(...objects: (Styles | undefined | null)[]): Styles;
5
5
  //#endregion
6
6
  export { mergeStyles as t };
7
- //# sourceMappingURL=merge-styles-CU7JbEwg.d.ts.map
7
+ //# sourceMappingURL=merge-styles-BFktNP8J.d.ts.map
@@ -1,4 +1,4 @@
1
- import { t as hydrateTastyClasses } from "../hydrate-OeMX99We.js";
1
+ import { t as hydrateTastyClasses } from "../chunks/hydration-CLdVKcH2.js";
2
2
  //#region src/ssr/astro-client.ts
3
3
  /**
4
4
  * Client-side cache hydration for Astro islands.
@@ -0,0 +1,11 @@
1
+ //#region src/ssr/astro-middleware-extract-static.d.ts
2
+ /**
3
+ * Prerender-extraction middleware entrypoint for sites without islands.
4
+ * Exported only so Astro can resolve it through the package exports map.
5
+ */
6
+ declare const onRequest: (context: {
7
+ isPrerendered?: boolean;
8
+ }, next: () => Promise<Response>) => Promise<Response>;
9
+ //#endregion
10
+ export { onRequest };
11
+ //# sourceMappingURL=astro-middleware-extract-static.d.ts.map
@@ -0,0 +1,9 @@
1
+ import { tastyMiddleware } from "./astro.js";
2
+ const onRequest = tastyMiddleware({
3
+ transferCache: false,
4
+ extractionMetadata: true
5
+ });
6
+ //#endregion
7
+ export { onRequest };
8
+
9
+ //# sourceMappingURL=astro-middleware-extract-static.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"astro-middleware-extract-static.js","names":[],"sources":["../../src/ssr/astro-middleware-extract-static.ts"],"sourcesContent":["/**\n * Prerender-extraction middleware entrypoint for sites without islands.\n * Exported only so Astro can resolve it through the package exports map.\n */\n\nimport { tastyMiddleware } from './astro';\n\nconst options = {\n transferCache: false,\n extractionMetadata: true,\n};\n\nexport const onRequest = tastyMiddleware(options);\n"],"mappings":";AAYA,MAAa,YAAY,gBAAgB;CAJvC,eAAe;CACf,oBAAoB;AAGmB,CAAO"}
@@ -0,0 +1,11 @@
1
+ //#region src/ssr/astro-middleware-extract.d.ts
2
+ /**
3
+ * Prerender-extraction middleware entrypoint with island cache transfer.
4
+ * Exported only so Astro can resolve it through the package exports map.
5
+ */
6
+ declare const onRequest: (context: {
7
+ isPrerendered?: boolean;
8
+ }, next: () => Promise<Response>) => Promise<Response>;
9
+ //#endregion
10
+ export { onRequest };
11
+ //# sourceMappingURL=astro-middleware-extract.d.ts.map
@@ -0,0 +1,9 @@
1
+ import { tastyMiddleware } from "./astro.js";
2
+ const onRequest = tastyMiddleware({
3
+ transferCache: true,
4
+ extractionMetadata: true
5
+ });
6
+ //#endregion
7
+ export { onRequest };
8
+
9
+ //# sourceMappingURL=astro-middleware-extract.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"astro-middleware-extract.js","names":[],"sources":["../../src/ssr/astro-middleware-extract.ts"],"sourcesContent":["/**\n * Prerender-extraction middleware entrypoint with island cache transfer.\n * Exported only so Astro can resolve it through the package exports map.\n */\n\nimport { tastyMiddleware } from './astro';\n\nconst options = {\n transferCache: true,\n extractionMetadata: true,\n};\n\nexport const onRequest = tastyMiddleware(options);\n"],"mappings":";AAYA,MAAa,YAAY,gBAAgB;CAJvC,eAAe;CACf,oBAAoB;AAGmB,CAAO"}
@@ -10,7 +10,9 @@
10
10
  * Identical to `./astro-middleware` except that no class-list `<script>` is
11
11
  * emitted, so a site without `client:*` islands ships zero client JavaScript.
12
12
  */
13
- declare const onRequest: (_context: unknown, next: () => Promise<Response>) => Promise<Response>;
13
+ declare const onRequest: (context: {
14
+ isPrerendered?: boolean;
15
+ }, next: () => Promise<Response>) => Promise<Response>;
14
16
  //#endregion
15
17
  export { onRequest };
16
18
  //# sourceMappingURL=astro-middleware-static.d.ts.map
@@ -11,7 +11,9 @@
11
11
  * `./astro-middleware-static` for the variant used by
12
12
  * `tastyIntegration({ islands: false })`.
13
13
  */
14
- declare const onRequest: (_context: unknown, next: () => Promise<Response>) => Promise<Response>;
14
+ declare const onRequest: (context: {
15
+ isPrerendered?: boolean;
16
+ }, next: () => Promise<Response>) => Promise<Response>;
15
17
  //#endregion
16
18
  export { onRequest };
17
19
  //# sourceMappingURL=astro-middleware.d.ts.map
@@ -43,7 +43,19 @@ interface TastyMiddlewareOptions {
43
43
  * );
44
44
  * ```
45
45
  */
46
- declare function tastyMiddleware(options?: TastyMiddlewareOptions): (_context: unknown, next: () => Promise<Response>) => Promise<Response>;
46
+ declare function tastyMiddleware(options?: TastyMiddlewareOptions): (context: {
47
+ isPrerendered?: boolean;
48
+ }, next: () => Promise<Response>) => Promise<Response>;
49
+ interface TastyIntegrationCSSOptions {
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
+ */
57
+ mode?: 'inline' | 'extract';
58
+ }
47
59
  interface TastyIntegrationOptions {
48
60
  /**
49
61
  * Enable island hydration support.
@@ -57,6 +69,8 @@ interface TastyIntegrationOptions {
57
69
  * directives.
58
70
  */
59
71
  islands?: boolean;
72
+ /** Configure inline or build-wide extracted CSS delivery. */
73
+ css?: TastyIntegrationCSSOptions;
60
74
  }
61
75
  /**
62
76
  * Astro integration that automatically sets up Tasty SSR.
@@ -86,8 +100,36 @@ interface TastyIntegrationOptions {
86
100
  */
87
101
  declare function tastyIntegration(options?: TastyIntegrationOptions): {
88
102
  name: string;
89
- hooks: Record<string, (...args: never[]) => void>;
103
+ hooks: {
104
+ 'astro:config:setup': ({
105
+ addMiddleware,
106
+ injectScript
107
+ }: {
108
+ addMiddleware: (middleware: {
109
+ entrypoint: string | URL;
110
+ order: "pre" | "post";
111
+ }) => void;
112
+ injectScript: (stage: "head-inline" | "before-hydration" | "page" | "page-ssr", content: string) => void;
113
+ }) => void;
114
+ 'astro:config:done': ({
115
+ config
116
+ }: {
117
+ config: {
118
+ base?: string;
119
+ site?: URL;
120
+ build?: {
121
+ assets?: string;
122
+ assetsPrefix?: string | Record<string, string>;
123
+ };
124
+ };
125
+ }) => void;
126
+ 'astro:build:done': ({
127
+ dir
128
+ }: {
129
+ dir: URL;
130
+ }) => Promise<void>;
131
+ };
90
132
  };
91
133
  //#endregion
92
- export { TastyIntegrationOptions, TastyMiddlewareOptions, tastyIntegration, tastyMiddleware };
134
+ export { TastyIntegrationCSSOptions, TastyIntegrationOptions, TastyMiddlewareOptions, tastyIntegration, tastyMiddleware };
93
135
  //# sourceMappingURL=astro.d.ts.map
package/dist/ssr/astro.js CHANGED
@@ -1,7 +1,122 @@
1
- import { n as getConfig } from "../config-B5kHzuNz.js";
2
- import { a as registerSSRCollectorGetterGlobal } from "../format-rules-DKOA-6qu.js";
3
- import { t as ServerStyleCollector } from "../collector-DTahQUiV.js";
4
- import { n as runWithCollector, t as getSSRCollector } from "../async-storage-DKK-wTD4.js";
1
+ import { j as getConfig, s as registerSSRCollectorGetterGlobal } from "../chunks/runtime-engine-DQ5laRou.js";
2
+ import { t as ServerStyleCollector } from "../chunks/collector-DcViW2ZQ.js";
3
+ import { n as runWithCollector, t as getSSRCollector } from "../chunks/async-storage-DKK-wTD4.js";
4
+ import { t as findUnsafeCSSResource } from "../chunks/css-resources-Cyl_axbI.js";
5
+ import { createHash } from "node:crypto";
6
+ import { join } from "node:path";
7
+ import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
8
+ import { fileURLToPath } from "node:url";
9
+ //#region src/ssr/astro-extraction.ts
10
+ const METADATA_START = "<template data-tasty-extract>";
11
+ const METADATA_END = "</template>";
12
+ function createExtractionMetadata(artifacts) {
13
+ return `${METADATA_START}${Buffer.from(JSON.stringify(artifacts), "utf8").toString("base64")}${METADATA_END}`;
14
+ }
15
+ function parseExtractablePage(path, html) {
16
+ const metadataStart = html.indexOf(METADATA_START);
17
+ if (metadataStart === -1) return null;
18
+ const metadataContentStart = metadataStart + 29;
19
+ const metadataEnd = html.indexOf(METADATA_END, metadataContentStart);
20
+ if (metadataEnd === -1) return null;
21
+ const encoded = html.slice(metadataContentStart, metadataEnd);
22
+ let artifacts;
23
+ try {
24
+ artifacts = JSON.parse(Buffer.from(encoded, "base64").toString("utf8"));
25
+ } catch {
26
+ return null;
27
+ }
28
+ const styleStart = html.lastIndexOf("<style data-tasty-ssr", metadataStart);
29
+ if (styleStart === -1) return null;
30
+ const styleOpenEnd = html.indexOf(">", styleStart);
31
+ const styleEnd = html.indexOf("</style>", styleOpenEnd + 1);
32
+ if (styleOpenEnd === -1 || styleEnd === -1 || styleEnd + 8 !== metadataStart) return null;
33
+ return {
34
+ path,
35
+ html,
36
+ artifacts,
37
+ styleStart,
38
+ replacementEnd: metadataEnd + 11,
39
+ styleOpen: html.slice(styleStart, styleOpenEnd + 1)
40
+ };
41
+ }
42
+ async function findHTMLFiles(dir) {
43
+ const paths = [];
44
+ const entries = await readdir(dir, { withFileTypes: true });
45
+ entries.sort((a, b) => a.name.localeCompare(b.name));
46
+ for (const entry of entries) {
47
+ const path = join(dir, entry.name);
48
+ if (entry.isDirectory()) paths.push(...await findHTMLFiles(path));
49
+ else if (entry.isFile() && entry.name.endsWith(".html")) paths.push(path);
50
+ }
51
+ return paths;
52
+ }
53
+ function crossOriginAssetsPrefix(assetsPrefix, site) {
54
+ if (!assetsPrefix) return null;
55
+ const prefix = typeof assetsPrefix === "string" ? assetsPrefix : assetsPrefix.css || assetsPrefix.fallback;
56
+ if (!/^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(prefix)) return null;
57
+ if (!site) return prefix;
58
+ try {
59
+ return (prefix.startsWith("//") ? new URL(`${site.protocol}${prefix}`) : new URL(prefix)).origin === site.origin ? null : prefix;
60
+ } catch {
61
+ return prefix;
62
+ }
63
+ }
64
+ function validateExtractedURLs(pages, assetsPrefix, site) {
65
+ const externalPrefix = crossOriginAssetsPrefix(assetsPrefix, site);
66
+ for (const page of pages) for (const artifact of page.artifacts) {
67
+ const unsafe = findUnsafeCSSResource(artifact.css, externalPrefix !== null);
68
+ if (unsafe) {
69
+ 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`;
70
+ 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)"}.`);
71
+ }
72
+ }
73
+ }
74
+ /** Find artifacts emitted by every styled page, in the first page's order. */
75
+ function selectSharedArtifacts(pages) {
76
+ if (pages.length < 2) return [];
77
+ const source = pages[0].artifacts;
78
+ const otherIds = pages.slice(1).map((page) => new Set(page.artifacts.map(({ id }) => id)));
79
+ return source.filter(({ id }) => otherIds.every((ids) => ids.has(id)));
80
+ }
81
+ function stylesheetHref(base, assets, filename, assetsPrefix) {
82
+ const assetsPath = assets.replace(/^\/+|\/+$/g, "");
83
+ if (assetsPrefix) return `${(typeof assetsPrefix === "string" ? assetsPrefix : assetsPrefix.css || assetsPrefix.fallback).replace(/\/+$/g, "")}/${assetsPath}/${filename}`;
84
+ return `${base === "/" ? "" : `/${base.replace(/^\/+|\/+$/g, "")}`}/${assetsPath}/${filename}`;
85
+ }
86
+ function stylesheetLink(page, href) {
87
+ return `<link rel="stylesheet" href="${href}" data-tasty-ssr${page.styleOpen.match(/\snonce="[^"]*"/)?.[0] ?? ""}>`;
88
+ }
89
+ function transformPage(page, hrefs) {
90
+ const replacement = hrefs.map((href) => stylesheetLink(page, href)).join("");
91
+ return page.html.slice(0, page.styleStart) + replacement + page.html.slice(page.replacementEnd);
92
+ }
93
+ async function writeStylesheet(assetDir, scope, artifacts) {
94
+ if (artifacts.length === 0) return null;
95
+ const css = artifacts.map(({ css }) => css).join("\n");
96
+ const filename = `tasty.${scope}.${createHash("sha256").update(css).digest("hex").slice(0, 12)}.css`;
97
+ await writeFile(join(assetDir, filename), css);
98
+ return filename;
99
+ }
100
+ async function extractAstroCSS(options) {
101
+ const outputDir = fileURLToPath(options.dir);
102
+ const paths = await findHTMLFiles(outputDir);
103
+ const pages = (await Promise.all(paths.map(async (path) => parseExtractablePage(path, await readFile(path, "utf8"))))).filter((page) => page !== null);
104
+ if (pages.length === 0) return;
105
+ validateExtractedURLs(pages, options.assetsPrefix, options.site);
106
+ const shared = selectSharedArtifacts(pages);
107
+ const assetDir = join(outputDir, options.assets);
108
+ await mkdir(assetDir, { recursive: true });
109
+ const sharedFilename = await writeStylesheet(assetDir, "shared", shared);
110
+ const sharedHref = sharedFilename ? stylesheetHref(options.base, options.assets, sharedFilename, options.assetsPrefix) : null;
111
+ const sharedIds = new Set(shared.map(({ id }) => id));
112
+ for (const page of pages) {
113
+ const pageFilename = await writeStylesheet(assetDir, "page", page.artifacts.filter(({ id }) => !sharedIds.has(id)));
114
+ const hrefs = sharedHref ? [sharedHref] : [];
115
+ if (pageFilename) hrefs.push(stylesheetHref(options.base, options.assets, pageFilename, options.assetsPrefix));
116
+ await writeFile(page.path, transformPage(page, hrefs));
117
+ }
118
+ }
119
+ //#endregion
5
120
  //#region src/ssr/astro.ts
6
121
  /**
7
122
  * Astro integration for Tasty SSR.
@@ -40,8 +155,10 @@ registerSSRCollectorGetterGlobal(getSSRCollector);
40
155
  * ```
41
156
  */
42
157
  function tastyMiddleware(options) {
43
- return async (_context, next) => {
158
+ const internalOptions = options;
159
+ return async (context, next) => {
44
160
  const transferCache = options?.transferCache ?? true;
161
+ const extractionMetadata = internalOptions?.extractionMetadata === true && context.isPrerendered === true;
45
162
  const collector = new ServerStyleCollector();
46
163
  const rendered = await runWithCollector(collector, async () => {
47
164
  const response = await next();
@@ -75,12 +192,13 @@ function tastyMiddleware(options) {
75
192
  const nonce = getConfig().nonce;
76
193
  const nonceAttr = nonce ? ` nonce="${nonce}"` : "";
77
194
  const styleTag = `<style data-tasty-ssr${nonceAttr}>${css}</style>`;
195
+ const metadataTag = extractionMetadata ? createExtractionMetadata(collector.getArtifacts()) : "";
78
196
  let cacheTag = "";
79
197
  if (transferCache) {
80
198
  const classNames = collector.getRenderedClassNames();
81
199
  if (classNames.length > 0) cacheTag = `<script${nonceAttr}>(window.__TASTY__=window.__TASTY__||[]).push(${classNames.map((n) => `"${n}"`).join(",")})<\/script>`;
82
200
  }
83
- const injection = styleTag + cacheTag;
201
+ const injection = styleTag + metadataTag + cacheTag;
84
202
  const idx = html.indexOf("</head>");
85
203
  if (idx !== -1) html = html.slice(0, idx) + injection + html.slice(idx);
86
204
  else html = injection + html;
@@ -104,7 +222,7 @@ function tastyMiddleware(options) {
104
222
  * by the consumer through our `exports` map, so it never depends on the
105
223
  * chunk layout.
106
224
  *
107
- * There are two entrypoints instead of one parameterised entrypoint because
225
+ * There are separate entrypoints instead of one parameterised entrypoint because
108
226
  * `addMiddleware()` cannot pass options: the integration runs when the Astro
109
227
  * config is loaded, while the middleware module is evaluated in the server
110
228
  * runtime — a different process for built output — so module-level state set
@@ -112,6 +230,8 @@ function tastyMiddleware(options) {
112
230
  */
113
231
  const MIDDLEWARE_ENTRYPOINT = "@tenphi/tasty/ssr/astro-middleware";
114
232
  const MIDDLEWARE_ENTRYPOINT_STATIC = "@tenphi/tasty/ssr/astro-middleware-static";
233
+ const MIDDLEWARE_ENTRYPOINT_EXTRACT = "@tenphi/tasty/ssr/astro-middleware-extract";
234
+ const MIDDLEWARE_ENTRYPOINT_EXTRACT_STATIC = "@tenphi/tasty/ssr/astro-middleware-extract-static";
115
235
  /**
116
236
  * Astro integration that automatically sets up Tasty SSR.
117
237
  *
@@ -140,15 +260,38 @@ const MIDDLEWARE_ENTRYPOINT_STATIC = "@tenphi/tasty/ssr/astro-middleware-static"
140
260
  */
141
261
  function tastyIntegration(options) {
142
262
  const { islands = true } = options ?? {};
263
+ const cssMode = options?.css?.mode ?? "inline";
264
+ let base = "/";
265
+ let assets = "_astro";
266
+ let assetsPrefix;
267
+ let site;
143
268
  return {
144
269
  name: "@tenphi/tasty",
145
- hooks: { "astro:config:setup": ({ addMiddleware, injectScript }) => {
146
- addMiddleware({
147
- entrypoint: islands ? MIDDLEWARE_ENTRYPOINT : MIDDLEWARE_ENTRYPOINT_STATIC,
148
- order: "pre"
149
- });
150
- if (islands) injectScript("before-hydration", `import "@tenphi/tasty/ssr/astro-client";`);
151
- } }
270
+ hooks: {
271
+ "astro:config:setup": ({ addMiddleware, injectScript }) => {
272
+ addMiddleware({
273
+ entrypoint: cssMode === "extract" ? islands ? MIDDLEWARE_ENTRYPOINT_EXTRACT : MIDDLEWARE_ENTRYPOINT_EXTRACT_STATIC : islands ? MIDDLEWARE_ENTRYPOINT : MIDDLEWARE_ENTRYPOINT_STATIC,
274
+ order: "pre"
275
+ });
276
+ if (islands) injectScript("before-hydration", `import "@tenphi/tasty/ssr/astro-client";`);
277
+ },
278
+ "astro:config:done": ({ config }) => {
279
+ base = config.base ?? "/";
280
+ assets = config.build?.assets ?? "_astro";
281
+ assetsPrefix = config.build?.assetsPrefix;
282
+ site = config.site;
283
+ },
284
+ "astro:build:done": async ({ dir }) => {
285
+ if (cssMode !== "extract") return;
286
+ await extractAstroCSS({
287
+ dir,
288
+ base,
289
+ assets,
290
+ assetsPrefix,
291
+ site
292
+ });
293
+ }
294
+ }
152
295
  };
153
296
  }
154
297
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"astro.js","names":[],"sources":["../../src/ssr/astro.ts"],"sourcesContent":["/**\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 { 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\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 return async (\n _context: unknown,\n next: () => Promise<Response>,\n ): Promise<Response> => {\n const transferCache = options?.transferCache ?? 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\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 + 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 two 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';\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}\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 name: string;\n hooks: Record<string, (...args: never[]) => void>;\n} {\n const { islands = true } = options ?? {};\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: 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 },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AAmBA,iCAAiC,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsChD,SAAgB,gBAAgB,SAAkC;CAChE,OAAO,OACL,UACA,SACsB;EACtB,MAAM,gBAAgB,SAAS,iBAAiB;EAChD,MAAM,YAAY,IAAI,qBAAqB;EAS3C,MAAM,WAAW,MAAM,iBACrB,WACA,YAA+B;GAC7B,MAAM,WAAW,MAAM,KAAK;GAC5B,MAAM,OAAO,SAAS;GAMtB,MAAM,cAAc,SAAS,QAAQ,IAAI,cAAc,KAAK;GAC5D,IAAI,CAAC,QAAQ,CAAC,YAAY,SAAS,WAAW,GAC5C,OAAO,EAAE,SAAS;GAGpB,MAAM,SAAS,KAAK,YAAY,IAAI,kBAAkB,CAAC,CAAC,CAAC,UAAU;GACnE,MAAM,QAAkB,CAAC;GACzB,SAAS;IACP,MAAM,EAAE,MAAM,UAAU,MAAM,OAAO,KAAK;IAC1C,IAAI,MAAM;IACV,MAAM,KAAK,KAAK;GAClB;GACA,OAAO;IACL,MAAM,MAAM,KAAK,EAAE;IACnB,QAAQ,SAAS;IACjB,SAAS,SAAS;GACpB;EACF,CACF;EAIA,IAAI,cAAc,UAChB,OAAO,SAAS;EAGlB,IAAI,CAAC,SAAS,MACZ,OAAO,IAAI,SAAS,MAAM;GACxB,QAAQ,SAAS;GACjB,SAAS,SAAS;EACpB,CAAC;EAGH,IAAI,EAAE,SAAS;EAEf,MAAM,MAAM,UAAU,OAAO;EAC7B,IAAI,CAAC,KACH,OAAO,IAAI,SAAS,MAAM;GACxB,QAAQ,SAAS;GACjB,SAAS,SAAS;EACpB,CAAC;EAGH,MAAM,QAAQ,UAAU,CAAC,CAAC;EAC1B,MAAM,YAAY,QAAQ,WAAW,MAAM,KAAK;EAChD,MAAM,WAAW,wBAAwB,UAAU,GAAG,IAAI;EAE1D,IAAI,WAAW;EACf,IAAI,eAAe;GACjB,MAAM,aAAa,UAAU,sBAAsB;GACnD,IAAI,WAAW,SAAS,GAEtB,WAAW,UAAU,UAAU,gDADT,WAAW,KAAK,MAAM,IAAI,EAAE,EAAE,CAAC,CAAC,KAAK,GACgC,EAAE;EAEjG;EAEA,MAAM,YAAY,WAAW;EAC7B,MAAM,MAAM,KAAK,QAAQ,SAAS;EAClC,IAAI,QAAQ,IACV,OAAO,KAAK,MAAM,GAAG,GAAG,IAAI,YAAY,KAAK,MAAM,GAAG;OAEtD,OAAO,YAAY;EAGrB,MAAM,UAAU,IAAI,QAAQ,SAAS,OAAO;EAC5C,QAAQ,OAAO,gBAAgB;EAE/B,OAAO,IAAI,SAAS,MAAM;GACxB,QAAQ,SAAS;GACjB;EACF,CAAC;CACH;AACF;;;;;;;;;;;;;;;;;;;AAwBA,MAAM,wBAAwB;AAC9B,MAAM,+BACJ;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CF,SAAgB,iBAAiB,SAG/B;CACA,MAAM,EAAE,UAAU,SAAS,WAAW,CAAC;CAEvC,OAAO;EACL,MAAM;EACN,OAAO,EACL,uBAAuB,EACrB,eACA,mBAUI;GACJ,cAAc;IACZ,YAAY,UACR,wBACA;IACJ,OAAO;GACT,CAAC;GAED,IAAI,SACF,aACE,oBACA,0CACF;EAEJ,EACF;CACF;AACF"}
1
+ {"version":3,"file":"astro.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';\nimport { findUnsafeCSSResource } from './css-resources';\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 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":";;;;;;;;;AAQA,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,MAAsB,eAEjC,OAAO;CAGT,OAAO;EACL;EACA;EACA;EACA;EACA,g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ACF"}
@@ -1,4 +1,4 @@
1
- import { n as createServerStyleCollector, t as ServerStyleCollector } from "../collector-DUaHCcTS.js";
1
+ import { i as ServerStyleArtifactKind, n as createServerStyleCollector, r as ServerStyleArtifact, t as ServerStyleCollector } from "../collector-CAmndLXe.js";
2
2
 
3
3
  //#region src/ssr/async-storage.d.ts
4
4
  /**
@@ -17,13 +17,13 @@ declare function getSSRCollector(): ServerStyleCollector | null;
17
17
  /**
18
18
  * Client-side cache hydration for SSR/RSC.
19
19
  *
20
- * Pre-populates the client injector's rules map with class names
21
- * rendered on the server. With hash-based naming, the client derives
22
- * the same class name from the same cache key, so only the class name
23
- * list needs to cross the wire — no cache keys or counters.
20
+ * Registers class names rendered on the server with the client injector. If
21
+ * the runtime is not initialized yet, registration is deferred until its first
22
+ * use. With hash-based naming, only the class name list needs to cross the
23
+ * wire — no cache keys or counters.
24
24
  */
25
25
  /**
26
- * Pre-populate the client-side style registry from the server's class name list.
26
+ * Hydrate the client-side style registry from the server's class name list.
27
27
  *
28
28
  * Call this before ReactDOM.hydrateRoot() or ensure it runs before
29
29
  * any tasty() component renders on the client.
@@ -33,5 +33,5 @@ declare function getSSRCollector(): ServerStyleCollector | null;
33
33
  */
34
34
  declare function hydrateTastyClasses(classes?: string[]): void;
35
35
  //#endregion
36
- export { ServerStyleCollector, createServerStyleCollector, getSSRCollector, hydrateTastyClasses, runWithCollector };
36
+ export { type ServerStyleArtifact, type ServerStyleArtifactKind, ServerStyleCollector, createServerStyleCollector, getSSRCollector, hydrateTastyClasses, runWithCollector };
37
37
  //# sourceMappingURL=index.d.ts.map
package/dist/ssr/index.js CHANGED
@@ -1,7 +1,7 @@
1
- import { a as registerSSRCollectorGetterGlobal } from "../format-rules-DKOA-6qu.js";
2
- import { n as createServerStyleCollector, t as ServerStyleCollector } from "../collector-DTahQUiV.js";
3
- import { n as runWithCollector, t as getSSRCollector } from "../async-storage-DKK-wTD4.js";
4
- import { t as hydrateTastyClasses } from "../hydrate-OeMX99We.js";
1
+ import { s as registerSSRCollectorGetterGlobal } from "../chunks/runtime-engine-DQ5laRou.js";
2
+ import { n as createServerStyleCollector, t as ServerStyleCollector } from "../chunks/collector-DcViW2ZQ.js";
3
+ import { n as runWithCollector, t as getSSRCollector } from "../chunks/async-storage-DKK-wTD4.js";
4
+ import { t as hydrateTastyClasses } from "../chunks/hydration-CLdVKcH2.js";
5
5
  //#region src/ssr/index.ts
6
6
  registerSSRCollectorGetterGlobal(getSSRCollector);
7
7
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/ssr/index.ts"],"sourcesContent":["/**\n * SSR entry point for @tenphi/tasty.\n *\n * Provides the core SSR infrastructure: ServerStyleCollector,\n * AsyncLocalStorage integration, and cache hydration.\n *\n * Import from '@tenphi/tasty/ssr'.\n */\n\n// Core collector\nexport { ServerStyleCollector, createServerStyleCollector } from './collector';\n\n// AsyncLocalStorage integration for Astro / generic frameworks\nexport { runWithCollector, getSSRCollector } from './async-storage';\n\n// Client-side cache hydration\nexport { hydrateTastyClasses } from './hydrate';\n\n// Register the ALS getter so hooks can find the collector\n// without importing 'node:async_hooks' in the browser bundle.\n// Uses globalThis so the getter is visible across separate module graphs.\nimport { getSSRCollector } from './async-storage';\nimport { registerSSRCollectorGetterGlobal } from './ssr-collector-ref';\n\nregisterSSRCollectorGetterGlobal(getSSRCollector);\n"],"mappings":";;;;;AAwBA,iCAAiC,eAAe"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/ssr/index.ts"],"sourcesContent":["/**\n * SSR entry point for @tenphi/tasty.\n *\n * Provides the core SSR infrastructure: ServerStyleCollector,\n * AsyncLocalStorage integration, and cache hydration.\n *\n * Import from '@tenphi/tasty/ssr'.\n */\n\n// Core collector\nexport { ServerStyleCollector, createServerStyleCollector } from './collector';\nexport type { ServerStyleArtifact, ServerStyleArtifactKind } from './collector';\n\n// AsyncLocalStorage integration for Astro / generic frameworks\nexport { runWithCollector, getSSRCollector } from './async-storage';\n\n// Client-side cache hydration\nexport { hydrateTastyClasses } from './hydrate';\n\n// Register the ALS getter so hooks can find the collector\n// without importing 'node:async_hooks' in the browser bundle.\n// Uses globalThis so the getter is visible across separate module graphs.\nimport { getSSRCollector } from './async-storage';\nimport { registerSSRCollectorGetterGlobal } from './ssr-collector-ref';\n\nregisterSSRCollectorGetterGlobal(getSSRCollector);\n"],"mappings":";;;;;AAyBA,iCAAiC,eAAe"}
@@ -0,0 +1,66 @@
1
+ import { t as TastyConfig } from "../config-BWYrv_Aa.js";
2
+
3
+ //#region src/ssr/next-config.d.ts
4
+ interface NextConfig {
5
+ basePath?: string;
6
+ env?: Record<string, string | undefined>;
7
+ headers?: () => Promise<NextHeader[]>;
8
+ output?: string;
9
+ [key: string]: unknown;
10
+ }
11
+ interface NextHeader {
12
+ source: string;
13
+ headers: {
14
+ key: string;
15
+ value: string;
16
+ }[];
17
+ [key: string]: unknown;
18
+ }
19
+ interface TastyNextOptions {
20
+ /**
21
+ * Next.js project directory. Useful when the build command runs from a
22
+ * monorepo root rather than the app directory.
23
+ *
24
+ * @default process.cwd()
25
+ */
26
+ rootDir?: string;
27
+ /**
28
+ * Tasty configuration used to generate the shared stylesheet.
29
+ * `config` takes precedence when both config sources are provided.
30
+ */
31
+ config?: TastyConfig;
32
+ /**
33
+ * Project-relative path to a TypeScript/JavaScript module whose default
34
+ * export is a Tasty configuration object.
35
+ *
36
+ * @example './app/tasty.config.ts'
37
+ */
38
+ configFile?: string;
39
+ /**
40
+ * Filesystem directory for generated stylesheets. When it is inside the
41
+ * project's `public` directory, its public URL is inferred automatically.
42
+ *
43
+ * @default 'public/_tasty'
44
+ */
45
+ outputDir?: string;
46
+ /**
47
+ * Root-relative URL path corresponding to `outputDir`. This is required
48
+ * when `outputDir` is outside the project's `public` directory.
49
+ * The Next.js `basePath` is prepended automatically.
50
+ *
51
+ * @default inferred from outputDir
52
+ * @example '/assets/tasty'
53
+ */
54
+ publicPath?: string;
55
+ /** Whether to generate and register the shared stylesheet. @default true */
56
+ enabled?: boolean;
57
+ }
58
+ /**
59
+ * Add a cacheable, content-hashed stylesheet for Tasty configuration globals.
60
+ * Route-dependent component and hook styles continue to stream through
61
+ * `TastyRegistry` so App Router navigation and Suspense remain correct.
62
+ */
63
+ declare function withTastyNext(options: TastyNextOptions): (nextConfig?: NextConfig) => NextConfig;
64
+ //#endregion
65
+ export { TastyNextOptions, withTastyNext };
66
+ //# sourceMappingURL=next-config.d.ts.map