foldkit-media 0.1.0 → 0.3.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 (73) hide show
  1. package/README.md +167 -66
  2. package/client.d.ts +2 -2
  3. package/dist/{asset-BNQ_j5tO.d.mts → asset-BLo8VWmd.d.mts} +32 -5
  4. package/dist/asset-BLo8VWmd.d.mts.map +1 -0
  5. package/dist/browser/index.d.mts +86 -4
  6. package/dist/browser/index.d.mts.map +1 -1
  7. package/dist/browser/index.mjs +88 -7
  8. package/dist/browser/index.mjs.map +1 -1
  9. package/dist/cloudflare/index.d.mts +13 -9
  10. package/dist/cloudflare/index.d.mts.map +1 -1
  11. package/dist/cloudflare/index.mjs +28 -12
  12. package/dist/cloudflare/index.mjs.map +1 -1
  13. package/dist/{describe-DdYvLhMY.d.mts → describe-BOgc0xbR.d.mts} +2 -6
  14. package/dist/describe-BOgc0xbR.d.mts.map +1 -0
  15. package/dist/{describe-Cqr63Gxa.mjs → describe-C6sWA_8p.mjs} +10 -10
  16. package/dist/describe-C6sWA_8p.mjs.map +1 -0
  17. package/dist/{errors-qETj7Pgi.mjs → errors-BhEgXJ4m.mjs} +2 -3
  18. package/dist/{errors-qETj7Pgi.mjs.map → errors-BhEgXJ4m.mjs.map} +1 -1
  19. package/dist/{format-BmfnR4jg.mjs → format-BCRTFU9j.mjs} +2 -3
  20. package/dist/{format-BmfnR4jg.mjs.map → format-BCRTFU9j.mjs.map} +1 -1
  21. package/dist/{icon-CowP8fQ0.mjs → icon-0A2dBtqj.mjs} +3 -4
  22. package/dist/{icon-CowP8fQ0.mjs.map → icon-0A2dBtqj.mjs.map} +1 -1
  23. package/dist/{icon-ClqtprHT.d.mts → icon-BGtxExTN.d.mts} +1 -2
  24. package/dist/{icon-ClqtprHT.d.mts.map → icon-BGtxExTN.d.mts.map} +1 -1
  25. package/dist/icons/index.d.mts +1 -3
  26. package/dist/icons/index.d.mts.map +1 -1
  27. package/dist/icons/index.mjs +2 -3
  28. package/dist/index.d.mts +13 -15
  29. package/dist/index.d.mts.map +1 -1
  30. package/dist/index.mjs +19 -21
  31. package/dist/index.mjs.map +1 -1
  32. package/dist/{limits-B6C9OOLl.mjs → limits-B4hHpyfE.mjs} +2 -3
  33. package/dist/{limits-B6C9OOLl.mjs.map → limits-B4hHpyfE.mjs.map} +1 -1
  34. package/dist/{provider-DztvQjOr.d.mts → provider-CB0nqu0m.d.mts} +21 -16
  35. package/dist/provider-CB0nqu0m.d.mts.map +1 -0
  36. package/dist/{rolldown-runtime-8H4AJuhK.mjs → rolldown-runtime-BJohB4LM.mjs} +1 -2
  37. package/dist/server/index.d.mts +34 -27
  38. package/dist/server/index.d.mts.map +1 -1
  39. package/dist/server/index.mjs +174 -8
  40. package/dist/server/index.mjs.map +1 -1
  41. package/dist/{services-BeakQl7F.mjs → services-7B4hsQM7.mjs} +3 -4
  42. package/dist/{services-BeakQl7F.mjs.map → services-7B4hsQM7.mjs.map} +1 -1
  43. package/dist/{services-Ck-7dhIP.d.mts → services-BZoK2VOY.d.mts} +3 -5
  44. package/dist/services-BZoK2VOY.d.mts.map +1 -0
  45. package/dist/sharp/index.d.mts +2 -4
  46. package/dist/sharp/index.d.mts.map +1 -1
  47. package/dist/sharp/index.mjs +5 -6
  48. package/dist/{upload-C5YM5jZR.mjs → stores-CxraN3kt.mjs} +128 -228
  49. package/dist/stores-CxraN3kt.mjs.map +1 -0
  50. package/dist/unpic/index.d.mts +2 -4
  51. package/dist/unpic/index.d.mts.map +1 -1
  52. package/dist/unpic/index.mjs +2 -3
  53. package/dist/{upload-C4_inwfv.d.mts → upload-lVLMRJoC.d.mts} +53 -24
  54. package/dist/upload-lVLMRJoC.d.mts.map +1 -0
  55. package/dist/{variant-BOg1M0Wj.d.mts → variant-B-vyMmFB.d.mts} +2 -3
  56. package/dist/{variant-BOg1M0Wj.d.mts.map → variant-B-vyMmFB.d.mts.map} +1 -1
  57. package/dist/vite/index.d.mts +1 -5
  58. package/dist/vite/index.d.mts.map +1 -1
  59. package/dist/vite/index.mjs +7 -9
  60. package/dist/vite/index.mjs.map +1 -1
  61. package/dist/{widths-BEa9odY6.mjs → widths-qp3jshiF.mjs} +3 -4
  62. package/dist/{widths-BEa9odY6.mjs.map → widths-qp3jshiF.mjs.map} +1 -1
  63. package/dist/{widths-Cg7-x89y.d.mts → widths-upkgLdek.d.mts} +1 -3
  64. package/dist/widths-upkgLdek.d.mts.map +1 -0
  65. package/package.json +6 -6
  66. package/dist/asset-BNQ_j5tO.d.mts.map +0 -1
  67. package/dist/describe-Cqr63Gxa.mjs.map +0 -1
  68. package/dist/describe-DdYvLhMY.d.mts.map +0 -1
  69. package/dist/provider-DztvQjOr.d.mts.map +0 -1
  70. package/dist/services-Ck-7dhIP.d.mts.map +0 -1
  71. package/dist/upload-C4_inwfv.d.mts.map +0 -1
  72. package/dist/upload-C5YM5jZR.mjs.map +0 -1
  73. package/dist/widths-Cg7-x89y.d.mts.map +0 -1
