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