@nuasite/cms-sidecar 0.56.4 → 0.58.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.
- package/README.md +306 -0
- package/dist/cli.js +17991 -16439
- package/dist/types/index.d.ts +1 -1
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/server.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/dist/types/types.d.ts +9 -1
- package/dist/types/types.d.ts.map +1 -1
- package/package.json +3 -3
- package/src/index.ts +1 -0
- package/src/server.ts +174 -73
- package/src/types.ts +10 -1
package/src/server.ts
CHANGED
|
@@ -1,4 +1,19 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
type CmsCore,
|
|
3
|
+
type CmsFileSystem,
|
|
4
|
+
isUnsafeFolder,
|
|
5
|
+
listFilteredMedia,
|
|
6
|
+
listProjectImages,
|
|
7
|
+
MEDIA_CURSOR_TYPE_MISMATCH,
|
|
8
|
+
MEDIA_INVALID_FOLDER,
|
|
9
|
+
MediaCursorError,
|
|
10
|
+
mediaErrorStatus,
|
|
11
|
+
parseMediaTypeFilter,
|
|
12
|
+
parseProjectCmsConfig,
|
|
13
|
+
resolvePathnameFromSpec,
|
|
14
|
+
scanRouteCollections,
|
|
15
|
+
} from '@nuasite/cms-core'
|
|
16
|
+
import { filterMediaItems } from '@nuasite/cms-types'
|
|
2
17
|
import type {
|
|
3
18
|
CmsConfig,
|
|
4
19
|
CollectionDefinition,
|
|
@@ -9,6 +24,7 @@ import type {
|
|
|
9
24
|
MediaItem,
|
|
10
25
|
MediaListResult,
|
|
11
26
|
MediaStorageAdapter,
|
|
27
|
+
MediaTypeFilter,
|
|
12
28
|
MutationResult,
|
|
13
29
|
} from '@nuasite/cms-types'
|
|
14
30
|
import { hashContent, hashSource, KeyedMutex, SharedRun } from './concurrency'
|
|
@@ -28,6 +44,7 @@ import {
|
|
|
28
44
|
type RenameEntryBody,
|
|
29
45
|
STATUS_BY_CODE,
|
|
30
46
|
type UpdateEntryBody,
|
|
47
|
+
type UpdateMediaAnnotationBody,
|
|
31
48
|
} from './types'
|
|
32
49
|
|
|
33
50
|
/** Features the sidecar advertises so older/newer clients can degrade gracefully. */
|
|
@@ -48,6 +65,7 @@ export const SIDECAR_FEATURES: readonly string[] = [
|
|
|
48
65
|
'redirects.crud',
|
|
49
66
|
'media',
|
|
50
67
|
'media.project-images',
|
|
68
|
+
'media.type-filter',
|
|
51
69
|
'components',
|
|
52
70
|
'config',
|
|
53
71
|
]
|
|
@@ -99,6 +117,19 @@ function mutationResponse(result: MutationResult, fallback: ErrorCode = 'validat
|
|
|
99
117
|
return error(code, message, result.sourcePath)
|
|
100
118
|
}
|
|
101
119
|
|
|
120
|
+
/**
|
|
121
|
+
* Map a failed media adapter result to an HTTP response. An id or folder the adapter
|
|
122
|
+
* refuses is the caller's mistake → 400, a file that is not there → 404; everything
|
|
123
|
+
* else is a storage failure → 500. The adapter says which by answering with one of
|
|
124
|
+
* cms-core's exact strings (`mediaErrorStatus`): the text of any other error decides
|
|
125
|
+
* nothing, since it may come from an SDK or an upstream service.
|
|
126
|
+
*/
|
|
127
|
+
function mediaFailure(message: string): Response {
|
|
128
|
+
const status = mediaErrorStatus(message)
|
|
129
|
+
const code: ErrorCode = status === 400 ? 'validation' : status === 404 ? 'not_found' : 'io_error'
|
|
130
|
+
return error(code, message)
|
|
131
|
+
}
|
|
132
|
+
|
|
102
133
|
async function parseJson<T>(req: Request): Promise<{ ok: true; value: T } | { ok: false; response: Response }> {
|
|
103
134
|
try {
|
|
104
135
|
// `JSON.parse` returns `any`, which flows to `T` without a cast. Body shapes
|
|
@@ -139,6 +170,11 @@ function parseEntriesQuery(url: URL): EntriesQuery {
|
|
|
139
170
|
* The cursor is self-identifying (`v`), so a caller that loses the
|
|
140
171
|
* `?includeProjectImages` flag mid-scroll gets a 400 instead of having our private
|
|
141
172
|
* cursor handed to the adapter, which would parse it as garbage.
|
|
173
|
+
*
|
|
174
|
+
* A `?type=` listing is paged by cursors we mint for the same reason, merged or not: every
|
|
175
|
+
* position one marks is a position in the *filtered* stream, so following it under a different tab
|
|
176
|
+
* would address a different list. An unfiltered listing still hands the adapter's own cursor
|
|
177
|
+
* through untouched, exactly as before.
|
|
142
178
|
*/
|
|
143
179
|
interface MediaCursorState {
|
|
144
180
|
/** The adapter's own continuation cursor. */
|
|
@@ -153,10 +189,23 @@ interface MediaCursorState {
|
|
|
153
189
|
* media root's only (the merge is disabled for `?folder=`), so it stays small.
|
|
154
190
|
*/
|
|
155
191
|
folders?: MediaFolderItem[]
|
|
192
|
+
/**
|
|
193
|
+
* The tab the cursor was minted under, when it was minted under one. Absent means no filter,
|
|
194
|
+
* which is also how every cursor minted before `?type=` existed decodes.
|
|
195
|
+
*/
|
|
196
|
+
type?: MediaTypeFilter
|
|
156
197
|
}
|
|
157
198
|
|
|
158
199
|
const MEDIA_CURSOR_VERSION = 1
|
|
159
200
|
|
|
201
|
+
/** The tab a decoded cursor belongs to; absent has always meant "the whole listing". */
|
|
202
|
+
function cursorType(state: MediaCursorState): MediaTypeFilter {
|
|
203
|
+
return state.type ?? 'all'
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** A merged-listing cursor followed somewhere the merge does not run: without the flag, or in a folder. */
|
|
207
|
+
const MERGED_CURSOR_OUTSIDE_MERGE = 'This cursor continues an ?includeProjectImages listing: keep the flag set and drop ?folder when following it'
|
|
208
|
+
|
|
160
209
|
function encodeMediaCursor(state: MediaCursorState): string {
|
|
161
210
|
return Buffer.from(JSON.stringify({ v: MEDIA_CURSOR_VERSION, ...state }), 'utf8').toString('base64url')
|
|
162
211
|
}
|
|
@@ -203,6 +252,12 @@ function decodeMediaCursor(raw: string | undefined): { ok: true; state: MediaCur
|
|
|
203
252
|
if (folders === null) return { ok: false }
|
|
204
253
|
state.folders = folders
|
|
205
254
|
}
|
|
255
|
+
if ('type' in parsed) {
|
|
256
|
+
if (typeof parsed.type !== 'string') return { ok: false }
|
|
257
|
+
const type = parseMediaTypeFilter(parsed.type)
|
|
258
|
+
if (type === null) return { ok: false }
|
|
259
|
+
state.type = type
|
|
260
|
+
}
|
|
206
261
|
// We only ever mint a cursor that carries a position; one without is malformed.
|
|
207
262
|
if (state.adapter === undefined && state.project === undefined) return { ok: false }
|
|
208
263
|
return { ok: true, state }
|
|
@@ -358,8 +413,6 @@ async function listPages(fs: CmsFileSystem): Promise<PageEntry[]> {
|
|
|
358
413
|
// Collection → route base (sidecar-layer fs walk)
|
|
359
414
|
// ============================================================================
|
|
360
415
|
|
|
361
|
-
const GET_COLLECTION_RE = /getCollection\s*\(\s*['"`]([^'"`]+)['"`]/g
|
|
362
|
-
|
|
363
416
|
/**
|
|
364
417
|
* How the route that renders a collection turns an entry into a URL:
|
|
365
418
|
* - `perItem`: a dynamic route (`[...slug].astro`) → one page per entry, at
|
|
@@ -373,43 +426,10 @@ interface CollectionRoute {
|
|
|
373
426
|
}
|
|
374
427
|
|
|
375
428
|
/**
|
|
376
|
-
*
|
|
377
|
-
*
|
|
378
|
-
*
|
|
379
|
-
*
|
|
380
|
-
*
|
|
381
|
-
* Returns `null` when there is no `getStaticPaths` (e.g. an SSR `prerender=false` route),
|
|
382
|
-
* so the caller can fall back to its own heuristic.
|
|
383
|
-
*/
|
|
384
|
-
function getStaticPathsCollections(content: string): string[] | null {
|
|
385
|
-
const head = /getStaticPaths\s*\(/.exec(content)
|
|
386
|
-
if (!head) return null
|
|
387
|
-
// Skip the parameter list (it may destructure, e.g. `({ paginate })`) to reach the body brace.
|
|
388
|
-
let i = head.index + head[0].length
|
|
389
|
-
let parens = 1
|
|
390
|
-
for (; i < content.length && parens > 0; i++) {
|
|
391
|
-
if (content[i] === '(') parens++
|
|
392
|
-
else if (content[i] === ')') parens--
|
|
393
|
-
}
|
|
394
|
-
const open = content.indexOf('{', i)
|
|
395
|
-
if (parens !== 0 || open === -1) return null
|
|
396
|
-
// Brace-match the function body, then scan getCollection only within it.
|
|
397
|
-
let depth = 0
|
|
398
|
-
for (let j = open; j < content.length; j++) {
|
|
399
|
-
if (content[j] === '{') depth++
|
|
400
|
-
else if (content[j] === '}' && --depth === 0) {
|
|
401
|
-
const body = content.slice(open + 1, j)
|
|
402
|
-
return [...body.matchAll(GET_COLLECTION_RE)].map(m => m[1]).filter((n): n is string => Boolean(n))
|
|
403
|
-
}
|
|
404
|
-
}
|
|
405
|
-
return null
|
|
406
|
-
}
|
|
407
|
-
|
|
408
|
-
/**
|
|
409
|
-
* Map each collection to the route that renders it, by scanning the Astro pages
|
|
410
|
-
* under `src/pages` for `getCollection('<name>')`. This is the only reliable source
|
|
411
|
-
* for an entry's URL — it comes from the route, not the collection name (a `product`
|
|
412
|
-
* collection can live at `/products`, an `faq` collection on a single `/faq` page).
|
|
429
|
+
* Map each collection to the route that renders it, by parsing the Astro pages under
|
|
430
|
+
* `src/pages` with {@link scanRouteCollections}. This is the only reliable source for an
|
|
431
|
+
* entry's URL: it comes from the route, not the collection name (a `product` collection
|
|
432
|
+
* can live at `/products`, an `faq` collection on a single `/faq` page).
|
|
413
433
|
*
|
|
414
434
|
* - A *dynamic* route (`[...slug].astro`, or a `[slug]/index.astro` directory) renders one
|
|
415
435
|
* page per entry; the URL base is the path up to its dynamic segment. Every collection
|
|
@@ -449,8 +469,8 @@ async function resolveCollectionRoutes(fs: CmsFileSystem): Promise<Map<string, C
|
|
|
449
469
|
} catch {
|
|
450
470
|
continue
|
|
451
471
|
}
|
|
452
|
-
const
|
|
453
|
-
if (
|
|
472
|
+
const { staticPaths, all } = scanRouteCollections(content)
|
|
473
|
+
if (all.length === 0) continue
|
|
454
474
|
|
|
455
475
|
// Full route path: directory prefix + file segment (Astro drops `index`).
|
|
456
476
|
const baseName = entry.name.slice(0, -'.astro'.length)
|
|
@@ -465,14 +485,12 @@ async function resolveCollectionRoutes(fs: CmsFileSystem): Promise<Map<string, C
|
|
|
465
485
|
// Every collection the route's getStaticPaths enumerates is page-per-item; a single
|
|
466
486
|
// [slug] detail may drive several. Fall back to the first getCollection when there
|
|
467
487
|
// is no getStaticPaths block to read (e.g. an SSR route).
|
|
468
|
-
const drivers =
|
|
469
|
-
for (const name of
|
|
470
|
-
consider(name, { base, perItem: true })
|
|
471
|
-
}
|
|
488
|
+
const drivers = staticPaths.length > 0 ? staticPaths : all.slice(0, 1)
|
|
489
|
+
for (const name of drivers) consider(name, { base, perItem: true })
|
|
472
490
|
} else {
|
|
473
491
|
// Static page: every collection it lists shares this page's URL.
|
|
474
492
|
const pathname = routePath.replace(/\/$/, '') || '/'
|
|
475
|
-
for (const name of
|
|
493
|
+
for (const name of all) consider(name, { base: pathname, perItem: false })
|
|
476
494
|
}
|
|
477
495
|
}
|
|
478
496
|
}
|
|
@@ -540,7 +558,10 @@ export function createServer(opts: CreateServerOptions): CmsSidecarServer {
|
|
|
540
558
|
const mutex = new KeyedMutex()
|
|
541
559
|
// A client may ask for the entries of every collection at once, and each scan reads and parses
|
|
542
560
|
// all of the project's content: without sharing, N concurrent requests hold N full scans in memory.
|
|
543
|
-
const collectionsScan = new SharedRun(() => core.scanCollections())
|
|
561
|
+
const collectionsScan = new SharedRun(() => core.scanCollections({ report: false }))
|
|
562
|
+
// `GET /project` alone answers with the scan report, so it alone pays for building one. Its
|
|
563
|
+
// collections come from that same scan, so the two always describe one state of the disk.
|
|
564
|
+
const reportedScan = new SharedRun(() => core.scanCollections({ report: true }))
|
|
544
565
|
const collectionRoutes = new SharedRun(() => resolveCollectionRoutes(fs))
|
|
545
566
|
|
|
546
567
|
async function scanList(): Promise<CollectionDefinition[]> {
|
|
@@ -654,7 +675,12 @@ export function createServer(opts: CreateServerOptions): CmsSidecarServer {
|
|
|
654
675
|
return error('not_found', `No route: ${req.method} ${pathname}`)
|
|
655
676
|
}
|
|
656
677
|
const rest = pathname.slice(API_PREFIX.length) || '/'
|
|
657
|
-
|
|
678
|
+
let segments: string[]
|
|
679
|
+
try {
|
|
680
|
+
segments = rest.split('/').filter(Boolean).map(decodeURIComponent)
|
|
681
|
+
} catch {
|
|
682
|
+
return error('validation', 'Malformed percent-encoding in the request path')
|
|
683
|
+
}
|
|
658
684
|
const method = req.method
|
|
659
685
|
|
|
660
686
|
try {
|
|
@@ -663,6 +689,7 @@ export function createServer(opts: CreateServerOptions): CmsSidecarServer {
|
|
|
663
689
|
// Any write may change what the shared scans read.
|
|
664
690
|
if (method !== 'GET') {
|
|
665
691
|
collectionsScan.invalidate()
|
|
692
|
+
reportedScan.invalidate()
|
|
666
693
|
collectionRoutes.invalidate()
|
|
667
694
|
}
|
|
668
695
|
}
|
|
@@ -678,9 +705,13 @@ export function createServer(opts: CreateServerOptions): CmsSidecarServer {
|
|
|
678
705
|
|
|
679
706
|
case 'project':
|
|
680
707
|
if (method === 'GET') {
|
|
681
|
-
const [
|
|
708
|
+
const [scanned, pages] = await Promise.all([reportedScan.get(), listPages(fs)])
|
|
682
709
|
const capabilities: Capabilities = { coreVersion, features: [...SIDECAR_FEATURES] }
|
|
683
|
-
const model: ProjectModel = { collections, pages, capabilities }
|
|
710
|
+
const model: ProjectModel = { collections: Object.values(scanned), pages, capabilities }
|
|
711
|
+
// The report of the very scan `collections` came from. Left out, not sent empty,
|
|
712
|
+
// when the core has none: a client must be able to tell the two apart.
|
|
713
|
+
const collectionScan = core.collectionScanReport?.(scanned)
|
|
714
|
+
if (collectionScan !== undefined) model.collectionScan = collectionScan
|
|
684
715
|
return json(model)
|
|
685
716
|
}
|
|
686
717
|
break
|
|
@@ -951,9 +982,15 @@ export function createServer(opts: CreateServerOptions): CmsSidecarServer {
|
|
|
951
982
|
* - `folders` is the adapter's, carried through the cursor so that every page —
|
|
952
983
|
* including the scan-only ones, which never call the adapter — reports it.
|
|
953
984
|
*/
|
|
954
|
-
async function listMergedMedia(
|
|
985
|
+
async function listMergedMedia(
|
|
986
|
+
adapter: MediaStorageAdapter,
|
|
987
|
+
limit: number,
|
|
988
|
+
rawCursor: string | undefined,
|
|
989
|
+
type: MediaTypeFilter,
|
|
990
|
+
): Promise<Response> {
|
|
955
991
|
const decoded = decodeMediaCursor(rawCursor)
|
|
956
992
|
if (!decoded.ok) return error('validation', 'Invalid media cursor')
|
|
993
|
+
if (rawCursor !== undefined && cursorType(decoded.state) !== type) return error('validation', MEDIA_CURSOR_TYPE_MISMATCH)
|
|
957
994
|
const { adapter: adapterCursor, project: projectOffset, folders: carriedFolders } = decoded.state
|
|
958
995
|
|
|
959
996
|
const items: MediaItem[] = []
|
|
@@ -961,20 +998,24 @@ export function createServer(opts: CreateServerOptions): CmsSidecarServer {
|
|
|
961
998
|
|
|
962
999
|
// A `project` offset in the cursor means the adapter pages are already spent.
|
|
963
1000
|
if (projectOffset === undefined) {
|
|
964
|
-
|
|
1001
|
+
// Filtered above the adapter, which cannot do it itself — see `listFilteredMedia`. The
|
|
1002
|
+
// cursor it hands back is still one the adapter minted, so the phase resumes normally.
|
|
1003
|
+
const page = await listFilteredMedia(options => adapter.list(options), { limit, cursor: adapterCursor, type })
|
|
965
1004
|
items.push(...page.items)
|
|
966
1005
|
folders = page.folders
|
|
967
1006
|
// An adapter that reports more pages but hands back no cursor cannot be advanced. Stop
|
|
968
1007
|
// here anyway — falling through to the scan would silently drop the rest of its items.
|
|
969
1008
|
if (page.hasMore) {
|
|
970
|
-
const cursor = page.cursor === undefined ? undefined : encodeMediaCursor({ adapter: page.cursor, folders })
|
|
971
|
-
const more: MediaListResult = { items, folders, hasMore: true, cursor }
|
|
1009
|
+
const cursor = page.cursor === undefined ? undefined : encodeMediaCursor({ adapter: page.cursor, folders, type })
|
|
1010
|
+
const more: MediaListResult = { items, folders, hasMore: true, cursor, appliedType: type }
|
|
972
1011
|
return json(more)
|
|
973
1012
|
}
|
|
974
1013
|
}
|
|
975
1014
|
|
|
1015
|
+
// The scan is one unpaginated list, so its filter is a plain one — and the offset the cursor
|
|
1016
|
+
// carries indexes the *filtered* list, which is stable for as long as the tree is.
|
|
976
1017
|
const offset = projectOffset ?? 0
|
|
977
|
-
const projectImages = await listProjectImages(fs, { exclude: { dir: adapter.staticFiles?.dir, root } })
|
|
1018
|
+
const projectImages = filterMediaItems(await listProjectImages(fs, { exclude: { dir: adapter.staticFiles?.dir, root } }), type)
|
|
978
1019
|
const slice = projectImages.slice(offset, offset + Math.max(0, limit - items.length))
|
|
979
1020
|
items.push(...slice)
|
|
980
1021
|
|
|
@@ -984,11 +1025,26 @@ export function createServer(opts: CreateServerOptions): CmsSidecarServer {
|
|
|
984
1025
|
items,
|
|
985
1026
|
folders,
|
|
986
1027
|
hasMore,
|
|
987
|
-
cursor: hasMore ? encodeMediaCursor({ project: next, folders }) : undefined,
|
|
1028
|
+
cursor: hasMore ? encodeMediaCursor({ project: next, folders, type }) : undefined,
|
|
1029
|
+
appliedType: type,
|
|
988
1030
|
}
|
|
989
1031
|
return json(result)
|
|
990
1032
|
}
|
|
991
1033
|
|
|
1034
|
+
/** The media routes, with anything an adapter throws answered as a path-free `io_error`. */
|
|
1035
|
+
async function routeMedia(method: string, tail: string[], req: Request, url: URL): Promise<Response> {
|
|
1036
|
+
try {
|
|
1037
|
+
return await answerMedia(method, tail, req, url)
|
|
1038
|
+
} catch (cause) {
|
|
1039
|
+
// A filtered cursor `listFilteredMedia` refused is the caller's mistake, not storage's.
|
|
1040
|
+
if (cause instanceof MediaCursorError) return error('validation', cause.message)
|
|
1041
|
+
// Whatever an adapter throws may spell out a filesystem path, and left uncaught it
|
|
1042
|
+
// is rendered by the runtime's error page. The detail goes to the log instead.
|
|
1043
|
+
console.error('[cms-sidecar] media request failed:', cause)
|
|
1044
|
+
return error('io_error', 'Media storage failed')
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
|
|
992
1048
|
/**
|
|
993
1049
|
* `GET /media` lists the storage adapter alone by default. `?includeProjectImages`
|
|
994
1050
|
* (bare, or `=true` / `=1`; root only, no `folder`) merges in the project scan behind
|
|
@@ -996,10 +1052,13 @@ export function createServer(opts: CreateServerOptions): CmsSidecarServer {
|
|
|
996
1052
|
* feature. An unrecognised flag value, or a merge cursor followed without the flag,
|
|
997
1053
|
* is a 400 rather than a silently different listing.
|
|
998
1054
|
*/
|
|
999
|
-
async function
|
|
1055
|
+
async function answerMedia(method: string, tail: string[], req: Request, url: URL): Promise<Response> {
|
|
1000
1056
|
const adapter = core.media
|
|
1001
1057
|
if (!adapter) return error('unsupported', 'Media storage not configured')
|
|
1002
1058
|
|
|
1059
|
+
// An id is one path segment, with any `/` in it encoded. More segments would otherwise
|
|
1060
|
+
// act on the first one alone — `DELETE /media/photos/a.png` deleting `photos`.
|
|
1061
|
+
if (tail.length > 1) return error('not_found', `No route: ${method} /cms/v1/media/${tail.join('/')}`)
|
|
1003
1062
|
const [id] = tail
|
|
1004
1063
|
|
|
1005
1064
|
// GET /media
|
|
@@ -1013,19 +1072,44 @@ export function createServer(opts: CreateServerOptions): CmsSidecarServer {
|
|
|
1013
1072
|
if (includeProjectImages === null) {
|
|
1014
1073
|
return error('validation', 'includeProjectImages accepts no value, "true", "1", "false" or "0"')
|
|
1015
1074
|
}
|
|
1075
|
+
const type = parseMediaTypeFilter(url.searchParams.get('type'))
|
|
1076
|
+
if (type === null) {
|
|
1077
|
+
return error('validation', 'type accepts "all", "photo", "graphic", "video" or "document"')
|
|
1078
|
+
}
|
|
1016
1079
|
|
|
1017
1080
|
// The project scan has no folder structure, so it only makes sense at the
|
|
1018
1081
|
// media root — inside a folder the adapter stays the only source.
|
|
1019
1082
|
if (!includeProjectImages || folder !== undefined) {
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1083
|
+
if (type === 'all') {
|
|
1084
|
+
// Our own cursor means nothing to the adapter, which would parse it as an
|
|
1085
|
+
// offset of NaN and answer with an empty, hasMore:false page — the library
|
|
1086
|
+
// would look empty. Say what actually went wrong instead.
|
|
1087
|
+
if (cursor !== undefined && decodeMediaCursor(cursor).ok) return error('validation', MERGED_CURSOR_OUTSIDE_MERGE)
|
|
1088
|
+
return json(await adapter.list({ limit, cursor, folder }))
|
|
1025
1089
|
}
|
|
1026
|
-
|
|
1090
|
+
// A filtered page ends wherever the source happened to be once the page was full, so
|
|
1091
|
+
// the position it hands back belongs to this tab. Wrap the adapter's cursor in ours
|
|
1092
|
+
// to say so, and refuse one minted under another tab rather than answering from the
|
|
1093
|
+
// wrong place in the listing.
|
|
1094
|
+
const decoded = decodeMediaCursor(cursor)
|
|
1095
|
+
if (!decoded.ok) return error('validation', 'Invalid media cursor')
|
|
1096
|
+
if (cursor !== undefined && cursorType(decoded.state) !== type) return error('validation', MEDIA_CURSOR_TYPE_MISMATCH)
|
|
1097
|
+
// The cursors minted here carry only `adapter` and `type`. One with a project offset or
|
|
1098
|
+
// the carried root folders comes from the merged listing, and its `adapter` (if any)
|
|
1099
|
+
// is a position in the root's stream: following it here would restart the listing or
|
|
1100
|
+
// answer from another folder's offset.
|
|
1101
|
+
const { adapter: adapterCursor, project, folders: carried } = decoded.state
|
|
1102
|
+
if (cursor !== undefined && (project !== undefined || carried !== undefined || adapterCursor === undefined)) {
|
|
1103
|
+
return error('validation', MERGED_CURSOR_OUTSIDE_MERGE)
|
|
1104
|
+
}
|
|
1105
|
+
|
|
1106
|
+
const page = await listFilteredMedia(options => adapter.list(options), { limit, cursor: adapterCursor, folder, type })
|
|
1107
|
+
return json({
|
|
1108
|
+
...page,
|
|
1109
|
+
cursor: page.cursor === undefined ? undefined : encodeMediaCursor({ adapter: page.cursor, type }),
|
|
1110
|
+
})
|
|
1027
1111
|
}
|
|
1028
|
-
return listMergedMedia(adapter, limit, cursor)
|
|
1112
|
+
return listMergedMedia(adapter, limit, cursor, type)
|
|
1029
1113
|
}
|
|
1030
1114
|
|
|
1031
1115
|
// POST /media (multipart upload, or JSON create-folder)
|
|
@@ -1035,16 +1119,20 @@ export function createServer(opts: CreateServerOptions): CmsSidecarServer {
|
|
|
1035
1119
|
const parsed = await parseJson<CreateFolderBody>(req)
|
|
1036
1120
|
if (!parsed.ok) return parsed.response
|
|
1037
1121
|
if (!adapter.createFolder) return error('unsupported', 'Folder creation not supported by this adapter')
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1122
|
+
// The body is whatever JSON the caller sent, `null` included.
|
|
1123
|
+
const body: Partial<CreateFolderBody> | null = parsed.value
|
|
1124
|
+
const folder = body?.folder
|
|
1125
|
+
if (typeof folder !== 'string') return error('validation', 'A valid "folder" is required')
|
|
1126
|
+
// Held to the same rule as the bundled adapters for whatever adapter is configured.
|
|
1127
|
+
if (isUnsafeFolder(folder)) return error('validation', MEDIA_INVALID_FOLDER)
|
|
1128
|
+
const result = await adapter.createFolder(folder)
|
|
1129
|
+
return result.success ? json(result) : mediaFailure(result.error ?? 'Failed to create folder')
|
|
1043
1130
|
}
|
|
1044
1131
|
if (!contentType.includes('multipart/form-data')) {
|
|
1045
1132
|
return error('validation', 'Expected multipart/form-data or application/json')
|
|
1046
1133
|
}
|
|
1047
|
-
const form = await req.formData()
|
|
1134
|
+
const form = await req.formData().catch(() => null)
|
|
1135
|
+
if (form === null) return error('validation', 'Malformed multipart/form-data body')
|
|
1048
1136
|
const file = form.get('file')
|
|
1049
1137
|
if (!(file instanceof File)) return error('validation', 'No "file" found in the form data')
|
|
1050
1138
|
if (file.size > maxUploadSize) {
|
|
@@ -1053,13 +1141,26 @@ export function createServer(opts: CreateServerOptions): CmsSidecarServer {
|
|
|
1053
1141
|
const buffer = Buffer.from(await file.arrayBuffer())
|
|
1054
1142
|
const folder = url.searchParams.get('folder') ?? undefined
|
|
1055
1143
|
const result = await adapter.upload(buffer, file.name, file.type || 'application/octet-stream', { folder })
|
|
1056
|
-
return result.success ? json(result) :
|
|
1144
|
+
return result.success ? json(result) : mediaFailure(result.error ?? 'Upload failed')
|
|
1057
1145
|
}
|
|
1058
1146
|
|
|
1059
1147
|
// DELETE /media/:id
|
|
1060
1148
|
if (id !== undefined && method === 'DELETE') {
|
|
1061
1149
|
const result = await adapter.delete(id)
|
|
1062
|
-
return result.success ? json({ success: true }) :
|
|
1150
|
+
return result.success ? json({ success: true }) : mediaFailure(result.error ?? 'Delete failed')
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
// PATCH /media/:id { annotation }
|
|
1154
|
+
if (id !== undefined && method === 'PATCH') {
|
|
1155
|
+
if (!adapter.updateAnnotation) return error('unsupported', 'Annotations are not supported by this adapter')
|
|
1156
|
+
const parsed = await parseJson<UpdateMediaAnnotationBody>(req)
|
|
1157
|
+
if (!parsed.ok) return parsed.response
|
|
1158
|
+
// The body is whatever JSON the caller sent, `null` included.
|
|
1159
|
+
const body: Partial<UpdateMediaAnnotationBody> | null = parsed.value
|
|
1160
|
+
const annotation = body?.annotation
|
|
1161
|
+
if (typeof annotation !== 'string') return error('validation', 'A string "annotation" is required')
|
|
1162
|
+
const result = await adapter.updateAnnotation(id, annotation)
|
|
1163
|
+
return result.success ? json({ success: true }) : mediaFailure(result.error ?? 'Failed to update the annotation')
|
|
1063
1164
|
}
|
|
1064
1165
|
|
|
1065
1166
|
return error('not_found', `No route: ${method} /cms/v1/media${id ? `/${id}` : ''}`)
|
package/src/types.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { CollectionDefinition, CollectionEntryInfo } from '@nuasite/cms-types'
|
|
1
|
+
import type { CollectionDefinition, CollectionEntryInfo, CollectionScanReport } from '@nuasite/cms-types'
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Wire-level types specific to the `/cms/v1` HTTP contract. The structural model
|
|
@@ -90,6 +90,10 @@ export interface CreateFolderBody {
|
|
|
90
90
|
folder: string
|
|
91
91
|
}
|
|
92
92
|
|
|
93
|
+
export interface UpdateMediaAnnotationBody {
|
|
94
|
+
annotation: string
|
|
95
|
+
}
|
|
96
|
+
|
|
93
97
|
/** Parsed `GET …/entries` query. */
|
|
94
98
|
export interface EntriesQuery {
|
|
95
99
|
/** "slug,title" | "*" ; absent = light header (slug/title/draft/pathname/sourcePath), never the body. */
|
|
@@ -131,6 +135,11 @@ export interface ProjectModel {
|
|
|
131
135
|
/** Static page routes discovered under `src/pages` (pathname-only). */
|
|
132
136
|
pages: PageEntry[]
|
|
133
137
|
capabilities: Capabilities
|
|
138
|
+
/**
|
|
139
|
+
* What the scan behind `collections` could not vouch for. Absent when the core does not
|
|
140
|
+
* report, which is not the same as a report with nothing in it — see `CollectionScanReport`.
|
|
141
|
+
*/
|
|
142
|
+
collectionScan?: CollectionScanReport
|
|
134
143
|
}
|
|
135
144
|
|
|
136
145
|
/** Sparse list response: the projected entries plus an opaque continuation cursor. */
|