package/dist/index.mjs CHANGED
@@ -1,11 +1,11 @@
1
- import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.mjs";
2
- import { n as mimeType, t as Format } from "./format-BmfnR4jg.mjs";
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";
5
- import { n as icon_exports } from "./icon-CowP8fQ0.mjs";
1
+ import { t as __exportAll } from "./rolldown-runtime-BJohB4LM.mjs";
2
+ import { n as mimeType, t as Format } from "./format-BCRTFU9j.mjs";
3
+ import { i as widths_exports, n as make, r as standard, t as atLeast } from "./widths-qp3jshiF.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-C6sWA_8p.mjs";
5
+ import { n as icon_exports } from "./icon-0A2dBtqj.mjs";
6
6
  import { Option, Schema } from "effect";
7
7
  import { thumbHashToAverageRGBA, thumbHashToDataURL } from "thumbhash";
8
- //#region src/layout.ts
8
+ // src/layout.ts
9
9
  var layout_exports = /* @__PURE__ */ __exportAll({
10
10
  Constrained: () => Constrained,
11
11
  Fixed: () => Fixed,
@@ -82,8 +82,7 @@ const box = (layout, asset) => {
82
82
  })
83
83
  });
84
84
  };
85
- //#endregion
86
- //#region src/placeholder.ts
85
+ // src/placeholder.ts
87
86
  const DECODED_LIMIT = 256;
88
87
  const decoded = /* @__PURE__ */ new Map();
89
88
  const bytesOf = (hash) => Uint8Array.from(atob(hash), (char) => char.charCodeAt(0));
@@ -115,8 +114,7 @@ const background = (asset, provider, level) => Option.flatMap(asset.placeholder,
115
114
  encoding: provider.fallback
116
115
  }), cssUrl)
117
116
  }));
118
- //#endregion
119
- //#region src/picture.ts
117
+ // src/picture.ts
120
118
  var picture_exports = /* @__PURE__ */ __exportAll({
121
119
  derive: () => derive,
122
120
  ogImage: () => ogImage,
@@ -227,8 +225,7 @@ const ogImage = (asset, provider, origin) => {
227
225
  encoding
228
226
  }))), (url) => new URL(url, origin).href);
229
227
  };
