@yaks/blob 0.0.0-stage → 0.2.36

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 (172) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +946 -2
  3. package/_dist/accepts.d.ts +38 -0
  4. package/_dist/accepts.d.ts.map +1 -0
  5. package/_dist/artifact.d.ts +29 -0
  6. package/_dist/artifact.d.ts.map +1 -0
  7. package/_dist/attachment.d.ts +53 -0
  8. package/_dist/attachment.d.ts.map +1 -0
  9. package/_dist/backend.d.ts +20 -0
  10. package/_dist/backend.d.ts.map +1 -0
  11. package/_dist/broken.d.ts +24 -0
  12. package/_dist/broken.d.ts.map +1 -0
  13. package/_dist/browser.d.ts +27 -0
  14. package/_dist/browser.d.ts.map +1 -0
  15. package/_dist/compare.d.ts +4 -0
  16. package/_dist/compare.d.ts.map +1 -0
  17. package/_dist/content_type.d.ts +20 -0
  18. package/_dist/content_type.d.ts.map +1 -0
  19. package/_dist/graph.d.ts +13 -0
  20. package/_dist/graph.d.ts.map +1 -0
  21. package/_dist/hydrate.d.ts +36 -0
  22. package/_dist/hydrate.d.ts.map +1 -0
  23. package/_dist/identify.d.ts +7 -0
  24. package/_dist/identify.d.ts.map +1 -0
  25. package/_dist/image.d.ts +37 -0
  26. package/_dist/image.d.ts.map +1 -0
  27. package/_dist/keywords.d.ts +10 -0
  28. package/_dist/keywords.d.ts.map +1 -0
  29. package/_dist/mime.d.ts +2 -0
  30. package/_dist/mime.d.ts.map +1 -0
  31. package/_dist/mod.d.ts +97 -0
  32. package/_dist/mod.d.ts.map +1 -0
  33. package/_dist/object-put.d.ts +2 -0
  34. package/_dist/object-put.d.ts.map +1 -0
  35. package/_dist/object.d.ts +175 -0
  36. package/_dist/object.d.ts.map +1 -0
  37. package/_dist/parts.d.ts +91 -0
  38. package/_dist/parts.d.ts.map +1 -0
  39. package/_dist/plugin.d.ts +38 -0
  40. package/_dist/plugin.d.ts.map +1 -0
  41. package/_dist/png.d.ts +14 -0
  42. package/_dist/png.d.ts.map +1 -0
  43. package/_dist/props.d.ts +20 -0
  44. package/_dist/props.d.ts.map +1 -0
  45. package/_dist/representation.d.ts +17 -0
  46. package/_dist/representation.d.ts.map +1 -0
  47. package/_dist/representation_rules.d.ts +3 -0
  48. package/_dist/representation_rules.d.ts.map +1 -0
  49. package/_dist/routes.d.ts +65 -0
  50. package/_dist/routes.d.ts.map +1 -0
  51. package/_dist/serve.d.ts +29 -0
  52. package/_dist/serve.d.ts.map +1 -0
  53. package/_dist/sha256.d.ts +26 -0
  54. package/_dist/sha256.d.ts.map +1 -0
  55. package/_dist/sqlite.d.ts +57 -0
  56. package/_dist/sqlite.d.ts.map +1 -0
  57. package/_dist/store.d.ts +41 -0
  58. package/_dist/store.d.ts.map +1 -0
  59. package/_dist/stream.d.ts +91 -0
  60. package/_dist/stream.d.ts.map +1 -0
  61. package/_dist/upload.d.ts +114 -0
  62. package/_dist/upload.d.ts.map +1 -0
  63. package/_dist/value.d.ts +62 -0
  64. package/_dist/value.d.ts.map +1 -0
  65. package/_dist/vocab.d.ts +13 -0
  66. package/_dist/vocab.d.ts.map +1 -0
  67. package/accepts.js +76 -0
  68. package/accepts.js.map +1 -0
  69. package/accepts.ts +95 -0
  70. package/artifact.js +50 -0
  71. package/artifact.js.map +1 -0
  72. package/artifact.ts +93 -0
  73. package/attachment.js +190 -0
  74. package/attachment.js.map +1 -0
  75. package/attachment.ts +201 -0
  76. package/backend.js +37 -0
  77. package/backend.js.map +1 -0
  78. package/backend.ts +44 -0
  79. package/broken.js +278 -0
  80. package/broken.js.map +1 -0
  81. package/broken.ts +217 -0
  82. package/browser.js +124 -0
  83. package/browser.js.map +1 -0
  84. package/browser.ts +179 -0
  85. package/compare.js +82 -0
  86. package/compare.js.map +1 -0
  87. package/compare.ts +90 -0
  88. package/content_type.js +43 -0
  89. package/content_type.js.map +1 -0
  90. package/content_type.ts +58 -0
  91. package/deno.json +1 -0
  92. package/fixed.js +53 -0
  93. package/fixed.js.map +1 -0
  94. package/fixed.ts +61 -0
  95. package/graph.js +15 -0
  96. package/graph.js.map +1 -0
  97. package/graph.ts +22 -0
  98. package/hydrate.js +69 -0
  99. package/hydrate.js.map +1 -0
  100. package/hydrate.ts +72 -0
  101. package/identify.js +38 -0
  102. package/identify.js.map +1 -0
  103. package/identify.ts +50 -0
  104. package/image.js +111 -0
  105. package/image.js.map +1 -0
  106. package/image.ts +120 -0
  107. package/keywords.js +28 -0
  108. package/keywords.js.map +1 -0
  109. package/keywords.ts +28 -0
  110. package/meta/blob.vocab.json +17 -0
  111. package/mime.js +72 -0
  112. package/mime.js.map +1 -0
  113. package/mime.ts +73 -0
  114. package/mod.js +97 -0
  115. package/mod.js.map +1 -0
  116. package/mod.ts +115 -0
  117. package/object-put.js +90 -0
  118. package/object-put.js.map +1 -0
  119. package/object-put.ts +114 -0
  120. package/object.js +369 -0
  121. package/object.js.map +1 -0
  122. package/object.ts +592 -0
  123. package/package.json +84 -4
  124. package/parts.js +354 -0
  125. package/parts.js.map +1 -0
  126. package/parts.ts +423 -0
  127. package/plugin.js +158 -0
  128. package/plugin.js.map +1 -0
  129. package/plugin.ts +184 -0
  130. package/png.js +74 -0
  131. package/png.js.map +1 -0
  132. package/png.ts +58 -0
  133. package/props.js +32 -0
  134. package/props.js.map +1 -0
  135. package/props.ts +47 -0
  136. package/purge.js +65 -0
  137. package/purge.js.map +1 -0
  138. package/purge.ts +72 -0
  139. package/representation.js +34 -0
  140. package/representation.js.map +1 -0
  141. package/representation.ts +44 -0
  142. package/representation_rules.js +44 -0
  143. package/representation_rules.js.map +1 -0
  144. package/representation_rules.ts +57 -0
  145. package/routes.js +454 -0
  146. package/routes.js.map +1 -0
  147. package/routes.ts +575 -0
  148. package/serve.js +196 -0
  149. package/serve.js.map +1 -0
  150. package/serve.ts +242 -0
  151. package/sha256.js +185 -0
  152. package/sha256.js.map +1 -0
  153. package/sha256.ts +210 -0
  154. package/sqlite.js +201 -0
  155. package/sqlite.js.map +1 -0
  156. package/sqlite.ts +250 -0
  157. package/store.js +40 -0
  158. package/store.js.map +1 -0
  159. package/store.ts +93 -0
  160. package/stream.js +203 -0
  161. package/stream.js.map +1 -0
  162. package/stream.ts +256 -0
  163. package/upload.js +256 -0
  164. package/upload.js.map +1 -0
  165. package/upload.ts +404 -0
  166. package/value.js +234 -0
  167. package/value.js.map +1 -0
  168. package/value.ts +281 -0
  169. package/vocab.js +27 -0
  170. package/vocab.js.map +1 -0
  171. package/vocab.json +123 -0
  172. package/vocab.ts +32 -0
