@tenphi/tasty 0.0.0-snapshot.bbd10c7 → 0.0.0-snapshot.bbfcd75
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/README.md +196 -140
- package/dist/babel-Zs1Q03qt.d.ts +83 -0
- package/dist/chunks/async-storage-CG5HnUT5.js +20 -0
- package/dist/chunks/async-storage-CG5HnUT5.js.map +1 -0
- package/dist/chunks/build-config-CUQVwdWF.js +42 -0
- package/dist/chunks/build-config-CUQVwdWF.js.map +1 -0
- package/dist/chunks/collector-B0LTHw6Z.js +208 -0
- package/dist/chunks/collector-B0LTHw6Z.js.map +1 -0
- package/dist/chunks/config-engine-C3pF9EK9.js +267 -0
- package/dist/chunks/config-engine-C3pF9EK9.js.map +1 -0
- package/dist/chunks/css-definitions-D_it4XZH.js +875 -0
- package/dist/chunks/css-definitions-D_it4XZH.js.map +1 -0
- package/dist/chunks/css-resources-BN8apgxt.js +142 -0
- package/dist/chunks/css-resources-BN8apgxt.js.map +1 -0
- package/dist/{debug.js → chunks/debug-C9LeNVoJ.js} +187 -139
- package/dist/chunks/debug-C9LeNVoJ.js.map +1 -0
- package/dist/chunks/dsl-C5yuAn41.js +1373 -0
- package/dist/chunks/dsl-C5yuAn41.js.map +1 -0
- package/dist/chunks/hydration-TRcz5vnk.js +41 -0
- package/dist/chunks/hydration-TRcz5vnk.js.map +1 -0
- package/dist/chunks/react-runtime-O-OUrKLH.js +557 -0
- package/dist/chunks/react-runtime-O-OUrKLH.js.map +1 -0
- package/dist/chunks/runtime-engine-DvnE2g-E.js +2437 -0
- package/dist/chunks/runtime-engine-DvnE2g-E.js.map +1 -0
- package/dist/chunks/runtime-state-BTDqSYBk.js +127 -0
- package/dist/chunks/runtime-state-BTDqSYBk.js.map +1 -0
- package/dist/{utils/merge-styles.js → chunks/shared-utils-DWA4LjIa.js} +55 -55
- package/dist/chunks/shared-utils-DWA4LjIa.js.map +1 -0
- package/dist/chunks/style-engine-C1ECBZxR.js +5131 -0
- package/dist/chunks/style-engine-C1ECBZxR.js.map +1 -0
- package/dist/{zero/extractor.js → chunks/zero-engine-B6EnYcXY.js} +89 -82
- package/dist/chunks/zero-engine-B6EnYcXY.js.map +1 -0
- package/dist/collector-hl5KNH7k.d.ts +165 -0
- package/dist/config-DWL1ZYue.d.ts +1358 -0
- package/dist/core/index.d.ts +5 -34
- package/dist/core/index.js +9 -27
- package/dist/index-D9N9GV24.d.ts +1947 -0
- package/dist/index.d.ts +5 -51
- package/dist/index.js +11 -36
- package/dist/{utils/merge-styles.d.ts → merge-styles-C_oMoJVd.d.ts} +3 -3
- package/dist/ssr/astro-client.js +6 -0
- package/dist/ssr/astro-client.js.map +1 -0
- package/dist/ssr/astro-middleware-extract-static.d.ts +11 -0
- package/dist/ssr/astro-middleware-extract-static.js +9 -0
- package/dist/ssr/astro-middleware-extract-static.js.map +1 -0
- package/dist/ssr/astro-middleware-extract.d.ts +11 -0
- package/dist/ssr/astro-middleware-extract.js +9 -0
- package/dist/ssr/astro-middleware-extract.js.map +1 -0
- package/dist/ssr/astro-middleware-static.d.ts +18 -0
- package/dist/ssr/astro-middleware-static.js +7 -0
- package/dist/ssr/astro-middleware-static.js.map +1 -0
- package/dist/ssr/astro-middleware.d.ts +19 -0
- package/dist/ssr/astro-middleware.js +7 -0
- package/dist/ssr/astro-middleware.js.map +1 -0
- package/dist/ssr/astro.d.ts +117 -11
- package/dist/ssr/astro.js +204 -48
- package/dist/ssr/astro.js.map +1 -1
- package/dist/ssr/index.d.ts +37 -4
- package/dist/ssr/index.js +6 -6
- package/dist/ssr/index.js.map +1 -1
- package/dist/ssr/next-config.d.ts +66 -0
- package/dist/ssr/next-config.js +124 -0
- package/dist/ssr/next-config.js.map +1 -0
- package/dist/ssr/next.d.ts +14 -5
- package/dist/ssr/next.js +31 -46
- package/dist/ssr/next.js.map +1 -1
- package/dist/static/index.d.ts +91 -5
- package/dist/static/index.js +31 -3
- package/dist/static/index.js.map +1 -0
- package/dist/static/inject.js.map +1 -1
- package/dist/types-jKZNpias.d.ts +1616 -0
- package/dist/zero/babel.d.ts +2 -182
- package/dist/zero/babel.js +82 -113
- package/dist/zero/babel.js.map +1 -1
- package/dist/zero/index.d.ts +81 -3
- package/dist/zero/index.js +2 -3
- package/dist/zero/next.d.ts +1 -1
- package/dist/zero/next.js +0 -31
- package/dist/zero/next.js.map +1 -1
- package/docs/README.md +20 -12
- package/docs/adoption.md +59 -32
- package/docs/ai-agents.md +229 -0
- package/docs/comparison.md +76 -48
- package/docs/configuration.md +566 -69
- package/docs/debug.md +37 -23
- package/docs/design-system.md +63 -32
- package/docs/dsl.md +527 -179
- package/docs/getting-started.md +62 -41
- package/docs/injector.md +157 -51
- package/docs/methodology.md +69 -37
- package/docs/migration-v3.md +285 -0
- package/docs/pipeline.md +744 -0
- package/docs/plugins.md +353 -0
- package/docs/{runtime.md → react-api.md} +176 -67
- package/docs/runtime-benchmarks.md +377 -0
- package/docs/ssr.md +350 -94
- package/docs/styles.md +108 -27
- package/docs/tasty-static.md +149 -87
- package/package.json +121 -23
- package/tasty.config.ts +6 -0
- package/dist/_virtual/_rolldown/runtime.js +0 -7
- package/dist/chunks/cacheKey.js +0 -77
- package/dist/chunks/cacheKey.js.map +0 -1
- package/dist/chunks/definitions.d.ts +0 -37
- package/dist/chunks/definitions.js +0 -258
- package/dist/chunks/definitions.js.map +0 -1
- package/dist/chunks/index.d.ts +0 -1
- package/dist/chunks/renderChunk.d.ts +0 -1
- package/dist/chunks/renderChunk.js +0 -59
- package/dist/chunks/renderChunk.js.map +0 -1
- package/dist/compute-styles.d.ts +0 -31
- package/dist/compute-styles.js +0 -356
- package/dist/compute-styles.js.map +0 -1
- package/dist/config.d.ts +0 -372
- package/dist/config.js +0 -507
- package/dist/config.js.map +0 -1
- package/dist/counter-style/index.js +0 -51
- package/dist/counter-style/index.js.map +0 -1
- package/dist/debug.d.ts +0 -89
- package/dist/debug.js.map +0 -1
- package/dist/font-face/index.js +0 -63
- package/dist/font-face/index.js.map +0 -1
- package/dist/hooks/index.d.ts +0 -7
- package/dist/hooks/useCounterStyle.d.ts +0 -50
- package/dist/hooks/useCounterStyle.js +0 -45
- package/dist/hooks/useCounterStyle.js.map +0 -1
- package/dist/hooks/useFontFace.d.ts +0 -43
- package/dist/hooks/useFontFace.js +0 -69
- package/dist/hooks/useFontFace.js.map +0 -1
- package/dist/hooks/useGlobalStyles.d.ts +0 -30
- package/dist/hooks/useGlobalStyles.js +0 -77
- package/dist/hooks/useGlobalStyles.js.map +0 -1
- package/dist/hooks/useKeyframes.d.ts +0 -56
- package/dist/hooks/useKeyframes.js +0 -63
- package/dist/hooks/useKeyframes.js.map +0 -1
- package/dist/hooks/useProperty.d.ts +0 -79
- package/dist/hooks/useProperty.js +0 -108
- package/dist/hooks/useProperty.js.map +0 -1
- package/dist/hooks/useRawCSS.d.ts +0 -53
- package/dist/hooks/useRawCSS.js +0 -34
- package/dist/hooks/useRawCSS.js.map +0 -1
- package/dist/hooks/useStyles.d.ts +0 -40
- package/dist/hooks/useStyles.js +0 -29
- package/dist/hooks/useStyles.js.map +0 -1
- package/dist/injector/index.d.ts +0 -166
- package/dist/injector/index.js +0 -166
- package/dist/injector/index.js.map +0 -1
- package/dist/injector/injector.d.ts +0 -166
- package/dist/injector/injector.js +0 -464
- package/dist/injector/injector.js.map +0 -1
- package/dist/injector/sheet-manager.d.ts +0 -136
- package/dist/injector/sheet-manager.js +0 -733
- package/dist/injector/sheet-manager.js.map +0 -1
- package/dist/injector/types.d.ts +0 -204
- package/dist/keyframes/index.js +0 -206
- package/dist/keyframes/index.js.map +0 -1
- package/dist/parser/classify.js +0 -319
- package/dist/parser/classify.js.map +0 -1
- package/dist/parser/const.js +0 -60
- package/dist/parser/const.js.map +0 -1
- package/dist/parser/lru.js +0 -109
- package/dist/parser/lru.js.map +0 -1
- package/dist/parser/parser.d.ts +0 -25
- package/dist/parser/parser.js +0 -115
- package/dist/parser/parser.js.map +0 -1
- package/dist/parser/tokenizer.js +0 -69
- package/dist/parser/tokenizer.js.map +0 -1
- package/dist/parser/types.d.ts +0 -51
- package/dist/parser/types.js +0 -46
- package/dist/parser/types.js.map +0 -1
- package/dist/pipeline/conditions.d.ts +0 -134
- package/dist/pipeline/conditions.js +0 -406
- package/dist/pipeline/conditions.js.map +0 -1
- package/dist/pipeline/exclusive.js +0 -230
- package/dist/pipeline/exclusive.js.map +0 -1
- package/dist/pipeline/index.d.ts +0 -55
- package/dist/pipeline/index.js +0 -708
- package/dist/pipeline/index.js.map +0 -1
- package/dist/pipeline/materialize.js +0 -1103
- package/dist/pipeline/materialize.js.map +0 -1
- package/dist/pipeline/parseStateKey.d.ts +0 -15
- package/dist/pipeline/parseStateKey.js +0 -446
- package/dist/pipeline/parseStateKey.js.map +0 -1
- package/dist/pipeline/simplify.js +0 -515
- package/dist/pipeline/simplify.js.map +0 -1
- package/dist/pipeline/warnings.js +0 -18
- package/dist/pipeline/warnings.js.map +0 -1
- package/dist/plugins/index.d.ts +0 -2
- package/dist/plugins/okhsl-plugin.d.ts +0 -35
- package/dist/plugins/okhsl-plugin.js +0 -97
- package/dist/plugins/okhsl-plugin.js.map +0 -1
- package/dist/plugins/types.d.ts +0 -76
- package/dist/properties/index.js +0 -222
- package/dist/properties/index.js.map +0 -1
- package/dist/properties/property-type-resolver.d.ts +0 -24
- package/dist/properties/property-type-resolver.js +0 -90
- package/dist/properties/property-type-resolver.js.map +0 -1
- package/dist/ssr/async-storage.d.ts +0 -17
- package/dist/ssr/async-storage.js +0 -34
- package/dist/ssr/async-storage.js.map +0 -1
- package/dist/ssr/collect-auto-properties.js +0 -39
- package/dist/ssr/collect-auto-properties.js.map +0 -1
- package/dist/ssr/collector.d.ts +0 -102
- package/dist/ssr/collector.js +0 -219
- package/dist/ssr/collector.js.map +0 -1
- package/dist/ssr/format-global-rules.js +0 -22
- package/dist/ssr/format-global-rules.js.map +0 -1
- package/dist/ssr/format-keyframes.js +0 -69
- package/dist/ssr/format-keyframes.js.map +0 -1
- package/dist/ssr/format-property.js +0 -49
- package/dist/ssr/format-property.js.map +0 -1
- package/dist/ssr/format-rules.js +0 -73
- package/dist/ssr/format-rules.js.map +0 -1
- package/dist/ssr/hydrate.d.ts +0 -22
- package/dist/ssr/hydrate.js +0 -49
- package/dist/ssr/hydrate.js.map +0 -1
- package/dist/ssr/ssr-collector-ref.js +0 -12
- package/dist/ssr/ssr-collector-ref.js.map +0 -1
- package/dist/states/index.d.ts +0 -49
- package/dist/states/index.js +0 -170
- package/dist/states/index.js.map +0 -1
- package/dist/static/tastyStatic.d.ts +0 -46
- package/dist/static/tastyStatic.js +0 -30
- package/dist/static/tastyStatic.js.map +0 -1
- package/dist/static/types.d.ts +0 -49
- package/dist/static/types.js +0 -24
- package/dist/static/types.js.map +0 -1
- package/dist/styles/border.d.ts +0 -25
- package/dist/styles/border.js +0 -120
- package/dist/styles/border.js.map +0 -1
- package/dist/styles/color.d.ts +0 -14
- package/dist/styles/color.js +0 -26
- package/dist/styles/color.js.map +0 -1
- package/dist/styles/const.js +0 -17
- package/dist/styles/const.js.map +0 -1
- package/dist/styles/createStyle.js +0 -79
- package/dist/styles/createStyle.js.map +0 -1
- package/dist/styles/dimension.js +0 -109
- package/dist/styles/dimension.js.map +0 -1
- package/dist/styles/directional.js +0 -133
- package/dist/styles/directional.js.map +0 -1
- package/dist/styles/display.d.ts +0 -30
- package/dist/styles/display.js +0 -73
- package/dist/styles/display.js.map +0 -1
- package/dist/styles/fade.d.ts +0 -15
- package/dist/styles/fade.js +0 -62
- package/dist/styles/fade.js.map +0 -1
- package/dist/styles/fill.d.ts +0 -42
- package/dist/styles/fill.js +0 -51
- package/dist/styles/fill.js.map +0 -1
- package/dist/styles/flow.d.ts +0 -16
- package/dist/styles/flow.js +0 -12
- package/dist/styles/flow.js.map +0 -1
- package/dist/styles/gap.d.ts +0 -31
- package/dist/styles/gap.js +0 -38
- package/dist/styles/gap.js.map +0 -1
- package/dist/styles/height.d.ts +0 -17
- package/dist/styles/height.js +0 -19
- package/dist/styles/height.js.map +0 -1
- package/dist/styles/index.d.ts +0 -1
- package/dist/styles/index.js +0 -8
- package/dist/styles/index.js.map +0 -1
- package/dist/styles/inset.d.ts +0 -24
- package/dist/styles/inset.js +0 -34
- package/dist/styles/inset.js.map +0 -1
- package/dist/styles/list.d.ts +0 -16
- package/dist/styles/list.js +0 -100
- package/dist/styles/list.js.map +0 -1
- package/dist/styles/margin.d.ts +0 -24
- package/dist/styles/margin.js +0 -32
- package/dist/styles/margin.js.map +0 -1
- package/dist/styles/outline.d.ts +0 -29
- package/dist/styles/outline.js +0 -55
- package/dist/styles/outline.js.map +0 -1
- package/dist/styles/padding.d.ts +0 -24
- package/dist/styles/padding.js +0 -32
- package/dist/styles/padding.js.map +0 -1
- package/dist/styles/placement.d.ts +0 -37
- package/dist/styles/placement.js +0 -74
- package/dist/styles/placement.js.map +0 -1
- package/dist/styles/predefined.d.ts +0 -71
- package/dist/styles/predefined.js +0 -237
- package/dist/styles/predefined.js.map +0 -1
- package/dist/styles/preset.d.ts +0 -52
- package/dist/styles/preset.js +0 -127
- package/dist/styles/preset.js.map +0 -1
- package/dist/styles/radius.d.ts +0 -12
- package/dist/styles/radius.js +0 -83
- package/dist/styles/radius.js.map +0 -1
- package/dist/styles/scrollMargin.d.ts +0 -24
- package/dist/styles/scrollMargin.js +0 -32
- package/dist/styles/scrollMargin.js.map +0 -1
- package/dist/styles/scrollbar.d.ts +0 -25
- package/dist/styles/scrollbar.js +0 -51
- package/dist/styles/scrollbar.js.map +0 -1
- package/dist/styles/shadow.d.ts +0 -14
- package/dist/styles/shadow.js +0 -25
- package/dist/styles/shadow.js.map +0 -1
- package/dist/styles/shared.js +0 -17
- package/dist/styles/shared.js.map +0 -1
- package/dist/styles/transition.d.ts +0 -14
- package/dist/styles/transition.js +0 -159
- package/dist/styles/transition.js.map +0 -1
- package/dist/styles/types.d.ts +0 -564
- package/dist/styles/width.d.ts +0 -17
- package/dist/styles/width.js +0 -19
- package/dist/styles/width.js.map +0 -1
- package/dist/tasty.d.ts +0 -134
- package/dist/tasty.js +0 -240
- package/dist/tasty.js.map +0 -1
- package/dist/types.d.ts +0 -184
- package/dist/utils/cache-wrapper.js +0 -21
- package/dist/utils/cache-wrapper.js.map +0 -1
- package/dist/utils/case-converter.js +0 -8
- package/dist/utils/case-converter.js.map +0 -1
- package/dist/utils/color-math.d.ts +0 -46
- package/dist/utils/color-math.js +0 -749
- package/dist/utils/color-math.js.map +0 -1
- package/dist/utils/color-space.d.ts +0 -5
- package/dist/utils/color-space.js +0 -228
- package/dist/utils/color-space.js.map +0 -1
- package/dist/utils/colors.d.ts +0 -5
- package/dist/utils/colors.js +0 -10
- package/dist/utils/colors.js.map +0 -1
- package/dist/utils/css-types.d.ts +0 -7
- package/dist/utils/dotize.d.ts +0 -26
- package/dist/utils/dotize.js +0 -122
- package/dist/utils/dotize.js.map +0 -1
- package/dist/utils/filter-base-props.d.ts +0 -15
- package/dist/utils/filter-base-props.js +0 -45
- package/dist/utils/filter-base-props.js.map +0 -1
- package/dist/utils/get-display-name.d.ts +0 -7
- package/dist/utils/get-display-name.js +0 -10
- package/dist/utils/get-display-name.js.map +0 -1
- package/dist/utils/has-keys.js +0 -13
- package/dist/utils/has-keys.js.map +0 -1
- package/dist/utils/is-dev-env.js +0 -19
- package/dist/utils/is-dev-env.js.map +0 -1
- package/dist/utils/is-valid-element-type.js +0 -15
- package/dist/utils/is-valid-element-type.js.map +0 -1
- package/dist/utils/merge-styles.js.map +0 -1
- package/dist/utils/mod-attrs.d.ts +0 -6
- package/dist/utils/mod-attrs.js +0 -20
- package/dist/utils/mod-attrs.js.map +0 -1
- package/dist/utils/process-tokens.d.ts +0 -17
- package/dist/utils/process-tokens.js +0 -83
- package/dist/utils/process-tokens.js.map +0 -1
- package/dist/utils/resolve-recipes.d.ts +0 -17
- package/dist/utils/resolve-recipes.js +0 -146
- package/dist/utils/resolve-recipes.js.map +0 -1
- package/dist/utils/selector-transform.js +0 -32
- package/dist/utils/selector-transform.js.map +0 -1
- package/dist/utils/string.js +0 -8
- package/dist/utils/string.js.map +0 -1
- package/dist/utils/styles.d.ts +0 -99
- package/dist/utils/styles.js +0 -220
- package/dist/utils/styles.js.map +0 -1
- package/dist/utils/typography.d.ts +0 -47
- package/dist/utils/typography.js +0 -51
- package/dist/utils/typography.js.map +0 -1
- package/dist/utils/warnings.d.ts +0 -16
- package/dist/utils/warnings.js +0 -16
- package/dist/utils/warnings.js.map +0 -1
- package/dist/zero/css-writer.d.ts +0 -45
- package/dist/zero/css-writer.js +0 -73
- package/dist/zero/css-writer.js.map +0 -1
- package/dist/zero/extractor.d.ts +0 -24
- package/dist/zero/extractor.js.map +0 -1
- package/docs/PIPELINE.md +0 -519
- /package/dist/{chunks/cacheKey.d.ts → ssr/astro-client.d.ts} +0 -0
package/dist/ssr/astro.js
CHANGED
|
@@ -1,64 +1,220 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
1
|
+
import { r as registerSSRCollectorGetterGlobal, u as getRuntimeConfigState } from "../chunks/runtime-state-BTDqSYBk.js";
|
|
2
|
+
import { t as ServerStyleCollector } from "../chunks/collector-B0LTHw6Z.js";
|
|
3
|
+
import { n as runWithCollector, t as getSSRCollector } from "../chunks/async-storage-CG5HnUT5.js";
|
|
4
|
+
import { t as findUnsafeCSSResource } from "../chunks/css-resources-BN8apgxt.js";
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
9
|
+
//#region src/ssr/astro-extraction.ts
|
|
10
|
+
const METADATA_START = "<template data-tasty-extract>";
|
|
11
|
+
const METADATA_END = "</template>";
|
|
12
|
+
function createExtractionMetadata(artifacts) {
|
|
13
|
+
return `${METADATA_START}${Buffer.from(JSON.stringify(artifacts), "utf8").toString("base64")}${METADATA_END}`;
|
|
14
|
+
}
|
|
15
|
+
function parseExtractablePage(path, html) {
|
|
16
|
+
const metadataStart = html.indexOf(METADATA_START);
|
|
17
|
+
if (metadataStart === -1) return null;
|
|
18
|
+
const metadataContentStart = metadataStart + 29;
|
|
19
|
+
const metadataEnd = html.indexOf(METADATA_END, metadataContentStart);
|
|
20
|
+
if (metadataEnd === -1) return null;
|
|
21
|
+
const encoded = html.slice(metadataContentStart, metadataEnd);
|
|
22
|
+
let artifacts;
|
|
23
|
+
try {
|
|
24
|
+
artifacts = JSON.parse(Buffer.from(encoded, "base64").toString("utf8"));
|
|
25
|
+
} catch {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
const styleStart = html.lastIndexOf("<style data-tasty-ssr", metadataStart);
|
|
29
|
+
if (styleStart === -1) return null;
|
|
30
|
+
const styleOpenEnd = html.indexOf(">", styleStart);
|
|
31
|
+
const styleEnd = html.indexOf("</style>", styleOpenEnd + 1);
|
|
32
|
+
if (styleOpenEnd === -1 || styleEnd === -1 || styleEnd + 8 !== metadataStart) return null;
|
|
33
|
+
return {
|
|
34
|
+
path,
|
|
35
|
+
html,
|
|
36
|
+
artifacts,
|
|
37
|
+
styleStart,
|
|
38
|
+
replacementEnd: metadataEnd + 11,
|
|
39
|
+
styleOpen: html.slice(styleStart, styleOpenEnd + 1)
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
async function findHTMLFiles(dir) {
|
|
43
|
+
const paths = [];
|
|
44
|
+
const entries = await readdir(dir, { withFileTypes: true });
|
|
45
|
+
entries.sort((a, b) => a.name.localeCompare(b.name));
|
|
46
|
+
for (const entry of entries) {
|
|
47
|
+
const path = join(dir, entry.name);
|
|
48
|
+
if (entry.isDirectory()) paths.push(...await findHTMLFiles(path));
|
|
49
|
+
else if (entry.isFile() && entry.name.endsWith(".html")) paths.push(path);
|
|
50
|
+
}
|
|
51
|
+
return paths;
|
|
52
|
+
}
|
|
53
|
+
function crossOriginAssetsPrefix(assetsPrefix, site) {
|
|
54
|
+
if (!assetsPrefix) return null;
|
|
55
|
+
const prefix = typeof assetsPrefix === "string" ? assetsPrefix : assetsPrefix.css || assetsPrefix.fallback;
|
|
56
|
+
if (!/^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(prefix)) return null;
|
|
57
|
+
if (!site) return prefix;
|
|
58
|
+
try {
|
|
59
|
+
return (prefix.startsWith("//") ? new URL(`${site.protocol}${prefix}`) : new URL(prefix)).origin === site.origin ? null : prefix;
|
|
60
|
+
} catch {
|
|
61
|
+
return prefix;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
function validateExtractedURLs(pages, assetsPrefix, site) {
|
|
65
|
+
const externalPrefix = crossOriginAssetsPrefix(assetsPrefix, site);
|
|
66
|
+
for (const page of pages) for (const artifact of page.artifacts) {
|
|
67
|
+
const unsafe = findUnsafeCSSResource(artifact.css, externalPrefix !== null);
|
|
68
|
+
if (unsafe) {
|
|
69
|
+
const reason = unsafe.rootRelative ? `root-relative CSS URL "${unsafe.url}" would resolve against the external assetsPrefix "${externalPrefix}" instead of the page origin` : `page-relative CSS URL "${unsafe.url}" cannot preserve its target`;
|
|
70
|
+
throw new Error(`[Tasty] Astro CSS extraction cannot preserve ${reason} in ${page.path} (${artifact.kind} artifact ${artifact.id}). Use an absolute URL or a data URL${externalPrefix ? "" : ", or a root-relative URL such as url(/path/to/asset)"}.`);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
function selectSharedArtifacts(pages) {
|
|
75
|
+
if (pages.length < 2) return [];
|
|
76
|
+
const source = pages[0].artifacts;
|
|
77
|
+
const otherIds = pages.slice(1).map((page) => new Set(page.artifacts.map(({ id }) => id)));
|
|
78
|
+
return source.filter(({ id }) => otherIds.every((ids) => ids.has(id)));
|
|
79
|
+
}
|
|
80
|
+
function stylesheetHref(base, assets, filename, assetsPrefix) {
|
|
81
|
+
const assetsPath = assets.replace(/^\/+|\/+$/g, "");
|
|
82
|
+
if (assetsPrefix) return `${(typeof assetsPrefix === "string" ? assetsPrefix : assetsPrefix.css || assetsPrefix.fallback).replace(/\/+$/g, "")}/${assetsPath}/${filename}`;
|
|
83
|
+
return `${base === "/" ? "" : `/${base.replace(/^\/+|\/+$/g, "")}`}/${assetsPath}/${filename}`;
|
|
84
|
+
}
|
|
85
|
+
function stylesheetLink(page, href) {
|
|
86
|
+
return `<link rel="stylesheet" href="${href}" data-tasty-ssr${page.styleOpen.match(/\snonce="[^"]*"/)?.[0] ?? ""}>`;
|
|
87
|
+
}
|
|
88
|
+
function transformPage(page, hrefs) {
|
|
89
|
+
const replacement = hrefs.map((href) => stylesheetLink(page, href)).join("");
|
|
90
|
+
return page.html.slice(0, page.styleStart) + replacement + page.html.slice(page.replacementEnd);
|
|
91
|
+
}
|
|
92
|
+
async function writeStylesheet(assetDir, scope, artifacts) {
|
|
93
|
+
if (artifacts.length === 0) return null;
|
|
94
|
+
const css = artifacts.map(({ css }) => css).join("\n");
|
|
95
|
+
const filename = `tasty.${scope}.${createHash("sha256").update(css).digest("hex").slice(0, 12)}.css`;
|
|
96
|
+
await writeFile(join(assetDir, filename), css);
|
|
97
|
+
return filename;
|
|
98
|
+
}
|
|
99
|
+
async function extractAstroCSS(options) {
|
|
100
|
+
const outputDir = fileURLToPath(options.dir);
|
|
101
|
+
const paths = await findHTMLFiles(outputDir);
|
|
102
|
+
const pages = (await Promise.all(paths.map(async (path) => parseExtractablePage(path, await readFile(path, "utf8"))))).filter((page) => page !== null);
|
|
103
|
+
if (pages.length === 0) return;
|
|
104
|
+
validateExtractedURLs(pages, options.assetsPrefix, options.site);
|
|
105
|
+
const shared = selectSharedArtifacts(pages);
|
|
106
|
+
const assetDir = join(outputDir, options.assets);
|
|
107
|
+
await mkdir(assetDir, { recursive: true });
|
|
108
|
+
const sharedFilename = await writeStylesheet(assetDir, "shared", shared);
|
|
109
|
+
const sharedHref = sharedFilename ? stylesheetHref(options.base, options.assets, sharedFilename, options.assetsPrefix) : null;
|
|
110
|
+
const sharedIds = new Set(shared.map(({ id }) => id));
|
|
111
|
+
for (const page of pages) {
|
|
112
|
+
const pageFilename = await writeStylesheet(assetDir, "page", page.artifacts.filter(({ id }) => !sharedIds.has(id)));
|
|
113
|
+
const hrefs = sharedHref ? [sharedHref] : [];
|
|
114
|
+
if (pageFilename) hrefs.push(stylesheetHref(options.base, options.assets, pageFilename, options.assetsPrefix));
|
|
115
|
+
await writeFile(page.path, transformPage(page, hrefs));
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
//#endregion
|
|
6
119
|
//#region src/ssr/astro.ts
|
|
7
|
-
|
|
8
|
-
* Astro integration for Tasty SSR.
|
|
9
|
-
*
|
|
10
|
-
* Provides tastyMiddleware() for Astro's middleware system.
|
|
11
|
-
* The middleware wraps request handling in a ServerStyleCollector
|
|
12
|
-
* via AsyncLocalStorage, then injects collected CSS into </head>.
|
|
13
|
-
*
|
|
14
|
-
* Import from '@tenphi/tasty/ssr/astro'.
|
|
15
|
-
*/
|
|
16
|
-
registerSSRCollectorGetter(getSSRCollector);
|
|
17
|
-
/**
|
|
18
|
-
* Create an Astro middleware that collects Tasty styles during SSR.
|
|
19
|
-
*
|
|
20
|
-
* All React components rendered during the request (both static
|
|
21
|
-
* and islands) will have their useStyles() calls captured by the
|
|
22
|
-
* collector via AsyncLocalStorage. After rendering, the middleware
|
|
23
|
-
* injects the collected CSS into </head>.
|
|
24
|
-
*
|
|
25
|
-
* @example
|
|
26
|
-
* ```ts
|
|
27
|
-
* // src/middleware.ts
|
|
28
|
-
* import { tastyMiddleware } from '@tenphi/tasty/ssr/astro';
|
|
29
|
-
* export const onRequest = tastyMiddleware();
|
|
30
|
-
* ```
|
|
31
|
-
*/
|
|
120
|
+
registerSSRCollectorGetterGlobal(getSSRCollector);
|
|
32
121
|
function tastyMiddleware(options) {
|
|
33
|
-
const
|
|
34
|
-
return async (
|
|
122
|
+
const internalOptions = options;
|
|
123
|
+
return async (context, next) => {
|
|
124
|
+
const transferCache = options?.transferCache ?? true;
|
|
125
|
+
const extractionMetadata = internalOptions?.extractionMetadata === true && context.isPrerendered === true;
|
|
35
126
|
const collector = new ServerStyleCollector();
|
|
36
|
-
const
|
|
127
|
+
const rendered = await runWithCollector(collector, async () => {
|
|
128
|
+
const response = await next();
|
|
129
|
+
const body = response.body;
|
|
130
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
131
|
+
if (!body || !contentType.includes("text/html")) return { response };
|
|
132
|
+
const reader = body.pipeThrough(new TextDecoderStream()).getReader();
|
|
133
|
+
const parts = [];
|
|
134
|
+
for (;;) {
|
|
135
|
+
const { done, value } = await reader.read();
|
|
136
|
+
if (done) break;
|
|
137
|
+
parts.push(value);
|
|
138
|
+
}
|
|
139
|
+
return {
|
|
140
|
+
html: parts.join(""),
|
|
141
|
+
status: response.status,
|
|
142
|
+
headers: response.headers
|
|
143
|
+
};
|
|
144
|
+
});
|
|
145
|
+
if ("response" in rendered) return rendered.response;
|
|
146
|
+
if (!rendered.html) return new Response(null, {
|
|
147
|
+
status: rendered.status,
|
|
148
|
+
headers: rendered.headers
|
|
149
|
+
});
|
|
150
|
+
let { html } = rendered;
|
|
37
151
|
const css = collector.getCSS();
|
|
38
|
-
if (!css) return
|
|
39
|
-
|
|
152
|
+
if (!css) return new Response(html, {
|
|
153
|
+
status: rendered.status,
|
|
154
|
+
headers: rendered.headers
|
|
155
|
+
});
|
|
156
|
+
const nonce = getRuntimeConfigState()?.nonce;
|
|
40
157
|
const nonceAttr = nonce ? ` nonce="${nonce}"` : "";
|
|
41
|
-
const html = await response.text();
|
|
42
158
|
const styleTag = `<style data-tasty-ssr${nonceAttr}>${css}</style>`;
|
|
159
|
+
const metadataTag = extractionMetadata ? createExtractionMetadata(collector.getArtifacts()) : "";
|
|
43
160
|
let cacheTag = "";
|
|
44
161
|
if (transferCache) {
|
|
45
|
-
const
|
|
46
|
-
if (
|
|
162
|
+
const classNames = collector.getRenderedClassNames();
|
|
163
|
+
if (classNames.length > 0) cacheTag = `<script${nonceAttr}>(window.__TASTY__=window.__TASTY__||[]).push(${classNames.map((n) => `"${n}"`).join(",")})<\/script>`;
|
|
47
164
|
}
|
|
48
|
-
const
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
165
|
+
const injection = styleTag + metadataTag + cacheTag;
|
|
166
|
+
const idx = html.indexOf("</head>");
|
|
167
|
+
if (idx !== -1) html = html.slice(0, idx) + injection + html.slice(idx);
|
|
168
|
+
else html = injection + html;
|
|
169
|
+
const headers = new Headers(rendered.headers);
|
|
170
|
+
headers.delete("content-length");
|
|
171
|
+
return new Response(html, {
|
|
172
|
+
status: rendered.status,
|
|
173
|
+
headers
|
|
52
174
|
});
|
|
53
175
|
};
|
|
54
176
|
}
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
177
|
+
const MIDDLEWARE_ENTRYPOINT = "@tenphi/tasty/ssr/astro-middleware";
|
|
178
|
+
const MIDDLEWARE_ENTRYPOINT_STATIC = "@tenphi/tasty/ssr/astro-middleware-static";
|
|
179
|
+
const MIDDLEWARE_ENTRYPOINT_EXTRACT = "@tenphi/tasty/ssr/astro-middleware-extract";
|
|
180
|
+
const MIDDLEWARE_ENTRYPOINT_EXTRACT_STATIC = "@tenphi/tasty/ssr/astro-middleware-extract-static";
|
|
181
|
+
function tastyIntegration(options) {
|
|
182
|
+
const { islands = true } = options ?? {};
|
|
183
|
+
const cssMode = options?.css?.mode ?? "inline";
|
|
184
|
+
let base = "/";
|
|
185
|
+
let assets = "_astro";
|
|
186
|
+
let assetsPrefix;
|
|
187
|
+
let site;
|
|
188
|
+
return {
|
|
189
|
+
name: "@tenphi/tasty",
|
|
190
|
+
hooks: {
|
|
191
|
+
"astro:config:setup": ({ addMiddleware, injectScript }) => {
|
|
192
|
+
addMiddleware({
|
|
193
|
+
entrypoint: cssMode === "extract" ? islands ? MIDDLEWARE_ENTRYPOINT_EXTRACT : MIDDLEWARE_ENTRYPOINT_EXTRACT_STATIC : islands ? MIDDLEWARE_ENTRYPOINT : MIDDLEWARE_ENTRYPOINT_STATIC,
|
|
194
|
+
order: "pre"
|
|
195
|
+
});
|
|
196
|
+
if (islands) injectScript("before-hydration", `import "@tenphi/tasty/ssr/astro-client";`);
|
|
197
|
+
},
|
|
198
|
+
"astro:config:done": ({ config }) => {
|
|
199
|
+
base = config.base ?? "/";
|
|
200
|
+
assets = config.build?.assets ?? "_astro";
|
|
201
|
+
assetsPrefix = config.build?.assetsPrefix;
|
|
202
|
+
site = config.site;
|
|
203
|
+
},
|
|
204
|
+
"astro:build:done": async ({ dir }) => {
|
|
205
|
+
if (cssMode !== "extract") return;
|
|
206
|
+
await extractAstroCSS({
|
|
207
|
+
dir,
|
|
208
|
+
base,
|
|
209
|
+
assets,
|
|
210
|
+
assetsPrefix,
|
|
211
|
+
site
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
};
|
|
60
216
|
}
|
|
61
217
|
//#endregion
|
|
62
|
-
export {
|
|
218
|
+
export { tastyIntegration, tastyMiddleware };
|
|
63
219
|
|
|
64
220
|
//# sourceMappingURL=astro.js.map
|
package/dist/ssr/astro.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"astro.js","names":[],"sources":["../../src/ssr/astro.ts"],"sourcesContent":["/**\n * Astro integration for Tasty SSR.\n *\n * Provides tastyMiddleware() for Astro's middleware system.\n * The middleware wraps request handling in a ServerStyleCollector\n * via AsyncLocalStorage, then injects collected CSS into </head>.\n *\n * Import from '@tenphi/tasty/ssr/astro'.\n */\n\nimport { getConfig } from '../config';\nimport { getSSRCollector, runWithCollector } from './async-storage';\nimport { ServerStyleCollector } from './collector';\nimport { hydrateTastyCache } from './hydrate';\nimport { registerSSRCollectorGetter } from './ssr-collector-ref';\n\n// Wire up ALS-based collector discovery so useStyles can find\n// the collector set by tastyMiddleware's runWithCollector().\nregisterSSRCollectorGetter(getSSRCollector);\n\n// Re-export for convenience\nexport { hydrateTastyCache };\n\nexport interface TastyMiddlewareOptions {\n /**\n * Whether to embed the cache state script for client hydration.\n * Set to false to skip cache transfer. Default: true.\n */\n transferCache?: boolean;\n}\n\n/**\n * Create an Astro middleware that collects Tasty styles during SSR.\n *\n * All React components rendered during the request (both static\n * and islands) will have their useStyles() calls captured by the\n * collector via AsyncLocalStorage. After rendering, the middleware\n * injects the collected CSS into </head>.\n *\n * @example\n * ```ts\n * // src/middleware.ts\n * import { tastyMiddleware } from '@tenphi/tasty/ssr/astro';\n * export const onRequest = tastyMiddleware();\n * ```\n */\nexport function tastyMiddleware(options?: TastyMiddlewareOptions) {\n const { transferCache = true } = options ?? {};\n\n return async (\n _context: unknown,\n next: () => Promise<Response>,\n ): Promise<Response> => {\n const collector = new ServerStyleCollector();\n\n const response = await runWithCollector(collector, () => next());\n\n const css = collector.getCSS();\n if (!css) return response;\n\n const nonce = getConfig().nonce;\n const nonceAttr = nonce ? ` nonce=\"${nonce}\"` : '';\n const html = await response.text();\n const styleTag = `<style data-tasty-ssr${nonceAttr}>${css}</style>`;\n\n let cacheTag = '';\n if (transferCache) {\n const cacheState = collector.getCacheState();\n const hasHydratableStyles = Object.keys(cacheState.entries).length > 0;\n if (hasHydratableStyles) {\n cacheTag = `<script data-tasty-cache type=\"application/json\"${nonceAttr}>${JSON.stringify(cacheState)}</script>`;\n }\n }\n\n const modifiedHtml = html.replace(\n '</head>',\n `${styleTag}${cacheTag}</head>`,\n );\n\n return new Response(modifiedHtml, {\n status: response.status,\n headers: response.headers,\n });\n };\n}\n\n// Client-side auto-hydration.\n// When imported in the browser, reads the cache state from the DOM\n// and pre-populates the injector before any island hydrates.\nif (typeof window !== 'undefined') {\n const script = document.querySelector('script[data-tasty-cache]');\n if (script) {\n try {\n const state = JSON.parse(script.textContent!);\n hydrateTastyCache(state);\n } catch {\n // Ignore malformed cache state\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAkBA,2BAA2B,gBAAgB;;;;;;;;;;;;;;;;AA4B3C,SAAgB,gBAAgB,SAAkC;CAChE,MAAM,EAAE,gBAAgB,SAAS,WAAW,EAAE;AAE9C,QAAO,OACL,UACA,SACsB;EACtB,MAAM,YAAY,IAAI,sBAAsB;EAE5C,MAAM,WAAW,MAAM,iBAAiB,iBAAiB,MAAM,CAAC;EAEhE,MAAM,MAAM,UAAU,QAAQ;AAC9B,MAAI,CAAC,IAAK,QAAO;EAEjB,MAAM,QAAQ,WAAW,CAAC;EAC1B,MAAM,YAAY,QAAQ,WAAW,MAAM,KAAK;EAChD,MAAM,OAAO,MAAM,SAAS,MAAM;EAClC,MAAM,WAAW,wBAAwB,UAAU,GAAG,IAAI;EAE1D,IAAI,WAAW;AACf,MAAI,eAAe;GACjB,MAAM,aAAa,UAAU,eAAe;AAE5C,OAD4B,OAAO,KAAK,WAAW,QAAQ,CAAC,SAAS,EAEnE,YAAW,mDAAmD,UAAU,GAAG,KAAK,UAAU,WAAW,CAAC;;EAI1G,MAAM,eAAe,KAAK,QACxB,WACA,GAAG,WAAW,SAAS,SACxB;AAED,SAAO,IAAI,SAAS,cAAc;GAChC,QAAQ,SAAS;GACjB,SAAS,SAAS;GACnB,CAAC;;;AAON,IAAI,OAAO,WAAW,aAAa;CACjC,MAAM,SAAS,SAAS,cAAc,2BAA2B;AACjE,KAAI,OACF,KAAI;AAEF,oBADc,KAAK,MAAM,OAAO,YAAa,CACrB;SAClB"}
|
|
1
|
+
{"version":3,"file":"astro.js","names":[],"sources":["../../src/ssr/astro-extraction.ts","../../src/ssr/astro.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { readdir, readFile, writeFile, mkdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport type { ServerStyleArtifact } from './collector';\nimport { findUnsafeCSSResource } from './css-resources';\n\nconst METADATA_START = '<template data-tasty-extract>';\nconst METADATA_END = '</template>';\n\ninterface ExtractablePage {\n path: string;\n html: string;\n artifacts: ServerStyleArtifact[];\n styleStart: number;\n replacementEnd: number;\n styleOpen: string;\n}\n\nexport function createExtractionMetadata(\n artifacts: ServerStyleArtifact[],\n): string {\n const encoded = Buffer.from(JSON.stringify(artifacts), 'utf8').toString(\n 'base64',\n );\n return `${METADATA_START}${encoded}${METADATA_END}`;\n}\n\nfunction parseExtractablePage(\n path: string,\n html: string,\n): ExtractablePage | null {\n const metadataStart = html.indexOf(METADATA_START);\n if (metadataStart === -1) return null;\n\n const metadataContentStart = metadataStart + METADATA_START.length;\n const metadataEnd = html.indexOf(METADATA_END, metadataContentStart);\n if (metadataEnd === -1) return null;\n\n const encoded = html.slice(metadataContentStart, metadataEnd);\n let artifacts: ServerStyleArtifact[];\n try {\n artifacts = JSON.parse(\n Buffer.from(encoded, 'base64').toString('utf8'),\n ) as ServerStyleArtifact[];\n } catch {\n return null;\n }\n\n const styleStart = html.lastIndexOf('<style data-tasty-ssr', metadataStart);\n if (styleStart === -1) return null;\n const styleOpenEnd = html.indexOf('>', styleStart);\n const styleEnd = html.indexOf('</style>', styleOpenEnd + 1);\n if (\n styleOpenEnd === -1 ||\n styleEnd === -1 ||\n styleEnd + '</style>'.length !== metadataStart\n ) {\n return null;\n }\n\n return {\n path,\n html,\n artifacts,\n styleStart,\n replacementEnd: metadataEnd + METADATA_END.length,\n styleOpen: html.slice(styleStart, styleOpenEnd + 1),\n };\n}\n\nasync function findHTMLFiles(dir: string): Promise<string[]> {\n const paths: string[] = [];\n const entries = await readdir(dir, { withFileTypes: true });\n entries.sort((a, b) => a.name.localeCompare(b.name));\n for (const entry of entries) {\n const path = join(dir, entry.name);\n if (entry.isDirectory()) {\n paths.push(...(await findHTMLFiles(path)));\n } else if (entry.isFile() && entry.name.endsWith('.html')) {\n paths.push(path);\n }\n }\n return paths;\n}\n\nfunction crossOriginAssetsPrefix(\n assetsPrefix?: string | Record<string, string>,\n site?: URL,\n): string | null {\n if (!assetsPrefix) return null;\n const prefix =\n typeof assetsPrefix === 'string'\n ? assetsPrefix\n : assetsPrefix.css || assetsPrefix.fallback;\n if (!/^(?:[a-z][a-z\\d+.-]*:|\\/\\/)/i.test(prefix)) return null;\n if (!site) return prefix;\n\n try {\n const prefixURL = prefix.startsWith('//')\n ? new URL(`${site.protocol}${prefix}`)\n : new URL(prefix);\n return prefixURL.origin === site.origin ? null : prefix;\n } catch {\n return prefix;\n }\n}\n\nfunction validateExtractedURLs(\n pages: ExtractablePage[],\n assetsPrefix?: string | Record<string, string>,\n site?: URL,\n): void {\n const externalPrefix = crossOriginAssetsPrefix(assetsPrefix, site);\n for (const page of pages) {\n for (const artifact of page.artifacts) {\n const unsafe = findUnsafeCSSResource(\n artifact.css,\n externalPrefix !== null,\n );\n if (unsafe) {\n const reason = unsafe.rootRelative\n ? `root-relative CSS URL \"${unsafe.url}\" would resolve against the external assetsPrefix \"${externalPrefix}\" instead of the page origin`\n : `page-relative CSS URL \"${unsafe.url}\" cannot preserve its target`;\n throw new Error(\n `[Tasty] Astro CSS extraction cannot preserve ${reason} in ${page.path} (${artifact.kind} artifact ${artifact.id}). Use an absolute URL or a data URL${externalPrefix ? '' : ', or a root-relative URL such as url(/path/to/asset)'}.`,\n );\n }\n }\n }\n}\n\n/** Find artifacts emitted by every styled page, in the first page's order. */\nfunction selectSharedArtifacts(\n pages: ExtractablePage[],\n): ServerStyleArtifact[] {\n if (pages.length < 2) return [];\n\n const source = pages[0].artifacts;\n const otherIds = pages\n .slice(1)\n .map((page) => new Set(page.artifacts.map(({ id }) => id)));\n\n return source.filter(({ id }) => otherIds.every((ids) => ids.has(id)));\n}\n\nfunction stylesheetHref(\n base: string,\n assets: string,\n filename: string,\n assetsPrefix?: string | Record<string, string>,\n): string {\n const assetsPath = assets.replace(/^\\/+|\\/+$/g, '');\n if (assetsPrefix) {\n const prefix =\n typeof assetsPrefix === 'string'\n ? assetsPrefix\n : assetsPrefix.css || assetsPrefix.fallback;\n return `${prefix.replace(/\\/+$/g, '')}/${assetsPath}/${filename}`;\n }\n\n const basePath = base === '/' ? '' : `/${base.replace(/^\\/+|\\/+$/g, '')}`;\n return `${basePath}/${assetsPath}/${filename}`;\n}\n\nfunction stylesheetLink(page: ExtractablePage, href: string): string {\n const nonceAttr = page.styleOpen.match(/\\snonce=\"[^\"]*\"/)?.[0] ?? '';\n return `<link rel=\"stylesheet\" href=\"${href}\" data-tasty-ssr${nonceAttr}>`;\n}\n\nfunction transformPage(page: ExtractablePage, hrefs: string[]): string {\n const replacement = hrefs.map((href) => stylesheetLink(page, href)).join('');\n\n return (\n page.html.slice(0, page.styleStart) +\n replacement +\n page.html.slice(page.replacementEnd)\n );\n}\n\nasync function writeStylesheet(\n assetDir: string,\n scope: 'shared' | 'page',\n artifacts: ServerStyleArtifact[],\n): Promise<string | null> {\n if (artifacts.length === 0) return null;\n\n const css = artifacts.map(({ css }) => css).join('\\n');\n const hash = createHash('sha256').update(css).digest('hex').slice(0, 12);\n const filename = `tasty.${scope}.${hash}.css`;\n await writeFile(join(assetDir, filename), css);\n return filename;\n}\n\nexport async function extractAstroCSS(options: {\n dir: URL;\n base: string;\n assets: string;\n assetsPrefix?: string | Record<string, string>;\n site?: URL;\n}): Promise<void> {\n const outputDir = fileURLToPath(options.dir);\n const paths = await findHTMLFiles(outputDir);\n const pages = (\n await Promise.all(\n paths.map(async (path) =>\n parseExtractablePage(path, await readFile(path, 'utf8')),\n ),\n )\n ).filter((page): page is ExtractablePage => page !== null);\n if (pages.length === 0) return;\n validateExtractedURLs(pages, options.assetsPrefix, options.site);\n\n const shared = selectSharedArtifacts(pages);\n const assetDir = join(outputDir, options.assets);\n await mkdir(assetDir, { recursive: true });\n const sharedFilename = await writeStylesheet(assetDir, 'shared', shared);\n const sharedHref = sharedFilename\n ? stylesheetHref(\n options.base,\n options.assets,\n sharedFilename,\n options.assetsPrefix,\n )\n : null;\n const sharedIds = new Set(shared.map(({ id }) => id));\n\n for (const page of pages) {\n const remainder = page.artifacts.filter(({ id }) => !sharedIds.has(id));\n const pageFilename = await writeStylesheet(assetDir, 'page', remainder);\n const hrefs = sharedHref ? [sharedHref] : [];\n if (pageFilename) {\n hrefs.push(\n stylesheetHref(\n options.base,\n options.assets,\n pageFilename,\n options.assetsPrefix,\n ),\n );\n }\n await writeFile(page.path, transformPage(page, hrefs));\n }\n}\n","/**\n * Astro integration for Tasty SSR.\n *\n * Provides:\n * - tastyIntegration() — Astro Integration API (recommended)\n * - tastyMiddleware() — manual middleware for advanced composition\n *\n * Import from '@tenphi/tasty/ssr/astro'.\n */\n\nimport { getRuntimeConfigState } from '../config-resources';\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 = getRuntimeConfigState()?.nonce;\n const nonceAttr = nonce ? ` nonce=\"${nonce}\"` : '';\n const styleTag = `<style data-tasty-ssr${nonceAttr}>${css}</style>`;\n const metadataTag = extractionMetadata\n ? createExtractionMetadata(collector.getArtifacts())\n : '';\n\n let cacheTag = '';\n if (transferCache) {\n const classNames = collector.getRenderedClassNames();\n if (classNames.length > 0) {\n const classListJSON = classNames.map((n) => `\"${n}\"`).join(',');\n cacheTag = `<script${nonceAttr}>(window.__TASTY__=window.__TASTY__||[]).push(${classListJSON})</script>`;\n }\n }\n\n const injection = styleTag + metadataTag + cacheTag;\n const idx = html.indexOf('</head>');\n if (idx !== -1) {\n html = html.slice(0, idx) + injection + html.slice(idx);\n } else {\n html = injection + html;\n }\n\n const headers = new Headers(rendered.headers);\n headers.delete('content-length');\n\n return new Response(html, {\n status: rendered.status,\n headers,\n });\n };\n}\n\n// ============================================================================\n// Astro Integration API\n// ============================================================================\n\n/**\n * Package subpaths of the middleware entrypoints registered by\n * `tastyIntegration()`.\n *\n * These must be bare specifiers rather than\n * `new URL('./astro-middleware.js', import.meta.url)`. The bundler is free to\n * hoist `tastyIntegration` into a shared chunk at a different directory depth\n * than `dist/ssr/`, which makes a relative URL resolve to a file that does not\n * exist and breaks the build for every consumer. A package subpath is resolved\n * by the consumer through our `exports` map, so it never depends on the\n * chunk layout.\n *\n * There are separate entrypoints instead of one parameterised entrypoint because\n * `addMiddleware()` cannot pass options: the integration runs when the Astro\n * config is loaded, while the middleware module is evaluated in the server\n * runtime — a different process for built output — so module-level state set\n * by the integration is not visible to the middleware.\n */\nconst MIDDLEWARE_ENTRYPOINT = '@tenphi/tasty/ssr/astro-middleware';\nconst MIDDLEWARE_ENTRYPOINT_STATIC =\n '@tenphi/tasty/ssr/astro-middleware-static';\nconst MIDDLEWARE_ENTRYPOINT_EXTRACT =\n '@tenphi/tasty/ssr/astro-middleware-extract';\nconst MIDDLEWARE_ENTRYPOINT_EXTRACT_STATIC =\n '@tenphi/tasty/ssr/astro-middleware-extract-static';\n\nexport interface TastyIntegrationCSSOptions {\n /**\n * CSS delivery mode. Extraction only applies to prerendered builds.\n * Extracted CSS preserves resource URLs verbatim, so use absolute URLs or\n * data URLs. Root-relative URLs are also supported unless `assetsPrefix`\n * sends CSS to an external origin. The build rejects resource URLs whose\n * targets would change after extraction.\n */\n mode?: 'inline' | 'extract';\n}\n\nexport interface TastyIntegrationOptions {\n /**\n * Enable island hydration support.\n *\n * When `true` (default): injects a client hydration script via\n * `injectScript('before-hydration')` and sets `transferCache: true`\n * on the middleware. Islands skip the style pipeline during hydration.\n *\n * When `false`: no client JS is shipped and `transferCache` is set\n * to `false`. Use this for fully static sites without `client:*`\n * directives.\n */\n islands?: boolean;\n /** Configure inline or build-wide extracted CSS delivery. */\n css?: TastyIntegrationCSSOptions;\n}\n\n/**\n * Astro integration that automatically sets up Tasty SSR.\n *\n * Registers middleware for cross-component CSS deduplication and\n * optionally injects a client hydration script for island support.\n *\n * @example Basic setup (with islands)\n * ```ts\n * // astro.config.mjs\n * import { tastyIntegration } from '@tenphi/tasty/ssr/astro';\n *\n * export default defineConfig({\n * integrations: [tastyIntegration()],\n * });\n * ```\n *\n * @example Static-only (no client JS)\n * ```ts\n * // astro.config.mjs\n * import { tastyIntegration } from '@tenphi/tasty/ssr/astro';\n *\n * export default defineConfig({\n * integrations: [tastyIntegration({ islands: false })],\n * });\n * ```\n */\nexport function tastyIntegration(options?: TastyIntegrationOptions) {\n const { islands = true } = options ?? {};\n const cssMode = options?.css?.mode ?? 'inline';\n let base = '/';\n let assets = '_astro';\n let assetsPrefix: string | Record<string, string> | undefined;\n let site: URL | undefined;\n\n return {\n name: '@tenphi/tasty',\n hooks: {\n 'astro:config:setup': ({\n addMiddleware,\n injectScript,\n }: {\n addMiddleware: (middleware: {\n entrypoint: string | URL;\n order: 'pre' | 'post';\n }) => void;\n injectScript: (\n stage: 'head-inline' | 'before-hydration' | 'page' | 'page-ssr',\n content: string,\n ) => void;\n }) => {\n addMiddleware({\n entrypoint:\n cssMode === 'extract'\n ? islands\n ? MIDDLEWARE_ENTRYPOINT_EXTRACT\n : MIDDLEWARE_ENTRYPOINT_EXTRACT_STATIC\n : islands\n ? MIDDLEWARE_ENTRYPOINT\n : MIDDLEWARE_ENTRYPOINT_STATIC,\n order: 'pre',\n });\n\n if (islands) {\n injectScript(\n 'before-hydration',\n `import \"@tenphi/tasty/ssr/astro-client\";`,\n );\n }\n },\n 'astro:config:done': ({\n config,\n }: {\n config: {\n base?: string;\n site?: URL;\n build?: {\n assets?: string;\n assetsPrefix?: string | Record<string, string>;\n };\n };\n }) => {\n base = config.base ?? '/';\n assets = config.build?.assets ?? '_astro';\n assetsPrefix = config.build?.assetsPrefix;\n site = config.site;\n },\n 'astro:build:done': async ({ dir }: { dir: URL }) => {\n if (cssMode !== 'extract') return;\n await extractAstroCSS({ dir, base, assets, assetsPrefix, site });\n },\n },\n };\n}\n"],"mappings":";;;;;;;;;AAQA,MAAM,iBAAiB;AACvB,MAAM,eAAe;AAWrB,SAAgB,yBACd,WACQ;CAIR,OAAO,GAAG,iBAHM,OAAO,KAAK,KAAK,UAAU,SAAS,GAAG,MAAM,CAAC,CAAC,SAC7D,QAE+B,IAAI;AACvC;AAEA,SAAS,qBACP,MACA,MACwB;CACxB,MAAM,gBAAgB,KAAK,QAAQ,cAAc;CACjD,IAAI,kBAAkB,IAAI,OAAO;CAEjC,MAAM,uBAAuB,gBAAgB;CAC7C,MAAM,cAAc,KAAK,QAAQ,cAAc,oBAAoB;CACnE,IAAI,gBAAgB,IAAI,OAAO;CAE/B,MAAM,UAAU,KAAK,MAAM,sBAAsB,WAAW;CAC5D,IAAI;CACJ,IAAI;EACF,YAAY,KAAK,MACf,OAAO,KAAK,SAAS,QAAQ,CAAC,CAAC,SAAS,MAAM,CAChD;CACF,QAAQ;EACN,OAAO;CACT;CAEA,MAAM,aAAa,KAAK,YAAY,yBAAyB,aAAa;CAC1E,IAAI,eAAe,IAAI,OAAO;CAC9B,MAAM,eAAe,KAAK,QAAQ,KAAK,UAAU;CACjD,MAAM,WAAW,KAAK,QAAQ,YAAY,eAAe,CAAC;CAC1D,IACE,iBAAiB,MACjB,aAAa,MACb,WAAW,MAAsB,eAEjC,OAAO;CAGT,OAAO;EACL;EACA;EACA;EACA;EACA,gBAAgB,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
4
|
-
|
|
1
|
+
import { i as ServerStyleArtifactKind, n as createServerStyleCollector, r as ServerStyleArtifact, t as ServerStyleCollector } from "../collector-hl5KNH7k.js";
|
|
2
|
+
|
|
3
|
+
//#region src/ssr/async-storage.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Run a function with a ServerStyleCollector bound to the current
|
|
6
|
+
* async context. All useStyles() calls within `fn` (and any async
|
|
7
|
+
* continuations) will find this collector via getSSRCollector().
|
|
8
|
+
*/
|
|
9
|
+
declare function runWithCollector<T>(collector: ServerStyleCollector, fn: () => T): T;
|
|
10
|
+
/**
|
|
11
|
+
* Retrieve the ServerStyleCollector bound to the current async context.
|
|
12
|
+
* Returns null when called outside of runWithCollector() or on the client.
|
|
13
|
+
*/
|
|
14
|
+
declare function getSSRCollector(): ServerStyleCollector | null;
|
|
15
|
+
//#endregion
|
|
16
|
+
//#region src/ssr/hydrate.d.ts
|
|
17
|
+
/**
|
|
18
|
+
* Client-side cache hydration for SSR/RSC.
|
|
19
|
+
*
|
|
20
|
+
* Registers class names rendered on the server with the client injector. If
|
|
21
|
+
* the runtime is not initialized yet, registration is deferred until its first
|
|
22
|
+
* use. With hash-based naming, only the class name list needs to cross the
|
|
23
|
+
* wire — no cache keys or counters.
|
|
24
|
+
*/
|
|
25
|
+
/**
|
|
26
|
+
* Hydrate the client-side style registry from the server's class name list.
|
|
27
|
+
*
|
|
28
|
+
* Call this before ReactDOM.hydrateRoot() or ensure it runs before
|
|
29
|
+
* any tasty() component renders on the client.
|
|
30
|
+
*
|
|
31
|
+
* When called without arguments, reads the class list from `window.__TASTY__`
|
|
32
|
+
* (populated by inline scripts emitted during SSR/RSC streaming).
|
|
33
|
+
*/
|
|
34
|
+
declare function hydrateTastyClasses(classes?: string[]): void;
|
|
35
|
+
//#endregion
|
|
36
|
+
export { type ServerStyleArtifact, type ServerStyleArtifactKind, ServerStyleCollector, createServerStyleCollector, getSSRCollector, hydrateTastyClasses, runWithCollector };
|
|
37
|
+
//# sourceMappingURL=index.d.ts.map
|
package/dist/ssr/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { ServerStyleCollector } from "
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
1
|
+
import { r as registerSSRCollectorGetterGlobal } from "../chunks/runtime-state-BTDqSYBk.js";
|
|
2
|
+
import { n as createServerStyleCollector, t as ServerStyleCollector } from "../chunks/collector-B0LTHw6Z.js";
|
|
3
|
+
import { n as runWithCollector, t as getSSRCollector } from "../chunks/async-storage-CG5HnUT5.js";
|
|
4
|
+
import { t as hydrateTastyClasses } from "../chunks/hydration-TRcz5vnk.js";
|
|
5
5
|
//#region src/ssr/index.ts
|
|
6
|
-
|
|
6
|
+
registerSSRCollectorGetterGlobal(getSSRCollector);
|
|
7
7
|
//#endregion
|
|
8
|
-
export { ServerStyleCollector, getSSRCollector,
|
|
8
|
+
export { ServerStyleCollector, createServerStyleCollector, getSSRCollector, hydrateTastyClasses, runWithCollector };
|
|
9
9
|
|
|
10
10
|
//# sourceMappingURL=index.js.map
|
package/dist/ssr/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/ssr/index.ts"],"sourcesContent":["/**\n * SSR entry point for @tenphi/tasty.\n *\n * Provides the core SSR infrastructure: ServerStyleCollector,\n * AsyncLocalStorage integration, and cache hydration.\n *\n * Import from '@tenphi/tasty/ssr'.\n */\n\n// Core collector\nexport { ServerStyleCollector } from './collector';\nexport type {
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/ssr/index.ts"],"sourcesContent":["/**\n * SSR entry point for @tenphi/tasty.\n *\n * Provides the core SSR infrastructure: ServerStyleCollector,\n * AsyncLocalStorage integration, and cache hydration.\n *\n * Import from '@tenphi/tasty/ssr'.\n */\n\n// Core collector\nexport { ServerStyleCollector, createServerStyleCollector } from './collector';\nexport type { ServerStyleArtifact, ServerStyleArtifactKind } from './collector';\n\n// AsyncLocalStorage integration for Astro / generic frameworks\nexport { runWithCollector, getSSRCollector } from './async-storage';\n\n// Client-side cache hydration\nexport { hydrateTastyClasses } from './hydrate';\n\n// Register the ALS getter so hooks can find the collector\n// without importing 'node:async_hooks' in the browser bundle.\n// Uses globalThis so the getter is visible across separate module graphs.\nimport { getSSRCollector } from './async-storage';\nimport { registerSSRCollectorGetterGlobal } from './ssr-collector-ref';\n\nregisterSSRCollectorGetterGlobal(getSSRCollector);\n"],"mappings":";;;;;AAyBA,iCAAiC,eAAe"}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { t as TastyConfig } from "../config-DWL1ZYue.js";
|
|
2
|
+
|
|
3
|
+
//#region src/ssr/next-config.d.ts
|
|
4
|
+
interface NextConfig {
|
|
5
|
+
basePath?: string;
|
|
6
|
+
env?: Record<string, string | undefined>;
|
|
7
|
+
headers?: () => Promise<NextHeader[]>;
|
|
8
|
+
output?: string;
|
|
9
|
+
[key: string]: unknown;
|
|
10
|
+
}
|
|
11
|
+
interface NextHeader {
|
|
12
|
+
source: string;
|
|
13
|
+
headers: {
|
|
14
|
+
key: string;
|
|
15
|
+
value: string;
|
|
16
|
+
}[];
|
|
17
|
+
[key: string]: unknown;
|
|
18
|
+
}
|
|
19
|
+
interface TastyNextOptions {
|
|
20
|
+
/**
|
|
21
|
+
* Next.js project directory. Useful when the build command runs from a
|
|
22
|
+
* monorepo root rather than the app directory.
|
|
23
|
+
*
|
|
24
|
+
* @default process.cwd()
|
|
25
|
+
*/
|
|
26
|
+
rootDir?: string;
|
|
27
|
+
/**
|
|
28
|
+
* Tasty configuration used to generate the shared stylesheet.
|
|
29
|
+
* `config` takes precedence when both config sources are provided.
|
|
30
|
+
*/
|
|
31
|
+
config?: TastyConfig;
|
|
32
|
+
/**
|
|
33
|
+
* Project-relative path to a TypeScript/JavaScript module whose default
|
|
34
|
+
* export is a Tasty configuration object.
|
|
35
|
+
*
|
|
36
|
+
* @example './app/tasty.config.ts'
|
|
37
|
+
*/
|
|
38
|
+
configFile?: string;
|
|
39
|
+
/**
|
|
40
|
+
* Filesystem directory for generated stylesheets. When it is inside the
|
|
41
|
+
* project's `public` directory, its public URL is inferred automatically.
|
|
42
|
+
*
|
|
43
|
+
* @default 'public/_tasty'
|
|
44
|
+
*/
|
|
45
|
+
outputDir?: string;
|
|
46
|
+
/**
|
|
47
|
+
* Root-relative URL path corresponding to `outputDir`. This is required
|
|
48
|
+
* when `outputDir` is outside the project's `public` directory.
|
|
49
|
+
* The Next.js `basePath` is prepended automatically.
|
|
50
|
+
*
|
|
51
|
+
* @default inferred from outputDir
|
|
52
|
+
* @example '/assets/tasty'
|
|
53
|
+
*/
|
|
54
|
+
publicPath?: string;
|
|
55
|
+
/** Whether to generate and register the shared stylesheet. @default true */
|
|
56
|
+
enabled?: boolean;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Add a cacheable, content-hashed stylesheet for Tasty configuration globals.
|
|
60
|
+
* Route-dependent component and hook styles continue to stream through
|
|
61
|
+
* `TastyRegistry` so App Router navigation and Suspense remain correct.
|
|
62
|
+
*/
|
|
63
|
+
declare function withTastyNext(options: TastyNextOptions): (nextConfig?: NextConfig) => NextConfig;
|
|
64
|
+
//#endregion
|
|
65
|
+
export { TastyNextOptions, withTastyNext };
|
|
66
|
+
//# sourceMappingURL=next-config.d.ts.map
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { L as DEFAULT_PROPERTIES, U as parseFunctionName, V as formatFunctionRule, a as formatPropertyCSS, b as formatFontFaceRule, h as formatCounterStyleRule, n as formatGlobalRules, t as createServerStyleArtifact, v as fontFaceContentHash } from "../chunks/css-definitions-D_it4XZH.js";
|
|
2
|
+
import { b as renderStyles } from "../chunks/style-engine-C1ECBZxR.js";
|
|
3
|
+
import { n as functionsForExtraction, r as resetZeroConfig, t as configureZero } from "../chunks/build-config-CUQVwdWF.js";
|
|
4
|
+
import { t as findUnsafeCSSResource } from "../chunks/css-resources-BN8apgxt.js";
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
6
|
+
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { createRequire } from "node:module";
|
|
8
|
+
import { isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
9
|
+
//#region src/ssr/next-config.ts
|
|
10
|
+
const ENV_KEY = "TASTY_NEXT_SHARED_CSS_HREF";
|
|
11
|
+
const packageRequire = createRequire(import.meta.url);
|
|
12
|
+
function loadConfig(projectDir, options) {
|
|
13
|
+
if (options.config) return options.config;
|
|
14
|
+
if (!options.configFile) throw new Error("[Tasty] withTastyNext() requires either `config` or `configFile`.");
|
|
15
|
+
const configPath = resolve(projectDir, options.configFile);
|
|
16
|
+
let jitiPath;
|
|
17
|
+
try {
|
|
18
|
+
jitiPath = packageRequire.resolve("jiti");
|
|
19
|
+
} catch (error) {
|
|
20
|
+
if (error instanceof Error && "code" in error && error.code === "MODULE_NOT_FOUND") throw new Error("[Tasty] `configFile` requires the optional `jiti` package. Install `jiti` or pass the imported config through `config` instead.", { cause: error });
|
|
21
|
+
throw error;
|
|
22
|
+
}
|
|
23
|
+
const { createJiti } = packageRequire(jitiPath);
|
|
24
|
+
const loaded = createJiti(projectDir, { moduleCache: false })(configPath);
|
|
25
|
+
return loaded && typeof loaded === "object" && "default" in loaded ? loaded.default : loaded;
|
|
26
|
+
}
|
|
27
|
+
function collectSharedCSS(config) {
|
|
28
|
+
resetZeroConfig();
|
|
29
|
+
try {
|
|
30
|
+
const resolved = configureZero(config);
|
|
31
|
+
const { normalized } = resolved;
|
|
32
|
+
const artifacts = [];
|
|
33
|
+
const append = (kind, key, css) => {
|
|
34
|
+
if (!css) return;
|
|
35
|
+
artifacts.push(createServerStyleArtifact(kind, key, css, artifacts.length));
|
|
36
|
+
};
|
|
37
|
+
for (const [token, definition] of Object.entries({
|
|
38
|
+
...DEFAULT_PROPERTIES,
|
|
39
|
+
...normalized.properties
|
|
40
|
+
})) append("property", `__prop:${token}`, formatPropertyCSS(token, definition));
|
|
41
|
+
for (const [family, input] of Object.entries(normalized.fontFaces)) {
|
|
42
|
+
const descriptors = Array.isArray(input) ? input : [input];
|
|
43
|
+
for (const descriptor of descriptors) append("font-face", fontFaceContentHash(family, descriptor), formatFontFaceRule(family, descriptor));
|
|
44
|
+
}
|
|
45
|
+
for (const [name, descriptors] of Object.entries(normalized.counterStyles)) append("counter-style", name, formatCounterStyleRule(name, descriptors));
|
|
46
|
+
for (const [name, definition] of Object.entries(functionsForExtraction(resolved) ?? {})) append("function", parseFunctionName(name), formatFunctionRule(name, definition));
|
|
47
|
+
if (Object.keys(normalized.tokens).length > 0) append("global", "__global:tokens", formatGlobalRules(renderStyles(normalized.tokens, ":root")));
|
|
48
|
+
for (const [selector, styles] of Object.entries(normalized.globalStyles)) {
|
|
49
|
+
if (Object.keys(styles).length === 0) continue;
|
|
50
|
+
const rules = renderStyles(styles, selector);
|
|
51
|
+
append("global", `__global:styles:${selector}`, formatGlobalRules(rules));
|
|
52
|
+
}
|
|
53
|
+
for (const artifact of artifacts) {
|
|
54
|
+
const unsafe = findUnsafeCSSResource(artifact.css, false);
|
|
55
|
+
if (unsafe) throw new Error(`[Tasty] Next.js shared CSS extraction cannot preserve page-relative CSS URL "${unsafe.url}" in ${artifact.kind} artifact ${artifact.id}. Use an absolute URL, a data URL, or a root-relative URL such as url(/path/to/asset).`);
|
|
56
|
+
}
|
|
57
|
+
return artifacts.map(({ css }) => css).join("\n");
|
|
58
|
+
} finally {
|
|
59
|
+
resetZeroConfig();
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
function inferPublicPath(projectDir, outputDir) {
|
|
63
|
+
const relativePath = relative(resolve(projectDir, "public"), outputDir);
|
|
64
|
+
if (relativePath === ".." || relativePath.startsWith(`..${sep}`) || isAbsolute(relativePath)) throw new Error("[Tasty] `publicPath` is required when `outputDir` is outside the Next.js public directory.");
|
|
65
|
+
return `/${relativePath.split(sep).filter(Boolean).join("/")}`;
|
|
66
|
+
}
|
|
67
|
+
function normalizeURLPath(path, option) {
|
|
68
|
+
if (!path.startsWith("/") || path.startsWith("//") || path.includes("?") || path.includes("#") || path.includes("\\")) throw new Error(`[Tasty] \`${option}\` must be a root-relative URL path.`);
|
|
69
|
+
let end = path.length;
|
|
70
|
+
while (end > 0 && path[end - 1] === "/") end--;
|
|
71
|
+
return path.slice(0, end);
|
|
72
|
+
}
|
|
73
|
+
function writeSharedCSS(outputDir, css) {
|
|
74
|
+
mkdirSync(outputDir, { recursive: true });
|
|
75
|
+
const filename = `tasty.shared.${createHash("sha256").update(css).digest("hex").slice(0, 12)}.css`;
|
|
76
|
+
const outputPath = join(outputDir, filename);
|
|
77
|
+
let existing;
|
|
78
|
+
try {
|
|
79
|
+
existing = readFileSync(outputPath, "utf8");
|
|
80
|
+
} catch {}
|
|
81
|
+
if (existing !== css) writeFileSync(outputPath, css);
|
|
82
|
+
return filename;
|
|
83
|
+
}
|
|
84
|
+
function withTastyNext(options) {
|
|
85
|
+
return (nextConfig = {}) => {
|
|
86
|
+
if (options.enabled === false) return nextConfig;
|
|
87
|
+
const projectDir = resolve(process.cwd(), options.rootDir ?? ".");
|
|
88
|
+
const outputDir = resolve(projectDir, options.outputDir ?? "public/_tasty");
|
|
89
|
+
const publicPath = normalizeURLPath(options.publicPath ?? inferPublicPath(projectDir, outputDir), "publicPath");
|
|
90
|
+
const basePath = normalizeURLPath(nextConfig.basePath || "/", "basePath");
|
|
91
|
+
const css = collectSharedCSS(loadConfig(projectDir, options));
|
|
92
|
+
if (!css) return nextConfig;
|
|
93
|
+
const filename = writeSharedCSS(outputDir, css);
|
|
94
|
+
const href = `${basePath}${publicPath}/${filename}`;
|
|
95
|
+
const headerSource = `${publicPath}/${filename}`;
|
|
96
|
+
const existingEnv = nextConfig.env ?? {};
|
|
97
|
+
const existingHeaders = nextConfig.headers;
|
|
98
|
+
if (existingEnv[ENV_KEY] && existingEnv[ENV_KEY] !== href) throw new Error(`[Tasty] Next.js env key ${ENV_KEY} is reserved by withTastyNext().`);
|
|
99
|
+
const generatedConfig = {
|
|
100
|
+
...nextConfig,
|
|
101
|
+
env: {
|
|
102
|
+
...existingEnv,
|
|
103
|
+
[ENV_KEY]: href
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
if (nextConfig.output === "export") return generatedConfig;
|
|
107
|
+
return {
|
|
108
|
+
...generatedConfig,
|
|
109
|
+
async headers() {
|
|
110
|
+
return [...existingHeaders ? await existingHeaders() : [], {
|
|
111
|
+
source: headerSource,
|
|
112
|
+
headers: [{
|
|
113
|
+
key: "Cache-Control",
|
|
114
|
+
value: "public, max-age=31536000, immutable"
|
|
115
|
+
}]
|
|
116
|
+
}];
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
//#endregion
|
|
122
|
+
export { withTastyNext };
|
|
123
|
+
|
|
124
|
+
//# sourceMappingURL=next-config.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"next-config.js","names":[],"sources":["../../src/ssr/next-config.ts"],"sourcesContent":["/**\n * Next.js configuration wrapper for extracting Tasty's configured global CSS.\n *\n * Import this Node-only module from `next.config.ts`. The client-safe registry\n * remains available from `@tenphi/tasty/ssr/next`.\n */\n\nimport { createHash } from 'node:crypto';\nimport { mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { isAbsolute, join, relative, resolve, sep } from 'node:path';\nimport type { createJiti as createJitiType } from 'jiti';\n\nimport type { TastyConfig } 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 { DEFAULT_PROPERTIES } from '../properties/defaults';\nimport {\n configureZero,\n functionsForExtraction,\n resetZeroConfig,\n} from '../zero/config';\nimport { createServerStyleArtifact } from './artifacts';\nimport type { ServerStyleArtifact, ServerStyleArtifactKind } from './artifacts';\nimport { findUnsafeCSSResource } from './css-resources';\nimport { formatGlobalRules } from './format-global-rules';\nimport { formatPropertyCSS } from './format-property';\n\nconst ENV_KEY = 'TASTY_NEXT_SHARED_CSS_HREF';\nconst packageRequire = createRequire(import.meta.url);\n\ninterface NextConfig {\n basePath?: string;\n env?: Record<string, string | undefined>;\n headers?: () => Promise<NextHeader[]>;\n output?: string;\n [key: string]: unknown;\n}\n\ninterface NextHeader {\n source: string;\n headers: { key: string; value: string }[];\n [key: string]: unknown;\n}\n\nexport interface TastyNextOptions {\n /**\n * Next.js project directory. Useful when the build command runs from a\n * monorepo root rather than the app directory.\n *\n * @default process.cwd()\n */\n rootDir?: string;\n\n /**\n * Tasty configuration used to generate the shared stylesheet.\n * `config` takes precedence when both config sources are provided.\n */\n config?: TastyConfig;\n\n /**\n * Project-relative path to a TypeScript/JavaScript module whose default\n * export is a Tasty configuration object.\n *\n * @example './app/tasty.config.ts'\n */\n configFile?: string;\n\n /**\n * Filesystem directory for generated stylesheets. When it is inside the\n * project's `public` directory, its public URL is inferred automatically.\n *\n * @default 'public/_tasty'\n */\n outputDir?: string;\n\n /**\n * Root-relative URL path corresponding to `outputDir`. This is required\n * when `outputDir` is outside the project's `public` directory.\n * The Next.js `basePath` is prepended automatically.\n *\n * @default inferred from outputDir\n * @example '/assets/tasty'\n */\n publicPath?: string;\n\n /** Whether to generate and register the shared stylesheet. @default true */\n enabled?: boolean;\n}\n\nfunction loadConfig(\n projectDir: string,\n options: TastyNextOptions,\n): TastyConfig {\n if (options.config) return options.config;\n if (!options.configFile) {\n throw new Error(\n '[Tasty] withTastyNext() requires either `config` or `configFile`.',\n );\n }\n\n const configPath = resolve(projectDir, options.configFile);\n let jitiPath: string;\n try {\n jitiPath = packageRequire.resolve('jiti');\n } catch (error) {\n if (\n error instanceof Error &&\n 'code' in error &&\n error.code === 'MODULE_NOT_FOUND'\n ) {\n throw new Error(\n '[Tasty] `configFile` requires the optional `jiti` package. Install `jiti` or pass the imported config through `config` instead.',\n { cause: error },\n );\n }\n throw error;\n }\n const { createJiti } = packageRequire(jitiPath) as {\n createJiti: typeof createJitiType;\n };\n const jiti = createJiti(projectDir, { moduleCache: false });\n const loaded = jiti(configPath) as TastyConfig | { default: TastyConfig };\n\n return loaded && typeof loaded === 'object' && 'default' in loaded\n ? loaded.default\n : loaded;\n}\n\nfunction collectSharedCSS(config: TastyConfig): string {\n resetZeroConfig();\n try {\n const resolved = configureZero(config);\n const { normalized } = resolved;\n const artifacts: ServerStyleArtifact[] = [];\n const append = (\n kind: ServerStyleArtifactKind,\n key: string,\n css: string,\n ) => {\n if (!css) return;\n\n artifacts.push(\n createServerStyleArtifact(kind, key, css, artifacts.length),\n );\n };\n\n for (const [token, definition] of Object.entries({\n ...DEFAULT_PROPERTIES,\n ...normalized.properties,\n })) {\n append(\n 'property',\n `__prop:${token}`,\n formatPropertyCSS(token, definition),\n );\n }\n\n for (const [family, input] of Object.entries(normalized.fontFaces)) {\n const descriptors = Array.isArray(input) ? input : [input];\n for (const descriptor of descriptors) {\n append(\n 'font-face',\n fontFaceContentHash(family, descriptor),\n formatFontFaceRule(family, descriptor),\n );\n }\n }\n\n for (const [name, descriptors] of Object.entries(\n normalized.counterStyles,\n )) {\n append('counter-style', name, formatCounterStyleRule(name, descriptors));\n }\n\n for (const [name, definition] of Object.entries(\n functionsForExtraction(resolved) ?? {},\n )) {\n append(\n 'function',\n parseFunctionName(name),\n formatFunctionRule(name, definition),\n );\n }\n\n if (Object.keys(normalized.tokens).length > 0) {\n const rules = renderStyles(normalized.tokens, ':root') as StyleResult[];\n append('global', '__global:tokens', formatGlobalRules(rules));\n }\n\n for (const [selector, styles] of Object.entries(normalized.globalStyles)) {\n if (Object.keys(styles).length === 0) continue;\n const rules = renderStyles(styles, selector) as StyleResult[];\n append('global', `__global:styles:${selector}`, formatGlobalRules(rules));\n }\n\n for (const artifact of artifacts) {\n const unsafe = findUnsafeCSSResource(artifact.css, false);\n if (unsafe) {\n throw new Error(\n `[Tasty] Next.js shared CSS extraction cannot preserve page-relative CSS URL \"${unsafe.url}\" in ${artifact.kind} artifact ${artifact.id}. Use an absolute URL, a data URL, or a root-relative URL such as url(/path/to/asset).`,\n );\n }\n }\n\n return artifacts.map(({ css }) => css).join('\\n');\n } finally {\n resetZeroConfig();\n }\n}\n\nfunction inferPublicPath(projectDir: string, outputDir: string): string {\n const publicDir = resolve(projectDir, 'public');\n const relativePath = relative(publicDir, outputDir);\n if (\n relativePath === '..' ||\n relativePath.startsWith(`..${sep}`) ||\n isAbsolute(relativePath)\n ) {\n throw new Error(\n '[Tasty] `publicPath` is required when `outputDir` is outside the Next.js public directory.',\n );\n }\n\n return `/${relativePath.split(sep).filter(Boolean).join('/')}`;\n}\n\nfunction normalizeURLPath(path: string, option: string): string {\n if (\n !path.startsWith('/') ||\n path.startsWith('//') ||\n path.includes('?') ||\n path.includes('#') ||\n path.includes('\\\\')\n ) {\n throw new Error(`[Tasty] \\`${option}\\` must be a root-relative URL path.`);\n }\n\n let end = path.length;\n while (end > 0 && path[end - 1] === '/') end--;\n return path.slice(0, end);\n}\n\nfunction writeSharedCSS(outputDir: string, css: string): string {\n mkdirSync(outputDir, { recursive: true });\n const hash = createHash('sha256').update(css).digest('hex').slice(0, 12);\n const filename = `tasty.shared.${hash}.css`;\n\n const outputPath = join(outputDir, filename);\n let existing: string | undefined;\n try {\n existing = readFileSync(outputPath, 'utf8');\n } catch {\n // The file does not exist yet (or is unreadable); write it below.\n }\n if (existing !== css) writeFileSync(outputPath, css);\n\n return filename;\n}\n\n/**\n * Add a cacheable, content-hashed stylesheet for Tasty configuration globals.\n * Route-dependent component and hook styles continue to stream through\n * `TastyRegistry` so App Router navigation and Suspense remain correct.\n */\nexport function withTastyNext(options: TastyNextOptions) {\n return (nextConfig: NextConfig = {}): NextConfig => {\n if (options.enabled === false) return nextConfig;\n\n const projectDir = resolve(process.cwd(), options.rootDir ?? '.');\n const outputDir = resolve(projectDir, options.outputDir ?? 'public/_tasty');\n const publicPath = normalizeURLPath(\n options.publicPath ?? inferPublicPath(projectDir, outputDir),\n 'publicPath',\n );\n const basePath = normalizeURLPath(nextConfig.basePath || '/', 'basePath');\n const css = collectSharedCSS(loadConfig(projectDir, options));\n\n if (!css) return nextConfig;\n\n const filename = writeSharedCSS(outputDir, css);\n const href = `${basePath}${publicPath}/${filename}`;\n const headerSource = `${publicPath}/${filename}`;\n const existingEnv = nextConfig.env ?? {};\n const existingHeaders = nextConfig.headers;\n if (existingEnv[ENV_KEY] && existingEnv[ENV_KEY] !== href) {\n throw new Error(\n `[Tasty] Next.js env key ${ENV_KEY} is reserved by withTastyNext().`,\n );\n }\n\n const generatedConfig: NextConfig = {\n ...nextConfig,\n env: {\n ...existingEnv,\n [ENV_KEY]: href,\n },\n };\n\n // `headers()` is not emitted by Next's static export. Avoid introducing an\n // unsupported-config warning; the content hash still makes the asset safe\n // for the static host to cache immutably.\n if (nextConfig.output === 'export') return generatedConfig;\n\n return {\n ...generatedConfig,\n async headers() {\n const headers = existingHeaders ? await existingHeaders() : [];\n return [\n ...headers,\n {\n source: headerSource,\n headers: [\n {\n key: 'Cache-Control',\n value: 'public, max-age=31536000, immutable',\n },\n ],\n },\n ];\n },\n };\n };\n}\n"],"mappings":";;;;;;;;;AA+BA,MAAM,UAAU;AAChB,MAAM,iBAAiB,cAAc,OAAO,KAAK,GAAG;AA6DpD,SAAS,WACP,YACA,SACa;CACb,IAAI,QAAQ,QAAQ,OAAO,QAAQ;CACnC,IAAI,CAAC,QAAQ,YACX,MAAM,IAAI,MACR,mEACF;CAGF,MAAM,aAAa,QAAQ,YAAY,QAAQ,UAAU;CACzD,IAAI;CACJ,IAAI;EACF,WAAW,eAAe,QAAQ,MAAM;CAC1C,SAAS,OAAO;EACd,IACE,iBAAiB,SACjB,UAAU,SACV,MAAM,SAAS,oBAEf,MAAM,IAAI,MACR,mIACA,EAAE,OAAO,MAAM,CACjB;EAEF,MAAM;CACR;CACA,MAAM,EAAE,e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