@nuasite/cms-sidecar 0.59.0 → 0.61.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/src/server.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import {
2
+ CmsCommitConflictError,
2
3
  type CmsCore,
3
4
  type CmsFileSystem,
5
+ type EntryAsset,
4
6
  isUnsafeFolder,
5
7
  listFilteredMedia,
6
8
  listProjectImages,
@@ -10,6 +12,7 @@ import {
10
12
  mediaErrorStatus,
11
13
  parseMediaTypeFilter,
12
14
  parseProjectCmsConfig,
15
+ resolveByteRange,
13
16
  resolvePathnameFromSpec,
14
17
  scanRouteCollections,
15
18
  } from '@nuasite/cms-core'
@@ -105,6 +108,19 @@ function error(code: ErrorCode, message: string, sourcePath?: string): Response
105
108
  return json(body, STATUS_BY_CODE[code])
106
109
  }
107
110
 
111
+ /** An asset's bytes, or the slice a `Range` request asked for — what a `<video>` preview needs to seek. */
112
+ function assetBytesResponse(asset: EntryAsset, req: Request): Response {
113
+ const size = asset.bytes.byteLength
114
+ const headers = { 'content-type': asset.contentType, 'cache-control': 'no-cache', 'accept-ranges': 'bytes' }
115
+ const range = resolveByteRange(req.headers.get('range'), size)
116
+ if (range === null) return new Response(asset.bytes, { headers })
117
+ if (range === 'unsatisfiable') return new Response(null, { status: 416, headers: { ...headers, 'content-range': `bytes */${size}` } })
118
+ return new Response(asset.bytes.subarray(range.start, range.end + 1), {
119
+ status: 206,
120
+ headers: { ...headers, 'content-range': `bytes ${range.start}-${range.end}/${size}` },
121
+ })
122
+ }
123
+
108
124
  /**
109
125
  * Map a cms-core `MutationResult` to an HTTP response. A failed result becomes a
110
126
  * typed `ApiError`: "not found" → 404, everything else (validation, already
@@ -609,21 +625,21 @@ export function createServer(opts: CreateServerOptions): CmsSidecarServer {
609
625
  }
610
626
 
611
627
  // --- GET entry asset (resolve an image/file value relative to the entry source, stream the bytes) ---
612
- async function assetResponse(collection: string, slug: string, url: URL): Promise<Response> {
628
+ async function assetResponse(collection: string, slug: string, req: Request, url: URL): Promise<Response> {
613
629
  const assetPath = url.searchParams.get('path')
614
630
  if (assetPath === null || assetPath === '') return error('validation', 'A "path" query parameter is required')
615
631
  const asset = await core.getEntryAsset(collection, slug, assetPath)
616
632
  if (!asset) return error('not_found', `Asset not found for ${collection}/${slug}: ${assetPath}`)
617
- return new Response(asset.bytes, { headers: { 'content-type': asset.contentType, 'cache-control': 'no-cache' } })
633
+ return assetBytesResponse(asset, req)
618
634
  }
619
635
 
620
636
  // --- GET project asset (resolve a root-relative /assets|/uploads value with no owning entry) ---
621
- async function projectAssetResponse(url: URL): Promise<Response> {
637
+ async function projectAssetResponse(req: Request, url: URL): Promise<Response> {
622
638
  const assetPath = url.searchParams.get('path')
623
639
  if (assetPath === null || assetPath === '') return error('validation', 'A "path" query parameter is required')
624
640
  const asset = await core.getProjectAsset(assetPath)
625
641
  if (!asset) return error('not_found', `Asset not found: ${assetPath}`)
626
- return new Response(asset.bytes, { headers: { 'content-type': asset.contentType, 'cache-control': 'no-cache' } })
642
+ return assetBytesResponse(asset, req)
627
643
  }
628
644
 
629
645
  // --- PATCH entry (optimistic concurrency + per-file mutex) ---
@@ -631,27 +647,43 @@ export function createServer(opts: CreateServerOptions): CmsSidecarServer {
631
647
  const existing = await core.getEntry(collection, slug)
632
648
  if (!existing) return error('not_found', `Entry not found: ${collection}/${slug}`)
633
649
  const sourcePath = existing.sourcePath
650
+ const existingFrontmatter = existing.frontmatter
651
+
652
+ /** The 409 with the entry as it is now, so the client can offer "use server" vs "use ours". */
653
+ async function conflictResponse(serverHash: string): Promise<Response> {
654
+ const current = await core.getEntry(collection, slug)
655
+ const conflict: ConflictResponse = {
656
+ code: 'conflict',
657
+ serverHash,
658
+ serverFrontmatter: current?.frontmatter ?? existingFrontmatter,
659
+ }
660
+ if (current && current.content !== '') conflict.serverBody = current.content
661
+ return json(conflict, STATUS_BY_CODE.conflict)
662
+ }
634
663
 