230
- //#endregion
231
- //#region src/provider.ts
228
+ // src/provider.ts
232
229
  var provider_exports = /* @__PURE__ */ __exportAll({
233
230
  cdnCgi: () => cdnCgi,
234
231
  fromFiles: () => fromFiles,
@@ -283,11 +280,12 @@ const cdnCgiSource = (key) => {
283
280
  };
284
281
  /**
285
282
  * 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.
283
+ * `baseUrl`. An original is named by its content hash, so it takes a
284
+ * `HashedAsset`, and has no URL for `auto`: this server names the format in
285
+ * the URL, never reads `Accept`, so every cache can key on the URL alone.
286
+ * Its formats and quality must be in `space`, or it is refused here rather
287
+ * than answered with a 400 on every image. Give the same value to the server
288
+ * (`serveFetch`'s `images.provider`), which reads its space from it.
291
289
  */
292
290
  const hosted = (options = {}) => {
293
291
  const { baseUrl: askedBaseUrl = "", space = standard$1 } = options;
@@ -305,20 +303,20 @@ const hosted = (options = {}) => {
305
303
  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
304
  const encodeVariant = Schema.encodeOption(space.schema);
307
305
  return {
306
+ space,
308
307
  widths: space.widths,
309
308
  sources,
310
309
  fallback,
311
310
  url: (asset, { width, encoding }) => {
312
311
  if (encoding === "auto") return Option.none();
313
- return Option.flatMap(asset.hash, (hash) => Option.map(encodeVariant({
312
+ return Option.map(encodeVariant({
314
313
  width,
315
314
  format: encoding,
316
315
  quality
317
- }), (variant) => baseUrl + PATH.replace(":hash", hash).replace(":variant", variant)));
316
+ }), (variant) => baseUrl + PATH.replace(":hash", asset.hash.value).replace(":variant", variant));
318
317
  }
319
318
  };
320
319
  };
321
- //#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 };
320
+ 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
321
 
324
322
  //# 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;;CAEtC,OAAO,EAAE,OAAO,UAAU;;CAE1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AC,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;;CAEhC,WAAW,CAAC;AACd,CAAC;AAID,MAAa,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AGjF,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,4 +1,4 @@
1
- //#region src/limits.ts
1
+ // src/limits.ts
2
2
  const nonNegativeInteger = (name, value) => {
3
3
  if (!Number.isSafeInteger(value) || value < 0) throw new Error(`foldkit-media: ${name} must be a non-negative integer`);
4
4
  return value;
@@ -7,7 +7,6 @@ const positiveInteger = (name, value) => {
7
7
  if (!Number.isSafeInteger(value) || value < 1) throw new Error(`${name} must be a positive integer`);
8
8
  return value;
9
9
  };
10
- //#endregion
11
10
  export { positiveInteger as n, nonNegativeInteger as t };
12
11
 
13
- //# sourceMappingURL=limits-B6C9OOLl.mjs.map
12
+ //# sourceMappingURL=limits-B4hHpyfE.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"limits-B6C9OOLl.mjs","names":[],"sources":["../src/limits.ts"],"sourcesContent":["export const nonNegativeInteger = (name: string, value: number): number => {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new Error(`foldkit-media: ${name} must be a non-negative integer`)\n }\n return value\n}\n\nexport const positiveInteger = (name: string, value: number): number => {\n if (!Number.isSafeInteger(value) || value < 1) {\n throw new Error(`${name} must be a positive integer`)\n }\n return value\n}\n"],"mappings":";AAAA,MAAa,sBAAsB,MAAc,UAA0B;CACzE,IAAI,CAAC,OAAO,cAAc,KAAK,KAAK,QAAQ,GAC1C,MAAM,IAAI,MAAM,kBAAkB,KAAK,gCAAgC;CAEzE,OAAO;AACT;AAEA,MAAa,mBAAmB,MAAc,UAA0B;CACtE,IAAI,CAAC,OAAO,cAAc,KAAK,KAAK,QAAQ,GAC1C,MAAM,IAAI,MAAM,GAAG,KAAK,4BAA4B;CAEtD,OAAO;AACT"}
1
+ {"version":3,"file":"limits-B4hHpyfE.mjs","names":[],"sources":["../src/limits.ts"],"sourcesContent":["export const nonNegativeInteger = (name: string, value: number): number => {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new Error(`foldkit-media: ${name} must be a non-negative integer`)\n }\n return value\n}\n\nexport const positiveInteger = (name: string, value: number): number => {\n if (!Number.isSafeInteger(value) || value < 1) {\n throw new Error(`${name} must be a positive integer`)\n }\n return value\n}\n"],"mappings":";AAAA,MAAa,sBAAsB,MAAc,UAA0B;CACzE,IAAI,CAAC,OAAO,cAAc,KAAK,KAAK,QAAQ,GAC1C,MAAM,IAAI,MAAM,kBAAkB,KAAK,gCAAgC;CAEzE,OAAO;AACT;AAEA,MAAa,mBAAmB,MAAc,UAA0B;CACtE,IAAI,CAAC,OAAO,cAAc,KAAK,KAAK,QAAQ,GAC1C,MAAM,IAAI,MAAM,GAAG,KAAK,4BAA4B;CAEtD,OAAO;AACT"}
@@ -1,9 +1,9 @@
1
- import { n as ImageAsset } from "./asset-BNQ_j5tO.mjs";
2
- import { i as Format, r as Encoding, t as Widths } from "./widths-Cg7-x89y.mjs";
3
- import { t as Space } from "./variant-BOg1M0Wj.mjs";
1
+ import { n as HashedAsset, r as ImageAsset } from "./asset-BLo8VWmd.mjs";
2
+ import { i as Format, r as Encoding, t as Widths } from "./widths-upkgLdek.mjs";
3
+ import { t as Space } from "./variant-B-vyMmFB.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,6 @@ 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;
73
- //#endregion
74
- export { provider_d_exports as n, Provider as t };
75
- //# sourceMappingURL=provider-DztvQjOr.d.mts.map
78
+ }) => Hosted;
79
+ export { Provider as n, provider_d_exports as r, Hosted as t };
80
+ //# sourceMappingURL=provider-CB0nqu0m.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider-CB0nqu0m.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,5 +1,5 @@
1
1
  import "node:module";
2
- //#region \0rolldown/runtime.js
2
+ // \0rolldown/runtime.js
3
3
  var __defProp = Object.defineProperty;
4
4
  var __exportAll = (all, no_symbols) => {
5
5
  let target = {};
@@ -10,5 +10,4 @@ var __exportAll = (all, no_symbols) => {
10
10
  if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
11
11
  return target;
12
12
  };
13
- //#endregion
14
13
  export { __exportAll as t };
@@ -1,12 +1,11 @@
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-BOgc0xbR.mjs";
2
+ import { _ as factsOf, a as UploadPolicy, b as admissionRateLimiter, c as Uploads, d as uploadLayer, f as uploadPolicyAny, g as FactsUnavailable, h as FactsOptions, i as UploadOptions, l as storedFactsKeyValueStore, m as uploadsKeyValueStore, n as UploadApi, o as UploadRoute, p as uploadPolicyBearer, r as UploadForbidden, s as UploadUnauthenticated, t as StoredFacts, u as uploadHandlers, v as Admission, y as RateLimited } from "../upload-lVLMRJoC.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-BZoK2VOY.mjs";
4
+ import { t as Hosted } from "../provider-CB0nqu0m.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";
8
8
  import { KeyValueStore } from "effect/persistence";
9
- //#region src/server/api.d.ts
10
9
  /**
11
10
  * The media server's HTTP API: one route, a variant of an original named by
12
11
  * its content hash. The route takes its params as text, and the handler
@@ -18,8 +17,6 @@ export declare const MediaApi: HttpApi.HttpApi<"foldkit-media", HttpApiGroup.Htt
18
17
  hash: Schema.String;
19
18
  variant: Schema.String;
20
19
  }>>, never, never, never, HttpApiSchema.StreamUint8Array, never, never, never>, false>>;
21
- //#endregion
22
- //#region src/server/headers.d.ts
23
20
  /** Every answer the media server gives, and nothing else: each has its status and its headers. */
24
21
  export declare const Answer: Schema.TaggedUnion<{
25
22
  readonly Described: Schema.TaggedStruct<"Described", {}>;
@@ -38,6 +35,7 @@ export declare const Answer: Schema.TaggedUnion<{
38
35
  readonly retryAfterSeconds: Schema.Number;
39
36
  }>;
40
37
  readonly TooLarge: Schema.TaggedStruct<"TooLarge", {}>;
38
+ readonly Unauthenticated: Schema.TaggedStruct<"Unauthenticated", {}>;
41
39
  readonly Unavailable: Schema.TaggedStruct<"Unavailable", {}>;
42
40
  readonly Unoffered: Schema.TaggedStruct<"Unoffered", {}>;
43
41
  readonly Unsupported: Schema.TaggedStruct<"Unsupported", {}>;
@@ -52,24 +50,25 @@ export type Answer = typeof Answer.Type;
52
50
  export declare const statusOf: (answer: Answer) => number;
53
51
  /**
54
52
  * Every response's headers, decided in one place, so the server, the edge
55
- * and a static host cannot disagree. A variant's URL names its bytes, so it
56
- * is kept for a year. A refusal of a variant is not: another release, or the
53
+ * and a static host cannot disagree. A variant's URL names the variant, and
54
+ * a new way of making it is a new revision, so it is kept for a year. A refusal of a variant is not: another release, or the
57
55
  * same one configured otherwise, may answer it, so only a CDN keeps it,
58
56
  * briefly; a failure is never kept. Every image may be read by a canvas on
59
57
  * another origin, and its type is never sniffed.
60
58
  */
61
59
  export declare const headersFor: (answer: Answer) => Readonly<Record<string, string>>;
62
- //#endregion
63
- //#region src/server/handlers.d.ts
64
60
  interface Options {
65
- /** Every variant this server makes: the same value `Provider.hosted` writes URLs in. */
66
- readonly space?: Space;
61
+ /**
62
+ * The `Provider.hosted` the pages write URLs with: the server makes every
63
+ * variant of its space and nothing else. `Provider.hosted()` when omitted.
64
+ */
65
+ readonly provider?: Hosted;
67
66
  /** The largest original read, in bytes; larger ones are a 413. */
68
67
  readonly maxBytes?: number;
69
68
  /**
70
69
  * Concurrent misses for one variant share one transform and one write.
71
70
  * 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
71
+ * `layer` (a Node server), off in `serveFetch`, since a Worker request
73
72
  * cannot wake another's.
74
73
  */
75
74
  readonly coalesce?: boolean;
@@ -94,17 +93,28 @@ export declare const handlers: (options?: Options) => Layer.Layer<import("effect
94
93
  * the `HttpRouter`, needing `Originals`, `Transformer` and `Variants`.
95
94
  */
96
95
  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>;
96
+ /** What `serveFetch` answers, each side's services built from the request's bindings. */
97
+ interface FetchOptions<Env> {
98
+ /** `GET /_image/…`: the variants. A Worker request cannot wait on another's, so nothing coalesces. */
99
+ readonly images?: Omit<Options, 'coalesce'> & {
100
+ readonly layer: (env: Env) => Layer.Layer<Originals | Transformer | Variants, unknown>;
101
+ };
102
+ /** `POST /_media/upload` and `GET /_media/facts`: originals entering. */
103
+ readonly uploads?: UploadOptions & {
104
+ readonly layer: (env: Env) => Layer.Layer<Uploads | Inspector | UploadPolicy, unknown>;
105
+ };
106
+ /** Every path outside `/_image/` and `/_media/`: the application's own routes. A 404 when omitted. */
107
+ readonly otherwise?: (request: Request, env: Env) => Promise<Response>;
108
+ }
97
109
  /**
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/`).
110
+ * The media server as a Worker's fetch handler. It owns `/_image/` and
111
+ * `/_media/`: a route of either it was not given, another method (a
112
+ * preflight, which the upload route never answers), or another path under
113
+ * them is a 404, and everything else goes to `otherwise`. The services are
114
+ * built from each environment's bindings once and kept; a layer that fails
115
+ * to build answers a 500.
101
116
  */
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>);
106
- //#endregion
107
- //#region src/server/stores.d.ts
117
+ export declare const serveFetch: <Env extends object>(options: FetchOptions<Env>) => ((request: Request, env: Env) => Promise<Response>);
108
118
  /**
109
119
  * Variants kept in the application's `KeyValueStore`, under `prefix`:
110
120
  * `KeyValueStore.layerMemory` for tests, `layerFileSystem` on a disk,
@@ -121,8 +131,6 @@ export declare const variantsKeyValueStore: (options?: {
121
131
  export declare const originalsKeyValueStore: (options?: {
122
132
  readonly prefix?: string;
123
133
  }) => Layer.Layer<Originals, never, KeyValueStore.KeyValueStore>;
124
- //#endregion
125
- //#region src/server/materialize.d.ts
126
134
  /** A variant written out as a file, at its own URL's path. */
127
135
  interface Materialized {
128
136
  readonly file: string;
@@ -158,6 +166,5 @@ export declare const materialize: (options: {
158
166
  /** Variants made at once. */
159
167
  readonly concurrency?: number;
160
168
  }) => Promise<ReadonlyArray<Materialized>>;
161
- //#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 };
169
+ export { Admission, type Encoded, type FactsOptions, FactsUnavailable, type FetchOptions, type Kept, type Materialized, type Options, type Original, OriginalNotFound, OriginalTooLarge, Originals, QuotaExhausted, RateLimited, StoredFacts, TransformFailed, Transformer, UploadApi, UploadForbidden, type UploadOptions, UploadPolicy, type UploadRoute, UploadUnauthenticated, Uploads, Variants, admissionRateLimiter, factsOf, limitTransforms, storedFactsKeyValueStore, uploadHandlers, uploadLayer, uploadPolicyAny, uploadPolicyBearer, uploadsKeyValueStore, variantsNone };
163
170
  //# 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;;;;;;;;;;;;;;;;;;;;;;;;;;;YA4CP,gBAAgB,OAAO;;qBActB,WAAW,QAAQ;;;;;;;;;qBA2BnB,aAAU,QAAY,WAAS,SAAS;UC7EpC;;;;;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"}