foldkit-media 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +95 -58
  2. package/client.d.ts +2 -2
  3. package/dist/{asset-BNQ_j5tO.d.mts → asset-Dlkss5qp.d.mts} +32 -3
  4. package/dist/asset-Dlkss5qp.d.mts.map +1 -0
  5. package/dist/browser/index.d.mts +1 -1
  6. package/dist/browser/index.mjs +1 -1
  7. package/dist/cloudflare/index.d.mts +7 -6
  8. package/dist/cloudflare/index.d.mts.map +1 -1
  9. package/dist/cloudflare/index.mjs +11 -5
  10. package/dist/cloudflare/index.mjs.map +1 -1
  11. package/dist/{describe-DdYvLhMY.d.mts → describe-CivKHl4x.d.mts} +2 -2
  12. package/dist/{describe-DdYvLhMY.d.mts.map → describe-CivKHl4x.d.mts.map} +1 -1
  13. package/dist/{describe-Cqr63Gxa.mjs → describe-h9F5stgR.mjs} +5 -2
  14. package/dist/describe-h9F5stgR.mjs.map +1 -0
  15. package/dist/index.d.mts +10 -9
  16. package/dist/index.d.mts.map +1 -1
  17. package/dist/index.mjs +11 -9
  18. package/dist/index.mjs.map +1 -1
  19. package/dist/{provider-DztvQjOr.d.mts → provider-g0Vlvlrb.d.mts} +19 -13
  20. package/dist/provider-g0Vlvlrb.d.mts.map +1 -0
  21. package/dist/server/index.d.mts +33 -15
  22. package/dist/server/index.d.mts.map +1 -1
  23. package/dist/server/index.mjs +172 -2
  24. package/dist/server/index.mjs.map +1 -1
  25. package/dist/{services-Ck-7dhIP.d.mts → services-8_h0ubLB.d.mts} +2 -2
  26. package/dist/{services-Ck-7dhIP.d.mts.map → services-8_h0ubLB.d.mts.map} +1 -1
  27. package/dist/sharp/index.d.mts +2 -2
  28. package/dist/sharp/index.mjs +1 -1
  29. package/dist/{upload-C5YM5jZR.mjs → stores-BtmSl8X3.mjs} +61 -203
  30. package/dist/stores-BtmSl8X3.mjs.map +1 -0
  31. package/dist/unpic/index.d.mts +1 -1
  32. package/dist/{upload-C4_inwfv.d.mts → upload-kp0_oK76.d.mts} +10 -10
  33. package/dist/{upload-C4_inwfv.d.mts.map → upload-kp0_oK76.d.mts.map} +1 -1
  34. package/dist/vite/index.mjs +3 -3
  35. package/dist/vite/index.mjs.map +1 -1
  36. package/package.json +1 -1
  37. package/dist/asset-BNQ_j5tO.d.mts.map +0 -1
  38. package/dist/describe-Cqr63Gxa.mjs.map +0 -1
  39. package/dist/provider-DztvQjOr.d.mts.map +0 -1
  40. package/dist/upload-C5YM5jZR.mjs.map +0 -1
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.mjs";
2
2
  import { n as mimeType, t as Format } from "./format-BmfnR4jg.mjs";
3
3
  import { i as widths_exports, n as make, r as standard, t as atLeast } from "./widths-BEa9odY6.mjs";
4
- import { a as Placeholder, c as Quality, f as standard$1, i as ImageAsset, n as describe, p as variant_exports, r as Focus, s as PATH, t as Inspector } from "./describe-Cqr63Gxa.mjs";
4
+ import { a as ImageAsset, h as variant_exports, i as HashedAsset, l as PATH, m as standard$1, n as describe, o as Placeholder, r as Focus, s as isHashed, t as Inspector, u as Quality } from "./describe-h9F5stgR.mjs";
5
5
  import { n as icon_exports } from "./icon-CowP8fQ0.mjs";
6
6
  import { Option, Schema } from "effect";
7
7
  import { thumbHashToAverageRGBA, thumbHashToDataURL } from "thumbhash";
@@ -283,11 +283,12 @@ const cdnCgiSource = (key) => {
283
283
  };
284
284
  /**
285
285
  * Our own server's variants (`foldkit-media/server`), at `Variant.PATH` under
286
- * `baseUrl`. An original is named by its content hash, so an asset without
287
- * one has no hosted URL, and neither has `auto`: this server names the format
288
- * in the URL, never reads `Accept`, so every cache can key on the URL alone.
289
- * Its formats and quality must be in `space`, the server's own, or it is
290
- * refused here rather than answered with a 400 on every image.
286
+ * `baseUrl`. An original is named by its content hash, so it takes a
287
+ * `HashedAsset`, and has no URL for `auto`: this server names the format in
288
+ * the URL, never reads `Accept`, so every cache can key on the URL alone.
289
+ * Its formats and quality must be in `space`, or it is refused here rather
290
+ * than answered with a 400 on every image. Give the same value to the server
291
+ * (`serveFetch`'s `images.provider`), which reads its space from it.
291
292
  */
