@demiurgejs/core 0.2.0-beta.4 → 0.2.0-beta.5
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 +23 -0
- package/bin/demiurge.mjs +17 -1
- package/dist/adapter/index.d.ts +1 -1
- package/dist/adapter/index.d.ts.map +1 -1
- package/dist/browser/file-router.d.ts +1 -1
- package/dist/chunks/{document-shell-CpJnFtSC.js → document-shell-9GPwtcTt.js} +2 -2
- package/dist/chunks/{document-shell-CpJnFtSC.js.map → document-shell-9GPwtcTt.js.map} +1 -1
- package/dist/chunks/{image-codec-BmzWnH6W.js → image-codec-Dh1POFhE.js} +2 -2
- package/dist/chunks/{image-codec-BmzWnH6W.js.map → image-codec-Dh1POFhE.js.map} +1 -1
- package/dist/chunks/{images-BQ80950B.js → images-CG7ZzayG.js} +2 -2
- package/dist/chunks/{images-BQ80950B.js.map → images-CG7ZzayG.js.map} +1 -1
- package/dist/chunks/{index-BVk9zWbe.js → index-0MNiR_wo.js} +4 -3
- package/dist/chunks/{index-BVk9zWbe.js.map → index-0MNiR_wo.js.map} +1 -1
- package/dist/chunks/plugin-BZauDxRY.js +2310 -0
- package/dist/chunks/plugin-BZauDxRY.js.map +1 -0
- package/dist/chunks/streaming-GYIsVTQH.js +560 -0
- package/dist/chunks/streaming-GYIsVTQH.js.map +1 -0
- package/dist/chunks/testing-CUwGj2ie.js +4751 -0
- package/dist/chunks/testing-CUwGj2ie.js.map +1 -0
- package/dist/chunks/{vite-DO70kZA6.js → vite-QoqrGl6f.js} +43 -43
- package/dist/chunks/vite-QoqrGl6f.js.map +1 -0
- package/dist/cli.d.ts +4 -2
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +224 -98
- package/dist/cli.js.map +1 -1
- package/dist/config/index.js +2 -2
- package/dist/config/types.d.ts +11 -1
- package/dist/config/types.d.ts.map +1 -1
- package/dist/edge/index.js +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +161 -139
- package/dist/index.js.map +1 -1
- package/dist/inspect/command.d.ts +28 -0
- package/dist/inspect/command.d.ts.map +1 -0
- package/dist/inspect/index.d.ts +9 -0
- package/dist/inspect/index.d.ts.map +1 -0
- package/dist/inspect/redact.d.ts +35 -0
- package/dist/inspect/redact.d.ts.map +1 -0
- package/dist/inspect/report.d.ts +24 -0
- package/dist/inspect/report.d.ts.map +1 -0
- package/dist/inspect/types.d.ts +102 -0
- package/dist/inspect/types.d.ts.map +1 -0
- package/dist/internal/testing.js +12 -12
- package/dist/node/http.d.ts +5 -0
- package/dist/node/http.d.ts.map +1 -1
- package/dist/node/index.d.ts +1 -1
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +26 -24
- package/dist/node/index.js.map +1 -1
- package/dist/route/index.d.ts +1 -0
- package/dist/route/index.d.ts.map +1 -1
- package/dist/route/mutation.d.ts.map +1 -1
- package/dist/route/serialization.d.ts +24 -0
- package/dist/route/serialization.d.ts.map +1 -0
- package/dist/route/webhook.d.ts +6 -1
- package/dist/route/webhook.d.ts.map +1 -1
- package/dist/router/manifest.d.ts.map +1 -1
- package/dist/security/audit.d.ts +2 -1
- package/dist/security/audit.d.ts.map +1 -1
- package/dist/security/authorization.d.ts +36 -0
- package/dist/security/authorization.d.ts.map +1 -0
- package/dist/security/csrf.d.ts.map +1 -1
- package/dist/security/env-startup.d.ts +0 -2
- package/dist/security/env-startup.d.ts.map +1 -1
- package/dist/security/env.d.ts +27 -8
- package/dist/security/env.d.ts.map +1 -1
- package/dist/security/exceptions.d.ts +29 -0
- package/dist/security/exceptions.d.ts.map +1 -0
- package/dist/security/finding-codes.d.ts +56 -0
- package/dist/security/finding-codes.d.ts.map +1 -0
- package/dist/security/index.d.ts +5 -2
- package/dist/security/index.d.ts.map +1 -1
- package/dist/security/policy.d.ts +2 -5
- package/dist/security/policy.d.ts.map +1 -1
- package/dist/security/report.d.ts +2 -1
- package/dist/security/report.d.ts.map +1 -1
- package/dist/security/request.d.ts +1 -0
- package/dist/security/request.d.ts.map +1 -1
- package/dist/security/types.d.ts +138 -5
- package/dist/security/types.d.ts.map +1 -1
- package/dist/security/upload.d.ts +3 -3
- package/dist/security/upload.d.ts.map +1 -1
- package/dist/security/verification.d.ts.map +1 -1
- package/dist/server/request-handler.d.ts +3 -2
- package/dist/server/request-handler.d.ts.map +1 -1
- package/dist/server-only/browser.d.ts +2 -0
- package/dist/server-only/browser.d.ts.map +1 -0
- package/dist/server-only/browser.js +4 -0
- package/dist/server-only/browser.js.map +1 -0
- package/dist/server-only/index.d.ts +2 -0
- package/dist/server-only/index.d.ts.map +1 -0
- package/dist/server-only/index.js +2 -0
- package/dist/server-only/index.js.map +1 -0
- package/dist/static/index.js +4 -4
- package/dist/vite/index.d.ts +9 -4
- package/dist/vite/index.d.ts.map +1 -1
- package/dist/vite/index.js +28 -21
- package/dist/vite/plugin.d.ts +18 -2
- package/dist/vite/plugin.d.ts.map +1 -1
- package/dist/vite/policy-verification.d.ts +33 -2
- package/dist/vite/policy-verification.d.ts.map +1 -1
- package/dist/vite/route-audit.d.ts +14 -2
- package/dist/vite/route-audit.d.ts.map +1 -1
- package/dist/vite/server-only-boundary.d.ts +8 -0
- package/dist/vite/server-only-boundary.d.ts.map +1 -0
- package/package.json +6 -1
- package/dist/chunks/env-startup-DOBYWlZD.js +0 -257
- package/dist/chunks/env-startup-DOBYWlZD.js.map +0 -1
- package/dist/chunks/plugin-BQgMiHxa.js +0 -1827
- package/dist/chunks/plugin-BQgMiHxa.js.map +0 -1
- package/dist/chunks/streaming-BEbPN7Uk.js +0 -469
- package/dist/chunks/streaming-BEbPN7Uk.js.map +0 -1
- package/dist/chunks/testing-DueXbMo4.js +0 -4167
- package/dist/chunks/testing-DueXbMo4.js.map +0 -1
- package/dist/chunks/vite-DO70kZA6.js.map +0 -1
package/README.md
CHANGED
|
@@ -77,6 +77,29 @@ covers host allowlists, proxy trust, timeouts, and graceful shutdown.
|
|
|
77
77
|
Vite is an optional peer dependency with `@vitejs/plugin-react`. A consumer
|
|
78
78
|
that only runs the built output does not install them.
|
|
79
79
|
|
|
80
|
+
## Export prefixes
|
|
81
|
+
|
|
82
|
+
The package uses three levels for an export name. The two prefixes describe
|
|
83
|
+
different properties, so one name can carry both.
|
|
84
|
+
|
|
85
|
+
| Prefix | Promise |
|
|
86
|
+
| --- | --- |
|
|
87
|
+
| none | The name is stable. Demiurge changes it under the semantic version policy of the package. |
|
|
88
|
+
| `unstable_` | The shape can change in any release. A consumer accepts that risk. |
|
|
89
|
+
| `unsafe_` | Use of the export moves a framework guarantee to the application. The shape can still be stable. |
|
|
90
|
+
|
|
91
|
+
A type and the function that returns it carry the same prefix. The function
|
|
92
|
+
`unstable_createRouteAudit` therefore returns `unstable_RouteAudit`.
|
|
93
|
+
|
|
94
|
+
A name leaves the `unstable_` prefix when it meets three conditions. An
|
|
95
|
+
accepted decision record describes the interface. The report of the interface
|
|
96
|
+
states a version. A packed-consumer test covers the interface.
|
|
97
|
+
|
|
98
|
+
The `unsafe_` prefix does not describe maturity, so a name never leaves it.
|
|
99
|
+
[ADR 0019](https://github.com/NorthShoreSoftwareLabs/demiurge/blob/main/architecture/decisions/0019-versioned-inspection-interfaces.md)
|
|
100
|
+
records these levels.
|
|
101
|
+
|
|
102
|
+
|
|
80
103
|
## Support and license
|
|
81
104
|
|
|
82
105
|
Report defects through [GitHub Issues](https://github.com/NorthShoreSoftwareLabs/demiurge/issues).
|
package/bin/demiurge.mjs
CHANGED
|
@@ -9,6 +9,7 @@ import {
|
|
|
9
9
|
resolvePreviewOutputDirectory,
|
|
10
10
|
runBuild,
|
|
11
11
|
runDev,
|
|
12
|
+
runInspectCommand,
|
|
12
13
|
} from "../dist/cli.js";
|
|
13
14
|
import { loadDemiurgeConfig } from "../dist/config/index.js";
|
|
14
15
|
import {
|
|
@@ -16,7 +17,22 @@ import {
|
|
|
16
17
|
} from "../dist/static/index.js";
|
|
17
18
|
|
|
18
19
|
async function main() {
|
|
19
|
-
const
|
|
20
|
+
const commandArguments = process.argv.slice(2);
|
|
21
|
+
|
|
22
|
+
// The inspect command owns its exit codes and its problem document, so it
|
|
23
|
+
// runs before the shared argument parser and the shared configuration load.
|
|
24
|
+
if (commandArguments[0] === "inspect") {
|
|
25
|
+
const result = await runInspectCommand({
|
|
26
|
+
arguments: commandArguments.slice(1),
|
|
27
|
+
loadConfig: () => loadDemiurgeConfig(),
|
|
28
|
+
});
|
|
29
|
+
console.error(result.stderr);
|
|
30
|
+
console.log(result.stdout);
|
|
31
|
+
process.exitCode = result.exitCode;
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const options = parseCliArguments(commandArguments, process.env);
|
|
20
36
|
|
|
21
37
|
if (options.command === "help") {
|
|
22
38
|
console.log(helpText);
|
package/dist/adapter/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export type AdapterCapability = "backgroundLifetime" | "crossOriginIsolationHeaders" | "nonceInjection" | "sharedCache" | "staticOutput" | "streaming" | "webSocket" | "webTransport";
|
|
1
|
+
export type AdapterCapability = "backgroundLifetime" | "crossOriginIsolationHeaders" | "nonceInjection" | "requestTimeoutEnforcement" | "sharedCache" | "staticOutput" | "streaming" | "webSocket" | "webTransport";
|
|
2
2
|
export type AdapterCapabilityMap = Record<AdapterCapability, boolean>;
|
|
3
3
|
export type Adapter = {
|
|
4
4
|
capabilities: AdapterCapabilityMap;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/adapter/index.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,iBAAiB,GACzB,oBAAoB,GACpB,6BAA6B,GAC7B,gBAAgB,GAChB,aAAa,GACb,cAAc,GACd,WAAW,GACX,WAAW,GACX,cAAc,CAAC;AAEnB,MAAM,MAAM,oBAAoB,GAAG,MAAM,CAAC,iBAAiB,EAAE,OAAO,CAAC,CAAC;AAEtE,MAAM,MAAM,OAAO,G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AO,EAChB,QAAQ,EAAE,SAAS,iBAAiB,EAAE,GACrC,sBAAsB,CAYxB;AAED,wBAAgB,yBAAyB,CACvC,OAAO,EAAE,OAAO,EAChB,QAAQ,EAAE,SAAS,iBAAiB,EAAE,0BAWvC"}
|
|
@@ -112,11 +112,11 @@ export declare function MutationSubmit(props: MutationSubmitProps): import("reac
|
|
|
112
112
|
value?: string | number | readonly string[] | undefined;
|
|
113
113
|
name?: string | undefined | undefined;
|
|
114
114
|
style?: import("react").CSSProperties | undefined;
|
|
115
|
+
security?: string | undefined | undefined;
|
|
115
116
|
title?: string | undefined | undefined;
|
|
116
117
|
type?: "submit" | "reset" | "button" | undefined | undefined;
|
|
117
118
|
nonce?: string | undefined | undefined;
|
|
118
119
|
id?: string | undefined | undefined;
|
|
119
|
-
security?: string | undefined | undefined;
|
|
120
120
|
form?: string | undefined | undefined;
|
|
121
121
|
slot?: string | undefined | undefined;
|
|
122
122
|
children?: ReactNode;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { r as c } from "./index-
|
|
1
|
+
import { r as c } from "./index-0MNiR_wo.js";
|
|
2
2
|
const r = '<template data-demiurge-stream-root=""></template>';
|
|
3
3
|
async function i(t, e) {
|
|
4
4
|
const l = c({
|
|
@@ -33,4 +33,4 @@ async function i(t, e) {
|
|
|
33
33
|
export {
|
|
34
34
|
i as c
|
|
35
35
|
};
|
|
36
|
-
//# sourceMappingURL=document-shell-
|
|
36
|
+
//# sourceMappingURL=document-shell-9GPwtcTt.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"document-shell-
|
|
1
|
+
{"version":3,"file":"document-shell-9GPwtcTt.js","sources":["../../src/server/document-shell.ts"],"sourcesContent":["import { renderDocumentShell } from \"../document/render\";\nimport type { ScriptTag } from \"../document/scripts\";\nimport type { LoadedRouteMatch } from \"../router\";\nimport type { SsrRenderOptions } from \"./ssr\";\n\n// A streaming render sends the document head before the body exists. A\n// transform that rewrites the document therefore needs a placeholder where the\n// streamed body will go, and it has to leave that placeholder in place.\nexport const STREAM_ROOT_MARKER =\n '<template data-demiurge-stream-root=\"\"></template>';\n\nexport type DocumentShell = {\n prefix: string;\n suffix: string;\n};\n\nexport async function createDocumentShell(\n match: LoadedRouteMatch,\n options: SsrRenderOptions & { scripts?: ScriptTag[] },\n): Promise<DocumentShell> {\n const shell = renderDocumentShell({\n body: { data: match.data, locale: options.locale, navigation: options.navigation },\n dir: options.dir,\n entrySrc: options.clientEntry,\n lang: options.lang,\n links: match.links,\n metadata: match.metadata,\n nonce: options.nonce,\n scripts: options.scripts ?? match.scripts,\n styles: options.styles,\n title: options.title,\n });\n\n if (!options.transformDocument) {\n return shell;\n }\n\n const transformed = await options.transformDocument(\n `${shell.prefix}${STREAM_ROOT_MARKER}${shell.suffix}`,\n );\n const markerIndex = transformed.indexOf(STREAM_ROOT_MARKER);\n\n if (\n markerIndex === -1 ||\n transformed.indexOf(\n STREAM_ROOT_MARKER,\n markerIndex + STREAM_ROOT_MARKER.length,\n ) !== -1\n ) {\n throw new Error(\n \"Demiurge streaming document transform must preserve the root marker exactly once.\",\n );\n }\n\n return {\n prefix: transformed.slice(0, markerIndex),\n suffix: transformed.slice(markerIndex + STREAM_ROOT_MARKER.length),\n };\n}\n"],"names":["STREAM_ROOT_MARKER","createDocumentShell","match","options","shell","renderDocumentShell","transformed","markerIndex"],"mappings":";AAQO,MAAMA,IACX;AAOF,eAAsBC,EACpBC,GACAC,GACwB;AACxB,QAAMC,IAAQC,EAAoB;AAAA,IAChC,MAAM,EAAE,MAAMH,EAAM,MAAM,QAAQC,EAAQ,QAAQ,YAAYA,EAAQ,WAAA;AAAA,IACtE,KAAKA,EAAQ;AAAA,IACb,UAAUA,EAAQ;AAAA,IAClB,MAAMA,EAAQ;AAAA,IACd,OAAOD,EAAM;AAAA,IACb,UAAUA,EAAM;AAAA,IAChB,OAAOC,EAAQ;AAAA,IACf,SAASA,EAAQ,WAAWD,EAAM;AAAA,IAClC,QAAQC,EAAQ;AAAA,IAChB,OAAOA,EAAQ;AAAA,EAAA,CAChB;AAED,MAAI,CAACA,EAAQ;AACX,WAAOC;AAGT,QAAME,IAAc,MAAMH,EAAQ;AAAA,IAChC,GAAGC,EAAM,MAAM,GAAGJ,CAAkB,GAAGI,EAAM,MAAM;AAAA,EAAA,GAE/CG,IAAcD,EAAY,QAAQN,CAAkB;AAE1D,MACEO,MAAgB,MAChBD,EAAY;AAAA,IACVN;AAAA,IACAO,IAAcP,EAAmB;AAAA,EAAA,MAC7B;AAEN,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAIJ,SAAO;AAAA,IACL,QAAQM,EAAY,MAAM,GAAGC,CAAW;AAAA,IACxC,QAAQD,EAAY,MAAMC,IAAcP,EAAmB,MAAM;AAAA,EAAA;AAErE;"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createHash as d } from "node:crypto";
|
|
2
2
|
import { readFile as h, mkdir as p, writeFile as F } from "node:fs/promises";
|
|
3
3
|
import { resolve as u, join as w, relative as b, sep as $ } from "node:path";
|
|
4
|
-
import { d as v, f as S, a as N, r as E, b as J, c as O, i as j } from "./images-
|
|
4
|
+
import { d as v, f as S, a as N, r as E, b as J, c as O, i as j } from "./images-CG7ZzayG.js";
|
|
5
5
|
const y = 5 * 1024 * 1024;
|
|
6
6
|
async function H(e) {
|
|
7
7
|
const t = e.fonts ?? [];
|
|
@@ -138,4 +138,4 @@ export {
|
|
|
138
138
|
H as r,
|
|
139
139
|
q as t
|
|
140
140
|
};
|
|
141
|
-
//# sourceMappingURL=image-codec-
|
|
141
|
+
//# sourceMappingURL=image-codec-Dh1POFhE.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"image-codec-BmzWnH6W.js","sources":["../../src/platform/font-assets.ts","../../src/platform/image-codec.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { join, relative, resolve, sep } from \"node:path\";\nimport {\n defaultFontPath,\n fontAssetFileName,\n fontFormat,\n fontMediaType,\n fontStylesheetUrl,\n renderFontFaceCss,\n type FontContribution,\n type FontDefinition,\n} from \"./fonts\";\n\nexport type FontAssetFetch = (\n input: string,\n init?: { signal?: AbortSignal },\n) => Promise<Response>;\n\nexport type FontAssetOptions = {\n basePath?: string;\n // Where a downloaded font file stays between builds. A build that already\n // downloaded a font reads it back and makes no network request.\n cacheDir?: string;\n fetch?: FontAssetFetch;\n fonts?: FontContribution;\n // The project directory that every local font source resolves against.\n root: string;\n};\n\nexport type FontAsset = {\n body: Uint8Array;\n contentType: string;\n // The output path, relative to the directory that the build publishes.\n file: string;\n url: string;\n};\n\nconst maximumFontBytes = 5 * 1024 * 1024;\n\n// One font declaration becomes one published file plus one stylesheet. The\n// build writes these files, and the Node handler serves the same set from\n// memory. Both derive every URL from the declaration, so they cannot drift.\nexport async function resolveFontAssets(\n options: FontAssetOptions,\n): Promise<FontAsset[]> {\n const fonts = options.fonts ?? [];\n\n if (fonts.length === 0) {\n return [];\n }\n\n const basePath = options.basePath ?? defaultFontPath;\n const root = resolve(options.root);\n const cacheDir = resolve(\n options.cacheDir ?? join(root, \"node_modules\", \".demiurge\", \"fonts\"),\n );\n const load = options.fetch ?? ((input, init) => fetch(input, init));\n const published = new Map<string, string>();\n const assets: FontAsset[] = [];\n\n for (const definition of fonts) {\n if (!definition.selfHost) {\n continue;\n }\n\n const name = fontAssetFileName(definition);\n const claimed = published.get(name);\n\n if (claimed !== undefined) {\n if (claimed !== definition.src) {\n throw new Error(\n `Font family ${JSON.stringify(definition.family)} declares two sources that publish the same file ${JSON.stringify(name)}. Give one of them a different weight or style.`,\n );\n }\n\n continue;\n }\n\n published.set(name, definition.src);\n assets.push({\n body: await readFontBody(definition, { cacheDir, load, root }),\n contentType: fontMediaType(definition.src),\n file: outputFile(basePath, name),\n url: `${basePath}/${name}`,\n });\n }\n\n const stylesheet = `${renderFontFaceCss(fonts, basePath)}\\n`;\n\n assets.push({\n body: new TextEncoder().encode(stylesheet),\n contentType: \"text/css; charset=utf-8\",\n file: outputFile(basePath, \"fonts.css\"),\n url: fontStylesheetUrl(basePath),\n });\n\n return assets;\n}\n\nasync function readFontBody(\n definition: FontDefinition,\n context: { cacheDir: string; load: FontAssetFetch; root: string },\n) {\n const body = definition.source === \"google\"\n ? await downloadFontFile(definition, context)\n : await readLocalFontFile(definition, context.root);\n\n if (body.byteLength === 0) {\n throw new Error(\n `Font family ${JSON.stringify(definition.family)} resolved to an empty file.`,\n );\n }\n\n if (body.byteLength > maximumFontBytes) {\n throw new Error(\n `Font family ${JSON.stringify(definition.family)} is larger than the ${maximumFontBytes} byte limit.`,\n );\n }\n\n return body;\n}\n\nasync function readLocalFontFile(definition: FontDefinition, root: string) {\n const file = resolve(root, definition.src.replace(/^\\/+/, \"\"));\n\n if (relative(root, file).split(sep).includes(\"..\")) {\n throw new Error(\n `Font source escaped the project directory: ${JSON.stringify(definition.src)}.`,\n );\n }\n\n try {\n return new Uint8Array(await readFile(file));\n } catch (error) {\n throw new Error(\n `Demiurge could not read the font file ${JSON.stringify(definition.src)} for family ${JSON.stringify(definition.family)}.`,\n { cause: error },\n );\n }\n}\n\n// A downloaded font stays in the cache directory. The first build reaches the\n// font host once, and every later build reads the file from disk. A build that\n// runs without network access therefore keeps working.\nasync function downloadFontFile(\n definition: FontDefinition,\n context: { cacheDir: string; load: FontAssetFetch; root: string },\n) {\n const digest = createHash(\"sha256\").update(definition.src).digest(\"hex\");\n const cacheFile = join(\n context.cacheDir,\n `${digest.slice(0, 32)}.${fontFormat(definition.src)}`,\n );\n\n try {\n return new Uint8Array(await readFile(cacheFile));\n } catch {\n // The cache holds no copy yet, so the font host answers this once.\n }\n\n let response: Response;\n\n try {\n response = await context.load(definition.src);\n } catch (error) {\n throw new Error(\n `Demiurge could not download the font for family ${JSON.stringify(definition.family)} from ${JSON.stringify(definition.src)}.`,\n { cause: error },\n );\n }\n\n if (!response.ok) {\n throw new Error(\n `The font host answered ${response.status} for family ${JSON.stringify(definition.family)} at ${JSON.stringify(definition.src)}.`,\n );\n }\n\n const body = new Uint8Array(await response.arrayBuffer());\n\n await mkdir(context.cacheDir, { recursive: true });\n await writeFile(cacheFile, body);\n\n return body;\n}\n\nfunction outputFile(basePath: string, name: string) {\n return `${basePath.replace(/^\\/+/, \"\")}/${name}`;\n}\n","import type { ImageFormat } from \"./images\";\nimport { imageSourceExtension, type ImageVariantDescriptor } from \"./image-url\";\n\nexport type EncodedImage = {\n body: Uint8Array;\n contentType: string;\n};\n\ntype SharpModule = {\n default: (input: Uint8Array) => SharpPipeline;\n};\n\ntype SharpPipeline = {\n avif: (options: { quality: number }) => SharpPipeline;\n jpeg: (options: { quality: number }) => SharpPipeline;\n png: () => SharpPipeline;\n resize: (options: {\n width: number;\n withoutEnlargement: boolean;\n }) => SharpPipeline;\n toBuffer: () => Promise<Buffer>;\n webp: (options: { quality: number }) => SharpPipeline;\n};\n\nconst contentTypes: Record<Exclude<ImageFormat, \"auto\">, string> = {\n avif: \"image/avif\",\n jpeg: \"image/jpeg\",\n png: \"image/png\",\n webp: \"image/webp\",\n};\n\nconst defaultQuality = 75;\n\nexport function imageContentType(format: Exclude<ImageFormat, \"auto\">) {\n return contentTypes[format];\n}\n\n// `auto` lets the browser take the smallest format that it accepts. A client\n// that sends no usable `accept` header keeps the source format.\nexport function negotiateImageFormat(\n descriptor: ImageVariantDescriptor,\n accept: string | null,\n): Exclude<ImageFormat, \"auto\"> {\n if (descriptor.format !== \"auto\") {\n return descriptor.format;\n }\n\n const accepted = (accept ?? \"\").toLowerCase();\n\n if (accepted.includes(\"image/avif\")) {\n return \"avif\";\n }\n\n if (accepted.includes(\"image/webp\")) {\n return \"webp\";\n }\n\n return sourceFormat(descriptor.src);\n}\n\nexport function sourceFormat(src: string): Exclude<ImageFormat, \"auto\"> {\n const extension = imageSourceExtension(src);\n\n if (extension === \"avif\") {\n return \"avif\";\n }\n\n if (extension === \"webp\") {\n return \"webp\";\n }\n\n if (extension === \"png\") {\n return \"png\";\n }\n\n return \"jpeg\";\n}\n\nexport async function transformImage(\n source: Uint8Array,\n options: {\n format: Exclude<ImageFormat, \"auto\">;\n quality?: number;\n width: number;\n },\n): Promise<EncodedImage> {\n const sharp = await loadImageCodec();\n const quality = options.quality ?? defaultQuality;\n const resized = sharp(source).resize({\n width: options.width,\n withoutEnlargement: true,\n });\n\n return {\n body: new Uint8Array(await encode(resized, options.format, quality)),\n contentType: contentTypes[options.format],\n };\n}\n\nfunction encode(\n pipeline: SharpPipeline,\n format: Exclude<ImageFormat, \"auto\">,\n quality: number,\n) {\n if (format === \"png\") {\n return pipeline.png().toBuffer();\n }\n\n if (format === \"jpeg\") {\n return pipeline.jpeg({ quality }).toBuffer();\n }\n\n if (format === \"avif\") {\n return pipeline.avif({ quality }).toBuffer();\n }\n\n return pipeline.webp({ quality }).toBuffer();\n}\n\n// `sharp` is an optional peer dependency. Only an application that optimizes\n// an image installs it, the same rule that ADR 0006 states for a host\n// adapter dependency.\nasync function loadImageCodec() {\n let module: SharpModule;\n\n try {\n // TYPE-EVIDENCE: sharp ships no types. The local type describes the methods the codec calls.\n module = (await import(\"sharp\")) as SharpModule;\n } catch (error) {\n throw new Error(\n \"Demiurge image optimization requires the optional peer dependency sharp. Install sharp in the application.\",\n { cause: error },\n );\n }\n\n return module.default;\n}\n"],"names":["maximumFontBytes","resolveFontAssets","options","fonts","basePath","defaultFontPath","root","resolve","cacheDir","join","load","input","init","published","assets","definition","name","fontAssetFileName","claimed","readFontBody","fontMediaType","outputFile","stylesheet","renderFontFaceCss","fontStylesheetUrl","context","body","downloadFontFile","readLocalFontFile","file","relative","sep","readFile","error","digest","createHash","cacheFile","fontFormat","response","mkdir","writeFile","contentTypes","defaultQuality","negotiateImageFormat","descriptor","accept","accepted","sourceFormat","src","extension","imageSourceExtension","transformImage","source","sharp","loadImageCodec","quality","resized","encode","pipeline","format","module"],"mappings":";;;;AAsCA,MAAMA,IAAmB,IAAI,OAAO;AAKpC,eAAs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Q,MAAMC,EAAA,GACdC,IAAUrD,EAAQ,WAAWwC,GAC7Bc,IAAUH,EAAMD,CAAM,EAAE,OAAO;AAAA,IACnC,OAAOlD,EAAQ;AAAA,IACf,oBAAoB;AAAA,EAAA,CACrB;AAED,SAAO;AAAA,IACL,MAAM,IAAI,WAAW,MAAMuD,EAAOD,GAAStD,EAAQ,QAAQqD,CAAO,CAAC;AAAA,IACnE,aAAad,EAAavC,EAAQ,MAAM;AAAA,EAAA;AAE5C;AAEA,SAASuD,EACPC,GACAC,GACAJ,GACA;AACA,SAAII,MAAW,QACND,EAAS,IAAA,EAAM,SAAA,IAGpBC,MAAW,SACND,EAAS,KAAK,EAAE,SAAAH,EAAA,CAAS,EAAE,SAAA,IAGhCI,MAAW,SACND,EAAS,KAAK,EAAE,SAAAH,EAAA,CAAS,EAAE,SAAA,IAG7BG,EAAS,KAAK,EAAE,SAAAH,EAAA,CAAS,EAAE,SAAA;AACpC;AAKA,eAAeD,IAAiB;AAC9B,MAAIM;AAEJ,MAAI;AAEF,IAAAA,IAAU,MAAM,OAAO,OAAO;AAAA,EAChC,SAAS3B,GAAO;AACd,UAAM,IAAI;AAAA,MACR;AAAA,MACA,EAAE,OAAOA,EAAA;AAAA,IAAM;AAAA,EAEnB;AAEA,SAAO2B,EAAO;AAChB;"}
|
|
1
|
+
{"version":3,"file":"image-codec-Dh1POFhE.js","sources":["../../src/platform/font-assets.ts","../../src/platform/image-codec.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { join, relative, resolve, sep } from \"node:path\";\nimport {\n defaultFontPath,\n fontAssetFileName,\n fontFormat,\n fontMediaType,\n fontStylesheetUrl,\n renderFontFaceCss,\n type FontContribution,\n type FontDefinition,\n} from \"./fonts\";\n\nexport type FontAssetFetch = (\n input: string,\n init?: { signal?: AbortSignal },\n) => Promise<Response>;\n\nexport type FontAssetOptions = {\n basePath?: string;\n // Where a downloaded font file stays between builds. A build that already\n // downloaded a font reads it back and makes no network request.\n cacheDir?: string;\n fetch?: FontAssetFetch;\n fonts?: FontContribution;\n // The project directory that every local font source resolves against.\n root: string;\n};\n\nexport type FontAsset = {\n body: Uint8Array;\n contentType: string;\n // The output path, relative to the directory that the build publishes.\n file: string;\n url: string;\n};\n\nconst maximumFontBytes = 5 * 1024 * 1024;\n\n// One font declaration becomes one published file plus one stylesheet. The\n// build writes these files, and the Node handler serves the same set from\n// memory. Both derive every URL from the declaration, so they cannot drift.\nexport async function resolveFontAssets(\n options: FontAssetOptions,\n): Promise<FontAsset[]> {\n const fonts = options.fonts ?? [];\n\n if (fonts.length === 0) {\n return [];\n }\n\n const basePath = options.basePath ?? defaultFontPath;\n const root = resolve(options.root);\n const cacheDir = resolve(\n options.cacheDir ?? join(root, \"node_modules\", \".demiurge\", \"fonts\"),\n );\n const load = options.fetch ?? ((input, init) => fetch(input, init));\n const published = new Map<string, string>();\n const assets: FontAsset[] = [];\n\n for (const definition of fonts) {\n if (!definition.selfHost) {\n continue;\n }\n\n const name = fontAssetFileName(definition);\n const claimed = published.get(name);\n\n if (claimed !== undefined) {\n if (claimed !== definition.src) {\n throw new Error(\n `Font family ${JSON.stringify(definition.family)} declares two sources that publish the same file ${JSON.stringify(name)}. Give one of them a different weight or style.`,\n );\n }\n\n continue;\n }\n\n published.set(name, definition.src);\n assets.push({\n body: await readFontBody(definition, { cacheDir, load, root }),\n contentType: fontMediaType(definition.src),\n file: outputFile(basePath, name),\n url: `${basePath}/${name}`,\n });\n }\n\n const stylesheet = `${renderFontFaceCss(fonts, basePath)}\\n`;\n\n assets.push({\n body: new TextEncoder().encode(stylesheet),\n contentType: \"text/css; charset=utf-8\",\n file: outputFile(basePath, \"fonts.css\"),\n url: fontStylesheetUrl(basePath),\n });\n\n return assets;\n}\n\nasync function readFontBody(\n definition: FontDefinition,\n context: { cacheDir: string; load: FontAssetFetch; root: string },\n) {\n const body = definition.source === \"google\"\n ? await downloadFontFile(definition, context)\n : await readLocalFontFile(definition, context.root);\n\n if (body.byteLength === 0) {\n throw new Error(\n `Font family ${JSON.stringify(definition.family)} resolved to an empty file.`,\n );\n }\n\n if (body.byteLength > maximumFontBytes) {\n throw new Error(\n `Font family ${JSON.stringify(definition.family)} is larger than the ${maximumFontBytes} byte limit.`,\n );\n }\n\n return body;\n}\n\nasync function readLocalFontFile(definition: FontDefinition, root: string) {\n const file = resolve(root, definition.src.replace(/^\\/+/, \"\"));\n\n if (relative(root, file).split(sep).includes(\"..\")) {\n throw new Error(\n `Font source escaped the project directory: ${JSON.stringify(definition.src)}.`,\n );\n }\n\n try {\n return new Uint8Array(await readFile(file));\n } catch (error) {\n throw new Error(\n `Demiurge could not read the font file ${JSON.stringify(definition.src)} for family ${JSON.stringify(definition.family)}.`,\n { cause: error },\n );\n }\n}\n\n// A downloaded font stays in the cache directory. The first build reaches the\n// font host once, and every later build reads the file from disk. A build that\n// runs without network access therefore keeps working.\nasync function downloadFontFile(\n definition: FontDefinition,\n context: { cacheDir: string; load: FontAssetFetch; root: string },\n) {\n const digest = createHash(\"sha256\").update(definition.src).digest(\"hex\");\n const cacheFile = join(\n context.cacheDir,\n `${digest.slice(0, 32)}.${fontFormat(definition.src)}`,\n );\n\n try {\n return new Uint8Array(await readFile(cacheFile));\n } catch {\n // The cache holds no copy yet, so the font host answers this once.\n }\n\n let response: Response;\n\n try {\n response = await context.load(definition.src);\n } catch (error) {\n throw new Error(\n `Demiurge could not download the font for family ${JSON.stringify(definition.family)} from ${JSON.stringify(definition.src)}.`,\n { cause: error },\n );\n }\n\n if (!response.ok) {\n throw new Error(\n `The font host answered ${response.status} for family ${JSON.stringify(definition.family)} at ${JSON.stringify(definition.src)}.`,\n );\n }\n\n const body = new Uint8Array(await response.arrayBuffer());\n\n await mkdir(context.cacheDir, { recursive: true });\n await writeFile(cacheFile, body);\n\n return body;\n}\n\nfunction outputFile(basePath: string, name: string) {\n return `${basePath.replace(/^\\/+/, \"\")}/${name}`;\n}\n","import type { ImageFormat } from \"./images\";\nimport { imageSourceExtension, type ImageVariantDescriptor } from \"./image-url\";\n\nexport type EncodedImage = {\n body: Uint8Array;\n contentType: string;\n};\n\ntype SharpModule = {\n default: (input: Uint8Array) => SharpPipeline;\n};\n\ntype SharpPipeline = {\n avif: (options: { quality: number }) => SharpPipeline;\n jpeg: (options: { quality: number }) => SharpPipeline;\n png: () => SharpPipeline;\n resize: (options: {\n width: number;\n withoutEnlargement: boolean;\n }) => SharpPipeline;\n toBuffer: () => Promise<Buffer>;\n webp: (options: { quality: number }) => SharpPipeline;\n};\n\nconst contentTypes: Record<Exclude<ImageFormat, \"auto\">, string> = {\n avif: \"image/avif\",\n jpeg: \"image/jpeg\",\n png: \"image/png\",\n webp: \"image/webp\",\n};\n\nconst defaultQuality = 75;\n\nexport function imageContentType(format: Exclude<ImageFormat, \"auto\">) {\n return contentTypes[format];\n}\n\n// `auto` lets the browser take the smallest format that it accepts. A client\n// that sends no usable `accept` header keeps the source format.\nexport function negotiateImageFormat(\n descriptor: ImageVariantDescriptor,\n accept: string | null,\n): Exclude<ImageFormat, \"auto\"> {\n if (descriptor.format !== \"auto\") {\n return descriptor.format;\n }\n\n const accepted = (accept ?? \"\").toLowerCase();\n\n if (accepted.includes(\"image/avif\")) {\n return \"avif\";\n }\n\n if (accepted.includes(\"image/webp\")) {\n return \"webp\";\n }\n\n return sourceFormat(descriptor.src);\n}\n\nexport function sourceFormat(src: string): Exclude<ImageFormat, \"auto\"> {\n const extension = imageSourceExtension(src);\n\n if (extension === \"avif\") {\n return \"avif\";\n }\n\n if (extension === \"webp\") {\n return \"webp\";\n }\n\n if (extension === \"png\") {\n return \"png\";\n }\n\n return \"jpeg\";\n}\n\nexport async function transformImage(\n source: Uint8Array,\n options: {\n format: Exclude<ImageFormat, \"auto\">;\n quality?: number;\n width: number;\n },\n): Promise<EncodedImage> {\n const sharp = await loadImageCodec();\n const quality = options.quality ?? defaultQuality;\n const resized = sharp(source).resize({\n width: options.width,\n withoutEnlargement: true,\n });\n\n return {\n body: new Uint8Array(await encode(resized, options.format, quality)),\n contentType: contentTypes[options.format],\n };\n}\n\nfunction encode(\n pipeline: SharpPipeline,\n format: Exclude<ImageFormat, \"auto\">,\n quality: number,\n) {\n if (format === \"png\") {\n return pipeline.png().toBuffer();\n }\n\n if (format === \"jpeg\") {\n return pipeline.jpeg({ quality }).toBuffer();\n }\n\n if (format === \"avif\") {\n return pipeline.avif({ quality }).toBuffer();\n }\n\n return pipeline.webp({ quality }).toBuffer();\n}\n\n// `sharp` is an optional peer dependency. Only an application that optimizes\n// an image installs it, the same rule that ADR 0006 states for a host\n// adapter dependency.\nasync function loadImageCodec() {\n let module: SharpModule;\n\n try {\n // TYPE-EVIDENCE: sharp ships no types. The local type describes the methods the codec calls.\n module = (await import(\"sharp\")) as SharpModule;\n } catch (error) {\n throw new Error(\n \"Demiurge image optimization requires the optional peer dependency sharp. Install sharp in the application.\",\n { cause: error },\n );\n }\n\n return module.default;\n}\n"],"names":["maximumFontBytes","resolveFontAssets","options","fonts","basePath","defaultFontPath","root","resolve","cacheDir","join","load","input","init","published","assets","definition","name","fontAssetFileName","claimed","readFontBody","fontMediaType","outputFile","stylesheet","renderFontFaceCss","fontStylesheetUrl","context","body","downloadFontFile","readLocalFontFile","file","relative","sep","readFile","error","digest","createHash","cacheFile","fontFormat","response","mkdir","writeFile","contentTypes","defaultQuality","negotiateImageFormat","descriptor","accept","accepted","sourceFormat","src","extension","imageSourceExtension","transformImage","source","sharp","loadImageCodec","quality","resized","encode","pipeline","format","module"],"mappings":";;;;AAsCA,MAAMA,IAAmB,IAAI,OAAO;AAKpC,eAAsBC,EACpBC,GACsB;AACtB,QAAMC,IAAQD,EAAQ,SAAS,CAAA;AAE/B,MAAIC,EAAM,WAAW;AACnB,WAAO,CAAA;AAGT,QAAMC,IAAWF,EAAQ,YAAYG,GAC/BC,IAAOC,EAAQL,EAAQ,IAAI,GAC3BM,IAAWD;AAAA,IACfL,EAAQ,YAAYO,EAAKH,GAAM,gB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D,CAAO,CAAC;AAAA,IACnE,aAAad,EAAavC,EAAQ,MAAM;AAAA,EAAA;AAE5C;AAEA,SAASuD,EACPC,GACAC,GACAJ,GACA;AACA,SAAII,MAAW,QACND,EAAS,IAAA,EAAM,SAAA,IAGpBC,MAAW,SACND,EAAS,KAAK,EAAE,SAAAH,EAAA,CAAS,EAAE,SAAA,IAGhCI,MAAW,SACND,EAAS,KAAK,EAAE,SAAAH,EAAA,CAAS,EAAE,SAAA,IAG7BG,EAAS,KAAK,EAAE,SAAAH,EAAA,CAAS,EAAE,SAAA;AACpC;AAKA,eAAeD,IAAiB;AAC9B,MAAIM;AAEJ,MAAI;AAEF,IAAAA,IAAU,MAAM,OAAO,OAAO;AAAA,EAChC,SAAS3B,GAAO;AACd,UAAM,IAAI;AAAA,MACR;AAAA,MACA,EAAE,OAAOA,EAAA;AAAA,IAAM;AAAA,EAEnB;AAEA,SAAO2B,EAAO;AAChB;"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { p as P } from "./index-
|
|
1
|
+
import { p as P } from "./index-0MNiR_wo.js";
|
|
2
2
|
function j(t) {
|
|
3
3
|
return t.split("?")[0].split("#")[0];
|
|
4
4
|
}
|
|
@@ -344,4 +344,4 @@ export {
|
|
|
344
344
|
Z as t,
|
|
345
345
|
j as u
|
|
346
346
|
};
|
|
347
|
-
//# sourceMappingURL=images-
|
|
347
|
+
//# sourceMappingURL=images-CG7ZzayG.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"images-BQ80950B.js","sources":["../../src/platform/url.ts","../../src/platform/fonts.ts","../../src/platform/image-url.ts","../../src/platform/images.ts"],"sourcesContent":["/**\n * Drops the query string and the fragment from a URL or path, leaving the\n * path portion. Both are cut at the first occurrence, so a `?` inside a\n * fragment and a `#` inside a query are handled the way a browser handles\n * them: the earlier delimiter wins.\n */\nexport function urlPath(url: string) {\n return url.split(\"?\")[0]!.split(\"#\")[0]!;\n}\n\n/**\n * Resolves the file extension of a URL or path, lower-cased and without the\n * leading dot. The query string and the fragment are ignored, and only the\n * last path segment is considered, so a dot in a directory name never leaks\n * into the answer.\n *\n * A name with no dot and a name ending in a dot both answer the empty\n * string, which no caller's extension table names, so an unparseable name is\n * reported as unknown rather than mistaken for a format.\n */\nexport function urlExtension(url: string) {\n const name = urlPath(url).split(\"/\").at(-1)!;\n\n return name.includes(\".\") ? name.split(\".\").at(-1)!.toLowerCase() : \"\";\n}\n","import { preload } from \"../document/links\";\nimport { urlExtension } from \"./url\";\nimport type { LinkTag } from \"../document\";\n\nexport type FontStyle = \"normal\" | \"italic\" | \"oblique\";\n\nexport type FontFormat = \"otf\" | \"ttf\" | \"woff\" | \"woff2\";\n\nexport type FontDefinition = {\n display: \"auto\" | \"block\" | \"fallback\" | \"optional\" | \"swap\";\n family: string;\n kind: \"font\";\n // A self-hosted font is published from the application origin, so `'self'`\n // covers it. A font left on a third-party host stays a `font-src` entry and\n // a privacy question, and `fontSources` makes that cost visible.\n selfHost: boolean;\n source: \"google\" | \"local\";\n src: string;\n style: FontStyle;\n weight: number | `${number} ${number}`;\n};\n\nexport type LocalFontOptions = {\n display?: FontDefinition[\"display\"];\n name: string;\n src: string;\n style?: FontStyle;\n weight?: FontDefinition[\"weight\"];\n};\n\nexport type GoogleFontOptions = {\n display?: FontDefinition[\"display\"];\n family: string;\n selfHost?: boolean;\n src: string;\n style?: FontStyle;\n weight?: FontDefinition[\"weight\"];\n};\n\nexport type FontContribution = readonly FontDefinition[];\n\n// The framework publishes every self-hosted font under one path. The build\n// writes the files, and the Node handler serves the same URLs at request time.\nexport const defaultFontPath = \"/_demiurge/font\";\n\nconst fontFormats: Record<string, FontFormat> = {\n otf: \"otf\",\n ttf: \"ttf\",\n woff: \"woff\",\n woff2: \"woff2\",\n};\n\nconst fontFaceFormats: Record<FontFormat, string> = {\n otf: \"opentype\",\n ttf: \"truetype\",\n woff: \"woff\",\n woff2: \"woff2\",\n};\n\nconst fontMediaTypes: Record<FontFormat, string> = {\n otf: \"font/otf\",\n ttf: \"font/ttf\",\n woff: \"font/woff\",\n woff2: \"font/woff2\",\n};\n\nexport const font = {\n // A Google font needs the file URL that the Google stylesheet points at.\n // The framework reads no third-party stylesheet, because that request is\n // the privacy cost self-hosting removes.\n google(options: GoogleFontOptions): FontDefinition {\n const src = options.src.trim();\n\n if (!isRemoteSource(src)) {\n throw new Error(\n `Google font ${JSON.stringify(options.family)} needs an https font file URL as its source.`,\n );\n }\n\n assertKnownFormat(src);\n\n return {\n display: options.display ?? \"swap\",\n family: options.family,\n kind: \"font\",\n selfHost: options.selfHost ?? true,\n source: \"google\",\n src,\n style: options.style ?? \"normal\",\n weight: options.weight ?? 400,\n };\n },\n // A local font names a file in the project. The build reads that file and\n // publishes it, so the file does not have to sit in the public directory.\n local(options: LocalFontOptions): FontDefinition {\n const src = options.src.trim();\n\n if (!src) {\n throw new Error(\"Local font source must not be empty.\");\n }\n\n if (isRemoteSource(src)) {\n throw new Error(\n `Local font ${JSON.stringify(options.name)} must name a project file rather than a URL.`,\n );\n }\n\n assertKnownFormat(src);\n\n return {\n display: options.display ?? \"swap\",\n family: options.name,\n kind: \"font\",\n selfHost: true,\n source: \"local\",\n src,\n style: options.style ?? \"normal\",\n weight: options.weight ?? 400,\n };\n },\n};\n\nexport function defineFonts(fonts: FontContribution): FontContribution {\n return [...fonts];\n}\n\n// The published file name derives from the declaration alone. The renderer\n// and the build therefore agree on every URL without sharing any state.\nexport function fontAssetFileName(definition: FontDefinition) {\n const family = slug(definition.family);\n const weight = slug(String(definition.weight));\n\n return `${family}-${weight}-${definition.style}.${fontFormat(definition.src)}`;\n}\n\nexport function fontAssetUrl(\n definition: FontDefinition,\n basePath: string = defaultFontPath,\n) {\n return definition.selfHost\n ? `${basePath}/${fontAssetFileName(definition)}`\n : definition.src;\n}\n\nexport function fontStylesheetUrl(basePath: string = defaultFontPath) {\n return `${basePath}/fonts.css`;\n}\n\nexport function fontMediaType(file: string) {\n return fontMediaTypes[fontFormat(file)];\n}\n\nexport function fontFormat(file: string): FontFormat {\n const format = fontFormats[urlExtension(file)];\n\n if (!format) {\n throw new Error(\n `Font source ${JSON.stringify(file)} has no known font extension.`,\n );\n }\n\n return format;\n}\n\n// The stylesheet and the preload links are the whole document contribution.\n// An application spreads them into `links` in its root layout.\nexport function fontLinks(\n fonts: FontContribution,\n basePath: string = defaultFontPath,\n): LinkTag[] {\n if (fonts.length === 0) {\n return [];\n }\n\n return [\n {\n href: fontStylesheetUrl(basePath),\n kind: \"link\" as const,\n rel: \"stylesheet\",\n },\n ...fontPreloadLinks(fonts, basePath),\n ];\n}\n\nexport function fontPreloadLinks(\n fonts: FontContribution,\n basePath: string = defaultFontPath,\n): LinkTag[] {\n return fonts.map((definition) =>\n preload(fontAssetUrl(definition, basePath), {\n as: \"font\",\n // A font request runs in CORS mode even on the same origin. A preload\n // without this attribute fetches the file twice.\n crossOrigin: \"anonymous\",\n type: fontMediaType(definition.src),\n })\n );\n}\n\nexport function renderFontFaceCss(\n fonts: FontContribution,\n basePath: string = defaultFontPath,\n) {\n return fonts\n .map((definition) => {\n const url = fontAssetUrl(definition, basePath);\n\n return [\n \"@font-face {\",\n ` font-family: \"${escapeCss(definition.family)}\";`,\n ` src: url(\"${escapeCss(url)}\") format(\"${\n fontFaceFormats[fontFormat(definition.src)]\n }\");`,\n ` font-style: ${definition.style};`,\n ` font-weight: ${definition.weight};`,\n ` font-display: ${definition.display};`,\n \"}\",\n ].join(\"\\n\");\n })\n .join(\"\\n\");\n}\n\n// A self-hosted font set collapses to `'self'`, which every framework preset\n// already declares. A third-party host has to be named here instead.\nexport function fontSources(fonts: FontContribution): string[] {\n const origins = new Set<string>();\n\n for (const definition of fonts) {\n if (!definition.selfHost) {\n origins.add(new URL(definition.src).origin);\n }\n }\n\n return [\"'self'\", ...[...origins].sort()];\n}\n\nfunction isRemoteSource(src: string) {\n return /^https?:\\/\\//i.test(src);\n}\n\nfunction assertKnownFormat(src: string) {\n fontFormat(src);\n}\n\nfunction slug(value: string) {\n return value\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\") || \"font\";\n}\n\nfunction escapeCss(value: string) {\n return value.replace(/[\\\\\"]/g, \"\\\\$&\");\n}\n","import type { ImageFormat } from \"./images\";\nimport { urlExtension } from \"./url\";\n\nexport type ImageSourceKind = \"local\" | \"remote\";\n\n// The descriptor is the complete input of one variant. The build pipeline and\n// the runtime optimizer both derive a file name and an encoded body from it.\nexport type ImageVariantDescriptor = {\n format: ImageFormat;\n quality?: number;\n sourceKind: ImageSourceKind;\n src: string;\n width: number;\n};\n\nexport const defaultImageOptimizerPath = \"/_demiurge/image\";\n\nconst formatExtensions: Record<Exclude<ImageFormat, \"auto\">, string> = {\n avif: \"avif\",\n jpeg: \"jpg\",\n png: \"png\",\n webp: \"webp\",\n};\n\nconst extensionFormats: Record<string, Exclude<ImageFormat, \"auto\">> = {\n avif: \"avif\",\n jpeg: \"jpeg\",\n jpg: \"jpeg\",\n png: \"png\",\n webp: \"webp\",\n};\n\nconst variantNamePattern = /^(.+)\\.w(\\d{1,5})(?:\\.q(\\d{1,3}))?\\.([a-z0-9]+)$/;\n\nexport function createImageOptimizerUrl(\n descriptor: ImageVariantDescriptor,\n optimizerPath: string,\n) {\n const params = new URLSearchParams({\n src: descriptor.src,\n w: String(descriptor.width),\n });\n\n if (descriptor.quality !== undefined) {\n params.set(\"q\", String(descriptor.quality));\n }\n\n if (descriptor.format !== \"auto\") {\n params.set(\"f\", descriptor.format);\n }\n\n return `${optimizerPath}?${params.toString()}`;\n}\n\n// A static build has no optimizer process, so the variant path must describe\n// the complete transform. The build reads the path back and emits the file,\n// and no shared state has to cross the build and render boundary.\nexport function createImageVariantPath(\n descriptor: ImageVariantDescriptor,\n optimizerPath: string,\n) {\n if (descriptor.sourceKind === \"remote\") {\n throw new Error(\n `Image source ${JSON.stringify(descriptor.src)} is remote. A static image loader can only emit a local image.`,\n );\n }\n\n const quality = descriptor.quality === undefined\n ? \"\"\n : `.q${descriptor.quality}`;\n\n return `${optimizerPath}${descriptor.src}.w${descriptor.width}${quality}.${\n resolveVariantExtension(descriptor)\n }`;\n}\n\nexport function parseImageVariantPath(\n pathname: string,\n optimizerPath: string,\n): ImageVariantDescriptor | undefined {\n if (!pathname.startsWith(`${optimizerPath}/`)) {\n return undefined;\n }\n\n const match = variantNamePattern.exec(pathname.slice(optimizerPath.length));\n\n if (!match) {\n return undefined;\n }\n\n const [, src, rawWidth, rawQuality, extension] = match;\n const format = extensionFormats[extension!];\n const width = Number(rawWidth);\n const quality = rawQuality === undefined ? undefined : Number(rawQuality);\n\n if (\n !format ||\n !imageSourceExtension(src!) ||\n width <= 0 ||\n (quality !== undefined && (quality < 1 || quality > 100))\n ) {\n return undefined;\n }\n\n return { format, quality, sourceKind: \"local\", src: src!, width };\n}\n\nexport function resolveVariantExtension(descriptor: ImageVariantDescriptor) {\n if (descriptor.format !== \"auto\") {\n return formatExtensions[descriptor.format];\n }\n\n const extension = imageSourceExtension(descriptor.src);\n\n if (!extension) {\n throw new Error(\n `Image source ${JSON.stringify(descriptor.src)} has no known image extension. Declare an explicit format.`,\n );\n }\n\n return extension === \"jpeg\" ? \"jpg\" : extension;\n}\n\nexport function imageSourceExtension(src: string) {\n const extension = urlExtension(src);\n\n return extension in extensionFormats ? extension : undefined;\n}\n\n// The build and the development server both find variants by reading the\n// documents that the application rendered. A variant that no document\n// references is a variant that nothing can request.\nexport function collectImageVariantPaths(html: string, optimizerPath: string) {\n const pattern = new RegExp(\n `${escapeRegExp(optimizerPath)}/[^\"'\\\\s,)<>]+`,\n \"g\",\n );\n\n return [...new Set(html.match(pattern) ?? [])];\n}\n\nfunction escapeRegExp(value: string) {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n","import {\n createImageOptimizerUrl,\n createImageVariantPath,\n defaultImageOptimizerPath,\n type ImageVariantDescriptor,\n} from \"./image-url\";\n\n// `optimizer` points every variant at a request-time endpoint. `static`\n// points every variant at a file that the static build emits.\nexport type ImageLoader = \"optimizer\" | \"static\";\n\nexport type ImageFormat = \"auto\" | \"avif\" | \"webp\" | \"jpeg\" | \"png\";\n\nexport type RemoteImagePattern = {\n hostname: string;\n pathname?: string;\n port?: string;\n protocol?: \"http:\" | \"https:\";\n};\n\nexport type ImagePolicy = {\n loader?: ImageLoader;\n local?: boolean;\n optimizerPath?: string;\n remote?: readonly (string | RemoteImagePattern)[];\n};\n\nexport type ImageTransformOptions = {\n alt: string;\n format?: ImageFormat;\n height: number;\n priority?: boolean;\n quality?: number;\n sizes?: string;\n src: string;\n width: number;\n widths?: readonly number[];\n};\n\nexport type ImageVariant = {\n format: ImageFormat;\n height: number;\n src: string;\n width: number;\n};\n\nexport type ImageTransformPlan = {\n alt: string;\n decoding: \"async\";\n fetchPriority?: \"high\";\n height: number;\n loading: \"eager\" | \"lazy\";\n sizes?: string;\n source: {\n kind: \"local\" | \"remote\";\n src: string;\n };\n src: string;\n srcSet: string;\n variants: ImageVariant[];\n width: number;\n};\n\nexport function defineImages(policy: ImagePolicy): ImagePolicy {\n return policy;\n}\n\nexport function isAllowedImageSource(src: string, policy: ImagePolicy = {}) {\n return classifyImageSource(src, policy) !== null;\n}\n\nexport function planImageTransform(\n options: ImageTransformOptions,\n policy: ImagePolicy = {},\n): ImageTransformPlan {\n const source = classifyImageSource(options.src, policy);\n\n if (!source) {\n throw new Error(`Image source \"${options.src}\" is not allowed by the image policy.`);\n }\n\n validateImageDimension(\"width\", options.width);\n validateImageDimension(\"height\", options.height);\n validateImageQuality(options.quality);\n\n const format = options.format ?? \"auto\";\n const loader = policy.loader ?? \"optimizer\";\n const optimizerPath = policy.optimizerPath ?? defaultImageOptimizerPath;\n const widths = normalizeVariantWidths(options.width, options.widths);\n const variants = widths.map((width) => {\n const height = Math.round((options.height / options.width) * width);\n const descriptor: ImageVariantDescriptor = {\n format,\n quality: options.quality,\n sourceKind: source.kind,\n src: source.kind === \"remote\" ? source.src : options.src,\n width,\n };\n\n return {\n format,\n height,\n src: loader === \"static\"\n ? createImageVariantPath(descriptor, optimizerPath)\n : createImageOptimizerUrl(descriptor, optimizerPath),\n width,\n };\n });\n const primaryVariant = variants[0];\n\n return {\n alt: options.alt,\n decoding: \"async\",\n fetchPriority: options.priority ? \"high\" : undefined,\n height: options.height,\n loading: options.priority ? \"eager\" : \"lazy\",\n sizes: options.sizes,\n source,\n src: primaryVariant.src,\n srcSet: variants\n .map((variant) => `${variant.src} ${variant.width}w`)\n .join(\", \"),\n variants,\n width: options.width,\n };\n}\n\nfunction classifyImageSource(\n src: string,\n policy: ImagePolicy,\n): ImageTransformPlan[\"source\"] | null {\n if (src.startsWith(\"/\") && !src.startsWith(\"//\")) {\n return policy.local === false ? null : { kind: \"local\", src };\n }\n\n let url: URL;\n\n try {\n url = new URL(src);\n } catch {\n return null;\n }\n\n if (url.protocol !== \"https:\" && url.protocol !== \"http:\") {\n return null;\n }\n\n return isAllowedRemoteImage(url, policy.remote ?? [])\n ? { kind: \"remote\", src: url.toString() }\n : null;\n}\n\nfunction isAllowedRemoteImage(\n url: URL,\n remotes: readonly (string | RemoteImagePattern)[],\n) {\n return remotes.some((remote) =>\n typeof remote === \"string\"\n ? matchesRemoteOrigin(url, remote)\n : matchesRemotePattern(url, remote),\n );\n}\n\nfunction matchesRemoteOrigin(url: URL, origin: string) {\n try {\n return url.origin === new URL(origin).origin;\n } catch {\n return false;\n }\n}\n\nfunction matchesRemotePattern(url: URL, pattern: RemoteImagePattern) {\n if (pattern.protocol && url.protocol !== pattern.protocol) {\n return false;\n }\n\n if (url.hostname !== pattern.hostname) {\n return false;\n }\n\n if (pattern.port !== undefined && url.port !== pattern.port) {\n return false;\n }\n\n return pattern.pathname\n ? matchesPathnamePattern(url.pathname, pattern.pathname)\n : true;\n}\n\nfunction matchesPathnamePattern(pathname: string, pattern: string) {\n if (pattern.endsWith(\"*\")) {\n return pathname.startsWith(pattern.slice(0, -1));\n }\n\n return pathname === pattern;\n}\n\nfunction validateImageDimension(name: \"height\" | \"width\", value: number) {\n if (!Number.isInteger(value) || value <= 0) {\n throw new Error(`Image ${name} must be a positive integer.`);\n }\n}\n\nfunction validateImageQuality(quality: number | undefined) {\n if (quality === undefined) {\n return;\n }\n\n if (!Number.isInteger(quality) || quality < 1 || quality > 100) {\n throw new Error(\"Image quality must be an integer between 1 and 100.\");\n }\n}\n\nfunction normalizeVariantWidths(width: number, widths: readonly number[] | undefined) {\n const candidates = widths ?? [width, width * 2];\n const uniqueWidths = [...new Set(candidates)];\n\n for (const candidate of uniqueWidths) {\n validateImageDimension(\"width\", candidate);\n }\n\n return uniqueWidths.sort((left, right) => left - right);\n}\n\nexport type ImageRequestRejection = {\n reason: string;\n status: 400 | 403;\n};\n\nexport type ImageRequestResult =\n | { descriptor: ImageVariantDescriptor; ok: true }\n | { ok: false; rejection: ImageRequestRejection };\n\nconst imageFormats = new Set<ImageFormat>([\n \"avif\",\n \"jpeg\",\n \"png\",\n \"webp\",\n]);\n\n// The runtime optimizer reads a query that any client can write. It repeats\n// the policy check that the planner made, so an unallowed source never\n// reaches the file system or the network.\nexport function parseImageOptimizerRequest(\n url: URL,\n policy: ImagePolicy = {},\n): ImageRequestResult {\n const src = url.searchParams.get(\"src\");\n\n if (!src) {\n return reject(400, \"The image request must declare a src parameter.\");\n }\n\n const source = classifyImageSource(src, policy);\n\n if (!source) {\n return reject(403, \"The image policy does not allow this image source.\");\n }\n\n const width = Number(url.searchParams.get(\"w\"));\n\n if (!Number.isInteger(width) || width <= 0) {\n return reject(400, \"The image width must be a positive integer.\");\n }\n\n const rawQuality = url.searchParams.get(\"q\");\n const quality = rawQuality === null ? undefined : Number(rawQuality);\n\n if (\n quality !== undefined &&\n (!Number.isInteger(quality) || quality < 1 || quality > 100)\n ) {\n return reject(400, \"The image quality must be an integer from 1 through 100.\");\n }\n\n const rawFormat = url.searchParams.get(\"f\");\n\n // TYPE-EVIDENCE: the set membership check confirms the raw format is a known image format. The cast matches that check.\n if (rawFormat !== null && !imageFormats.has(rawFormat as ImageFormat)) {\n return reject(400, \"The image format is not supported.\");\n }\n\n // TYPE-EVIDENCE: the raw format value is a string that names an image format or is null. The cast labels it with the format union.\n return {\n descriptor: {\n format: (rawFormat as ImageFormat | null) ?? \"auto\",\n quality,\n sourceKind: source.kind,\n src: source.src,\n width,\n },\n ok: true,\n };\n}\n\nfunction reject(status: 400 | 403, reason: string): ImageRequestResult {\n return { ok: false, rejection: { reason, status } };\n}\n"],"names":["urlPath","url","urlExtension","name","defaultFontPath","fontFormats","fontFaceFormats","fontMediaTypes","font","options","src","isRemoteSource","assertKnownFormat","defineFonts","fonts","fontAssetFileName","definition","family","slug","weight","fontFormat","fontAssetUrl","basePath","fontStylesheetUrl","fontMediaType","file","format","fontLinks","fontPreloadLinks","preload","renderFontFaceCss","escapeCss","fontSources","origins","value","defaultImageOptimizerPath","formatExtensions","extensionFormats","variantNamePattern","createImageOptimizerUrl","descriptor","optimizerPath","params","createImageVariantPath","quality","resolveVariantExtension","parseImageVariantPath","pathname","match","rawWidth","rawQuality","extension","width","imageSourceExtension","collectImageVariantPaths","html","pattern","escapeRegExp","defineImages","policy","isAllowedImageSource","classifyImageSource","planImageTransform","source","validateImageDimension","validateImageQuality","loader","variants","normalizeVariantWidths","height","primaryVariant","variant","isAllowedRemoteImage","remotes","remote","matchesRemoteOrigin","matchesRemotePattern","origin","matchesPathnamePattern","widths","candidates","uniqueWidths","candidate","left","right","imageFormats","parseImageOptimizerRequest","reject","rawFormat","status","reason"],"mappings":";AAMO,SAASA,EAAQC,GAAa;AACnC,SAAOA,EAAI,MAAM,GAAG,EAAE,CAAC,EAAG,MAAM,GAAG,EAAE,CAAC;AACxC;AAYO,SAASC,EAAaD,GAAa;AACxC,QAAME,IAAOH,EAAQC,CAAG,EAAE,MAAM,GAAG,EAAE,GAAG,EAAE;AAE1C,SAAOE,EAAK,SAAS,GAAG,IAAIA,EAAK,MAAM,GAAG,EAAE,GAAG,EAAE,EAAG,YAAA,IAAgB;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src/platform/url.ts","../../src/platform/fonts.ts","../../src/platform/image-url.ts","../../src/platform/images.ts"],"sourcesContent":["/**\n * Drops the query string and the fragment from a URL or path, leaving the\n * path portion. Both are cut at the first occurrence, so a `?` inside a\n * fragment and a `#` inside a query are handled the way a browser handles\n * them: the earlier delimiter wins.\n */\nexport function urlPath(url: string) {\n return url.split(\"?\")[0]!.split(\"#\")[0]!;\n}\n\n/**\n * Resolves the file extension of a URL or path, lower-cased and without the\n * leading dot. The query string and the fragment are ignored, and only the\n * last path segment is considered, so a dot in a directory name never leaks\n * into the answer.\n *\n * A name with no dot and a name ending in a dot both answer the empty\n * string, which no caller's extension table names, so an unparseable name is\n * reported as unknown rather than mistaken for a format.\n */\nexport function urlExtension(url: string) {\n const name = urlPath(url).split(\"/\").at(-1)!;\n\n return name.includes(\".\") ? name.split(\".\").at(-1)!.toLowerCase() : \"\";\n}\n","import { preload } from \"../document/links\";\nimport { urlExtension } from \"./url\";\nimport type { LinkTag } from \"../document\";\n\nexport type FontStyle = \"normal\" | \"italic\" | \"oblique\";\n\nexport type FontFormat = \"otf\" | \"ttf\" | \"woff\" | \"woff2\";\n\nexport type FontDefinition = {\n display: \"auto\" | \"block\" | \"fallback\" | \"optional\" | \"swap\";\n family: string;\n kind: \"font\";\n // A self-hosted font is published from the application origin, so `'self'`\n // covers it. A font left on a third-party host stays a `font-src` entry and\n // a privacy question, and `fontSources` makes that cost visible.\n selfHost: boolean;\n source: \"google\" | \"local\";\n src: string;\n style: FontStyle;\n weight: number | `${number} ${number}`;\n};\n\nexport type LocalFontOptions = {\n display?: FontDefinition[\"display\"];\n name: string;\n src: string;\n style?: FontStyle;\n weight?: FontDefinition[\"weight\"];\n};\n\nexport type GoogleFontOptions = {\n display?: FontDefinition[\"display\"];\n family: string;\n selfHost?: boolean;\n src: string;\n style?: FontStyle;\n weight?: FontDefinition[\"weight\"];\n};\n\nexport type FontContribution = readonly FontDefinition[];\n\n// The framework publishes every self-hosted font under one path. The build\n// writes the files, and the Node handler serves the same URLs at request time.\nexport const defaultFontPath = \"/_demiurge/font\";\n\nconst fontFormats: Record<string, FontFormat> = {\n otf: \"otf\",\n ttf: \"ttf\",\n woff: \"woff\",\n woff2: \"woff2\",\n};\n\nconst fontFaceFormats: Record<FontFormat, string> = {\n otf: \"opentype\",\n ttf: \"truetype\",\n woff: \"woff\",\n woff2: \"woff2\",\n};\n\nconst fontMediaTypes: Record<FontFormat, string> = {\n otf: \"font/otf\",\n ttf: \"font/ttf\",\n woff: \"font/woff\",\n woff2: \"font/woff2\",\n};\n\nexport const font = {\n // A Google font needs the file URL that the Google stylesheet points at.\n // The framework reads no third-party stylesheet, because that request is\n // the privacy cost self-hosting removes.\n google(options: GoogleFontOptions): FontDefinition {\n const src = options.src.trim();\n\n if (!isRemoteSource(src)) {\n throw new Error(\n `Google font ${JSON.stringify(options.family)} needs an https font file URL as its source.`,\n );\n }\n\n assertKnownFormat(src);\n\n return {\n display: options.display ?? \"swap\",\n family: options.family,\n kind: \"font\",\n selfHost: options.selfHost ?? true,\n source: \"google\",\n src,\n style: options.style ?? \"normal\",\n weight: options.weight ?? 400,\n };\n },\n // A local font names a file in the project. The build reads that file and\n // publishes it, so the file does not have to sit in the public directory.\n local(options: LocalFontOptions): FontDefinition {\n const src = options.src.trim();\n\n if (!src) {\n throw new Error(\"Local font source must not be empty.\");\n }\n\n if (isRemoteSource(src)) {\n throw new Error(\n `Local font ${JSON.stringify(options.name)} must name a project file rather than a URL.`,\n );\n }\n\n assertKnownFormat(src);\n\n return {\n display: options.display ?? \"swap\",\n family: options.name,\n kind: \"font\",\n selfHost: true,\n source: \"local\",\n src,\n style: options.style ?? \"normal\",\n weight: options.weight ?? 400,\n };\n },\n};\n\nexport function defineFonts(fonts: FontContribution): FontContribution {\n return [...fonts];\n}\n\n// The published file name derives from the declaration alone. The renderer\n// and the build therefore agree on every URL without sharing any state.\nexport function fontAssetFileName(definition: FontDefinition) {\n const family = slug(definition.family);\n const weight = slug(String(definition.weight));\n\n return `${family}-${weight}-${definition.style}.${fontFormat(definition.src)}`;\n}\n\nexport function fontAssetUrl(\n definition: FontDefinition,\n basePath: string = defaultFontPath,\n) {\n return definition.selfHost\n ? `${basePath}/${fontAssetFileName(definition)}`\n : definition.src;\n}\n\nexport function fontStylesheetUrl(basePath: string = defaultFontPath) {\n return `${basePath}/fonts.css`;\n}\n\nexport function fontMediaType(file: string) {\n return fontMediaTypes[fontFormat(file)];\n}\n\nexport function fontFormat(file: string): FontFormat {\n const format = fontFormats[urlExtension(file)];\n\n if (!format) {\n throw new Error(\n `Font source ${JSON.stringify(file)} has no known font extension.`,\n );\n }\n\n return format;\n}\n\n// The stylesheet and the preload links are the whole document contribution.\n// An application spreads them into `links` in its root layout.\nexport function fontLinks(\n fonts: FontContribution,\n basePath: string = defaultFontPath,\n): LinkTag[] {\n if (fonts.length === 0) {\n return [];\n }\n\n return [\n {\n href: fontStylesheetUrl(basePath),\n kind: \"link\" as const,\n rel: \"stylesheet\",\n },\n ...fontPreloadLinks(fonts, basePath),\n ];\n}\n\nexport function fontPreloadLinks(\n fonts: FontContribution,\n basePath: string = defaultFontPath,\n): LinkTag[] {\n return fonts.map((definition) =>\n preload(fontAssetUrl(definition, basePath), {\n as: \"font\",\n // A font request runs in CORS mode even on the same origin. A preload\n // without this attribute fetches the file twice.\n crossOrigin: \"anonymous\",\n type: fontMediaType(definition.src),\n })\n );\n}\n\nexport function renderFontFaceCss(\n fonts: FontContribution,\n basePath: string = defaultFontPath,\n) {\n return fonts\n .map((definition) => {\n const url = fontAssetUrl(definition, basePath);\n\n return [\n \"@font-face {\",\n ` font-family: \"${escapeCss(definition.family)}\";`,\n ` src: url(\"${escapeCss(url)}\") format(\"${\n fontFaceFormats[fontFormat(definition.src)]\n }\");`,\n ` font-style: ${definition.style};`,\n ` font-weight: ${definition.weight};`,\n ` font-display: ${definition.display};`,\n \"}\",\n ].join(\"\\n\");\n })\n .join(\"\\n\");\n}\n\n// A self-hosted font set collapses to `'self'`, which every framework preset\n// already declares. A third-party host has to be named here instead.\nexport function fontSources(fonts: FontContribution): string[] {\n const origins = new Set<string>();\n\n for (const definition of fonts) {\n if (!definition.selfHost) {\n origins.add(new URL(definition.src).origin);\n }\n }\n\n return [\"'self'\", ...[...origins].sort()];\n}\n\nfunction isRemoteSource(src: string) {\n return /^https?:\\/\\//i.test(src);\n}\n\nfunction assertKnownFormat(src: string) {\n fontFormat(src);\n}\n\nfunction slug(value: string) {\n return value\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\") || \"font\";\n}\n\nfunction escapeCss(value: string) {\n return value.replace(/[\\\\\"]/g, \"\\\\$&\");\n}\n","import type { ImageFormat } from \"./images\";\nimport { urlExtension } from \"./url\";\n\nexport type ImageSourceKind = \"local\" | \"remote\";\n\n// The descriptor is the complete input of one variant. The build pipeline and\n// the runtime optimizer both derive a file name and an encoded body from it.\nexport type ImageVariantDescriptor = {\n format: ImageFormat;\n quality?: number;\n sourceKind: ImageSourceKind;\n src: string;\n width: number;\n};\n\nexport const defaultImageOptimizerPath = \"/_demiurge/image\";\n\nconst formatExtensions: Record<Exclude<ImageFormat, \"auto\">, string> = {\n avif: \"avif\",\n jpeg: \"jpg\",\n png: \"png\",\n webp: \"webp\",\n};\n\nconst extensionFormats: Record<string, Exclude<ImageFormat, \"auto\">> = {\n avif: \"avif\",\n jpeg: \"jpeg\",\n jpg: \"jpeg\",\n png: \"png\",\n webp: \"webp\",\n};\n\nconst variantNamePattern = /^(.+)\\.w(\\d{1,5})(?:\\.q(\\d{1,3}))?\\.([a-z0-9]+)$/;\n\nexport function createImageOptimizerUrl(\n descriptor: ImageVariantDescriptor,\n optimizerPath: string,\n) {\n const params = new URLSearchParams({\n src: descriptor.src,\n w: String(descriptor.width),\n });\n\n if (descriptor.quality !== undefined) {\n params.set(\"q\", String(descriptor.quality));\n }\n\n if (descriptor.format !== \"auto\") {\n params.set(\"f\", descriptor.format);\n }\n\n return `${optimizerPath}?${params.toString()}`;\n}\n\n// A static build has no optimizer process, so the variant path must describe\n// the complete transform. The build reads the path back and emits the file,\n// and no shared state has to cross the build and render boundary.\nexport function createImageVariantPath(\n descriptor: ImageVariantDescriptor,\n optimizerPath: string,\n) {\n if (descriptor.sourceKind === \"remote\") {\n throw new Error(\n `Image source ${JSON.stringify(descriptor.src)} is remote. A static image loader can only emit a local image.`,\n );\n }\n\n const quality = descriptor.quality === undefined\n ? \"\"\n : `.q${descriptor.quality}`;\n\n return `${optimizerPath}${descriptor.src}.w${descriptor.width}${quality}.${\n resolveVariantExtension(descriptor)\n }`;\n}\n\nexport function parseImageVariantPath(\n pathname: string,\n optimizerPath: string,\n): ImageVariantDescriptor | undefined {\n if (!pathname.startsWith(`${optimizerPath}/`)) {\n return undefined;\n }\n\n const match = variantNamePattern.exec(pathname.slice(optimizerPath.length));\n\n if (!match) {\n return undefined;\n }\n\n const [, src, rawWidth, rawQuality, extension] = match;\n const format = extensionFormats[extension!];\n const width = Number(rawWidth);\n const quality = rawQuality === undefined ? undefined : Number(rawQuality);\n\n if (\n !format ||\n !imageSourceExtension(src!) ||\n width <= 0 ||\n (quality !== undefined && (quality < 1 || quality > 100))\n ) {\n return undefined;\n }\n\n return { format, quality, sourceKind: \"local\", src: src!, width };\n}\n\nexport function resolveVariantExtension(descriptor: ImageVariantDescriptor) {\n if (descriptor.format !== \"auto\") {\n return formatExtensions[descriptor.format];\n }\n\n const extension = imageSourceExtension(descriptor.src);\n\n if (!extension) {\n throw new Error(\n `Image source ${JSON.stringify(descriptor.src)} has no known image extension. Declare an explicit format.`,\n );\n }\n\n return extension === \"jpeg\" ? \"jpg\" : extension;\n}\n\nexport function imageSourceExtension(src: string) {\n const extension = urlExtension(src);\n\n return extension in extensionFormats ? extension : undefined;\n}\n\n// The build and the development server both find variants by reading the\n// documents that the application rendered. A variant that no document\n// references is a variant that nothing can request.\nexport function collectImageVariantPaths(html: string, optimizerPath: string) {\n const pattern = new RegExp(\n `${escapeRegExp(optimizerPath)}/[^\"'\\\\s,)<>]+`,\n \"g\",\n );\n\n return [...new Set(html.match(pattern) ?? [])];\n}\n\nfunction escapeRegExp(value: string) {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n","import {\n createImageOptimizerUrl,\n createImageVariantPath,\n defaultImageOptimizerPath,\n type ImageVariantDescriptor,\n} from \"./image-url\";\n\n// `optimizer` points every variant at a request-time endpoint. `static`\n// points every variant at a file that the static build emits.\nexport type ImageLoader = \"optimizer\" | \"static\";\n\nexport type ImageFormat = \"auto\" | \"avif\" | \"webp\" | \"jpeg\" | \"png\";\n\nexport type RemoteImagePattern = {\n hostname: string;\n pathname?: string;\n port?: string;\n protocol?: \"http:\" | \"https:\";\n};\n\nexport type ImagePolicy = {\n loader?: ImageLoader;\n local?: boolean;\n optimizerPath?: string;\n remote?: readonly (string | RemoteImagePattern)[];\n};\n\nexport type ImageTransformOptions = {\n alt: string;\n format?: ImageFormat;\n height: number;\n priority?: boolean;\n quality?: number;\n sizes?: string;\n src: string;\n width: number;\n widths?: readonly number[];\n};\n\nexport type ImageVariant = {\n format: ImageFormat;\n height: number;\n src: string;\n width: number;\n};\n\nexport type ImageTransformPlan = {\n alt: string;\n decoding: \"async\";\n fetchPriority?: \"high\";\n height: number;\n loading: \"eager\" | \"lazy\";\n sizes?: string;\n source: {\n kind: \"local\" | \"remote\";\n src: string;\n };\n src: string;\n srcSet: string;\n variants: ImageVariant[];\n width: number;\n};\n\nexport function defineImages(policy: ImagePolicy): ImagePolicy {\n return policy;\n}\n\nexport function isAllowedImageSource(src: string, policy: ImagePolicy = {}) {\n return classifyImageSource(src, policy) !== null;\n}\n\nexport function planImageTransform(\n options: ImageTransformOptions,\n policy: ImagePolicy = {},\n): ImageTransformPlan {\n const source = classifyImageSource(options.src, policy);\n\n if (!source) {\n throw new Error(`Image source \"${options.src}\" is not allowed by the image policy.`);\n }\n\n validateImageDimension(\"width\", options.width);\n validateImageDimension(\"height\", options.height);\n validateImageQuality(options.quality);\n\n const format = options.format ?? \"auto\";\n const loader = policy.loader ?? \"optimizer\";\n const optimizerPath = policy.optimizerPath ?? defaultImageOptimizerPath;\n const widths = normalizeVariantWidths(options.width, options.widths);\n const variants = widths.map((width) => {\n const height = Math.round((options.height / options.width) * width);\n const descriptor: ImageVariantDescriptor = {\n format,\n quality: options.quality,\n sourceKind: source.kind,\n src: source.kind === \"remote\" ? source.src : options.src,\n width,\n };\n\n return {\n format,\n height,\n src: loader === \"static\"\n ? createImageVariantPath(descriptor, optimizerPath)\n : createImageOptimizerUrl(descriptor, optimizerPath),\n width,\n };\n });\n const primaryVariant = variants[0];\n\n return {\n alt: options.alt,\n decoding: \"async\",\n fetchPriority: options.priority ? \"high\" : undefined,\n height: options.height,\n loading: options.priority ? \"eager\" : \"lazy\",\n sizes: options.sizes,\n source,\n src: primaryVariant.src,\n srcSet: variants\n .map((variant) => `${variant.src} ${variant.width}w`)\n .join(\", \"),\n variants,\n width: options.width,\n };\n}\n\nfunction classifyImageSource(\n src: string,\n policy: ImagePolicy,\n): ImageTransformPlan[\"source\"] | null {\n if (src.startsWith(\"/\") && !src.startsWith(\"//\")) {\n return policy.local === false ? null : { kind: \"local\", src };\n }\n\n let url: URL;\n\n try {\n url = new URL(src);\n } catch {\n return null;\n }\n\n if (url.protocol !== \"https:\" && url.protocol !== \"http:\") {\n return null;\n }\n\n return isAllowedRemoteImage(url, policy.remote ?? [])\n ? { kind: \"remote\", src: url.toString() }\n : null;\n}\n\nfunction isAllowedRemoteImage(\n url: URL,\n remotes: readonly (string | RemoteImagePattern)[],\n) {\n return remotes.some((remote) =>\n typeof remote === \"string\"\n ? matchesRemoteOrigin(url, remote)\n : matchesRemotePattern(url, remote),\n );\n}\n\nfunction matchesRemoteOrigin(url: URL, origin: string) {\n try {\n return url.origin === new URL(origin).origin;\n } catch {\n return false;\n }\n}\n\nfunction matchesRemotePattern(url: URL, pattern: RemoteImagePattern) {\n if (pattern.protocol && url.protocol !== pattern.protocol) {\n return false;\n }\n\n if (url.hostname !== pattern.hostname) {\n return false;\n }\n\n if (pattern.port !== undefined && url.port !== pattern.port) {\n return false;\n }\n\n return pattern.pathname\n ? matchesPathnamePattern(url.pathname, pattern.pathname)\n : true;\n}\n\nfunction matchesPathnamePattern(pathname: string, pattern: string) {\n if (pattern.endsWith(\"*\")) {\n return pathname.startsWith(pattern.slice(0, -1));\n }\n\n return pathname === pattern;\n}\n\nfunction validateImageDimension(name: \"height\" | \"width\", value: number) {\n if (!Number.isInteger(value) || value <= 0) {\n throw new Error(`Image ${name} must be a positive integer.`);\n }\n}\n\nfunction validateImageQuality(quality: number | undefined) {\n if (quality === undefined) {\n return;\n }\n\n if (!Number.isInteger(quality) || quality < 1 || quality > 100) {\n throw new Error(\"Image quality must be an integer between 1 and 100.\");\n }\n}\n\nfunction normalizeVariantWidths(width: number, widths: readonly number[] | undefined) {\n const candidates = widths ?? [width, width * 2];\n const uniqueWidths = [...new Set(candidates)];\n\n for (const candidate of uniqueWidths) {\n validateImageDimension(\"width\", candidate);\n }\n\n return uniqueWidths.sort((left, right) => left - right);\n}\n\nexport type ImageRequestRejection = {\n reason: string;\n status: 400 | 403;\n};\n\nexport type ImageRequestResult =\n | { descriptor: ImageVariantDescriptor; ok: true }\n | { ok: false; rejection: ImageRequestRejection };\n\nconst imageFormats = new Set<ImageFormat>([\n \"avif\",\n \"jpeg\",\n \"png\",\n \"webp\",\n]);\n\n// The runtime optimizer reads a query that any client can write. It repeats\n// the policy check that the planner made, so an unallowed source never\n// reaches the file system or the network.\nexport function parseImageOptimizerRequest(\n url: URL,\n policy: ImagePolicy = {},\n): ImageRequestResult {\n const src = url.searchParams.get(\"src\");\n\n if (!src) {\n return reject(400, \"The image request must declare a src parameter.\");\n }\n\n const source = classifyImageSource(src, policy);\n\n if (!source) {\n return reject(403, \"The image policy does not allow this image source.\");\n }\n\n const width = Number(url.searchParams.get(\"w\"));\n\n if (!Number.isInteger(width) || width <= 0) {\n return reject(400, \"The image width must be a positive integer.\");\n }\n\n const rawQuality = url.searchParams.get(\"q\");\n const quality = rawQuality === null ? undefined : Number(rawQuality);\n\n if (\n quality !== undefined &&\n (!Number.isInteger(quality) || quality < 1 || quality > 100)\n ) {\n return reject(400, \"The image quality must be an integer from 1 through 100.\");\n }\n\n const rawFormat = url.searchParams.get(\"f\");\n\n // TYPE-EVIDENCE: the set membership check confirms the raw format is a known image format. The cast matches that check.\n if (rawFormat !== null && !imageFormats.has(rawFormat as ImageFormat)) {\n return reject(400, \"The image format is not supported.\");\n }\n\n // TYPE-EVIDENCE: the raw format value is a string that names an image format or is null. The cast labels it with the format union.\n return {\n descriptor: {\n format: (rawFormat as ImageFormat | null) ?? \"auto\",\n quality,\n sourceKind: source.kind,\n src: source.src,\n width,\n },\n ok: true,\n };\n}\n\nfunction reject(status: 400 | 403, reason: string): ImageRequestResult {\n return { ok: false, rejection: { reason, status } };\n}\n"],"names":["urlPath","url","urlExtension","name","defaultFontPath","fontFormats","fontFaceFormats","fontMediaTypes","font","options","src","isRemoteSource","assertKnownFormat","defineFonts","fonts","fontAssetFileName","definition","family","slug","weight","fontFormat","fontAssetUrl","basePath","fontStylesheetUrl","fontMediaType","file","format","fontLinks","fontPreloadLinks","preload","renderFontFaceCss","escapeCss","fontSources","origins","value","defaultImageOptimizerPath","formatExtensions","extensionFormats","variantNamePattern","createImageOptimizerUrl","descriptor","optimizerPath","params","createImageVariantPath","quality","resolveVariantExtension","parseImageVariantPath","pathname","match","rawWidth","rawQuality","extension","width","imageSourceExtension","collectImageVariantPaths","html","pattern","escapeRegExp","defineImages","policy","isAllowedImageSource","classifyImageSource","planImageTransform","source","validateImageDimension","validateImageQuality","loader","variants","normalizeVariantWidths","height","primaryVariant","variant","isAllowedRemoteImage","remotes","remote","matchesRemoteOrigin","matchesRemotePattern","origin","matchesPathnamePattern","widths","candidates","uniqueWidths","candidate","left","right","imageFormats","parseImageOptimizerRequest","reject","rawFormat","status","reason"],"mappings":";AAMO,SAASA,EAAQC,GAA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A,YAAYmB,EAAO;AAAA,MACnB,KAAKA,EAAO;AAAA,MACZ,OAAAX;AAAA,IAAA;AAAA,IAEF,IAAI;AAAA,EAAA;AAER;AAEA,SAASmC,EAAOE,GAAmBC,GAAoC;AACrE,SAAO,EAAE,IAAI,IAAO,WAAW,EAAE,QAAAA,GAAQ,QAAAD,IAAO;AAClD;"}
|
|
@@ -757,6 +757,7 @@ const Xe = {
|
|
|
757
757
|
backgroundLifetime: !1,
|
|
758
758
|
crossOriginIsolationHeaders: !1,
|
|
759
759
|
nonceInjection: !1,
|
|
760
|
+
requestTimeoutEnforcement: !1,
|
|
760
761
|
sharedCache: !1,
|
|
761
762
|
staticOutput: !1,
|
|
762
763
|
streaming: !1,
|
|
@@ -798,9 +799,9 @@ export {
|
|
|
798
799
|
De as D,
|
|
799
800
|
Oe as E,
|
|
800
801
|
T as F,
|
|
801
|
-
|
|
802
|
+
$t as G,
|
|
802
803
|
ie as H,
|
|
803
|
-
|
|
804
|
+
ht as I,
|
|
804
805
|
Pe as S,
|
|
805
806
|
gt as a,
|
|
806
807
|
Ke as b,
|
|
@@ -829,4 +830,4 @@ export {
|
|
|
829
830
|
at as y,
|
|
830
831
|
ot as z
|
|
831
832
|
};
|
|
832
|
-
//# sourceMappingURL=index-
|
|
833
|
+
//# sourceMappingURL=index-0MNiR_wo.js.map
|