foldkit-media 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +95 -58
  2. package/client.d.ts +2 -2
  3. package/dist/{asset-BNQ_j5tO.d.mts → asset-Dlkss5qp.d.mts} +32 -3
  4. package/dist/asset-Dlkss5qp.d.mts.map +1 -0
  5. package/dist/browser/index.d.mts +1 -1
  6. package/dist/browser/index.mjs +1 -1
  7. package/dist/cloudflare/index.d.mts +7 -6
  8. package/dist/cloudflare/index.d.mts.map +1 -1
  9. package/dist/cloudflare/index.mjs +11 -5
  10. package/dist/cloudflare/index.mjs.map +1 -1
  11. package/dist/{describe-DdYvLhMY.d.mts → describe-CivKHl4x.d.mts} +2 -2
  12. package/dist/{describe-DdYvLhMY.d.mts.map → describe-CivKHl4x.d.mts.map} +1 -1
  13. package/dist/{describe-Cqr63Gxa.mjs → describe-h9F5stgR.mjs} +5 -2
  14. package/dist/describe-h9F5stgR.mjs.map +1 -0
  15. package/dist/index.d.mts +10 -9
  16. package/dist/index.d.mts.map +1 -1
  17. package/dist/index.mjs +11 -9
  18. package/dist/index.mjs.map +1 -1
  19. package/dist/{provider-DztvQjOr.d.mts → provider-g0Vlvlrb.d.mts} +19 -13
  20. package/dist/provider-g0Vlvlrb.d.mts.map +1 -0
  21. package/dist/server/index.d.mts +33 -15
  22. package/dist/server/index.d.mts.map +1 -1
  23. package/dist/server/index.mjs +172 -2
  24. package/dist/server/index.mjs.map +1 -1
  25. package/dist/{services-Ck-7dhIP.d.mts → services-8_h0ubLB.d.mts} +2 -2
  26. package/dist/{services-Ck-7dhIP.d.mts.map → services-8_h0ubLB.d.mts.map} +1 -1
  27. package/dist/sharp/index.d.mts +2 -2
  28. package/dist/sharp/index.mjs +1 -1
  29. package/dist/{upload-C5YM5jZR.mjs → stores-BtmSl8X3.mjs} +61 -203
  30. package/dist/stores-BtmSl8X3.mjs.map +1 -0
  31. package/dist/unpic/index.d.mts +1 -1
  32. package/dist/{upload-C4_inwfv.d.mts → upload-kp0_oK76.d.mts} +10 -10
  33. package/dist/{upload-C4_inwfv.d.mts.map → upload-kp0_oK76.d.mts.map} +1 -1
  34. package/dist/vite/index.mjs +3 -3
  35. package/dist/vite/index.mjs.map +1 -1
  36. package/package.json +1 -1
  37. package/dist/asset-BNQ_j5tO.d.mts.map +0 -1
  38. package/dist/describe-Cqr63Gxa.mjs.map +0 -1
  39. package/dist/provider-DztvQjOr.d.mts.map +0 -1
  40. package/dist/upload-C5YM5jZR.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["Widths.standard"],"sources":["../../src/vite/images.ts","../../src/vite/index.ts"],"sourcesContent":["/**\n * Images as imports: `import hero from './hero.jpg?image'` gives `{ asset,\n * provider }`, ready for `Picture.derive` or `foldkit-mixins-ui`'s `Image.view`.\n * The build reads the file's facts once (`describe`, through sharp), writes a\n * file for each ladder width up to the original's own in each format, and\n * names them by content, so a host may keep them for good. The development\n * server makes the same variants when a page asks for them.\n */\nimport { createHash, randomUUID } from 'node:crypto'\nimport { mkdir, readFile, rename, writeFile } from 'node:fs/promises'\nimport { availableParallelism } from 'node:os'\nimport { join, relative, sep } from 'node:path'\nimport { Cause, Effect, Exit, Layer, ManagedRuntime, Option, Schema, Semaphore } from 'effect'\nimport type { Plugin } from 'vite'\nimport { ImageAsset } from '../asset.js'\nimport type { Format } from '../format.js'\nimport type { Variant } from '../variant.js'\nimport * as Widths from '../widths.js'\nimport { describe, type Inspector } from '../describe.js'\nimport { Transformer } from '../server/services.js'\n\nconst QUERY = 'image'\n// The kept facts' and variants' generation: raised when what `describe` reads or the encoder\n// makes changes, so every build re-reads once, and one that changes neither encodes nothing\n// again. sharp's own version is not in it: a patch release would re-encode every AVIF for\n// nothing anyone sees. r2: an original is read as its EXIF orientation shows it.\nconst CACHE_REVISION = 'r2'\nconst DEV_PREFIX = '/@foldkit-media/image/'\nconst DEV_PATH = /^\\/@foldkit-media\\/image\\/([0-9a-f]{64})\\/w(\\d+)\\.(avif|webp|jpeg|png)$/\n\nexport interface ImagesOptions {\n /** The widths offered, up to each original's own: `Widths.standard` unless given. */\n readonly widths?: Widths.Widths | undefined\n /** Formats offered as `source`s, most preferred first: `['avif']` unless given. */\n readonly sources?: ReadonlyArray<Format> | undefined\n /** The `img`'s own format: `webp` unless given. */\n readonly fallback?: Format | undefined\n /** The encoder's quality, 1 to 100; its own default unless given. */\n readonly quality?: number | undefined\n}\n\ntype Media = ManagedRuntime.ManagedRuntime<Inspector | Transformer, never>\n\n/** The widths a build writes of an original: the ladder's below its own, then its own. */\nconst widthsFor = (ladder: Widths.Widths, width: number): ReadonlyArray<number> => [\n ...ladder.values.filter(value => value < width),\n width,\n]\n\n/**\n * Keeps `bytes` at `file` whole or not at all: written beside it, then moved in, so a build\n * stopped halfway leaves no cut-short file that a later build would trust.\n */\nconst keep = async (file: string, bytes: Uint8Array | string) => {\n const partial = `${file}.${randomUUID()}.partial`\n await writeFile(partial, bytes)\n await rename(partial, file)\n}\n\nconst run = async <A, E>(\n media: Media,\n effect: Effect.Effect<A, E, Inspector | Transformer>,\n what: string,\n) => {\n const exit = await media.runPromiseExit(effect)\n if (Exit.isSuccess(exit)) return exit.value\n throw new Error(`foldkit-media/vite: ${what}: ${Cause.pretty(exit.cause)}`)\n}\n\n/**\n * The plugin: an import with `?image` becomes the image's facts and a\n * provider over its variants. sharp is read on the first such import, so an\n * application that imports none needs no sharp.\n */\nexport const images = (options: ImagesOptions = {}): Plugin => {\n const ladder = options.widths ?? Widths.standard\n const sources = options.sources ?? ['avif']\n const fallback = options.fallback ?? 'webp'\n const formats = [...new Set([...sources, fallback])]\n const quality = Option.fromNullishOr(options.quality)\n if (\n Option.isSome(quality) &&\n !(Number.isInteger(quality.value) && quality.value >= 1 && quality.value <= 100)\n ) {\n throw new Error(\n `foldkit-media/vite: a quality is a whole number from 1 to 100, not ${quality.value}.`,\n )\n }\n\n let root = process.cwd()\n let cache = join(root, 'node_modules', '.vite', 'foldkit-media', CACHE_REVISION)\n let serving = false\n /** The originals the development server has been asked to vary, by content hash. */\n const originals = new Map<\n string,\n { readonly bytes: Uint8Array<ArrayBuffer>; readonly widths: ReadonlyArray<number> }\n >()\n\n // Each read decodes a whole original, and a build loads every import at once: as many at a\n // time as there are cores, as the Transformer's own bound.\n const inspecting = Semaphore.makeUnsafe(availableParallelism())\n let media: Promise<Media> | undefined\n const mediaOf = () =>\n (media ??= import('../sharp/index.js').then(\n ({ inspectorSharp, transformerSharp }) =>\n ManagedRuntime.make(Layer.mergeAll(inspectorSharp(), transformerSharp())),\n cause => {\n throw new Error(\n `foldkit-media/vite: a ?image import needs sharp; add it to the application. (${String(cause)})`,\n )\n },\n ))\n\n const factsOf = async (\n key: string,\n bytes: Uint8Array<ArrayBuffer>,\n hash: string,\n ): Promise<ImageAsset> => {\n const file = join(cache, hash, 'asset.json')\n try {\n return Schema.decodeUnknownSync(ImageAsset)({\n ...JSON.parse(await readFile(file, 'utf8')),\n key,\n })\n } catch {\n // Not kept yet, or kept by an older version: the facts are made again, as a cache's are.\n const asset = await run(\n await mediaOf(),\n Semaphore.withPermit(inspecting)(describe(key, bytes)),\n `${key} could not be read`,\n )\n await mkdir(join(cache, hash), { recursive: true })\n await keep(file, JSON.stringify(Schema.encodeSync(ImageAsset)(asset)))\n return asset\n }\n }\n\n const variantOf = async (\n key: string,\n bytes: Uint8Array<ArrayBuffer>,\n hash: string,\n width: number,\n format: Format,\n ): Promise<Uint8Array<ArrayBuffer>> => {\n const name = `w${width}${Option.match(quality, { onNone: () => '', onSome: q => `q${q}` })}.${format}`\n const file = join(cache, hash, name)\n try {\n return new Uint8Array(await readFile(file))\n } catch {\n // Not kept yet: made, and kept for the next build.\n const variant: Variant = { width, format, quality }\n const made = await run(\n await mediaOf(),\n Transformer.use(transformer =>\n transformer.transform(\n { body: new Blob([bytes]).stream(), size: bytes.byteLength },\n variant,\n ),\n ),\n `${key} could not be made ${width} wide in ${format}`,\n )\n await mkdir(join(cache, hash), { recursive: true })\n await keep(file, made.bytes)\n return made.bytes\n }\n }\n\n return {\n name: 'foldkit-media:images',\n // Before Vite's own asset handling, which takes a `.jpg` import of any query as a URL.\n enforce: 'pre',\n configResolved(config) {\n root = config.root\n cache = join(config.cacheDir, 'foldkit-media', CACHE_REVISION)\n serving = config.command === 'serve'\n },\n async load(id) {\n const [file, query] = id.split('?')\n if (query === undefined || !new URLSearchParams(query).has(QUERY)) return undefined\n const bytes = new Uint8Array(await readFile(file!))\n const hash = createHash('sha256').update(bytes).digest('hex')\n const key = relative(root, file!).split(sep).join('/')\n const asset = await factsOf(key, bytes, hash)\n const widths = widthsFor(ladder, asset.width)\n if (serving) originals.set(hash, { bytes, widths })\n const stem = key\n .split('/')\n .pop()!\n .replace(/\\.[^.]+$/, '')\n // Made together: the Transformer bounds how many run at once, and AVIF is slow one by one.\n const files = await Promise.all(\n widths.flatMap(width =>\n formats.map(async format => {\n let url: string\n if (serving) {\n url = JSON.stringify(`${DEV_PREFIX}${hash}/w${width}.${format}`)\n } else {\n const source = await variantOf(key, bytes, hash, width, format)\n const contentHash = createHash('sha256').update(source).digest('hex')\n url = `import.meta.ROLLUP_FILE_URL_${this.emitFile({\n type: 'asset',\n fileName: `${stem}-${width}-${contentHash}.${format}`,\n source,\n })}`\n }\n return `{ width: ${width}, format: ${JSON.stringify(format)}, url: ${url} }`\n }),\n ),\n )\n return [\n `import { Schema } from 'effect'`,\n `import { ImageAsset, Provider } from 'foldkit-media'`,\n `export default {`,\n ` asset: Schema.decodeUnknownSync(ImageAsset)(${JSON.stringify(Schema.encodeSync(ImageAsset)(asset))}),`,\n ` provider: Provider.fromFiles([${files.join(', ')}], ${JSON.stringify({ sources, fallback })}),`,\n `}`,\n ].join('\\n')\n },\n configureServer(server) {\n server.middlewares.use((request, response, next) => {\n const match = DEV_PATH.exec(request.url?.split('?')[0] ?? '')\n if (match === null) return next()\n const [, hash, width, asked] = match\n const original = originals.get(hash!)\n const format = formats.find(offered => offered === asked)\n if (\n original === undefined ||\n format === undefined ||\n !original.widths.includes(Number(width))\n ) {\n response.statusCode = 404\n return response.end()\n }\n variantOf(hash!, original.bytes, hash!, Number(width), format).then(bytes => {\n response.setHeader('Content-Type', `image/${format}`)\n response.setHeader('Cache-Control', 'no-store')\n response.end(bytes)\n }, next)\n })\n },\n }\n}\n","/**\n * Icons as imports: `import { arrowLeft } from 'virtual:foldkit-icons/lucide'`\n * gives the icon's `IconData`, read from an Iconify set or a folder of the\n * application's own SVG files when the build reads the import. The import is\n * the selection, and the bundler drops what nothing imports. A declaration\n * file names every icon of every set, so a misspelt name is a type error.\n */\nimport { readdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { extname, isAbsolute, join, relative, resolve } from 'node:path'\nimport { Schema } from 'effect'\nimport type { Plugin } from 'vite'\nimport type { IconData } from '../icon.js'\nimport { fromIconify, IconifySet, namesOf, parse } from '../icons/index.js'\n\nconst PREFIX = 'virtual:foldkit-icons/'\n// Rollup's mark for a module no file holds, which other plugins leave alone.\nconst RESOLVED = `${String.fromCharCode(0)}${PREFIX}`\nconst SET_NAME = /^[a-z0-9]+(-[a-z0-9]+)*$/\n\nexport interface IconsOptions {\n /** Iconify sets by prefix (`lucide`, `uil`), each read from the application's `@iconify-json/<prefix>`. */\n readonly iconify?: ReadonlyArray<string> | undefined\n /** The application's own sets: a name, and a folder whose SVG files are its icons, each named by its file. */\n readonly folders?: Readonly<Record<string, string>> | undefined\n /** Where the declaration of every set is written, from the root: `foldkit-icons.d.ts` unless given; `false` writes none. */\n readonly dts?: string | false | undefined\n}\n\n/** An icon set ready to be a module: each icon under the name it is imported by. */\ninterface ReadSet {\n readonly icons: ReadonlyArray<readonly [exported: string, icon: IconData]>\n /** The icons of an Iconify set the parser refused, and why: left out, so importing one fails. */\n readonly refused: ReadonlyArray<readonly [name: string, reason: string]>\n}\n\n/** `arrow-left` is `arrowLeft`, and `1-circle` `_1Circle`; JavaScript's reserved words export as they are. */\nexport const exportName = (name: string): string => {\n const camel = name.replace(/[-_:.]+([a-zA-Z0-9])/g, (_, next: string) => next.toUpperCase())\n return /^[0-9]/.test(camel) ? `_${camel}` : camel\n}\n\nconst named = (\n set: string,\n entries: ReadonlyArray<readonly [name: string, icon: IconData]>,\n): ReadSet['icons'] => {\n const seen = new Map<string, string>()\n return entries.map(([name, icon]) => {\n const exported = exportName(name)\n if (!/^[A-Za-z_$][\\w$]*$/.test(exported)) {\n throw new Error(`foldkit-media/vite: the icon \"${set}:${name}\" has no name to import it by.`)\n }\n const earlier = seen.get(exported)\n if (earlier !== undefined) {\n throw new Error(\n `foldkit-media/vite: the icons \"${set}:${earlier}\" and \"${set}:${name}\" would both be imported as ${exported}.`,\n )\n }\n seen.set(exported, name)\n return [exported, icon] as const\n })\n}\n\nconst moduleOf = ({ icons }: ReadSet): string =>\n [\n ...icons.map(([, icon], at) => `const i${at} = ${JSON.stringify(icon)}`),\n `export { ${icons.map(([exported], at) => `i${at} as ${exported}`).join(', ')} }`,\n ].join('\\n')\n\nconst declarationOf = (sets: ReadonlyMap<string, ReadSet>): string =>\n [\n '// Written by foldkit-media/vite from the icon sets it is given. Do not edit.',\n ...[...sets].map(([name, { icons, refused }]) =>\n [\n `declare module '${PREFIX}${name}' {`,\n \" import type { IconData } from 'foldkit-media'\",\n ...refused.map(\n ([icon, reason]) => ` // Left out, ${icon}: ${reason.replace(/\\s+/g, ' ')}`,\n ),\n ...icons.map((_, at) => ` const i${at}: IconData`),\n ` export { ${icons.map(([exported], at) => `i${at} as ${exported}`).join(', ')} }`,\n '}',\n ].join('\\n'),\n ),\n '',\n ].join('\\n')\n\n/**\n * The plugin: give it the sets the application imports from. An SVG in a\n * folder that the parser refuses fails the build, naming the file; an icon of\n * an Iconify set that it refuses is left out of the set, and its declaration\n * says why, so only importing that icon fails.\n */\nexport const icons = (options: IconsOptions = {}): Plugin => {\n const iconify = options.iconify ?? []\n const folders = Object.entries(options.folders ?? {})\n for (const name of [...iconify, ...folders.map(([name]) => name)]) {\n if (!SET_NAME.test(name)) {\n throw new Error(\n `foldkit-media/vite: \"${name}\" is not a set name (lowercase words and hyphens).`,\n )\n }\n }\n const twice = [...iconify, ...folders.map(([name]) => name)].find(\n (name, at, all) => all.indexOf(name) !== at,\n )\n if (twice !== undefined) throw new Error(`foldkit-media/vite: the set \"${twice}\" is given twice.`)\n\n let root = process.cwd()\n const read = new Map<string, ReadSet>()\n const folderDirs = new Map(folders)\n const folderOf = (name: string) => resolve(root, folderDirs.get(name)!)\n\n const readIconify = (prefix: string): ReadSet => {\n const require = createRequire(join(root, 'package.json'))\n let file: string\n try {\n file = require.resolve(`@iconify-json/${prefix}/icons.json`)\n } catch {\n throw new Error(\n `foldkit-media/vite: the Iconify set \"${prefix}\" is not installed: add @iconify-json/${prefix}.`,\n )\n }\n let set: IconifySet\n try {\n set = Schema.decodeUnknownSync(IconifySet)(JSON.parse(readFileSync(file, 'utf8')))\n } catch (error) {\n throw new Error(\n `foldkit-media/vite: ${file} is not an Iconify set: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n const icons: Array<readonly [string, IconData]> = []\n const refused: Array<readonly [string, string]> = []\n for (const name of namesOf(set)) {\n try {\n icons.push([name, fromIconify(set, name)])\n } catch (error) {\n refused.push([name, error instanceof Error ? error.message : String(error)])\n }\n }\n return { icons: named(prefix, icons), refused }\n }\n\n const readFolder = (name: string): ReadSet => {\n const folder = folderOf(name)\n const files = readdirSync(folder)\n .filter(file => extname(file) === '.svg')\n .sort()\n return {\n icons: named(\n name,\n files.map(file => {\n const path = join(folder, file)\n return [\n file.slice(0, -4),\n parse(readFileSync(path, 'utf8'), relative(root, path)),\n ] as const\n }),\n ),\n refused: [],\n }\n }\n\n const setOf = (name: string): ReadSet => {\n const known = read.get(name)\n if (known !== undefined) return known\n const made = iconify.includes(name) ? readIconify(name) : readFolder(name)\n read.set(name, made)\n return made\n }\n\n const all = () => [...iconify, ...folders.map(([name]) => name)]\n\n const writeDeclaration = () => {\n if (options.dts === false) return\n const path = resolve(root, options.dts ?? 'foldkit-icons.d.ts')\n const text = declarationOf(new Map(all().map(name => [name, setOf(name)])))\n let current: string | undefined\n try {\n current = readFileSync(path, 'utf8')\n } catch {\n current = undefined\n }\n // Written only when it changes, so a watcher on the file does not see a write of every build.\n if (current !== text) writeFileSync(path, text)\n }\n\n return {\n name: 'foldkit-media:icons',\n configResolved(config) {\n root = config.root\n },\n buildStart() {\n read.clear()\n writeDeclaration()\n for (const [name] of folders) this.addWatchFile(folderOf(name))\n },\n resolveId(id) {\n if (!id.startsWith(PREFIX)) return undefined\n const name = id.slice(PREFIX.length)\n if (!all().includes(name)) {\n throw new Error(\n `foldkit-media/vite: there is no icon set \"${name}\"; the sets given are ${all().join(', ') || 'none'}.`,\n )\n }\n return `${RESOLVED}${name}`\n },\n load(id) {\n if (!id.startsWith(RESOLVED)) return undefined\n const name = id.slice(RESOLVED.length)\n if (folders.some(([folder]) => folder === name)) {\n for (const file of readdirSync(folderOf(name)))\n this.addWatchFile(join(folderOf(name), file))\n }\n return moduleOf(setOf(name))\n },\n configureServer(server) {\n const dirs = folders.map(([name]) => [name, folderOf(name)] as const)\n server.watcher.add(dirs.map(([, dir]) => dir))\n server.watcher.on('all', (_, file) => {\n const changed = dirs.find(([, dir]) => {\n const path = relative(dir, file)\n return !isAbsolute(path) && !path.startsWith('..')\n })\n if (changed === undefined || extname(file) !== '.svg') return\n read.delete(changed[0])\n try {\n writeDeclaration()\n } catch (error) {\n // A throw here would end the server; the set's next load fails with it, where the page shows it.\n server.config.logger.error(error instanceof Error ? error.message : String(error))\n }\n for (const environment of Object.values(server.environments)) {\n const module = environment.moduleGraph.getModuleById(`${RESOLVED}${changed[0]}`)\n if (module !== undefined) environment.moduleGraph.invalidateModule(module)\n }\n server.ws.send({ type: 'full-reload' })\n })\n },\n }\n}\n\nexport { images, type ImagesOptions } from './images.js'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAqBA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ACD,IAAI,YAAY,KAAA,KAAa,QAAQ,IAAI,MAAM,QAAQ;IACvD,KAAK,OAAO,QAAQ,EAAE;IACtB,IAAI;KACF,iBAAiB;IACnB,SAAS,OAAO;KAEd,OAAO,OAAO,OAAO,MAAM,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;IACnF;IACA,KAAK,MAAM,eAAe,OAAO,OAAO,OAAO,YAAY,GAAG;KAC5D,MAAM,SAAS,YAAY,YAAY,cAAc,GAAG,WAAW,QAAQ,IAAI;KAC/E,IAAI,WAAW,KAAA,GAAW,YAAY,YAAY,iBAAiB,MAAM;IAC3E;IACA,OAAO,GAAG,KAAK,EAAE,MAAM,cAAc,CAAC;GACxC,CAAC;EACH;CACF;AACF"}
