foldkit-media 0.3.1 → 0.5.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 (175) hide show
  1. package/README.md +65 -4
  2. package/dist/{asset-BLo8VWmd.d.mts → asset.d.ts} +10 -11
  3. package/dist/asset.d.ts.map +1 -0
  4. package/dist/asset.js +66 -0
  5. package/dist/asset.js.map +1 -0
  6. package/dist/browser/index.d.ts +15 -0
  7. package/dist/browser/index.d.ts.map +1 -0
  8. package/dist/browser/index.js +69 -0
  9. package/dist/browser/index.js.map +1 -0
  10. package/dist/browser/{index.d.mts → upload.d.ts} +5 -16
  11. package/dist/browser/upload.d.ts.map +1 -0
  12. package/dist/browser/upload.js +87 -0
  13. package/dist/browser/upload.js.map +1 -0
  14. package/dist/cloudflare/{index.d.mts → index.d.ts} +8 -6
  15. package/dist/cloudflare/index.d.ts.map +1 -0
  16. package/dist/cloudflare/{index.mjs → index.js} +35 -15
  17. package/dist/cloudflare/index.js.map +1 -0
  18. package/dist/describe.d.ts +32 -0
  19. package/dist/describe.d.ts.map +1 -0
  20. package/dist/describe.js +30 -0
  21. package/dist/describe.js.map +1 -0
  22. package/dist/format.d.ts +12 -0
  23. package/dist/format.d.ts.map +1 -0
  24. package/dist/{format-BCRTFU9j.mjs → format.js} +2 -2
  25. package/dist/format.js.map +1 -0
  26. package/dist/{icon-BGtxExTN.d.mts → icon.d.ts} +14 -17
  27. package/dist/icon.d.ts.map +1 -0
  28. package/dist/{icon-0A2dBtqj.mjs → icon.js} +2 -12
  29. package/dist/icon.js.map +1 -0
  30. package/dist/icons/{index.d.mts → index.d.ts} +2 -2
  31. package/dist/icons/index.d.ts.map +1 -0
  32. package/dist/icons/{index.mjs → index.js} +2 -2
  33. package/dist/icons/index.js.map +1 -0
  34. package/dist/index.d.ts +11 -0
  35. package/dist/index.js +10 -0
  36. package/dist/layout.d.ts +60 -0
  37. package/dist/layout.d.ts.map +1 -0
  38. package/dist/layout.js +72 -0
  39. package/dist/layout.js.map +1 -0
  40. package/dist/limits.d.ts +3 -0
  41. package/dist/limits.d.ts.map +1 -0
  42. package/dist/{limits-B4hHpyfE.mjs → limits.js} +2 -2
  43. package/dist/limits.js.map +1 -0
  44. package/dist/picture.d.ts +88 -0
  45. package/dist/picture.d.ts.map +1 -0
  46. package/dist/picture.js +113 -0
  47. package/dist/picture.js.map +1 -0
  48. package/dist/placeholder.d.ts +16 -0
  49. package/dist/placeholder.d.ts.map +1 -0
  50. package/dist/placeholder.js +38 -0
  51. package/dist/placeholder.js.map +1 -0
  52. package/dist/{provider-CB0nqu0m.d.mts → provider.d.ts} +16 -19
  53. package/dist/provider.d.ts.map +1 -0
  54. package/dist/provider.js +93 -0
  55. package/dist/provider.js.map +1 -0
  56. package/dist/server/admission.d.ts +31 -0
  57. package/dist/server/admission.d.ts.map +1 -0
  58. package/dist/server/admission.js +41 -0
  59. package/dist/server/admission.js.map +1 -0
  60. package/dist/server/api.d.ts +14 -0
  61. package/dist/server/api.d.ts.map +1 -0
  62. package/dist/server/api.js +21 -0
  63. package/dist/server/api.js.map +1 -0
  64. package/dist/server/diagnostics.d.ts +53 -0
  65. package/dist/server/diagnostics.d.ts.map +1 -0
  66. package/dist/server/diagnostics.js +50 -0
  67. package/dist/server/diagnostics.js.map +1 -0
  68. package/dist/server/errors.d.ts +24 -0
  69. package/dist/server/errors.d.ts.map +1 -0
  70. package/dist/{errors-BhEgXJ4m.mjs → server/errors.js} +2 -2
  71. package/dist/server/errors.js.map +1 -0
  72. package/dist/server/facts.d.ts +36 -0
  73. package/dist/server/facts.d.ts.map +1 -0
  74. package/dist/server/facts.js +126 -0
  75. package/dist/server/facts.js.map +1 -0
  76. package/dist/server/fetch.d.ts +29 -0
  77. package/dist/server/fetch.d.ts.map +1 -0
  78. package/dist/server/fetch.js +32 -0
  79. package/dist/server/fetch.js.map +1 -0
  80. package/dist/server/handlers.d.ts +48 -0
  81. package/dist/server/handlers.d.ts.map +1 -0
  82. package/dist/server/handlers.js +151 -0
  83. package/dist/server/handlers.js.map +1 -0
  84. package/dist/server/headers.d.ts +47 -0
  85. package/dist/server/headers.d.ts.map +1 -0
  86. package/dist/server/headers.js +134 -0
  87. package/dist/server/headers.js.map +1 -0
  88. package/dist/server/index.d.ts +13 -0
  89. package/dist/server/index.js +12 -0
  90. package/dist/server/materialize.d.ts +36 -0
  91. package/dist/server/materialize.d.ts.map +1 -0
  92. package/dist/server/materialize.js +62 -0
  93. package/dist/server/materialize.js.map +1 -0
  94. package/dist/{services-BZoK2VOY.d.mts → server/services.d.ts} +12 -12
  95. package/dist/server/services.d.ts.map +1 -0
  96. package/dist/{services-7B4hsQM7.mjs → server/services.js} +3 -3
  97. package/dist/server/services.js.map +1 -0
  98. package/dist/server/stores.d.ts +27 -0
  99. package/dist/server/stores.d.ts.map +1 -0
  100. package/dist/server/stores.js +62 -0
  101. package/dist/server/stores.js.map +1 -0
  102. package/dist/server/upload.d.ts +113 -0
  103. package/dist/server/upload.d.ts.map +1 -0
  104. package/dist/server/upload.js +185 -0
  105. package/dist/server/upload.js.map +1 -0
  106. package/dist/sharp/{index.d.mts → index.d.ts} +3 -3
  107. package/dist/sharp/index.d.ts.map +1 -0
  108. package/dist/sharp/{index.mjs → index.js} +11 -9
  109. package/dist/sharp/index.js.map +1 -0
  110. package/dist/unpic/{index.d.mts → index.d.ts} +5 -4
  111. package/dist/unpic/index.d.ts.map +1 -0
  112. package/dist/unpic/{index.mjs → index.js} +3 -3
  113. package/dist/unpic/index.js.map +1 -0
  114. package/dist/{variant-B-vyMmFB.d.mts → variant.d.ts} +15 -18
  115. package/dist/variant.d.ts.map +1 -0
  116. package/dist/variant.js +75 -0
  117. package/dist/variant.js.map +1 -0
  118. package/dist/vite/{index.d.mts → icons.d.ts} +1 -19
  119. package/dist/vite/icons.d.ts.map +1 -0
  120. package/dist/vite/{index.mjs → icons.js} +7 -168
  121. package/dist/vite/icons.js.map +1 -0
  122. package/dist/vite/images.d.ts +20 -0
  123. package/dist/vite/images.d.ts.map +1 -0
  124. package/dist/vite/images.js +167 -0
  125. package/dist/vite/images.js.map +1 -0
  126. package/dist/vite/index.d.ts +3 -0
  127. package/dist/vite/index.js +3 -0
  128. package/dist/widths.d.ts +22 -0
  129. package/dist/widths.d.ts.map +1 -0
  130. package/dist/{widths-qp3jshiF.mjs → widths.js} +2 -8
  131. package/dist/widths.js.map +1 -0
  132. package/package.json +23 -22
  133. package/dist/asset-BLo8VWmd.d.mts.map +0 -1
  134. package/dist/browser/index.d.mts.map +0 -1
  135. package/dist/browser/index.mjs +0 -150
  136. package/dist/browser/index.mjs.map +0 -1
  137. package/dist/cloudflare/index.d.mts.map +0 -1
  138. package/dist/cloudflare/index.mjs.map +0 -1
  139. package/dist/describe-BOgc0xbR.d.mts +0 -52
  140. package/dist/describe-BOgc0xbR.d.mts.map +0 -1
  141. package/dist/describe-C6sWA_8p.mjs +0 -171
  142. package/dist/describe-C6sWA_8p.mjs.map +0 -1
  143. package/dist/errors-BhEgXJ4m.mjs.map +0 -1
  144. package/dist/format-BCRTFU9j.mjs.map +0 -1
  145. package/dist/icon-0A2dBtqj.mjs.map +0 -1
  146. package/dist/icon-BGtxExTN.d.mts.map +0 -1
  147. package/dist/icons/index.d.mts.map +0 -1
  148. package/dist/icons/index.mjs.map +0 -1
  149. package/dist/index.d.mts +0 -157
  150. package/dist/index.d.mts.map +0 -1
  151. package/dist/index.mjs +0 -322
  152. package/dist/index.mjs.map +0 -1
  153. package/dist/limits-B4hHpyfE.mjs.map +0 -1
  154. package/dist/provider-CB0nqu0m.d.mts.map +0 -1
  155. package/dist/rolldown-runtime-BJohB4LM.mjs +0 -13
  156. package/dist/server/index.d.mts +0 -170
  157. package/dist/server/index.d.mts.map +0 -1
  158. package/dist/server/index.mjs +0 -231
  159. package/dist/server/index.mjs.map +0 -1
  160. package/dist/services-7B4hsQM7.mjs.map +0 -1
  161. package/dist/services-BZoK2VOY.d.mts.map +0 -1
  162. package/dist/sharp/index.d.mts.map +0 -1
  163. package/dist/sharp/index.mjs.map +0 -1
  164. package/dist/stores-CxraN3kt.mjs +0 -490
  165. package/dist/stores-CxraN3kt.mjs.map +0 -1
  166. package/dist/unpic/index.d.mts.map +0 -1
  167. package/dist/unpic/index.mjs.map +0 -1
  168. package/dist/upload-lVLMRJoC.d.mts +0 -160
  169. package/dist/upload-lVLMRJoC.d.mts.map +0 -1
  170. package/dist/variant-B-vyMmFB.d.mts.map +0 -1
  171. package/dist/vite/index.d.mts.map +0 -1
  172. package/dist/vite/index.mjs.map +0 -1
  173. package/dist/widths-qp3jshiF.mjs.map +0 -1
  174. package/dist/widths-upkgLdek.d.mts +0 -36
  175. package/dist/widths-upkgLdek.d.mts.map +0 -1
