@crombolo/server 0.34.0 → 0.36.2

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.
@@ -0,0 +1,613 @@
1
+ /**
2
+ * The `media` capability (story 198): a server bundle creating and changing
3
+ * media items as the member its route was given, under the media permissions
4
+ * (story 196). `docs/bundles.md`, Part 3.
5
+ *
6
+ * A bundle declares the folders it uses by path; the boot resolves them to
7
+ * keys and refuses a path that does not exist. Every call is confined to those
8
+ * folders and the subfolders below them. A member needs write permission on
9
+ * the folder to create, on the item to change or delete it, and read
10
+ * permission to see it; a back-office route acts as its user; a public route
11
+ * may not use media at all.
12
+ *
13
+ * An upload is checked before anything is stored: the folder, the permission,
14
+ * the file's type by its first bytes and its extension against the folder's
15
+ * list, and its size, counted as it is read. An image is turned upright and
16
+ * stored without its metadata, and what that metadata said is returned.
17
+ */
18
+ import { hasSection } from '@crombolo/api-management'
19
+ import { type MediaActor, type MediaOperations, memberActor, userActor } from '@crombolo/content'
20
+ import {
21
+ checkMemberUpload,
22
+ DEFAULT_UPLOAD_SETTINGS,
23
+ extensionOf,
24
+ hasPathAccess,
25
+ MEMBER_FILE_TYPES,
26
+ type MediaMember,
27
+ type MediaRule,
28
+ mediaFileOf,
29
+ memberMay,
30
+ nearestMediaRule,
31
+ normaliseUuid,
32
+ ObjectTypes,
33
+ OPEN_MEDIA,
34
+ SYSTEM_MEDIA_TYPE_KEYS,
35
+ type UploadSettings,
36
+ } from '@crombolo/core'
37
+ import {
38
+ ContentTypeRepository,
39
+ type Db,
40
+ MediaAccessRepository,
41
+ MediaListingRepository,
42
+ NodeRepository,
43
+ } from '@crombolo/data'
44
+ import type { CropRequest, MediaCache, PublishedMedia } from '@crombolo/render'
45
+ import { createMediaPort } from './adapters/media.ts'
46
+ import type { BundleCaller, ServerBundle } from './bundles.ts'
47
+ import { ImageRefusedError, type MemberImageFacts, prepareMemberImage } from './imaging.ts'
48
+ import type { MediaFileStore } from './media-files.ts'
49
+
50
+ /** What a bundle declares to use media: the folders, and what it accepts. */
51
+ export interface BundleMediaDeclaration {
52
+ /**
53
+ * Media folders by path from the top of the library, such as
54
+ * `/Observations/Photos`. The bundle writes only into these and the
55
+ * subfolders below them; a path that does not exist refuses the boot.
56
+ */
57
+ folders: readonly string[]
58
+ /**
59
+ * The file types it accepts, such as `['jpeg', 'png']`: narrows what each
60
+ * folder allows members, never widens it. Every type the folder allows when
61
+ * absent.
62
+ */
63
+ types?: readonly string[]
64
+ /** The largest upload, in bytes; a folder's own limit, if smaller, wins. */
65
+ maxBytes: number
66
+ }
67
+
68
+ /** What an image said about itself before it was stripped; nothing for other files. */
69
+ export type BundleMediaMetadata = Partial<MemberImageFacts>
70
+
71
+ /** Why a call was refused: the status to answer with and words to show the member. */
72
+ export interface BundleMediaRefusal {
73
+ ok: false
74
+ status: 400 | 401 | 403 | 404 | 409 | 413 | 415
75
+ message: string
76
+ }
77
+
78
+ /** A media item as a bundle sees it. */
79
+ export interface BundleMediaItem {
80
+ key: string
81
+ name: string
82
+ /** The media type's alias: `Image`, `File`… */
83
+ mediaType: string
84
+ /** Where its file is served, which only those who may read it can open; null with no file. */
85
+ url: string | null
86
+ /** The named crops its image defines, with their sizes. */
87
+ crops: Array<{ alias: string; width: number; height: number }>
88
+ /** The member who created it, by key. */
89
+ creator: string | null
90
+ createdAt: Date
91
+ updatedAt: Date
92
+ }
93
+
94
+ export interface BundleMediaCreate {
95
+ /** A declared folder's path, or a subfolder's below one; a missing subfolder is created. */
96
+ folder: string
97
+ /** The media item's name. */
98
+ name: string
99
+ /** The upload: a `File`, or a request whose body is the file. */
100
+ file: Blob | Request
101
+ /** The file's name, for its extension; a `File`'s own name, else `name`, when absent. */
102
+ fileName?: string
103
+ /** The media type's alias; chosen from the extension, as the back office chooses, when absent. */
104
+ mediaType?: string
105
+ }
106
+
107
+ export interface BundleMediaUpdate {
108
+ name?: string
109
+ file?: Blob | Request
110
+ fileName?: string
111
+ }
112
+
113
+ /** Media as the member, or user, a route was given (story 198). */
114
+ export interface BundleMedia {
115
+ create(
116
+ input: BundleMediaCreate,
117
+ ): Promise<
118
+ | { ok: true; key: string; url: string | null; metadata: BundleMediaMetadata }
119
+ | BundleMediaRefusal
120
+ >
121
+ /** The item, when it is in the bundle's folders and the caller may read it. */
122
+ get(key: string): Promise<BundleMediaItem | undefined>
123
+ update(
124
+ key: string,
125
+ input: BundleMediaUpdate,
126
+ ): Promise<{ ok: true; url: string | null; metadata: BundleMediaMetadata } | BundleMediaRefusal>
127
+ /** Moves the item to the recycle bin. */
128
+ delete(key: string): Promise<{ ok: true } | BundleMediaRefusal>
129
+ /** A page of a folder's items the caller may read. */
130
+ list(
131
+ folder: string,
132
+ paging?: { skip?: number; take?: number },
133
+ ): Promise<{ ok: true; total: number; items: BundleMediaItem[] } | BundleMediaRefusal>
134
+ /**
135
+ * The item's file, or an image's named crop or size, as a response to send
136
+ * on: never kept by a shared cache. 404 when it may not be read.
137
+ */
138
+ crop(key: string, request?: CropRequest): Promise<Response>
139
+ }
140
+
141
+ /** A declared folder as the boot found it. */
142
+ export interface ResolvedMediaFolder {
143
+ /** As declared. */
144
+ path: string
145
+ key: string
146
+ id: number
147
+ /** Its node path of ids, root first. */
148
+ nodePath: string
149
+ }
150
+
151
+ export interface BundleMediaDeps {
152
+ db: Db
153
+ /** Writes through the same rules, audit and events as the back office's. */
154
+ operations: MediaOperations
155
+ files: MediaFileStore
156
+ cache: MediaCache
157
+ uploadSettings?: UploadSettings
158
+ /** Each bundle's declared folders, resolved at boot. */
159
+ folders(bundleId: string): readonly ResolvedMediaFolder[]
160
+ /** The bundle's name, for the audit log. */
161
+ bundleName(bundleId: string): string
162
+ /** Streams a file, or a variant of an image, never to be kept by a shared cache. */
163
+ stream(src: string, search: URLSearchParams): Promise<Response>
164
+ }
165
+
166
+ const refuse = (status: BundleMediaRefusal['status'], message: string): BundleMediaRefusal => ({
167
+ ok: false,
168
+ status,
169
+ message,
170
+ })
171
+
172
+ const segmentsOf = (path: string) =>
173
+ path
174
+ .split('/')
175
+ .map((s) => s.trim())
176
+ .filter(Boolean)
177
+ const lower = (value: string) => value.toLowerCase()
178
+
179
+ /**
180
+ * The bytes of an upload, read only while they fit: undefined as soon as they
181
+ * pass `max`, so an oversized upload stops being read there.
182
+ */
183
+ export async function readWithin(
184
+ stream: ReadableStream<Uint8Array> | null,
185
+ max: number,
186
+ ): Promise<Uint8Array | undefined> {
187
+ if (!stream) return new Uint8Array()
188
+ const reader = stream.getReader()
189
+ const parts: Uint8Array[] = []
190
+ let total = 0
191
+ for (;;) {
192
+ const { done, value } = await reader.read()
193
+ if (done) break
194
+ total += value.byteLength
195
+ if (total > max) {
196
+ await reader.cancel().catch(() => {})
197
+ return undefined
198
+ }
199
+ parts.push(value)
200
+ }
201
+ const out = new Uint8Array(total)
202
+ let at = 0
203
+ for (const part of parts) {
204
+ out.set(part, at)
205
+ at += part.byteLength
206
+ }
207
+ return out
208
+ }
209
+
210
+ const sizeWords = (bytes: number) =>
211
+ bytes >= 1024 * 1024
212
+ ? `${Math.round((bytes / (1024 * 1024)) * 10) / 10} MB`
213
+ : `${Math.max(1, Math.round(bytes / 1024))} KB`
214
+
215
+ /** Resolves each declared path to its folder; the problems name the bundle and the path. */
216
+ export async function resolveBundleMediaFolders(
217
+ db: Db,
218
+ bundles: readonly ServerBundle[],
219
+ names: (id: string) => string = (id) => id,
220
+ ): Promise<{ folders: Map<string, ResolvedMediaFolder[]>; problems: string[] }> {
221
+ const listing = new MediaListingRepository(db)
222
+ const folders = new Map<string, ResolvedMediaFolder[]>()
223
+ const problems: string[] = []
224
+ for (const bundle of bundles) {
225
+ if (!bundle.capabilities.includes('media') || !bundle.media) continue
226
+ const found: ResolvedMediaFolder[] = []
227
+ for (const path of bundle.media.folders) {
228
+ const node = await listing.byPath(path)
229
+ if (!node)
230
+ problems.push(
231
+ `Bundle "${names(bundle.id)}" uses the media folder "${path}", which does not exist. Create it in Media, or take the bundle out of crombolo.config.ts until it does.`,
232
+ )
233
+ else found.push({ path, key: node.key, id: node.id, nodePath: node.path })
234
+ }
235
+ folders.set(bundle.id, found)
236
+ }
237
+ return { folders, problems }
238
+ }
239
+
240
+ /** The media capability, built per request for whoever the route was given. */
241
+ export function createBundleMedia(deps: BundleMediaDeps) {
242
+ const { db } = deps
243
+ const nodes = new NodeRepository(db)
244
+ const access = new MediaAccessRepository(db)
245
+ const listing = new MediaListingRepository(db)
246
+ const types = new ContentTypeRepository(db, { kind: 'media' })
247
+ const port = createMediaPort(db)
248
+ const settings = deps.uploadSettings ?? DEFAULT_UPLOAD_SETTINGS
249
+
250
+ return (caller: BundleCaller, bundle: ServerBundle): BundleMedia => {
251
+ const declared = bundle.media as BundleMediaDeclaration
252
+ const folders = deps.folders(bundle.id)
253
+ const member: MediaMember | undefined =
254
+ caller.kind === 'member'
255
+ ? { key: caller.member.key, groups: caller.member.groups }
256
+ : undefined
257
+ const actor: MediaActor | undefined =
258
+ caller.kind === 'member'
259
+ ? memberActor(caller.member, { via: deps.bundleName(bundle.id) })
260
+ : caller.kind === 'backoffice'
261
+ ? userActor(caller.principal)
262
+ : undefined
263
+ const nobody = refuse(401, 'Sign in to do that.')
264
+
265
+ /** Whether a node path lies in one of the declared folders, the folder itself included. */
266
+ const within = (nodePath: string) =>
267
+ folders.some((folder) => `,${nodePath},`.includes(`,${folder.id},`))
268
+
269
+ /** The rule governing a node path, from every rule there is: few, one per protected folder. */
270
+ const ruleAt = async (nodePath: string): Promise<MediaRule | undefined> =>
271
+ nearestMediaRule(nodePath, new Map((await access.allRules()).map((r) => [r.nodeId, r])))
272
+
273
+ /** A back-office user's view of the path: the Media section, within their start nodes. */
274
+ const userMayView = async (nodePath: string, trashed = false) => {
275
+ if (caller.kind !== 'backoffice') return false
276
+ if (!hasSection(caller.principal, 'media')) return false
277
+ const ids = nodePath
278
+ .split(',')
279
+ .map(Number)
280
+ .filter((id) => id > 0)
281
+ const chain = (await nodes.byIds(ids))
282
+ .filter((row) => row.objectType === ObjectTypes.Media)
283
+ .sort((a, b) => ids.indexOf(a.id) - ids.indexOf(b.id))
284
+ .map((row) => row.key)
285
+ return hasPathAccess(caller.principal.startNodes.media, chain, trashed)
286
+ }
287
+
288
+ const mayRead = async (item: PublishedMedia) =>
289
+ caller.kind === 'member'
290
+ ? memberMay('read', item.access, await ruleAt(item.path), member)
291
+ : userMayView(item.path)
292
+
293
+ /**
294
+ * Where a folder path leads: the declared folder it starts with, the
295
+ * deepest folder that exists along it, and the names still to be made.
296
+ */
297
+ const locate = async (path: string) => {
298
+ const wanted = segmentsOf(path).map(lower)
299
+ const root = folders
300
+ .filter((folder) => {
301
+ const own = segmentsOf(folder.path).map(lower)
302
+ return own.length <= wanted.length && own.every((s, i) => s === wanted[i])
303
+ })
304
+ .sort((a, b) => segmentsOf(b.path).length - segmentsOf(a.path).length)[0]
305
+ if (!root) return undefined
306
+ let at = { key: root.key, id: root.id, path: root.nodePath }
307
+ const original = segmentsOf(path)
308
+ const rest = original.slice(segmentsOf(root.path).length)
309
+ for (const [index, name] of rest.entries()) {
310
+ const child = await childFolder(at.id, name)
311
+ if (!child) return { at, missing: rest.slice(index) }
312
+ at = child
313
+ }
314
+ return { at, missing: [] as string[] }
315
+ }
316
+ const childFolder = async (parentId: number, name: string) => {
317
+ const rows = await db.query<{ id: number; unique_id: string; path: string; text: string }>(
318
+ 'SELECT id, unique_id, path, text FROM node WHERE parent_id = ? AND node_object_type = ? AND trashed = ? AND LOWER(text) = ?',
319
+ [parentId, ObjectTypes.Media, db.dialect.boolValue(false), lower(name)],
320
+ )
321
+ const row =
322
+ rows[0] ??
323
+ // SQLite lowers only ASCII.
324
+ (/[^ -~]/.test(name)
325
+ ? (
326
+ await db.query<{ id: number; unique_id: string; path: string; text: string }>(
327
+ 'SELECT id, unique_id, path, text FROM node WHERE parent_id = ? AND node_object_type = ? AND trashed = ?',
328
+ [parentId, ObjectTypes.Media, db.dialect.boolValue(false)],
329
+ )
330
+ ).find((r) => lower(String(r.text)) === lower(name))
331
+ : undefined)
332
+ return row
333
+ ? { id: Number(row.id), key: normaliseUuid(String(row.unique_id)), path: String(row.path) }
334
+ : undefined
335
+ }
336
+
337
+ /** Whether the caller may write into a folder, or a new subfolder that will follow its rule. */
338
+ const mayWriteInto = async (folderKey: string, path: string, creating: boolean) => {
339
+ if (caller.kind === 'backoffice') return true // the operations check the user's permissions
340
+ const rule = await ruleAt(path)
341
+ const own = (await access.itemAccess(folderKey)) ?? OPEN_MEDIA
342
+ return (
343
+ memberMay('write', own, rule, member) &&
344
+ (!creating || memberMay('write', OPEN_MEDIA, rule, member))
345
+ )
346
+ }
347
+
348
+ /** The types and size an upload below `path` must keep to. */
349
+ const limitsAt = async (path: string) => {
350
+ const rule = caller.kind === 'member' ? await ruleAt(path) : undefined
351
+ const all = MEMBER_FILE_TYPES.map((t) => t.id)
352
+ const folderTypes = caller.kind === 'member' ? (rule?.memberTypes ?? []) : all
353
+ const bundleTypes = declared.types ?? all
354
+ const allowed = folderTypes.filter((t) => bundleTypes.includes(t))
355
+ const max = Math.min(
356
+ declared.maxBytes,
357
+ rule?.memberMaxBytes ?? Number.POSITIVE_INFINITY,
358
+ settings.maxFileSize ?? Number.POSITIVE_INFINITY,
359
+ )
360
+ return { allowed, max }
361
+ }
362
+
363
+ /** The upload's bytes and type, checked; or why not. */
364
+ const receive = async (
365
+ file: Blob | Request,
366
+ fileName: string,
367
+ limits: { allowed: readonly string[]; max: number },
368
+ ) => {
369
+ if (limits.allowed.length === 0) return refuse(415, 'Files cannot be uploaded here.')
370
+ const tooBig = refuse(
371
+ 413,
372
+ `The file is too large. The most that can be uploaded here is ${sizeWords(limits.max)}.`,
373
+ )
374
+ const declaredSize =
375
+ file instanceof Request
376
+ ? Number(file.headers.get('content-length') ?? Number.NaN)
377
+ : file.size
378
+ if (Number.isFinite(declaredSize) && declaredSize > limits.max) return tooBig
379
+ const bytes = await readWithin(
380
+ file instanceof Request ? file.body : file.stream(),
381
+ limits.max,
382
+ )
383
+ if (!bytes) return tooBig
384
+ if (bytes.byteLength === 0) return refuse(400, 'The file is empty.')
385
+ const checked = checkMemberUpload(fileName, bytes.subarray(0, 64), limits.allowed, settings)
386
+ if (!checked.ok) return refuse(checked.status, checked.reason)
387
+ if (!checked.type.image) return { bytes, metadata: {} as BundleMediaMetadata }
388
+ try {
389
+ const prepared = await prepareMemberImage(bytes, checked.type.id)
390
+ return { bytes: prepared.bytes, metadata: prepared.facts as BundleMediaMetadata }
391
+ } catch (error) {
392
+ if (error instanceof ImageRefusedError) return refuse(415, error.message)
393
+ throw error
394
+ }
395
+ }
396
+
397
+ const fileNameOf = (file: Blob | Request, given: string | undefined, fallback: string) =>
398
+ given ?? (file instanceof File && file.name ? file.name : fallback)
399
+
400
+ /** Stages the bytes as a temporary upload, for the value a media item's file is made from. */
401
+ const stage = async (bytes: Uint8Array, fileName: string) => {
402
+ const id = crypto.randomUUID()
403
+ await deps.files.saveTemporary(id, new File([bytes as BlobPart], fileName))
404
+ return id
405
+ }
406
+
407
+ const fileValue = (temporaryFileId: string) => ({
408
+ alias: 'umbracoFile',
409
+ culture: null,
410
+ segment: null,
411
+ value: { temporaryFileId },
412
+ })
413
+
414
+ const urlOf = async (key: string) => {
415
+ const doc = await deps.operations.repository.byKey(key)
416
+ return doc ? mediaFileOf(doc) : null
417
+ }
418
+
419
+ const describe = (item: PublishedMedia): BundleMediaItem => ({
420
+ key: item.key,
421
+ name: item.name,
422
+ mediaType: item.mediaType.alias,
423
+ url: item.url || null,
424
+ crops: item.image.crops.map((c) => ({ alias: c.alias, width: c.width, height: c.height })),
425
+ creator: item.access.creatorMemberKey,
426
+ createdAt: item.createDate,
427
+ updatedAt: item.updateDate,
428
+ })
429
+
430
+ /** The item, when it is media in the bundle's folders and not in the bin. */
431
+ const inFolders = async (key: string) => {
432
+ const node = await nodes.byKey(key)
433
+ return node && node.objectType === ObjectTypes.Media && !node.trashed && within(node.path)
434
+ ? node
435
+ : undefined
436
+ }
437
+
438
+ const readable = async (key: string) => {
439
+ if (!(await inFolders(key))) return undefined
440
+ const item = await deps.cache.byKey(key)
441
+ return item && (await mayRead(item)) ? item : undefined
442
+ }
443
+
444
+ const operationRefusal = (result: { status: number; reason: string }): BundleMediaRefusal =>
445
+ refuse(
446
+ ([400, 403, 404, 409].includes(result.status) ? result.status : 400) as 400,
447
+ result.reason,
448
+ )
449
+
450
+ return Object.freeze({
451
+ async create(input) {
452
+ if (!actor) return nobody
453
+ const name = input.name?.trim()
454
+ if (!name) return refuse(400, 'Give the file a name.')
455
+ const place = await locate(input.folder ?? '')
456
+ if (!place) return refuse(403, `This site feature cannot add files to "${input.folder}".`)
457
+ const creating = place.missing.length > 0
458
+ if (!(await mayWriteInto(place.at.key, place.at.path, creating)))
459
+ return refuse(403, 'You do not have permission to add files here.')
460
+ const fileName = fileNameOf(input.file, input.fileName, name)
461
+ const received = await receive(input.file, fileName, await limitsAt(place.at.path))
462
+ if ('ok' in received) return received
463
+
464
+ const extension = extensionOf(fileName)
465
+ let typeKey: string | undefined
466
+ if (input.mediaType) {
467
+ typeKey = (await types.byAlias(input.mediaType))?.key
468
+ if (!typeKey) return refuse(400, `There is no media type "${input.mediaType}".`)
469
+ } else {
470
+ const choices = await port.typesForExtension(extension)
471
+ typeKey = (choices.find((c) => c.matched) ?? choices[0])?.key
472
+ if (!typeKey)
473
+ return refuse(415, `This site has no kind of media for .${extension} files.`)
474
+ }
475
+
476
+ let parent = place.at.key
477
+ for (const folderName of place.missing) {
478
+ const made = await deps.operations.create(actor, {
479
+ key: crypto.randomUUID(),
480
+ contentTypeKey: SYSTEM_MEDIA_TYPE_KEYS.Folder,
481
+ parentKey: parent,
482
+ values: [],
483
+ variants: [{ culture: null, segment: null, name: folderName }],
484
+ stamp: false,
485
+ })
486
+ if (!made.ok) return operationRefusal(made)
487
+ parent = made.key
488
+ }
489
+
490
+ const temporary = await stage(received.bytes, fileName)
491
+ const created = await deps.operations.create(actor, {
492
+ key: crypto.randomUUID(),
493
+ contentTypeKey: typeKey,
494
+ parentKey: parent,
495
+ values: [fileValue(temporary)],
496
+ variants: [{ culture: null, segment: null, name }],
497
+ })
498
+ if (!created.ok) {
499
+ await deps.files.deleteTemporary(temporary)
500
+ return operationRefusal(created)
501
+ }
502
+ return {
503
+ ok: true,
504
+ key: created.key,
505
+ url: await urlOf(created.key),
506
+ metadata: received.metadata,
507
+ }
508
+ },
509
+
510
+ async get(key) {
511
+ if (!actor) return undefined
512
+ const item = await readable(key)
513
+ return item ? describe(item) : undefined
514
+ },
515
+
516
+ async update(key, input) {
517
+ if (!actor) return nobody
518
+ const node = await inFolders(key)
519
+ if (!node) return refuse(404, 'The file could not be found.')
520
+ const before = await deps.operations.repository.byKey(key)
521
+ if (!before) return refuse(404, 'The file could not be found.')
522
+ if (caller.kind === 'member') {
523
+ const own = (await access.itemAccess(key)) ?? OPEN_MEDIA
524
+ if (!memberMay('write', own, await ruleAt(node.path), member))
525
+ return refuse(403, 'You do not have permission to change this file.')
526
+ }
527
+ let values = before.values
528
+ let metadata: BundleMediaMetadata = {}
529
+ let temporary: string | undefined
530
+ if (input.file) {
531
+ const fileName = fileNameOf(input.file, input.fileName, input.name ?? node.text ?? 'file')
532
+ const parentPath = node.path.split(',').slice(0, -1).join(',')
533
+ const received = await receive(input.file, fileName, await limitsAt(parentPath))
534
+ if ('ok' in received) return received
535
+ const choices = await port.typesForExtension(extensionOf(fileName))
536
+ if (!choices.some((c) => c.key === before.contentTypeKey))
537
+ return refuse(415, 'The new file must be the same kind of file as the one it replaces.')
538
+ temporary = await stage(received.bytes, fileName)
539
+ values = [...values.filter((v) => v.alias !== 'umbracoFile'), fileValue(temporary)]
540
+ metadata = received.metadata
541
+ }
542
+ const name = input.name?.trim()
543
+ const saved = await deps.operations.save(actor, key, {
544
+ contentTypeKey: before.contentTypeKey,
545
+ parentKey: before.parentKey,
546
+ values,
547
+ variants: name
548
+ ? before.variants.map((v) => ({ culture: v.culture, segment: v.segment, name }))
549
+ : before.variants.map((v) => ({
550
+ culture: v.culture,
551
+ segment: v.segment,
552
+ name: v.name,
553
+ })),
554
+ })
555
+ if (!saved.ok) {
556
+ if (temporary) await deps.files.deleteTemporary(temporary)
557
+ return operationRefusal(saved)
558
+ }
559
+ return { ok: true, url: await urlOf(key), metadata }
560
+ },
561
+
562
+ async delete(key) {
563
+ if (!actor) return nobody
564
+ const node = await inFolders(key)
565
+ if (!node) return refuse(404, 'The file could not be found.')
566
+ const trashed = await deps.operations.trash(actor, key)
567
+ if (!trashed.ok)
568
+ return trashed.status === 403
569
+ ? refuse(403, 'You do not have permission to delete this file.')
570
+ : operationRefusal(trashed)
571
+ return { ok: true }
572
+ },
573
+
574
+ async list(folder, paging = {}) {
575
+ if (!actor) return nobody
576
+ const place = await locate(folder)
577
+ if (!place) return refuse(403, `This site feature cannot read "${folder}".`)
578
+ if (place.missing.length > 0) return { ok: true, total: 0, items: [] }
579
+ if (caller.kind === 'backoffice' && !(await userMayView(place.at.path)))
580
+ return refuse(403, 'You do not have permission to see this folder.')
581
+ const rules = new Map((await access.allRules()).map((r) => [r.nodeId, r]))
582
+ const page = await listing.children({
583
+ parentId: place.at.id,
584
+ parentPath: place.at.path,
585
+ skip: Math.max(0, Math.floor(paging.skip ?? 0)),
586
+ take: Math.min(100, Math.max(0, Math.floor(paging.take ?? 20))),
587
+ readable: caller.kind === 'member' ? { rules, member } : undefined,
588
+ })
589
+ const found = await deps.cache.byKeys(page.keys)
590
+ const items = page.keys.flatMap((key) => {
591
+ const item = found.get(key.toLowerCase())
592
+ return item ? [describe(item)] : []
593
+ })
594
+ return { ok: true, total: page.total, items }
595
+ },
596
+
597
+ async crop(key, request) {
598
+ const notFound = new Response('Not Found', {
599
+ status: 404,
600
+ headers: { 'cache-control': 'private, no-store' },
601
+ })
602
+ if (!actor) return notFound
603
+ const item = await readable(key)
604
+ if (!item?.url) return notFound
605
+ const target = request === undefined ? item.url : item.image.cropUrl(request)
606
+ if (!target) return notFound
607
+ return deps.stream(item.url, new URL(target, 'http://local').searchParams)
608
+ },
609
+ } satisfies BundleMedia)
610
+ }
611
+ }
612
+
613
+ export type BundleMediaFactory = ReturnType<typeof createBundleMedia>