1
+ {"version":3,"file":"index.mjs","names":["Widths.standard"],"sources":["../../src/vite/images.ts","../../src/vite/index.ts"],"sourcesContent":["/**\n * Images as imports: `import hero from './hero.jpg?image'` gives `{ asset,\n * provider }`, ready for `Picture.derive` or `foldkit-mixins-ui`'s `Image.view`.\n * The build reads the file's facts once (`describe`, through sharp), writes a\n * file for each ladder width up to the original's own in each format, and\n * names them by content, so a host may keep them for good. The development\n * server makes the same variants when a page asks for them.\n */\nimport { createHash, randomUUID } from 'node:crypto'\nimport { mkdir, readFile, rename, writeFile } from 'node:fs/promises'\nimport { availableParallelism } from 'node:os'\nimport { join, relative, sep } from 'node:path'\nimport { Cause, Effect, Exit, Layer, ManagedRuntime, Option, Schema, Semaphore } from 'effect'\nimport type { Plugin } from 'vite'\nimport { ImageAsset } from '../asset.js'\nimport type { Format } from '../format.js'\nimport type { Variant } from '../variant.js'\nimport * as Widths from '../widths.js'\nimport { describe, type Inspector } from '../describe.js'\nimport { Transformer } from '../server/services.js'\n\nconst QUERY = 'image'\n// The kept facts' and variants' generation: raised when what `describe` reads or the encoder\n// makes changes, so every build re-reads once, and one that changes neither encodes nothing\n// again. sharp's own version is not in it: a patch release would re-encode every AVIF for\n// nothing anyone sees. r2: an original is read as its EXIF orientation shows it.\nconst CACHE_REVISION = 'r2'\nconst DEV_PREFIX = '/@foldkit-media/image/'\nconst DEV_PATH = /^\\/@foldkit-media\\/image\\/([0-9a-f]{64})\\/w(\\d+)\\.(avif|webp|jpeg|png)$/\n\nexport interface ImagesOptions {\n /** The widths offered, up to each original's own: `Widths.standard` unless given. */\n readonly widths?: Widths.Widths | undefined\n /** Formats offered as `source`s, most preferred first: `['avif']` unless given. */\n readonly sources?: ReadonlyArray<Format> | undefined\n /** The `img`'s own format: `webp` unless given. */\n readonly fallback?: Format | undefined\n /** The encoder's quality, 1 to 100; its own default unless given. */\n readonly quality?: number | undefined\n}\n\ntype Media = ManagedRuntime.ManagedRuntime<Inspector | Transformer, never>\n\n/** The widths a build writes of an original: the ladder's below its own, then its own. */\nconst widthsFor = (ladder: Widths.Widths, width: number): ReadonlyArray<number> => [\n ...ladder.values.filter(value => value < width),\n width,\n]\n\n/**\n * Keeps `bytes` at `file` whole or not at all: written beside it, then moved in, so a build\n * stopped halfway leaves no cut-short file that a later build would trust.\n */\nconst keep = async (file: string, bytes: Uint8Array | string) => {\n const partial = `${file}.${randomUUID()}.partial`\n await writeFile(partial, bytes)\n await rename(partial, file)\n}\n\nconst run = async <A, E>(\n media: Media,\n effect: Effect.Effect<A, E, Inspector | Transformer>,\n what: string,\n) => {\n const exit = await media.runPromiseExit(effect)\n if (Exit.isSuccess(exit)) return exit.value\n throw new Error(`foldkit-media/vite: ${what}: ${Cause.pretty(exit.cause)}`)\n}\n\n/**\n * The plugin: an import with `?image` becomes the image's facts and a\n * provider over its variants. sharp is read on the first such import, so an\n * application that imports none needs no sharp.\n */\nexport const images = (options: ImagesOptions = {}): Plugin => {\n const ladder = options.widths ?? Widths.standard\n const sources = options.sources ?? ['avif']\n const fallback = options.fallback ?? 'webp'\n const formats = [...new Set([...sources, fallback])]\n const quality = Option.fromNullishOr(options.quality)\n if (\n Option.isSome(quality) &&\n !(Number.isInteger(quality.value) && quality.value >= 1 && quality.value <= 100)\n ) {\n throw new Error(\n `foldkit-media/vite: a quality is a whole number from 1 to 100, not ${quality.value}.`,\n )\n }\n\n let root = process.cwd()\n let cache = join(root, 'node_modules', '.vite', 'foldkit-media', CACHE_REVISION)\n let serving = false\n /** The originals the development server has been asked to vary, by content hash. */\n const originals = new Map<\n string,\n { readonly bytes: Uint8Array<ArrayBuffer>; readonly widths: ReadonlyArray<number> }\n >()\n\n // Each read decodes a whole original, and a build loads every import at once: as many at a\n // time as there are cores, as the Transformer's own bound.\n const inspecting = Semaphore.makeUnsafe(availableParallelism())\n let media: Promise<Media> | undefined\n const mediaOf = () =>\n (media ??= import('../sharp/index.js').then(\n ({ inspectorSharp, transformerSharp }) =>\n ManagedRuntime.make(Layer.mergeAll(inspectorSharp(), transformerSharp())),\n cause => {\n throw new Error(\n `foldkit-media/vite: a ?image import needs sharp; add it to the application. (${String(cause)})`,\n )\n },\n ))\n\n const factsOf = async (\n key: string,\n bytes: Uint8Array<ArrayBuffer>,\n hash: string,\n ): Promise<ImageAsset> => {\n const file = join(cache, hash, 'asset.json')\n try {\n return Schema.decodeUnknownSync(ImageAsset)({\n ...JSON.parse(await readFile(file, 'utf8')),\n key,\n })\n } catch {\n // Not kept yet, or kept by an older version: the facts are made again, as a cache's are.\n const asset = await run(\n await mediaOf(),\n Semaphore.withPermit(inspecting)(describe(key, bytes)),\n `${key} could not be read`,\n )\n await mkdir(join(cache, hash), { recursive: true })\n await keep(file, JSON.stringify(Schema.encodeSync(ImageAsset)(asset)))\n return asset\n }\n }\n\n const variantOf = async (\n key: string,\n bytes: Uint8Array<ArrayBuffer>,\n hash: string,\n width: number,\n format: Format,\n ): Promise<Uint8Array<ArrayBuffer>> => {\n const name = `w${width}${Option.match(quality, { onNone: () => '', onSome: q => `q${q}` })}.${format}`\n const file = join(cache, hash, name)\n try {\n return new Uint8Array(await readFile(file))\n } catch {\n // Not kept yet: made, and kept for the next build.\n const variant: Variant = { width, format, quality }\n const made = await run(\n await mediaOf(),\n Transformer.use(transformer =>\n transformer.transform(\n { body: new Blob([bytes]).stream(), size: bytes.byteLength },\n variant,\n ),\n ),\n `${key} could not be made ${width} wide in ${format}`,\n )\n await mkdir(join(cache, hash), { recursive: true })\n await keep(file, made.bytes)\n return made.bytes\n }\n }\n\n return {\n name: 'foldkit-media:images',\n // Before Vite's own asset handling, which takes a `.jpg` import of any query as a URL.\n enforce: 'pre',\n configResolved(config) {\n root = config.root\n cache = join(config.cacheDir, 'foldkit-media', CACHE_REVISION)\n serving = config.command === 'serve'\n },\n async load(id) {\n const [file, query] = id.split('?')\n if (query === undefined || !new URLSearchParams(query).has(QUERY)) return undefined\n const bytes = new Uint8Array(await readFile(file!))\n const hash = createHash('sha256').update(bytes).digest('hex')\n const key = relative(root, file!).split(sep).join('/')\n const asset = await factsOf(key, bytes, hash)\n const widths = widthsFor(ladder, asset.width)\n if (serving) originals.set(hash, { bytes, widths })\n const stem = key\n .split('/')\n .pop()!\n .replace(/\\.[^.]+$/, '')\n // Made together: the Transformer bounds how many run at once, and AVIF is slow one by one.\n const files = await Promise.all(\n widths.flatMap(width =>\n formats.map(async format => {\n let url: string\n if (serving) {\n url = JSON.stringify(`${DEV_PREFIX}${hash}/w${width}.${format}`)\n } else {\n const source = await variantOf(key, bytes, hash, width, format)\n const contentHash = createHash('sha256').update(source).digest('hex')\n url = `import.meta.ROLLUP_FILE_URL_${this.emitFile({\n type: 'asset',\n fileName: `${stem}-${width}-${contentHash}.${format}`,\n source,\n })}`\n }\n return `{ width: ${width}, format: ${JSON.stringify(format)}, url: ${url} }`\n }),\n ),\n )\n return [\n `import { Schema } from 'effect'`,\n `import { HashedAsset, Provider } from 'foldkit-media'`,\n `export default {`,\n ` asset: Schema.decodeUnknownSync(HashedAsset)(${JSON.stringify(Schema.encodeSync(ImageAsset)(asset))}),`,\n ` provider: Provider.fromFiles([${files.join(', ')}], ${JSON.stringify({ sources, fallback })}),`,\n `}`,\n ].join('\\n')\n },\n configureServer(server) {\n server.middlewares.use((request, response, next) => {\n const match = DEV_PATH.exec(request.url?.split('?')[0] ?? '')\n if (match === null) return next()\n const [, hash, width, asked] = match\n const original = originals.get(hash!)\n const format = formats.find(offered => offered === asked)\n if (\n original === undefined ||\n format === undefined ||\n !original.widths.includes(Number(width))\n ) {\n response.statusCode = 404\n return response.end()\n }\n variantOf(hash!, original.bytes, hash!, Number(width), format).then(bytes => {\n response.setHeader('Content-Type', `image/${format}`)\n response.setHeader('Cache-Control', 'no-store')\n response.end(bytes)\n }, next)\n })\n },\n }\n}\n","/**\n * Icons as imports: `import { arrowLeft } from 'virtual:foldkit-icons/lucide'`\n * gives the icon's `IconData`, read from an Iconify set or a folder of the\n * application's own SVG files when the build reads the import. The import is\n * the selection, and the bundler drops what nothing imports. A declaration\n * file names every icon of every set, so a misspelt name is a type error.\n */\nimport { readdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { extname, isAbsolute, join, relative, resolve } from 'node:path'\nimport { Schema } from 'effect'\nimport type { Plugin } from 'vite'\nimport type { IconData } from '../icon.js'\nimport { fromIconify, IconifySet, namesOf, parse } from '../icons/index.js'\n\nconst PREFIX = 'virtual:foldkit-icons/'\n// Rollup's mark for a module no file holds, which other plugins leave alone.\nconst RESOLVED = `${String.fromCharCode(0)}${PREFIX}`\nconst SET_NAME = /^[a-z0-9]+(-[a-z0-9]+)*$/\n\nexport interface IconsOptions {\n /** Iconify sets by prefix (`lucide`, `uil`), each read from the application's `@iconify-json/<prefix>`. */\n readonly iconify?: ReadonlyArray<string> | undefined\n /** The application's own sets: a name, and a folder whose SVG files are its icons, each named by its file. */\n readonly folders?: Readonly<Record<string, string>> | undefined\n /** Where the declaration of every set is written, from the root: `foldkit-icons.d.ts` unless given; `false` writes none. */\n readonly dts?: string | false | undefined\n}\n\n/** An icon set ready to be a module: each icon under the name it is imported by. */\ninterface ReadSet {\n readonly icons: ReadonlyArray<readonly [exported: string, icon: IconData]>\n /** The icons of an Iconify set the parser refused, and why: left out, so importing one fails. */\n readonly refused: ReadonlyArray<readonly [name: string, reason: string]>\n}\n\n/** `arrow-left` is `arrowLeft`, and `1-circle` `_1Circle`; JavaScript's reserved words export as they are. */\nexport const exportName = (name: string): string => {\n const camel = name.replace(/[-_:.]+([a-zA-Z0-9])/g, (_, next: string) => next.toUpperCase())\n return /^[0-9]/.test(camel) ? `_${camel}` : camel\n}\n\nconst named = (\n set: string,\n entries: ReadonlyArray<readonly [name: string, icon: IconData]>,\n): ReadSet['icons'] => {\n const seen = new Map<string, string>()\n return entries.map(([name, icon]) => {\n const exported = exportName(name)\n if (!/^[A-Za-z_$][\\w$]*$/.test(exported)) {\n throw new Error(`foldkit-media/vite: the icon \"${set}:${name}\" has no name to import it by.`)\n }\n const earlier = seen.get(exported)\n if (earlier !== undefined) {\n throw new Error(\n `foldkit-media/vite: the icons \"${set}:${earlier}\" and \"${set}:${name}\" would both be imported as ${exported}.`,\n )\n }\n seen.set(exported, name)\n return [exported, icon] as const\n })\n}\n\nconst moduleOf = ({ icons }: ReadSet): string =>\n [\n ...icons.map(([, icon], at) => `const i${at} = ${JSON.stringify(icon)}`),\n `export { ${icons.map(([exported], at) => `i${at} as ${exported}`).join(', ')} }`,\n ].join('\\n')\n\nconst declarationOf = (sets: ReadonlyMap<string, ReadSet>): string =>\n [\n '// Written by foldkit-media/vite from the icon sets it is given. Do not edit.',\n ...[...sets].map(([name, { icons, refused }]) =>\n [\n `declare module '${PREFIX}${name}' {`,\n \" import type { IconData } from 'foldkit-media'\",\n ...refused.map(\n ([icon, reason]) => ` // Left out, ${icon}: ${reason.replace(/\\s+/g, ' ')}`,\n ),\n ...icons.map((_, at) => ` const i${at}: IconData`),\n ` export { ${icons.map(([exported], at) => `i${at} as ${exported}`).join(', ')} }`,\n '}',\n ].join('\\n'),\n ),\n '',\n ].join('\\n')\n\n/**\n * The plugin: give it the sets the application imports from. An SVG in a\n * folder that the parser refuses fails the build, naming the file; an icon of\n * an Iconify set that it refuses is left out of the set, and its declaration\n * says why, so only importing that icon fails.\n */\nexport const icons = (options: IconsOptions = {}): Plugin => {\n const iconify = options.iconify ?? []\n const folders = Object.entries(options.folders ?? {})\n for (const name of [...iconify, ...folders.map(([name]) => name)]) {\n if (!SET_NAME.test(name)) {\n throw new Error(\n `foldkit-media/vite: \"${name}\" is not a set name (lowercase words and hyphens).`,\n )\n }\n }\n const twice = [...iconify, ...folders.map(([name]) => name)].find(\n (name, at, all) => all.indexOf(name) !== at,\n )\n if (twice !== undefined) throw new Error(`foldkit-media/vite: the set \"${twice}\" is given twice.`)\n\n let root = process.cwd()\n const read = new Map<string, ReadSet>()\n const folderDirs = new Map(folders)\n const folderOf = (name: string) => resolve(root, folderDirs.get(name)!)\n\n const readIconify = (prefix: string): ReadSet => {\n const require = createRequire(join(root, 'package.json'))\n let file: string\n try {\n file = require.resolve(`@iconify-json/${prefix}/icons.json`)\n } catch {\n throw new Error(\n `foldkit-media/vite: the Iconify set \"${prefix}\" is not installed: add @iconify-json/${prefix}.`,\n )\n }\n let set: IconifySet\n try {\n set = Schema.decodeUnknownSync(IconifySet)(JSON.parse(readFileSync(file, 'utf8')))\n } catch (error) {\n throw new Error(\n `foldkit-media/vite: ${file} is not an Iconify set: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n const icons: Array<readonly [string, IconData]> = []\n const refused: Array<readonly [string, string]> = []\n for (const name of namesOf(set)) {\n try {\n icons.push([name, fromIconify(set, name)])\n } catch (error) {\n refused.push([name, error instanceof Error ? error.message : String(error)])\n }\n }\n return { icons: named(prefix, icons), refused }\n }\n\n const readFolder = (name: string): ReadSet => {\n const folder = folderOf(name)\n const files = readdirSync(folder)\n .filter(file => extname(file) === '.svg')\n .sort()\n return {\n icons: named(\n name,\n files.map(file => {\n const path = join(folder, file)\n return [\n file.slice(0, -4),\n parse(readFileSync(path, 'utf8'), relative(root, path)),\n ] as const\n }),\n ),\n refused: [],\n }\n }\n\n const setOf = (name: string): ReadSet => {\n const known = read.get(name)\n if (known !== undefined) return known\n const made = iconify.includes(name) ? readIconify(name) : readFolder(name)\n read.set(name, made)\n return made\n }\n\n const all = () => [...iconify, ...folders.map(([name]) => name)]\n\n const writeDeclaration = () => {\n if (options.dts === false) return\n const path = resolve(root, options.dts ?? 'foldkit-icons.d.ts')\n const text = declarationOf(new Map(all().map(name => [name, setOf(name)])))\n let current: string | undefined\n try {\n current = readFileSync(path, 'utf8')\n } catch {\n current = undefined\n }\n // Written only when it changes, so a watcher on the file does not see a write of every build.\n if (current !== text) writeFileSync(path, text)\n }\n\n return {\n name: 'foldkit-media:icons',\n configResolved(config) {\n root = config.root\n },\n buildStart() {\n read.clear()\n writeDeclaration()\n for (const [name] of folders) this.addWatchFile(folderOf(name))\n },\n resolveId(id) {\n if (!id.startsWith(PREFIX)) return undefined\n const name = id.slice(PREFIX.length)\n if (!all().includes(name)) {\n throw new Error(\n `foldkit-media/vite: there is no icon set \"${name}\"; the sets given are ${all().join(', ') || 'none'}.`,\n )\n }\n return `${RESOLVED}${name}`\n },\n load(id) {\n if (!id.startsWith(RESOLVED)) return undefined\n const name = id.slice(RESOLVED.length)\n if (folders.some(([folder]) => folder === name)) {\n for (const file of readdirSync(folderOf(name)))\n this.addWatchFile(join(folderOf(name), file))\n }\n return moduleOf(setOf(name))\n },\n configureServer(server) {\n const dirs = folders.map(([name]) => [name, folderOf(name)] as const)\n server.watcher.add(dirs.map(([, dir]) => dir))\n server.watcher.on('all', (_, file) => {\n const changed = dirs.find(([, dir]) => {\n const path = relative(dir, file)\n return !isAbsolute(path) && !path.startsWith('..')\n })\n if (changed === undefined || extname(file) !== '.svg') return\n read.delete(changed[0])\n try {\n writeDeclaration()\n } catch (error) {\n // A throw here would end the server; the set's next load fails with it, where the page shows it.\n server.config.logger.error(error instanceof Error ? error.message : String(error))\n }\n for (const environment of Object.values(server.environments)) {\n const module = environment.moduleGraph.getModuleById(`${RESOLVED}${changed[0]}`)\n if (module !== undefined) environment.moduleGraph.invalidateModule(module)\n }\n server.ws.send({ type: 'full-reload'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AAK,IAAI;KAC/B,OAAO,CAAC,WAAW,IAAI,KAAK,CAAC,KAAK,WAAW,IAAI;IACnD,CAAC;IACD,IAAI,YAAY,KAAA,KAAa,QAAQ,IAAI,MAAM,QAAQ;IACvD,KAAK,OAAO,QAAQ,EAAE;IACtB,IAAI;KACF,iBAAiB;IACnB,SAAS,OAAO;KAEd,OAAO,OAAO,OAAO,MAAM,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;IACnF;IACA,KAAK,MAAM,eAAe,OAAO,OAAO,OAAO,YAAY,GAAG;KAC5D,MAAM,SAAS,YAAY,YAAY,cAAc,GAAG,WAAW,QAAQ,IAAI;KAC/E,IAAI,WAAW,KAAA,GAAW,YAAY,YAAY,iBAAiB,MAAM;IAC3E;IACA,OAAO,GAAG,KAAK,EAAE,MAAM,cAAc,CAAC;GACxC,CAAC;EACH;CACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "foldkit-media",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Responsive images for Foldkit Plus: an image is a URL to write, through providers that share one width ladder.",
5
5
  "keywords": [
6
6
  "foldkit",
@@ -1 +0,0 @@
1
- {"version":3,"file":"asset-BNQ_j5tO.d.mts","names":[],"sources":["../src/asset.ts"],"mappings":";;;cAuCa,aAAW,OAAA;;;;;;;;;KAYZ,qBAAqB,YAAY;;cAOhC,OAAK,OAAA;;;;KACN,eAAe,MAAM;;;;;;;;;cAUpB,YAAU,OAAA;;;;;;;;;;;;;;;;;;;;KASX,oBAAoB,WAAW"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"describe-Cqr63Gxa.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 { 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","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,MAA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
1
- {"version":3,"file":"provider-DztvQjOr.d.mts","names":["Widths.Widths","Variant.Space"],"sources":["../src/provider.ts"],"mappings":";;;;;;;;UAOiB;WACN;WACA,UAAU;;;;;;UAOJ;WACN,QAAQA;;WAER,SAAS,cAAc;;WAEvB,UAAU;;WAEV,MAAM,OAAO,YAAY,SAAS,YAAY,OAAO;;;UAI/C;WACN;WACA,QAAQ;WACR;;;;;;;cAQE,YAAS,OACb,cAAc,OAAK;WACN,SAAS,cAAc;WAAkB,UAAU;MACtE;;;;;;;cA2BU,SAAM;;WAGN;WACA,SAASA;;WAET;MAEV;;;;;;;;;cAmCU,SAAM;;WAGN;;WAEA,QAAQC;;WAER,UAAU,cAAc;;WAExB,WAAW;WACX;MAEV"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"upload-C5YM5jZR.mjs","names":["Variant.PATH","DEFAULT_MAX_BYTES","refused","Variant.standard","Variant.ContentHash","Variant.Spelling","Variant.respell","Variant.revisionOf","DEFAULT_MAX_BYTES"],"sources":["../src/server/api.ts","../src/server/headers.ts","../src/server/admission.ts","../src/server/handlers.ts","../src/server/stores.ts","../src/server/facts.ts","../src/server/upload.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 { Schema } from 'effect'\n\n/** Where a variant came from: the edge's cache, the server's store, or made for this request. */\nexport const From = Schema.Literals(['edge', 'store', 'made'])\nexport type From = typeof From.Type\n\n/** Every answer the media server gives, and nothing else: each has its status and its headers. */\nexport const Answer = Schema.TaggedUnion({\n /** A variant's bytes. */\n Variant: { etag: Schema.String, from: From },\n /** The variant the request's `If-None-Match` already holds. */\n NotModified: { etag: Schema.String },\n /**\n * No URL of this server's grammar. A later release may read it (a new format\n * or parameter, in a rollout), so it is kept as briefly as `NotFound`.\n */\n Malformed: {},\n /** No original under the hash: an upload may yet put one there. */\n NotFound: {},\n /**\n * A spelling of the grammar outside this space: another release (the next\n * one, in a rollout) may offer it, so it is kept as briefly as `NotFound`.\n */\n Unoffered: {},\n /**\n * A variant of an earlier revision, made no longer and not kept: its URL now names the\n * current revision's, at `location`. A 302 kept briefly, since a rollback to that revision,\n * or a server of it still in the rollout, answers the old URL again.\n */\n Moved: { location: Schema.String },\n /** The original is larger than the server reads: a server configured to read more may. */\n TooLarge: {},\n /** The transformer failed: perhaps not for good. */\n Failed: {},\n /** The client has had too many variants made lately. */\n RateLimited: { retryAfterSeconds: Schema.Number },\n /** The host's allowance is spent. */\n Exhausted: {},\n /** An upload kept; its facts are the body. */\n Uploaded: {},\n /** The upload policy refused the request. */\n Forbidden: {},\n /** An upload that is not an image the server reads. */\n Unsupported: {},\n /** The facts of an image named by URL; the facts are the body. */\n Described: {},\n /** No facts could be read for that URL: a host not allowed, a read that failed, no image. */\n Unavailable: {},\n})\nexport type Answer = typeof Answer.Type\n\nconst YEAR = 'public, max-age=31536000, immutable'\n\n// What may yet be answered: the browser keeps nothing, and the edge a minute, to blunt a crawler.\nconst BRIEFLY: Readonly<Record<string, string>> = {\n 'cache-control': 'no-store',\n 'cdn-cache-control': 'public, max-age=60',\n}\n\n// Retry a spent allowance after an hour: the host's window is not known here.\nconst EXHAUSTED_RETRY_SECONDS = '3600'\n\n/** The status of each answer. */\nexport const statusOf: (answer: Answer) => number = Answer.match({\n Variant: () => 200,\n NotModified: () => 304,\n Malformed: () => 400,\n NotFound: () => 404,\n Unoffered: () => 404,\n Moved: () => 302,\n TooLarge: () => 413,\n Failed: () => 502,\n RateLimited: () => 429,\n Exhausted: () => 503,\n Uploaded: () => 201,\n Forbidden: () => 403,\n Unsupported: () => 415,\n Described: () => 200,\n Unavailable: () => 422,\n})\n\n/**\n * Every response's headers, decided in one place, so the server, the edge\n * and a static host cannot disagree. A variant's URL names its bytes, so it\n * is kept for a year. A refusal of a variant is not: another release, or the\n * same one configured otherwise, may answer it, so only a CDN keeps it,\n * briefly; a failure is never kept. Every image may be read by a canvas on\n * another origin, and its type is never sniffed.\n */\nexport const headersFor = (answer: Answer): Readonly<Record<string, string>> => ({\n 'x-content-type-options': 'nosniff',\n 'access-control-allow-origin': '*',\n 'cross-origin-resource-policy': 'cross-origin',\n 'timing-allow-origin': '*',\n ...Answer.match(answer, {\n Variant: ({ etag, from }): Record<string, string> => ({\n 'cache-control': YEAR,\n etag,\n 'server-timing': `media;desc=\"${from}\"`,\n }),\n NotModified: ({ etag }): Record<string, string> => ({ 'cache-control': YEAR, etag }),\n Malformed: (): Record<string, string> => BRIEFLY,\n NotFound: (): Record<string, string> => BRIEFLY,\n Unoffered: (): Record<string, string> => BRIEFLY,\n Moved: ({ location }): Record<string, string> => ({ ...BRIEFLY, location }),\n TooLarge: (): Record<string, string> => BRIEFLY,\n Failed: (): Record<string, string> => ({ 'cache-control': 'no-store' }),\n RateLimited: ({ retryAfterSeconds }): Record<string, string> => ({\n 'cache-control': 'no-store',\n 'retry-after': String(retryAfterSeconds),\n }),\n Exhausted: (): Record<string, string> => ({\n 'cache-control': 'no-store',\n 'retry-after': EXHAUSTED_RETRY_SECONDS,\n }),\n // An upload's answers are about one request, and are never kept.\n Uploaded: (): Record<string, string> => ({ 'cache-control': 'no-store' }),\n Forbidden: (): Record<string, string> => ({ 'cache-control': 'no-store' }),\n Unsupported: (): Record<string, string> => ({ 'cache-control': 'no-store' }),\n Described: (): Record<string, string> => ({ 'cache-control': 'no-store' }),\n Unavailable: (): Record<string, string> => ({ 'cache-control': 'no-store' }),\n }),\n})\n\n/** Whether an `If-None-Match` names `etag` (weakly, as a GET compares, or `*`). */\nexport const matches = (ifNoneMatch: string | undefined, etag: string): boolean =>\n ifNoneMatch !== undefined &&\n ifNoneMatch\n .split(',')\n .map(tag => tag.trim().replace(/^W\\//, ''))\n .some(tag => tag === '*' || tag === etag)\n","import { Context, Duration, Effect, Layer, Match, Schema } from 'effect'\nimport { RateLimiter } from 'effect/persistence'\n\n/** The client has made too many variants lately; it may try again after `retryAfterSeconds`. */\nexport class RateLimited extends Schema.TaggedError<RateLimited>()(\n 'RateLimited',\n { retryAfterSeconds: Schema.Number },\n { httpApiStatus: 429 },\n) {}\n\n/**\n * Whether a client may have a variant made now. Asked only on a miss, after\n * the store and before the original is read: a variant already made costs a\n * read, and only making one costs work. Optional: without it, every miss is\n * admitted.\n */\nexport class Admission extends Context.Service<\n Admission,\n { readonly admit: (client: string) => Effect.Effect<void, RateLimited> }\n>()('foldkit-media/Admission') {}\n\n/**\n * Admission through Effect's `RateLimiter`, `limit` misses a client per\n * `window`, over the limiter's store (`RateLimiter.layerStoreMemory` for one\n * process, Redis for several). A store that fails admits the request, logged:\n * a limiter that is down should not take the images down with it.\n */\nexport const admissionRateLimiter = (options: {\n readonly limit: number\n readonly window: Duration.Input\n readonly algorithm?: 'fixed-window' | 'token-bucket'\n}): Layer.Layer<Admission, never, RateLimiter.RateLimiter> =>\n Layer.effect(\n Admission,\n Effect.gen(function* () {\n const limiter = yield* RateLimiter.RateLimiter\n return {\n admit: (client: string) =>\n limiter\n .consume({\n key: `foldkit-media:${client}`,\n limit: options.limit,\n window: options.window,\n algorithm: options.algorithm ?? 'token-bucket',\n onExceeded: 'fail',\n })\n .pipe(\n Effect.asVoid,\n Effect.catch(error =>\n Match.valueTags(error.reason, {\n RateLimitExceeded: ({ retryAfter }) =>\n Effect.fail(\n new RateLimited({\n retryAfterSeconds: Math.max(1, Math.ceil(Duration.toSeconds(retryAfter))),\n }),\n ),\n RateLimitStoreError: () =>\n Effect.logWarning('Media: the rate limiter failed; admitting', error),\n }),\n ),\n ),\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 * 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 /** Every variant this server makes: the same value `Provider.hosted` writes URLs in. */\n readonly space?: Variant.Space\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 for `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 space = Variant.standard,\n maxBytes: requestedMaxBytes = DEFAULT_MAX_BYTES,\n coalesce = false,\n clientOf = defaultClientOf,\n } = options\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\n/**\n * The media server as a Worker's fetch handler, its services from each\n * environment's bindings. It answers its own route and 404s anything else, so\n * route to it by path (`/_image/`).\n */\nexport const serveFetch = <Env extends object>(\n options: Options & {\n /** The services, from the request's bindings. A layer that fails to build answers a 500. */\n readonly layer: (env: Env) => Layer.Layer<Originals | Transformer | Variants, unknown>\n },\n): ((request: Request, env: Env) => Promise<Response>) =>\n fetchOf(env => layer({ coalesce: false, ...options }).pipe(Layer.provide(options.layer(env))))\n","import { Effect, Layer, Option, Schema } from 'effect'\nimport { KeyValueStore } from 'effect/persistence'\nimport { Format, mimeType } from '../format.js'\nimport { OriginalNotFound } from './errors.js'\nimport { Originals, Variants } from './services.js'\n\n// A key ends in its variant's spelling (`<hash>/w640.avif`), which names the format.\nconst mediaTypeOf = (key: string): string => {\n const extension = key.slice(key.lastIndexOf('.') + 1)\n return Schema.is(Format)(extension) ? mimeType(extension) : 'application/octet-stream'\n}\n\n/**\n * `Variants` over a `KeyValueStore`. A variant's bytes are its value and its\n * media type is its key's extension, so nothing else is stored. A store that\n * fails is logged and read as a miss, or a write it drops: a variant is a\n * cache, and the request is answered either way.\n */\nexport const makeVariants = (store: KeyValueStore.KeyValueStore): Variants['Service'] => ({\n get: key =>\n store.getUint8Array(key).pipe(\n Effect.map(bytes =>\n Option.map(Option.fromNullishOr(bytes), value => ({\n encoded: { bytes: new Uint8Array(value), contentType: mediaTypeOf(key) },\n from: 'store' as const,\n })),\n ),\n Effect.catch(error =>\n Effect.logWarning('Media: the variant store failed a read', error).pipe(\n Effect.as(Option.none()),\n ),\n ),\n ),\n put: (key, encoded) =>\n store\n .set(key, encoded.bytes)\n .pipe(\n Effect.catch(error => Effect.logWarning('Media: the variant store failed a write', error)),\n ),\n})\n\n/**\n * Variants kept in the application's `KeyValueStore`, under `prefix`:\n * `KeyValueStore.layerMemory` for tests, `layerFileSystem` on a disk,\n * `layerSql` over SQLite or D1.\n */\nexport const variantsKeyValueStore = (\n options: { readonly prefix?: string } = {},\n): Layer.Layer<Variants, never, KeyValueStore.KeyValueStore> =>\n Layer.effect(\n Variants,\n Effect.gen(function* () {\n const store = yield* KeyValueStore.KeyValueStore\n return makeVariants(KeyValueStore.prefix(store, options.prefix ?? 'variants/'))\n }),\n )\n\n/**\n * Originals in the application's `KeyValueStore`, each under its content\n * hash after `prefix`. A store that fails is a defect, not a missing\n * original: the original is the data, and a 404 would say it is gone.\n */\nexport const originalsKeyValueStore = (\n options: { readonly prefix?: string } = {},\n): Layer.Layer<Originals, never, KeyValueStore.KeyValueStore> =>\n Layer.effect(\n Originals,\n Effect.gen(function* () {\n const store = KeyValueStore.prefix(yield* KeyValueStore.KeyValueStore, options.prefix ?? '')\n return {\n get: (hash: string) =>\n store.getUint8Array(hash).pipe(\n Effect.orDie,\n Effect.flatMap(bytes =>\n bytes === undefined\n ? Effect.fail(new OriginalNotFound({ hash }))\n : Effect.succeed({\n body: new Blob([new Uint8Array(bytes)]).stream(),\n size: bytes.byteLength,\n }),\n ),\n ),\n }\n }),\n )\n","import { Effect, Option, Schema } from 'effect'\nimport type { KeyValueStore } from 'effect/persistence'\nimport { ImageAsset } from '../asset.js'\nimport { describe, type Inspector } from '../describe.js'\nimport { nonNegativeInteger } from '../limits.js'\n\n/** No facts could be read for the image at `url`; `reason` says why, for the build's report. */\nexport class FactsUnavailable extends Schema.TaggedError<FactsUnavailable>()('FactsUnavailable', {\n url: Schema.String,\n reason: Schema.String,\n}) {}\n\nconst Cached = Schema.Struct({\n target: Schema.String,\n etag: Schema.OptionFromNullOr(Schema.String),\n asset: ImageAsset,\n})\nconst CachedJson = Schema.fromJsonString(Cached)\n\n// A redirect chain longer than this is refused, not followed.\nconst MAX_REDIRECTS = 3\n\nconst DEFAULT_MAX_BYTES = 20 * 1024 * 1024\n\nexport interface FactsOptions {\n /** The hosts an original may be read from, matched exactly: `cdn.example.com`, not a suffix. */\n readonly allow: ReadonlyArray<string>\n /** The largest original read, in bytes, counted as it streams. */\n readonly maxBytes?: number\n /** Facts kept by URL and revalidated with the original's `ETag`. */\n readonly cache?: KeyValueStore.KeyValueStore\n /** How to fetch; the platform's `fetch` by default. */\n readonly fetch?: (request: Request) => Promise<Response>\n}\n\n/**\n * The facts of an image a page names only by URL (a rich-text image, a CMS\n * block), so it is drawn with its box and placeholder like any other: its\n * original read from an allowed host and described (`describe`), with the\n * URL as its key. Only `https` on a host in `allow`, at its default port, is read, and every\n * redirect is checked again, so content cannot point the build at an\n * internal address. Kept in `cache`, an unchanged original is asked for\n * with its `ETag` and not read or inspected again.\n */\nexport const factsOf = (\n url: string,\n options: FactsOptions,\n): Effect.Effect<ImageAsset, FactsUnavailable, Inspector> => {\n const unavailable = (reason: string) => new FactsUnavailable({ url, reason })\n const fetchOne = options.fetch ?? ((request: Request) => fetch(request))\n const maxBytes = nonNegativeInteger('maxBytes', options.maxBytes ?? DEFAULT_MAX_BYTES)\n // An allowed host on its own port alone: another port of it is another service.\n const allowed = (target: URL) =>\n target.protocol === 'https:' && target.port === '' && options.allow.includes(target.hostname)\n const cacheKey = `facts/${url}`\n\n const readCached = Option.match(Option.fromNullishOr(options.cache), {\n onNone: () => Effect.succeed(Option.none<typeof Cached.Type>()),\n onSome: store =>\n store.get(cacheKey).pipe(\n Effect.map(text =>\n Option.flatMap(Option.fromNullishOr(text), Schema.decodeUnknownOption(CachedJson)),\n ),\n Effect.catch(() => Effect.succeed(Option.none<typeof Cached.Type>())),\n ),\n })\n\n const request = (cached: Option.Option<typeof Cached.Type>) =>\n Effect.tryPromise({\n try: async () => {\n let target = new URL(url)\n for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {\n if (!allowed(target))\n return { refused: `${target.origin} is not an allowed host` } as const\n const etag = Option.flatMap(cached, entry =>\n entry.target === target.href ? entry.etag : Option.none(),\n )\n const headers = Option.match(etag, {\n onNone: () => ({}),\n onSome: tag => ({ 'if-none-match': tag }),\n })\n const response = await fetchOne(new Request(target, { headers, redirect: 'manual' }))\n const location = response.headers.get('location')\n if (\n response.status < 300 ||\n response.status >= 400 ||\n response.status === 304 ||\n location === null\n ) {\n return { response, target: target.href } as const\n }\n target = new URL(location, target)\n }\n return { refused: `more than ${MAX_REDIRECTS} redirects` } as const\n },\n catch: cause => unavailable(`the fetch failed: ${String(cause)}`),\n })\n\n // Counted as it streams: a missing or false Content-Length does not let a larger body through.\n const bytesOf = (response: Response) =>\n Effect.tryPromise({\n try: async () => {\n const chunks: Array<Uint8Array> = []\n let size = 0\n const reader = response.body?.getReader()\n for (\n let read = await reader?.read();\n read !== undefined && !read.done;\n read = await reader?.read()\n ) {\n size += read.value.byteLength\n if (size > maxBytes) {\n await reader?.cancel()\n return undefined\n }\n chunks.push(read.value)\n }\n const bytes = new Uint8Array(size)\n let at = 0\n for (const chunk of chunks) {\n bytes.set(chunk, at)\n at += chunk.byteLength\n }\n return bytes\n },\n catch: cause => unavailable(`the body could not be read: ${String(cause)}`),\n })\n\n return Effect.gen(function* () {\n const cached = yield* readCached\n const answer = yield* request(cached)\n if ('refused' in answer) return yield* unavailable(answer.refused)\n const { response, target } = answer\n const unchanged = Option.filter(cached, entry => entry.target === target)\n if (response.status === 304 && Option.isSome(unchanged)) return unchanged.value.asset\n if (response.status !== 200)\n return yield* unavailable(`the original answered ${response.status}`)\n const bytes = yield* bytesOf(response)\n if (bytes === undefined)\n return yield* unavailable(`the original is larger than ${maxBytes} bytes`)\n const asset = yield* describe(url, bytes).pipe(\n Effect.mapError(error => unavailable(`the original could not be inspected: ${error._tag}`)),\n )\n const store = options.cache\n if (store !== undefined) {\n const entry = Schema.encodeSync(CachedJson)({\n target,\n etag: Option.fromNullishOr(response.headers.get('etag')),\n asset,\n })\n yield* store.set(cacheKey, entry).pipe(Effect.ignore)\n }\n return asset\n })\n}\n","/**\n * Where an original enters: `POST /_media/upload` takes an image's bytes,\n * reads its facts (`describe`, through the `Inspector`), keeps the bytes\n * under their content hash (`Uploads`), and answers the facts as an\n * `ImageAsset`, for whoever registers them (a CMS's asset row). The bytes\n * travel once, over HTTP; only the facts go on to the application's data.\n */\nimport { Context, Effect, Layer, Option, Schema, Stream } from 'effect'\nimport { HttpServerResponse, type HttpServerRequest } from 'effect/http'\nimport { HttpApi, HttpApiBuilder, HttpApiEndpoint, HttpApiGroup } from 'effect/http-api'\nimport { KeyValueStore } from 'effect/persistence'\nimport { ImageAsset } from '../asset.js'\nimport { describe, type Inspector } from '../describe.js'\nimport { nonNegativeInteger } from '../limits.js'\nimport { fetchOf } from './handlers.js'\nimport { OriginalTooLarge } from './errors.js'\nimport { factsOf, type FactsOptions } from './facts.js'\nimport { Answer, headersFor, statusOf } from './headers.js'\n\n/**\n * Where an original's facts enter, apart from `MediaApi`, so the variant server needs none of\n * its services: an upload, and the facts of an image named by URL.\n */\nexport const UploadApi = HttpApi.make('foldkit-media-upload').add(\n HttpApiGroup.make('uploads').add(\n HttpApiEndpoint.post('upload', '/_media/upload'),\n HttpApiEndpoint.get('facts', '/_media/facts'),\n ),\n)\n\n/** Keeps an uploaded original under its content hash: the one writer of what `Originals` reads. */\nexport class Uploads extends Context.Service<\n Uploads,\n { readonly put: (hash: string, bytes: Uint8Array<ArrayBuffer>) => Effect.Effect<void> }\n>()('foldkit-media/Uploads') {}\n\n/** The request may not upload. Why stays with the policy: the answer says only no. */\nexport class UploadForbidden extends Schema.TaggedError<UploadForbidden>()(\n 'UploadForbidden',\n {},\n { httpApiStatus: 403 },\n) {}\n\n/**\n * Who may upload, asked of every request before its body is read. The route\n * has no default: an application that serves uploads says who may (a\n * `foldkit-guard` policy over the session, an API key), so a server is never\n * open to every upload by omission.\n */\nexport class UploadPolicy extends Context.Service<\n UploadPolicy,\n {\n readonly admit: (\n request: HttpServerRequest.HttpServerRequest,\n ) => Effect.Effect<void, UploadForbidden>\n }\n>()('foldkit-media/UploadPolicy') {}\n\n/** The Cloudflare Images binding reads at most 20 MB; so does the variant server by default. */\nconst DEFAULT_MAX_BYTES = 20 * 1024 * 1024\n\nexport interface UploadOptions {\n /** The largest upload read, in bytes; a larger one is a 413, read no further. */\n readonly maxBytes?: number\n /**\n * How `GET /_media/facts?url=` reads an image named by URL (`factsOf`): the hosts it may\n * fetch from, and a cache. No hosts unless given, so a server names every host it reads.\n */\n readonly facts?: Omit<FactsOptions, 'allow'> & { readonly allow?: ReadonlyArray<string> }\n}\n\nconst answered = (answer: Answer, body: unknown) =>\n HttpServerResponse.jsonUnsafe(body, { status: statusOf(answer), headers: headersFor(answer) })\n\nconst refused = (answer: Answer) => answered(answer, { error: answer._tag })\n\n/** The body, refused past `maxBytes` as it streams: a declared length is the client's to write, so it is not read. */\nconst bodyOf = (request: HttpServerRequest.HttpServerRequest, maxBytes: number) =>\n Effect.gen(function* () {\n const chunks: Array<Uint8Array> = []\n let size = 0\n yield* request.stream.pipe(\n Stream.runForEach(chunk =>\n Effect.suspend(() => {\n size += chunk.byteLength\n if (size > maxBytes) {\n return Effect.fail(new OriginalTooLarge({ size, limit: maxBytes, unit: 'bytes' }))\n }\n chunks.push(chunk)\n return Effect.void\n }),\n ),\n )\n const bytes = new Uint8Array(size)\n let at = 0\n for (const chunk of chunks) {\n bytes.set(chunk, at)\n at += chunk.byteLength\n }\n return bytes\n })\n\n/**\n * The upload route's handler. It asks the `UploadPolicy` first; takes only\n * an `image/*` body, which a browser cannot send to another origin without a\n * preflight this route never answers, so a cookie alone cannot upload from\n * another site; reads at most `maxBytes`; and refuses what the `Inspector`\n * cannot read as an image (415). Its answer is the facts, with the hash as\n * the key, `201`.\n */\nexport const uploadHandlers = (options: UploadOptions = {}) => {\n const maxBytes = nonNegativeInteger('maxBytes', options.maxBytes ?? DEFAULT_MAX_BYTES)\n const encode = Schema.encodeSync(ImageAsset)\n return HttpApiBuilder.group(UploadApi, 'uploads', group =>\n Effect.gen(function* () {\n const uploads = yield* Uploads\n const policy = yield* UploadPolicy\n const services = yield* Effect.context<Inspector>()\n const facts = { ...options.facts, allow: options.facts?.allow ?? [] }\n return group\n .handle('upload', ({ request }) =>\n Effect.gen(function* () {\n yield* policy.admit(request)\n if (!(request.headers['content-type'] ?? '').startsWith('image/')) {\n return refused(Answer.cases.Unsupported.make({}))\n }\n const bytes = yield* bodyOf(request, maxBytes)\n const described = yield* describe('upload', bytes)\n const hash = Option.getOrThrow(described.hash)\n yield* uploads.put(hash, bytes)\n return answered(Answer.cases.Uploaded.make({}), encode({ ...described, key: hash }))\n }).pipe(\n Effect.provide(services),\n Effect.catchTags({\n UploadForbidden: () => Effect.succeed(refused(Answer.cases.Forbidden.make({}))),\n OriginalTooLarge: () => Effect.succeed(refused(Answer.cases.TooLarge.make({}))),\n TransformFailed: () => Effect.succeed(refused(Answer.cases.Unsupported.make({}))),\n // The body broke off or could not be read: the request's fault, not the server's.\n HttpServerError: () => Effect.succeed(refused(Answer.cases.Malformed.make({}))),\n }),\n Effect.withSpan('Media.upload'),\n ),\n )\n .handle('facts', ({ request }) =>\n Effect.gen(function* () {\n yield* policy.admit(request)\n const url = new URL(request.url, 'http://media.invalid').searchParams.get('url')\n if (url === null) return refused(Answer.cases.Malformed.make({}))\n return answered(Answer.cases.Described.make({}), encode(yield* factsOf(url, facts)))\n }).pipe(\n Effect.provide(services),\n Effect.catchTags({\n UploadForbidden: () => Effect.succeed(refused(Answer.cases.Forbidden.make({}))),\n // Why stays in the server: a host refused, a read failed, a file that is no image.\n FactsUnavailable: () => Effect.succeed(refused(Answer.cases.Unavailable.make({}))),\n }),\n Effect.withSpan('Media.facts'),\n ),\n )\n }),\n )\n}\n\n/**\n * The upload route as an Effect HTTP application, registered with the\n * `HttpRouter` beside the variant server's, needing `Uploads`, an\n * `Inspector` and the `UploadPolicy`.\n */\nexport const uploadLayer = (options: UploadOptions = {}) =>\n HttpApiBuilder.layer(UploadApi).pipe(Layer.provide(uploadHandlers(options)))\n\n/**\n * The upload route as a Worker's fetch handler, its services from each\n * environment's bindings (`uploadsR2`, `inspectorImages`, and the\n * application's `UploadPolicy`). Route `/_media/upload` to it.\n */\nexport const serveUploadFetch = <Env extends object>(\n options: UploadOptions & {\n readonly layer: (env: Env) => Layer.Layer<Uploads | Inspector | UploadPolicy, unknown>\n },\n): ((request: Request, env: Env) => Promise<Response>) =>\n fetchOf(env => uploadLayer(options).pipe(Layer.provide(options.layer(env))))\n\n/**\n * Uploads kept in the application's `KeyValueStore`, each under its content\n * hash after `prefix`: the same keys `originalsKeyValueStore` reads, with the\n * same `prefix`. A store that fails is a defect: an upload it dropped is lost.\n */\nexport const uploadsKeyValueStore = (\n options: { readonly prefix?: string } = {},\n): Layer.Layer<Uploads, never, KeyValueStore.KeyValueStore> =>\n Layer.effect(\n Uploads,\n Effect.gen(function* () {\n const store = KeyValueStore.prefix(yield* KeyValueStore.KeyValueStore, options.prefix ?? '')\n return {\n put: (hash: string, bytes: Uint8Array<ArrayBuffer>) =>\n store.set(hash, bytes).pipe(Effect.orDie),\n }\n }),\n )\n"],"mappings":";;;;;;;;;;;;;;;;;AAWA,MAAa,WAAW,QAAQ,KAAK,eAAe,CAAC,CAAC,IACpD,aAAa,KAAK,QAAQ,CAAC,CAAC,IAC1B,gBAAgB,IAAI,WAAWA,MAAc;CAC3C,QAAQ;EAAE,MAAM,OAAO;EAAQ,SAAS,OAAO;CAAO;CACtD,SAAS,cAAc,iBAAiB;AAC1C,CAAC,CACH,CACF;;;;ACfA,MAAa,OAAO,OAAO,SAAS;CAAC;CAAQ;CAAS;AAAM,CAAC;;AAI7D,MAAa,SAAS,OAAO,YAAY;;CAEvC,SAAS;EAAE,MAAM,OAAO;EAAQ,MAAM;CAAK;;CAE3C,aAAa,EAAE,MAAM,OAAO,OAAO;;;;;CAKnC,WAAW,CAAC;;CAEZ,UAAU,CAAC;;;;;CAKX,WAAW,CAAC;;;;;;CAMZ,OAAO,EAAE,UAAU,OAAO,OAAO;;CAEjC,UAAU,CAAC;;CAEX,QAAQ,CAAC;;CAET,aAAa,EAAE,mBAAmB,OAAO,OAAO;;CAEhD,WAAW,CAAC;;CAEZ,UAAU,CAAC;;CAEX,WAAW,CAAC;;CAEZ,aAAa,CAAC;;CAEd,WAAW,CAAC;;CAEZ,aAAa,CAAC;AAChB,CAAC;AAGD,MAAM,OAAO;AAGb,MAAM,UAA4C;CAChD,iBAAiB;CACjB,qBAAqB;AACvB;AAGA,MAAM,0BAA0B;;AAGhC,MAAa,WAAuC,OAAO,MAAM;CAC/D,eAAe;CACf,mBAAmB;CACnB,iBAAiB;CACjB,gBAAgB;CAChB,iBAAiB;CACjB,aAAa;CACb,gBAAgB;CAChB,cAAc;CACd,mBAAmB;CACnB,iBAAiB;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