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":"describe-C6sWA_8p.mjs","names":["Widths.standard"],"sources":["../src/variant.ts","../src/asset.ts","../src/describe.ts"],"sourcesContent":["import { Option, Schema, SchemaGetter } from 'effect'\nimport { Format } from './format.js'\nimport * as Widths from './widths.js'\n\n/**\n * Where a hosted variant lives: the original's content hash, then the variant.\n * The server routes this path and `Provider.hosted` fills it in, so the two\n * read one string. It ends in the format's extension, so a variant written\n * out as a file is served with its type by any static host.\n */\nexport const PATH = '/_image/:hash/:variant'\n\n/** An original's SHA-256, in lowercase hex: its name in the store. */\nexport const ContentHash = Schema.String.check(Schema.isPattern(/^[0-9a-f]{64}$/))\n\n/** A quality from 1 to 100. */\nexport const Quality = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 100 }))\n\n// No leading zero anywhere: one request has one spelling, so one cache key. The output's\n// revision is written only above 0, so every URL written before revisions keeps its spelling.\nconst SPELLING = /^w([1-9]\\d{0,4})(?:q([1-9]\\d?|100))?(?:\\.r([1-9]\\d{0,3}))?\\.(avif|webp|jpeg|png)$/\n\n/**\n * The grammar every release reads, whatever its space: a spelling it matches\n * may be one another release offers, so refusing it says nothing for good.\n */\nexport const Spelling = Schema.String.check(Schema.isPattern(SPELLING))\n\n/** The output revision a spelling names: `w640.r2.avif` is 2, and one naming none is 0. */\nexport const revisionOf = (spelling: string): number => Number(SPELLING.exec(spelling)?.[3] ?? 0)\n\n/** `spelling` at `revision`: the same variant, as that revision writes it. */\nexport const respell = (spelling: string, revision: number): string =>\n spelling.replace(/(?:\\.r\\d+)?(\\.[a-z]+)$/, revision === 0 ? '$1' : `.r${revision}$1`)\n\n/** A variant as its server reads it. */\nexport interface Variant {\n readonly width: number\n readonly format: Format\n /** None: the encoder's own default. */\n readonly quality: Option.Option<number>\n}\n\n/**\n * Every variant a server will make: the widths, the formats and the qualities\n * it accepts, and the Schema that reads a variant's spelling against them. A\n * request outside it is refused before any work, so an original has at most\n * `size` variants, whoever asks.\n */\nexport interface Space {\n readonly widths: Widths.Widths\n readonly formats: ReadonlyArray<Format>\n /** Qualities a URL may name; empty, no URL names one. */\n readonly qualities: ReadonlyArray<number>\n /**\n * The generation of what its variants are: raised when the output changes (the encoder's\n * settings, its resizing), so a changed variant has a new URL rather than new bytes behind\n * an old one. 0 writes no revision.\n */\n readonly revision: number\n /** `w640.avif`, `w640q75.webp` or `w640.r1.avif`, decoded to a `Variant` of this space's revision. */\n readonly schema: Schema.Codec<Variant, string>\n /** How many variants one original can have. */\n readonly size: number\n}\n\nconst distinct = <A>(label: string, values: ReadonlyArray<A>) => {\n if (new Set(values).size !== values.length)\n throw new Error(`Variant.space: a ${label} appears twice`)\n}\n\n/**\n * A space from its ladders. Refuses no formats, a repeated format or\n * quality, and a quality outside 1 to 100.\n */\nexport const space = (\n options: {\n readonly widths?: Widths.Widths\n readonly formats?: ReadonlyArray<Format>\n readonly qualities?: ReadonlyArray<number>\n readonly revision?: number\n } = {},\n): Space => {\n const {\n widths = Widths.standard,\n formats = ['avif', 'webp'],\n qualities = [],\n revision = 0,\n } = options\n if (!(Number.isInteger(revision) && revision >= 0 && revision <= 9999)) {\n throw new Error(`Variant.space: revision ${revision} is not an integer from 0 to 9999`)\n }\n const unspellableWidth = widths.values.find(width => width > 99_999)\n if (unspellableWidth !== undefined) {\n throw new Error(`Variant.space: width ${unspellableWidth} cannot be spelled in a variant URL`)\n }\n if (formats.length === 0) throw new Error('Variant.space: a space needs at least one format')\n distinct('format', formats)\n distinct('quality', qualities)\n for (const quality of qualities) {\n if (!Schema.is(Quality)(quality)) {\n throw new Error(`Variant.space: quality ${quality} is not an integer from 1 to 100`)\n }\n }\n const schema = Spelling.check(\n Schema.makeFilter(spelling => revisionOf(spelling) === revision || `not revision ${revision}`),\n ).pipe(\n Schema.decodeTo(\n Schema.Struct({\n width: widths.Schema,\n format: Schema.Literals(formats),\n quality: Schema.Option(Schema.Literals(qualities)),\n }),\n {\n decode: SchemaGetter.transform(spelling => {\n const [, width, quality, , format] = SPELLING.exec(spelling)!\n return {\n width: Number(width),\n // The spelling's pattern admits only formats; the struct checks this space's.\n format: format as Format,\n quality: Option.map(Option.fromNullishOr(quality), Number),\n }\n }),\n encode: SchemaGetter.transform(\n ({ width, format, quality }) =>\n `w${width}${Option.match(quality, { onNone: () => '', onSome: value => `q${value}` })}${revision === 0 ? '' : `.r${revision}`}.${format}`,\n ),\n },\n ),\n )\n return {\n widths,\n formats,\n qualities,\n revision,\n schema,\n size: widths.values.length * formats.length * (1 + qualities.length),\n }\n}\n\n/** The standard ladder, AVIF and WebP, and no quality in any URL: 16 variants an original. */\nexport const standard: Space = space()\n","import { Option, Schema } from 'effect'\nimport { ContentHash } from './variant.js'\n\n// A placeholder's color lands in a style the page writes, so it is a color\n// and nothing else: no `;`, no `url(`, no second declaration.\nconst CSS_COLOR =\n /^(?:#[0-9a-f]{3,8}|(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch)\\([0-9a-z%.,\\s/+-]*\\))$/i\n\nconst coefficientCount = (x: number, y: number): number => {\n let count = 0\n for (let cy = 0; cy < y; cy++)\n for (let cx = cy === 0 ? 1 : 0; cx * y < x * (y - cy); cx++) count++\n return count\n}\n\n// A ThumbHash's header decides exactly how many coefficient bytes follow it.\n// Checking that layout here keeps malformed stored data out of the renderer.\nconst isThumbHash = (encoded: string): boolean => {\n try {\n const bytes = Uint8Array.from(atob(encoded), character => character.charCodeAt(0))\n if (bytes.length < 5) return false\n const hasAlpha = (bytes[2]! & 0x80) !== 0\n const landscape = (bytes[4]! & 0x80) !== 0\n const shorter = bytes[3]! & 7\n if (shorter === 0) return false\n const long = hasAlpha ? 5 : 7\n const lx = landscape ? long : shorter\n const ly = landscape ? shorter : long\n const coefficients =\n coefficientCount(lx, ly) +\n coefficientCount(3, 3) * 2 +\n (hasAlpha ? coefficientCount(5, 5) : 0)\n return bytes.length === (hasAlpha ? 6 : 5) + Math.ceil(coefficients / 2)\n } catch {\n return false\n }\n}\n\n/** What stands in an image's place until it loads. */\nexport const Placeholder = Schema.TaggedUnion({\n /** A flat color, such as one taken from a logo. */\n Color: { value: Schema.String.check(Schema.isPattern(CSS_COLOR)) },\n /** A ThumbHash: a blurred likeness, alpha and aspect ratio included. */\n ThumbHash: {\n hash: Schema.String.check(\n Schema.makeFilter(encoded => isThumbHash(encoded) || 'not a valid ThumbHash'),\n ),\n },\n /** The provider's smallest width of the image itself, scaled up. */\n LowRes: {},\n})\nexport type Placeholder = typeof Placeholder.Type\n\nconst Pixels = Schema.Int.check(Schema.isGreaterThan(0))\n\nconst Share = Schema.Finite.check(Schema.isBetween({ minimum: 0, maximum: 1 }))\n\n/** Where an image's subject is, from its top left (0, 0) to its bottom right (1, 1). */\nexport const Focus = Schema.Struct({ x: Share, y: Share })\nexport type Focus = typeof Focus.Type\n\n/**\n * The facts of one original image, derived from it once and stored beside it.\n * `key` is where the original lives, as its provider reads it. `hash` is the\n * original's content hash, absent for an image never read; `alpha` says\n * whether it has transparent pixels. `focus`, the one fact an editor sets\n * rather than one derived, is where a crop keeps the subject; a stored asset\n * without it reads as none.\n */\nexport const ImageAsset = Schema.Struct({\n key: Schema.String.check(Schema.isNonEmpty()),\n width: Pixels,\n height: Pixels,\n alpha: Schema.Boolean,\n hash: Schema.OptionFromNullOr(ContentHash),\n placeholder: Schema.OptionFromNullOr(Placeholder),\n focus: Schema.OptionFromOptionalNullOr(Focus),\n})\nexport type ImageAsset = typeof ImageAsset.Type\n\n/**\n * Facts that name the original by its content hash: what a build or an upload\n * answers, and what `Provider.hosted` needs to write a URL.\n */\nexport type HashedAsset = ImageAsset & { readonly hash: Option.Some<string> }\n\nexport const isHashed = (asset: ImageAsset): asset is HashedAsset => Option.isSome(asset.hash)\n\n/** `ImageAsset`, refusing facts with no content hash. */\nexport const HashedAsset = ImageAsset.pipe(Schema.refine(isHashed))\n","import { Context, Effect, Option } from 'effect'\nimport { rgbaToThumbHash } from 'thumbhash'\nimport { Placeholder, type ImageAsset } from './asset.js'\nimport type { OriginalTooLarge, TransformFailed } from './server/errors.js'\n\n/** A picture at most 100 pixels a side, as raw RGBA: what a ThumbHash is made from. */\nexport interface Thumbnail {\n readonly width: number\n readonly height: number\n readonly rgba: Uint8Array\n}\n\n/** What an inspector reads of an original. */\nexport interface Inspected {\n readonly width: number\n readonly height: number\n /** Whether it may have transparent pixels; an inspector that cannot tell says yes. */\n readonly alpha: boolean\n /** None where the inspector cannot make one (the Images binding offline makes no raw pixels). */\n readonly thumbnail: Option.Option<Thumbnail>\n}\n\n/** Reads an original's facts: its size, its alpha, and a thumbnail. */\nexport class Inspector extends Context.Service<\n Inspector,\n {\n readonly inspect: (\n bytes: Uint8Array<ArrayBuffer>,\n ) => Effect.Effect<Inspected, TransformFailed | OriginalTooLarge>\n }\n>()('foldkit-media/Inspector') {}\n\nconst hex = (buffer: ArrayBuffer) =>\n Array.from(new Uint8Array(buffer), byte => byte.toString(16).padStart(2, '0')).join('')\n\nconst base64 = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes))\n\n/**\n * An original's facts, as an `ImageAsset` under `key`: its size and alpha\n * from the `Inspector`, its SHA-256, and a ThumbHash placeholder where the\n * inspector made a thumbnail. Where an original enters (an upload, a build, a\n * page's content naming a URL), so its facts are derived once and stored.\n */\nexport const describe = (\n key: string,\n bytes: Uint8Array<ArrayBuffer>,\n): Effect.Effect<ImageAsset, TransformFailed | OriginalTooLarge, Inspector> =>\n Effect.gen(function* () {\n const inspected = yield* Inspector.use(inspector => inspector.inspect(bytes))\n const digest = yield* Effect.promise(() => crypto.subtle.digest('SHA-256', bytes))\n return {\n key,\n width: inspected.width,\n height: inspected.height,\n alpha: inspected.alpha,\n hash: Option.some(hex(digest)),\n placeholder: Option.map(inspected.thumbnail, ({ width, height, rgba }) =>\n Placeholder.cases.ThumbHash.make({ hash: base64(rgbaToThumbHash(width, height, rgba)) }),\n ),\n focus: Option.none(),\n }\n })\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAUA,MAAa,OAAO;;AAGpB,MAAa,cAAc,OAAO,OAAO,MAAM,OAAO,UAAU,gBAAgB,CAAC;;AAGjF,MAAa,UAAU,OAAO,IAAI,MAAM,OAAO,UAAU;CAAE,SAAS;CAAG,SAAS;AAAI,CAAC,CAAC;AAItF,MAAM,WAAW;;;;;AAMjB,MAAa,WAAW,OAAO,OAAO,MAAM,OAAO,UAAU,QAAQ,CAAC;;AAGtE,MAAa,cAAc,aAA6B,OAAO,SAAS,KAAK,QAAQ,CAAC,GAAG,MAAM,CAAC;;AAGhG,MAAa,WAAW,UAAkB,aACxC,SAAS,QAAQ,0BAA0B,aAAa,IAAI,OAAO,KAAK,SAAS,GAAG;AAiCtF,MAAM,YAAe,OAAe,WAA6B;CAC/D,IAAI,IAAI,IAAI,MAAM,CAAC,CAAC,SAAS,OAAO,QAClC,MAAM,IAAI,MAAM,oBAAoB,MAAM,eAAe;AAC7D;;;;;AAMA,MAAa,SACX,UAKI,CAAC,MACK;CACV,MAAM,EACJ,SAASA,YACT,UAAU,CAAC,QAAQ,MAAM,GACzB,YAAY,CAAC,GACb,WAAW,MACT;CACJ,IAAI,EAAE,OAAO,UAAU,QAAQ,KAAK,YAAY,KAAK,YAAY,OAC/D,MAAM,IAAI,MAAM,2BAA2B,SAAS,kCAAkC;CAExF,MAAM,mBAAm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,OAAO,OAAO;CACd,MAAM,OAAO,iBAAiB,WAAW;CACzC,aAAa,OAAO,iBAAiB,WAAW;CAChD,OAAO,OAAO,yBAAyB,KAAK;AAC9C,CAAC;AASD,MAAa,YAAY,UAA4C,OAAO,OAAO,MAAM,IAAI;;AAG7F,MAAa,cAAc,WAAW,KAAK,OAAO,OAAO,QAAQ,CAAC;;;AClElE,IAAa,YAAb,cAA+B,QAAQ,QAOrC,CAAC,CAAC,yBAAyB,CAAC,CAAC,CAAC;AAEhC,MAAM,OAAO,WACX,MAAM,KAAK,IAAI,WAAW,MAAM,IAAG,SAAQ,KAAK,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE;AAExF,MAAM,UAAU,UAAsB,KAAK,OAAO,aAAa,GAAG,KAAK,CAAC;;;;;;;AAQxE,MAAa,YACX,KACA,UAEA,OAAO,IAAI,aAAa;CACtB,MAAM,YAAY,OAAO,UAAU,KAAI,cAAa,UAAU,QAAQ,KAAK,CAAC;CAC5E,MAAM,SAAS,OAAO,OAAO,cAAc,OAAO,OAAO,OAAO,WAAW,KAAK,CAAC;CACjF,OAAO;EACL;EACA,OAAO,UAAU;EACjB,QAAQ,UAAU;EAClB,OAAO,UAAU;EACjB,MAAM,OAAO,KAAK,IAAI,MAAM,CAAC;EAC7B,aAAa,OAAO,IAAI,UAAU,YAAY,EAAE,OAAO,QAAQ,WAC7D,YAAY,MAAM,UAAU,KAAK,EAAE,MAAM,OAAO,gBAAgB,OAAO,QAAQ,IAAI,CAAC,EAAE,CAAC,CACzF;EACA,OAAO,OAAO,KAAK;CACrB;AACF,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"errors-BhEgXJ4m.mjs","names":[],"sources":["../src/server/errors.ts"],"sourcesContent":["import { Schema } from 'effect'\n\n/** No original is stored under this hash. */\nexport class OriginalNotFound extends Schema.TaggedError<OriginalNotFound>()(\n 'OriginalNotFound',\n { hash: Schema.String },\n { httpApiStatus: 404 },\n) {}\n\n/** The original is larger than the server will read: in bytes, or in pixels once decoded. */\nexport class OriginalTooLarge extends Schema.TaggedError<OriginalTooLarge>()(\n 'OriginalTooLarge',\n { size: Schema.Number, limit: Schema.Number, unit: Schema.Literals(['bytes', 'pixels']) },\n { httpApiStatus: 413 },\n) {}\n\n/**\n * The transformer could not make the variant: the original is not an image it\n * reads, or it failed. Its reason stays in the server's log, not the response.\n */\nexport class TransformFailed extends Schema.TaggedError<TransformFailed>()(\n 'TransformFailed',\n {},\n { httpApiStatus: 502 },\n) {}\n\n/** The host's transformation allowance is spent; variants already made still serve. */\nexport class QuotaExhausted extends Schema.TaggedError<QuotaExhausted>()(\n 'QuotaExhausted',\n {},\n { httpApiStatus: 503 },\n) {}\n"],"mappings":";;;AAGA,IAAa,mBAAb,cAAsC,OAAO,YAA8B,CAAC,CAC1E,oBACA,EAAE,MAAM,OAAO,OAAO,GACtB,EAAE,eAAe,IAAI,CACvB,CAAC,CAAC,CAAC;;AAGH,IAAa,mBAAb,cAAsC,OAAO,YAA8B,CAAC,CAC1E,oBACA;CAAE,MAAM,OAAO;CAAQ,OAAO,OAAO;CAAQ,MAAM,OAAO,SAAS,CAAC,SAAS,QAAQ,CAAC;AAAE,GACxF,EAAE,eAAe,IAAI,CACvB,CAAC,CAAC,CAAC;;;;;AAMH,IAAa,kBAAb,cAAqC,OAAO,YAA6B,CAAC,CACxE,mBACA,CAAC,GACD,EAAE,eAAe,IAAI,CACvB,CAAC,CAAC,CAAC;;AAGH,IAAa,iBAAb,cAAoC,OAAO,YAA4B,CAAC,CACtE,kBACA,CAAC,GACD,EAAE,eAAe,IAAI,CACvB,CAAC,CAAC,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"format-BCRTFU9j.mjs","names":[],"sources":["../src/format.ts"],"sourcesContent":["import { Schema } from 'effect'\n\n/** An encoding a variant can be written in. */\nexport const Format = Schema.Literals(['avif', 'webp', 'jpeg', 'png'])\nexport type Format = typeof Format.Type\n\n/**\n * What a provider is asked for: a format, or `auto` for a provider that picks\n * the format itself from the request's `Accept`.\n */\nexport type Encoding = Format | 'auto'\n\nconst mimeTypes: Readonly<Record<Format, string>> = {\n avif: 'image/avif',\n webp: 'image/webp',\n jpeg: 'image/jpeg',\n png: 'image/png',\n}\n\n/** The media type a `source` element names. */\nexport const mimeType = (format: Format): string => mimeTypes[format]\n"],"mappings":";;;AAGA,MAAa,SAAS,OAAO,SAAS;CAAC;CAAQ;CAAQ;CAAQ;AAAK,CAAC;AASrE,MAAM,YAA8C;CAClD,MAAM;CACN,MAAM;CACN,MAAM;CACN,KAAK;AACP;;AAGA,MAAa,YAAY,WAA2B,UAAU"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"icon-0A2dBtqj.mjs","names":[],"sources":["../src/icon.ts"],"sourcesContent":["/**\n * An icon as data: what a build reads from an icon set or an SVG file, parsed\n * (`foldkit-media/icons`), not markup to set as HTML. A view draws it\n * (`draw`), and a style masks with it (`maskUrl`),\n * from the one value.\n */\n\n/** The elements an icon may hold: presentational SVG, nothing that runs, loads or holds text. */\nexport const TAGS = [\n 'g',\n 'path',\n 'circle',\n 'ellipse',\n 'rect',\n 'line',\n 'polyline',\n 'polygon',\n 'defs',\n 'linearGradient',\n 'radialGradient',\n 'stop',\n 'clipPath',\n 'mask',\n 'use',\n] as const\nexport type SvgTag = (typeof TAGS)[number]\n\n/** One element of an icon's drawing, and its children. */\nexport interface SvgNode {\n readonly tag: SvgTag\n readonly attributes: Readonly<Record<string, string>>\n readonly children: ReadonlyArray<SvgNode>\n}\n\n/** An icon: its `viewBox`, the attributes its root `svg` carries (its fill and stroke), and its drawing. */\nexport interface IconData {\n readonly viewBox: string\n readonly attributes: Readonly<Record<string, string>>\n readonly nodes: ReadonlyArray<SvgNode>\n}\n\nconst escapeAttribute = (value: string): string =>\n value.replace(/&/g, '&amp;').replace(/\"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;')\n\nconst attributesOf = (attributes: Readonly<Record<string, string>>): string =>\n Object.entries(attributes)\n .map(([name, value]) => ` ${name}=\"${escapeAttribute(value)}\"`)\n .join('')\n\nconst nodeMarkup = ({ tag, attributes, children }: SvgNode): string =>\n children.length === 0\n ? `<${tag}${attributesOf(attributes)}/>`\n : `<${tag}${attributesOf(attributes)}>${children.map(nodeMarkup).join('')}</${tag}>`\n\n/** The icon as one standalone `svg` document. */\nexport const serialize = (icon: IconData): string =>\n `<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"${escapeAttribute(icon.viewBox)}\"${attributesOf(icon.attributes)}>${icon.nodes.map(nodeMarkup).join('')}</svg>`\n\n/**\n * The icon as a CSS `url()`, for a mask (`Icons.byAttribute`, `Icons.glyph`):\n * a mask reads only the drawing's shape, so its colours do not matter, and\n * the element it masks paints in `currentColor`.\n */\nexport const maskUrl = (icon: IconData): string =>\n // Only what a data URL in a quoted CSS `url()` cannot hold is escaped (a line break ends a CSS\n // string): a theme writes every chrome icon this way, and escaping the spaces, `=` and `/`\n // too adds a quarter to each.\n `url(\"data:image/svg+xml,${serialize(icon).replace(/[%#<>\"\\n\\r\\t]/g, unsafe => `%${unsafe.charCodeAt(0).toString(16).padStart(2, '0').toUpperCase()}`)}\")`\n\nconst keys = new WeakMap<IconData, string>()\n\n/**\n * A short name for the icon, from its content: the same drawing has the same\n * key on a server and in the browser, and two drawings almost never share\n * one. A drawing's ids are prefixed with it, and a sprite names its symbol by it.\n */\nexport const key = (icon: IconData): string => {\n const known = keys.get(icon)\n if (known !== undefined) return known\n // 64-bit FNV-1a over the serialized drawing.\n let hash = 0xcbf29ce484222325n\n for (const unit of serialize(icon)) {\n hash ^= BigInt(unit.codePointAt(0)!)\n hash = BigInt.asUintN(64, hash * 0x100000001b3n)\n }\n const made = `i${hash.toString(36)}`\n keys.set(icon, made)\n return made\n}\n\nconst idsOf = (nodes: ReadonlyArray<SvgNode>, into: Set<string>): Set<string> => {\n for (const node of nodes) {\n if (node.attributes['id'] !== undefined) into.add(node.attributes['id'])\n idsOf(node.children, into)\n }\n return into\n}\n\ninterface Prefixed {\n readonly ids: ReadonlySet<string>\n readonly byPrefix: Map<string, IconData>\n}\n\nconst prefixed = new WeakMap<IconData, Prefixed>()\n\nconst idPrefix = (prefix: string): string => {\n if (/^(?!fk_)[A-Za-z0-9_-]+$/.test(prefix)) return prefix\n let encoded = ''\n for (let at = 0; at < prefix.length; at++) {\n encoded += prefix.charCodeAt(at).toString(16).padStart(4, '0')\n }\n return `fk_${encoded}`\n}\n\n/**\n * The icon with each id it defines, and each `href` and `url()` naming one,\n * prefixed: two icons drawn inline on one page share the document's ids, and\n * an exported SVG's `id=\"a\"` would otherwise paint another icon's gradient.\n * A prefix outside an identifier's safe characters is encoded before it\n * reaches a CSS `url()`. An icon with no ids is returned as it was given.\n * Kept per icon and prefix, since a view asks again on every render.\n */\nexport const prefixIds = (icon: IconData, prefix: string): IconData => {\n const memo = prefixed.get(icon) ?? { ids: idsOf(icon.nodes, new Set()), byPrefix: new Map() }\n prefixed.set(icon, memo)\n const { ids, byPrefix } = memo\n if (ids.size === 0) return icon\n const known = byPrefix.get(prefix)\n if (known !== undefined) return known\n const writtenPrefix = idPrefix(prefix)\n const rename = (id: string) => (ids.has(id) ? `${writtenPrefix}-${id}` : id)\n const rewriteValue = (name: string, value: string): string => {\n if (name === 'id') return rename(value)\n // The parser admits only a fragment `href`.\n if (name === 'href') return `#${rename(value.slice(1))}`\n return value.replace(\n /url\\(\\s*(['\"]?)#([^)'\"\\s]*)\\1\\s*\\)/gi,\n (_, quote: string, id: string) => `url(${quote}#${rename(id)}${quote})`,\n )\n }\n const rewrite = (attributes: Readonly<Record<string, string>>) =>\n Object.fromEntries(\n Object.entries(attributes).map(([name, value]) => [name, rewriteValue(name, value)]),\n )\n const walk = (node: SvgNode): SvgNode => ({\n tag: node.tag,\n attributes: rewrite(node.attributes),\n children: node.children.map(walk),\n })\n const made: IconData = {\n viewBox: icon.viewBox,\n attributes: rewrite(icon.attributes),\n nodes: icon.nodes.map(walk),\n }\n byPrefix.set(prefix, made)\n return made\n}\n\n/** How a drawing's strokes are drawn: their width, and whether their ends and joins are round. */\nexport interface Stroke {\n readonly width?: number | undefined\n readonly corners?: 'round' | 'square' | undefined\n}\n\n/**\n * The icon with its strokes redrawn: every `stroke-width`, `stroke-linecap`\n * and `stroke-linejoin` it sets replaced, or set on its root where it sets\n * none. A filled icon draws no stroke, so it is unchanged in what shows. For\n * a mask, whose drawing CSS cannot reach once it is a `url()`.\n */\nexport const withStroke = (icon: IconData, stroke: Stroke): IconData => {\n const set: Record<string, string> = {}\n if (stroke.width !== undefined) set['stroke-width'] = String(stroke.width)\n if (stroke.corners !== undefined) {\n set['stroke-linecap'] = stroke.corners\n set['stroke-linejoin'] = stroke.corners === 'round' ? 'round' : 'miter'\n }\n const names = Object.keys(set)\n const found = new Set<string>()\n const restroke = (attributes: Readonly<Record<string, string>>) => {\n const written = { ...attributes }\n for (const name of names) {\n if (Object.hasOwn(attributes, name)) {\n written[name] = set[name]!\n found.add(name)\n }\n }\n return written\n }\n const walk = (node: SvgNode): SvgNode => ({\n tag: node.tag,\n attributes: restroke(node.attributes),\n children: node.children.map(walk),\n })\n const nodes = icon.nodes.map(walk)\n const attributes = restroke(icon.attributes)\n // A property the drawing never sets is set once on the root, which every node inherits.\n for (const name of names) if (!found.has(name)) attributes[name] = set[name]!\n return { viewBox: icon.viewBox, attributes, nodes }\n}\n\ntype Element<Node, Attribute> = (\n attributes: ReadonlyArray<Attribute>,\n children: ReadonlyArray<Node>,\n) => Node\n\n/**\n * What `draw` needs of a view's builder: an element per tag an icon may hold,\n * and raw attributes. Foldkit's `HtmlBuilder` is one, so this package needs\n * no view library of its own.\n */\nexport type SvgBuilder<Node, Attribute> = {\n readonly svg: Element<Node, Attribute>\n readonly Attribute: (name: string, value: string) => Attribute\n readonly AriaHidden: (value: boolean) => Attribute\n} & { readonly [Tag in SvgTag]: Element<Node, Attribute> }\n\n/**\n * The icon as inline SVG, through a view's builder (`h`): `size` square\n * (`1em` unless given, so it stands as tall as its text; `foldkit-mixins-ui`'s\n * `Icon.view` fills its glyph with it), kept so in a squeezed flex row, and\n * hidden from assistive technology,\n * since the control it sits in carries the name. Every attribute is written as\n * an attribute, so a server render writes the same markup. Ids are prefixed by\n * `key(icon)`; `options.key` sets one drawing's ids apart from another of the\n * same icon, since a gradient defined in a copy that is hidden paints nothing\n * for the copy that shows. Each key's drawing is kept for the icon's life, so\n * take keys from a small fixed set (a place on the page), not one per row.\n */\nexport const draw = <Node, Attribute>(\n icon: IconData,\n h: SvgBuilder<Node, Attribute>,\n options: { readonly key?: string; readonly size?: string } = {},\n): Node => {\n const prefix = key(icon) + (options.key === undefined ? '' : `-${options.key}`)\n const { viewBox, attributes, nodes } = prefixIds(icon, prefix)\n const size = options.size ?? '1em'\n const written = (from: Readonly<Record<string, string>>) =>\n Object.entries(from).map(([name, value]) => h.Attribute(name, value))\n const drawn = ({ tag, attributes, children }: SvgNode): Node =>\n h[tag](written(attributes), children.map(drawn))\n return h.svg(\n [\n h.Attribute('viewBox', viewBox),\n h.Attribute('width', size),\n h.Attribute('height', size),\n // A flex row squeezed narrower than its content shrinks an svg to nothing, width or not.\n h.Attribute('style', 'flex-shrink: 0'),\n h.AriaHidden(true),\n ...written(attributes),\n ],\n nodes.map(drawn),\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAQA,MAAa,OAAO;CAClB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAiBA,MAAM,mBAAmB,UACvB,MAAM,QAAQ,MAAM,OAAO,CAAC,CAAC,QAAQ,MAAM,QAAQ,CAAC,CAAC,QAAQ,MAAM,MAAM,CAAC,CAAC,QAAQ,MAAM,MAAM;AAEjG,MAAM,gBAAgB,eACpB,OAAO,QAAQ,UAAU,CAAC,CACvB,KAAK,CAAC,MAAM,WAAW,IAAI,KAAK,IAAI,gBAAgB,KAAK,EAAE,EAAE,CAAC,CAC9D,KAA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tE,MAAM,SAAS,EAAE,KAAK,YAAY,eAChC,EAAE,IAAI,CAAC,QAAQ,UAAU,GAAG,SAAS,IAAI,KAAK,CAAC;CACjD,OAAO,EAAE,IACP;EACE,EAAE,UAAU,WAAW,OAAO;EAC9B,EAAE,UAAU,SAAS,IAAI;EACzB,EAAE,UAAU,UAAU,IAAI;EAE1B,EAAE,UAAU,SAAS,gBAAgB;EACrC,EAAE,WAAW,IAAI;EACjB,GAAG,QAAQ,UAAU;CACvB,GACA,MAAM,IAAI,KAAK,CACjB;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"icon-BGtxExTN.d.mts","names":[],"sources":["../src/icon.ts"],"mappings":";;;;;;;;;;cAQa;KAiBD,iBAAiB;;UAGZ;WACN,KAAK;WACL,YAAY,SAAS;WACrB,UAAU,cAAc;;;UAIlB;WACN;WACA,YAAY,SAAS;WACrB,OAAO,cAAc;;;cAiBnB,YAAS,MAAU;;;;;;cAQnB,UAAO,MAAU;;;;;;cAajB,MAAG,MAAU;;;;;;;;;cA8Cb,YAAS,MAAU,UAAQ,mBAAmB;;UAqC1C;WACN;WACA;;;;;;;;cASE,aAAU,MAAU,UAAQ,QAAU,WAAS;KA+BvD,QAAQ,MAAM,cACjB,YAAY,cAAc,YAC1B,UAAU,cAAc,UACrB;;;;;;KAOO,WAAW,MAAM;WAClB,KAAK,QAAQ,MAAM;WACnB,YAAY,cAAc,kBAAkB;WAC5C,aAAa,mBAAmB;gBAC3B,OAAO,SAAS,QAAQ,MAAM;;;;;;;;;;;;;cAcjC,OAAQ,MAAM,WAAS,MAC5B,UAAQ,GACX,WAAW,MAAM,YAAU;WACV;WAAuB;MAC1C"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/icons/index.ts"],"mappings":";;;;;;qBA0Ha,QAAK,aAAe,iBAAiB;;;;;;qBAgMrC,YAAU,OAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;YAQX,oBAAoB,WAAW;;qBAG9B,UAAO,KAAS,eAAa;;;;;;qBAU7B,cAAW,KAAS,YAAU,iBAAiB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../src/icons/index.ts"],"sourcesContent":["/**\n * SVG to `IconData`, for builds and generator scripts: a Vite plugin reading\n * an icon set, a script writing a package's icon constants. The parse is where\n * an icon is checked, because it is drawn inline: an element or attribute\n * outside the presentational allowlist, a `style`, an event attribute, or a\n * reference outside the icon fails here, naming the icon, rather than being\n * dropped.\n */\nimport { Schema } from 'effect'\nimport { TAGS, type IconData, type SvgNode, type SvgTag } from '../icon.js'\n\nconst ELEMENTS: ReadonlySet<string> = new Set(TAGS)\nconst isTag = (tag: string): tag is SvgTag => ELEMENTS.has(tag)\n\n/** Words for a reader, which an icon's label replaces; skipped with what they hold. */\nconst DROPPED_ELEMENTS = new Set(['title', 'desc', 'metadata'])\n\nconst PRESENTATION = [\n 'clip-path',\n 'clip-rule',\n 'color',\n 'display',\n 'fill',\n 'fill-opacity',\n 'fill-rule',\n 'mask',\n 'opacity',\n 'paint-order',\n 'shape-rendering',\n 'stroke',\n 'stroke-dasharray',\n 'stroke-dashoffset',\n 'stroke-linecap',\n 'stroke-linejoin',\n 'stroke-miterlimit',\n 'stroke-opacity',\n 'stroke-width',\n 'transform',\n 'vector-effect',\n 'visibility',\n]\n\nconst ATTRIBUTES = new Set([\n ...PRESENTATION,\n 'id',\n 'd',\n 'pathLength',\n 'cx',\n 'cy',\n 'r',\n 'rx',\n 'ry',\n 'x',\n 'y',\n 'x1',\n 'y1',\n 'x2',\n 'y2',\n 'width',\n 'height',\n 'points',\n 'href',\n 'offset',\n 'stop-color',\n 'stop-opacity',\n 'fx',\n 'fy',\n 'fr',\n 'gradientUnits',\n 'gradientTransform',\n 'spreadMethod',\n 'clipPathUnits',\n 'maskUnits',\n 'maskContentUnits',\n])\n\n/** The root keeps what it paints; its size is its container's, so it gives that up. */\nconst ROOT_ATTRIBUTES = new Set(PRESENTATION)\nconst DROPPED_ROOT = new Set(['xmlns', 'xmlns:xlink', 'version', 'width', 'height', 'viewBox'])\nconst ROOT_ALLOWED = new Set([...ROOT_ATTRIBUTES, ...DROPPED_ROOT])\n\nconst ENTITIES: ReadonlyMap<string, string> = new Map([\n ['amp', '&'],\n ['lt', '<'],\n ['gt', '>'],\n ['quot', '\"'],\n ['apos', \"'\"],\n])\n\nconst USER_UNITS = /^\\d+(\\.\\d+)?$/\n\n/**\n * The CSS and SVG functions an attribute may call: colours, transforms, and\n * `url()`, whose target is checked apart. Any other is refused, since a\n * presentation attribute is read as CSS, where `image-set()` or `cross-fade()`\n * fetches a bare URL.\n */\nconst FUNCTIONS: ReadonlySet<string> = new Set([\n 'url',\n 'rgb',\n 'rgba',\n 'hsl',\n 'hsla',\n 'hwb',\n 'lab',\n 'lch',\n 'oklab',\n 'oklch',\n 'color',\n 'color-mix',\n 'matrix',\n 'translate',\n 'scale',\n 'rotate',\n 'skewx',\n 'skewy',\n])\n\n/**\n * The icon in `svg`, one whole SVG document, as `IconData`; `name` says which\n * icon a refusal is about. Throws on anything outside the allowlist.\n */\nexport const parse = (svg: string, name: string): IconData => {\n const refuse = (reason: string): never => {\n throw new Error(`The icon \"${name}\" cannot be drawn inline: ${reason}.`)\n }\n\n const decode = (value: string): string =>\n value.replace(/&([^;\\s]*);/g, (whole, entity: string) => {\n if (!entity.startsWith('#')) {\n return ENTITIES.get(entity) ?? refuse(`it holds the unknown entity ${whole}`)\n }\n const [, hex, decimal] = /^#(?:x([0-9a-fA-F]+)|([0-9]+))$/.exec(entity) ?? []\n const point =\n hex !== undefined ? Number.parseInt(hex, 16) : Number.parseInt(decimal ?? '0', 10)\n return point > 0 && point <= 0x10ffff\n ? String.fromCodePoint(point)\n : refuse(`it holds ${whole}, which is no character`)\n })\n\n const ATTRIBUTE = /\\s+([^\\s=/>]+)\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)')/y\n\n // Every id the icon defines, and every fragment it names: one naming no id of its own\n // would reach the page's, so the two are compared once the whole icon is read.\n const ids = new Set<string>()\n const references: Array<{\n readonly tag: string\n readonly attribute: string\n readonly id: string\n }> = []\n\n const attributesOf = (tag: string, source: string, allowed: ReadonlySet<string>) => {\n const attributes: Record<string, string> = Object.create(null)\n ATTRIBUTE.lastIndex = 0\n while (ATTRIBUTE.lastIndex < source.trimEnd().length) {\n const from = ATTRIBUTE.lastIndex\n const match = ATTRIBUTE.exec(source)\n if (match === null)\n return refuse(`its <${tag}> is malformed at \"${source.slice(from).trim()}\"`)\n const written = match[1]!\n const value = decode(match[2] ?? match[3]!)\n const attribute = written === 'xlink:href' ? 'href' : written\n if (Object.hasOwn(attributes, attribute)) refuse(`its <${tag}> sets ${attribute} twice`)\n if (!allowed.has(attribute))\n refuse(`its <${tag}> has the attribute ${attribute}, which is not drawn inline`)\n if (attribute === 'href') {\n if (!value.startsWith('#')) refuse(`its <${tag}> links outside the icon (${value})`)\n references.push({ tag, attribute, id: value.slice(1) })\n }\n // A presentation attribute is read as CSS, where `URL(` is `url(` and an escape can spell either.\n if (value.includes('\\\\')) refuse(`its <${tag}>'s ${attribute} holds a CSS escape`)\n for (const [, called] of value.matchAll(/([a-z][a-z0-9-]*)\\s*\\(/gi)) {\n if (!FUNCTIONS.has(called!.toLowerCase()))\n refuse(`its <${tag}>'s ${attribute} calls ${called}(), which is not drawn inline`)\n }\n for (const [, target] of value.matchAll(/url\\(\\s*['\"]?([^)'\"]*)/gi)) {\n if (!target!.trim().startsWith('#'))\n refuse(`its <${tag}>'s ${attribute} refers outside the icon (${value})`)\n references.push({ tag, attribute, id: target!.trim().slice(1) })\n }\n if (attribute === 'id') ids.add(value)\n attributes[attribute] = value\n }\n return attributes\n }\n\n interface Open {\n readonly tag: SvgTag\n readonly attributes: Readonly<Record<string, string>>\n readonly children: Array<SvgNode>\n }\n let root:\n | { readonly attributes: Readonly<Record<string, string>>; readonly children: Array<SvgNode> }\n | undefined\n /** The elements open inside the root now, innermost last. */\n const open: Array<Open> = []\n let closed = false\n /** How deep inside a dropped element the parse is; its content is skipped whole. */\n let dropping = 0\n let at = 0\n\n while (at < svg.length) {\n const start = svg.indexOf('<', at)\n const text = svg.slice(at, start === -1 ? svg.length : start).trim()\n if (text !== '' && dropping === 0) refuse(`it holds the text \"${text}\"`)\n if (start === -1) break\n\n const [opener, closer] = svg.startsWith('<!--', start) ? ['<!--', '-->'] : ['<', '>']\n const end = svg.indexOf(closer, start + opener.length)\n if (end === -1) refuse(`a ${opener === '<' ? 'tag' : 'comment'} never closes`)\n at = end + closer.length\n if (opener === '<!--') continue\n const inside = svg.slice(start + 1, end)\n\n if (inside.startsWith('?') || inside.startsWith('!DOCTYPE')) {\n if (root !== undefined) refuse('it holds a declaration inside its drawing')\n continue\n }\n if (inside.startsWith('!')) refuse('it holds CDATA or a declaration')\n\n if (inside.startsWith('/')) {\n const tag = inside.slice(1).trim()\n if (dropping > 0) {\n if (DROPPED_ELEMENTS.has(tag)) dropping -= 1\n continue\n }\n if (open.length === 0 && tag === 'svg' && root !== undefined && !closed) {\n closed = true\n continue\n }\n const element = open.pop()\n if (element?.tag !== tag) {\n refuse(`</${tag}> closes ${element === undefined ? 'nothing' : `<${element.tag}>`}`)\n }\n ;(open.at(-1) ?? root!).children.push(element!)\n continue\n }\n\n const selfClosing = inside.endsWith('/')\n const body = selfClosing ? inside.slice(0, -1) : inside\n const tag = /^[^\\s/>]*/.exec(body)![0]\n if (dropping > 0) {\n if (DROPPED_ELEMENTS.has(tag) && !selfClosing) dropping += 1\n continue\n }\n if (closed) refuse('it holds markup after its svg')\n if (root === undefined) {\n if (tag !== 'svg') refuse(`its root is <${tag}>, not <svg>`)\n root = { attributes: attributesOf(tag, body.slice(tag.length), ROOT_ALLOWED), children: [] }\n if (selfClosing) closed = true\n continue\n }\n if (DROPPED_ELEMENTS.has(tag)) {\n if (!selfClosing) dropping += 1\n continue\n }\n if (!isTag(tag)) return refuse(`it holds <${tag}>, which is not drawn inline`)\n const element: Open = {\n tag,\n attributes: attributesOf(tag, body.slice(tag.length), ATTRIBUTES),\n children: [],\n }\n if (selfClosing) (open.at(-1) ?? root).children.push(element)\n else open.push(element)\n }\n\n if (root === undefined) return refuse('it holds no svg')\n if (!closed) refuse(`<${open.at(-1)?.tag ?? 'svg'}> never closes`)\n for (const { tag, attribute, id } of references) {\n if (!ids.has(id))\n refuse(`its <${tag}>'s ${attribute} names #${id}, which the icon does not define`)\n }\n\n const { viewBox, width, height } = root.attributes\n const presentation: Record<string, string> = {}\n for (const [attribute, value] of Object.entries(root.attributes)) {\n if (!DROPPED_ROOT.has(attribute)) presentation[attribute] = value\n }\n return {\n viewBox:\n viewBox ??\n (width !== undefined &&\n height !== undefined &&\n USER_UNITS.test(width) &&\n USER_UNITS.test(height)\n ? `0 0 ${width} ${height}`\n : refuse('it has no viewBox, and no width and height in user units to make one')),\n attributes: presentation,\n nodes: root.children,\n }\n}\n\nconst Box = {\n width: Schema.optional(Schema.Number),\n height: Schema.optional(Schema.Number),\n left: Schema.optional(Schema.Number),\n top: Schema.optional(Schema.Number),\n}\ntype IconifyBox = Schema.Struct.Type<typeof Box>\n\n// An icon or an alias may turn its drawing; read so that it is refused, not drawn unturned.\nconst Turn = {\n rotate: Schema.optional(Schema.Number),\n hFlip: Schema.optional(Schema.Boolean),\n vFlip: Schema.optional(Schema.Boolean),\n}\nconst turns = (entry: Schema.Struct.Type<typeof Turn>): boolean =>\n (entry.rotate !== undefined && entry.rotate !== 0) || entry.hFlip === true || entry.vFlip === true\n\n/**\n * An Iconify set, as its JSON file holds it (`@iconify-json/<prefix>/icons.json`).\n * What the drawing does not need (`info`, `categories`, an icon's `hidden`) is\n * read past.\n */\nexport const IconifySet = Schema.Struct({\n prefix: Schema.String,\n icons: Schema.Record(Schema.String, Schema.Struct({ body: Schema.String, ...Turn, ...Box })),\n aliases: Schema.optional(\n Schema.Record(Schema.String, Schema.Struct({ parent: Schema.String, ...Turn, ...Box })),\n ),\n ...Box,\n})\nexport type IconifySet = typeof IconifySet.Type\n\n/** Every name the set draws: its icons, then its aliases. */\nexport const namesOf = (set: IconifySet): ReadonlyArray<string> => [\n ...Object.keys(set.icons),\n ...Object.keys(set.aliases ?? {}),\n]\n\n/**\n * The icon `name` of an Iconify set, through its aliases, each of which may\n * give its own box. An alias that rotates or flips its parent is refused\n * rather than drawn as a second, transformed drawing.\n */\nexport const fromIconify = (set: IconifySet, name: string): IconData => {\n const label = `${set.prefix}:${name}`\n const refuse = (reason: string): never => {\n throw new Error(`The icon \"${label}\" cannot be drawn inline: ${reason}.`)\n }\n const boxes: Array<IconifyBox> = []\n let current = name\n while (!Object.hasOwn(set.icons, current)) {\n const alias =\n set.aliases !== undefined && Object.hasOwn(set.aliases, current)\n ? set.aliases[current]!\n : undefined\n if (alias === undefined) return refuse(`the set has no icon ${current}`)\n if (turns(alias)) refuse('it is an alias that rotates or flips its parent')\n if (boxes.length > 16) refuse('its aliases go round in a circle')\n boxes.push(alias)\n current = alias.parent\n }\n const icon = set.icons[current]!\n if (turns(icon)) refuse(`its drawing ${current} rotates or flips itself`)\n const nearest = [...boxes, icon, set]\n const read = (key: keyof IconifyBox, otherwise: number) =>\n nearest.find(box => box[key] !== undefined)?.[key] ?? otherwise\n return parse(\n `<svg viewBox=\"${read('left', 0)} ${read('top', 0)} ${read('width', 16)} ${read('height', 16)}\">${icon.body}</svg>`,\n label,\n )\n}\n"],"mappings":";;;;;;;;;;;AAWA,MAAM,WAAgC,IAAI,IAAI,IAAI;AAClD,MAAM,SAAS,QAA+B,SAAS,IAAI,GAAG;;AAG9D,MAAM,mCAAmB,IAAI,IAAI;CAAC;CAAS;CAAQ;AAAU,CAAC;AAE9D,MAAM,eAAe;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAM,6BAAa,IAAI,IAAI;CACzB,GAAG;CACH;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;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AO,KAAK,IAAI,KAAK,GACxB,GAAG,OAAO,KAAK,IAAI,WAAW,CAAC,CAAC,CAClC;;;;;;AAOA,MAAa,eAAe,KAAiB,SAA2B;CACtE,MAAM,QAAQ,GAAG,IAAI,OAAO,GAAG;CAC/B,MAAM,UAAU,WAA0B;EACxC,MAAM,IAAI,MAAM,aAAa,MAAM,4BAA4B,OAAO,EAAE;CAC1E;CACA,MAAM,QAA2B,CAAC;CAClC,IAAI,UAAU;CACd,OAAO,CAAC,OAAO,OAAO,IAAI,OAAO,OAAO,GAAG;EACzC,MAAM,QACJ,IAAI,YAAY,KAAA,KAAa,OAAO,OAAO,IAAI,SAAS,OAAO,IAC3D,IAAI,QAAQ,WACZ,KAAA;EACN,IAAI,UAAU,KAAA,GAAW,OAAO,OAAO,uBAAuB,SAAS;EACvE,IAAI,MAAM,KAAK,GAAG,OAAO,iDAAiD;EAC1E,IAAI,MAAM,SAAS,IAAI,OAAO,kCAAkC;EAChE,MAAM,KAAK,KAAK;EAChB,UAAU,MAAM;CAClB;CACA,MAAM,OAAO,IAAI,MAAM;CACvB,IAAI,MAAM,IAAI,GAAG,OAAO,eAAe,QAAQ,yBAAyB;CACxE,MAAM,UAAU;EAAC,GAAG;EAAO;EAAM;CAAG;CACpC,MAAM,QAAQ,KAAuB,cACnC,QAAQ,MAAK,QAAO,IAAI,SAAS,KAAA,CAAS,CAAC,GAAG,QAAQ;CACxD,OAAO,MACL,iBAAiB,KAAK,QAAQ,CAAC,EAAE,GAAG,KAAK,OAAO,CAAC,EAAE,GAAG,KAAK,SAAS,EAAE,EAAE,GAAG,KAAK,UAAU,EAAE,EAAE,IAAI,KAAK,KAAK,SAC5G,KACF;AACF"}
package/dist/index.d.mts DELETED
@@ -1,157 +0,0 @@
1
- import { a as isHashed, i as Placeholder, n as HashedAsset, r as ImageAsset, t as Focus } from "./asset-BLo8VWmd.mjs";
2
- import { i as describe, n as Inspector, r as Thumbnail, t as Inspected } from "./describe-BOgc0xbR.mjs";
3
- import { a as mimeType, i as Format, n as widths_d_exports, r as Encoding, t as Widths } from "./widths-upkgLdek.mjs";
4
- import { r as variant_d_exports } from "./variant-B-vyMmFB.mjs";
5
- import { a as SvgTag, i as SvgNode, n as Stroke, o as icon_d_exports, r as SvgBuilder, t as IconData } from "./icon-BGtxExTN.mjs";
6
- import { n as Provider, r as provider_d_exports } from "./provider-CB0nqu0m.mjs";
7
- import { Option, Schema } from "effect";
8
- declare namespace layout_d_exports {
9
- export { Candidate, Constrained, Fixed, FullWidth, Layout, LayoutSchema as Schema, box, candidates, ratio, sizes$1 as sizes };
10
- }
11
- /** How wide an image is drawn, from which its candidates and `sizes` follow. */
12
- declare const LayoutSchema: Schema.TaggedUnion<{
13
- readonly Constrained: Schema.TaggedStruct<"Constrained", {
14
- readonly width: Schema.Finite;
15
- }>;
16
- readonly Fixed: Schema.TaggedStruct<"Fixed", {
17
- readonly width: Schema.Finite;
18
- }>;
19
- readonly FullWidth: Schema.TaggedStruct<"FullWidth", {}>;
20
- }>;
21
- type Layout = typeof LayoutSchema.Type;
22
- declare const Fixed: (input: {
23
- readonly _tag?: "Fixed";
24
- readonly width: number;
25
- }, options?: Schema.MakeOptions) => {
26
- readonly _tag: "Fixed";
27
- readonly width: number;
28
- };
29
- declare const Constrained: (input: {
30
- readonly _tag?: "Constrained";
31
- readonly width: number;
32
- }, options?: Schema.MakeOptions) => {
33
- readonly _tag: "Constrained";
34
- readonly width: number;
35
- };
36
- declare const FullWidth: () => Layout;
37
- /**
38
- * One `srcset` entry: the ladder width asked of the provider, and the width
39
- * the answer has. They differ only above the original's own width, where a
40
- * provider that does not enlarge answers with the original's.
41
- */
42
- interface Candidate {
43
- readonly request: number;
44
- readonly described: number;
45
- }
46
- /**
47
- * The widths worth offering for `layout`: for a fixed image its 1x and 2x,
48
- * for a constrained one every width up to its 2x, for a full-width one the
49
- * whole ladder. Widths above the original fetch the original's pixels, so
50
- * only the first of them is kept.
51
- */
52
- declare const candidates: (layout: Layout, widths: Widths, intrinsic: number) => ReadonlyArray<Candidate>;
53
- /** The `sizes` a layout implies: how wide the image is drawn at each viewport. */
54
- declare const sizes$1: (layout: Layout) => string;
55
- /** The original's aspect ratio, as CSS writes one. */
56
- declare const ratio: (asset: Pick<ImageAsset, 'width' | 'height'>) => string;
57
- /**
58
- * The `width` and `height` attributes: the drawn size where the layout fixes
59
- * one, the original's where it does not. Either way their ratio is the
60
- * original's, which is what reserves the box before a byte arrives.
61
- */
62
- declare const box: (layout: Layout, asset: Pick<ImageAsset, 'width' | 'height'>) => {
63
- readonly width: number;
64
- readonly height: number;
65
- };
66
- /**
67
- * How much of a ThumbHash a placeholder paints: its blurred picture
68
- * (`detail`), or its average color (`average`).
69
- */
70
- type Level = 'detail' | 'average';
71
- declare namespace picture_d_exports {
72
- export { Img, Input, Picture, Preloaded, Source, derive, ogImage, preload, preloadLink };
73
- }
74
- /** A `source` element's attributes: one format's candidates. */
75
- interface Source {
76
- readonly type: string;
77
- readonly srcset: string;
78
- }
79
- /** The `img` element's attributes. */
80
- interface Img {
81
- readonly src: string;
82
- readonly srcset: string;
83
- readonly sizes: string;
84
- readonly width: number;
85
- readonly height: number;
86
- readonly loading: 'lazy' | 'eager';
87
- readonly decoding: Option.Option<'async'>;
88
- readonly fetchPriority: Option.Option<'high'>;
89
- }
90
- /**
91
- * Everything an image's markup says, derived from its facts, its provider and
92
- * its layout. A view writes these; it decides nothing.
93
- */
94
- interface Picture {
95
- /** One per format the provider offers before the `img`'s own; none, a bare `img`. */
96
- readonly sources: ReadonlyArray<Source>;
97
- readonly img: Img;
98
- /** The original's aspect ratio, as CSS writes one. */
99
- readonly ratio: string;
100
- /** Where a crop keeps the subject, as `object-position` writes it. */
101
- readonly focus: Option.Option<string>;
102
- /**
103
- * The CSS `background` to paint behind the image until it loads. None for
104
- * an image with transparent pixels, which would show it through them.
105
- */
106
- readonly placeholder: Option.Option<string>;
107
- }
108
- /** An image's facts, and a provider that takes them: a hashed one for `Provider.hosted`. */
109
- interface Input<Asset extends ImageAsset = ImageAsset> {
110
- readonly asset: Asset;
111
- readonly provider: Provider<NoInfer<Asset>>;
112
- readonly layout: Layout;
113
- /** The page's largest image: fetched first, not lazily. */
114
- readonly priority?: boolean;
115
- /** In place of the layout's `sizes`, when the page knows the drawn width better. */
116
- readonly sizes?: string;
117
- /**
118
- * How much of a ThumbHash to paint. By default its picture for a `priority`
119
- * image, the one a reader waits on, and its average color for the rest, so
120
- * a grid of thumbnails adds colors to the HTML, not pictures.
121
- */
122
- readonly placeholder?: Level;
123
- }
124
- /**
125
- * The attributes of one image, or none when the provider has no URL for any
126
- * of its candidates in the `img`'s own encoding (a build table that never made
127
- * this image). Candidates the provider lacks are left out, never written as a
128
- * broken URL.
129
- */
130
- declare const derive: <Asset extends ImageAsset>(input: Input<Asset>) => Option.Option<Picture>;
131
- /** What a preload names: the candidates the browser will choose from, at the `img`'s sizes. */
132
- interface Preloaded {
133
- /** A `source`'s media type, so a browser that cannot show it skips the preload. */
134
- readonly type: Option.Option<string>;
135
- readonly srcset: string;
136
- readonly sizes: string;
137
- }
138
- /** The `<link rel="preload">` naming `preloaded`, its values escaped for the attribute. */
139
- declare const preloadLink: ({ type, srcset, sizes }: Preloaded) => string;
140
- /**
141
- * A `<link rel="preload">` for a page's `head`, so the browser fetches its
142
- * largest image before it reaches the `img`. It names the candidates the
143
- * browser will choose from: the first `source`'s, with its `type`, so a
144
- * browser that cannot show that format skips the preload rather than fetching
145
- * a file it will not use; the `img`'s when there is no `source`. Only for the
146
- * image drawn with `priority`.
147
- */
148
- declare const preload: ({ sources, img }: Picture) => string;
149
- /**
150
- * An image for a page's Open Graph `og:image`: at the first ladder width of
151
- * at least 1200, as JPEG when the provider makes it, else WebP or PNG, never
152
- * AVIF, as an absolute URL against `origin`. None when the provider has no
153
- * such variant.
154
- */
155
- declare const ogImage: <Asset extends ImageAsset>(asset: Asset, provider: Provider<NoInfer<Asset>>, origin: string) => Option.Option<string>;
156
- export { type Encoding, Focus, Format, HashedAsset, icon_d_exports as Icon, type IconData, ImageAsset, type Inspected, Inspector, layout_d_exports as Layout, picture_d_exports as Picture, Placeholder, provider_d_exports as Provider, type Stroke, type SvgBuilder, type SvgNode, type SvgTag, type Thumbnail, variant_d_exports as Variant, widths_d_exports as Widths, describe, isHashed, mimeType };
157
- //# sourceMappingURL=index.d.mts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.mts","names":["sizes","Layout.Layout"],"sources":["../src/layout.ts","../src/placeholder.ts","../src/picture.ts"],"mappings":";;;;;;;;;;;cAOM,cAAY,OAAA;;;;;;;;;KASN,gBAAgB,aAAa;cAE5B,QAAK;;;;;;;cACL,cAAW;;;;;;;cACX,iBAAgB;;;;;;UAOZ;WACN;WACA;;;;;;;;cASE,aAAU,QACb,QAAM,QACN,QAAM,sBAEb,cAAc;;cAkBJA,UAAK,QAAY;;cAQjB,QAAK,OAAW,KAAK;;;;;;cAQrB,MAAG,QACN,QAAM,OACP,KAAK;WACA;WAAwB;;;;;;KC3C1B;;;;;UC3BK;WACN;WACA;;;UAIM;WACN;WACA;WACA;WACA;WACA;WACA;WACA,UAAU,OAAO;WACjB,eAAe,OAAO;;;;;;UAOhB;;WAEN,SAAS,cAAc;WACvB,KAAK;;WAEL;;WAEA,OAAO,OAAO;;;;;WAKd,aAAa,OAAO;;;UAId,MAAM,cAAc,aAAa;WACvC,OAAO;WACP,UAAU,SAAS,QAAQ;WAC3B,QAAQC;;WAER;;WAEA;;;;;;WAMA,cAAc;;;;;;;;cASZ,SAAU,cAAc,YAAU,OAAS,MAAM,WAAS,OAAO,OAAO;;UA0DpE;;WAEN,MAAM,OAAO;WACb;WACA;;;cAIE,gBAAW,MAAA,QAAA,SAA6B;;;;;;;;;cAoBxC,YAAO,SAAA,OAAsB;;;;;;;cAkB7B,UAAW,cAAc,YAAU,OACvC,OAAK,UACF,SAAS,QAAQ,SAAO,mBAEjC,OAAO"}
package/dist/index.mjs DELETED
@@ -1,322 +0,0 @@
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
- import { Option, Schema } from "effect";
7
- import { thumbHashToAverageRGBA, thumbHashToDataURL } from "thumbhash";
8
- // src/layout.ts
9
- var layout_exports = /* @__PURE__ */ __exportAll({
10
- Constrained: () => Constrained,
11
- Fixed: () => Fixed,
12
- FullWidth: () => FullWidth,
13
- Schema: () => LayoutSchema,
14
- box: () => box,
15
- candidates: () => candidates,
16
- ratio: () => ratio,
17
- sizes: () => sizes
18
- });
19
- const CssPixels = Schema.Finite.check(Schema.isGreaterThan(0));
20
- /** How wide an image is drawn, from which its candidates and `sizes` follow. */
21
- const LayoutSchema = Schema.TaggedUnion({
22
- /** Always this many CSS pixels wide. */
23
- Fixed: { width: CssPixels },
24
- /** At most this wide, and the viewport's width when that is narrower. */
25
- Constrained: { width: CssPixels },
26
- /** The viewport's width. */
27
- FullWidth: {}
28
- });
29
- const Fixed = LayoutSchema.cases.Fixed.make;
30
- const Constrained = LayoutSchema.cases.Constrained.make;
31
- const FullWidth = () => LayoutSchema.cases.FullWidth.make({});
32
- /**
33
- * The widths worth offering for `layout`: for a fixed image its 1x and 2x,
34
- * for a constrained one every width up to its 2x, for a full-width one the
35
- * whole ladder. Widths above the original fetch the original's pixels, so
36
- * only the first of them is kept.
37
- */
38
- const candidates = (layout, widths, intrinsic) => {
39
- const wanted = LayoutSchema.match(layout, {
40
- Fixed: ({ width }) => [atLeast(widths, width), atLeast(widths, 2 * width)],
41
- Constrained: ({ width }) => {
42
- const top = atLeast(widths, 2 * width);
43
- return widths.values.filter((value) => value <= top);
44
- },
45
- FullWidth: () => widths.values
46
- });
47
- const result = [];
48
- for (const request of wanted) {
49
- const described = Math.min(request, intrinsic);
50
- if (result.at(-1)?.described !== described) result.push({
51
- request,
52
- described
53
- });
54
- }
55
- return result;
56
- };
57
- /** The `sizes` a layout implies: how wide the image is drawn at each viewport. */
58
- const sizes = (layout) => LayoutSchema.match(layout, {
59
- Fixed: ({ width }) => `${width}px`,
60
- Constrained: ({ width }) => `(min-width: ${width}px) ${width}px, 100vw`,
61
- FullWidth: () => "100vw"
62
- });
63
- /** The original's aspect ratio, as CSS writes one. */
64
- const ratio = (asset) => `${asset.width} / ${asset.height}`;
65
- /**
66
- * The `width` and `height` attributes: the drawn size where the layout fixes
67
- * one, the original's where it does not. Either way their ratio is the
68
- * original's, which is what reserves the box before a byte arrives.
69
- */
70
- const box = (layout, asset) => {
71
- const pixel = (value) => Math.max(1, Math.round(value));
72
- const scaled = (width) => ({
73
- width: pixel(width),
74
- height: pixel(width * asset.height / asset.width)
75
- });
76
- return LayoutSchema.match(layout, {
77
- Fixed: ({ width }) => scaled(width),
78
- Constrained: ({ width }) => scaled(width),
79
- FullWidth: () => ({
80
- width: asset.width,
81
- height: asset.height
82
- })
83
- });
84
- };
85
- // src/placeholder.ts
86
- const DECODED_LIMIT = 256;
87
- const decoded = /* @__PURE__ */ new Map();
88
- const bytesOf = (hash) => Uint8Array.from(atob(hash), (char) => char.charCodeAt(0));
89
- const decode = (hash) => {
90
- const cached = decoded.get(hash);
91
- if (cached !== void 0) return cached;
92
- const url = thumbHashToDataURL(bytesOf(hash));
93
- if (decoded.size >= DECODED_LIMIT) decoded.delete(decoded.keys().next().value);
94
- decoded.set(hash, url);
95
- return url;
96
- };
97
- const cssUrl = (url) => `url("${url.replace(/["\\\n\r]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`)}")`;
98
- const average = (hash) => {
99
- const { r, g, b, a } = thumbHashToAverageRGBA(bytesOf(hash));
100
- const channel = (value) => Math.round(value * 255);
101
- return `rgb(${channel(r)} ${channel(g)} ${channel(b)} / ${Math.round(a * 100) / 100})`;
102
- };
103
- /**
104
- * The CSS `background` an image's placeholder paints, whatever the image: a
105
- * color, a ThumbHash at `level`, or the provider's smallest width of the
106
- * image. None when the image has no placeholder, or the provider has no URL
107
- * for the smallest width.
108
- */
109
- const background = (asset, provider, level) => Option.flatMap(asset.placeholder, (placeholder) => Placeholder.match(placeholder, {
110
- Color: ({ value }) => Option.some(value),
111
- ThumbHash: ({ hash }) => Option.some(level === "detail" ? cssUrl(decode(hash)) : average(hash)),
112
- LowRes: () => Option.map(provider.url(asset, {
113
- width: provider.widths.values[0],
114
- encoding: provider.fallback
115
- }), cssUrl)
116
- }));
117
- // src/picture.ts
118
- var picture_exports = /* @__PURE__ */ __exportAll({
119
- derive: () => derive,
120
- ogImage: () => ogImage,
121
- preload: () => preload,
122
- preloadLink: () => preloadLink
123
- });
124
- /**
125
- * The attributes of one image, or none when the provider has no URL for any
126
- * of its candidates in the `img`'s own encoding (a build table that never made
127
- * this image). Candidates the provider lacks are left out, never written as a
128
- * broken URL.
129
- */
130
- const derive = (input) => {
131
- const { asset, provider, layout, priority = false } = input;
132
- const candidates$1 = candidates(layout, provider.widths, asset.width);
133
- const entries = (encoding) => candidates$1.flatMap((candidate) => Option.match(provider.url(asset, {
134
- width: candidate.request,
135
- encoding
136
- }), {
137
- onNone: () => [],
138
- onSome: (url) => [{
139
- url,
140
- described: candidate.described
141
- }]
142
- }));
143
- const srcsetOf = (list) => list.map(({ url, described }) => `${url} ${described}w`).join(", ");
144
- const own = entries(provider.fallback);
145
- if (own.length === 0) return Option.none();
146
- const drawn = LayoutSchema.match(layout, {
147
- Fixed: ({ width }) => width,
148
- Constrained: ({ width }) => width,
149
- FullWidth: () => Number.POSITIVE_INFINITY
150
- });
151
- const src = (own.find((entry) => entry.described >= drawn) ?? own[own.length - 1]).url;
152
- const sources = provider.sources.flatMap((format) => {
153
- const list = entries(format);
154
- return list.length === 0 ? [] : [{
155
- type: mimeType(format),
156
- srcset: srcsetOf(list)
157
- }];
158
- });
159
- const sizes$1 = input.sizes ?? sizes(layout);
160
- const box$1 = box(layout, asset);
161
- return Option.some({
162
- sources,
163
- img: {
164
- src,
165
- srcset: srcsetOf(own),
166
- sizes: priority || sizes$1.startsWith("auto") ? sizes$1 : `auto, ${sizes$1}`,
167
- width: box$1.width,
168
- height: box$1.height,
169
- loading: priority ? "eager" : "lazy",
170
- decoding: priority ? Option.none() : Option.some("async"),
171
- fetchPriority: priority ? Option.some("high") : Option.none()
172
- },
173
- ratio: ratio(asset),
174
- focus: Option.map(asset.focus, ({ x, y }) => `${x * 100}% ${y * 100}%`),
175
- placeholder: asset.alpha ? Option.none() : background(asset, provider, input.placeholder ?? (priority ? "detail" : "average"))
176
- });
177
- };
178
- const escapeAttribute = (value) => value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
179
- /** The `<link rel="preload">` naming `preloaded`, its values escaped for the attribute. */
180
- const preloadLink = ({ type, srcset, sizes }) => {
181
- return `<link ${[
182
- ["rel", "preload"],
183
- ["as", "image"],
184
- ...Option.match(type, {
185
- onNone: () => [],
186
- onSome: (value) => [["type", value]]
187
- }),
188
- ["imagesrcset", srcset],
189
- ["imagesizes", sizes],
190
- ["fetchpriority", "high"]
191
- ].map(([name, value]) => `${name}="${escapeAttribute(value)}"`).join(" ")}>`;
192
- };
193
- /**
194
- * A `<link rel="preload">` for a page's `head`, so the browser fetches its
195
- * largest image before it reaches the `img`. It names the candidates the
196
- * browser will choose from: the first `source`'s, with its `type`, so a
197
- * browser that cannot show that format skips the preload rather than fetching
198
- * a file it will not use; the `img`'s when there is no `source`. Only for the
199
- * image drawn with `priority`.
200
- */
201
- const preload = ({ sources, img }) => {
202
- const [first] = sources;
203
- return preloadLink({
204
- type: Option.map(Option.fromNullishOr(first), (source) => source.type),
205
- srcset: first === void 0 ? img.srcset : first.srcset,
206
- sizes: img.sizes
207
- });
208
- };
209
- const OPEN_GRAPH_ENCODINGS = [
210
- "jpeg",
211
- "webp",
212
- "png"
213
- ];
214
- /**
215
- * An image for a page's Open Graph `og:image`: at the first ladder width of
216
- * at least 1200, as JPEG when the provider makes it, else WebP or PNG, never
217
- * AVIF, as an absolute URL against `origin`. None when the provider has no
218
- * such variant.
219
- */
220
- const ogImage = (asset, provider, origin) => {
221
- const width = atLeast(provider.widths, 1200);
222
- const encodings = provider.fallback === "auto" ? ["auto"] : OPEN_GRAPH_ENCODINGS;
223
- return Option.map(Option.firstSomeOf(encodings.map((encoding) => provider.url(asset, {
224
- width,
225
- encoding
226
- }))), (url) => new URL(url, origin).href);
227
- };
228
- // src/provider.ts
229
- var provider_exports = /* @__PURE__ */ __exportAll({
230
- cdnCgi: () => cdnCgi,
231
- fromFiles: () => fromFiles,
232
- hosted: () => hosted
233
- });
234
- /**
235
- * The provider of one image whose variants a build already wrote: a table of
236
- * files, no URL scheme. Its ladder is the widths it has, and it answers none
237
- * for a variant it lacks. Refuses no files, and two files for one variant.
238
- */
239
- const fromFiles = (files, formats) => {
240
- if (files.length === 0) throw new Error("Provider.fromFiles: no files");
241
- const byVariant = /* @__PURE__ */ new Map();
242
- for (const file of files) {
243
- const variant = `${file.width}:${file.format}`;
244
- if (byVariant.has(variant)) throw new Error(`Provider.fromFiles: two files for ${file.width}px ${file.format}`);
245
- byVariant.set(variant, file.url);
246
- }
247
- return {
248
- widths: make([...new Set(files.map((file) => file.width))]),
249
- sources: formats.sources,
250
- fallback: formats.fallback,
251
- url: (_asset, { width, encoding }) => Option.fromNullishOr(byVariant.get(`${width}:${encoding}`))
252
- };
253
- };
254
- const HOSTNAME = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/i;
255
- /**
256
- * Cloudflare's own resizing, as URLs under `/cdn-cgi/image/` on a zone that
257
- * has it on. No Worker of ours runs: the zone fetches the original by its
258
- * `key` (a path on the zone, or an absolute URL it may fetch), scales it down
259
- * without enlarging, and picks the format from `Accept`.
260
- */
261
- const cdnCgi = (options = {}) => {
262
- const { zone, widths = standard, quality } = options;
263
- if (zone !== void 0 && !HOSTNAME.test(zone)) throw new Error(`Provider.cdnCgi: "${zone}" is not a host name`);
264
- if (quality !== void 0 && !Schema.is(Quality)(quality)) throw new Error(`Provider.cdnCgi: quality ${quality} is not an integer from 1 to 100`);
265
- const base = zone === void 0 ? "" : `https://${zone}`;
266
- const qualityOption = quality === void 0 ? "" : `,quality=${quality}`;
267
- return {
268
- widths,
269
- sources: [],
270
- fallback: "auto",
271
- url: (asset, { width, encoding }) => {
272
- const operations = `width=${width},format=${encoding},fit=scale-down${qualityOption}`;
273
- return Option.some(`${base}/cdn-cgi/image/${operations}/${cdnCgiSource(asset.key)}`);
274
- }
275
- };
276
- };
277
- const cdnCgiSource = (key) => {
278
- if (!/^https?:\/\//.test(key)) return key.replace(/^\/+/, "");
279
- return key.includes("?") ? encodeURIComponent(key) : key;
280
- };
281
- /**
282
- * Our own server's variants (`foldkit-media/server`), at `Variant.PATH` under
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.
289
- */
290
- const hosted = (options = {}) => {
291
- const { baseUrl: askedBaseUrl = "", space = standard$1 } = options;
292
- const fallback = options.fallback ?? space.formats[space.formats.length - 1];
293
- const sources = options.sources ?? space.formats.slice(0, -1);
294
- const parsed = Option.liftThrowable((value) => new URL(value))(askedBaseUrl);
295
- const origin = Option.filter(parsed, (url) => (url.protocol === "http:" || url.protocol === "https:") && askedBaseUrl === url.origin);
296
- if (askedBaseUrl !== "" && Option.isNone(origin)) throw new Error(`Provider.hosted: "${askedBaseUrl}" is not an origin`);
297
- const baseUrl = Option.match(origin, {
298
- onNone: () => "",
299
- onSome: (url) => url.origin
300
- });
301
- for (const format of [...sources, fallback]) if (!space.formats.includes(format)) throw new Error(`Provider.hosted: the server's space does not make ${format}`);
302
- const quality = Option.fromNullishOr(options.quality);
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}`);
304
- const encodeVariant = Schema.encodeOption(space.schema);
305
- return {
306
- space,
307
- widths: space.widths,
308
- sources,
309
- fallback,
310
- url: (asset, { width, encoding }) => {
311
- if (encoding === "auto") return Option.none();
312
- return Option.map(encodeVariant({
313
- width,
314
- format: encoding,
315
- quality
316
- }), (variant) => baseUrl + PATH.replace(":hash", asset.hash.value).replace(":variant", variant));
317
- }
318
- };
319
- };
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 };
321
-
322
- //# sourceMappingURL=index.mjs.map