292
293
  const hosted = (options = {}) => {
293
294
  const { baseUrl: askedBaseUrl = "", space = standard$1 } = options;
@@ -305,20 +306,21 @@ const hosted = (options = {}) => {
305
306
  if (Option.isSome(quality) && !space.qualities.includes(quality.value)) throw new Error(`Provider.hosted: the server's space does not make quality ${quality.value}`);
306
307
  const encodeVariant = Schema.encodeOption(space.schema);
307
308
  return {
309
+ space,
308
310
  widths: space.widths,
309
311
  sources,
310
312
  fallback,
311
313
  url: (asset, { width, encoding }) => {
312
314
  if (encoding === "auto") return Option.none();
313
- return Option.flatMap(asset.hash, (hash) => Option.map(encodeVariant({
315
+ return Option.map(encodeVariant({
314
316
  width,
315
317
  format: encoding,
316
318
  quality
317
- }), (variant) => baseUrl + PATH.replace(":hash", hash).replace(":variant", variant)));
319
+ }), (variant) => baseUrl + PATH.replace(":hash", asset.hash.value).replace(":variant", variant));
318
320
  }
319
321
  };
320
322
  };
321
323
  //#endregion
322
- export { Focus, Format, icon_exports as Icon, ImageAsset, Inspector, layout_exports as Layout, picture_exports as Picture, Placeholder, provider_exports as Provider, variant_exports as Variant, widths_exports as Widths, describe, mimeType };
324
+ export { Focus, Format, HashedAsset, icon_exports as Icon, ImageAsset, Inspector, layout_exports as Layout, picture_exports as Picture, Placeholder, provider_exports as Provider, variant_exports as Variant, widths_exports as Widths, describe, isHashed, mimeType };
323
325
 
324
326
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["candidates","Layout.candidates","sizes","Layout.sizes","box","Layout.box","Layout.ratio","Widths.atLeast","Widths.make","Widths.standard","Variant.Quality","Variant.standard"],"sources":["../src/layout.ts","../src/placeholder.ts","../src/picture.ts","../src/provider.ts"],"sourcesContent":["import { Schema } from 'effect'\nimport type { ImageAsset } from './asset.js'\nimport { atLeast, type Widths } from './widths.js'\n\nconst CssPixels = Schema.Finite.check(Schema.isGreaterThan(0))\n\n/** How wide an image is drawn, from which its candidates and `sizes` follow. */\nconst LayoutSchema = Schema.TaggedUnion({\n /** Always this many CSS pixels wide. */\n Fixed: { width: CssPixels },\n /** At most this wide, and the viewport's width when that is narrower. */\n Constrained: { width: CssPixels },\n /** The viewport's width. */\n FullWidth: {},\n})\nexport { LayoutSchema as Schema }\nexport type Layout = typeof LayoutSchema.Type\n\nexport const Fixed = LayoutSchema.cases.Fixed.make\nexport const Constrained = LayoutSchema.cases.Constrained.make\nexport const FullWidth = (): Layout => LayoutSchema.cases.FullWidth.make({})\n\n/**\n * One `srcset` entry: the ladder width asked of the provider, and the width\n * the answer has. They differ only above the original's own width, where a\n * provider that does not enlarge answers with the original's.\n */\nexport interface Candidate {\n readonly request: number\n readonly described: number\n}\n\n/**\n * The widths worth offering for `layout`: for a fixed image its 1x and 2x,\n * for a constrained one every width up to its 2x, for a full-width one the\n * whole ladder. Widths above the original fetch the original's pixels, so\n * only the first of them is kept.\n */\nexport const candidates = (\n layout: Layout,\n widths: Widths,\n intrinsic: number,\n): ReadonlyArray<Candidate> => {\n const wanted = LayoutSchema.match(layout, {\n Fixed: ({ width }) => [atLeast(widths, width), atLeast(widths, 2 * width)],\n Constrained: ({ width }) => {\n const top = atLeast(widths, 2 * width)\n return widths.values.filter(value => value <= top)\n },\n FullWidth: () => widths.values,\n })\n const result: Array<Candidate> = []\n for (const request of wanted) {\n const described = Math.min(request, intrinsic)\n if (result.at(-1)?.described !== described) result.push({ request, described })\n }\n return result\n}\n\n/** The `sizes` a layout implies: how wide the image is drawn at each viewport. */\nexport const sizes = (layout: Layout): string =>\n LayoutSchema.match(layout, {\n Fixed: ({ width }) => `${width}px`,\n Constrained: ({ width }) => `(min-width: ${width}px) ${width}px, 100vw`,\n FullWidth: () => '100vw',\n })\n\n/** The original's aspect ratio, as CSS writes one. */\nexport const ratio = (asset: Pick<ImageAsset, 'width' | 'height'>): string =>\n `${asset.width} / ${asset.height}`\n\n/**\n * The `width` and `height` attributes: the drawn size where the layout fixes\n * one, the original's where it does not. Either way their ratio is the\n * original's, which is what reserves the box before a byte arrives.\n */\nexport const box = (\n layout: Layout,\n asset: Pick<ImageAsset, 'width' | 'height'>,\n): { readonly width: number; readonly height: number } => {\n const pixel = (value: number) => Math.max(1, Math.round(value))\n const scaled = (width: number) => ({\n width: pixel(width),\n height: pixel((width * asset.height) / asset.width),\n })\n return LayoutSchema.match(layout, {\n Fixed: ({ width }) => scaled(width),\n Constrained: ({ width }) => scaled(width),\n FullWidth: () => ({ width: asset.width, height: asset.height }),\n })\n}\n","import { Option } from 'effect'\nimport { thumbHashToAverageRGBA, thumbHashToDataURL } from 'thumbhash'\nimport { Placeholder, type ImageAsset } from './asset.js'\nimport type { Provider } from './provider.js'\n\n// A list redraws the same images, and decoding draws a PNG each time; a few\n// hundred recent ones cover a page without growing for the life of the app.\nconst DECODED_LIMIT = 256\nconst decoded = new Map<string, string>()\n\nconst bytesOf = (hash: string) => Uint8Array.from(atob(hash), char => char.charCodeAt(0))\n\nconst decode = (hash: string): string => {\n const cached = decoded.get(hash)\n if (cached !== undefined) return cached\n const url = thumbHashToDataURL(bytesOf(hash))\n if (decoded.size >= DECODED_LIMIT) decoded.delete(decoded.keys().next().value!)\n decoded.set(hash, url)\n return url\n}\n\n// Percent-encode what would end or escape a quoted CSS `url()`.\nconst cssUrl = (url: string): string =>\n `url(\"${url.replace(/[\"\\\\\\n\\r]/g, char => `%${char.charCodeAt(0).toString(16).toUpperCase().padStart(2, '0')}`)}\")`\n\n// A ThumbHash's average color, which costs a few bytes of HTML where its picture costs kilobytes.\nconst average = (hash: string): string => {\n const { r, g, b, a } = thumbHashToAverageRGBA(bytesOf(hash))\n const channel = (value: number) => Math.round(value * 255)\n return `rgb(${channel(r)} ${channel(g)} ${channel(b)} / ${Math.round(a * 100) / 100})`\n}\n\n/**\n * How much of a ThumbHash a placeholder paints: its blurred picture\n * (`detail`), or its average color (`average`).\n */\nexport type Level = 'detail' | 'average'\n\n/**\n * The CSS `background` an image's placeholder paints, whatever the image: a\n * color, a ThumbHash at `level`, or the provider's smallest width of the\n * image. None when the image has no placeholder, or the provider has no URL\n * for the smallest width.\n */\nexport const background = (\n asset: ImageAsset,\n provider: Provider,\n level: Level,\n): Option.Option<string> =>\n Option.flatMap(asset.placeholder, placeholder =>\n Placeholder.match(placeholder, {\n Color: ({ value }) => Option.some(value),\n ThumbHash: ({ hash }) =>\n Option.some(level === 'detail' ? cssUrl(decode(hash)) : average(hash)),\n LowRes: () =>\n Option.map(\n provider.url(asset, { width: provider.widths.values[0]!, encoding: provider.fallback }),\n cssUrl,\n ),\n }),\n )\n","import { Option } from 'effect'\nimport type { ImageAsset } from './asset.js'\nimport { mimeType, type Encoding } from './format.js'\nimport * as Layout from './layout.js'\nimport { background, type Level } from './placeholder.js'\nimport type { Provider } from './provider.js'\nimport * as Widths from './widths.js'\n\n/** A `source` element's attributes: one format's candidates. */\nexport interface Source {\n readonly type: string\n readonly srcset: string\n}\n\n/** The `img` element's attributes. */\nexport interface Img {\n readonly src: string\n readonly srcset: string\n readonly sizes: string\n readonly width: number\n readonly height: number\n readonly loading: 'lazy' | 'eager'\n readonly decoding: Option.Option<'async'>\n readonly fetchPriority: Option.Option<'high'>\n}\n\n/**\n * Everything an image's markup says, derived from its facts, its provider and\n * its layout. A view writes these; it decides nothing.\n */\nexport interface Picture {\n /** One per format the provider offers before the `img`'s own; none, a bare `img`. */\n readonly sources: ReadonlyArray<Source>\n readonly img: Img\n /** The original's aspect ratio, as CSS writes one. */\n readonly ratio: string\n /** Where a crop keeps the subject, as `object-position` writes it. */\n readonly focus: Option.Option<string>\n /**\n * The CSS `background` to paint behind the image until it loads. None for\n * an image with transparent pixels, which would show it through them.\n */\n readonly placeholder: Option.Option<string>\n}\n\nexport interface Input {\n readonly asset: ImageAsset\n readonly provider: Provider\n readonly layout: Layout.Layout\n /** The page's largest image: fetched first, not lazily. */\n readonly priority?: boolean\n /** In place of the layout's `sizes`, when the page knows the drawn width better. */\n readonly sizes?: string\n /**\n * How much of a ThumbHash to paint. By default its picture for a `priority`\n * image, the one a reader waits on, and its average color for the rest, so\n * a grid of thumbnails adds colors to the HTML, not pictures.\n */\n readonly placeholder?: Level\n}\n\n/**\n * The attributes of one image, or none when the provider has no URL for any\n * of its candidates in the `img`'s own encoding (a build table that never made\n * this image). Candidates the provider lacks are left out, never written as a\n * broken URL.\n */\nexport const derive = (input: Input): Option.Option<Picture> => {\n const { asset, provider, layout, priority = false } = input\n const candidates = Layout.candidates(layout, provider.widths, asset.width)\n\n const entries = (encoding: Encoding) =>\n candidates.flatMap(candidate =>\n Option.match(provider.url(asset, { width: candidate.request, encoding }), {\n onNone: () => [],\n onSome: url => [{ url, described: candidate.described }],\n }),\n )\n const srcsetOf = (list: ReadonlyArray<{ readonly url: string; readonly described: number }>) =>\n list.map(({ url, described }) => `${url} ${described}w`).join(', ')\n\n const own = entries(provider.fallback)\n if (own.length === 0) return Option.none()\n\n // A browser that ignores `srcset` fetches `src`: the first width at least\n // as wide as the image is drawn, or the largest there is.\n const drawn = Layout.Schema.match(layout, {\n Fixed: ({ width }) => width,\n Constrained: ({ width }) => width,\n FullWidth: () => Number.POSITIVE_INFINITY,\n })\n const src = (own.find(entry => entry.described >= drawn) ?? own[own.length - 1]!).url\n\n const sources = provider.sources.flatMap(format => {\n const list = entries(format)\n return list.length === 0 ? [] : [{ type: mimeType(format), srcset: srcsetOf(list) }]\n })\n\n const sizes = input.sizes ?? Layout.sizes(layout)\n const box = Layout.box(layout, asset)\n return Option.some({\n sources,\n img: {\n src,\n srcset: srcsetOf(own),\n // A lazy image may let the browser use its laid-out width instead.\n sizes: priority || sizes.startsWith('auto') ? sizes : `auto, ${sizes}`,\n width: box.width,\n height: box.height,\n loading: priority ? 'eager' : 'lazy',\n decoding: priority ? Option.none() : Option.some('async'),\n fetchPriority: priority ? Option.some('high') : Option.none(),\n },\n ratio: Layout.ratio(asset),\n focus: Option.map(asset.focus, ({ x, y }) => `${x * 100}% ${y * 100}%`),\n placeholder: asset.alpha\n ? Option.none()\n : background(asset, provider, input.placeholder ?? (priority ? 'detail' : 'average')),\n })\n}\n\nconst escapeAttribute = (value: string): string =>\n value.replace(/&/g, '&amp;').replace(/\"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;')\n\n/** What a preload names: the candidates the browser will choose from, at the `img`'s sizes. */\nexport interface Preloaded {\n /** A `source`'s media type, so a browser that cannot show it skips the preload. */\n readonly type: Option.Option<string>\n readonly srcset: string\n readonly sizes: string\n}\n\n/** The `<link rel=\"preload\">` naming `preloaded`, its values escaped for the attribute. */\nexport const preloadLink = ({ type, srcset, sizes }: Preloaded): string => {\n const attributes: ReadonlyArray<readonly [string, string]> = [\n ['rel', 'preload'],\n ['as', 'image'],\n ...Option.match(type, { onNone: () => [], onSome: value => [['type', value] as const] }),\n ['imagesrcset', srcset],\n ['imagesizes', sizes],\n ['fetchpriority', 'high'],\n ]\n return `<link ${attributes.map(([name, value]) => `${name}=\"${escapeAttribute(value)}\"`).join(' ')}>`\n}\n\n/**\n * A `<link rel=\"preload\">` for a page's `head`, so the browser fetches its\n * largest image before it reaches the `img`. It names the candidates the\n * browser will choose from: the first `source`'s, with its `type`, so a\n * browser that cannot show that format skips the preload rather than fetching\n * a file it will not use; the `img`'s when there is no `source`. Only for the\n * image drawn with `priority`.\n */\nexport const preload = ({ sources, img }: Picture): string => {\n const [first] = sources\n return preloadLink({\n type: Option.map(Option.fromNullishOr(first), source => source.type),\n srcset: first === undefined ? img.srcset : first.srcset,\n sizes: img.sizes,\n })\n}\n\n// Link-preview fetchers read JPEG; many read WebP and PNG; not all read AVIF.\nconst OPEN_GRAPH_ENCODINGS = ['jpeg', 'webp', 'png'] as const\n\n/**\n * An image for a page's Open Graph `og:image`: at the first ladder width of\n * at least 1200, as JPEG when the provider makes it, else WebP or PNG, never\n * AVIF, as an absolute URL against `origin`. None when the provider has no\n * such variant.\n */\nexport const ogImage = (\n asset: ImageAsset,\n provider: Provider,\n origin: string,\n): Option.Option<string> => {\n const width = Widths.atLeast(provider.widths, 1200)\n // A provider that picks the format reads the fetcher's `Accept`; the rest are asked in turn.\n const encodings: ReadonlyArray<Encoding> =\n provider.fallback === 'auto' ? ['auto'] : OPEN_GRAPH_ENCODINGS\n return Option.map(\n Option.firstSomeOf(encodings.map(encoding => provider.url(asset, { width, encoding }))),\n url => new URL(url, origin).href,\n )\n}\n","import { Option, Schema } from 'effect'\nimport type { ImageAsset } from './asset.js'\nimport type { Encoding, Format } from './format.js'\nimport * as Variant from './variant.js'\nimport * as Widths from './widths.js'\n\n/** One variant asked of a provider: a ladder width, in an encoding. */\nexport interface Request {\n readonly width: number\n readonly encoding: Encoding\n}\n\n/**\n * Writes the URL of a variant. A provider performs no I/O: it knows a host's\n * URL scheme, the widths it makes, and the encodings worth offering.\n */\nexport interface Provider {\n readonly widths: Widths.Widths\n /** Formats offered as `source`s before the `img`, most preferred first. */\n readonly sources: ReadonlyArray<Format>\n /** What the `img` itself asks for; `auto` lets the host choose. */\n readonly fallback: Encoding\n /** The variant's URL, or none when this provider has no such variant. */\n readonly url: (asset: ImageAsset, request: Request) => Option.Option<string>\n}\n\n/** A file a build emitted: one width of one original, in one format. */\nexport interface File {\n readonly width: number\n readonly format: Format\n readonly url: string\n}\n\n/**\n * The provider of one image whose variants a build already wrote: a table of\n * files, no URL scheme. Its ladder is the widths it has, and it answers none\n * for a variant it lacks. Refuses no files, and two files for one variant.\n */\nexport const fromFiles = (\n files: ReadonlyArray<File>,\n formats: { readonly sources: ReadonlyArray<Format>; readonly fallback: Format },\n): Provider => {\n if (files.length === 0) throw new Error('Provider.fromFiles: no files')\n const byVariant = new Map<string, string>()\n for (const file of files) {\n const variant = `${file.width}:${file.format}`\n if (byVariant.has(variant)) {\n throw new Error(`Provider.fromFiles: two files for ${file.width}px ${file.format}`)\n }\n byVariant.set(variant, file.url)\n }\n return {\n widths: Widths.make([...new Set(files.map(file => file.width))]),\n sources: formats.sources,\n fallback: formats.fallback,\n url: (_asset, { width, encoding }) =>\n Option.fromNullishOr(byVariant.get(`${width}:${encoding}`)),\n }\n}\n\nconst HOSTNAME = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z]{2,63}$/i\n\n/**\n * Cloudflare's own resizing, as URLs under `/cdn-cgi/image/` on a zone that\n * has it on. No Worker of ours runs: the zone fetches the original by its\n * `key` (a path on the zone, or an absolute URL it may fetch), scales it down\n * without enlarging, and picks the format from `Accept`.\n */\nexport const cdnCgi = (\n options: {\n /** The zone's host; omitted, URLs are relative to the page's. */\n readonly zone?: string\n readonly widths?: Widths.Widths\n /** 1 to 100. Cloudflare's default when omitted. */\n readonly quality?: number\n } = {},\n): Provider => {\n const { zone, widths = Widths.standard, quality } = options\n if (zone !== undefined && !HOSTNAME.test(zone)) {\n throw new Error(`Provider.cdnCgi: \"${zone}\" is not a host name`)\n }\n if (quality !== undefined && !Schema.is(Variant.Quality)(quality)) {\n throw new Error(`Provider.cdnCgi: quality ${quality} is not an integer from 1 to 100`)\n }\n const base = zone === undefined ? '' : `https://${zone}`\n const qualityOption = quality === undefined ? '' : `,quality=${quality}`\n return {\n widths,\n sources: [],\n fallback: 'auto',\n url: (asset, { width, encoding }) => {\n const operations = `width=${width},format=${encoding},fit=scale-down${qualityOption}`\n return Option.some(`${base}/cdn-cgi/image/${operations}/${cdnCgiSource(asset.key)}`)\n },\n }\n}\n\nconst cdnCgiSource = (key: string): string => {\n if (!/^https?:\\/\\//.test(key)) return key.replace(/^\\/+/, '')\n // A query in an absolute source would be read as the image URL's own.\n return key.includes('?') ? encodeURIComponent(key) : key\n}\n\n/**\n * Our own server's variants (`foldkit-media/server`), at `Variant.PATH` under\n * `baseUrl`. An original is named by its content hash, so an asset without\n * one has no hosted URL, and neither has `auto`: this server names the format\n * in the URL, never reads `Accept`, so every cache can key on the URL alone.\n * Its formats and quality must be in `space`, the server's own, or it is\n * refused here rather than answered with a 400 on every image.\n */\nexport const hosted = (\n options: {\n /** The server's origin, such as `https://img.example.com`; omitted, the page's. */\n readonly baseUrl?: string\n /** The server's space; the same value its handler decodes with. */\n readonly space?: Variant.Space\n /** Formats offered as `source`s; by default every one of the space's but the last. */\n readonly sources?: ReadonlyArray<Format>\n /** The `img`'s own format; by default the space's last. */\n readonly fallback?: Format\n readonly quality?: number\n } = {},\n): Provider => {\n const { baseUrl: askedBaseUrl = '', space = Variant.standard } = options\n const fallback = options.fallback ?? space.formats[space.formats.length - 1]!\n const sources = options.sources ?? space.formats.slice(0, -1)\n const parsed = Option.liftThrowable((value: string) => new URL(value))(askedBaseUrl)\n const origin = Option.filter(\n parsed,\n url => (url.protocol === 'http:' || url.protocol === 'https:') && askedBaseUrl === url.origin,\n )\n if (askedBaseUrl !== '' && Option.isNone(origin)) {\n throw new Error(`Provider.hosted: \"${askedBaseUrl}\" is not an origin`)\n }\n const baseUrl = Option.match(origin, { onNone: () => '', onSome: url => url.origin })\n for (const format of [...sources, fallback]) {\n if (!space.formats.includes(format)) {\n throw new Error(`Provider.hosted: the server's space does not make ${format}`)\n }\n }\n const quality = Option.fromNullishOr(options.quality)\n if (Option.isSome(quality) && !space.qualities.includes(quality.value)) {\n throw new Error(`Provider.hosted: the server's space does not make quality ${quality.value}`)\n }\n const encodeVariant = Schema.encodeOption(space.schema)\n return {\n widths: space.widths,\n sources,\n fallback,\n url: (asset, { width, encoding }) => {\n if (encoding === 'auto') return Option.none()\n return Option.flatMap(asset.hash, hash =>\n Option.map(\n encodeVariant({ width, format: encoding, quality }),\n variant => baseUrl + Variant.PATH.replace(':hash', hash).replace(':variant', variant),\n ),\n )\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAIA,MAAM,YAAY,OAAO,OAAO,MAAM,OAAO,cAAc,CAAC,CAAC;;AAG7D,MAAM,eAAe,OAAO,YAAY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CAAC,GAAG,SAAS,QAAQ,GACxC,IAAI,CAAC,MAAM,QAAQ,SAAS,MAAM,GAChC,MAAM,IAAI,MAAM,qDAAqD,QAAQ;CAGjF,MAAM,UAAU,OAAO,cAAc,QAAQ,OAAO;CACpD,IAAI,OAAO,OAAO,OAAO,KAAK,CAAC,MAAM,UAAU,SAAS,QAAQ,KAAK,GACnE,MAAM,IAAI,MAAM,6DAA6D,QAAQ,OAAO;CAE9F,MAAM,gBAAgB,OAAO,aAAa,MAAM,MAAM;CACtD,OAAO;EACL,QAAQ,MAAM;EACd;EACA;EACA,MAAM,OAAO,EAAE,OAAO,eAAe;GACnC,IAAI,aAAa,QAAQ,OAAO,OAAO,KAAK;GAC5C,OAAO,OAAO,QAAQ,MAAM,OAAM,SAChC,OAAO,IACL,cAAc;IAAE;IAAO,QAAQ;IAAU;GAAQ,CAAC,IAClD,YAAW,UAAA,KAAuB,QAAQ,SAAS,IAAI,CAAC,CAAC,QAAQ,YAAY,OAAO,CACtF,CACF;EACF;CACF;AACF"}
1
+ {"version":3,"file":"index.mjs","names":["candidates","Layout.candidates","sizes","Layout.sizes","box","Layout.box","Layout.ratio","Widths.atLeast","Widths.make","Widths.standard","Variant.Quality","Variant.standard"],"sources":["../src/layout.ts","../src/placeholder.ts","../src/picture.ts","../src/provider.ts"],"sourcesContent":["import { Schema } from 'effect'\nimport type { ImageAsset } from './asset.js'\nimport { atLeast, type Widths } from './widths.js'\n\nconst CssPixels = Schema.Finite.check(Schema.isGreaterThan(0))\n\n/** How wide an image is drawn, from which its candidates and `sizes` follow. */\nconst LayoutSchema = Schema.TaggedUnion({\n /** Always this many CSS pixels wide. */\n Fixed: { width: CssPixels },\n /** At most this wide, and the viewport's width when that is narrower. */\n Constrained: { width: CssPixels },\n /** The viewport's width. */\n FullWidth: {},\n})\nexport { LayoutSchema as Schema }\nexport type Layout = typeof LayoutSchema.Type\n\nexport const Fixed = LayoutSchema.cases.Fixed.make\nexport const Constrained = LayoutSchema.cases.Constrained.make\nexport const FullWidth = (): Layout => LayoutSchema.cases.FullWidth.make({})\n\n/**\n * One `srcset` entry: the ladder width asked of the provider, and the width\n * the answer has. They differ only above the original's own width, where a\n * provider that does not enlarge answers with the original's.\n */\nexport interface Candidate {\n readonly request: number\n readonly described: number\n}\n\n/**\n * The widths worth offering for `layout`: for a fixed image its 1x and 2x,\n * for a constrained one every width up to its 2x, for a full-width one the\n * whole ladder. Widths above the original fetch the original's pixels, so\n * only the first of them is kept.\n */\nexport const candidates = (\n layout: Layout,\n widths: Widths,\n intrinsic: number,\n): ReadonlyArray<Candidate> => {\n const wanted = LayoutSchema.match(layout, {\n Fixed: ({ width }) => [atLeast(widths, width), atLeast(widths, 2 * width)],\n Constrained: ({ width }) => {\n const top = atLeast(widths, 2 * width)\n return widths.values.filter(value => value <= top)\n },\n FullWidth: () => widths.values,\n })\n const result: Array<Candidate> = []\n for (const request of wanted) {\n const described = Math.min(request, intrinsic)\n if (result.at(-1)?.described !== described) result.push({ request, described })\n }\n return result\n}\n\n/** The `sizes` a layout implies: how wide the image is drawn at each viewport. */\nexport const sizes = (layout: Layout): string =>\n LayoutSchema.match(layout, {\n Fixed: ({ width }) => `${width}px`,\n Constrained: ({ width }) => `(min-width: ${width}px) ${width}px, 100vw`,\n FullWidth: () => '100vw',\n })\n\n/** The original's aspect ratio, as CSS writes one. */\nexport const ratio = (asset: Pick<ImageAsset, 'width' | 'height'>): string =>\n `${asset.width} / ${asset.height}`\n\n/**\n * The `width` and `height` attributes: the drawn size where the layout fixes\n * one, the original's where it does not. Either way their ratio is the\n * original's, which is what reserves the box before a byte arrives.\n */\nexport const box = (\n layout: Layout,\n asset: Pick<ImageAsset, 'width' | 'height'>,\n): { readonly width: number; readonly height: number } => {\n const pixel = (value: number) => Math.max(1, Math.round(value))\n const scaled = (width: number) => ({\n width: pixel(width),\n height: pixel((width * asset.height) / asset.width),\n })\n return LayoutSchema.match(layout, {\n Fixed: ({ width }) => scaled(width),\n Constrained: ({ width }) => scaled(width),\n FullWidth: () => ({ width: asset.width, height: asset.height }),\n })\n}\n","import { Option } from 'effect'\nimport { thumbHashToAverageRGBA, thumbHashToDataURL } from 'thumbhash'\nimport { Placeholder, type ImageAsset } from './asset.js'\nimport type { Provider } from './provider.js'\n\n// A list redraws the same images, and decoding draws a PNG each time; a few\n// hundred recent ones cover a page without growing for the life of the app.\nconst DECODED_LIMIT = 256\nconst decoded = new Map<string, string>()\n\nconst bytesOf = (hash: string) => Uint8Array.from(atob(hash), char => char.charCodeAt(0))\n\nconst decode = (hash: string): string => {\n const cached = decoded.get(hash)\n if (cached !== undefined) return cached\n const url = thumbHashToDataURL(bytesOf(hash))\n if (decoded.size >= DECODED_LIMIT) decoded.delete(decoded.keys().next().value!)\n decoded.set(hash, url)\n return url\n}\n\n// Percent-encode what would end or escape a quoted CSS `url()`.\nconst cssUrl = (url: string): string =>\n `url(\"${url.replace(/[\"\\\\\\n\\r]/g, char => `%${char.charCodeAt(0).toString(16).toUpperCase().padStart(2, '0')}`)}\")`\n\n// A ThumbHash's average color, which costs a few bytes of HTML where its picture costs kilobytes.\nconst average = (hash: string): string => {\n const { r, g, b, a } = thumbHashToAverageRGBA(bytesOf(hash))\n const channel = (value: number) => Math.round(value * 255)\n return `rgb(${channel(r)} ${channel(g)} ${channel(b)} / ${Math.round(a * 100) / 100})`\n}\n\n/**\n * How much of a ThumbHash a placeholder paints: its blurred picture\n * (`detail`), or its average color (`average`).\n */\nexport type Level = 'detail' | 'average'\n\n/**\n * The CSS `background` an image's placeholder paints, whatever the image: a\n * color, a ThumbHash at `level`, or the provider's smallest width of the\n * image. None when the image has no placeholder, or the provider has no URL\n * for the smallest width.\n */\nexport const background = <Asset extends ImageAsset>(\n asset: Asset,\n provider: Provider<Asset>,\n level: Level,\n): Option.Option<string> =>\n Option.flatMap(asset.placeholder, placeholder =>\n Placeholder.match(placeholder, {\n Color: ({ value }) => Option.some(value),\n ThumbHash: ({ hash }) =>\n Option.some(level === 'detail' ? cssUrl(decode(hash)) : average(hash)),\n LowRes: () =>\n Option.map(\n provider.url(asset, { width: provider.widths.values[0]!, encoding: provider.fallback }),\n cssUrl,\n ),\n }),\n )\n","import { Option } from 'effect'\nimport type { ImageAsset } from './asset.js'\nimport { mimeType, type Encoding } from './format.js'\nimport * as Layout from './layout.js'\nimport { background, type Level } from './placeholder.js'\nimport type { Provider } from './provider.js'\nimport * as Widths from './widths.js'\n\n/** A `source` element's attributes: one format's candidates. */\nexport interface Source {\n readonly type: string\n readonly srcset: string\n}\n\n/** The `img` element's attributes. */\nexport interface Img {\n readonly src: string\n readonly srcset: string\n readonly sizes: string\n readonly width: number\n readonly height: number\n readonly loading: 'lazy' | 'eager'\n readonly decoding: Option.Option<'async'>\n readonly fetchPriority: Option.Option<'high'>\n}\n\n/**\n * Everything an image's markup says, derived from its facts, its provider and\n * its layout. A view writes these; it decides nothing.\n */\nexport interface Picture {\n /** One per format the provider offers before the `img`'s own; none, a bare `img`. */\n readonly sources: ReadonlyArray<Source>\n readonly img: Img\n /** The original's aspect ratio, as CSS writes one. */\n readonly ratio: string\n /** Where a crop keeps the subject, as `object-position` writes it. */\n readonly focus: Option.Option<string>\n /**\n * The CSS `background` to paint behind the image until it loads. None for\n * an image with transparent pixels, which would show it through them.\n */\n readonly placeholder: Option.Option<string>\n}\n\n/** An image's facts, and a provider that takes them: a hashed one for `Provider.hosted`. */\nexport interface Input<Asset extends ImageAsset = ImageAsset> {\n readonly asset: Asset\n readonly provider: Provider<NoInfer<Asset>>\n readonly layout: Layout.Layout\n /** The page's largest image: fetched first, not lazily. */\n readonly priority?: boolean\n /** In place of the layout's `sizes`, when the page knows the drawn width better. */\n readonly sizes?: string\n /**\n * How much of a ThumbHash to paint. By default its picture for a `priority`\n * image, the one a reader waits on, and its average color for the rest, so\n * a grid of thumbnails adds colors to the HTML, not pictures.\n */\n readonly placeholder?: Level\n}\n\n/**\n * The attributes of one image, or none when the provider has no URL for any\n * of its candidates in the `img`'s own encoding (a build table that never made\n * this image). Candidates the provider lacks are left out, never written as a\n * broken URL.\n */\nexport const derive = <Asset extends ImageAsset>(input: Input<Asset>): Option.Option<Picture> => {\n const { asset, provider, layout, priority = false } = input\n const candidates = Layout.candidates(layout, provider.widths, asset.width)\n\n const entries = (encoding: Encoding) =>\n candidates.flatMap(candidate =>\n Option.match(provider.url(asset, { width: candidate.request, encoding }), {\n onNone: () => [],\n onSome: url => [{ url, described: candidate.described }],\n }),\n )\n const srcsetOf = (list: ReadonlyArray<{ readonly url: string; readonly described: number }>) =>\n list.map(({ url, described }) => `${url} ${described}w`).join(', ')\n\n const own = entries(provider.fallback)\n if (own.length === 0) return Option.none()\n\n // A browser that ignores `srcset` fetches `src`: the first width at least\n // as wide as the image is drawn, or the largest there is.\n const drawn = Layout.Schema.match(layout, {\n Fixed: ({ width }) => width,\n Constrained: ({ width }) => width,\n FullWidth: () => Number.POSITIVE_INFINITY,\n })\n const src = (own.find(entry => entry.described >= drawn) ?? own[own.length - 1]!).url\n\n const sources = provider.sources.flatMap(format => {\n const list = entries(format)\n return list.length === 0 ? [] : [{ type: mimeType(format), srcset: srcsetOf(list) }]\n })\n\n const sizes = input.sizes ?? Layout.sizes(layout)\n const box = Layout.box(layout, asset)\n return Option.some({\n sources,\n img: {\n src,\n srcset: srcsetOf(own),\n // A lazy image may let the browser use its laid-out width instead.\n sizes: priority || sizes.startsWith('auto') ? sizes : `auto, ${sizes}`,\n width: box.width,\n height: box.height,\n loading: priority ? 'eager' : 'lazy',\n decoding: priority ? Option.none() : Option.some('async'),\n fetchPriority: priority ? Option.some('high') : Option.none(),\n },\n ratio: Layout.ratio(asset),\n focus: Option.map(asset.focus, ({ x, y }) => `${x * 100}% ${y * 100}%`),\n placeholder: asset.alpha\n ? Option.none()\n : background(asset, provider, input.placeholder ?? (priority ? 'detail' : 'average')),\n })\n}\n\nconst escapeAttribute = (value: string): string =>\n value.replace(/&/g, '&amp;').replace(/\"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;')\n\n/** What a preload names: the candidates the browser will choose from, at the `img`'s sizes. */\nexport interface Preloaded {\n /** A `source`'s media type, so a browser that cannot show it skips the preload. */\n readonly type: Option.Option<string>\n readonly srcset: string\n readonly sizes: string\n}\n\n/** The `<link rel=\"preload\">` naming `preloaded`, its values escaped for the attribute. */\nexport const preloadLink = ({ type, srcset, sizes }: Preloaded): string => {\n const attributes: ReadonlyArray<readonly [string, string]> = [\n ['rel', 'preload'],\n ['as', 'image'],\n ...Option.match(type, { onNone: () => [], onSome: value => [['type', value] as const] }),\n ['imagesrcset', srcset],\n ['imagesizes', sizes],\n ['fetchpriority', 'high'],\n ]\n return `<link ${attributes.map(([name, value]) => `${name}=\"${escapeAttribute(value)}\"`).join(' ')}>`\n}\n\n/**\n * A `<link rel=\"preload\">` for a page's `head`, so the browser fetches its\n * largest image before it reaches the `img`. It names the candidates the\n * browser will choose from: the first `source`'s, with its `type`, so a\n * browser that cannot show that format skips the preload rather than fetching\n * a file it will not use; the `img`'s when there is no `source`. Only for the\n * image drawn with `priority`.\n */\nexport const preload = ({ sources, img }: Picture): string => {\n const [first] = sources\n return preloadLink({\n type: Option.map(Option.fromNullishOr(first), source => source.type),\n srcset: first === undefined ? img.srcset : first.srcset,\n sizes: img.sizes,\n })\n}\n\n// Link-preview fetchers read JPEG; many read WebP and PNG; not all read AVIF.\nconst OPEN_GRAPH_ENCODINGS = ['jpeg', 'webp', 'png'] as const\n\n/**\n * An image for a page's Open Graph `og:image`: at the first ladder width of\n * at least 1200, as JPEG when the provider makes it, else WebP or PNG, never\n * AVIF, as an absolute URL against `origin`. None when the provider has no\n * such variant.\n */\nexport const ogImage = <Asset extends ImageAsset>(\n asset: Asset,\n provider: Provider<NoInfer<Asset>>,\n origin: string,\n): Option.Option<string> => {\n const width = Widths.atLeast(provider.widths, 1200)\n // A provider that picks the format reads the fetcher's `Accept`; the rest are asked in turn.\n const encodings: ReadonlyArray<Encoding> =\n provider.fallback === 'auto' ? ['auto'] : OPEN_GRAPH_ENCODINGS\n return Option.map(\n Option.firstSomeOf(encodings.map(encoding => provider.url(asset, { width, encoding }))),\n url => new URL(url, origin).href,\n )\n}\n","import { Option, Schema } from 'effect'\nimport type { HashedAsset, ImageAsset } from './asset.js'\nimport type { Encoding, Format } from './format.js'\nimport * as Variant from './variant.js'\nimport * as Widths from './widths.js'\n\n/** One variant asked of a provider: a ladder width, in an encoding. */\nexport interface Request {\n readonly width: number\n readonly encoding: Encoding\n}\n\n/**\n * Writes the URL of a variant. A provider performs no I/O: it knows a host's\n * URL scheme, the widths it makes, and the encodings worth offering. `Asset`\n * is the facts it needs: `HashedAsset` for one that names originals by hash.\n */\nexport interface Provider<in Asset extends ImageAsset = ImageAsset> {\n readonly widths: Widths.Widths\n /** Formats offered as `source`s before the `img`, most preferred first. */\n readonly sources: ReadonlyArray<Format>\n /** What the `img` itself asks for; `auto` lets the host choose. */\n readonly fallback: Encoding\n /** The variant's URL, or none when this provider has no such variant. */\n readonly url: (asset: Asset, request: Request) => Option.Option<string>\n}\n\n/** A file a build emitted: one width of one original, in one format. */\nexport interface File {\n readonly width: number\n readonly format: Format\n readonly url: string\n}\n\n/**\n * The provider of one image whose variants a build already wrote: a table of\n * files, no URL scheme. Its ladder is the widths it has, and it answers none\n * for a variant it lacks. Refuses no files, and two files for one variant.\n */\nexport const fromFiles = (\n files: ReadonlyArray<File>,\n formats: { readonly sources: ReadonlyArray<Format>; readonly fallback: Format },\n): Provider => {\n if (files.length === 0) throw new Error('Provider.fromFiles: no files')\n const byVariant = new Map<string, string>()\n for (const file of files) {\n const variant = `${file.width}:${file.format}`\n if (byVariant.has(variant)) {\n throw new Error(`Provider.fromFiles: two files for ${file.width}px ${file.format}`)\n }\n byVariant.set(variant, file.url)\n }\n return {\n widths: Widths.make([...new Set(files.map(file => file.width))]),\n sources: formats.sources,\n fallback: formats.fallback,\n url: (_asset, { width, encoding }) =>\n Option.fromNullishOr(byVariant.get(`${width}:${encoding}`)),\n }\n}\n\nconst HOSTNAME = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z]{2,63}$/i\n\n/**\n * Cloudflare's own resizing, as URLs under `/cdn-cgi/image/` on a zone that\n * has it on. No Worker of ours runs: the zone fetches the original by its\n * `key` (a path on the zone, or an absolute URL it may fetch), scales it down\n * without enlarging, and picks the format from `Accept`.\n */\nexport const cdnCgi = (\n options: {\n /** The zone's host; omitted, URLs are relative to the page's. */\n readonly zone?: string\n readonly widths?: Widths.Widths\n /** 1 to 100. Cloudflare's default when omitted. */\n readonly quality?: number\n } = {},\n): Provider => {\n const { zone, widths = Widths.standard, quality } = options\n if (zone !== undefined && !HOSTNAME.test(zone)) {\n throw new Error(`Provider.cdnCgi: \"${zone}\" is not a host name`)\n }\n if (quality !== undefined && !Schema.is(Variant.Quality)(quality)) {\n throw new Error(`Provider.cdnCgi: quality ${quality} is not an integer from 1 to 100`)\n }\n const base = zone === undefined ? '' : `https://${zone}`\n const qualityOption = quality === undefined ? '' : `,quality=${quality}`\n return {\n widths,\n sources: [],\n fallback: 'auto',\n url: (asset, { width, encoding }) => {\n const operations = `width=${width},format=${encoding},fit=scale-down${qualityOption}`\n return Option.some(`${base}/cdn-cgi/image/${operations}/${cdnCgiSource(asset.key)}`)\n },\n }\n}\n\nconst cdnCgiSource = (key: string): string => {\n if (!/^https?:\\/\\//.test(key)) return key.replace(/^\\/+/, '')\n // A query in an absolute source would be read as the image URL's own.\n return key.includes('?') ? encodeURIComponent(key) : key\n}\n\n/** `Provider.hosted`'s provider, carrying its space, so its server reads the same one. */\nexport interface Hosted extends Provider<HashedAsset> {\n readonly space: Variant.Space\n}\n\n/**\n * Our own server's variants (`foldkit-media/server`), at `Variant.PATH` under\n * `baseUrl`. An original is named by its content hash, so it takes a\n * `HashedAsset`, and has no URL for `auto`: this server names the format in\n * the URL, never reads `Accept`, so every cache can key on the URL alone.\n * Its formats and quality must be in `space`, or it is refused here rather\n * than answered with a 400 on every image. Give the same value to the server\n * (`serveFetch`'s `images.provider`), which reads its space from it.\n */\nexport const hosted = (\n options: {\n /** The server's origin, such as `https://img.example.com`; omitted, the page's. */\n readonly baseUrl?: string\n /** The server's space; the same value its handler decodes with. */\n readonly space?: Variant.Space\n /** Formats offered as `source`s; by default every one of the space's but the last. */\n readonly sources?: ReadonlyArray<Format>\n /** The `img`'s own format; by default the space's last. */\n readonly fallback?: Format\n readonly quality?: number\n } = {},\n): Hosted => {\n const { baseUrl: askedBaseUrl = '', space = Variant.standard } = options\n const fallback = options.fallback ?? space.formats[space.formats.length - 1]!\n const sources = options.sources ?? space.formats.slice(0, -1)\n const parsed = Option.liftThrowable((value: string) => new URL(value))(askedBaseUrl)\n const origin = Option.filter(\n parsed,\n url => (url.protocol === 'http:' || url.protocol === 'https:') && askedBaseUrl === url.origin,\n )\n if (askedBaseUrl !== '' && Option.isNone(origin)) {\n throw new Error(`Provider.hosted: \"${askedBaseUrl}\" is not an origin`)\n }\n const baseUrl = Option.match(origin, { onNone: () => '', onSome: url => url.origin })\n for (const format of [...sources, fallback]) {\n if (!space.formats.includes(format)) {\n throw new Error(`Provider.hosted: the server's space does not make ${format}`)\n }\n }\n const quality = Option.fromNullishOr(options.quality)\n if (Option.isSome(quality) && !space.qualities.includes(quality.value)) {\n throw new Error(`Provider.hosted: the server's space does not make quality ${quality.value}`)\n }\n const encodeVariant = Schema.encodeOption(space.schema)\n return {\n space,\n widths: space.widths,\n sources,\n fallback,\n url: (asset, { width, encoding }) => {\n if (encoding === 'auto') return Option.none()\n return Option.map(\n encodeVariant({ width, format: encoding, quality }),\n variant =>\n baseUrl + Variant.PATH.replace(':hash', asset.hash.value).replace(':variant', variant),\n )\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAIA,MAAM,YAAY,OAAO,OAAO,MAAM,OAAO,cAAc,CAAC,CAAC;;AAG7D,MAAM,eAAe,OAAO,YAAY;;CAEtC,OAAO,EAAE,OAAO,UAAU;;CAE1B,aAAa,EAAE,OAAO,UAAU;;C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M,GAChC,MAAM,IAAI,MAAM,qDAAqD,QAAQ;CAGjF,MAAM,UAAU,OAAO,cAAc,QAAQ,OAAO;CACpD,IAAI,OAAO,OAAO,OAAO,KAAK,CAAC,MAAM,UAAU,SAAS,QAAQ,KAAK,GACnE,MAAM,IAAI,MAAM,6DAA6D,QAAQ,OAAO;CAE9F,MAAM,gBAAgB,OAAO,aAAa,MAAM,MAAM;CACtD,OAAO;EACL;EACA,QAAQ,MAAM;EACd;EACA;EACA,MAAM,OAAO,EAAE,OAAO,eAAe;GACnC,IAAI,aAAa,QAAQ,OAAO,OAAO,KAAK;GAC5C,OAAO,OAAO,IACZ,cAAc;IAAE;IAAO,QAAQ;IAAU;GAAQ,CAAC,IAClD,YACE,UAAA,KAAuB,QAAQ,SAAS,MAAM,KAAK,KAAK,CAAC,CAAC,QAAQ,YAAY,OAAO,CACzF;EACF;CACF;AACF"}
@@ -1,9 +1,9 @@
1
- import { n as ImageAsset } from "./asset-BNQ_j5tO.mjs";
1
+ import { n as HashedAsset, r as ImageAsset } from "./asset-Dlkss5qp.mjs";
2
2
  import { i as Format, r as Encoding, t as Widths } from "./widths-Cg7-x89y.mjs";
3
3
  import { t as Space } from "./variant-BOg1M0Wj.mjs";
4
4
  import { Option } from "effect";
5
5
  declare namespace provider_d_exports {
6
- export { File, Provider, Request, cdnCgi, fromFiles, hosted };
6
+ export { File, Hosted, Provider, Request, cdnCgi, fromFiles, hosted };
7
7
  }
8
8
  /** One variant asked of a provider: a ladder width, in an encoding. */
9
9
  interface Request {
@@ -12,16 +12,17 @@ interface Request {
12
12
  }
13
13
  /**
14
14
  * Writes the URL of a variant. A provider performs no I/O: it knows a host's
15
- * URL scheme, the widths it makes, and the encodings worth offering.
15
+ * URL scheme, the widths it makes, and the encodings worth offering. `Asset`
16
+ * is the facts it needs: `HashedAsset` for one that names originals by hash.
16
17
  */
17
- interface Provider {
18
+ interface Provider<in Asset extends ImageAsset = ImageAsset> {
18
19
  readonly widths: Widths;
19
20
  /** Formats offered as `source`s before the `img`, most preferred first. */
20
21
  readonly sources: ReadonlyArray<Format>;
21
22
  /** What the `img` itself asks for; `auto` lets the host choose. */
22
23
  readonly fallback: Encoding;
23
24
  /** The variant's URL, or none when this provider has no such variant. */
24
- readonly url: (asset: ImageAsset, request: Request) => Option.Option<string>;
25
+ readonly url: (asset: Asset, request: Request) => Option.Option<string>;
25
26
  }
26
27
  /** A file a build emitted: one width of one original, in one format. */
27
28
  interface File {
@@ -51,13 +52,18 @@ declare const cdnCgi: (options?: {
51
52
  /** 1 to 100. Cloudflare's default when omitted. */
52
53
  readonly quality?: number;
53
54
  }) => Provider;
55
+ /** `Provider.hosted`'s provider, carrying its space, so its server reads the same one. */
56
+ interface Hosted extends Provider<HashedAsset> {
57
+ readonly space: Space;
58
+ }
54
59
  /**
55
60
  * Our own server's variants (`foldkit-media/server`), at `Variant.PATH` under
56
- * `baseUrl`. An original is named by its content hash, so an asset without
57
- * one has no hosted URL, and neither has `auto`: this server names the format
58
- * in the URL, never reads `Accept`, so every cache can key on the URL alone.
59
- * Its formats and quality must be in `space`, the server's own, or it is
60
- * refused here rather than answered with a 400 on every image.
61
+ * `baseUrl`. An original is named by its content hash, so it takes a
62
+ * `HashedAsset`, and has no URL for `auto`: this server names the format in
63
+ * the URL, never reads `Accept`, so every cache can key on the URL alone.
64
+ * Its formats and quality must be in `space`, or it is refused here rather
65
+ * than answered with a 400 on every image. Give the same value to the server
66
+ * (`serveFetch`'s `images.provider`), which reads its space from it.
61
67
  */
62
68
  declare const hosted: (options?: {
63
69
  /** The server's origin, such as `https://img.example.com`; omitted, the page's. */
@@ -69,7 +75,7 @@ declare const hosted: (options?: {
69
75
  /** The `img`'s own format; by default the space's last. */
70
76
  readonly fallback?: Format;
71
77
  readonly quality?: number;
72
- }) => Provider;
78
+ }) => Hosted;
73
79
  //#endregion
74
- export { provider_d_exports as n, Provider as t };
75
- //# sourceMappingURL=provider-DztvQjOr.d.mts.map
80
+ export { Provider as n, provider_d_exports as r, Hosted as t };
81
+ //# sourceMappingURL=provider-g0Vlvlrb.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider-g0Vlvlrb.d.mts","names":["Widths.Widths","Variant.Space"],"sources":["../src/provider.ts"],"mappings":";;;;;;;;UAOiB;WACN;WACA,UAAU;;;;;;;UAQJ,YAAY,cAAc,aAAa;WAC7C,QAAQA;;WAER,SAAS,cAAc;;WAEvB,UAAU;;WAEV,MAAM,OAAO,OAAO,SAAS,YAAY,OAAO;;;UAI1C;WACN;WACA,QAAQ;WACR;;;;;;;cAQE,YAAS,OACb,cAAc,OAAK;WACN,SAAS,cAAc;WAAkB,UAAU;MACtE;;;;;;;cA2BU,SAAM;;WAGN;WACA,SAASA;;WAET;MAEV;;UA4Bc,eAAe,SAAS;WAC9B,OAAOC;;;;;;;;;;;cAYL,SAAM;;WAGN;;WAEA,QAAQA;;WAER,UAAU,cAAc;;WAExB,WAAW;WACX;MAEV"}
@@ -1,7 +1,7 @@
1
- import { a as OriginalNotFound, c as TransformFailed, o as OriginalTooLarge, s as QuotaExhausted } from "../describe-DdYvLhMY.mjs";
2
- import { a as Uploads, c as uploadLayer, d as FactsUnavailable, f as factsOf, h as admissionRateLimiter, i as UploadPolicy, l as uploadsKeyValueStore, m as RateLimited, n as UploadForbidden, o as serveUploadFetch, p as Admission, r as UploadOptions, s as uploadHandlers, t as UploadApi, u as FactsOptions } from "../upload-C4_inwfv.mjs";
3
- import { t as Space } from "../variant-BOg1M0Wj.mjs";
4
- import { a as Transformer, c as variantsNone, i as Originals, n as Kept, o as Variants, r as Original, s as limitTransforms, t as Encoded } from "../services-Ck-7dhIP.mjs";
1
+ import { a as OriginalNotFound, c as TransformFailed, n as Inspector, o as OriginalTooLarge, s as QuotaExhausted } from "../describe-CivKHl4x.mjs";
2
+ import { a as Uploads, c as uploadPolicyBearer, d as FactsUnavailable, f as factsOf, h as admissionRateLimiter, i as UploadPolicy, l as uploadsKeyValueStore, m as RateLimited, n as UploadForbidden, o as uploadHandlers, p as Admission, r as UploadOptions, s as uploadLayer, t as UploadApi, u as FactsOptions } from "../upload-kp0_oK76.mjs";
3
+ import { a as Transformer, c as variantsNone, i as Originals, n as Kept, o as Variants, r as Original, s as limitTransforms, t as Encoded } from "../services-8_h0ubLB.mjs";
4
+ import { t as Hosted } from "../provider-g0Vlvlrb.mjs";
5
5
  import { Layer, Schema } from "effect";
6
6
  import { HttpApi, HttpApiEndpoint, HttpApiGroup, HttpApiSchema } from "effect/http-api";
7
7
  import { HttpRouter, HttpServer, HttpServerRequest } from "effect/http";
@@ -62,14 +62,17 @@ export declare const headersFor: (answer: Answer) => Readonly<Record<string, str
62
62
  //#endregion
63
63
  //#region src/server/handlers.d.ts
64
64
  interface Options {
65
- /** Every variant this server makes: the same value `Provider.hosted` writes URLs in. */
66
- readonly space?: Space;
65
+ /**
66
+ * The `Provider.hosted` the pages write URLs with: the server makes every
67
+ * variant of its space and nothing else. `Provider.hosted()` when omitted.
68
+ */
69
+ readonly provider?: Hosted;
67
70
  /** The largest original read, in bytes; larger ones are a 413. */
68
71
  readonly maxBytes?: number;
69
72
  /**
70
73
  * Concurrent misses for one variant share one transform and one write.
71
74
  * Only where requests may wait on one another's work: on by default for
72
- * `layer` (a Node server), off for `serveFetch`, since a Worker request
75
+ * `layer` (a Node server), off in `serveFetch`, since a Worker request
73
76
  * cannot wake another's.
74
77
  */
75
78
  readonly coalesce?: boolean;
@@ -94,15 +97,30 @@ export declare const handlers: (options?: Options) => Layer.Layer<import("effect
94
97
  * the `HttpRouter`, needing `Originals`, `Transformer` and `Variants`.
95
98
  */
96
99
  export declare const layer: (options?: Options) => Layer.Layer<never, never, import("effect/FileSystem").FileSystem | import("effect/http/Etag").Generator | import("effect/http/HttpPlatform").HttpPlatform | HttpRouter.HttpRouter | Originals | import("effect/Path").Path | Transformer | Variants>;
100
+ //#endregion
101
+ //#region src/server/fetch.d.ts
102
+ /** What `serveFetch` answers, each side's services built from the request's bindings. */
103
+ interface FetchOptions<Env> {
104
+ /** `GET /_image/…`: the variants. A Worker request cannot wait on another's, so nothing coalesces. */
105
+ readonly images?: Omit<Options, 'coalesce'> & {
106
+ readonly layer: (env: Env) => Layer.Layer<Originals | Transformer | Variants, unknown>;
107
+ };
108
+ /** `POST /_media/upload` and `GET /_media/facts`: originals entering. */
109
+ readonly uploads?: UploadOptions & {
110
+ readonly layer: (env: Env) => Layer.Layer<Uploads | Inspector | UploadPolicy, unknown>;
111
+ };
112
+ /** Every path outside `/_image/` and `/_media/`: the application's own routes. A 404 when omitted. */
113
+ readonly otherwise?: (request: Request, env: Env) => Promise<Response>;
114
+ }
97
115
  /**
98
- * The media server as a Worker's fetch handler, its services from each
99
- * environment's bindings. It answers its own route and 404s anything else, so
100
- * route to it by path (`/_image/`).
116
+ * The media server as a Worker's fetch handler. It owns `/_image/` and
117
+ * `/_media/`: a route of either it was not given, another method (a
118
+ * preflight, which the upload route never answers), or another path under
119
+ * them is a 404, and everything else goes to `otherwise`. The services are
120
+ * built from each environment's bindings once and kept; a layer that fails
121
+ * to build answers a 500.
101
122
  */
102
- export declare const serveFetch: <Env extends object>(options: Options & {
103
- /** The services, from the request's bindings. A layer that fails to build answers a 500. */
104
- readonly layer: (env: Env) => Layer.Layer<Originals | Transformer | Variants, unknown>;
105
- }) => ((request: Request, env: Env) => Promise<Response>);
123
+ export declare const serveFetch: <Env extends object>(options: FetchOptions<Env>) => ((request: Request, env: Env) => Promise<Response>);
106
124
  //#endregion
107
125
  //#region src/server/stores.d.ts
108
126
  /**
@@ -159,5 +177,5 @@ export declare const materialize: (options: {
159
177
  readonly concurrency?: number;
160
178
  }) => Promise<ReadonlyArray<Materialized>>;
161
179
  //#endregion
162
- export { Admission, type Encoded, type FactsOptions, FactsUnavailable, type Kept, type Materialized, type Options, type Original, OriginalNotFound, OriginalTooLarge, Originals, QuotaExhausted, RateLimited, TransformFailed, Transformer, UploadApi, UploadForbidden, type UploadOptions, UploadPolicy, Uploads, Variants, admissionRateLimiter, factsOf, limitTransforms, serveUploadFetch, uploadHandlers, uploadLayer, uploadsKeyValueStore, variantsNone };
180
+ export { Admission, type Encoded, type FactsOptions, FactsUnavailable, type FetchOptions, type Kept, type Materialized, type Options, type Original, OriginalNotFound, OriginalTooLarge, Originals, QuotaExhausted, RateLimited, TransformFailed, Transformer, UploadApi, UploadForbidden, type UploadOptions, UploadPolicy, Uploads, Variants, admissionRateLimiter, factsOf, limitTransforms, uploadHandlers, uploadLayer, uploadPolicyBearer, uploadsKeyValueStore, variantsNone };
163
181
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":["Variant.Space"],"sources":["../../src/server/api.ts","../../src/server/headers.ts","../../src/server/handlers.ts","../../src/server/stores.ts","../../src/server/materialize.ts"],"mappings":";;;;;;;;;;;;;;;;qBAWa,UAAQ,QAAA,yBAAA,aAAA,uBAAA,gBAAA,4DAAA,OAAA,kBAAA,OAAA;;;0BAOpB,cAAA;;;;qBCXY,QAAM,OAAA;;;;;;;;;;;;;;;;;;;;;;;;;;YA0CP,gBAAgB,OAAO;;qBActB,WAAW,QAAQ;;;;;;;;;qBA0BnB,aAAU,QAAY,WAAS,SAAS;;;UC3EpC;;WAEN,QAAQA;;WAER;;;;;;;WAOA;;;;;;WAMA,YAAY,SAAS,kBAAkB;;;;;;;;;;qBA6BrC,WAAQ,UAAa,YAAO,MAAA,6CAAA,2CAAA,YAAA,cAAA;;;;;qBA4H5B,QAAK,UAAa,YAAO,MAAA,gDAAA,wCAAA,+CAAA,eAAA,WAAA,aAAA,kCAAA,OAAA,cAAA;;;;;;qBAoCzB,aAAc,oBAAkB,SAClC;;WAEE,QAAQ,KAAK,QAAQ,MAAM,MAAM,YAAY,cAAc;QAEnE,SAAS,SAAS,KAAK,QAAQ,QAAQ;;;;;;;;qBCnL/B,wBAAqB;WACZ;MACnB,MAAM,MAAM,iBAAiB,cAAc;;;;;;qBAcjC,yBAAsB;WACb;MACnB,MAAM,MAAM,kBAAkB,cAAc;;;;UC5D9B;WACN;WACA,UAAU;;;;;;;qBAgBR;;;;;;;;;;;;;qBAoBA,cAAW;WACb,OAAO;aAAyB;;WAChC,QAAQ,SAAS,YAAY,QAAQ;;WAErC;;WAEA;;WAEA;MACP,QAAQ,cAAc"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/server/api.ts","../../src/server/headers.ts","../../src/server/handlers.ts","../../src/server/fetch.ts","../../src/server/stores.ts","../../src/server/materialize.ts"],"mappings":";;;;;;;;;;;;;;;;qBAWa,UAAQ,QAAA,yBAAA,aAAA,uBAAA,gBAAA,4DAAA,OAAA,kBAAA,OAAA;;;0BAOpB,cAAA;;;;qBCXY,QAAM,OAAA;;;;;;;;;;;;;;;;;;;;;;;;;;YA0CP,gBAAgB,OAAO;;qBActB,WAAW,QAAQ;;;;;;;;;qBA0BnB,aAAU,QAAY,WAAS,SAAS;;;UC1EpC;;;;;WAKN,WAAW;;WAEX;;;;;;;WAOA;;;;;;WAMA,YAAY,SAAS,kBAAkB;;;;;;;;;;qBA6BrC,WAAQ,UAAa,YAAO,MAAA,6CAAA,2CAAA,YAAA,cAAA;;;;;qBA4H5B,QAAK,UAAa,YAAO,MAAA,gDAAA,wCAAA,+CAAA,eAAA,WAAA,aAAA,kCAAA,OAAA,cAAA;;;;UCjLrB,aAAa;;WAEnB,SAAS,KAAK;aACZ,QAAQ,KAAK,QAAQ,MAAM,MAAM,YAAY,cAAc;;;WAG7D,UAAU;aACR,QAAQ,KAAK,QAAQ,MAAM,MAAM,UAAU,YAAY;;;WAGzD,aAAa,SAAS,SAAS,KAAK,QAAQ,QAAQ;;;;;;;;;;qBAWlD,aAAc,oBAAkB,SAClC,aAAa,WACnB,SAAS,SAAS,KAAK,QAAQ,QAAQ;;;;;;;;qBCY/B,wBAAqB;WACZ;MACnB,MAAM,MAAM,iBAAiB,cAAc;;;;;;qBAcjC,yBAAsB;WACb;MACnB,MAAM,MAAM,kBAAkB,cAAc;;;;UC5D9B;WACN;WACA,UAAU;;;;;;;qBAgBR;;;;;;;;;;;;;qBAoBA,cAAW;WACb,OAAO;aAAyB;;WAChC,QAAQ,SAAS,YAAY,QAAQ;;WAErC;;WAEA;;WAEA;MACP,QAAQ,cAAc"}
@@ -1,7 +1,177 @@
1
+ import { c as ContentHash, d as Spelling, f as respell, l as PATH, m as standard, p as revisionOf } from "../describe-h9F5stgR.mjs";
1
2
  import { n as positiveInteger, t as nonNegativeInteger } from "../limits-B6C9OOLl.mjs";
2
3
  import { i as TransformFailed, n as OriginalTooLarge, r as QuotaExhausted, t as OriginalNotFound } from "../errors-qETj7Pgi.mjs";
3
- import { C as MediaApi, S as statusOf, _ as Admission, a as serveUploadFetch, b as Answer, c as uploadsKeyValueStore, f as originalsKeyValueStore, g as serveFetch, h as layer, i as Uploads, l as FactsUnavailable, m as handlers, n as UploadForbidden, o as uploadHandlers, p as variantsKeyValueStore, r as UploadPolicy, s as uploadLayer, t as UploadApi, u as factsOf, v as RateLimited, x as headersFor, y as admissionRateLimiter } from "../upload-C5YM5jZR.mjs";
4
+ import { _ as Answer, a as UploadForbidden, b as statusOf, c as uploadHandlers, d as uploadsKeyValueStore, f as FactsUnavailable, g as admissionRateLimiter, h as RateLimited, i as UploadApi, l as uploadLayer, m as Admission, n as originalsKeyValueStore, o as UploadPolicy, p as factsOf, r as variantsKeyValueStore, s as Uploads, u as uploadPolicyBearer, v as headersFor, y as matches } from "../stores-BtmSl8X3.mjs";
4
5
  import { a as variantsNone, i as limitTransforms, n as Transformer, r as Variants, t as Originals } from "../services-BeakQl7F.mjs";
6
+ import { Cache, Effect, Layer, Option, Schema } from "effect";
7
+ import { HttpApi, HttpApiBuilder, HttpApiEndpoint, HttpApiGroup, HttpApiSchema } from "effect/http-api";
8
+ import { HttpRouter, HttpServer, HttpServerResponse } from "effect/http";
9
+ //#region src/server/api.ts
10
+ /**
11
+ * The media server's HTTP API: one route, a variant of an original named by
12
+ * its content hash. The route takes its params as text, and the handler
13
+ * decodes them with the space's Schema, the one `Provider.hosted` encodes
14
+ * with, so a variant outside the space is refused before any work, and that
15
+ * refusal, like every answer, carries the headers `headersFor` decides.
16
+ */
17
+ const MediaApi = HttpApi.make("foldkit-media").add(HttpApiGroup.make("images").add(HttpApiEndpoint.get("variant", PATH, {
18
+ params: {
19
+ hash: Schema.String,
20
+ variant: Schema.String
21
+ },
22
+ success: HttpApiSchema.StreamUint8Array()
23
+ })));
24
+ //#endregion
25
+ //#region src/server/handlers.ts
26
+ /** The Cloudflare Images binding reads at most 20 MB; a store's own limit may be lower. */
27
+ const DEFAULT_MAX_BYTES = 20971520;
28
+ const defaultClientOf = (request) => request.headers["cf-connecting-ip"] ?? Option.getOrElse(request.remoteAddress, () => "unknown");
29
+ const optionsOf = (answer) => ({
30
+ status: statusOf(answer),
31
+ headers: headersFor(answer)
32
+ });
33
+ const served = (etag, from, encoded) => HttpServerResponse.uint8Array(encoded.bytes, {
34
+ ...optionsOf(Answer.cases.Variant.make({
35
+ etag,
36
+ from
37
+ })),
38
+ contentType: encoded.contentType
39
+ });
40
+ const notModified = (etag) => HttpServerResponse.empty(optionsOf(Answer.cases.NotModified.make({ etag })));
41
+ const refused = (answer) => HttpServerResponse.jsonUnsafe({ error: answer._tag }, optionsOf(answer));
42
+ /**
43
+ * The handlers of `MediaApi`'s one route. The path is decoded against the
44
+ * space; a variant kept is served as kept, and one the request already holds
45
+ * (`If-None-Match`) is a 304 before the store is read; otherwise the original
46
+ * is read, transformed, kept and served. Every answer, a refusal included,
47
+ * goes through `headersFor`, and a failure is never the original in the
48
+ * variant's place.
49
+ */
50
+ const handlers = (options = {}) => {
51
+ const { maxBytes: requestedMaxBytes = DEFAULT_MAX_BYTES, coalesce = false, clientOf = defaultClientOf } = options;
52
+ const space = options.provider?.space ?? standard;
53
+ const maxBytes = nonNegativeInteger("maxBytes", requestedMaxBytes);
54
+ const decodeHash = Schema.decodeUnknownOption(ContentHash);
55
+ const decodeVariant = Schema.decodeUnknownOption(space.schema);
56
+ const isSpelling = Schema.is(Spelling);
57
+ const spell = Schema.encodeSync(space.schema);
58
+ return HttpApiBuilder.group(MediaApi, "images", (group) => Effect.gen(function* () {
59
+ const originals = yield* Originals;
60
+ const transformer = yield* Transformer;
61
+ const variants = yield* Variants;
62
+ const admit = Option.match(yield* Effect.serviceOption(Admission), {
63
+ onNone: () => (_client) => Effect.void,
64
+ onSome: (admission) => admission.admit
65
+ });
66
+ const make = Effect.fn("Media.make")(function* (hash, variant) {
67
+ const original = yield* originals.get(hash);
68
+ if (original.size > maxBytes) return yield* new OriginalTooLarge({
69
+ size: original.size,
70
+ limit: maxBytes,
71
+ unit: "bytes"
72
+ });
73
+ return yield* transformer.transform(original, variant);
74
+ });
75
+ const makeAndKeep = (key, hash, variant) => make(hash, variant).pipe(Effect.tap((made) => variants.put(key, made)));
76
+ const shared = yield* Cache.make({
77
+ capacity: 1e4,
78
+ timeToLive: 0,
79
+ lookup: (key) => {
80
+ const at = key.indexOf("/");
81
+ const variant = Schema.decodeUnknownSync(space.schema)(key.slice(at + 1));
82
+ return makeAndKeep(key, key.slice(0, at), variant);
83
+ }
84
+ });
85
+ const serve = Effect.fn("Media.serve")(function* (hash, variant, ifNoneMatch, client) {
86
+ const key = `${hash}/${spell(variant)}`;
87
+ const etag = `"${key}"`;
88
+ if (matches(ifNoneMatch, etag)) return notModified(etag);
89
+ return yield* Option.match(yield* variants.get(key), {
90
+ onSome: ({ encoded, from }) => Effect.succeed(served(etag, from, encoded)),
91
+ onNone: () => admit(client).pipe(Effect.andThen(coalesce ? Cache.get(shared, key) : makeAndKeep(key, hash, variant)), Effect.map((made) => served(etag, "made", made)), Effect.catchTags({
92
+ OriginalNotFound: () => Effect.succeed(refused(Answer.cases.NotFound.make({}))),
93
+ OriginalTooLarge: () => Effect.succeed(refused(Answer.cases.TooLarge.make({}))),
94
+ TransformFailed: () => Effect.succeed(refused(Answer.cases.Failed.make({}))),
95
+ QuotaExhausted: () => Effect.succeed(refused(Answer.cases.Exhausted.make({}))),
96
+ RateLimited: ({ retryAfterSeconds }) => Effect.succeed(refused(Answer.cases.RateLimited.make({ retryAfterSeconds })))
97
+ }))
98
+ });
99
+ });
100
+ /**
101
+ * A spelling of the grammar this space does not read. An earlier revision of a variant
102
+ * it makes is served while kept and else sent to its current URL; anything else (a later
103
+ * revision, a width another release offers) is `Unoffered`, kept briefly.
104
+ */
105
+ const elsewhere = (hash, spelling, ifNoneMatch) => {
106
+ const current = respell(spelling, space.revision);
107
+ if (revisionOf(spelling) >= space.revision || Option.isNone(decodeVariant(current))) return Effect.succeed(refused(Answer.cases.Unoffered.make({})));
108
+ const key = `${hash}/${spelling}`;
109
+ const etag = `"${key}"`;
110
+ if (matches(ifNoneMatch, etag)) return Effect.succeed(notModified(etag));
111
+ return Effect.map(variants.get(key), (kept) => Option.match(kept, {
112
+ onSome: ({ encoded, from }) => served(etag, from, encoded),
113
+ onNone: () => refused(Answer.cases.Moved.make({ location: PATH.replace(":hash", hash).replace(":variant", current) }))
114
+ }));
115
+ };
116
+ return group.handle("variant", ({ params, request }) => Option.match(Option.all([decodeHash(params.hash), decodeVariant(params.variant)]), {
117
+ onNone: () => Option.match(decodeHash(params.hash), {
118
+ onNone: () => Effect.succeed(refused(Answer.cases.Malformed.make({}))),
119
+ onSome: (hash) => isSpelling(params.variant) ? elsewhere(hash, params.variant, request.headers["if-none-match"]) : Effect.succeed(refused(Answer.cases.Malformed.make({})))
120
+ }),
121
+ onSome: ([hash, variant]) => serve(hash, variant, request.headers["if-none-match"], clientOf(request))
122
+ }));
123
+ }));
124
+ };
125
+ /**
126
+ * The media server as an Effect HTTP application: its route registered with
127
+ * the `HttpRouter`, needing `Originals`, `Transformer` and `Variants`.
128
+ */
129
+ const layer = (options = {}) => HttpApiBuilder.layer(MediaApi).pipe(Layer.provide(handlers({
130
+ coalesce: true,
131
+ ...options
132
+ })));
133
+ /**
134
+ * A Worker's fetch handler over `app`, built from each environment's bindings
135
+ * once and kept, since a Worker hands every request the same bindings. A
136
+ * layer that fails to build answers a 500.
137
+ */
138
+ const fetchOf = (app) => {
139
+ const built = /* @__PURE__ */ new WeakMap();
140
+ return (request, env) => {
141
+ const known = built.get(env);
142
+ if (known !== void 0) return known(request);
143
+ const { handler } = HttpRouter.toWebHandler(app(env).pipe(Layer.provide(HttpServer.layerServices)), { disableLogger: true });
144
+ const answer = (incoming) => handler(incoming);
145
+ built.set(env, answer);
146
+ return answer(request);
147
+ };
148
+ };
149
+ //#endregion
150
+ //#region src/server/fetch.ts
151
+ const IMAGES = PATH.slice(0, PATH.indexOf(":"));
152
+ const UPLOADS = "/_media/";
153
+ /**
154
+ * The media server as a Worker's fetch handler. It owns `/_image/` and
155
+ * `/_media/`: a route of either it was not given, another method (a
156
+ * preflight, which the upload route never answers), or another path under
157
+ * them is a 404, and everything else goes to `otherwise`. The services are
158
+ * built from each environment's bindings once and kept; a layer that fails
159
+ * to build answers a 500.
160
+ */
161
+ const serveFetch = (options) => {
162
+ const { images, uploads, otherwise } = options;
163
+ if (images === void 0 && uploads === void 0) throw new Error("serveFetch: give it `images`, `uploads`, or both");
164
+ const media = fetchOf((env) => Layer.mergeAll(images === void 0 ? Layer.empty : layer({
165
+ ...images,
166
+ coalesce: false
167
+ }).pipe(Layer.provide(images.layer(env))), uploads === void 0 ? Layer.empty : uploadLayer(uploads).pipe(Layer.provide(uploads.layer(env)))));
168
+ return (request, env) => {
169
+ const { pathname } = new URL(request.url);
170
+ if (pathname.startsWith(IMAGES) || pathname.startsWith(UPLOADS)) return media(request, env);
171
+ return otherwise === void 0 ? Promise.resolve(new Response(null, { status: 404 })) : otherwise(request, env);
172
+ };
173
+ };
174
+ //#endregion
5
175
  //#region src/server/materialize.ts
6
176
  const VARIANT_PATH = /\/_image\/[0-9a-f]{64}\/[^\s"',)<>]+/g;
7
177
  const DEFAULT_MAX_FILES = 2e4;
@@ -60,6 +230,6 @@ const materialize = async (options) => {
60
230
  return made.sort((a, b) => a.file < b.file ? -1 : a.file > b.file ? 1 : 0);
61
231
  };
62
232
  //#endregion
63
- export { Admission, Answer, FactsUnavailable, MediaApi, OriginalNotFound, OriginalTooLarge, Originals, QuotaExhausted, RateLimited, TransformFailed, Transformer, UploadApi, UploadForbidden, UploadPolicy, Uploads, Variants, admissionRateLimiter, factsOf, handlers, headersFor, headersRule, layer, limitTransforms, materialize, originalsKeyValueStore, serveFetch, serveUploadFetch, statusOf, uploadHandlers, uploadLayer, uploadsKeyValueStore, variantsKeyValueStore, variantsNone };
233
+ export { Admission, Answer, FactsUnavailable, MediaApi, OriginalNotFound, OriginalTooLarge, Originals, QuotaExhausted, RateLimited, TransformFailed, Transformer, UploadApi, UploadForbidden, UploadPolicy, Uploads, Variants, admissionRateLimiter, factsOf, handlers, headersFor, headersRule, layer, limitTransforms, materialize, originalsKeyValueStore, serveFetch, statusOf, uploadHandlers, uploadLayer, uploadPolicyBearer, uploadsKeyValueStore, variantsKeyValueStore, variantsNone };
64
234
 
65
235
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../src/server/materialize.ts"],"sourcesContent":["import { nonNegativeInteger, positiveInteger } from '../limits.js'\nimport { Answer, headersFor } from './headers.js'\n\n/** A variant written out as a file, at its own URL's path. */\nexport interface Materialized {\n readonly file: string\n readonly contents: Uint8Array\n}\n\n// A hosted variant's path, wherever a page names one: in a `srcset`, a `src`, a preload.\nconst VARIANT_PATH = /\\/_image\\/[0-9a-f]{64}\\/[^\\s\"',)<>]+/g\n\n// Cloudflare Pages serves at most 20,000 files a site on its free plan.\nconst DEFAULT_MAX_FILES = 20_000\n\nconst PATTERN = '/_image/*'\n\n/**\n * The `_headers` rule (Cloudflare Pages, Netlify) a host needs for variants\n * written out as files: what the server itself sends a variant, from the same\n * `headersFor`, less the `ETag` and `Server-Timing` of one answer.\n */\nexport const headersRule = (): string => {\n const headers = headersFor(Answer.cases.Variant.make({ etag: '', from: 'made' }))\n const lines = Object.entries(headers)\n .filter(([name]) => name !== 'etag' && name !== 'server-timing')\n .map(([name, value]) => ` ${name}: ${value}`)\n return [PATTERN, ...lines].join('\\n') + '\\n'\n}\n\n/**\n * Every hosted variant the built pages name, made through `fetch` (the media\n * server's own handler, `serveFetch`) and returned as files at their own\n * paths, for `foldkit-ssr`'s `emit`. `Provider.hosted` then works on a static\n * host with no server at all. With a `Variants` store on disk, a second build\n * writes without encoding.\n *\n * It fails the build, naming every one, when a variant cannot be made (a\n * page would show a broken image), when there would be more than `maxFiles`,\n * and, given the site's `_headers` text, when that file has no rule for the\n * variants, which a static host would otherwise serve uncached.\n */\nexport const materialize = async (options: {\n readonly pages: ReadonlyArray<{ readonly html: string }>\n readonly fetch: (request: Request) => Promise<Response>\n /** The most files to write. */\n readonly maxFiles?: number\n /** The site's `_headers` text, to check it has `headersRule()`'s pattern. */\n readonly headersFile?: string\n /** Variants made at once. */\n readonly concurrency?: number\n}): Promise<ReadonlyArray<Materialized>> => {\n const paths = [\n ...new Set(options.pages.flatMap(page => page.html.match(VARIANT_PATH) ?? [])),\n ].sort()\n const maxFiles = nonNegativeInteger('maxFiles', options.maxFiles ?? DEFAULT_MAX_FILES)\n const concurrency = positiveInteger(\n 'foldkit-media: materialize concurrency',\n options.concurrency ?? 4,\n )\n if (paths.length > maxFiles) {\n throw new Error(\n `foldkit-media: the pages name ${paths.length} variants, more than maxFiles (${maxFiles})`,\n )\n }\n if (\n paths.length > 0 &&\n options.headersFile !== undefined &&\n !options.headersFile.split(/\\r?\\n/).some(line => line.trim() === PATTERN)\n ) {\n throw new Error(\n `foldkit-media: _headers has no ${PATTERN} rule, so the variants would be served uncached: add Media.headersRule()`,\n )\n }\n const made: Array<Materialized> = []\n const failed: Array<string> = []\n const queue = [...paths]\n const worker = async () => {\n for (let path = queue.shift(); path !== undefined; path = queue.shift()) {\n try {\n const response = await options.fetch(new Request(`http://materialize.invalid${path}`))\n if (response.status !== 200) {\n failed.push(`${path}: ${response.status}`)\n continue\n }\n made.push({ file: path.slice(1), contents: new Uint8Array(await response.arrayBuffer()) })\n } catch (cause) {\n failed.push(`${path}: ${cause instanceof Error ? cause.message : String(cause)}`)\n }\n }\n }\n await Promise.all(Array.from({ length: concurrency }, worker))\n if (failed.length > 0) {\n throw new Error(\n `foldkit-media: ${failed.length} variants could not be made:\\n${failed.sort().join('\\n')}`,\n )\n }\n return made.sort((a, b) => (a.file < b.file ? -1 : a.file > b.file ? 1 : 0))\n}\n"],"mappings":";;;;;AAUA,MAAM,eAAe;AAGrB,MAAM,oBAAoB;AAE1B,MAAM,UAAU;;;;;;AAOhB,MAAa,oBAA4B;CACvC,MAAM,UAAU,WAAW,OAAO,MAAM,QAAQ,KAAK;EAAE,MAAM;EAAI,MAAM;CAAO,CAAC,CAAC;CAChF,MAAM,QAAQ,OAAO,QAAQ,OAAO,CAAC,CAClC,QAAQ,CAAC,UAAU,SAAS,UAAU,SAAS,eAAe,CAAC,CAC/D,KAAK,CAAC,MAAM,WAAW,KAAK,KAAK,IAAI,OAAO;CAC/C,OAAO,CAAC,SAAS,GAAG,KAAK,CAAC,CAAC,KAAK,IAAI,IAAI;AAC1C;;;;;;;;;;;;;AAcA,MAAa,cAAc,OAAO,YASU;CAC1C,MAAM,QAAQ,CACZ,GAAG,IAAI,IAAI,QAAQ,MAAM,SAAQ,SAAQ,KAAK,KAAK,MAAM,YAAY,KAAK,CAAC,CAAC,CAAC,CAC/E,CAAC,CAAC,KAAK;CACP,MAAM,WAAW,mBAAmB,YAAY,QAAQ,YAAY,iBAAiB;CACrF,MAAM,cAAc,gBAClB,0CACA,QAAQ,eAAe,CACzB;CACA,IAAI,MAAM,SAAS,UACjB,MAAM,IAAI,MACR,iCAAiC,MAAM,OAAO,iCAAiC,SAAS,EAC1F;CAEF,IACE,MAAM,SAAS,KACf,QAAQ,gBAAgB,KAAA,KACxB,CAAC,QAAQ,YAAY,MAAM,OAAO,CAAC,CAAC,MAAK,SAAQ,KAAK,KAAK,MAAM,OAAO,GAExE,MAAM,IAAI,MACR,kCAAkC,QAAQ,yEAC5C;CAEF,MAAM,OAA4B,CAAC;CACnC,MAAM,SAAwB,CAAC;CAC/B,MAAM,QAAQ,CAAC,GAAG,KAAK;CACvB,MAAM,SAAS,YAAY;EACzB,KAAK,IAAI,OAAO,MAAM,MAAM,GAAG,SAAS,KAAA,GAAW,OAAO,MAAM,MAAM,GACpE,IAAI;GACF,MAAM,WAAW,MAAM,QAAQ,MAAM,IAAI,QAAQ,6BAA6B,MAAM,CAAC;GACrF,IAAI,SAAS,WAAW,KAAK;IAC3B,OAAO,KAAK,GAAG,KAAK,IAAI,SAAS,QAAQ;IACzC;GACF;GACA,KAAK,KAAK;IAAE,MAAM,KAAK,MAAM,CAAC;IAAG,UAAU,IAAI,WAAW,MAAM,SAAS,YAAY,CAAC;GAAE,CAAC;EAC3F,SAAS,OAAO;GACd,OAAO,KAAK,GAAG,KAAK,IAAI,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAAG;EAClF;CAEJ;CACA,MAAM,QAAQ,IAAI,MAAM,KAAK,EAAE,QAAQ,YAAY,GAAG,MAAM,CAAC;CAC7D,IAAI,OAAO,SAAS,GAClB,MAAM,IAAI,MACR,kBAAkB,OAAO,OAAO,gCAAgC,OAAO,KAAK,CAAC,CAAC,KAAK,IAAI,GACzF;CAEF,OAAO,KAAK,MAAM,GAAG,MAAO,EAAE,OAAO,EAAE,OAAO,KAAK,EAAE,OAAO,EAAE,OAAO,IAAI,CAAE;AAC7E"}
1
+ {"version":3,"file":"index.mjs","names":["Variant.PATH","Variant.standard","Variant.ContentHash","Variant.Spelling","Variant.respell","Variant.revisionOf"],"sources":["../../src/server/api.ts","../../src/server/handlers.ts","../../src/server/fetch.ts","../../src/server/materialize.ts"],"sourcesContent":["import { Schema } from 'effect'\nimport { HttpApi, HttpApiEndpoint, HttpApiGroup, HttpApiSchema } from 'effect/http-api'\nimport * as Variant from '../variant.js'\n\n/**\n * The media server's HTTP API: one route, a variant of an original named by\n * its content hash. The route takes its params as text, and the handler\n * decodes them with the space's Schema, the one `Provider.hosted` encodes\n * with, so a variant outside the space is refused before any work, and that\n * refusal, like every answer, carries the headers `headersFor` decides.\n */\nexport const MediaApi = HttpApi.make('foldkit-media').add(\n HttpApiGroup.make('images').add(\n HttpApiEndpoint.get('variant', Variant.PATH, {\n params: { hash: Schema.String, variant: Schema.String },\n success: HttpApiSchema.StreamUint8Array(),\n }),\n ),\n)\n","import { Cache, Effect, Layer, Option, Schema } from 'effect'\nimport { HttpRouter, HttpServer, HttpServerResponse, type HttpServerRequest } from 'effect/http'\nimport { HttpApiBuilder } from 'effect/http-api'\nimport type { Hosted } from '../provider.js'\nimport * as Variant from '../variant.js'\nimport { nonNegativeInteger } from '../limits.js'\nimport { MediaApi } from './api.js'\nimport { Admission } from './admission.js'\nimport { OriginalTooLarge } from './errors.js'\nimport { Answer, headersFor, matches, statusOf, type From } from './headers.js'\nimport { Originals, Transformer, Variants, type Encoded } from './services.js'\n\n/** The Cloudflare Images binding reads at most 20 MB; a store's own limit may be lower. */\nconst DEFAULT_MAX_BYTES = 20 * 1024 * 1024\n\nexport interface Options {\n /**\n * The `Provider.hosted` the pages write URLs with: the server makes every\n * variant of its space and nothing else. `Provider.hosted()` when omitted.\n */\n readonly provider?: Hosted\n /** The largest original read, in bytes; larger ones are a 413. */\n readonly maxBytes?: number\n /**\n * Concurrent misses for one variant share one transform and one write.\n * Only where requests may wait on one another's work: on by default for\n * `layer` (a Node server), off in `serveFetch`, since a Worker request\n * cannot wake another's.\n */\n readonly coalesce?: boolean\n /**\n * Who is asking, for `Admission`: by default Cloudflare's `CF-Connecting-IP`,\n * else the connection's address. `X-Forwarded-For` is the client's to write,\n * so read it here only behind a proxy that sets it.\n */\n readonly clientOf?: (request: HttpServerRequest.HttpServerRequest) => string\n}\n\nconst defaultClientOf = (request: HttpServerRequest.HttpServerRequest): string =>\n request.headers['cf-connecting-ip'] ?? Option.getOrElse(request.remoteAddress, () => 'unknown')\n\nconst optionsOf = (answer: Answer) => ({ status: statusOf(answer), headers: headersFor(answer) })\n\nconst served = (etag: string, from: From, encoded: Encoded) =>\n HttpServerResponse.uint8Array(encoded.bytes, {\n ...optionsOf(Answer.cases.Variant.make({ etag, from })),\n contentType: encoded.contentType,\n })\n\nconst notModified = (etag: string) =>\n HttpServerResponse.empty(optionsOf(Answer.cases.NotModified.make({ etag })))\n\n// A refusal names its kind, and nothing of the server's internals.\nconst refused = (answer: Answer) =>\n HttpServerResponse.jsonUnsafe({ error: answer._tag }, optionsOf(answer))\n\n/**\n * The handlers of `MediaApi`'s one route. The path is decoded against the\n * space; a variant kept is served as kept, and one the request already holds\n * (`If-None-Match`) is a 304 before the store is read; otherwise the original\n * is read, transformed, kept and served. Every answer, a refusal included,\n * goes through `headersFor`, and a failure is never the original in the\n * variant's place.\n */\nexport const handlers = (options: Options = {}) => {\n const {\n maxBytes: requestedMaxBytes = DEFAULT_MAX_BYTES,\n coalesce = false,\n clientOf = defaultClientOf,\n } = options\n const space = options.provider?.space ?? Variant.standard\n const maxBytes = nonNegativeInteger('maxBytes', requestedMaxBytes)\n const decodeHash = Schema.decodeUnknownOption(Variant.ContentHash)\n const decodeVariant = Schema.decodeUnknownOption(space.schema)\n const isSpelling = Schema.is(Variant.Spelling)\n const spell = Schema.encodeSync(space.schema)\n return HttpApiBuilder.group(MediaApi, 'images', group =>\n Effect.gen(function* () {\n // Resolved once, when the route is built, so a store kept in memory lives as long as the server.\n const originals = yield* Originals\n const transformer = yield* Transformer\n const variants = yield* Variants\n const admit = Option.match(yield* Effect.serviceOption(Admission), {\n onNone: () => (_client: string) => Effect.void,\n onSome: admission => admission.admit,\n })\n const make = Effect.fn('Media.make')(function* (hash: string, variant: Variant.Variant) {\n const original = yield* originals.get(hash)\n if (original.size > maxBytes) {\n return yield* new OriginalTooLarge({\n size: original.size,\n limit: maxBytes,\n unit: 'bytes',\n })\n }\n return yield* transformer.transform(original, variant)\n })\n const makeAndKeep = (key: string, hash: string, variant: Variant.Variant) =>\n make(hash, variant).pipe(Effect.tap(made => variants.put(key, made)))\n // In flight only: an entry expires as it settles, so nothing is kept here and no failure is remembered.\n const shared = yield* Cache.make({\n capacity: 10_000,\n timeToLive: 0,\n lookup: (key: string) => {\n // The key is the hash, a slash, and the spelling: neither holds a slash of its own.\n const at = key.indexOf('/')\n const variant = Schema.decodeUnknownSync(space.schema)(key.slice(at + 1))\n return makeAndKeep(key, key.slice(0, at), variant)\n },\n })\n const serve = Effect.fn('Media.serve')(function* (\n hash: string,\n variant: Variant.Variant,\n ifNoneMatch: string | undefined,\n client: string,\n ) {\n // The decoded request spelled again: one request, one key, one ETag.\n const key = `${hash}/${spell(variant)}`\n const etag = `\"${key}\"`\n if (matches(ifNoneMatch, etag)) return notModified(etag)\n return yield* Option.match(yield* variants.get(key), {\n onSome: ({ encoded, from }) => Effect.succeed(served(etag, from, encoded)),\n onNone: () =>\n admit(client).pipe(\n Effect.andThen(coalesce ? Cache.get(shared, key) : makeAndKeep(key, hash, variant)),\n Effect.map(made => served(etag, 'made', made)),\n Effect.catchTags({\n OriginalNotFound: () => Effect.succeed(refused(Answer.cases.NotFound.make({}))),\n OriginalTooLarge: () => Effect.succeed(refused(Answer.cases.TooLarge.make({}))),\n TransformFailed: () => Effect.succeed(refused(Answer.cases.Failed.make({}))),\n QuotaExhausted: () => Effect.succeed(refused(Answer.cases.Exhausted.make({}))),\n RateLimited: ({ retryAfterSeconds }) =>\n Effect.succeed(refused(Answer.cases.RateLimited.make({ retryAfterSeconds }))),\n }),\n ),\n })\n })\n /**\n * A spelling of the grammar this space does not read. An earlier revision of a variant\n * it makes is served while kept and else sent to its current URL; anything else (a later\n * revision, a width another release offers) is `Unoffered`, kept briefly.\n */\n const elsewhere = (hash: string, spelling: string, ifNoneMatch: string | undefined) => {\n const current = Variant.respell(spelling, space.revision)\n if (\n Variant.revisionOf(spelling) >= space.revision ||\n Option.isNone(decodeVariant(current))\n ) {\n return Effect.succeed(refused(Answer.cases.Unoffered.make({})))\n }\n const key = `${hash}/${spelling}`\n const etag = `\"${key}\"`\n if (matches(ifNoneMatch, etag)) return Effect.succeed(notModified(etag))\n return Effect.map(variants.get(key), kept =>\n Option.match(kept, {\n onSome: ({ encoded, from }) => served(etag, from, encoded),\n onNone: () =>\n refused(\n Answer.cases.Moved.make({\n location: Variant.PATH.replace(':hash', hash).replace(':variant', current),\n }),\n ),\n }),\n )\n }\n return group.handle('variant', ({ params, request }) =>\n Option.match(Option.all([decodeHash(params.hash), decodeVariant(params.variant)]), {\n // Kept a year only when no release could spell it; anything else is answered above.\n onNone: () =>\n Option.match(decodeHash(params.hash), {\n onNone: () => Effect.succeed(refused(Answer.cases.Malformed.make({}))),\n onSome: hash =>\n isSpelling(params.variant)\n ? elsewhere(hash, params.variant, request.headers['if-none-match'])\n : Effect.succeed(refused(Answer.cases.Malformed.make({}))),\n }),\n onSome: ([hash, variant]) =>\n serve(hash, variant, request.headers['if-none-match'], clientOf(request)),\n }),\n )\n }),\n )\n}\n\n/**\n * The media server as an Effect HTTP application: its route registered with\n * the `HttpRouter`, needing `Originals`, `Transformer` and `Variants`.\n */\nexport const layer = (options: Options = {}) =>\n HttpApiBuilder.layer(MediaApi).pipe(Layer.provide(handlers({ coalesce: true, ...options })))\n\n/**\n * A Worker's fetch handler over `app`, built from each environment's bindings\n * once and kept, since a Worker hands every request the same bindings. A\n * layer that fails to build answers a 500.\n */\nexport const fetchOf = <Env extends object>(\n app: (\n env: Env,\n ) => Layer.Layer<\n never,\n unknown,\n HttpRouter.HttpRouter | Layer.Success<typeof HttpServer.layerServices>\n >,\n): ((request: Request, env: Env) => Promise<Response>) => {\n const built = new WeakMap<Env, (request: Request) => Promise<Response>>()\n return (request, env) => {\n const known = built.get(env)\n if (known !== undefined) return known(request)\n const { handler } = HttpRouter.toWebHandler(\n app(env).pipe(Layer.provide(HttpServer.layerServices)),\n { disableLogger: true },\n )\n const answer = (incoming: Request) => handler(incoming)\n built.set(env, answer)\n return answer(request)\n }\n}\n","import { Layer } from 'effect'\nimport type { Inspector } from '../describe.js'\nimport * as Variant from '../variant.js'\nimport { fetchOf, layer, type Options } from './handlers.js'\nimport type { Originals, Transformer, Variants } from './services.js'\nimport { uploadLayer, type UploadOptions, type UploadPolicy, type Uploads } from './upload.js'\n\nconst IMAGES = Variant.PATH.slice(0, Variant.PATH.indexOf(':'))\nconst UPLOADS = '/_media/'\n\n/** What `serveFetch` answers, each side's services built from the request's bindings. */\nexport interface FetchOptions<Env> {\n /** `GET /_image/…`: the variants. A Worker request cannot wait on another's, so nothing coalesces. */\n readonly images?: Omit<Options, 'coalesce'> & {\n readonly layer: (env: Env) => Layer.Layer<Originals | Transformer | Variants, unknown>\n }\n /** `POST /_media/upload` and `GET /_media/facts`: originals entering. */\n readonly uploads?: UploadOptions & {\n readonly layer: (env: Env) => Layer.Layer<Uploads | Inspector | UploadPolicy, unknown>\n }\n /** Every path outside `/_image/` and `/_media/`: the application's own routes. A 404 when omitted. */\n readonly otherwise?: (request: Request, env: Env) => Promise<Response>\n}\n\n/**\n * The media server as a Worker's fetch handler. It owns `/_image/` and\n * `/_media/`: a route of either it was not given, another method (a\n * preflight, which the upload route never answers), or another path under\n * them is a 404, and everything else goes to `otherwise`. The services are\n * built from each environment's bindings once and kept; a layer that fails\n * to build answers a 500.\n */\nexport const serveFetch = <Env extends object>(\n options: FetchOptions<Env>,\n): ((request: Request, env: Env) => Promise<Response>) => {\n const { images, uploads, otherwise } = options\n if (images === undefined && uploads === undefined) {\n throw new Error('serveFetch: give it `images`, `uploads`, or both')\n }\n const media = fetchOf<Env>(env =>\n Layer.mergeAll(\n images === undefined\n ? Layer.empty\n : layer({ ...images, coalesce: false }).pipe(Layer.provide(images.layer(env))),\n uploads === undefined\n ? Layer.empty\n : uploadLayer(uploads).pipe(Layer.provide(uploads.layer(env))),\n ),\n )\n return (request, env) => {\n const { pathname } = new URL(request.url)\n if (pathname.startsWith(IMAGES) || pathname.startsWith(UPLOADS)) return media(request, env)\n return otherwise === undefined\n ? Promise.resolve(new Response(null, { status: 404 }))\n : otherwise(request, env)\n }\n}\n","import { nonNegativeInteger, positiveInteger } from '../limits.js'\nimport { Answer, headersFor } from './headers.js'\n\n/** A variant written out as a file, at its own URL's path. */\nexport interface Materialized {\n readonly file: string\n readonly contents: Uint8Array\n}\n\n// A hosted variant's path, wherever a page names one: in a `srcset`, a `src`, a preload.\nconst VARIANT_PATH = /\\/_image\\/[0-9a-f]{64}\\/[^\\s\"',)<>]+/g\n\n// Cloudflare Pages serves at most 20,000 files a site on its free plan.\nconst DEFAULT_MAX_FILES = 20_000\n\nconst PATTERN = '/_image/*'\n\n/**\n * The `_headers` rule (Cloudflare Pages, Netlify) a host needs for variants\n * written out as files: what the server itself sends a variant, from the same\n * `headersFor`, less the `ETag` and `Server-Timing` of one answer.\n */\nexport const headersRule = (): string => {\n const headers = headersFor(Answer.cases.Variant.make({ etag: '', from: 'made' }))\n const lines = Object.entries(headers)\n .filter(([name]) => name !== 'etag' && name !== 'server-timing')\n .map(([name, value]) => ` ${name}: ${value}`)\n return [PATTERN, ...lines].join('\\n') + '\\n'\n}\n\n/**\n * Every hosted variant the built pages name, made through `fetch` (the media\n * server's own handler, `serveFetch`) and returned as files at their own\n * paths, for `foldkit-ssr`'s `emit`. `Provider.hosted` then works on a static\n * host with no server at all. With a `Variants` store on disk, a second build\n * writes without encoding.\n *\n * It fails the build, naming every one, when a variant cannot be made (a\n * page would show a broken image), when there would be more than `maxFiles`,\n * and, given the site's `_headers` text, when that file has no rule for the\n * variants, which a static host would otherwise serve uncached.\n */\nexport const materialize = async (options: {\n readonly pages: ReadonlyArray<{ readonly html: string }>\n readonly fetch: (request: Request) => Promise<Response>\n /** The most files to write. */\n readonly maxFiles?: number\n /** The site's `_headers` text, to check it has `headersRule()`'s pattern. */\n readonly headersFile?: string\n /** Variants made at once. */\n readonly concurrency?: number\n}): Promise<ReadonlyArray<Materialized>> => {\n const paths = [\n ...new Set(options.pages.flatMap(page => page.html.match(VARIANT_PATH) ?? [])),\n ].sort()\n const maxFiles = nonNegativeInteger('maxFiles', options.maxFiles ?? DEFAULT_MAX_FILES)\n const concurrency = positiveInteger(\n 'foldkit-media: materialize concurrency',\n options.concurrency ?? 4,\n )\n if (paths.length > maxFiles) {\n throw new Error(\n `foldkit-media: the pages name ${paths.length} variants, more than maxFiles (${maxFiles})`,\n )\n }\n if (\n paths.length > 0 &&\n options.headersFile !== undefined &&\n !options.headersFile.split(/\\r?\\n/).some(line => line.trim() === PATTERN)\n ) {\n throw new Error(\n `foldkit-media: _headers has no ${PATTERN} rule, so the variants would be served uncached: add Media.headersRule()`,\n )\n }\n const made: Array<Materialized> = []\n const failed: Array<string> = []\n const queue = [...paths]\n const worker = async () => {\n for (let path = queue.shift(); path !== undefined; path = queue.shift()) {\n try {\n const response = await options.fetch(new Request(`http://materialize.invalid${path}`))\n if (response.status !== 200) {\n failed.push(`${path}: ${response.status}`)\n continue\n }\n made.push({ file: path.slice(1), contents: new Uint8Array(await response.arrayBuffer()) })\n } catch (cause) {\n failed.push(`${path}: ${cause instanceof Error ? cause.message : String(cause)}`)\n }\n }\n }\n await Promise.all(Array.from({ length: concurrency }, worker))\n if (failed.length > 0) {\n throw new Error(\n `foldkit-media: ${failed.length} variants could not be made:\\n${failed.sort().join('\\n')}`,\n )\n }\n return made.sort((a, b) => (a.file < b.file ? -1 : a.file > b.file ? 1 : 0))\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAWA,MAAa,WAAW,QAAQ,KAAK,eAAe,CAAC,CAAC,IACpD,aAAa,KAAK,QAAQ,CAAC,CAAC,IAC1B,gBAAgB,IAAI,WAAWA,MAAc;CAC3C,QAAQ;EAAE,MAAM,OAAO;EAAQ,SAAS,OAAO;CAAO;CACtD,SAAS,cAAc,iBAAiB;AAC1C,CAAC,CACH,CACF;;;;ACLA,MAAM,oBAAoB;AAyB1B,MAAM,mBAAmB,YACvB,QAAQ,QAAQ,uBAAuB,OAAO,UAAU,QAAQ,qBAAqB,SAAS;AAEhG,MAAM,aAAa,YAAoB;CAAE,QAAQ,S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