@tenphi/tasty 3.5.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.
- package/dist/{astro-ib7E7V4Y.js → astro-CeYENy2x.js} +61 -67
- package/dist/astro-CeYENy2x.js.map +1 -0
- package/dist/{collector-C6TtL8HJ.js → collector-B3OsM252.js} +2 -2
- package/dist/{collector-C6TtL8HJ.js.map → collector-B3OsM252.js.map} +1 -1
- package/dist/core/index.js +1 -1
- package/dist/{core-Bq7w2kti.js → core-DGm0CFHP.js} +76 -30
- package/dist/{core-Bq7w2kti.js.map → core-DGm0CFHP.js.map} +1 -1
- package/dist/css-resources-Cyl_axbI.js +149 -0
- package/dist/css-resources-Cyl_axbI.js.map +1 -0
- package/dist/{format-rules-rCZ37rqY.js → format-rules-XRw9u7d4.js} +2 -28
- package/dist/format-rules-XRw9u7d4.js.map +1 -0
- package/dist/index.js +2 -2
- package/dist/ssr/astro-middleware-extract-static.js +1 -1
- package/dist/ssr/astro-middleware-extract.js +1 -1
- package/dist/ssr/astro-middleware-static.js +1 -1
- package/dist/ssr/astro-middleware.js +1 -1
- package/dist/ssr/astro.d.ts +9 -1
- package/dist/ssr/astro.js +1 -1
- package/dist/ssr/index.js +2 -2
- package/dist/ssr/next-config.d.ts +66 -0
- package/dist/ssr/next-config.js +115 -0
- package/dist/ssr/next-config.js.map +1 -0
- package/dist/ssr/next.d.ts +8 -1
- package/dist/ssr/next.js +24 -7
- package/dist/ssr/next.js.map +1 -1
- package/dist/ssr-collector-ref-COs_ioWl.js +29 -0
- package/dist/ssr-collector-ref-COs_ioWl.js.map +1 -0
- package/docs/debug.md +13 -0
- package/docs/runtime-benchmarks.md +185 -12
- package/docs/ssr.md +151 -31
- package/package.json +9 -1
- package/dist/astro-ib7E7V4Y.js.map +0 -1
- package/dist/format-rules-rCZ37rqY.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"astro-ib7E7V4Y.js","names":[],"sources":["../src/ssr/astro-extraction.ts","../src/ssr/astro.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { readdir, readFile, writeFile, mkdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport type { ServerStyleArtifact } from './collector';\n\nconst METADATA_START = '<template data-tasty-extract>';\nconst METADATA_END = '</template>';\n\ninterface ExtractablePage {\n path: string;\n html: string;\n artifacts: ServerStyleArtifact[];\n styleStart: number;\n replacementEnd: number;\n styleOpen: string;\n}\n\nexport function createExtractionMetadata(\n artifacts: ServerStyleArtifact[],\n): string {\n const encoded = Buffer.from(JSON.stringify(artifacts), 'utf8').toString(\n 'base64',\n );\n return `${METADATA_START}${encoded}${METADATA_END}`;\n}\n\nfunction parseExtractablePage(\n path: string,\n html: string,\n): ExtractablePage | null {\n const metadataStart = html.indexOf(METADATA_START);\n if (metadataStart === -1) return null;\n\n const metadataContentStart = metadataStart + METADATA_START.length;\n const metadataEnd = html.indexOf(METADATA_END, metadataContentStart);\n if (metadataEnd === -1) return null;\n\n const encoded = html.slice(metadataContentStart, metadataEnd);\n let artifacts: ServerStyleArtifact[];\n try {\n artifacts = JSON.parse(\n Buffer.from(encoded, 'base64').toString('utf8'),\n ) as ServerStyleArtifact[];\n } catch {\n return null;\n }\n\n const styleStart = html.lastIndexOf('<style data-tasty-ssr', metadataStart);\n if (styleStart === -1) return null;\n const styleOpenEnd = html.indexOf('>', styleStart);\n const styleEnd = html.indexOf('</style>', styleOpenEnd + 1);\n if (\n styleOpenEnd === -1 ||\n styleEnd === -1 ||\n styleEnd + '</style>'.length !== metadataStart\n ) {\n return null;\n }\n\n return {\n path,\n html,\n artifacts,\n styleStart,\n replacementEnd: metadataEnd + METADATA_END.length,\n styleOpen: html.slice(styleStart, styleOpenEnd + 1),\n };\n}\n\nasync function findHTMLFiles(dir: string): Promise<string[]> {\n const paths: string[] = [];\n const entries = await readdir(dir, { withFileTypes: true });\n entries.sort((a, b) => a.name.localeCompare(b.name));\n for (const entry of entries) {\n const path = join(dir, entry.name);\n if (entry.isDirectory()) {\n paths.push(...(await findHTMLFiles(path)));\n } else if (entry.isFile() && entry.name.endsWith('.html')) {\n paths.push(path);\n }\n }\n return paths;\n}\n\nfunction findSequence(haystack: string[], needle: string[]): number {\n if (needle.length === 0) return -1;\n outer: for (let i = 0; i <= haystack.length - needle.length; i++) {\n for (let j = 0; j < needle.length; j++) {\n if (haystack[i + j] !== needle[j]) continue outer;\n }\n return i;\n }\n return -1;\n}\n\n/** Find the largest byte-sized artifact block that is contiguous on every page. */\nfunction selectSharedArtifacts(\n pages: ExtractablePage[],\n): ServerStyleArtifact[] {\n if (pages.length < 2) return [];\n\n const source = pages.reduce((shortest, page) =>\n page.artifacts.length < shortest.artifacts.length ? page : shortest,\n );\n const otherIds = pages\n .filter((page) => page !== source)\n .map((page) => page.artifacts.map(({ id }) => id));\n const sourceIds = source.artifacts.map(({ id }) => id);\n\n let best: ServerStyleArtifact[] = [];\n let bestBytes = 0;\n for (let start = 0; start < source.artifacts.length; start++) {\n let length = source.artifacts.length - start;\n for (const pageIds of otherIds) {\n let pageLength = 0;\n for (let pageStart = 0; pageStart < pageIds.length; pageStart++) {\n if (pageIds[pageStart] !== sourceIds[start]) continue;\n let matchLength = 1;\n while (\n start + matchLength < sourceIds.length &&\n pageStart + matchLength < pageIds.length &&\n sourceIds[start + matchLength] === pageIds[pageStart + matchLength]\n ) {\n matchLength++;\n }\n pageLength = Math.max(pageLength, matchLength);\n }\n length = Math.min(length, pageLength);\n if (length === 0) break;\n }\n\n const candidate = source.artifacts.slice(start, start + length);\n const bytes = candidate.reduce((total, item) => total + item.css.length, 0);\n if (bytes > bestBytes) {\n best = candidate;\n bestBytes = bytes;\n }\n }\n\n return best;\n}\n\nfunction stylesheetHref(\n base: string,\n assets: string,\n filename: string,\n): string {\n const basePath = base === '/' ? '' : `/${base.replace(/^\\/+|\\/+$/g, '')}`;\n const assetsPath = assets.replace(/^\\/+|\\/+$/g, '');\n return `${basePath}/${assetsPath}/${filename}`;\n}\n\nfunction styleTag(styleOpen: string, artifacts: ServerStyleArtifact[]): string {\n if (artifacts.length === 0) return '';\n return `${styleOpen}${artifacts.map(({ css }) => css).join('\\n')}</style>`;\n}\n\nfunction transformPage(\n page: ExtractablePage,\n selected: ServerStyleArtifact[],\n href: string,\n): string {\n const selectedIds = selected.map(({ id }) => id);\n const pageIds = page.artifacts.map(({ id }) => id);\n const first = findSequence(pageIds, selectedIds);\n if (first === -1) {\n const metadataStart = page.html.indexOf(METADATA_START, page.styleStart);\n return (\n page.html.slice(0, metadataStart) + page.html.slice(page.replacementEnd)\n );\n }\n\n const before = page.artifacts.slice(0, first);\n const after = page.artifacts.slice(first + selected.length);\n const nonceAttr = page.styleOpen.match(/\\snonce=\"[^\"]*\"/)?.[0] ?? '';\n const link = `<link rel=\"stylesheet\" href=\"${href}\" data-tasty-ssr${nonceAttr}>`;\n const replacement =\n styleTag(page.styleOpen, before) + link + styleTag(page.styleOpen, after);\n\n return (\n page.html.slice(0, page.styleStart) +\n replacement +\n page.html.slice(page.replacementEnd)\n );\n}\n\nexport async function extractAstroCSS(options: {\n dir: URL;\n base: string;\n assets: string;\n}): Promise<void> {\n const outputDir = fileURLToPath(options.dir);\n const paths = await findHTMLFiles(outputDir);\n const pages = (\n await Promise.all(\n paths.map(async (path) =>\n parseExtractablePage(path, await readFile(path, 'utf8')),\n ),\n )\n ).filter((page): page is ExtractablePage => page !== null);\n if (pages.length === 0) return;\n\n const selected = selectSharedArtifacts(pages);\n if (selected.length === 0) {\n for (const page of pages) {\n const metadataStart = page.html.indexOf(METADATA_START, page.styleStart);\n await writeFile(\n page.path,\n page.html.slice(0, metadataStart) +\n page.html.slice(page.replacementEnd),\n );\n }\n return;\n }\n\n const css = selected.map(({ css }) => css).join('\\n');\n const hash = createHash('sha256').update(css).digest('hex').slice(0, 12);\n const filename = `tasty.${hash}.css`;\n const assetDir = join(outputDir, options.assets);\n await mkdir(assetDir, { recursive: true });\n await writeFile(join(assetDir, filename), css);\n\n const href = stylesheetHref(options.base, options.assets, filename);\n for (const page of pages) {\n await writeFile(page.path, transformPage(page, selected, href));\n }\n}\n","/**\n * Astro integration for Tasty SSR.\n *\n * Provides:\n * - tastyIntegration() — Astro Integration API (recommended)\n * - tastyMiddleware() — manual middleware for advanced composition\n *\n * Import from '@tenphi/tasty/ssr/astro'.\n */\n\nimport { getConfig } from '../config';\nimport { getSSRCollector, runWithCollector } from './async-storage';\nimport { createExtractionMetadata, extractAstroCSS } from './astro-extraction';\nimport { ServerStyleCollector } from './collector';\nimport { registerSSRCollectorGetterGlobal } from './ssr-collector-ref';\n\n// Wire up ALS-based collector discovery so computeStyles() can find\n// the collector set by tastyMiddleware's runWithCollector().\n// Uses globalThis so the getter is visible across Astro's separate\n// module graphs (middleware vs page components).\nregisterSSRCollectorGetterGlobal(getSSRCollector);\n\nexport interface TastyMiddlewareOptions {\n /**\n * Whether to embed the class-list script for client hydration.\n * Set to false to skip class transfer (e.g. for CSP restrictions).\n * Without it, client components may re-inject CSS that already exists\n * in server-rendered `<style>` tags. Default: true.\n */\n transferCache?: boolean;\n}\n\ninterface InternalTastyMiddlewareOptions extends TastyMiddlewareOptions {\n extractionMetadata?: boolean;\n}\n\n/**\n * Create an Astro middleware that collects Tasty styles during SSR.\n *\n * All React components rendered during the request will have their\n * computeStyles() calls captured by the collector via AsyncLocalStorage.\n * After rendering, the middleware injects the collected CSS into </head>.\n *\n * @example Manual middleware setup\n * ```ts\n * // src/middleware.ts\n * import { tastyMiddleware } from '@tenphi/tasty/ssr/astro';\n * export const onRequest = tastyMiddleware();\n * ```\n *\n * @example Composing with other middleware\n * ```ts\n * // src/middleware.ts\n * import { sequence } from 'astro:middleware';\n * import { tastyMiddleware } from '@tenphi/tasty/ssr/astro';\n *\n * export const onRequest = sequence(\n * tastyMiddleware(),\n * myOtherMiddleware,\n * );\n * ```\n */\nexport function tastyMiddleware(options?: TastyMiddlewareOptions) {\n const internalOptions = options as InternalTastyMiddlewareOptions | undefined;\n return async (\n context: { isPrerendered?: boolean },\n next: () => Promise<Response>,\n ): Promise<Response> => {\n const transferCache = options?.transferCache ?? true;\n const extractionMetadata =\n internalOptions?.extractionMetadata === true &&\n context.isPrerendered === true;\n const collector = new ServerStyleCollector();\n\n // Run the entire request — including body stream consumption — inside\n // the ALS context so that components rendering lazily during stream\n // reads can still find the collector via getSSRCollector().\n type Rendered =\n | { response: Response }\n | { html: string | null; status: number; headers: Headers };\n\n const rendered = await runWithCollector<Promise<Rendered>>(\n collector,\n async (): Promise<Rendered> => {\n const response = await next();\n const body = response.body;\n\n // Only process HTML responses. Reading a non-HTML body (e.g. an\n // image, font, or JSON endpoint) as UTF-8 text corrupts binary\n // payloads: every byte >= 0x80 is decoded to U+FFFD and re-encoded\n // as EF BF BD. Pass anything that isn't HTML straight through.\n const contentType = response.headers.get('content-type') ?? '';\n if (!body || !contentType.includes('text/html')) {\n return { response };\n }\n\n const reader = body.pipeThrough(new TextDecoderStream()).getReader();\n const parts: string[] = [];\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n parts.push(value);\n }\n return {\n html: parts.join(''),\n status: response.status,\n headers: response.headers,\n };\n },\n );\n\n // Non-HTML responses are returned untouched to avoid corrupting\n // binary payloads.\n if ('response' in rendered) {\n return rendered.response;\n }\n\n if (!rendered.html) {\n return new Response(null, {\n status: rendered.status,\n headers: rendered.headers,\n });\n }\n\n let { html } = rendered;\n\n const css = collector.getCSS();\n if (!css) {\n return new Response(html, {\n status: rendered.status,\n headers: rendered.headers,\n });\n }\n\n const nonce = getConfig().nonce;\n const nonceAttr = nonce ? ` nonce=\"${nonce}\"` : '';\n const styleTag = `<style data-tasty-ssr${nonceAttr}>${css}</style>`;\n const metadataTag = extractionMetadata\n ? createExtractionMetadata(collector.getArtifacts())\n : '';\n\n let cacheTag = '';\n if (transferCache) {\n const classNames = collector.getRenderedClassNames();\n if (classNames.length > 0) {\n const classListJSON = classNames.map((n) => `\"${n}\"`).join(',');\n cacheTag = `<script${nonceAttr}>(window.__TASTY__=window.__TASTY__||[]).push(${classListJSON})</script>`;\n }\n }\n\n const injection = styleTag + metadataTag + cacheTag;\n const idx = html.indexOf('</head>');\n if (idx !== -1) {\n html = html.slice(0, idx) + injection + html.slice(idx);\n } else {\n html = injection + html;\n }\n\n const headers = new Headers(rendered.headers);\n headers.delete('content-length');\n\n return new Response(html, {\n status: rendered.status,\n headers,\n });\n };\n}\n\n// ============================================================================\n// Astro Integration API\n// ============================================================================\n\n/**\n * Package subpaths of the middleware entrypoints registered by\n * `tastyIntegration()`.\n *\n * These must be bare specifiers rather than\n * `new URL('./astro-middleware.js', import.meta.url)`. The bundler is free to\n * hoist `tastyIntegration` into a shared chunk at a different directory depth\n * than `dist/ssr/`, which makes a relative URL resolve to a file that does not\n * exist and breaks the build for every consumer. A package subpath is resolved\n * by the consumer through our `exports` map, so it never depends on the\n * chunk layout.\n *\n * There are separate entrypoints instead of one parameterised entrypoint because\n * `addMiddleware()` cannot pass options: the integration runs when the Astro\n * config is loaded, while the middleware module is evaluated in the server\n * runtime — a different process for built output — so module-level state set\n * by the integration is not visible to the middleware.\n */\nconst MIDDLEWARE_ENTRYPOINT = '@tenphi/tasty/ssr/astro-middleware';\nconst MIDDLEWARE_ENTRYPOINT_STATIC =\n '@tenphi/tasty/ssr/astro-middleware-static';\nconst MIDDLEWARE_ENTRYPOINT_EXTRACT =\n '@tenphi/tasty/ssr/astro-middleware-extract';\nconst MIDDLEWARE_ENTRYPOINT_EXTRACT_STATIC =\n '@tenphi/tasty/ssr/astro-middleware-extract-static';\n\nexport interface TastyIntegrationCSSOptions {\n /** CSS delivery mode. Extraction only applies to prerendered builds. */\n mode?: 'inline' | 'extract';\n}\n\nexport interface TastyIntegrationOptions {\n /**\n * Enable island hydration support.\n *\n * When `true` (default): injects a client hydration script via\n * `injectScript('before-hydration')` and sets `transferCache: true`\n * on the middleware. Islands skip the style pipeline during hydration.\n *\n * When `false`: no client JS is shipped and `transferCache` is set\n * to `false`. Use this for fully static sites without `client:*`\n * directives.\n */\n islands?: boolean;\n /** Configure inline or build-wide extracted CSS delivery. */\n css?: TastyIntegrationCSSOptions;\n}\n\n/**\n * Astro integration that automatically sets up Tasty SSR.\n *\n * Registers middleware for cross-component CSS deduplication and\n * optionally injects a client hydration script for island support.\n *\n * @example Basic setup (with islands)\n * ```ts\n * // astro.config.mjs\n * import { tastyIntegration } from '@tenphi/tasty/ssr/astro';\n *\n * export default defineConfig({\n * integrations: [tastyIntegration()],\n * });\n * ```\n *\n * @example Static-only (no client JS)\n * ```ts\n * // astro.config.mjs\n * import { tastyIntegration } from '@tenphi/tasty/ssr/astro';\n *\n * export default defineConfig({\n * integrations: [tastyIntegration({ islands: false })],\n * });\n * ```\n */\nexport function tastyIntegration(options?: TastyIntegrationOptions) {\n const { islands = true } = options ?? {};\n const cssMode = options?.css?.mode ?? 'inline';\n let base = '/';\n let assets = '_astro';\n\n return {\n name: '@tenphi/tasty',\n hooks: {\n 'astro:config:setup': ({\n addMiddleware,\n injectScript,\n }: {\n addMiddleware: (middleware: {\n entrypoint: string | URL;\n order: 'pre' | 'post';\n }) => void;\n injectScript: (\n stage: 'head-inline' | 'before-hydration' | 'page' | 'page-ssr',\n content: string,\n ) => void;\n }) => {\n addMiddleware({\n entrypoint:\n cssMode === 'extract'\n ? islands\n ? MIDDLEWARE_ENTRYPOINT_EXTRACT\n : MIDDLEWARE_ENTRYPOINT_EXTRACT_STATIC\n : islands\n ? MIDDLEWARE_ENTRYPOINT\n : MIDDLEWARE_ENTRYPOINT_STATIC,\n order: 'pre',\n });\n\n if (islands) {\n injectScript(\n 'before-hydration',\n `import \"@tenphi/tasty/ssr/astro-client\";`,\n );\n }\n },\n 'astro:config:done': ({\n config,\n }: {\n config: { base?: string; build?: { assets?: string } };\n }) => {\n base = config.base ?? '/';\n assets = config.build?.assets ?? '_astro';\n },\n 'astro:build:done': async ({ dir }: { dir: URL }) => {\n if (cssMode !== 'extract')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,UAAU,gDADT,WAAW,KAAK,MAAM,IAAI,EAAE,EAAE,CAAC,CAAC,KAAK,GACgC,EAAE;EAEjG;EAEA,MAAM,YAAY,WAAW,cAAc;EAC3C,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;AACF,MAAM,gCACJ;AACF,MAAM,uCACJ;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDF,SAAgB,iBAAiB,SAAmC;CAClE,MAAM,EAAE,UAAU,SAAS,WAAW,CAAC;CACvC,MAAM,UAAU,SAAS,KAAK,QAAQ;CACtC,IAAI,OAAO;CACX,IAAI,SAAS;CAEb,OAAO;EACL,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,aAGI;IACJ,OAAO,OAAO,QAAQ;IACtB,SAAS,OAAO,OAAO,UAAU;GACnC;GACA,oBAAoB,OAAO,EAAE,UAAwB;IACnD,IAAI,YAAY,WAAW;IAC3B,MAAM,gBAAgB;KAAE;KAAK;KAAM;IAAO,CAAC;GAC7C;EACF;CACF;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"format-rules-rCZ37rqY.js","names":[],"sources":["../src/ssr/ssr-collector-ref.ts","../src/ssr/format-property.ts","../src/ssr/format-rules.ts"],"sourcesContent":["/**\n * Global reference to the SSR collector getter function.\n *\n * This indirection avoids importing 'node:async_hooks' in the browser bundle.\n * The SSR entry point sets this ref when loaded on the server. The useStyles\n * hook calls it if set; on the client it stays null and is never called.\n *\n * Uses a module-level variable as the primary mechanism. In Next.js App\n * Router the RSC and SSR module graphs load separate copies of this module,\n * so the getter registered by TastyRegistry (SSR layer) is invisible to\n * server components (RSC layer) — which correctly fall through to inline\n * RSC styles.\n *\n * A globalThis fallback (`registerSSRCollectorGetterGlobal`) is provided\n * for frameworks like Astro where middleware and page components live in\n * different module graphs and must share the getter across them.\n */\n\nimport type { ServerStyleCollector } from './collector';\n\ntype SSRCollectorGetter = () => ServerStyleCollector | null;\n\nconst GETTER_KEY = '__tasty_ssr_collector_getter__';\n\nlet _getSSRCollector: SSRCollectorGetter | null = null;\n\n/**\n * Register the collector getter in the current module graph only.\n * Used by Next.js TastyRegistry.\n */\nexport function registerSSRCollectorGetter(fn: SSRCollectorGetter): void {\n _getSSRCollector = fn;\n}\n\n/**\n * Register the collector getter on globalThis so it is visible across\n * separate module graphs (e.g. Astro middleware ↔ page components).\n */\nexport function registerSSRCollectorGetterGlobal(fn: SSRCollectorGetter): void {\n (globalThis as Record<string, unknown>)[GETTER_KEY] = fn;\n}\n\n/**\n * Retrieve the SSR collector: module-level first, globalThis fallback.\n */\nexport function getRegisteredSSRCollector(): ServerStyleCollector | null {\n if (_getSSRCollector) return _getSSRCollector();\n const getter = (globalThis as Record<string, unknown>)[GETTER_KEY] as\n SSRCollectorGetter | undefined;\n return getter ? getter() : null;\n}\n","/**\n * Format @property CSS rules for SSR output.\n *\n * Replicates the CSS construction from StyleInjector.property()\n * but returns a CSS string instead of inserting into the DOM.\n */\n\nimport type { PropertyDefinition } from '../injector/types';\nimport { getEffectiveDefinition } from '../properties';\nimport type { StyleValue } from '../utils/styles';\nimport { parseStyle } from '../utils/styles';\n\n/**\n * Format a single @property rule as a CSS string.\n *\n * Returns the full `@property --name { ... }` text, or empty string\n * if the token is invalid.\n */\nexport function formatPropertyCSS(\n token: string,\n definition: PropertyDefinition,\n): string {\n const result = getEffectiveDefinition(token, definition);\n if (!result.isValid) return '';\n\n return buildPropertyRule(result.cssName, result.definition);\n}\n\nfunction buildPropertyRule(\n cssName: string,\n definition: PropertyDefinition,\n): string {\n const parts: string[] = [];\n\n if (definition.syntax != null) {\n let syntax = String(definition.syntax).trim();\n if (!/^['\"]/u.test(syntax)) syntax = `\"${syntax}\"`;\n parts.push(`syntax: ${syntax};`);\n }\n\n const inherits = definition.inherits ?? true;\n parts.push(`inherits: ${inherits ? 'true' : 'false'};`);\n\n if (definition.initialValue != null) {\n let initialValueStr: string;\n if (typeof definition.initialValue === 'number') {\n initialValueStr = String(definition.initialValue);\n } else {\n initialValueStr = parseStyle(\n definition.initialValue as StyleValue,\n ).output;\n }\n parts.push(`initial-value: ${initialValueStr};`);\n }\n\n const declarations = parts.join(' ').trim();\n return `@property ${cssName} { ${declarations} }`;\n}\n","/**\n * Shared CSS rule formatting utility.\n *\n * Extracted from SheetManager to allow both the DOM-based injector (client)\n * and the ServerStyleCollector (server) to produce identical CSS text\n * from StyleResult arrays.\n */\n\nimport type { StyleResult } from '../pipeline';\n\n/**\n * Resolve selectors for a rule, applying className-based specificity doubling\n * and rootPrefix handling. Mirrors the logic in StyleInjector.inject().\n */\nfunction resolveSelector(rule: StyleResult, className: string): string {\n let selector = rule.selector;\n\n if (rule.needsClassName) {\n const selectorParts = selector ? selector.split('|||') : [''];\n const classPrefix = `.${className}.${className}`;\n\n selector = selectorParts\n .map((part) => {\n const classSelector = part ? `${classPrefix}${part}` : classPrefix;\n\n if (rule.rootPrefix) {\n return `${rule.rootPrefix} ${classSelector}`;\n }\n return classSelector;\n })\n .join(', ');\n }\n\n return selector;\n}\n\ninterface GroupedRule {\n selector: string;\n declarations: string;\n atRules?: string[];\n startingStyle?: boolean;\n}\n\n/**\n * Group rules by selector + at-rules + startingStyle and merge their declarations.\n * Mirrors the grouping logic in SheetManager.insertRule().\n */\nfunction groupRules(rules: GroupedRule[]): GroupedRule[] {\n const groupMap = new Map<string, GroupedRule>();\n const order: string[] = [];\n\n const atKey = (at?: string[]) => (at && at.length ? at.join('|') : '');\n\n for (const r of rules) {\n const key = `${atKey(r.atRules)}||${r.selector}||${r.startingStyle ? '1' : '0'}`;\n const existing = groupMap.get(key);\n if (existing) {\n existing.declarations = existing.declarations\n ? `${existing.declarations} ${r.declarations}`\n : r.declarations;\n } else {\n groupMap.set(key, {\n selector: r.selector,\n atRules: r.atRules,\n startingStyle: r.startingStyle,\n declarations: r.declarations,\n });\n order.push(key);\n }\n }\n\n return order.map((key) => groupMap.get(key)!);\n}\n\n/**\n * Format an array of StyleResult rules into a CSS text string.\n *\n * Applies className-based specificity doubling (.cls.cls),\n * groups rules by selector + at-rules, and wraps with at-rule blocks.\n *\n * Produces the same CSS text as SheetManager.insertRule() would insert\n * into the DOM, but as a plain string suitable for SSR output.\n */\nexport function formatRules(rules: StyleResult[], className: string): string {\n if (rules.length === 0) return '';\n\n const resolvedRules = rules.map((rule) => ({\n selector: resolveSelector(rule, className),\n declarations: rule.declarations,\n atRules: rule.atRules,\n startingStyle: rule.startingStyle,\n }));\n\n const grouped = groupRules(resolvedRules);\n const cssRules: string[] = [];\n\n for (const rule of grouped) {\n const innerContent = rule.startingStyle\n ? `@starting-style { ${rule.declarations} }`\n : rule.declarations;\n const baseRule = `${rule.selector} { ${innerContent} }`;\n\n let fullRule = baseRule;\n if (rule.atRules && rule.atRules.length > 0) {\n fullRule = rule.atRules.reduce(\n (css, atRule) => `${atRule} { ${css} }`,\n baseRule,\n );\n }\n\n cssRules.push(fullRule);\n }\n\n return cssRules.join('\\n');\n}\n"],"mappings":";;AAsBA,MAAM,aAAa;AAEnB,IAAI,mBAA8C;;;;;AAMlD,SAAgB,2BAA2B,IAA8B;CACvE,mBAAmB;AACrB;;;;;AAMA,SAAgB,iCAAiC,IAA8B;CAC7E,WAAwC,cAAc;AACxD;;;;AAKA,SAAgB,4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