635
664
  return mutex.runExclusive(sourcePath, async () => {
636
665
  // Re-hash under the lock so a concurrent writer cannot slip in between.
637
666
  const serverHash = await hashSource(fs, sourcePath)
638
667
  if (body.baseHash !== undefined && serverHash !== null && body.baseHash !== serverHash) {
639
- const current = await core.getEntry(collection, slug)
640
- const conflict: ConflictResponse = {
641
- code: 'conflict',
642
- serverHash,
643
- serverFrontmatter: current?.frontmatter ?? existing.frontmatter,
644
- }
645
- if (current && current.content !== '') conflict.serverBody = current.content
646
- return json(conflict, STATUS_BY_CODE.conflict)
668
+ return conflictResponse(serverHash)
647
669
  }
648
670
 
649
- const result = await core.updateEntry({
650
- collection,
651
- slug,
652
- frontmatter: body.frontmatter,
653
- body: body.body,
654
- })
671
+ let result: MutationResult
672
+ try {
673
+ result = await core.updateEntry({
674
+ collection,
675
+ slug,
676
+ frontmatter: body.frontmatter,
677
+ body: body.body,
678
+ })
679
+ } catch (cause) {
680
+ // The core's commit found the file changed by a writer outside this server's lock.
681
+ if (!(cause instanceof CmsCommitConflictError)) throw cause
682
+ const currentHash = await hashSource(fs, sourcePath)
683
+ // Removed meanwhile: there is no server version to offer, only the plain conflict.
684
+ if (currentHash === null) throw cause
685
+ return conflictResponse(currentHash)
686
+ }
655
687
  if (!result.success) return mutationResponse(result)
656
688
 
657
689
  const newHash = await hashSource(fs, result.sourcePath ?? sourcePath)
@@ -685,6 +717,9 @@ export function createServer(opts: CreateServerOptions): CmsSidecarServer {
685
717
 
686
718
  try {
687
719
  return await route(method, segments, req, url)
720
+ } catch (cause) {
721
+ if (cause instanceof CmsCommitConflictError) return error('conflict', cause.message)
722
+ throw cause
688
723
  } finally {
689
724
  // Any write may change what the shared scans read.
690
725
  if (method !== 'GET') {
@@ -725,7 +760,7 @@ export function createServer(opts: CreateServerOptions): CmsSidecarServer {
725
760
  break
726
761
 
727
762
  case 'asset':
728
- if (method === 'GET') return projectAssetResponse(url)
763
+ if (method === 'GET') return projectAssetResponse(req, url)
729
764
  break
730
765
 
731
766
  case 'collections':
@@ -773,7 +808,7 @@ export function createServer(opts: CreateServerOptions): CmsSidecarServer {
773
808
  if (action === 'rename' && method === 'POST') return renameEntryRoute(collection, slug, req)
774
809
  if (action === 'array' && method === 'POST') return addArrayRoute(collection, slug, req)
775
810
  if (action === 'array' && method === 'DELETE') return removeArrayRoute(collection, slug, req)
776
- if (action === 'asset' && method === 'GET') return assetResponse(collection, slug, url)
811
+ if (action === 'asset' && method === 'GET') return assetResponse(collection, slug, req, url)
777
812
  }
778
813
 
779
814
  return error('not_found', `No route: ${method} /cms/v1/collections/${tail.join('/')}`)