@tenphi/tasty 3.6.0 → 3.7.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.
@@ -1,10 +1,11 @@
1
1
  import { n as getConfig } from "./config-B3gPdCqd.js";
2
- import { a as registerSSRCollectorGetterGlobal } from "./format-rules-rCZ37rqY.js";
3
- import { t as ServerStyleCollector } from "./collector-C6TtL8HJ.js";
2
+ import { r as registerSSRCollectorGetterGlobal } from "./ssr-collector-ref-COs_ioWl.js";
3
+ import { t as ServerStyleCollector } from "./collector-B3OsM252.js";
4
4
  import { n as runWithCollector, t as getSSRCollector } from "./async-storage-DKK-wTD4.js";
5
+ import { t as findUnsafeCSSResource } from "./css-resources-Cyl_axbI.js";
5
6
  import { createHash } from "node:crypto";
6
- import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
7
7
  import { join } from "node:path";
8
+ import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
8
9
  import { fileURLToPath } from "node:url";
9
10
  //#region src/ssr/astro-extraction.ts
10
11
  const METADATA_START = "<template data-tasty-extract>";
@@ -50,143 +51,6 @@ async function findHTMLFiles(dir) {
50
51
  }
51
52
  return paths;
52
53
  }
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;
88
- }
89
- return index === start ? null : {
90
- name,
91
- end: index
92
- };
93
- }
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;
136
- }
137
- index = stringEnd - 1;
138
- continue;
139
- }
140
- if (css[index] === ")") {
141
- functionStack.pop();
142
- continue;
143
- }
144
- if (css[index] === "(") {
145
- functionStack.push(null);
146
- continue;
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;
187
- }
188
- return null;
189
- }
190
54
  function crossOriginAssetsPrefix(assetsPrefix, site) {
191
55
  if (!assetsPrefix) return null;
192
56
  const prefix = typeof assetsPrefix === "string" ? assetsPrefix : assetsPrefix.css || assetsPrefix.fallback;
@@ -434,4 +298,4 @@ function tastyIntegration(options) {
434
298
  //#endregion
435
299
  export { tastyMiddleware as n, tastyIntegration as t };
436
300
 
437
- //# sourceMappingURL=astro-CzY4LCpr.js.map
301
+ //# sourceMappingURL=astro-CeYENy2x.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"astro-CeYENy2x.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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,MAAM;EACN,OAAO;GACL,uBAAuB,EACrB,eACA,mBAUI;IACJ,cAAc;KACZ,YACE,YAAY,YACR,UACE,gCACA,uCACF,UACE,wBACA;KACR,OAAO;IACT,CAAC;IAED,IAAI,SACF,aACE,oBACA,0CACF;GAEJ;GACA,sBAAsB,EACpB,aAUI;IACJ,OAAO,OAAO,QAAQ;IACtB,SAAS,OAAO,OAAO,UAAU;IACjC,eAAe,OAAO,OAAO;IAC7B,OAAO,OAAO;GAChB;GACA,oBAAoB,OAAO,EAAE,UAAwB;IACnD,IAAI,YAAY,WAAW;IAC3B,MAAM,gBAAgB;KAAE;KAAK;KAAM;KAAQ;KAAc;IAAK,CAAC;GACjE;EACF;CACF;AACF"}
@@ -1,5 +1,5 @@
1
1
  import { L as renderStyles, Mt as formatFunctionRule, Pt as parseFunctionName, X as fontFaceContentHash, Z as formatFontFaceRule, _t as hashString, a as getGlobalCounterStyles, d as getGlobalStyles, f as getNamePrefix, ft as makeClassName, gt as validateNamePrefix, i as getGlobalConfigTokens, mt as makeKeyframeName, o as getGlobalFontFaces, pt as makeCounterStyleName, q as formatCounterStyleRule, r as getEffectiveProperties, s as getGlobalFunctions } from "./config-B3gPdCqd.js";
2
- import { n as formatPropertyCSS, t as formatRules } from "./format-rules-rCZ37rqY.js";
2
+ import { n as formatPropertyCSS, t as formatRules } from "./format-rules-XRw9u7d4.js";
3
3
  import { t as formatGlobalRules } from "./format-global-rules-DklyaXv-.js";
4
4
  //#region src/ssr/collector.ts
5
5
  /**
@@ -324,4 +324,4 @@ function createServerStyleCollector(namePrefix) {
324
324
  //#endregion
325
325
  export { createServerStyleCollector as n, ServerStyleCollector as t };
326
326
 
327
- //# sourceMappingURL=collector-C6TtL8HJ.js.map
327
+ //# sourceMappingURL=collector-B3OsM252.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"collector-C6TtL8HJ.js","names":[],"sources":["../src/ssr/collector.ts"],"sourcesContent":["/**\n * ServerStyleCollector — server-safe style collector for SSR.\n *\n * Accumulates CSS rules and cache metadata during server rendering.\n * This is the server-side counterpart to StyleInjector: it allocates\n * hash-based class names using the configured `namePrefix` (defaults\n * to `'t'`), formats CSS rules into text, and tracks rendered class\n * names for lightweight client transfer.\n *\n * One instance is created per HTTP request. Concurrent requests\n * each get their own collector (via AsyncLocalStorage or React context).\n */\n\nimport {\n getEffectiveProperties,\n getGlobalStyles,\n getGlobalCounterStyles,\n getGlobalFontFaces,\n getGlobalFunctions,\n getGlobalConfigTokens,\n getNamePrefix,\n} from '../config';\nimport { formatCounterStyleRule } from '../counter-style';\nimport { fontFaceContentHash, formatFontFaceRule } from '../font-face';\nimport { formatFunctionRule, parseFunctionName } from '../functions';\nimport { renderStyles } from '../pipeline';\nimport type { StyleResult } from '../pipeline';\nimport { hashString } from '../utils/hash';\nimport {\n makeClassName,\n makeCounterStyleName,\n makeKeyframeName,\n validateNamePrefix,\n} from '../utils/name-prefix';\nimport { formatPropertyCSS } from './format-property';\nimport { formatGlobalRules } from './format-global-rules';\nimport { formatRules } from './format-rules';\n\nexport type ServerStyleArtifactKind =\n | 'property'\n | 'font-face'\n | 'counter-style'\n | 'function'\n | 'raw'\n | 'global'\n | 'chunk'\n | 'keyframes';\n\nexport interface ServerStyleArtifact {\n /** Stable identifier derived from the artifact kind, logical key, and CSS. */\n id: string;\n kind: ServerStyleArtifactKind;\n css: string;\n /** Zero-based position in the collector's final cascade order. */\n order: number;\n}\n\nfunction artifactId(kind: ServerStyleArtifactKind, key: string, css: string) {\n const content = `${kind}\\0${key}\\0${css}`;\n return `${kind}:${hashString(content)}:${content.length.toString(36)}`;\n}\n\nexport class ServerStyleCollector {\n private chunks = new Map<string, string>();\n private cacheKeyToClassName = new Map<string, string>();\n private flushedKeys = new Set<string>();\n private propertyRules = new Map<string, string>();\n private flushedPropertyKeys = new Set<string>();\n private keyframeRules = new Map<string, string>();\n private flushedKeyframeKeys = new Set<string>();\n private globalStyles = new Map<string, string>();\n private flushedGlobalKeys = new Set<string>();\n private rawCSS = new Map<string, string>();\n private flushedRawKeys = new Set<string>();\n private fontFaceRules = new Map<string, string>();\n private flushedFontFaceKeys = new Set<string>();\n private counterStyleRules = new Map<string, string>();\n private flushedCounterStyleKeys = new Set<string>();\n private functionRules = new Map<string, string>();\n private flushedFunctionKeys = new Set<string>();\n private keyframesCounter = 0;\n private counterStyleCounter = 0;\n private internalsCollected = false;\n private namePrefix: string;\n\n /**\n * @param namePrefix - Optional override for the configured prefix.\n * Defaults to the value from `configure({ namePrefix })` (or `'t'`).\n * Pass an explicit prefix when constructing a collector outside the\n * normal configure() lifecycle (e.g. in tests). Validated eagerly\n * so misconfiguration fails before any CSS is collected.\n */\n constructor(namePrefix?: string) {\n if (namePrefix !== undefined) {\n validateNamePrefix(namePrefix);\n }\n this.namePrefix = namePrefix ?? getNamePrefix();\n }\n\n private generateClassName(cacheKey: string): string {\n return makeClassName(this.namePrefix, hashString(cacheKey));\n }\n\n /**\n * Collect internal @property rules and :root token defaults.\n * Mirrors markStylesGenerated() from the client-side injector.\n * Called automatically on first chunk collection; idempotent.\n *\n * Internals are always emitted here — the RSC path deliberately\n * defers to SSR so that tokens appear exactly once per page in\n * <style data-tasty-ssr> (avoiding duplication of large token sets).\n */\n collectInternals(): void {\n if (this.internalsCollected) return;\n this.internalsCollected = true;\n\n for (const [token, definition] of Object.entries(\n getEffectiveProperties(),\n )) {\n const css = formatPropertyCSS(token, definition);\n if (css) {\n this.collectProperty(`__prop:${token}`, css);\n }\n }\n\n const tokenStyles = getGlobalConfigTokens();\n if (tokenStyles && Object.keys(tokenStyles).length > 0) {\n const tokenRules = renderStyles(tokenStyles, ':root') as StyleResult[];\n if (tokenRules.length > 0) {\n const css = formatGlobalRules(tokenRules);\n if (css) {\n this.collectGlobalStyles('__global:tokens', css);\n }\n }\n }\n\n const globalFF = getGlobalFontFaces();\n if (globalFF) {\n for (const [family, input] of Object.entries(globalFF)) {\n const descriptors = Array.isArray(input) ? input : [input];\n for (const desc of descriptors) {\n const hash = fontFaceContentHash(family, desc);\n const css = formatFontFaceRule(family, desc);\n this.collectFontFace(hash, css);\n }\n }\n }\n\n const globalCS = getGlobalCounterStyles();\n if (globalCS) {\n for (const [name, descriptors] of Object.entries(globalCS)) {\n const css = formatCounterStyleRule(name, descriptors);\n this.collectCounterStyle(name, css, { weak: true });\n }\n }\n\n const globalFn = getGlobalFunctions();\n if (globalFn) {\n for (const [name, definition] of Object.entries(globalFn)) {\n const css = formatFunctionRule(name, definition);\n this.collectFunction(parseFunctionName(name), css, { weak: true });\n }\n }\n\n const globalStyles = getGlobalStyles();\n if (globalStyles) {\n for (const [selector, styles] of Object.entries(globalStyles)) {\n if (Object.keys(styles).length > 0) {\n const rules = renderStyles(styles, selector) as StyleResult[];\n if (rules.length > 0) {\n const css = formatGlobalRules(rules);\n if (css) {\n this.collectGlobalStyles(`__global:styles:${selector}`, css);\n }\n }\n }\n }\n }\n }\n\n /**\n * Allocate a className for a cache key, server-side.\n * Mirrors StyleInjector.allocateClassName but without DOM access.\n */\n allocateClassName(cacheKey: string): {\n className: string;\n isNewAllocation: boolean;\n } {\n const existing = this.cacheKeyToClassName.get(cacheKey);\n if (existing) {\n return { className: existing, isNewAllocation: false };\n }\n\n const className = this.generateClassName(cacheKey);\n this.cacheKeyToClassName.set(cacheKey, className);\n\n return { className, isNewAllocation: true };\n }\n\n /**\n * Record CSS rules for a chunk.\n * Called by useStyles during server render.\n */\n collectChunk(\n cacheKey: string,\n className: string,\n rules: StyleResult[],\n ): void {\n if (this.chunks.has(cacheKey)) return;\n const css = formatRules(rules, className);\n if (css) {\n this.chunks.set(cacheKey, css);\n }\n }\n\n /**\n * Record a @property rule. Deduplicated by name.\n */\n collectProperty(name: string, css: string): void {\n if (!this.propertyRules.has(name)) {\n this.propertyRules.set(name, css);\n }\n }\n\n /**\n * Record a @keyframes rule. Deduplicated by name.\n */\n collectKeyframes(name: string, css: string): void {\n if (!this.keyframeRules.has(name)) {\n this.keyframeRules.set(name, css);\n }\n }\n\n /**\n * Allocate a keyframe name for SSR. Uses provided name or generates one.\n */\n allocateKeyframeName(providedName?: string): string {\n return (\n providedName ??\n makeKeyframeName(this.namePrefix, String(this.keyframesCounter++))\n );\n }\n\n /**\n * Record a @font-face rule. Deduplicated by key (content hash).\n */\n collectFontFace(key: string, css: string): void {\n if (!this.fontFaceRules.has(key)) {\n this.fontFaceRules.set(key, css);\n }\n }\n\n /**\n * Record a @counter-style rule. Deduplicated by name and overrides an\n * existing rule by default. Pass `weak: true` for global `configure()`\n * definitions, which never clobber an existing rule.\n */\n collectCounterStyle(\n name: string,\n css: string,\n options?: { weak?: boolean },\n ): void {\n const existing = this.counterStyleRules.get(name);\n if (existing === undefined) {\n this.counterStyleRules.set(name, css);\n return;\n }\n if (options?.weak || existing === css) return;\n this.counterStyleRules.set(name, css);\n // If a rule with this name was already flushed (streaming), allow the\n // overriding rule to be flushed again so it wins by source order.\n this.flushedCounterStyleKeys.delete(name);\n }\n\n /**\n * Record a @function rule. Deduplicated by CSS function name and overrides an\n * existing rule by default. Pass `weak: true` for global `configure()`\n * definitions, which never clobber an existing rule.\n */\n collectFunction(\n name: string,\n css: string,\n options?: { weak?: boolean },\n ): void {\n const existing = this.functionRules.get(name);\n if (existing === undefined) {\n this.functionRules.set(name, css);\n return;\n }\n if (options?.weak || existing === css) return;\n this.functionRules.set(name, css);\n // If a rule with this name was already flushed (streaming), allow the\n // overriding rule to be flushed again so it wins by source order.\n this.flushedFunctionKeys.delete(name);\n }\n\n /**\n * Allocate a counter-style name for SSR. Uses provided name or generates one.\n */\n allocateCounterStyleName(providedName?: string): string {\n return (\n providedName ??\n makeCounterStyleName(this.namePrefix, String(this.counterStyleCounter++))\n );\n }\n\n /**\n * Record global styles (from useGlobalStyles). Deduplicated by key.\n *\n * Pass `replace` for slot-keyed entries (an explicit `id`), where the last\n * write must win to match the client's update-tracking behavior.\n */\n collectGlobalStyles(key: string, css: string, replace?: boolean): void {\n if (replace || !this.globalStyles.has(key)) {\n this.globalStyles.set(key, css);\n }\n }\n\n /**\n * Record raw CSS text (from useRawCSS). Deduplicated by key.\n *\n * Pass `replace` for slot-keyed entries (an explicit `id`), where the last\n * write must win to match the client's update-tracking behavior.\n */\n collectRawCSS(key: string, css: string, replace?: boolean): void {\n if (replace || !this.rawCSS.has(key)) {\n this.rawCSS.set(key, css);\n }\n }\n\n /**\n * Return the collected CSS as structured, ordered artifacts.\n *\n * Artifact boundaries are part of the collector output so build tools never\n * need to split or parse CSS text. IDs include the logical collection key\n * and content, making them stable across equivalent page renders while a CSS\n * change always produces a different ID.\n */\n getArtifacts(): ServerStyleArtifact[] {\n const artifacts: ServerStyleArtifact[] = [];\n\n const append = (\n kind: ServerStyleArtifactKind,\n entries: Iterable<[string, string]>,\n ) => {\n for (const [key, css] of entries) {\n artifacts.push({\n id: artifactId(kind, key, css),\n kind,\n css,\n order: artifacts.length,\n });\n }\n };\n\n append('property', this.propertyRules);\n append('font-face', this.fontFaceRules);\n append('counter-style', this.counterStyleRules);\n append('function', this.functionRules);\n append('raw', this.rawCSS);\n append('global', this.globalStyles);\n append('chunk', this.chunks);\n append('keyframes', this.keyframeRules);\n\n return artifacts;\n }\n\n /**\n * Extract all CSS collected so far as a single string.\n * Includes @property and @keyframes rules.\n * Used for non-streaming SSR (renderToString).\n */\n getCSS(): string {\n return this.getArtifacts()\n .map(({ css }) => css)\n .join('\\n');\n }\n\n /**\n * Flush only newly collected CSS since the last flush.\n * Used for streaming SSR (renderToPipeableStream + useServerInsertedHTML).\n */\n flushCSS(): string {\n const parts: string[] = [];\n\n for (const [name, css] of this.propertyRules) {\n if (!this.flushedPropertyKeys.has(name)) {\n parts.push(css);\n this.flushedPropertyKeys.add(name);\n }\n }\n\n for (const [key, css] of this.fontFaceRules) {\n if (!this.flushedFontFaceKeys.has(key)) {\n parts.push(css);\n this.flushedFontFaceKeys.add(key);\n }\n }\n\n for (const [key, css] of this.counterStyleRules) {\n if (!this.flushedCounterStyleKeys.has(key)) {\n parts.push(css);\n this.flushedCounterStyleKeys.add(key);\n }\n }\n\n for (const [key, css] of this.functionRules) {\n if (!this.flushedFunctionKeys.has(key)) {\n parts.push(css);\n this.flushedFunctionKeys.add(key);\n }\n }\n\n for (const [key, css] of this.rawCSS) {\n if (!this.flushedRawKeys.has(key)) {\n parts.push(css);\n this.flushedRawKeys.add(key);\n }\n }\n\n for (const [key, css] of this.globalStyles) {\n if (!this.flushedGlobalKeys.has(key)) {\n parts.push(css);\n this.flushedGlobalKeys.add(key);\n }\n }\n\n for (const [key, css] of this.chunks) {\n if (!this.flushedKeys.has(key)) {\n parts.push(css);\n this.flushedKeys.add(key);\n }\n }\n\n for (const [name, css] of this.keyframeRules) {\n if (!this.flushedKeyframeKeys.has(name)) {\n parts.push(css);\n this.flushedKeyframeKeys.add(name);\n }\n }\n\n return parts.join('\\n');\n }\n\n private flushedClassNames = new Set<string>();\n\n /**\n * Return class names rendered since the last call (for streaming).\n * Used to emit lightweight class-list scripts for client hydration.\n */\n getRenderedClassNames(): string[] {\n const names: string[] = [];\n for (const className of this.cacheKeyToClassName.values()) {\n if (!this.flushedClassNames.has(className)) {\n this.flushedClassNames.add(className);\n names.push(className);\n }\n }\n return names;\n }\n}\n\n/**\n * Factory for creating a {@link ServerStyleCollector} instance.\n *\n * Canonical functional entry point; the `ServerStyleCollector` class remains\n * exported for advanced/internal use.\n *\n * @param namePrefix - Optional override for the configured class-name prefix.\n * Defaults to the value from `configure({ namePrefix })` (or `'t'`).\n *\n * @example\n * ```ts\n * import { createServerStyleCollector } from '@tenphi/tasty/ssr';\n *\n * const collector = createServerStyleCollector();\n * ```\n */\nexport function createServerStyleCollector(\n namePrefix?: string,\n): ServerStyleCollector {\n return new ServerStyleCollector(namePrefix);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAyDA,SAAS,WAAW,MAA+B,KAAa,KAAa;CAC3E,MAAM,UAAU,GAAG,KAAK,IAAI,IAAI,IAAI;CACpC,OAAO,GAAG,KAAK,GAAG,WAAW,OAAO,EAAE,GAAG,Q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AK,kBAAkB,IAAI,SAAS;GACpC,MAAM,KAAK,SAAS;EACtB;EAEF,OAAO;CACT;AACF;;;;;;;;;;;;;;;;;AAkBA,SAAgB,2BACd,YACsB;CACtB,OAAO,IAAI,qBAAqB,UAAU;AAC5C"}
1
+ {"version":3,"file":"collector-B3OsM252.js","names":[],"sources":["../src/ssr/collector.ts"],"sourcesContent":["/**\n * ServerStyleCollector — server-safe style collector for SSR.\n *\n * Accumulates CSS rules and cache metadata during server rendering.\n * This is the server-side counterpart to StyleInjector: it allocates\n * hash-based class names using the configured `namePrefix` (defaults\n * to `'t'`), formats CSS rules into text, and tracks rendered class\n * names for lightweight client transfer.\n *\n * One instance is created per HTTP request. Concurrent requests\n * each get their own collector (via AsyncLocalStorage or React context).\n */\n\nimport {\n getEffectiveProperties,\n getGlobalStyles,\n getGlobalCounterStyles,\n getGlobalFontFaces,\n getGlobalFunctions,\n getGlobalConfigTokens,\n getNamePrefix,\n} from '../config';\nimport { formatCounterStyleRule } from '../counter-style';\nimport { fontFaceContentHash, formatFontFaceRule } from '../font-face';\nimport { formatFunctionRule, parseFunctionName } from '../functions';\nimport { renderStyles } from '../pipeline';\nimport type { StyleResult } from '../pipeline';\nimport { hashString } from '../utils/hash';\nimport {\n makeClassName,\n makeCounterStyleName,\n makeKeyframeName,\n validateNamePrefix,\n} from '../utils/name-prefix';\nimport { formatPropertyCSS } from './format-property';\nimport { formatGlobalRules } from './format-global-rules';\nimport { formatRules } from './format-rules';\n\nexport type ServerStyleArtifactKind =\n | 'property'\n | 'font-face'\n | 'counter-style'\n | 'function'\n | 'raw'\n | 'global'\n | 'chunk'\n | 'keyframes';\n\nexport interface ServerStyleArtifact {\n /** Stable identifier derived from the artifact kind, logical key, and CSS. */\n id: string;\n kind: ServerStyleArtifactKind;\n css: string;\n /** Zero-based position in the collector's final cascade order. */\n order: number;\n}\n\nfunction artifactId(kind: ServerStyleArtifactKind, key: string, css: string) {\n const content = `${kind}\\0${key}\\0${css}`;\n return `${kind}:${hashString(content)}:${content.length.toString(36)}`;\n}\n\nexport class ServerStyleCollector {\n private chunks = new Map<string, string>();\n private cacheKeyToClassName = new Map<string, string>();\n private flushedKeys = new Set<string>();\n private propertyRules = new Map<string, string>();\n private flushedPropertyKeys = new Set<string>();\n private keyframeRules = new Map<string, string>();\n private flushedKeyframeKeys = new Set<string>();\n private globalStyles = new Map<string, string>();\n private flushedGlobalKeys = new Set<string>();\n private rawCSS = new Map<string, string>();\n private flushedRawKeys = new Set<string>();\n private fontFaceRules = new Map<string, string>();\n private flushedFontFaceKeys = new Set<string>();\n private counterStyleRules = new Map<string, string>();\n private flushedCounterStyleKeys = new Set<string>();\n private functionRules = new Map<string, string>();\n private flushedFunctionKeys = new Set<string>();\n private keyframesCounter = 0;\n private counterStyleCounter = 0;\n private internalsCollected = false;\n private namePrefix: string;\n\n /**\n * @param namePrefix - Optional override for the configured prefix.\n * Defaults to the value from `configure({ namePrefix })` (or `'t'`).\n * Pass an explicit prefix when constructing a collector outside the\n * normal configure() lifecycle (e.g. in tests). Validated eagerly\n * so misconfiguration fails before any CSS is collected.\n */\n constructor(namePrefix?: string) {\n if (namePrefix !== undefined) {\n validateNamePrefix(namePrefix);\n }\n this.namePrefix = namePrefix ?? getNamePrefix();\n }\n\n private generateClassName(cacheKey: string): string {\n return makeClassName(this.namePrefix, hashString(cacheKey));\n }\n\n /**\n * Collect internal @property rules and :root token defaults.\n * Mirrors markStylesGenerated() from the client-side injector.\n * Called automatically on first chunk collection; idempotent.\n *\n * Internals are always emitted here — the RSC path deliberately\n * defers to SSR so that tokens appear exactly once per page in\n * <style data-tasty-ssr> (avoiding duplication of large token sets).\n */\n collectInternals(): void {\n if (this.internalsCollected) return;\n this.internalsCollected = true;\n\n for (const [token, definition] of Object.entries(\n getEffectiveProperties(),\n )) {\n const css = formatPropertyCSS(token, definition);\n if (css) {\n this.collectProperty(`__prop:${token}`, css);\n }\n }\n\n const tokenStyles = getGlobalConfigTokens();\n if (tokenStyles && Object.keys(tokenStyles).length > 0) {\n const tokenRules = renderStyles(tokenStyles, ':root') as StyleResult[];\n if (tokenRules.length > 0) {\n const css = formatGlobalRules(tokenRules);\n if (css) {\n this.collectGlobalStyles('__global:tokens', css);\n }\n }\n }\n\n const globalFF = getGlobalFontFaces();\n if (globalFF) {\n for (const [family, input] of Object.entries(globalFF)) {\n const descriptors = Array.isArray(input) ? input : [input];\n for (const desc of descriptors) {\n const hash = fontFaceContentHash(family, desc);\n const css = formatFontFaceRule(family, desc);\n this.collectFontFace(hash, css);\n }\n }\n }\n\n const globalCS = getGlobalCounterStyles();\n if (globalCS) {\n for (const [name, descriptors] of Object.entries(globalCS)) {\n const css = formatCounterStyleRule(name, descriptors);\n this.collectCounterStyle(name, css, { weak: true });\n }\n }\n\n const globalFn = getGlobalFunctions();\n if (globalFn) {\n for (const [name, definition] of Object.entries(globalFn)) {\n const css = formatFunctionRule(name, definition);\n this.collectFunction(parseFunctionName(name), css, { weak: true });\n }\n }\n\n const globalStyles = getGlobalStyles();\n if (globalStyles) {\n for (const [selector, styles] of Object.entries(globalStyles)) {\n if (Object.keys(styles).length > 0) {\n const rules = renderStyles(styles, selector) as StyleResult[];\n if (rules.length > 0) {\n const css = formatGlobalRules(rules);\n if (css) {\n this.collectGlobalStyles(`__global:styles:${selector}`, css);\n }\n }\n }\n }\n }\n }\n\n /**\n * Allocate a className for a cache key, server-side.\n * Mirrors StyleInjector.allocateClassName but without DOM access.\n */\n allocateClassName(cacheKey: string): {\n className: string;\n isNewAllocation: boolean;\n } {\n const existing = this.cacheKeyToClassName.get(cacheKey);\n if (existing) {\n return { className: existing, isNewAllocation: false };\n }\n\n const className = this.generateClassName(cacheKey);\n this.cacheKeyToClassName.set(cacheKey, className);\n\n return { className, isNewAllocation: true };\n }\n\n /**\n * Record CSS rules for a chunk.\n * Called by useStyles during server render.\n */\n collectChunk(\n cacheKey: string,\n className: string,\n rules: StyleResult[],\n ): void {\n if (this.chunks.has(cacheKey)) return;\n const css = formatRules(rules, className);\n if (css) {\n this.chunks.set(cacheKey, css);\n }\n }\n\n /**\n * Record a @property rule. Deduplicated by name.\n */\n collectProperty(name: string, css: string): void {\n if (!this.propertyRules.has(name)) {\n this.propertyRules.set(name, css);\n }\n }\n\n /**\n * Record a @keyframes rule. Deduplicated by name.\n */\n collectKeyframes(name: string, css: string): void {\n if (!this.keyframeRules.has(name)) {\n this.keyframeRules.set(name, css);\n }\n }\n\n /**\n * Allocate a keyframe name for SSR. Uses provided name or generates one.\n */\n allocateKeyframeName(providedName?: string): string {\n return (\n providedName ??\n makeKeyframeName(this.namePrefix, String(this.keyframesCounter++))\n );\n }\n\n /**\n * Record a @font-face rule. Deduplicated by key (content hash).\n */\n collectFontFace(key: string, css: string): void {\n if (!this.fontFaceRules.has(key)) {\n this.fontFaceRules.set(key, css);\n }\n }\n\n /**\n * Record a @counter-style rule. Deduplicated by name and overrides an\n * existing rule by default. Pass `weak: true` for global `configure()`\n * definitions, which never clobber an existing rule.\n */\n collectCounterStyle(\n name: string,\n css: string,\n options?: { weak?: boolean },\n ): void {\n const existing = this.counterStyleRules.get(name);\n if (existing === undefined) {\n this.counterStyleRules.set(name, css);\n return;\n }\n if (options?.weak || existing === css) return;\n this.counterStyleRules.set(name, css);\n // If a rule with this name was already flushed (streaming), allow the\n // overriding rule to be flushed again so it wins by source order.\n this.flushedCounterStyleKeys.delete(name);\n }\n\n /**\n * Record a @function rule. Deduplicated by CSS function name and overrides an\n * existing rule by default. Pass `weak: true` for global `configure()`\n * definitions, which never clobber an existing rule.\n */\n collectFunction(\n name: string,\n css: string,\n options?: { weak?: boolean },\n ): void {\n const existing = this.functionRules.get(name);\n if (existing === undefined) {\n this.functionRules.set(name, css);\n return;\n }\n if (options?.weak || existing === css) return;\n this.functionRules.set(name, css);\n // If a rule with this name was already flushed (streaming), allow the\n // overriding rule to be flushed again so it wins by source order.\n this.flushedFunctionKeys.delete(name);\n }\n\n /**\n * Allocate a counter-style name for SSR. Uses provided name or generates one.\n */\n allocateCounterStyleName(providedName?: string): string {\n return (\n providedName ??\n makeCounterStyleName(this.namePrefix, String(this.counterStyleCounter++))\n );\n }\n\n /**\n * Record global styles (from useGlobalStyles). Deduplicated by key.\n *\n * Pass `replace` for slot-keyed entries (an explicit `id`), where the last\n * write must win to match the client's update-tracking behavior.\n */\n collectGlobalStyles(key: string, css: string, replace?: boolean): void {\n if (replace || !this.globalStyles.has(key)) {\n this.globalStyles.set(key, css);\n }\n }\n\n /**\n * Record raw CSS text (from useRawCSS). Deduplicated by key.\n *\n * Pass `replace` for slot-keyed entries (an explicit `id`), where the last\n * write must win to match the client's update-tracking behavior.\n */\n collectRawCSS(key: string, css: string, replace?: boolean): void {\n if (replace || !this.rawCSS.has(key)) {\n this.rawCSS.set(key, css);\n }\n }\n\n /**\n * Return the collected CSS as structured, ordered artifacts.\n *\n * Artifact boundaries are part of the collector output so build tools never\n * need to split or parse CSS text. IDs include the logical collection key\n * and content, making them stable across equivalent page renders while a CSS\n * change always produces a different ID.\n */\n getArtifacts(): ServerStyleArtifact[] {\n const artifacts: ServerStyleArtifact[] = [];\n\n const append = (\n kind: ServerStyleArtifactKind,\n entries: Iterable<[string, string]>,\n ) => {\n for (const [key, css] of entries) {\n artifacts.push({\n id: artifactId(kind, key, css),\n kind,\n css,\n order: artifacts.length,\n });\n }\n };\n\n append('property', this.propertyRules);\n append('font-face', this.fontFaceRules);\n append('counter-style', this.counterStyleRules);\n append('function', this.functionRules);\n append('raw', this.rawCSS);\n append('global', this.globalStyles);\n append('chunk', this.chunks);\n append('keyframes', this.keyframeRules);\n\n return artifacts;\n }\n\n /**\n * Extract all CSS collected so far as a single string.\n * Includes @property and @keyframes rules.\n * Used for non-streaming SSR (renderToString).\n */\n getCSS(): string {\n return this.getArtifacts()\n .map(({ css }) => css)\n .join('\\n');\n }\n\n /**\n * Flush only newly collected CSS since the last flush.\n * Used for streaming SSR (renderToPipeableStream + useServerInsertedHTML).\n */\n flushCSS(): string {\n const parts: string[] = [];\n\n for (const [name, css] of this.propertyRules) {\n if (!this.flushedPropertyKeys.has(name)) {\n parts.push(css);\n this.flushedPropertyKeys.add(name);\n }\n }\n\n for (const [key, css] of this.fontFaceRules) {\n if (!this.flushedFontFaceKeys.has(key)) {\n parts.push(css);\n this.flushedFontFaceKeys.add(key);\n }\n }\n\n for (const [key, css] of this.counterStyleRules) {\n if (!this.flushedCounterStyleKeys.has(key)) {\n parts.push(css);\n this.flushedCounterStyleKeys.add(key);\n }\n }\n\n for (const [key, css] of this.functionRules) {\n if (!this.flushedFunctionKeys.has(key)) {\n parts.push(css);\n this.flushedFunctionKeys.add(key);\n }\n }\n\n for (const [key, css] of this.rawCSS) {\n if (!this.flushedRawKeys.has(key)) {\n parts.push(css);\n this.flushedRawKeys.add(key);\n }\n }\n\n for (const [key, css] of this.globalStyles) {\n if (!this.flushedGlobalKeys.has(key)) {\n parts.push(css);\n this.flushedGlobalKeys.add(key);\n }\n }\n\n for (const [key, css] of this.chunks) {\n if (!this.flushedKeys.has(key)) {\n parts.push(css);\n this.flushedKeys.add(key);\n }\n }\n\n for (const [name, css] of this.keyframeRules) {\n if (!this.flushedKeyframeKeys.has(name)) {\n parts.push(css);\n this.flushedKeyframeKeys.add(name);\n }\n }\n\n return parts.join('\\n');\n }\n\n private flushedClassNames = new Set<string>();\n\n /**\n * Return class names rendered since the last call (for streaming).\n * Used to emit lightweight class-list scripts for client hydration.\n */\n getRenderedClassNames(): string[] {\n const names: string[] = [];\n for (const className of this.cacheKeyToClassName.values()) {\n if (!this.flushedClassNames.has(className)) {\n this.flushedClassNames.add(className);\n names.push(className);\n }\n }\n return names;\n }\n}\n\n/**\n * Factory for creating a {@link ServerStyleCollector} instance.\n *\n * Canonical functional entry point; the `ServerStyleCollector` class remains\n * exported for advanced/internal use.\n *\n * @param namePrefix - Optional override for the configured class-name prefix.\n * Defaults to the value from `configure({ namePrefix })` (or `'t'`).\n *\n * @example\n * ```ts\n * import { createServerStyleCollector } from '@tenphi/tasty/ssr';\n *\n * const collector = createServerStyleCollector();\n * ```\n */\nexport function createServerStyleCollector(\n namePrefix?: string,\n): ServerStyleCollector {\n return new ServerStyleCollector(namePrefix);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAyDA,SAAS,WAAW,MAA+B,KAAa,KAAa;CAC3E,MAAM,UAAU,GAAG,KAAK,IAAI,IAAI,IAAI;CACpC,OAAO,GAAG,KAAK,GAAG,WAAW,OAAO,EAAE,GAAG,QAAQ,OAAO,SAAS,EAAE;AACrE;AAEA,IAAa,uBAAb,MAAkC;CAChC,yBAAiB,IAAI,IAAoB;CACzC,sCAA8B,IAAI,IAAoB;CACtD,8BAAsB,IAAI,IAAY;CACtC,gCAAwB,IAAI,IAAoB;CAChD,sCAA8B,IAAI,IAAY;CAC9C,gCAAwB,IAAI,IAAoB;CAChD,sCAA8B,IAAI,IAAY;CAC9C,+BAAuB,IAAI,IAAoB;CAC/C,oCAA4B,IAAI,IAAY;CAC5C,yBAAiB,IAAI,IAAoB;CACzC,iCAAyB,IAAI,IAAY;CACzC,gCAAwB,IAAI,IAAoB;CAChD,sCAA8B,IAAI,IAAY;CAC9C,oCAA4B,IAAI,IAAoB;CACpD,0CAAkC,IAAI,IAAY;CAClD,gCAAwB,IAAI,IAAoB;CAChD,sCAA8B,IAAI,IAAY;CAC9C,mBAA2B;CAC3B,sBAA8B;CAC9B,qBAA6B;CAC7B;;;;;;;;CASA,YAAY,YAAqB;EAC/B,IAAI,eAAe,KAAA,GACjB,mBAAmB,UAAU;EAE/B,KAAK,aAAa,cAAc,cAAc;CAChD;CAEA,kBAA0B,UAA0B;EAClD,OAAO,cAAc,KAAK,YAAY,WAAW,QAAQ,CAAC;CAC5D;;;;;;;;;;CAWA,mBAAyB;EACvB,IAAI,KAAK,oBAAoB;EAC7B,KAAK,qBAAqB;EAE1B,KAAK,MAAM,CAAC,OAAO,eAAe,OAAO,QACvC,uBAAuB,CACzB,GAAG;GACD,MAAM,MAAM,kBAAkB,OAAO,UAAU;GAC/C,IAAI,KAC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C,MAAM,KAAK,GAAG;GACd,KAAK,oBAAoB,IAAI,IAAI;EACnC;EAGF,OAAO,MAAM,KAAK,IAAI;CACxB;CAEA,oCAA4B,IAAI,IAAY;;;;;CAM5C,wBAAkC;EAChC,MAAM,QAAkB,CAAC;EACzB,KAAK,MAAM,aAAa,KAAK,oBAAoB,OAAO,GACtD,IAAI,CAAC,KAAK,kBAAkB,IAAI,SAAS,GAAG;GAC1C,KAAK,kBAAkB,IAAI,SAAS;GACpC,MAAM,KAAK,SAAS;EACtB;EAEF,OAAO;CACT;AACF;;;;;;;;;;;;;;;;;AAkBA,SAAgB,2BACd,YACsB;CACtB,OAAO,IAAI,qBAAqB,UAAU;AAC5C"}
@@ -1,5 +1,5 @@
1
1
  import { $ as SheetManager, $t as StyleParser, A as FLOW_STYLES, At as STYLE_TO_CHUNK, B as createStateParserContext, C as BASE_STYLES, Ct as APPEARANCE_CHUNK_STYLES, D as COLOR_STYLES, Dt as FONT_CHUNK_STYLES, E as BLOCK_STYLES, Et as DISPLAY_CHUNK_STYLES, G as StyleInjector, Gt as parseStyle, Ht as getGlobalPredefinedTokens, I as isSelector, Jt as okhstPlugin, Kt as stringifyStyles, L as renderStyles, Lt as CUSTOM_UNITS, M as OUTER_STYLES, N as POSITION_STYLES, O as CONTAINER_STYLES, Ot as LAYOUT_CHUNK_STYLES, P as TEXT_STYLES, R as parseStateKey, Rt as DIRECTIONS, T as BLOCK_OUTER_STYLES, Tt as DIMENSION_CHUNK_STYLES, U as getGlobalPredefinedStates, Ut as normalizeColorTokenValue, Vt as getGlobalParser, W as setGlobalPredefinedStates, Wt as parseColor, Xt as okhslPlugin, Yt as okhslFunction, Zt as createColorFunc, a as getGlobalCounterStyles, an as hslToRgbValues, b as resetConfig, dt as DEFAULT_ZERO_NAME_PREFIX, f as getNamePrefix, g as isConfigLocked, h as hasStylesGenerated, in as hexToRgb, j as INNER_STYLES, k as DIMENSION_STYLES, kt as POSITION_CHUNK_STYLES, l as getGlobalKeyframes, lt as resetStyleBatch, m as hasGlobalRecipes, n as getConfig, nn as getNamedColorHex, nt as styleHandlers, o as getGlobalFontFaces, on as strToRgb, ot as flushStyles, p as hasGlobalKeyframes, qt as okhstFunction, rn as getRgbValuesFromRgbaString, s as getGlobalFunctions, st as hasPendingStyleWrites, t as configure, tt as defineHandler, u as getGlobalRecipes, ut as DEFAULT_NAME_PREFIX, v as isTestEnvironment, w as BLOCK_INNER_STYLES, wt as CHUNK_NAMES, x as generateTypographyTokens, zt as filterMods } from "../config-B3gPdCqd.js";
2
- import { A as keyframes, C as getRawCSSText, D as injectRawCSS, E as injectGlobal, F as chunkSheetRegistry, I as resolveFunctionColor, M as property, N as touch, O as injector, P as ChunkSheetRegistry, S as getCSSTextForNode, T as inject, _ as destroy, a as color, b as gc, g as createInjector, h as counterStyle, i as _modAttrs, j as ownKeyframes, k as isPropertyDefined, m as cleanup, n as processTokens, o as filterBaseProps, r as dotize, s as computeStyles, t as tastyDebug, v as fontFace, w as holdKeyframes, x as getCSSText, y as func } from "../core-Bq7w2kti.js";
2
+ import { A as keyframes, C as getRawCSSText, D as injectRawCSS, E as injectGlobal, F as chunkSheetRegistry, I as resolveFunctionColor, M as property, N as touch, O as injector, P as ChunkSheetRegistry, S as getCSSTextForNode, T as inject, _ as destroy, a as color, b as gc, g as createInjector, h as counterStyle, i as _modAttrs, j as ownKeyframes, k as isPropertyDefined, m as cleanup, n as processTokens, o as filterBaseProps, r as dotize, s as computeStyles, t as tastyDebug, v as fontFace, w as holdKeyframes, x as getCSSText, y as func } from "../core-DGm0CFHP.js";
3
3
  import { d as categorizeStyleKeys } from "../keyframes-DE-OE76F.js";
4
4
  import { t as mergeStyles } from "../merge-styles-DuoZEsm9.js";
5
5
  import { t as resolveRecipes } from "../resolve-recipes-H9NqOQuP.js";
@@ -1,6 +1,7 @@
1
1
  import { Bt as getGlobalParseFunctions, G as StyleInjector, Gt as parseStyle, It as registerLocalFunctionPolyfills, J as hasLocalCounterStyle, K as extractLocalCounterStyle, Mt as formatFunctionRule, Nt as hasLocalFunctions, Pt as parseFunctionName, Q as hasLocalFontFace, Qt as isDevEnv, Ut as normalizeColorTokenValue, Vt as getGlobalParser, X as fontFaceContentHash, Y as extractLocalFontFace, Z as formatFontFaceRule, _ as isFunctionsPolyfillEnabled, _t as hashString, bt as hasLocalProperties, c as getGlobalInjector, en as Lru, et as STYLE_HANDLER_MAP, f as getNamePrefix, ft as makeClassName, ht as tastyClassRegex, it as PropertyTypeResolver, jt as extractLocalFunctions, l as getGlobalKeyframes, n as getConfig, ot as flushStyles, p as hasGlobalKeyframes, q as formatCounterStyleRule, rt as createStyle, sn as normalizeDslName, tn as overrideColorAlpha, v as isTestEnvironment, vt as extractLocalProperties, wt as CHUNK_NAMES, xt as parsePropertyToken, y as markStylesGenerated, z as camelToKebab } from "./config-B3gPdCqd.js";
2
2
  import { a as mergeKeyframes, c as resolveKeyframesNames, d as categorizeStyleKeys, i as hasLocalKeyframes, l as renderStylesForChunk, n as extractLocalKeyframes, o as referencesAnimation, r as filterUsedKeyframes, s as replaceAnimationNames, t as extractAnimationNamesFromStyles, u as generateChunkCacheKey } from "./keyframes-DE-OE76F.js";
3
- import { n as formatPropertyCSS, r as getRegisteredSSRCollector, t as formatRules } from "./format-rules-rCZ37rqY.js";
3
+ import { t as getRegisteredSSRCollector } from "./ssr-collector-ref-COs_ioWl.js";
4
+ import { n as formatPropertyCSS, t as formatRules } from "./format-rules-XRw9u7d4.js";
4
5
  import { t as resolveRecipes } from "./resolve-recipes-H9NqOQuP.js";
5
6
  import { cache } from "react";
6
7
  //#region src/utils/function-color.ts
@@ -1159,6 +1160,25 @@ function sortTastyClasses(classes) {
1159
1160
  return Array.from(classes).sort((a, b) => a.localeCompare(b));
1160
1161
  }
1161
1162
  /**
1163
+ * The root these helpers read, or `null` where there is no DOM.
1164
+ *
1165
+ * `document` used to be a default parameter value, and a default is evaluated
1166
+ * at the call site — so every read below threw a bare `ReferenceError` under
1167
+ * Node, taking out five of the eight public methods. A debug utility must not
1168
+ * be able to fail an SSR render because a call was left in, so the DOM-less
1169
+ * case reports an empty result and says why.
1170
+ */
1171
+ function defaultRoot() {
1172
+ return typeof document === "undefined" ? null : document;
1173
+ }
1174
+ let warnedNoDom = false;
1175
+ /** Say once why the numbers are empty. Silent under `{ raw: true }`. */
1176
+ function warnNoDom(raw) {
1177
+ if (raw || warnedNoDom) return;
1178
+ warnedNoDom = true;
1179
+ console.warn("[Tasty] tastyDebug reads the DOM and this environment has none, so the result is empty. During SSR, read the ServerStyleCollector instead.");
1180
+ }
1181
+ /**
1162
1182
  * The registry for `root`, with every queued write landed first.
1163
1183
  *
1164
1184
  * Every injector read API is a flush point, and the reads below reach past
@@ -1167,11 +1187,13 @@ function sortTastyClasses(classes) {
1167
1187
  * enqueued but not yet in a sheet is missing from `globalRules`, from the
1168
1188
  * sheets, and from anything counting either.
1169
1189
  */
1170
- function getRegistry(root = document) {
1190
+ function getRegistry(root = defaultRoot()) {
1191
+ if (!root) return void 0;
1171
1192
  flushStyles();
1172
1193
  return injector.instance._sheetManager?.getRegistry(root);
1173
1194
  }
1174
- function findDomTastyClasses(root = document) {
1195
+ function findDomTastyClasses(root = defaultRoot()) {
1196
+ if (!root) return [];
1175
1197
  const classes = /* @__PURE__ */ new Set();
1176
1198
  const elements = root.querySelectorAll?.("[class]") || [];
1177
1199
  const classRegex = tastyClassRegex(getNamePrefix());
@@ -1188,13 +1210,25 @@ function findDomTastyClasses(root = document) {
1188
1210
  * with the sources kept byte-for-byte — trimming would report a total smaller
1189
1211
  * than one of its own parts whenever raw CSS has edge whitespace.
1190
1212
  */
1191
- function getAllCSS(root = document) {
1213
+ function getAllCSS(root = defaultRoot()) {
1192
1214
  const registry = getRegistry(root);
1193
1215
  const sheetManager = injector.instance._sheetManager;
1194
- if (!registry || !sheetManager) return "";
1216
+ if (!root || !registry || !sheetManager) return "";
1195
1217
  return sheetManager.getOwnedCSSInOrder(registry, root).join("\n");
1196
1218
  }
1197
1219
  /**
1220
+ * The injector's own readers fall back to `document` when `root` is omitted, so
1221
+ * they have to be reached with a real root or not at all.
1222
+ */
1223
+ function cssTextForClasses(classNames, root) {
1224
+ if (!root) return "";
1225
+ return injector.instance.getCSSTextForClasses(classNames, { root });
1226
+ }
1227
+ function getInjectorMetrics(root) {
1228
+ if (!root) return null;
1229
+ return injector.instance.getMetrics({ root });
1230
+ }
1231
+ /**
1198
1232
  * Injected classes that no element carries and nobody pinned — the exact set
1199
1233
  * `gc({ force: true })` would delete.
1200
1234
  *
@@ -1202,11 +1236,12 @@ function getAllCSS(root = document) {
1202
1236
  * drifted apart once before, when this file still read "unused" off the pin
1203
1237
  * counts the render path had stopped maintaining.
1204
1238
  */
1205
- function getUnusedClasses(root = document) {
1239
+ function getUnusedClasses(root = defaultRoot()) {
1240
+ if (!root) return [];
1206
1241
  return sortTastyClasses(injector.instance.getUnusedClasses({ root }));
1207
1242
  }
1208
1243
  /** Every class this injector holds CSS for in `root`. */
1209
- function getOwnedClasses(root = document) {
1244
+ function getOwnedClasses(root = defaultRoot()) {
1210
1245
  const registry = getRegistry(root);
1211
1246
  if (!registry) return [];
1212
1247
  const owned = [];
@@ -1273,15 +1308,15 @@ function extractChunkName(cacheKey) {
1273
1308
  }
1274
1309
  return null;
1275
1310
  }
1276
- function getChunkForClass(className, root = document) {
1311
+ function getChunkForClass(className, root = defaultRoot()) {
1277
1312
  const registry = getRegistry(root);
1278
1313
  if (!registry) return null;
1279
1314
  for (const [key, cn] of registry.cacheKeyToClassName) if (cn === className) return extractChunkName(key);
1280
1315
  return null;
1281
1316
  }
1282
- function buildChunkBreakdown(root = document) {
1317
+ function buildChunkBreakdown(root = defaultRoot()) {
1283
1318
  const registry = getRegistry(root);
1284
- if (!registry) return {
1319
+ if (!root || !registry) return {
1285
1320
  byChunk: {},
1286
1321
  totalChunkTypes: 0,
1287
1322
  totalClasses: 0
@@ -1319,9 +1354,9 @@ const GLOBAL_RULE_PREFIXES = {
1319
1354
  counterStyle: "counterstyle:",
1320
1355
  function: "function:"
1321
1356
  };
1322
- function getGlobalTypeCSS(type, root = document) {
1357
+ function getGlobalTypeCSS(type, root = defaultRoot()) {
1323
1358
  const registry = getRegistry(root);
1324
- if (!registry) return {
1359
+ if (!root || !registry) return {
1325
1360
  css: "",
1326
1361
  ruleCount: 0,
1327
1362
  size: 0
@@ -1383,7 +1418,7 @@ function getGlobalTypeCSS(type, root = document) {
1383
1418
  size: raw.length
1384
1419
  };
1385
1420
  }
1386
- function getSourceCssForClasses(classNames, root = document) {
1421
+ function getSourceCssForClasses(classNames, root = defaultRoot()) {
1387
1422
  const registry = getRegistry(root);
1388
1423
  if (!registry) return null;
1389
1424
  const chunks = [];
@@ -1397,7 +1432,7 @@ function getSourceCssForClasses(classNames, root = document) {
1397
1432
  }
1398
1433
  return found ? chunks.join("\n") : null;
1399
1434
  }
1400
- function getDefs(root = document) {
1435
+ function getDefs(root = defaultRoot()) {
1401
1436
  const registry = getRegistry(root);
1402
1437
  let properties = [];
1403
1438
  if (registry?.injectedProperties) properties = Array.from(registry.injectedProperties.keys()).sort();
@@ -1427,7 +1462,11 @@ const CHUNK_ORDER = [
1427
1462
  ];
1428
1463
  const tastyDebug = {
1429
1464
  css(target, opts) {
1430
- const { root = document, prettify = true, raw = false, source = false } = opts || {};
1465
+ const { root = defaultRoot(), prettify = true, raw = false, source = false } = opts || {};
1466
+ if (!root) {
1467
+ warnNoDom(raw);
1468
+ return "";
1469
+ }
1431
1470
  let css = "";
1432
1471
  const classRegex = tastyClassRegex(getNamePrefix());
1433
1472
  if (source && typeof target === "string" && classRegex.test(target)) {
@@ -1473,8 +1512,9 @@ const tastyDebug = {
1473
1512
  return result;
1474
1513
  },
1475
1514
  inspect(target, opts) {
1476
- const { root = document, raw = false } = opts || {};
1477
- const element = typeof target === "string" ? root.querySelector?.(target) : target;
1515
+ const { root = defaultRoot(), raw = false } = opts || {};
1516
+ const element = !root ? null : typeof target === "string" ? root.querySelector?.(target) : target;
1517
+ if (!root) warnNoDom(raw);
1478
1518
  if (!element) {
1479
1519
  const empty = {
1480
1520
  element: null,
@@ -1484,7 +1524,7 @@ const tastyDebug = {
1484
1524
  size: 0,
1485
1525
  rules: 0
1486
1526
  };
1487
- if (!raw) console.warn("[Tasty] debug.inspect: element not found");
1527
+ if (!raw && root) console.warn("[Tasty] debug.inspect: element not found");
1488
1528
  return empty;
1489
1529
  }
1490
1530
  const classList = element.getAttribute("class") || "";
@@ -1494,7 +1534,7 @@ const tastyDebug = {
1494
1534
  className,
1495
1535
  chunkName: getChunkForClass(className, root)
1496
1536
  }));
1497
- const css = getCSSTextForNode(element, { root });
1537
+ const css = getCSSTextForNode(element, { root: root ?? void 0 });
1498
1538
  const rules = countRules(css);
1499
1539
  const result = {
1500
1540
  element,
@@ -1517,7 +1557,8 @@ const tastyDebug = {
1517
1557
  return result;
1518
1558
  },
1519
1559
  summary(opts) {
1520
- const { root = document, raw = false } = opts || {};
1560
+ const { root = defaultRoot(), raw = false } = opts || {};
1561
+ if (!root) warnNoDom(raw);
1521
1562
  const activeClasses = findDomTastyClasses(root);
1522
1563
  const unusedClasses = getUnusedClasses(root);
1523
1564
  const ownedClasses = getOwnedClasses(root);
@@ -1525,9 +1566,9 @@ const tastyDebug = {
1525
1566
  const unusedSet = new Set(unusedClasses);
1526
1567
  const activeSet = new Set(activeClasses);
1527
1568
  const hotClasses = ownedClasses.filter((className) => !activeSet.has(className) && !unusedSet.has(className));
1528
- const hotCSS = injector.instance.getCSSTextForClasses(hotClasses, { root });
1529
- const activeCSS = injector.instance.getCSSTextForClasses(activeClasses, { root });
1530
- const unusedCSS = injector.instance.getCSSTextForClasses(unusedClasses, { root });
1569
+ const hotCSS = cssTextForClasses(hotClasses, root);
1570
+ const activeCSS = cssTextForClasses(activeClasses, root);
1571
+ const unusedCSS = cssTextForClasses(unusedClasses, root);
1531
1572
  const allCSS = getAllCSS(root);
1532
1573
  const activeRuleCount = countRules(activeCSS);
1533
1574
  const unusedRuleCount = countRules(unusedCSS);
@@ -1552,7 +1593,7 @@ const tastyDebug = {
1552
1593
  size: 0
1553
1594
  });
1554
1595
  const totalRuleCount = activeRuleCount + unusedRuleCount + countRules(hotCSS) + globalData.ruleCount + atRuleData.ruleCount + rawData.ruleCount + kfData.ruleCount + propData.ruleCount;
1555
- const metrics = injector.instance.getMetrics({ root });
1596
+ const metrics = getInjectorMetrics(root);
1556
1597
  const defs = getDefs(root);
1557
1598
  const chunkBreakdown = buildChunkBreakdown(root);
1558
1599
  const summary = {
@@ -1609,7 +1650,8 @@ const tastyDebug = {
1609
1650
  return summary;
1610
1651
  },
1611
1652
  chunks(opts) {
1612
- const { root = document, raw = false } = opts || {};
1653
+ const { root = defaultRoot(), raw = false } = opts || {};
1654
+ if (!root) warnNoDom(raw);
1613
1655
  const breakdown = buildChunkBreakdown(root);
1614
1656
  if (!raw) {
1615
1657
  console.group(`Chunks (${breakdown.totalChunkTypes} types, ${breakdown.totalClasses} classes)`);
@@ -1623,10 +1665,11 @@ const tastyDebug = {
1623
1665
  return breakdown;
1624
1666
  },
1625
1667
  cache(opts) {
1626
- const { root = document, raw = false } = opts || {};
1668
+ const { root = defaultRoot(), raw = false } = opts || {};
1669
+ if (!root) warnNoDom(raw);
1627
1670
  const active = findDomTastyClasses(root);
1628
1671
  const unused = getUnusedClasses(root);
1629
- const metrics = injector.instance.getMetrics({ root });
1672
+ const metrics = getInjectorMetrics(root);
1630
1673
  const status = {
1631
1674
  classes: {
1632
1675
  active,
@@ -1648,7 +1691,9 @@ const tastyDebug = {
1648
1691
  return status;
1649
1692
  },
1650
1693
  cleanup(opts) {
1651
- injector.instance.cleanup(opts?.root);
1694
+ const root = opts?.root ?? defaultRoot();
1695
+ if (!root) return;
1696
+ injector.instance.cleanup(root);
1652
1697
  },
1653
1698
  help() {
1654
1699
  console.log(`tastyDebug API:
@@ -1670,7 +1715,8 @@ Options: { raw: true } suppresses logging, { root: shadowRoot } targets Shadow D
1670
1715
  }
1671
1716
  }
1672
1717
  };
1673
- function getPageCSS(root = document) {
1718
+ function getPageCSS(root = defaultRoot()) {
1719
+ if (!root) return "";
1674
1720
  const chunks = [];
1675
1721
  try {
1676
1722
  if ("styleSheets" in root) for (const sheet of Array.from(root.styleSheets)) try {
@@ -1683,4 +1729,4 @@ if (typeof window !== "undefined" && isDevEnv()) tastyDebug.install();
1683
1729
  //#endregion
1684
1730
  export { keyframes as A, getRawCSSText as C, injectRawCSS as D, injectGlobal as E, chunkSheetRegistry as F, resolveFunctionColor as I, property as M, touch as N, injector as O, ChunkSheetRegistry as P, getCSSTextForNode as S, inject as T, destroy as _, color as a, gc as b, hasKeys as c, collectAutoInferredPropertiesRSC as d, getStyleTarget as f, createInjector as g, counterStyle as h, _modAttrs as i, ownKeyframes as j, isPropertyDefined as k, formatKeyframesCSS as l, cleanup as m, processTokens as n, filterBaseProps as o, pushRSCCSS as p, dotize as r, computeStyles as s, tastyDebug as t, collectAutoInferredProperties as u, fontFace as v, holdKeyframes as w, getCSSText as x, func as y };
1685
1731
 
1686
- //# sourceMappingURL=core-Bq7w2kti.js.map
1732
+ //# sourceMappingURL=core-DGm0CFHP.js.map