@demiurgejs/core 0.2.0-beta.5 → 0.2.0-beta.6
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 +14 -0
- package/bin/demiurge.mjs +6 -0
- package/dist/chunks/{document-shell-9GPwtcTt.js → document-shell-C0aPrkhd.js} +2 -2
- package/dist/chunks/{document-shell-9GPwtcTt.js.map → document-shell-C0aPrkhd.js.map} +1 -1
- package/dist/chunks/image-CRerJ5BY.js +145 -0
- package/dist/chunks/image-CRerJ5BY.js.map +1 -0
- package/dist/chunks/{image-codec-Dh1POFhE.js → image-codec-CQ8Cwxwb.js} +2 -2
- package/dist/chunks/{image-codec-Dh1POFhE.js.map → image-codec-CQ8Cwxwb.js.map} +1 -1
- package/dist/chunks/{images-CG7ZzayG.js → images-QgdmLyQ3.js} +11 -11
- package/dist/chunks/{images-CG7ZzayG.js.map → images-QgdmLyQ3.js.map} +1 -1
- package/dist/chunks/{index-0MNiR_wo.js → index-LYve1rQp.js} +286 -351
- package/dist/chunks/index-LYve1rQp.js.map +1 -0
- package/dist/chunks/links-iU22QkCE.js +68 -0
- package/dist/chunks/links-iU22QkCE.js.map +1 -0
- package/dist/chunks/{plugin-BZauDxRY.js → plugin-bkP6WwrS.js} +13 -12
- package/dist/chunks/{plugin-BZauDxRY.js.map → plugin-bkP6WwrS.js.map} +1 -1
- package/dist/chunks/runtime-BH519j2t.js +294 -0
- package/dist/chunks/runtime-BH519j2t.js.map +1 -0
- package/dist/chunks/streaming-BlKlC3nw.js +427 -0
- package/dist/chunks/streaming-BlKlC3nw.js.map +1 -0
- package/dist/chunks/{testing-CUwGj2ie.js → testing-BEW1nchS.js} +645 -630
- package/dist/chunks/testing-BEW1nchS.js.map +1 -0
- package/dist/chunks/{vite-QoqrGl6f.js → vite-BADZA8Fl.js} +73 -70
- package/dist/chunks/vite-BADZA8Fl.js.map +1 -0
- package/dist/cli.d.ts +8 -2
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +186 -122
- package/dist/cli.js.map +1 -1
- package/dist/config/index.js +2 -2
- package/dist/config/types.d.ts +3 -1
- package/dist/config/types.d.ts.map +1 -1
- package/dist/config/validate.d.ts.map +1 -1
- package/dist/data/cache.d.ts +5 -0
- package/dist/data/cache.d.ts.map +1 -1
- package/dist/data/index.d.ts +1 -1
- package/dist/data/index.d.ts.map +1 -1
- package/dist/data/testing.d.ts.map +1 -1
- package/dist/data/testing.js +101 -67
- package/dist/data/testing.js.map +1 -1
- package/dist/data/tiered.d.ts.map +1 -1
- package/dist/edge/index.js +27 -26
- package/dist/edge/index.js.map +1 -1
- package/dist/edge/stores.d.ts.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +126 -125
- package/dist/index.js.map +1 -1
- package/dist/internal/testing.js +2 -2
- package/dist/kv/index.js +7 -6
- package/dist/kv/index.js.map +1 -1
- package/dist/kv/store.d.ts.map +1 -1
- package/dist/node/http.d.ts +2 -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 +12 -11
- package/dist/node/index.js.map +1 -1
- package/dist/node/serve.d.ts +4 -0
- package/dist/node/serve.d.ts.map +1 -1
- package/dist/redis/index.js +29 -28
- package/dist/redis/index.js.map +1 -1
- package/dist/redis/store.d.ts.map +1 -1
- package/dist/route/serialization.d.ts +4 -4
- package/dist/route/serialization.d.ts.map +1 -1
- package/dist/static/index.d.ts.map +1 -1
- package/dist/static/index.js +255 -255
- package/dist/static/index.js.map +1 -1
- package/dist/static/testing.d.ts +26 -0
- package/dist/static/testing.d.ts.map +1 -0
- package/dist/static/testing.js +76 -0
- package/dist/static/testing.js.map +1 -0
- package/dist/testing/index.d.ts +47 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +99 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/vercel/build.d.ts +31 -0
- package/dist/vercel/build.d.ts.map +1 -0
- package/dist/vercel/config.d.ts +15 -0
- package/dist/vercel/config.d.ts.map +1 -0
- package/dist/vercel/index.d.ts +7 -0
- package/dist/vercel/index.d.ts.map +1 -0
- package/dist/vercel/index.js +11 -0
- package/dist/vercel/index.js.map +1 -0
- package/dist/vercel/runtime.d.ts +29 -0
- package/dist/vercel/runtime.d.ts.map +1 -0
- package/dist/vite/index.js +1 -1
- package/package.json +13 -1
- package/dist/chunks/index-0MNiR_wo.js.map +0 -1
- package/dist/chunks/streaming-GYIsVTQH.js +0 -560
- package/dist/chunks/streaming-GYIsVTQH.js.map +0 -1
- package/dist/chunks/testing-CUwGj2ie.js.map +0 -1
- package/dist/chunks/vite-QoqrGl6f.js.map +0 -1
package/README.md
CHANGED
|
@@ -17,6 +17,18 @@ pnpm add @demiurgejs/core react react-dom
|
|
|
17
17
|
pnpm add -D vite @vitejs/plugin-react typescript @types/node @types/react @types/react-dom
|
|
18
18
|
```
|
|
19
19
|
|
|
20
|
+
Declare the root policy for a public page application:
|
|
21
|
+
|
|
22
|
+
```ts
|
|
23
|
+
// src/routes/@policy.ts
|
|
24
|
+
import { security } from "@demiurgejs/core";
|
|
25
|
+
|
|
26
|
+
export const policy = {
|
|
27
|
+
access: { public: true },
|
|
28
|
+
document: security.strict(),
|
|
29
|
+
};
|
|
30
|
+
```
|
|
31
|
+
|
|
20
32
|
Define a route under `src/routes`:
|
|
21
33
|
|
|
22
34
|
```tsx
|
|
@@ -65,6 +77,7 @@ covers host allowlists, proxy trust, timeouts, and graceful shutdown.
|
|
|
65
77
|
|
|
66
78
|
- `@demiurgejs/core` — routes, document APIs, security, caching, and browser runtime
|
|
67
79
|
- `@demiurgejs/core/node` — production Node HTTP, SSR, and static-file adapter
|
|
80
|
+
- `@demiurgejs/core/vercel` — Vercel Node Function deployment adapter
|
|
68
81
|
- `@demiurgejs/core/static` — static-output adapter
|
|
69
82
|
- `@demiurgejs/core/redis` — Redis-backed cache store with cross-instance tag invalidation
|
|
70
83
|
- `@demiurgejs/core/config` — the application configuration contract
|
|
@@ -72,6 +85,7 @@ covers host allowlists, proxy trust, timeouts, and graceful shutdown.
|
|
|
72
85
|
- `@demiurgejs/core/adapter/testing` — adapter capability conformance contract
|
|
73
86
|
- `@demiurgejs/core/deployment/testing` — deployment conformance kit for provider translation and production artifacts
|
|
74
87
|
- `@demiurgejs/core/data/testing` — cache-store conformance contract
|
|
88
|
+
- `@demiurgejs/core/testing` — application route-pipeline test boundary
|
|
75
89
|
- `@demiurgejs/core/internal/testing` — explicitly unstable test helpers
|
|
76
90
|
|
|
77
91
|
Vite is an optional peer dependency with `@vitejs/plugin-react`. A consumer
|
package/bin/demiurge.mjs
CHANGED
|
@@ -10,6 +10,7 @@ import {
|
|
|
10
10
|
runBuild,
|
|
11
11
|
runDev,
|
|
12
12
|
runInspectCommand,
|
|
13
|
+
runStart,
|
|
13
14
|
} from "../dist/cli.js";
|
|
14
15
|
import { loadDemiurgeConfig } from "../dist/config/index.js";
|
|
15
16
|
import {
|
|
@@ -64,6 +65,11 @@ async function main() {
|
|
|
64
65
|
return;
|
|
65
66
|
}
|
|
66
67
|
|
|
68
|
+
if (options.command === "start") {
|
|
69
|
+
await runStart(options, config);
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
|
|
67
73
|
const outDir = resolvePreviewOutputDirectory(
|
|
68
74
|
config.root,
|
|
69
75
|
options.outDir,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { r as c } from "./index-
|
|
1
|
+
import { r as c } from "./index-LYve1rQp.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-C0aPrkhd.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"document-shell-
|
|
1
|
+
{"version":3,"file":"document-shell-C0aPrkhd.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;"}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { createHash as A } from "node:crypto";
|
|
2
|
+
import { r as R, n as b, t as E } from "./image-codec-CQ8Cwxwb.js";
|
|
3
|
+
import { d as H, a as I, i as T, p as $, u as L } from "./images-QgdmLyQ3.js";
|
|
4
|
+
import { R as w } from "./static-files-ehaD1kE7.js";
|
|
5
|
+
import { readFile as S } from "node:fs/promises";
|
|
6
|
+
import { resolve as v, relative as z, sep as D } from "node:path";
|
|
7
|
+
function B(e) {
|
|
8
|
+
const t = e.basePath ?? H;
|
|
9
|
+
let n;
|
|
10
|
+
return async function(i) {
|
|
11
|
+
const c = new URL(i.url);
|
|
12
|
+
if (!c.pathname.startsWith(`${t}/`))
|
|
13
|
+
return null;
|
|
14
|
+
if (i.method !== "GET" && i.method !== "HEAD")
|
|
15
|
+
return new Response("Method Not Allowed", {
|
|
16
|
+
headers: {
|
|
17
|
+
allow: "GET, HEAD",
|
|
18
|
+
"content-type": "text/plain; charset=utf-8"
|
|
19
|
+
},
|
|
20
|
+
status: 405
|
|
21
|
+
});
|
|
22
|
+
n ??= o();
|
|
23
|
+
let d;
|
|
24
|
+
try {
|
|
25
|
+
d = await n;
|
|
26
|
+
} catch (r) {
|
|
27
|
+
throw n = void 0, r;
|
|
28
|
+
}
|
|
29
|
+
const l = d.get(c.pathname);
|
|
30
|
+
return l ? F(i, l) : null;
|
|
31
|
+
};
|
|
32
|
+
async function o() {
|
|
33
|
+
const s = await R({ ...e, basePath: t });
|
|
34
|
+
return new Map(s.map((i) => [i.url, i]));
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
function F(e, t) {
|
|
38
|
+
const n = `"${A("sha256").update(t.body).digest("base64url").slice(0, 27)}"`, o = new Headers({
|
|
39
|
+
"cache-control": w,
|
|
40
|
+
"content-type": t.contentType,
|
|
41
|
+
etag: n
|
|
42
|
+
});
|
|
43
|
+
return e.headers.get("if-none-match") === n ? new Response(null, { headers: o, status: 304 }) : (o.set("content-length", String(t.body.byteLength)), new Response(
|
|
44
|
+
e.method === "HEAD" ? null : t.body,
|
|
45
|
+
{ headers: o, status: 200 }
|
|
46
|
+
));
|
|
47
|
+
}
|
|
48
|
+
const x = 64, P = 20 * 1024 * 1024;
|
|
49
|
+
function V(e) {
|
|
50
|
+
const t = v(e.root), n = e.policy ?? {}, o = n.optimizerPath ?? I, s = e.cacheSize ?? x, i = e.fetch ?? ((l, r) => fetch(l, r)), c = /* @__PURE__ */ new Map();
|
|
51
|
+
return async function(r) {
|
|
52
|
+
const u = new URL(r.url), a = u.pathname === o ? void 0 : e.resolveVariant?.(u.pathname);
|
|
53
|
+
if (u.pathname !== o && !a)
|
|
54
|
+
return null;
|
|
55
|
+
if (r.method !== "GET" && r.method !== "HEAD")
|
|
56
|
+
return p(405, "Method Not Allowed", {
|
|
57
|
+
allow: "GET, HEAD"
|
|
58
|
+
});
|
|
59
|
+
if (a && !T(a.src, n))
|
|
60
|
+
return p(403, "The image policy does not allow this image source.");
|
|
61
|
+
const h = a ? { descriptor: a, ok: !0 } : $(u, n);
|
|
62
|
+
if (!h.ok)
|
|
63
|
+
return p(h.rejection.status, h.rejection.reason);
|
|
64
|
+
const y = b(
|
|
65
|
+
h.descriptor,
|
|
66
|
+
a ? null : r.headers.get("accept")
|
|
67
|
+
), f = `${y}|${u.pathname}${u.search}`;
|
|
68
|
+
let m = c.get(f);
|
|
69
|
+
if (m)
|
|
70
|
+
c.delete(f);
|
|
71
|
+
else {
|
|
72
|
+
const g = await d(h.descriptor);
|
|
73
|
+
if (!g)
|
|
74
|
+
return p(404, "The image source does not exist.");
|
|
75
|
+
m = await E(g, {
|
|
76
|
+
format: y,
|
|
77
|
+
quality: h.descriptor.quality,
|
|
78
|
+
width: h.descriptor.width
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
for (c.set(f, m); c.size > s; )
|
|
82
|
+
c.delete(c.keys().next().value);
|
|
83
|
+
return k(
|
|
84
|
+
r,
|
|
85
|
+
m,
|
|
86
|
+
!a && h.descriptor.format === "auto"
|
|
87
|
+
);
|
|
88
|
+
};
|
|
89
|
+
async function d(l) {
|
|
90
|
+
if (l.sourceKind === "remote") {
|
|
91
|
+
const u = await i(l.src);
|
|
92
|
+
if (!u.ok)
|
|
93
|
+
return;
|
|
94
|
+
const a = new Uint8Array(await u.arrayBuffer());
|
|
95
|
+
return a.byteLength > P ? void 0 : a;
|
|
96
|
+
}
|
|
97
|
+
const r = M(t, l.src);
|
|
98
|
+
if (r)
|
|
99
|
+
try {
|
|
100
|
+
return new Uint8Array(await S(r));
|
|
101
|
+
} catch {
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
function k(e, t, n) {
|
|
107
|
+
const o = `"${C(t.body)}"`, s = new Headers({
|
|
108
|
+
"cache-control": w,
|
|
109
|
+
"content-type": t.contentType,
|
|
110
|
+
etag: o
|
|
111
|
+
});
|
|
112
|
+
return n && s.set("vary", "accept"), e.headers.get("if-none-match") === o ? new Response(null, { headers: s, status: 304 }) : (s.set("content-length", String(t.body.byteLength)), new Response(
|
|
113
|
+
e.method === "HEAD" ? null : t.body,
|
|
114
|
+
{ headers: s, status: 200 }
|
|
115
|
+
));
|
|
116
|
+
}
|
|
117
|
+
function p(e, t, n = {}) {
|
|
118
|
+
return new Response(t, {
|
|
119
|
+
headers: { "content-type": "text/plain; charset=utf-8", ...n },
|
|
120
|
+
status: e
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
function M(e, t) {
|
|
124
|
+
let n;
|
|
125
|
+
try {
|
|
126
|
+
n = decodeURIComponent(L(t));
|
|
127
|
+
} catch {
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
if (n.split(/[\\/]/).includes(".."))
|
|
131
|
+
return;
|
|
132
|
+
const o = v(e, `.${n}`);
|
|
133
|
+
return z(e, o).split(D).includes("..") ? void 0 : o;
|
|
134
|
+
}
|
|
135
|
+
function C(e) {
|
|
136
|
+
let t = 2166136261, n = 16777619;
|
|
137
|
+
for (const o of e)
|
|
138
|
+
t = Math.imul(t ^ o, 16777619) >>> 0, n = Math.imul(n ^ o, 2246822507) >>> 0;
|
|
139
|
+
return `${t.toString(36)}${n.toString(36)}${e.byteLength.toString(36)}`;
|
|
140
|
+
}
|
|
141
|
+
export {
|
|
142
|
+
V as a,
|
|
143
|
+
B as c
|
|
144
|
+
};
|
|
145
|
+
//# sourceMappingURL=image-CRerJ5BY.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"image-CRerJ5BY.js","sources":["../../src/node/font.ts","../../src/node/image.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport {\n resolveFontAssets,\n type FontAsset,\n type FontAssetOptions,\n} from \"../platform/font-assets\";\nimport { defaultFontPath } from \"../platform/fonts\";\nimport { REVALIDATED_FILE_CACHE_CONTROL } from \"../static-files\";\nimport type { StaticFileHandler } from \"./static\";\n\nexport type FontAssetHandlerOptions = FontAssetOptions;\n\n// The handler answers the self-hosted font URLs that the document declares.\n// It returns null for every other path, so it composes with the static file\n// handler and the route pipeline. The image optimizer composes the same way.\nexport function createFontAssetHandler(\n options: FontAssetHandlerOptions,\n): StaticFileHandler {\n const basePath = options.basePath ?? defaultFontPath;\n let pending: Promise<Map<string, FontAsset>> | undefined;\n\n return async function handleFontRequest(request) {\n const url = new URL(request.url);\n\n if (!url.pathname.startsWith(`${basePath}/`)) {\n return null;\n }\n\n if (request.method !== \"GET\" && request.method !== \"HEAD\") {\n return new Response(\"Method Not Allowed\", {\n headers: {\n allow: \"GET, HEAD\",\n \"content-type\": \"text/plain; charset=utf-8\",\n },\n status: 405,\n });\n }\n\n pending ??= loadAssets();\n\n let assets: Map<string, FontAsset>;\n\n try {\n assets = await pending;\n } catch (error) {\n pending = undefined;\n throw error;\n }\n\n const asset = assets.get(url.pathname);\n\n return asset ? respond(request, asset) : null;\n };\n\n async function loadAssets() {\n const assets = await resolveFontAssets({ ...options, basePath });\n\n return new Map(assets.map((asset) => [asset.url, asset]));\n }\n}\n\n// A font URL names the family, the weight, and the style rather than the\n// content of the file. A strong entity tag keeps a replaced file cheap to\n// revalidate, the same trade the image optimizer makes.\nfunction respond(request: Request, asset: FontAsset) {\n const etag = `\"${createHash(\"sha256\").update(asset.body).digest(\"base64url\").slice(0, 27)}\"`;\n const headers = new Headers({\n \"cache-control\": REVALIDATED_FILE_CACHE_CONTROL,\n \"content-type\": asset.contentType,\n etag,\n });\n\n if (request.headers.get(\"if-none-match\") === etag) {\n return new Response(null, { headers, status: 304 });\n }\n\n headers.set(\"content-length\", String(asset.body.byteLength));\n\n // TYPE-EVIDENCE: the font body is an ArrayBuffer-backed view that the DOM body type accepts.\n return new Response(\n request.method === \"HEAD\" ? null : (asset.body as Uint8Array<ArrayBuffer>),\n { headers, status: 200 },\n );\n}\n","import { readFile } from \"node:fs/promises\";\nimport { relative, resolve, sep } from \"node:path\";\nimport {\n negotiateImageFormat,\n transformImage,\n type EncodedImage,\n} from \"../platform/image-codec\";\nimport { defaultImageOptimizerPath } from \"../platform/image-url\";\nimport type { ImageVariantDescriptor } from \"../platform/image-url\";\nimport {\n isAllowedImageSource,\n parseImageOptimizerRequest,\n} from \"../platform/images\";\nimport type { ImagePolicy } from \"../platform/images\";\nimport { urlPath } from \"../platform/url\";\nimport type { StaticFileHandler } from \"./static\";\nimport { REVALIDATED_FILE_CACHE_CONTROL } from \"../static-files\";\n\nexport type ImageOptimizerFetch = (\n input: string,\n init?: { signal?: AbortSignal },\n) => Promise<Response>;\n\nexport type ImageOptimizerOptions = {\n // The number of encoded variants that stay in memory. The optimizer keeps\n // the most recent request at the front.\n cacheSize?: number;\n fetch?: ImageOptimizerFetch;\n policy?: ImagePolicy;\n // Maps a static loader variant path back to the transform behind it. The\n // development server passes the recorded plans, so a page renders the same\n // URL in development and in the static build.\n resolveVariant?: (pathname: string) => ImageVariantDescriptor | undefined;\n // The directory that holds every local source image, normally the client\n // build output.\n root: string;\n};\n\nconst defaultCacheSize = 64;\nconst maximumRemoteImageBytes = 20 * 1024 * 1024;\n\n// The optimizer answers the same URL that `planImageTransform` writes. It\n// returns null for every other path, so it composes with the static file\n// handler and the route pipeline.\nexport function createImageOptimizer(\n options: ImageOptimizerOptions,\n): StaticFileHandler {\n const root = resolve(options.root);\n const policy = options.policy ?? {};\n const optimizerPath = policy.optimizerPath ?? defaultImageOptimizerPath;\n const cacheSize = options.cacheSize ?? defaultCacheSize;\n const load = options.fetch ?? ((input, init) => fetch(input, init));\n const cache = new Map<string, EncodedImage>();\n\n return async function handleImageRequest(request) {\n const url = new URL(request.url);\n const variant = url.pathname === optimizerPath\n ? undefined\n : options.resolveVariant?.(url.pathname);\n\n if (url.pathname !== optimizerPath && !variant) {\n return null;\n }\n\n if (request.method !== \"GET\" && request.method !== \"HEAD\") {\n return plainText(405, \"Method Not Allowed\", {\n allow: \"GET, HEAD\",\n });\n }\n\n if (variant && !isAllowedImageSource(variant.src, policy)) {\n return plainText(403, \"The image policy does not allow this image source.\");\n }\n\n const parsed = variant\n ? ({ descriptor: variant, ok: true } as const)\n : parseImageOptimizerRequest(url, policy);\n\n if (!parsed.ok) {\n return plainText(parsed.rejection.status, parsed.rejection.reason);\n }\n\n const format = negotiateImageFormat(\n parsed.descriptor,\n variant ? null : request.headers.get(\"accept\"),\n );\n const key = `${format}|${url.pathname}${url.search}`;\n let encoded = cache.get(key);\n\n if (encoded) {\n cache.delete(key);\n } else {\n const source = await readSource(parsed.descriptor);\n\n if (!source) {\n return plainText(404, \"The image source does not exist.\");\n }\n\n encoded = await transformImage(source, {\n format,\n quality: parsed.descriptor.quality,\n width: parsed.descriptor.width,\n });\n }\n\n cache.set(key, encoded);\n\n while (cache.size > cacheSize) {\n // TYPE-EVIDENCE: the loop runs only while the cache holds an entry. The next key therefore exists as a string.\n cache.delete(cache.keys().next().value as string);\n }\n\n return respond(\n request,\n encoded,\n !variant && parsed.descriptor.format === \"auto\",\n );\n };\n\n async function readSource(descriptor: ImageVariantDescriptor) {\n if (descriptor.sourceKind === \"remote\") {\n const response = await load(descriptor.src);\n\n if (!response.ok) {\n return undefined;\n }\n\n const body = new Uint8Array(await response.arrayBuffer());\n\n return body.byteLength > maximumRemoteImageBytes ? undefined : body;\n }\n\n const file = resolveLocalFile(root, descriptor.src);\n\n if (!file) {\n return undefined;\n }\n\n try {\n return new Uint8Array(await readFile(file));\n } catch {\n return undefined;\n }\n }\n}\n\n// The URL carries the source path rather than a content hash, so a long\n// immutable lifetime would outlive a replaced source file. A strong entity\n// tag keeps the revalidation cheap instead.\nfunction respond(request: Request, encoded: EncodedImage, varyOnAccept: boolean) {\n const etag = `\"${weakHash(encoded.body)}\"`;\n const headers = new Headers({\n \"cache-control\": REVALIDATED_FILE_CACHE_CONTROL,\n \"content-type\": encoded.contentType,\n etag,\n });\n\n if (varyOnAccept) {\n headers.set(\"vary\", \"accept\");\n }\n\n if (request.headers.get(\"if-none-match\") === etag) {\n return new Response(null, { headers, status: 304 });\n }\n\n headers.set(\"content-length\", String(encoded.body.byteLength));\n\n // TYPE-EVIDENCE: the encoded body is an ArrayBuffer-backed view that the DOM body type accepts.\n return new Response(\n request.method === \"HEAD\" ? null : (encoded.body as Uint8Array<ArrayBuffer>),\n { headers, status: 200 },\n );\n}\n\nfunction plainText(\n status: number,\n body: string,\n extraHeaders: Record<string, string> = {},\n) {\n return new Response(body, {\n headers: { \"content-type\": \"text/plain; charset=utf-8\", ...extraHeaders },\n status,\n });\n}\n\nfunction resolveLocalFile(root: string, src: string) {\n let decoded: string;\n\n try {\n decoded = decodeURIComponent(urlPath(src));\n } catch {\n return undefined;\n }\n\n if (decoded.split(/[\\\\/]/).includes(\"..\")) {\n return undefined;\n }\n\n const file = resolve(root, `.${decoded}`);\n\n return relative(root, file).split(sep).includes(\"..\") ? undefined : file;\n}\n\nfunction weakHash(body: Uint8Array) {\n let low = 0x811c9dc5;\n let high = 0x01000193;\n\n for (const byte of body) {\n low = Math.imul(low ^ byte, 0x01000193) >>> 0;\n high = Math.imul(high ^ byte, 0x85ebca6b) >>> 0;\n }\n\n return `${low.toString(36)}${high.toString(36)}${body.byteLength.toString(36)}`;\n}\n"],"names":["createFontAssetHandler","options","basePath","defaultFontPath","pending","request","url","loadAssets","assets","error","asset","respond","resolveFontAssets","etag","createHash","headers","REVALIDATED_FILE_CACHE_CONTROL","defaultCacheSize","maximumRemoteImageBytes","createImageOptimizer","root","resolve","policy","optimizerPath","defaultImageOptimizerPath","cacheSize","load","input","init","cache","variant","plainText","isAllowedImageSource","parsed","parseImageOptimizerRequest","format","negotiateImageFormat","key","encoded","source","readSource","transformImage","descriptor","response","body","file","resolveLocalFile","readFile","varyOnAccept","weakHash","status","extraHeaders","src","decoded","urlPath","relative","sep","low","high","byte"],"mappings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kdir 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,
|
|
4
|
+
import { d as v, f as S, b as N, r as E, c as J, e as O, g as j } from "./images-QgdmLyQ3.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-CQ8Cwxwb.js.map
|
|
@@ -1 +1 @@
|
|
|
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,gBAAgB,aAAa,OAAO;AAAA,EAAA,GAE/DI,IAAOR,EAAQ,UAAU,CAACS,GAAOC,MAAS,MAAMD,GAAOC,CAAI,IAC3DC,wBAAgB,IAAA,GAChBC,IAAsB,CAAA;AAE5B,aAAWC,KAAcZ,GAAO;AAC9B,QAAI,CAACY,EAAW;AACd;AAGF,UAAMC,IAAOC,EAAkBF,CAAU,GACnCG,IAAUL,EAAU,IAAIG,CAAI;AAElC,QAAIE,MAAY,QAAW;AACzB,UAAIA,MAAYH,EAAW;AACzB,cAAM,IAAI;AAAA,UACR,eAAe,KAAK,UAAUA,EAA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iB;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-CQ8Cwxwb.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,gBAAgB,aAAa,OAAO;AAAA,EAAA,GAE/DI,IAAOR,EAAQ,UAAU,CAACS,GAAOC,MAAS,MAAMD,GAAOC,CAAI,IAC3DC,wBAAgB,IAAA,GAChBC,IAAsB,CAAA;AAE5B,aAAWC,KAAcZ,GAAO;AAC9B,QAAI,CAACY,EAAW;AACd;AAGF,UAAMC,IAAOC,EAAkBF,CAAU,GACnCG,IAAUL,EAAU,IAAIG,CAAI;AAElC,QAAIE,MAAY,QAAW;AACzB,UAAIA,MAAYH,EAAW;AACzB,cAAM,IAAI;AAAA,UACR,eAAe,KAAK,UAAUA,EAAW,MAAM,CAAC,oDAAoD,KAAK,UAAUC,CAAI,CAAC;AAAA,QAAA;AAI5H;AAAA,IACF;AAEA,IAAAH,EAAU,IAAIG,GAAMD,EAAW,GAAG,GAClCD,EAAO,KAAK;AAAA,MACV,MAAM,MAAMK,EAAaJ,GAAY,EAAE,UAAAP,GAAU,MAAAE,GAAM,MAAAJ,GAAM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 @@
|
|
|
1
|
-
import { p as P } from "./
|
|
1
|
+
import { p as P } from "./links-iU22QkCE.js";
|
|
2
2
|
function j(t) {
|
|
3
3
|
return t.split("?")[0].split("#")[0];
|
|
4
4
|
}
|
|
@@ -322,26 +322,26 @@ function c(t, e) {
|
|
|
322
322
|
return { ok: !1, rejection: { reason: e, status: t } };
|
|
323
323
|
}
|
|
324
324
|
export {
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
325
|
+
z as a,
|
|
326
|
+
R as b,
|
|
327
|
+
F as c,
|
|
328
328
|
u as d,
|
|
329
|
-
|
|
329
|
+
m as e,
|
|
330
330
|
N as f,
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
331
|
+
b as g,
|
|
332
|
+
et as h,
|
|
333
|
+
nt as i,
|
|
334
|
+
tt as j,
|
|
335
335
|
at as k,
|
|
336
336
|
B as l,
|
|
337
337
|
rt as m,
|
|
338
338
|
G as n,
|
|
339
339
|
I as o,
|
|
340
|
-
|
|
340
|
+
ot as p,
|
|
341
341
|
X as q,
|
|
342
342
|
Y as r,
|
|
343
343
|
L as s,
|
|
344
344
|
Z as t,
|
|
345
345
|
j as u
|
|
346
346
|
};
|
|
347
|
-
//# sourceMappingURL=images-
|
|
347
|
+
//# sourceMappingURL=images-QgdmLyQ3.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"images-CG7ZzayG.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;AACtE;ACmBO,MAAMC,IAAkB,mBAEzBC,IAA0C;AAAA,EAC9C,KAAK;A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,CAAK;AACxD;AAWA,MAAMC,wBAAmB,IAAiB;AAAA,EACxC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAKM,SAASC,GACdrF,GACA0D,IAAsB,IACF;AACpB,QAAMjD,IAAMT,EAAI,aAAa,IAAI,KAAK;AAEtC,MAAI,CAACS;AACH,WAAO6E,EAAO,KAAK,iDAAiD;AAGtE,QAAMxB,IAASF,EAAoBnD,GAAKiD,CAAM;AAE9C,MAAI,CAACI;AACH,WAAOwB,EAAO,KAAK,oDAAoD;AAGzE,QAAMnC,IAAQ,OAAOnD,EAAI,aAAa,IAAI,GAAG,CAAC;AAE9C,MAAI,CAAC,OAAO,UAAUmD,CAAK,KAAKA,KAAS;AACvC,WAAOmC,EAAO,KAAK,6CAA6C;AAGlE,QAAMrC,IAAajD,EAAI,aAAa,IAAI,GAAG,GACrC2C,IAAUM,MAAe,OAAO,SAAY,OAAOA,CAAU;AAEnE,MACEN,MAAY,WACX,CAAC,OAAO,UAAUA,CAAO,KAAKA,IAAU,KAAKA,IAAU;AAExD,WAAO2C,EAAO,KAAK,0DAA0D;AAG/E,QAAMC,IAAYvF,EAAI,aAAa,IAAI,GAAG;AAG1C,SAAIuF,MAAc,QAAQ,CAACH,EAAa,IAAIG,CAAwB,IAC3DD,EAAO,KAAK,oCAAoC,IAIlD;AAAA,IACL,YAAY;AAAA,MACV,QAASC,KAAoC;AAAA,MAC7C,SAAA5C;AAAA,MACA,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;"}
|
|
1
|
+
{"version":3,"file":"images-QgdmLyQ3.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,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