@nuasite/cms-sidecar 0.70.4 → 0.71.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 +6 -0
- package/dist/cli.bundle.js +205 -70
- package/dist/concurrency.d.ts +7 -3
- package/dist/concurrency.d.ts.map +1 -1
- package/dist/concurrency.js +8 -4
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +74 -45
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/dist/types.d.ts +8 -2
- package/dist/types.d.ts.map +1 -1
- package/package.json +3 -3
- package/src/concurrency.ts +8 -5
- package/src/server.ts +68 -41
- package/src/types.ts +9 -2
package/package.json
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
"directory": "packages/cms-sidecar"
|
|
15
15
|
},
|
|
16
16
|
"license": "Apache-2.0",
|
|
17
|
-
"version": "0.
|
|
17
|
+
"version": "0.71.0",
|
|
18
18
|
"module": "./dist/index.js",
|
|
19
19
|
"types": "./dist/index.d.ts",
|
|
20
20
|
"type": "module",
|
|
@@ -30,8 +30,8 @@
|
|
|
30
30
|
"cms-sidecar": "src/cli.ts"
|
|
31
31
|
},
|
|
32
32
|
"dependencies": {
|
|
33
|
-
"@nuasite/cms-core": "0.
|
|
34
|
-
"@nuasite/cms-types": "0.
|
|
33
|
+
"@nuasite/cms-core": "0.71.0",
|
|
34
|
+
"@nuasite/cms-types": "0.71.0"
|
|
35
35
|
},
|
|
36
36
|
"devDependencies": {
|
|
37
37
|
"@types/bun": "1.3.11"
|
package/src/concurrency.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type CmsFileSystem, digestBytes } from '@nuasite/cms-core'
|
|
2
2
|
import { createHash } from 'node:crypto'
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -10,19 +10,22 @@ import { createHash } from 'node:crypto'
|
|
|
10
10
|
* the bytes a subsequent `getEntry` would parse.
|
|
11
11
|
*/
|
|
12
12
|
|
|
13
|
-
/**
|
|
13
|
+
/**
|
|
14
|
+
* Stable content hash of a UTF-8 string: `sha256:<hex>`. Equal to the `sourceHash` of a file only when
|
|
15
|
+
* the file is valid UTF-8 that decodes to `content`; the server hashes the bytes (`hashSource`).
|
|
16
|
+
*/
|
|
14
17
|
export function hashContent(content: string): string {
|
|
15
18
|
return `sha256:${createHash('sha256').update(content, 'utf-8').digest('hex')}`
|
|
16
19
|
}
|
|
17
20
|
|
|
18
21
|
/**
|
|
19
22
|
* Hash the current on-disk source at `sourcePath`, or `null` when the file does
|
|
20
|
-
* not exist.
|
|
23
|
+
* not exist. Hashes the bytes, as cms-core does for a read and a write, so the
|
|
24
|
+
* values compare exactly.
|
|
21
25
|
*/
|
|
22
26
|
export async function hashSource(fs: CmsFileSystem, sourcePath: string): Promise<string | null> {
|
|
23
27
|
if (!(await fs.exists(sourcePath))) return null
|
|
24
|
-
|
|
25
|
-
return hashContent(raw)
|
|
28
|
+
return digestBytes(await fs.readBytes(sourcePath))
|
|
26
29
|
}
|
|
27
30
|
|
|
28
31
|
/**
|
package/src/server.ts
CHANGED
|
@@ -33,7 +33,7 @@ import type {
|
|
|
33
33
|
MediaTypeFilter,
|
|
34
34
|
MutationResult,
|
|
35
35
|
} from '@nuasite/cms-types'
|
|
36
|
-
import {
|
|
36
|
+
import { hashSource, KeyedMutex, SharedRun } from './concurrency.ts'
|
|
37
37
|
import {
|
|
38
38
|
type AddArrayItemBody,
|
|
39
39
|
type ApiError,
|
|
@@ -41,6 +41,7 @@ import {
|
|
|
41
41
|
type ConflictResponse,
|
|
42
42
|
type CreateEntryBody,
|
|
43
43
|
type CreateFolderBody,
|
|
44
|
+
type DeleteEntryBody,
|
|
44
45
|
type EntriesListResult,
|
|
45
46
|
type EntriesQuery,
|
|
46
47
|
type ErrorCode,
|
|
@@ -161,6 +162,28 @@ async function parseJson<T>(req: Request): Promise<{ ok: true; value: T } | { ok
|
|
|
161
162
|
}
|
|
162
163
|
}
|
|
163
164
|
|
|
165
|
+
/** A body that may be absent: no body reads as `undefined`, anything else must be JSON. */
|
|
166
|
+
async function parseOptionalJson<T>(req: Request): Promise<{ ok: true; value: T | undefined } | { ok: false; response: Response }> {
|
|
167
|
+
const text = await req.text()
|
|
168
|
+
if (text.trim() === '') return { ok: true, value: undefined }
|
|
169
|
+
try {
|
|
170
|
+
// See `parseJson`: the route validates every field it reads.
|
|
171
|
+
const value: T = JSON.parse(text)
|
|
172
|
+
return { ok: true, value }
|
|
173
|
+
} catch {
|
|
174
|
+
return { ok: false, response: error('validation', 'Invalid JSON body') }
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function isOptionalHash(value: unknown): value is string | undefined {
|
|
179
|
+
return value === undefined || (typeof value === 'string' && value !== '')
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** A JSON object, the only shape a request body takes. */
|
|
183
|
+
function isBodyObject(value: unknown): value is object {
|
|
184
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
185
|
+
}
|
|
186
|
+
|
|
164
187
|
function parseEntriesQuery(url: URL): EntriesQuery {
|
|
165
188
|
const fields = url.searchParams.get('fields') ?? undefined
|
|
166
189
|
const rawDraft = url.searchParams.get('draft')
|
|
@@ -660,6 +683,7 @@ export function createServer(opts: CreateServerOptions): CmsSidecarServer {
|
|
|
660
683
|
frontmatter,
|
|
661
684
|
body: result.content,
|
|
662
685
|
bodyStartLine: 0,
|
|
686
|
+
sourceHash: result.sourceHash,
|
|
663
687
|
}
|
|
664
688
|
return json(entry)
|
|
665
689
|
}
|
|
@@ -687,26 +711,10 @@ export function createServer(opts: CreateServerOptions): CmsSidecarServer {
|
|
|
687
711
|
const existing = await core.getEntry(collection, slug)
|
|
688
712
|
if (!existing) return error('not_found', `Entry not found: ${collection}/${slug}`)
|
|
689
713
|
const sourcePath = existing.sourcePath
|
|
690
|
-
const existingFrontmatter = existing.frontmatter
|
|
691
|
-
|
|
692
|
-
/** The 409 with the entry as it is now, so the client can offer "use server" vs "use ours". */
|
|
693
|
-
async function conflictResponse(serverHash: string): Promise<Response> {
|
|
694
|
-
const current = await core.getEntry(collection, slug)
|
|
695
|
-
const conflict: ConflictResponse = {
|
|
696
|
-
code: 'conflict',
|
|
697
|
-
serverHash,
|
|
698
|
-
serverFrontmatter: current?.frontmatter ?? existingFrontmatter,
|
|
699
|
-
}
|
|
700
|
-
if (current && current.content !== '') conflict.serverBody = current.content
|
|
701
|
-
return json(conflict, STATUS_BY_CODE.conflict)
|
|
702
|
-
}
|
|
703
714
|
|
|
704
715
|
return mutex.runExclusive(sourcePath, async () => {
|
|
705
716
|
// Re-hash under the lock so a concurrent writer cannot slip in between.
|
|
706
|
-
|
|
707
|
-
if (body.baseHash !== undefined && serverHash !== null && body.baseHash !== serverHash) {
|
|
708
|
-
return conflictResponse(serverHash)
|
|
709
|
-
}
|
|
717
|
+
if (await isStale(sourcePath, body.baseHash)) return conflictResponse(collection, slug)
|
|
710
718
|
|
|
711
719
|
let result: MutationResult
|
|
712
720
|
try {
|
|
@@ -719,20 +727,39 @@ export function createServer(opts: CreateServerOptions): CmsSidecarServer {
|
|
|
719
727
|
} catch (cause) {
|
|
720
728
|
// The core's commit found the file changed by a writer outside this server's lock.
|
|
721
729
|
if (!(cause instanceof CmsCommitConflictError)) throw cause
|
|
722
|
-
const currentHash = await hashSource(fs, sourcePath)
|
|
723
730
|
// Removed meanwhile: there is no server version to offer, only the plain conflict.
|
|
724
|
-
if (
|
|
725
|
-
return conflictResponse(
|
|
731
|
+
if (await hashSource(fs, sourcePath) === null) throw cause
|
|
732
|
+
return conflictResponse(collection, slug)
|
|
726
733
|
}
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
const enriched: MutationResult = { ...result }
|
|
731
|
-
if (newHash !== null) enriched.sourceHash = newHash
|
|
732
|
-
return json(enriched)
|
|
734
|
+
// The result carries the hash of the bytes the core wrote; hashing the file again here
|
|
735
|
+
// could pick up a write that landed after it.
|
|
736
|
+
return mutationResponse(result)
|
|
733
737
|
})
|
|
734
738
|
}
|
|
735
739
|
|
|
740
|
+
/** Whether `baseHash` was given and no longer matches the file. Call under the file's lock. */
|
|
741
|
+
async function isStale(sourcePath: string, baseHash: string | undefined): Promise<boolean> {
|
|
742
|
+
if (baseHash === undefined) return false
|
|
743
|
+
const serverHash = await hashSource(fs, sourcePath)
|
|
744
|
+
return serverHash !== null && serverHash !== baseHash
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
/**
|
|
748
|
+
* The 409 with the entry as it is now, so the client can offer "use server" vs "use ours". The
|
|
749
|
+
* hash and the version come from one read, so they always describe the same bytes.
|
|
750
|
+
*/
|
|
751
|
+
async function conflictResponse(collection: string, slug: string): Promise<Response> {
|
|
752
|
+
const current = await core.getEntry(collection, slug)
|
|
753
|
+
if (current === null) return error('conflict', `Entry changed and was removed meanwhile: ${collection}/${slug}`)
|
|
754
|
+
const conflict: ConflictResponse = {
|
|
755
|
+
code: 'conflict',
|
|
756
|
+
serverHash: current.sourceHash,
|
|
757
|
+
serverFrontmatter: current.frontmatter,
|
|
758
|
+
}
|
|
759
|
+
if (current.content !== '') conflict.serverBody = current.content
|
|
760
|
+
return json(conflict, STATUS_BY_CODE.conflict)
|
|
761
|
+
}
|
|
762
|
+
|
|
736
763
|
async function fetchHandler(req: Request): Promise<Response> {
|
|
737
764
|
const url = new URL(req.url)
|
|
738
765
|
let pathname = url.pathname
|
|
@@ -841,7 +868,7 @@ export function createServer(opts: CreateServerOptions): CmsSidecarServer {
|
|
|
841
868
|
if (action === undefined) {
|
|
842
869
|
if (method === 'GET') return entryDetail(collection, slug)
|
|
843
870
|
if (method === 'PATCH') return updateEntryRoute(collection, slug, req)
|
|
844
|
-
if (method === 'DELETE') return deleteEntryRoute(collection, slug)
|
|
871
|
+
if (method === 'DELETE') return deleteEntryRoute(collection, slug, req)
|
|
845
872
|
return error('unsupported', `Unsupported: ${method} /collections/${collection}/entries/${slug}`)
|
|
846
873
|
}
|
|
847
874
|
|
|
@@ -896,12 +923,8 @@ export function createServer(opts: CreateServerOptions): CmsSidecarServer {
|
|
|
896
923
|
body: body.body,
|
|
897
924
|
fileExtension: body.fileExtension,
|
|
898
925
|
})
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
const newHash = result.sourcePath ? await hashSource(fs, result.sourcePath) : null
|
|
902
|
-
const enriched: MutationResult = { ...result }
|
|
903
|
-
if (newHash !== null) enriched.sourceHash = newHash
|
|
904
|
-
return json(enriched)
|
|
926
|
+
// The result carries the hash of the bytes the core wrote.
|
|
927
|
+
return mutationResponse(result)
|
|
905
928
|
}
|
|
906
929
|
|
|
907
930
|
async function updateEntryRoute(collection: string, slug: string, req: Request): Promise<Response> {
|
|
@@ -910,10 +933,16 @@ export function createServer(opts: CreateServerOptions): CmsSidecarServer {
|
|
|
910
933
|
return patchEntry(collection, slug, parsed.value)
|
|
911
934
|
}
|
|
912
935
|
|
|
913
|
-
async function deleteEntryRoute(collection: string, slug: string): Promise<Response> {
|
|
936
|
+
async function deleteEntryRoute(collection: string, slug: string, req: Request): Promise<Response> {
|
|
937
|
+
// The body is optional: a client that sends no `baseHash` deletes unchecked, as before.
|
|
938
|
+
const parsed = await parseOptionalJson<DeleteEntryBody>(req)
|
|
939
|
+
if (!parsed.ok) return parsed.response
|
|
940
|
+
if (parsed.value !== undefined && !isBodyObject(parsed.value)) return error('validation', 'The body must be a JSON object')
|
|
941
|
+
if (!isOptionalHash(parsed.value?.baseHash)) return error('validation', '"baseHash" must be a non-empty string')
|
|
914
942
|
const existing = await core.getEntry(collection, slug)
|
|
915
943
|
if (!existing) return error('not_found', `Entry not found: ${collection}/${slug}`)
|
|
916
944
|
return mutex.runExclusive(existing.sourcePath, async () => {
|
|
945
|
+
if (await isStale(existing.sourcePath, parsed.value?.baseHash)) return conflictResponse(collection, slug)
|
|
917
946
|
const result = await core.deleteEntry(collection, slug)
|
|
918
947
|
return mutationResponse(result)
|
|
919
948
|
})
|
|
@@ -925,15 +954,13 @@ export function createServer(opts: CreateServerOptions): CmsSidecarServer {
|
|
|
925
954
|
if (typeof parsed.value.to !== 'string' || parsed.value.to.trim() === '') {
|
|
926
955
|
return error('validation', 'A non-empty "to" slug is required')
|
|
927
956
|
}
|
|
957
|
+
if (!isOptionalHash(parsed.value.baseHash)) return error('validation', '"baseHash" must be a non-empty string')
|
|
928
958
|
const existing = await core.getEntry(collection, slug)
|
|
929
959
|
if (!existing) return error('not_found', `Entry not found: ${collection}/${slug}`)
|
|
930
960
|
return mutex.runExclusive(existing.sourcePath, async () => {
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
const enriched: MutationResult = { ...result }
|
|
935
|
-
if (newHash !== null) enriched.sourceHash = newHash
|
|
936
|
-
return json(enriched)
|
|
961
|
+
if (await isStale(existing.sourcePath, parsed.value.baseHash)) return conflictResponse(collection, slug)
|
|
962
|
+
// The result carries the hash of the bytes the core wrote at the new path.
|
|
963
|
+
return mutationResponse(await core.renameEntry(collection, slug, parsed.value.to))
|
|
937
964
|
})
|
|
938
965
|
}
|
|
939
966
|
|
package/src/types.ts
CHANGED
|
@@ -40,8 +40,8 @@ export const STATUS_BY_CODE: Record<ErrorCode, number> = {
|
|
|
40
40
|
}
|
|
41
41
|
|
|
42
42
|
/**
|
|
43
|
-
* Returned with `409` when a
|
|
44
|
-
* disk (an agent or a human wrote in between). Carries the current server
|
|
43
|
+
* Returned with `409` when a write's `baseHash` (`PATCH`, `DELETE`, rename) no longer
|
|
44
|
+
* matches the file on disk (an agent or a human wrote in between). Carries the current server
|
|
45
45
|
* version so the client can offer "use server" vs "use ours".
|
|
46
46
|
*/
|
|
47
47
|
export interface ConflictResponse {
|
|
@@ -73,6 +73,13 @@ export interface CreateEntryBody {
|
|
|
73
73
|
|
|
74
74
|
export interface RenameEntryBody {
|
|
75
75
|
to: string
|
|
76
|
+
/** Hash of the entry source the client saw; `409` on drift. Without it the rename is unchecked. */
|
|
77
|
+
baseHash?: string
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export interface DeleteEntryBody {
|
|
81
|
+
/** Hash of the entry source the client saw; `409` on drift. Without it the delete is unchecked. */
|
|
82
|
+
baseHash?: string
|
|
76
83
|
}
|
|
77
84
|
|
|
78
85
|
export interface AddArrayItemBody {
|