@@ -1 +0,0 @@
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,QAAQ,aAAa,MAAM,MAAM;AAC9C,MAAa,cAAc,aAAa,MAAM,YAAY;AAC1D,MAAa,kBAA0B,aAAa,MAAM,UAAU,KAAK,CAAC,CAAC;;;;;;;AAkB3E,M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AM,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 +0,0 @@
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 +0,0 @@
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,13 +0,0 @@
1
- import "node:module";
2
- // \0rolldown/runtime.js
3
- var __defProp = Object.defineProperty;
4
- var __exportAll = (all, no_symbols) => {
5
- let target = {};
6
- for (var name in all) __defProp(target, name, {
7
- get: all[name],
8
- enumerable: true
9
- });
10
- if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
11
- return target;
12
- };
13
- export { __exportAll as t };
@@ -1,170 +0,0 @@
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
- import { Layer, Schema } from "effect";
6
- import { HttpApi, HttpApiEndpoint, HttpApiGroup, HttpApiSchema } from "effect/http-api";
7
- import { HttpRouter, HttpServer, HttpServerRequest } from "effect/http";
8
- import { KeyValueStore } from "effect/persistence";
9
- /**
10
- * The media server's HTTP API: one route, a variant of an original named by
11
- * its content hash. The route takes its params as text, and the handler
12
- * decodes them with the space's Schema, the one `Provider.hosted` encodes
13
- * with, so a variant outside the space is refused before any work, and that
14
- * refusal, like every answer, carries the headers `headersFor` decides.
15
- */
16
- export declare const MediaApi: HttpApi.HttpApi<"foldkit-media", HttpApiGroup.HttpApiGroup<"images", HttpApiEndpoint.HttpApiEndpoint<"variant", "GET", "/_image/:hash/:variant", Schema.toCodecStringTree<Schema.Struct<{
17
- hash: Schema.String;
18
- variant: Schema.String;
19
- }>>, never, never, never, HttpApiSchema.StreamUint8Array, never, never, never>, false>>;
20
- /** Every answer the media server gives, and nothing else: each has its status and its headers. */
21
- export declare const Answer: Schema.TaggedUnion<{
22
- readonly Described: Schema.TaggedStruct<"Described", {}>;
23
- readonly Exhausted: Schema.TaggedStruct<"Exhausted", {}>;
24
- readonly Failed: Schema.TaggedStruct<"Failed", {}>;
25
- readonly Forbidden: Schema.TaggedStruct<"Forbidden", {}>;
26
- readonly Malformed: Schema.TaggedStruct<"Malformed", {}>;
27
- readonly Moved: Schema.TaggedStruct<"Moved", {
28
- readonly location: Schema.String;
29
- }>;
30
- readonly NotFound: Schema.TaggedStruct<"NotFound", {}>;
31
- readonly NotModified: Schema.TaggedStruct<"NotModified", {
32
- readonly etag: Schema.String;
33
- }>;
34
- readonly RateLimited: Schema.TaggedStruct<"RateLimited", {
35
- readonly retryAfterSeconds: Schema.Number;
36
- }>;
37
- readonly TooLarge: Schema.TaggedStruct<"TooLarge", {}>;
38
- readonly Unauthenticated: Schema.TaggedStruct<"Unauthenticated", {}>;
39
- readonly Unavailable: Schema.TaggedStruct<"Unavailable", {}>;
40
- readonly Unoffered: Schema.TaggedStruct<"Unoffered", {}>;
41
- readonly Unsupported: Schema.TaggedStruct<"Unsupported", {}>;
42
- readonly Uploaded: Schema.TaggedStruct<"Uploaded", {}>;
43
- readonly Variant: Schema.TaggedStruct<"Variant", {
44
- readonly etag: Schema.String;
45
- readonly from: Schema.Literals<readonly ["edge", "store", "made"]>;
46
- }>;
47
- }>;
48
- export type Answer = typeof Answer.Type;
49
- /** The status of each answer. */
50
- export declare const statusOf: (answer: Answer) => number;
51
- /**
52
- * Every response's headers, decided in one place, so the server, the edge
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
55
- * same one configured otherwise, may answer it, so only a CDN keeps it,
56
- * briefly; a failure is never kept. Every image may be read by a canvas on
57
- * another origin, and its type is never sniffed.
58
- */
59
- export declare const headersFor: (answer: Answer) => Readonly<Record<string, string>>;
60
- interface Options {
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;
66
- /** The largest original read, in bytes; larger ones are a 413. */
67
- readonly maxBytes?: number;
68
- /**
69
- * Concurrent misses for one variant share one transform and one write.
70
- * Only where requests may wait on one another's work: on by default for
71
- * `layer` (a Node server), off in `serveFetch`, since a Worker request
72
- * cannot wake another's.
73
- */
74
- readonly coalesce?: boolean;
75
- /**
76
- * Who is asking, for `Admission`: by default Cloudflare's `CF-Connecting-IP`,
77
- * else the connection's address. `X-Forwarded-For` is the client's to write,
78
- * so read it here only behind a proxy that sets it.
79
- */
80
- readonly clientOf?: (request: HttpServerRequest.HttpServerRequest) => string;
81
- }
82
- /**
83
- * The handlers of `MediaApi`'s one route. The path is decoded against the
84
- * space; a variant kept is served as kept, and one the request already holds
85
- * (`If-None-Match`) is a 304 before the store is read; otherwise the original
86
- * is read, transformed, kept and served. Every answer, a refusal included,
87
- * goes through `headersFor`, and a failure is never the original in the
88
- * variant's place.
89
- */
90
- export declare const handlers: (options?: Options) => Layer.Layer<import("effect/http-api/HttpApiGroup").Service<"foldkit-media", "images">, never, Originals | Transformer | Variants>;
91
- /**
92
- * The media server as an Effect HTTP application: its route registered with
93
- * the `HttpRouter`, needing `Originals`, `Transformer` and `Variants`.
94
- */
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
- }
109
- /**
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.
116
- */
117
- export declare const serveFetch: <Env extends object>(options: FetchOptions<Env>) => ((request: Request, env: Env) => Promise<Response>);
118
- /**
119
- * Variants kept in the application's `KeyValueStore`, under `prefix`:
120
- * `KeyValueStore.layerMemory` for tests, `layerFileSystem` on a disk,
121
- * `layerSql` over SQLite or D1.
122
- */
123
- export declare const variantsKeyValueStore: (options?: {
124
- readonly prefix?: string;
125
- }) => Layer.Layer<Variants, never, KeyValueStore.KeyValueStore>;
126
- /**
127
- * Originals in the application's `KeyValueStore`, each under its content
128
- * hash after `prefix`. A store that fails is a defect, not a missing
129
- * original: the original is the data, and a 404 would say it is gone.
130
- */
131
- export declare const originalsKeyValueStore: (options?: {
132
- readonly prefix?: string;
133
- }) => Layer.Layer<Originals, never, KeyValueStore.KeyValueStore>;
134
- /** A variant written out as a file, at its own URL's path. */
135
- interface Materialized {
136
- readonly file: string;
137
- readonly contents: Uint8Array;
138
- }
139
- /**
140
- * The `_headers` rule (Cloudflare Pages, Netlify) a host needs for variants
141
- * written out as files: what the server itself sends a variant, from the same
142
- * `headersFor`, less the `ETag` and `Server-Timing` of one answer.
143
- */
144
- export declare const headersRule: () => string;
145
- /**
146
- * Every hosted variant the built pages name, made through `fetch` (the media
147
- * server's own handler, `serveFetch`) and returned as files at their own
148
- * paths, for `foldkit-ssr`'s `emit`. `Provider.hosted` then works on a static
149
- * host with no server at all. With a `Variants` store on disk, a second build
150
- * writes without encoding.
151
- *
152
- * It fails the build, naming every one, when a variant cannot be made (a
153
- * page would show a broken image), when there would be more than `maxFiles`,
154
- * and, given the site's `_headers` text, when that file has no rule for the
155
- * variants, which a static host would otherwise serve uncached.
156
- */
157
- export declare const materialize: (options: {
158
- readonly pages: ReadonlyArray<{
159
- readonly html: string;
160
- }>;
161
- readonly fetch: (request: Request) => Promise<Response>;
162
- /** The most files to write. */
163
- readonly maxFiles?: number;
164
- /** The site's `_headers` text, to check it has `headersRule()`'s pattern. */
165
- readonly headersFile?: string;
166
- /** Variants made at once. */
167
- readonly concurrency?: number;
168
- }) => Promise<ReadonlyArray<Materialized>>;
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 };
170
- //# sourceMappingURL=index.d.mts.map
@@ -1 +0,0 @@
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"}
@@ -1,231 +0,0 @@
1
- import { c as ContentHash, d as Spelling, f as respell, l as PATH, m as standard, p as revisionOf } from "../describe-C6sWA_8p.mjs";
2
- import { n as positiveInteger, t as nonNegativeInteger } from "../limits-B4hHpyfE.mjs";
3
- import { i as TransformFailed, n as OriginalTooLarge, r as QuotaExhausted, t as OriginalNotFound } from "../errors-BhEgXJ4m.mjs";
4
- import { C as admissionRateLimiter, D as statusOf, E as matches, S as RateLimited, T as headersFor, _ as uploadPolicyBearer, a as UploadApi, b as factsOf, c as UploadUnauthenticated, g as uploadPolicyAny, h as uploadLayer, i as StoredFacts, l as Uploads, m as uploadHandlers, n as originalsKeyValueStore, o as UploadForbidden, p as storedFactsKeyValueStore, r as variantsKeyValueStore, s as UploadPolicy, v as uploadsKeyValueStore, w as Answer, x as Admission, y as FactsUnavailable } from "../stores-CxraN3kt.mjs";
5
- import { a as variantsNone, i as limitTransforms, n as Transformer, r as Variants, t as Originals } from "../services-7B4hsQM7.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
- // 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
- // src/server/handlers.ts
25
- /** The Cloudflare Images binding reads at most 20 MB; a store's own limit may be lower. */
26
- const DEFAULT_MAX_BYTES = 20971520;
27
- const defaultClientOf = (request) => request.headers["cf-connecting-ip"] ?? Option.getOrElse(request.remoteAddress, () => "unknown");
28
- const optionsOf = (answer) => ({
29
- status: statusOf(answer),
30
- headers: headersFor(answer)
31
- });
32
- const served = (etag, from, encoded) => HttpServerResponse.uint8Array(encoded.bytes, {
33
- ...optionsOf(Answer.cases.Variant.make({
34
- etag,
35
- from
36
- })),
37
- contentType: encoded.contentType
38
- });
39
- const notModified = (etag) => HttpServerResponse.empty(optionsOf(Answer.cases.NotModified.make({ etag })));
40
- const refused = (answer) => HttpServerResponse.jsonUnsafe({ error: answer._tag }, optionsOf(answer));
41
- /**
42
- * The handlers of `MediaApi`'s one route. The path is decoded against the
43
- * space; a variant kept is served as kept, and one the request already holds
44
- * (`If-None-Match`) is a 304 before the store is read; otherwise the original
45
- * is read, transformed, kept and served. Every answer, a refusal included,
46
- * goes through `headersFor`, and a failure is never the original in the
47
- * variant's place.
48
- */
49
- const handlers = (options = {}) => {
50
- const { maxBytes: requestedMaxBytes = DEFAULT_MAX_BYTES, coalesce = false, clientOf = defaultClientOf } = options;
51
- const space = options.provider?.space ?? standard;
52
- const maxBytes = nonNegativeInteger("maxBytes", requestedMaxBytes);
53
- const decodeHash = Schema.decodeUnknownOption(ContentHash);
54
- const decodeVariant = Schema.decodeUnknownOption(space.schema);
55
- const isSpelling = Schema.is(Spelling);
56
- const spell = Schema.encodeSync(space.schema);
57
- return HttpApiBuilder.group(MediaApi, "images", (group) => Effect.gen(function* () {
58
- const originals = yield* Originals;
59
- const transformer = yield* Transformer;
60
- const variants = yield* Variants;
61
- const admit = Option.match(yield* Effect.serviceOption(Admission), {
62
- onNone: () => (_client) => Effect.void,
63
- onSome: (admission) => admission.admit
64
- });
65
- const make = Effect.fn("Media.make")(function* (hash, variant) {
66
- const original = yield* originals.get(hash);
67
- if (original.size > maxBytes) return yield* new OriginalTooLarge({
68
- size: original.size,
69
- limit: maxBytes,
70
- unit: "bytes"
71
- });
72
- return yield* transformer.transform(original, variant);
73
- });
74
- const makeAndKeep = (key, hash, variant) => make(hash, variant).pipe(Effect.tap((made) => variants.put(key, made)));
75
- const shared = yield* Cache.make({
76
- capacity: 1e4,
77
- timeToLive: 0,
78
- lookup: (key) => {
79
- const at = key.indexOf("/");
80
- const variant = Schema.decodeUnknownSync(space.schema)(key.slice(at + 1));
81
- return makeAndKeep(key, key.slice(0, at), variant);
82
- }
83
- });
84
- const serve = Effect.fn("Media.serve")(function* (hash, variant, ifNoneMatch, client) {
85
- const key = `${hash}/${spell(variant)}`;
86
- const etag = `"${key}"`;
87
- if (matches(ifNoneMatch, etag)) return notModified(etag);
88
- return yield* Option.match(yield* variants.get(key), {
89
- onSome: ({ encoded, from }) => Effect.succeed(served(etag, from, encoded)),
90
- onNone: () => admit(client).pipe(Effect.andThen(coalesce ? Cache.get(shared, key) : makeAndKeep(key, hash, variant)), Effect.map((made) => served(etag, "made", made)), Effect.catchTags({
91
- OriginalNotFound: () => Effect.succeed(refused(Answer.cases.NotFound.make({}))),
92
- OriginalTooLarge: () => Effect.succeed(refused(Answer.cases.TooLarge.make({}))),
93
- TransformFailed: () => Effect.succeed(refused(Answer.cases.Failed.make({}))),
94
- QuotaExhausted: () => Effect.succeed(refused(Answer.cases.Exhausted.make({}))),
95
- RateLimited: ({ retryAfterSeconds }) => Effect.succeed(refused(Answer.cases.RateLimited.make({ retryAfterSeconds })))
96
- }))
97
- });
98
- });
99
- /**
100
- * A spelling of the grammar this space does not read. An earlier revision of a variant
101
- * it makes is served while kept and else sent to its current URL; anything else (a later
102
- * revision, a width another release offers) is `Unoffered`, kept briefly.
103
- */
104
- const elsewhere = (hash, spelling, ifNoneMatch) => {
105
- const current = respell(spelling, space.revision);
106
- if (revisionOf(spelling) >= space.revision || Option.isNone(decodeVariant(current))) return Effect.succeed(refused(Answer.cases.Unoffered.make({})));
107
- const key = `${hash}/${spelling}`;
108
- const etag = `"${key}"`;
109
- if (matches(ifNoneMatch, etag)) return Effect.succeed(notModified(etag));
110
- return Effect.map(variants.get(key), (kept) => Option.match(kept, {
111
- onSome: ({ encoded, from }) => served(etag, from, encoded),
112
- onNone: () => refused(Answer.cases.Moved.make({ location: PATH.replace(":hash", hash).replace(":variant", current) }))
113
- }));
114
- };
115
- return group.handle("variant", ({ params, request }) => Option.match(Option.all([decodeHash(params.hash), decodeVariant(params.variant)]), {
116
- onNone: () => Option.match(decodeHash(params.hash), {
117
- onNone: () => Effect.succeed(refused(Answer.cases.Malformed.make({}))),
118
- onSome: (hash) => isSpelling(params.variant) ? elsewhere(hash, params.variant, request.headers["if-none-match"]) : Effect.succeed(refused(Answer.cases.Malformed.make({})))
119
- }),
120
- onSome: ([hash, variant]) => serve(hash, variant, request.headers["if-none-match"], clientOf(request))
121
- }));
122
- }));
123
- };
124
- /**
125
- * The media server as an Effect HTTP application: its route registered with
126
- * the `HttpRouter`, needing `Originals`, `Transformer` and `Variants`.
127
- */
128
- const layer = (options = {}) => HttpApiBuilder.layer(MediaApi).pipe(Layer.provide(handlers({
129
- coalesce: true,
130
- ...options
131
- })));
132
- /**
133
- * A Worker's fetch handler over `app`, built from each environment's bindings
134
- * once and kept, since a Worker hands every request the same bindings. A
135
- * layer that fails to build answers a 500.
136
- */
137
- const fetchOf = (app) => {
138
- const built = /* @__PURE__ */ new WeakMap();
139
- return (request, env) => {
140
- const known = built.get(env);
141
- if (known !== void 0) return known(request);
142
- const { handler } = HttpRouter.toWebHandler(app(env).pipe(Layer.provide(HttpServer.layerServices)), { disableLogger: true });
143
- const answer = (incoming) => handler(incoming);
144
- built.set(env, answer);
145
- return answer(request);
146
- };
147
- };
148
- // src/server/fetch.ts
149
- const IMAGES = PATH.slice(0, PATH.indexOf(":"));
150
- const UPLOADS = "/_media/";
151
- /**
152
- * The media server as a Worker's fetch handler. It owns `/_image/` and
153
- * `/_media/`: a route of either it was not given, another method (a
154
- * preflight, which the upload route never answers), or another path under
155
- * them is a 404, and everything else goes to `otherwise`. The services are
156
- * built from each environment's bindings once and kept; a layer that fails
157
- * to build answers a 500.
158
- */
159
- const serveFetch = (options) => {
160
- const { images, uploads, otherwise } = options;
161
- if (images === void 0 && uploads === void 0) throw new Error("serveFetch: give it `images`, `uploads`, or both");
162
- const media = fetchOf((env) => Layer.mergeAll(images === void 0 ? Layer.empty : layer({
163
- ...images,
164
- coalesce: false
165
- }).pipe(Layer.provide(images.layer(env))), uploads === void 0 ? Layer.empty : uploadLayer(uploads).pipe(Layer.provide(uploads.layer(env)))));
166
- return (request, env) => {
167
- const { pathname } = new URL(request.url);
168
- if (pathname.startsWith(IMAGES) || pathname.startsWith(UPLOADS)) return media(request, env);
169
- return otherwise === void 0 ? Promise.resolve(new Response(null, { status: 404 })) : otherwise(request, env);
170
- };
171
- };
172
- // src/server/materialize.ts
173
- const VARIANT_PATH = /\/_image\/[0-9a-f]{64}\/[^\s"',)<>]+/g;
174
- const DEFAULT_MAX_FILES = 2e4;
175
- const PATTERN = "/_image/*";
176
- /**
177
- * The `_headers` rule (Cloudflare Pages, Netlify) a host needs for variants
178
- * written out as files: what the server itself sends a variant, from the same
179
- * `headersFor`, less the `ETag` and `Server-Timing` of one answer.
180
- */
181
- const headersRule = () => {
182
- const headers = headersFor(Answer.cases.Variant.make({
183
- etag: "",
184
- from: "made"
185
- }));
186
- const lines = Object.entries(headers).filter(([name]) => name !== "etag" && name !== "server-timing").map(([name, value]) => ` ${name}: ${value}`);
187
- return [PATTERN, ...lines].join("\n") + "\n";
188
- };
189
- /**
190
- * Every hosted variant the built pages name, made through `fetch` (the media
191
- * server's own handler, `serveFetch`) and returned as files at their own
192
- * paths, for `foldkit-ssr`'s `emit`. `Provider.hosted` then works on a static
193
- * host with no server at all. With a `Variants` store on disk, a second build
194
- * writes without encoding.
195
- *
196
- * It fails the build, naming every one, when a variant cannot be made (a
197
- * page would show a broken image), when there would be more than `maxFiles`,
198
- * and, given the site's `_headers` text, when that file has no rule for the
199
- * variants, which a static host would otherwise serve uncached.
200
- */
201
- const materialize = async (options) => {
202
- const paths = [...new Set(options.pages.flatMap((page) => page.html.match(VARIANT_PATH) ?? []))].sort();
203
- const maxFiles = nonNegativeInteger("maxFiles", options.maxFiles ?? DEFAULT_MAX_FILES);
204
- const concurrency = positiveInteger("foldkit-media: materialize concurrency", options.concurrency ?? 4);
205
- if (paths.length > maxFiles) throw new Error(`foldkit-media: the pages name ${paths.length} variants, more than maxFiles (${maxFiles})`);
206
- if (paths.length > 0 && options.headersFile !== void 0 && !options.headersFile.split(/\r?\n/).some((line) => line.trim() === PATTERN)) throw new Error(`foldkit-media: _headers has no ${PATTERN} rule, so the variants would be served uncached: add Media.headersRule()`);
207
- const made = [];
208
- const failed = [];
209
- const queue = [...paths];
210
- const worker = async () => {
211
- for (let path = queue.shift(); path !== void 0; path = queue.shift()) try {
212
- const response = await options.fetch(new Request(`http://materialize.invalid${path}`));
213
- if (response.status !== 200) {
214
- failed.push(`${path}: ${response.status}`);
215
- continue;
216
- }
217
- made.push({
218
- file: path.slice(1),
219
- contents: new Uint8Array(await response.arrayBuffer())
220
- });
221
- } catch (cause) {
222
- failed.push(`${path}: ${cause instanceof Error ? cause.message : String(cause)}`);
223
- }
224
- };
225
- await Promise.all(Array.from({ length: Math.min(concurrency, paths.length) }, worker));
226
- if (failed.length > 0) throw new Error(`foldkit-media: ${failed.length} variants could not be made:\n${failed.sort().join("\n")}`);
227
- return made.sort((a, b) => a.file < b.file ? -1 : a.file > b.file ? 1 : 0);
228
- };
229
- export { Admission, Answer, FactsUnavailable, MediaApi, OriginalNotFound, OriginalTooLarge, Originals, QuotaExhausted, RateLimited, StoredFacts, TransformFailed, Transformer, UploadApi, UploadForbidden, UploadPolicy, UploadUnauthenticated, Uploads, Variants, admissionRateLimiter, factsOf, handlers, headersFor, headersRule, layer, limitTransforms, materialize, originalsKeyValueStore, serveFetch, statusOf, storedFactsKeyValueStore, uploadHandlers, uploadLayer, uploadPolicyAny, uploadPolicyBearer, uploadsKeyValueStore, variantsKeyValueStore, variantsNone };
230
-
231
- //# sourceMappingURL=index.mjs.map
@@ -1 +0,0 @@
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 // No more workers than paths, which also keeps an absurd concurrency out of\n // an array length.\n await Promise.all(Array.from({ length: Math.min(concurrency, paths.length) }, 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,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AAO,EAAE,OAAO,EAAE,OAAO,KAAK,EAAE,OAAO,EAAE,OAAO,IAAI,CAAE;AAC7E"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"services-7B4hsQM7.mjs","names":[],"sources":["../src/server/services.ts"],"sourcesContent":["import { Context, Effect, Layer, Option, Semaphore } from 'effect'\nimport { positiveInteger } from '../limits.js'\nimport type { Variant } from '../variant.js'\nimport type {\n OriginalNotFound,\n OriginalTooLarge,\n QuotaExhausted,\n TransformFailed,\n} from './errors.js'\n\n/** An original's bytes, as the store hands them over, and how many there are. */\nexport interface Original {\n readonly body: ReadableStream<Uint8Array>\n readonly size: number\n}\n\n/** A variant made: its bytes and their media type. */\nexport interface Encoded {\n readonly bytes: Uint8Array<ArrayBuffer>\n readonly contentType: string\n}\n\n/** A variant found kept, and which layer had it. */\nexport interface Kept {\n readonly encoded: Encoded\n readonly from: 'edge' | 'store'\n}\n\n/** Where originals live, by their content hash. Authoritative: the server never writes it. */\nexport class Originals extends Context.Service<\n Originals,\n { readonly get: (hash: string) => Effect.Effect<Original, OriginalNotFound> }\n>()('foldkit-media/Originals') {}\n\n/**\n * Resizes and encodes an original into a variant, never larger than the\n * original (a width above it answers with the original's width). An original\n * too large to decode is `OriginalTooLarge`, a 413, as one too large to read.\n */\nexport class Transformer extends Context.Service<\n Transformer,\n {\n readonly transform: (\n original: Original,\n variant: Variant,\n ) => Effect.Effect<Encoded, TransformFailed | QuotaExhausted | OriginalTooLarge>\n }\n>()('foldkit-media/Transformer') {}\n\n/**\n * Variants already made, by the encoded request. A cache: losing it costs\n * time, and on a host that bills transformations, money; never data.\n */\nexport class Variants extends Context.Service<\n Variants,\n {\n readonly get: (key: string) => Effect.Effect<Option.Option<Kept>>\n readonly put: (key: string, encoded: Encoded) => Effect.Effect<void>\n }\n>()('foldkit-media/Variants') {}\n\n/** Keeps nothing: every request transforms. For a host with a cache of its own in front. */\nexport const variantsNone: Layer.Layer<Variants> = Layer.succeed(Variants, {\n get: () => Effect.succeed(Option.none()),\n put: () => Effect.void,\n})\n\n/**\n * A `Transformer` that runs at most `concurrency` transforms at once, the\n * rest waiting their turn: encoding is CPU work, and a burst of misses should\n * queue, not starve every other request. For a transformer that encodes in\n * this process (sharp, WebAssembly); a host's binding does the work elsewhere.\n */\nexport const limitTransforms = (concurrency: number) => {\n const permitsCount = positiveInteger('limitTransforms: concurrency', concurrency)\n return <E, R>(transformer: Layer.Layer<Transformer, E, R>): Layer.Layer<Transformer, E, R> =>\n Layer.effect(\n Transformer,\n Effect.gen(function* () {\n const inner = yield* Transformer\n const permits = yield* Semaphore.make(permitsCount)\n return {\n transform: (original: Original, variant: Variant) =>\n Semaphore.withPermit(permits)(inner.transform(original, variant)),\n }\n }),\n ).pipe(Layer.provide(transformer))\n}\n"],"mappings":";;;;AA6BA,IAAa,YAAb,cAA+B,QAAQ,QAGrC,CAAC,CAAC,yBAAyB,CAAC,CAAC,CAAC;;;;;;AAOhC,IAAa,cAAb,cAAiC,QAAQ,QAQvC,CAAC,CAAC,2BAA2B,CAAC,CAAC,CAAC;;;;;AAMlC,IAAa,WAAb,cAA8B,QAAQ,QAMpC,CAAC,CAAC,wBAAwB,CAAC,CAAC,CAAC;;AAG/B,MAAa,eAAsC,MAAM,QAAQ,UAAU;CACzE,WAAW,OAAO,QAAQ,OAAO,KAAK,CAAC;CACvC,WAAW,OAAO;AACpB,CAAC;;;;;;;AAQD,MAAa,mBAAmB,gBAAwB;CACtD,MAAM,eAAe,gBAAgB,gCAAgC,WAAW;CAChF,QAAc,gBACZ,MAAM,OACJ,aACA,OAAO,IAAI,aAAa;EACtB,MAAM,QAAQ,OAAO;EACrB,MAAM,UAAU,OAAO,UAAU,KAAK,YAAY;EAClD,OAAO,EACL,YAAY,UAAoB,YAC9B,UAAU,WAAW,OAAO,CAAC,CAAC,MAAM,UAAU,UAAU,OAAO,CAAC,EACpE;CACF,CAAC,CACH,CAAC,CAAC,KAAK,MAAM,QAAQ,WAAW,CAAC;AACrC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"services-BZoK2VOY.d.mts","names":[],"sources":["../src/server/services.ts"],"mappings":";;;;UAWiB;WACN,MAAM,eAAe;WACrB;;;UAIM;WACN,OAAO,WAAW;WAClB;;;UAIM;WACN,SAAS;WACT;;;WAMO,MAAC,iBAAiB,OAAO,OAAO,UAAU;;;cAF/C,kBAAkB;;WAaP,YAClB,UAAU,UACV,SAAS,YACN,OAAO,OAAO,SAAS,kBAAkB,iBAAiB;;;;;;;cANtD,oBAAoB;;WAiBf,MAAC,gBAAgB,OAAO,OAAO,OAAO,OAAO;WAC7C,MAAC,aAAa,SAAS,YAAY,OAAO;;;;;;cAJ/C,iBAAiB;;cASjB,cAAc,MAAM,MAAM;;;;;;;cAW1B,kBAAe,yBAElB,GAAG,GAAC,aAAe,MAAM,MAAM,aAAa,GAAG,OAAK,MAAM,MAAM,aAAa,GAAG"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/sharp/index.ts"],"mappings":";;;qBA8Ca,mBAAgB;;WAGhB;;WAEA;MAEV,MAAM,MAAM;;;;;;;qBAuCF,iBAAc;WACL;MACnB,MAAM,MAAM"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../src/sharp/index.ts"],"sourcesContent":["/**\n * The media server's `Transformer` on a Node server, through sharp. At most\n * `concurrency` transforms run at once (`limitTransforms`), and an original\n * is measured from its header before it is decoded, so a small file that\n * inflates to a huge picture is a 413, never an exhausted heap.\n */\nimport { availableParallelism } from 'node:os'\nimport { Effect, Layer, Option } from 'effect'\nimport sharp from 'sharp'\nimport { OriginalTooLarge, TransformFailed } from '../server/errors.js'\nimport { Inspector } from '../describe.js'\nimport { nonNegativeInteger } from '../limits.js'\nimport { Transformer, limitTransforms } from '../server/services.js'\n\n// About 50 megapixels: a 9000×5500 photograph decodes; a decompression bomb does not.\nconst DEFAULT_MAX_PIXELS = 50_000_000\n\n/** What a failed sharp call ends in: logged under `label`, and answered as a 502. */\nconst failedAs = (label: string) => (cause: unknown) =>\n Effect.logWarning(`${label} failed`, cause).pipe(\n Effect.andThen(Effect.fail(new TransformFailed({}))),\n )\n\n/**\n * An original's size from its header alone, refused above `maxPixels` before\n * anything is decoded: a small file that inflates to a huge picture is a 413,\n * never an exhausted heap. The size is as shown, after its EXIF orientation:\n * a phone's portrait photograph is stored landscape and turned when drawn.\n */\nconst measure = (\n input: Uint8Array,\n maxPixels: number,\n failed: (cause: unknown) => Effect.Effect<never, TransformFailed>,\n) =>\n Effect.gen(function* () {\n const { autoOrient } = yield* Effect.tryPromise({\n try: () => sharp(input).metadata(),\n catch: cause => cause,\n }).pipe(Effect.catch(failed))\n const { width, height } = autoOrient\n if (width * height > maxPixels) {\n return yield* new OriginalTooLarge({ size: width * height, limit: maxPixels, unit: 'pixels' })\n }\n return { width, height }\n })\n\nexport const transformerSharp = (\n options: {\n /** Transforms run at once; by default the machine's cores. */\n readonly concurrency?: number\n /** The largest original decoded, in pixels. */\n readonly maxPixels?: number\n } = {},\n): Layer.Layer<Transformer> => {\n const maxPixels = nonNegativeInteger('maxPixels', options.maxPixels ?? DEFAULT_MAX_PIXELS)\n const failed = failedAs('Media.transform')\n return Layer.succeed(Transformer, {\n transform: (original, variant) =>\n Effect.gen(function* () {\n const input = yield* Effect.promise(\n async () => new Uint8Array(await new Response(original.body).arrayBuffer()),\n )\n yield* measure(input, maxPixels, failed)\n const bytes = yield* Effect.tryPromise({\n try: () =>\n // Turned as shown, since a variant carries no orientation of its own.\n sharp(input, { limitInputPixels: maxPixels, failOn: 'error', autoOrient: true })\n .resize({ width: variant.width, withoutEnlargement: true })\n .toFormat(\n variant.format,\n Option.match(variant.quality, {\n onNone: () => ({}),\n onSome: quality => ({ quality }),\n }),\n )\n .toBuffer(),\n catch: cause => cause,\n }).pipe(Effect.catch(failed))\n return { bytes: new Uint8Array(bytes), contentType: `image/${variant.format}` }\n }).pipe(Effect.withSpan('Media.transform')),\n }).pipe(limitTransforms(options.concurrency ?? availableParallelism()))\n}\n\n// A ThumbHash is made from at most 100 pixels a side.\nconst THUMBNAIL_SIDE = 100\n\n/**\n * The `Inspector` on a Node server: an original's size and alpha from sharp,\n * and a thumbnail for its ThumbHash. Alpha is whether any pixel is not opaque\n * (`stats().isOpaque`), not whether the format has an alpha channel, so an\n * opaque PNG still gets a placeholder. An original above `maxPixels` is a 413.\n */\nexport const inspectorSharp = (\n options: { readonly maxPixels?: number } = {},\n): Layer.Layer<Inspector> => {\n const maxPixels = nonNegativeInteger('maxPixels', options.maxPixels ?? DEFAULT_MAX_PIXELS)\n const failed = failedAs('Media.inspect')\n return Layer.succeed(Inspector, {\n inspect: bytes =>\n Effect.gen(function* () {\n const { width, height } = yield* measure(bytes, maxPixels, failed)\n const { stats, thumbnail } = yield* Effect.tryPromise({\n try: async () => ({\n stats: await sharp(bytes, { limitInputPixels: maxPixels }).stats(),\n thumbnail: await sharp(bytes, { limitInputPixels: maxPixels, autoOrient: true })\n .resize(THUMBNAIL_SIDE, THUMBNAIL_SIDE, { fit: 'inside' })\n .ensureAlpha()\n .raw()\n .toBuffer({ resolveWithObject: true }),\n }),\n catch: cause => cause,\n }).pipe(Effect.catch(failed))\n return {\n width,\n height,\n alpha: !stats.isOpaque,\n thumbnail: Option.some({\n width: thumbnail.info.width,\n height: thumbnail.info.height,\n rgba: new Uint8Array(thumbnail.data),\n }),\n }\n }).pipe(Effect.withSpan('Media.inspect')),\n })\n}\n"],"mappings":";;;;;;;;;;;;;;AAeA,MAAM,qBAAqB;;AAG3B,MAAM,YAAY,WAAmB,UACnC,OAAO,WAAW,GAAG,MAAM,UAAU,KAAK,CAAC,CAAC,KAC1C,OAAO,QAAQ,OAAO,KAAK,IAAI,gBAAgB,CAAC,CAAC,CAAC,CAAC,CACrD;;;;;;;AAQF,MAAM,WACJ,OACA,WACA,WAEA,OAAO,IAAI,aAAa;CACtB,MAAM,EAAE,eAAe,OAAO,OAAO,WAAW;EAC9C,WAAW,MAAM,KAAK,CAAC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