package/routes.ts ADDED
@@ -0,0 +1,575 @@
1
+ // The public byte door. A bare SHA names the bytes as their rows say them
2
+ // now and redirects to an immutable representation; the representation fixes
3
+ // its MIME and name.
4
+ //
5
+ // POST <at> the bytes, their type as `content-type` and
6
+ // their name percent-encoded as `x-yak-name`
7
+ // PUT <at><sha> the same, sent to the address they hash to
8
+ // POST <at><sha> {bytes, name, mime}
9
+ // an upload in parts: where it stands,
10
+ // `{part, need}`, and once nothing is
11
+ // missing it is finished
12
+ // PUT <at><sha>/<n> part n, `x-yak-state` the SHA-256 state the
13
+ // bytes before it leave (./parts.ts)
14
+ // GET <at><sha>[/<eid>] the bytes
15
+ //
16
+ // Every upload answers `{eid, attachment, url, mime, bytes}`, and `w` and `h`
17
+ // for a picture: the address to point a row at, the use naming it
18
+ // (./upload.ts), and where to read it.
19
+ //
20
+ // The address is the name, which is what makes an upload a PUT: the same
21
+ // file sent twice, by two people or by one client retrying, is one stored
22
+ // object and one row, and bytes that do not hash to the address they were
23
+ // sent to are refused. Every call of an upload in parts is safe to send
24
+ // again too, so a page that lost its connection, or its tab, asks where it
25
+ // stands and sends what is missing.
26
+ //
27
+ // Who may upload is the graph's question, never a second one these endpoints
28
+ // ask. An upload first runs its rows against the graph as a check, so
29
+ // whatever refuses that write refuses the upload, and a server with an upload
30
+ // policy writes it as a rule like any other. What is left over is what only
31
+ // the server knows, and those are its options: where the bytes live
32
+ // (`store`), how large one may be (`limit`), what it takes (`accepts`), the
33
+ // room it has (`room`), its bucket's uploads in parts (`parts`) and the words
34
+ // its rows speak (`naming`).
35
+ //
36
+ // The read is fenced by ./serve.ts.
37
+
38
+ import { line } from '@yaks/query'
39
+ import {
40
+ type Authenticate,
41
+ fault,
42
+ json,
43
+ refuse,
44
+ type Route,
45
+ signed,
46
+ } from '@yaks/api'
47
+ import { Pending } from '@yaks/api/log'
48
+ import type { Bundle, Taken } from 'jsr:@yaks/graph@0.2.36'
49
+ import { Stale, status } from '@yaks/graph/errors'
50
+ import { mediaType } from './content_type.js'
51
+ import { contentType } from './identify.js'
52
+ import { mimeOf } from './mime.js'
53
+ import { type Objects, sliceOf } from './object.js'
54
+ import { Gone, type Multipart, parts as inParts, Wrong } from './parts.js'
55
+ import {
56
+ addressed,
57
+ type Representation,
58
+ representation,
59
+ represents,
60
+ } from './representation.js'
61
+ import { type Served, served, servedOpen, servedVia } from './serve.js'
62
+ import type { Blobs } from './store.ts'
63
+ import { bodyOf, HEAD } from './stream.js'
64
+ import {
65
+ admit,
66
+ admitted,
67
+ artifacts,
68
+ described,
69
+ type File,
70
+ type Read,
71
+ roomFor,
72
+ SCOPE,
73
+ servable,
74
+ settled,
75
+ Untaken,
76
+ type Upload,
77
+ useOf,
78
+ } from './upload.js'
79
+
80
+ /** The path the doors answer under where a configuration names none. */
81
+ export let PREFIX = '/blob/'
82
+
83
+ /** The largest upload accepted when the configuration sets no `limit`. */
84
+ export let LIMIT = 25 * 1024 * 1024
85
+
86
+ /** The size of each part an upload in parts goes up in but the last,
87
+ * measured from a box and from a Worker (T-124790). At least 5 MiB, the least
88
+ * R2 takes. */
89
+ export let PART = 8 * 1024 * 1024
90
+
91
+ /** A graph as this door reads and writes it. */
92
+ export type Rows = {
93
+ read: Read
94
+ apply: (
95
+ bundles: Bundle[],
96
+ opts: { check?: boolean; trusted?: boolean },
97
+ ) => Bundle[] | Promise<Bundle[]>
98
+ }
99
+
100
+ /** Where uploads in parts go (./parts.ts): the bucket by name and its
101
+ * multipart uploads, the prefix its objects are kept under (the store's), and
102
+ * the prefix of the ledger of uploads under way. */
103
+ export type InParts = {
104
+ objects: Objects
105
+ bucket: Multipart
106
+ prefix: string
107
+ ledger: string
108
+ /** the size of every part but the last (default {@link PART}) */
109
+ part?: number
110
+ }
111
+
112
+ /** The options a configuration passes to this plugin. */
113
+ export type Options = Omit<Upload, 'store'> & {
114
+ /** the path the doors answer under (default {@link PREFIX}) */
115
+ at?: string
116
+ /** uploads in parts, where the store's bucket takes them */
117
+ parts?: InParts
118
+ /** Let a host incorporate its pending record into the upload transaction. */
119
+ finish?: (request: Request, file: File) => Promise<File>
120
+ /** Whether the representation `eid` of the bytes at `sha` is served, where
121
+ * a host keeps that answer nearer than its graph (default {@link servable}
122
+ * of the graph). */
123
+ served?: (sha: string, eid: string) => Promise<Representation | null>
124
+ /** The bytes at `sha` answering `seek`, a GET or HEAD and its range, where
125
+ * a host reads them through a cache (default: from the store). */
126
+ bytes?: (seek: Request, sha: string) => Promise<Response>
127
+ /** A named byte range in an object shared by several immutable files. */
128
+ slice?: (read: Read, sha: string) => Promise<Slice | null>
129
+ /** A host's alternate representation, served after the original is authorized. */
130
+ variant?: (
131
+ request: Request,
132
+ sha: string,
133
+ source: Served,
134
+ read: (request: Request) => Promise<Response | null>,
135
+ ) => Promise<Response | null>
136
+ /** Let a host report and render a file whose rows exist but whose bytes do not. */
137
+ missing?: (request: Request, error: MissingBlob, answer: Response) => Response
138
+ /** Let a host render an unavailable read for its client. */
139
+ unavailable?: (request: Request, error: unknown, answer: Response) => Response
140
+ /** what the host adds to the failures this door reports */
141
+ tags?: Record<string, string>
142
+ }
143
+
144
+ export type Slice = {
145
+ object: string
146
+ offset: number
147
+ size: number
148
+ mime: string
149
+ }
150
+
151
+ // A refusal in the JSON shape every other endpoint here uses (@yaks/api),
152
+ // with the door's word for it.
153
+ let no = (
154
+ error: string,
155
+ message: string,
156
+ status: number,
157
+ code?: string,
158
+ ): Response => json({ error, message, ...code ? { code } : {} }, status)
159
+
160
+ let missing = () =>
161
+ no('NotFound', 'no object at that address', 404, 'no_such_file')
162
+
163
+ export class MissingBlob extends Error {
164
+ constructor(public sha: string, public mime: string | null | undefined) {
165
+ super(`missing blob ${sha}`)
166
+ }
167
+ }
168
+
169
+ let UNKNOWN = 'application/octet-stream'
170
+
171
+ // What an upload calls its bytes, percent-encoded since a header is ASCII and
172
+ // a file's name is not (@yaks/platform/client.js encodes it).
173
+ let nameOf = (sent: unknown): string => {
174
+ let name = typeof sent == 'string' ? sent : ''
175
+ try {
176
+ return decodeURIComponent(name).slice(0, 200)
177
+ } catch {
178
+ return name.slice(0, 200)
179
+ }
180
+ }
181
+
182
+ // What an upload says its bytes are, as a media type and nothing else, or
183
+ // what its name says. The parameters are dropped and the shape is validated
184
+ // because this string is written into a response header every time the
185
+ // object is read back.
186
+ let typeOf = (declared: unknown, name: string): string => {
187
+ let mime = mediaType(typeof declared == 'string' ? declared : '')
188
+ return mime == UNKNOWN ? mediaType(mimeOf(name)) : mime
189
+ }
190
+
191
+ /** The doors, answering under `options.at` (default {@link PREFIX}), over
192
+ * the host's artifact store, else its blob store. Building a store a
193
+ * configuration names is the host's (./backend.ts), so a host without files,
194
+ * a Worker, never loads the filesystem (./file.ts). */
195
+ export let routes = (
196
+ host: { blobs?: Blobs; graph: Rows; who?: Authenticate; artifacts?: Blobs },
197
+ options: Options = {},
198
+ ): Route[] => {
199
+ let store = host.artifacts ?? host.blobs
200
+ if (!store) {
201
+ console.warn('@yaks/blob: no door — the host keeps no bytes')
202
+ return []
203
+ }
204
+ let at = options.at ?? PREFIX
205
+ let upload: Upload = { ...options, store, limit: options.limit ?? LIMIT }
206
+ let naming = options.naming ?? artifacts
207
+ let scope = options.scope ?? SCOPE
208
+ let read: Read = (query) => host.graph.read(query as Taken)
209
+ let where = (request: Request) => `${request.method} ${PREFIX}*`
210
+ let finish = (request: Request, file: File) =>
211
+ options.finish ? options.finish(request, file) : file
212
+
213
+ // The address and the rest of the path below `at`.
214
+ let below = (request: Request) =>
215
+ new URL(request.url).pathname.slice(at.length).split('/')
216
+
217
+ // Rows written as whoever `host.who` reports is calling, so an upload is
218
+ // attributed the way a write through `/apply` beside it is. Fresh rows each
219
+ // time: `apply` reads and writes the bundles it is given, so the check's
220
+ // must not be the write's. A write the store's log keeps (@yaks/api/log
221
+ // `Pending`) lands when the store recovers, so the upload has not failed.
222
+ let writer = async (request: Request) => {
223
+ let actor = await host.who?.(request) ?? null
224
+ let as = (rows: Bundle[]) => signed(structuredClone(rows), actor)
225
+ return {
226
+ check: (rows: Bundle[]) =>
227
+ host.graph.apply(as(rows), { check: true, trusted: true }),
228
+ write: async (rows: Bundle[]) => {
229
+ try {
230
+ await host.graph.apply(as(rows), { trusted: true })
231
+ } catch (e) {
232
+ if (!(e instanceof Pending)) throw e
233
+ }
234
+ },
235
+ }
236
+ }
237
+
238
+ // What every upload answers.
239
+ let answer = (file: File) => {
240
+ let url = `${at}${file.path}`
241
+ let response = json({
242
+ eid: file.sha,
243
+ attachment: file.use,
244
+ url,
245
+ mime: file.mime,
246
+ bytes: file.bytes,
247
+ ...file.size,
248
+ })
249
+ response.headers.set('location', url)
250
+ return response
251
+ }
252
+
253
+ // Bytes sent whole, streamed as they arrive: the address the caller
254
+ // states, or none.
255
+ let whole = async (request: Request, sha?: string) => {
256
+ let body = bodyOf(request)
257
+ if (body.size === 0 && !sha) {
258
+ return no('Refused', 'an upload is some bytes', 400, 'no_bytes')
259
+ }
260
+ let staged = await admitted(upload, body)
261
+ try {
262
+ if (!staged.size && !sha) {
263
+ return no('Refused', 'an upload is some bytes', 400, 'no_bytes')
264
+ }
265
+ if (sha && staged.sha != sha) {
266
+ return no(
267
+ 'Refused',
268
+ `these bytes address ${staged.sha}`,
269
+ 400,
270
+ 'refused',
271
+ )
272
+ }
273
+ let name = nameOf(request.headers.get('x-yak-name'))
274
+ let as = await writer(request)
275
+ let file = await settled(
276
+ read,
277
+ upload,
278
+ staged,
279
+ typeOf(request.headers.get('content-type'), name),
280
+ name,
281
+ as.check,
282
+ (file) => finish(request, file),
283
+ )
284
+ await as.write(file.bundles)
285
+ return answer(file)
286
+ } finally {
287
+ await staged.drop()
288
+ }
289
+ }
290
+
291
+ // An upload in parts, where its bucket takes them.
292
+ let placed = (sha: string) => {
293
+ let p = options.parts
294
+ return p && {
295
+ key: p.prefix + sha,
296
+ up: inParts(p.objects, p.bucket, {
297
+ key: p.prefix + sha,
298
+ sha,
299
+ ledger: p.ledger,
300
+ part: p.part ?? PART,
301
+ }),
302
+ }
303
+ }
304
+ let unparted = () =>
305
+ no('Unsupported', 'this door takes no uploads in parts', 501, 'no_parts')
306
+
307
+ let begun = async (request: Request, sha: string) => {
308
+ let said = await request.json().catch(() => ({})) as Record<
309
+ string,
310
+ unknown
311
+ >
312
+ let bytes = Number(said.bytes)
313
+ if (!(Number.isInteger(bytes) && bytes > 0)) {
314
+ return no('Refused', 'an upload says how many bytes', 400, 'no_bytes')
315
+ }
316
+ admit(upload, bytes)
317
+ await roomFor(upload, sha, bytes)
318
+ let going = placed(sha)
319
+ if (!going) return unparted()
320
+ let { part, need, whole } = await going.up.post(bytes)
321
+ if (!whole) return json({ part, need })
322
+ let name = nameOf(said.name)
323
+ let file = await finish(
324
+ request,
325
+ await described(
326
+ read,
327
+ upload,
328
+ sha,
329
+ whole.head,
330
+ typeOf(said.mime, name),
331
+ name,
332
+ whole.bytes,
333
+ ),
334
+ )
335
+ // A completed upload remains recoverable if admission refuses its row.
336
+ let as = await writer(request)
337
+ admit(upload, whole.bytes, file.mime)
338
+ await as.check(file.bundles)
339
+ await as.write(file.bundles)
340
+ return answer(file)
341
+ }
342
+
343
+ let part = async (request: Request, sha: string, n: string) => {
344
+ let going = placed(sha)
345
+ if (!going) return unparted()
346
+ if (!/^[1-9][0-9]*$/.test(n)) return missing()
347
+ await going.up.put(
348
+ Number(n),
349
+ request.body ?? new Response('').body!,
350
+ Number(request.headers.get('content-length') ?? NaN),
351
+ request.headers.get('x-yak-state') ?? undefined,
352
+ )
353
+ return json({ n: Number(n) })
354
+ }
355
+
356
+ let writing =
357
+ (handle: (request: Request) => Promise<Response>) =>
358
+ async (request: Request) => {
359
+ try {
360
+ return await handle(request)
361
+ } catch (e) {
362
+ if (e instanceof Untaken) {
363
+ return no('Untaken', e.message, e.status, e.code)
364
+ }
365
+ if (e instanceof Gone) {
366
+ return no('Gone', e.message, 409, 'upload_gone')
367
+ }
368
+ if (e instanceof Wrong) return no('Refused', e.message, 400, 'refused')
369
+ return refuse(e, request, options.tags)
370
+ }
371
+ }
372
+
373
+ // The first bytes at `sha`, all a type is read off: only those are read
374
+ // from a store that streams.
375
+ let packed = async (sha: string) => {
376
+ let slice = await options.slice?.(read, sha)
377
+ if (!slice) return null
378
+ let { object, offset, size, mime } = slice
379
+ let part = sliceOf(await store.open?.(object), offset, size, sha)
380
+ if (!part) throw new MissingBlob(sha, mime)
381
+ return { part, mime }
382
+ }
383
+
384
+ let headOf = async (sha: string) => {
385
+ let object = await store.open?.(sha) ?? (await packed(sha))?.part
386
+ if (store.open && !object) return null
387
+ if (!object) {
388
+ let bytes = await store.get(sha)
389
+ return bytes ? { bytes: bytes.subarray(0, HEAD), whole: true } : null
390
+ }
391
+ let to = Math.min(HEAD, object.size) - 1
392
+ let bytes = to < 0 ? new Uint8Array() : new Uint8Array(
393
+ await new Response(await object.read({ from: 0, to })).arrayBuffer(),
394
+ )
395
+ return { bytes, whole: object.size <= HEAD }
396
+ }
397
+
398
+ // The representation the rows at `sha` say now, fixed once and kept.
399
+ let current = async (sha: string, eid?: string | null) => {
400
+ let use = await useOf(sha)
401
+ let said = naming.said(await read(line`.entity.eid=${[use, sha]}&*`), {
402
+ sha,
403
+ use,
404
+ }) ?? await naming.current?.(read, sha)
405
+ if (!said) return null
406
+ let rep = representation(scope, sha, said.mime, said.name)
407
+ if (eid && rep.eid != eid) return null
408
+ if (!eid) {
409
+ let [row] = await read(line`.entity.eid=${rep.eid} .representation`)
410
+ if (
411
+ row?.representation &&
412
+ represents(rep.eid, row.representation as Representation)
413
+ ) return rep
414
+ }
415
+ let head = await headOf(sha)
416
+ if (!head) throw new MissingBlob(sha, said.mime)
417
+ let fixed = await contentType(head.bytes, said.mime, head.whole)
418
+ rep = representation(scope, sha, fixed, said.name)
419
+ if (eid && rep.eid != eid) return null
420
+ let applied = await host.graph.apply([
421
+ { entity: { eid: rep.eid }, representation: rep.row },
422
+ ...fixed != said.mime ? said.fix(fixed) : [],
423
+ ], { trusted: true })
424
+ // A redirect to a representation the store did not keep is a broken link.
425
+ if (!applied.some((b) => b.entity.eid == rep.eid && b.representation)) {
426
+ throw new Error(`the representation ${rep.eid} was not written`)
427
+ }
428
+ return rep
429
+ }
430
+
431
+ let recovered = async (sha: string, eid?: string | null) => {
432
+ try {
433
+ return await current(sha, eid)
434
+ } catch (e) {
435
+ if (!(e instanceof Stale)) throw e
436
+ return await current(sha, eid)
437
+ }
438
+ }
439
+
440
+ // The bytes of a served representation, as a fenced answer.
441
+ let bytesOf = async (request: Request, sha: string, meta: Served) => {
442
+ if (options.bytes) {
443
+ let got = await servedVia(
444
+ (seek) => options.bytes!(seek, sha),
445
+ meta,
446
+ request,
447
+ )
448
+ if (got.status == 404) {
449
+ await got.body?.cancel()
450
+ return null
451
+ }
452
+ if (![200, 206, 304, 416].includes(got.status)) {
453
+ await got.body?.cancel()
454
+ throw new Error(`the bytes at ${sha} answered ${got.status}`)
455
+ }
456
+ return got
457
+ }
458
+ let object = await store.open?.(sha)
459
+ if (store.open && !object) return null
460
+ let bytes = object ? null : await store.get(sha)
461
+ if (!object && !bytes) return null
462
+ return object
463
+ ? servedOpen(object, meta, request)
464
+ : served(bytes!, meta, request)
465
+ }
466
+
467
+ // A read the store could not answer: a refusal it relays as it came, its
468
+ // wait among it, and anything else reported and unavailable.
469
+ let unavailable = (e: unknown, request: Request) => {
470
+ if (status(e) < 500) return refuse(e, request, options.tags)
471
+ fault(e, where(request), options.tags)
472
+ let answer = no(
473
+ 'Unavailable',
474
+ 'these bytes cannot be read just now',
475
+ 503,
476
+ 'blob_unavailable',
477
+ )
478
+ return options.unavailable?.(request, e, answer) ?? answer
479
+ }
480
+
481
+ // The reader's browser keeps the redirect for a week: every representation
482
+ // of one sha is the same bytes, so a kept redirect at worst names a file by
483
+ // an older name, and a removed file's representation is gone as its bare
484
+ // address is.
485
+ let REDIRECT = 'private, max-age=604800'
486
+
487
+ let sliced = async (request: Request, sha: string) => {
488
+ let slice = await packed(sha)
489
+ return slice
490
+ ? await servedOpen(
491
+ slice.part,
492
+ { mime: slice.mime, etag: `"${sha}"` },
493
+ request,
494
+ )
495
+ : missing()
496
+ }
497
+
498
+ let get = async (request: Request) => {
499
+ let address = addressed(below(request).join('/'))
500
+ if (!address) return missing()
501
+ let { sha, eid } = address
502
+ try {
503
+ if (!eid) {
504
+ let rep = await recovered(sha)
505
+ if (!rep) return await sliced(request, sha)
506
+ let to = new URL(request.url)
507
+ to.pathname += `/${rep.eid}`
508
+ return new Response(null, {
509
+ status: 302,
510
+ headers: { location: to.href, 'cache-control': REDIRECT },
511
+ })
512
+ }
513
+ let rep = await (options.served
514
+ ? options.served(sha, eid)
515
+ : servable(read, { scope, naming }, sha, eid)) ??
516
+ (await recovered(sha, eid))?.row
517
+ if (!rep) {
518
+ return missing()
519
+ }
520
+ let meta: Served = {
521
+ mime: rep.media_type,
522
+ name: rep.name,
523
+ etag: `"${eid}"`,
524
+ cache: 'browser',
525
+ download: new URL(request.url).searchParams.has('download'),
526
+ }
527
+ let load = async (request: Request) => {
528
+ let answer = await bytesOf(request, sha, meta)
529
+ if (answer) {
530
+ return answer
531
+ }
532
+ let slice = await packed(sha)
533
+ if (!slice) {
534
+ throw new MissingBlob(sha, meta.mime)
535
+ }
536
+ return await servedOpen(slice.part, meta, request)
537
+ }
538
+ return await options.variant?.(request, sha, meta, load) ??
539
+ await load(request)
540
+ } catch (e) {
541
+ if (e instanceof MissingBlob) {
542
+ let answer = missing()
543
+ if (options.missing) return options.missing(request, e, answer)
544
+ fault(e, where(request), options.tags)
545
+ return answer
546
+ }
547
+ return unavailable(e, request)
548
+ }
549
+ }
550
+
551
+ let put = writing((request) => {
552
+ let [sha, n, ...rest] = below(request)
553
+ if (!/^[0-9a-f]{64}$/.test(sha) || rest.length) {
554
+ return Promise.resolve(
555
+ no('Refused', 'an address is 64 lowercase hex digits', 400, 'refused'),
556
+ )
557
+ }
558
+ return n == null ? whole(request, sha) : part(request, sha, n)
559
+ })
560
+
561
+ let post = writing((request) => {
562
+ let [sha, ...rest] = below(request)
563
+ return /^[0-9a-f]{64}$/.test(sha) && !rest.length
564
+ ? begun(request, sha)
565
+ : Promise.resolve(missing())
566
+ })
567
+
568
+ return [
569
+ { method: 'GET', path: `${at}*`, handle: get },
570
+ { method: 'HEAD', path: `${at}*`, handle: get },
571
+ { method: 'POST', path: at.slice(0, -1), handle: writing(whole) },
572
+ { method: 'POST', path: `${at}*`, handle: post },
573
+ { method: 'PUT', path: `${at}*`, handle: put },
574
+ ]
575
+ }