@nuasite/cms-core 0.52.0 → 0.54.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.
Files changed (40) hide show
  1. package/dist/types/asset-paths.d.ts +28 -0
  2. package/dist/types/asset-paths.d.ts.map +1 -0
  3. package/dist/types/check-entries.d.ts +50 -0
  4. package/dist/types/check-entries.d.ts.map +1 -0
  5. package/dist/types/check-live.d.ts +25 -0
  6. package/dist/types/check-live.d.ts.map +1 -0
  7. package/dist/types/check-shape.d.ts +28 -0
  8. package/dist/types/check-shape.d.ts.map +1 -0
  9. package/dist/types/check-write.d.ts +35 -0
  10. package/dist/types/check-write.d.ts.map +1 -0
  11. package/dist/types/check.d.ts +21 -1
  12. package/dist/types/check.d.ts.map +1 -1
  13. package/dist/types/content-config-ast.d.ts +2 -0
  14. package/dist/types/content-config-ast.d.ts.map +1 -1
  15. package/dist/types/editor-write-model.d.ts +48 -0
  16. package/dist/types/editor-write-model.d.ts.map +1 -0
  17. package/dist/types/handlers/entry-ops.d.ts.map +1 -1
  18. package/dist/types/index.d.ts +9 -1
  19. package/dist/types/index.d.ts.map +1 -1
  20. package/dist/types/schema-port.d.ts +43 -0
  21. package/dist/types/schema-port.d.ts.map +1 -0
  22. package/dist/types/schema-probe.d.ts +53 -0
  23. package/dist/types/schema-probe.d.ts.map +1 -0
  24. package/dist/types/shared.d.ts +3 -10
  25. package/dist/types/shared.d.ts.map +1 -1
  26. package/dist/types/tsconfig.tsbuildinfo +1 -1
  27. package/package.json +7 -2
  28. package/src/asset-paths.ts +54 -0
  29. package/src/check-entries.ts +120 -0
  30. package/src/check-live.ts +61 -0
  31. package/src/check-shape.ts +137 -0
  32. package/src/check-write.ts +280 -0
  33. package/src/check.ts +198 -63
  34. package/src/content-config-ast.ts +196 -17
  35. package/src/editor-write-model.ts +82 -0
  36. package/src/handlers/entry-ops.ts +42 -64
  37. package/src/index.ts +30 -1
  38. package/src/schema-port.ts +46 -0
  39. package/src/schema-probe.ts +133 -0
  40. package/src/shared.ts +3 -19
@@ -0,0 +1,82 @@
1
+ /**
2
+ * What the editor actually writes when it creates an entry — the create-route half.
3
+ *
4
+ * The value rules underneath (what a blank field holds, which keys a repeater item carries,
5
+ * which required fields count as unfilled) live in `@nuasite/cms-types` so that every editor
6
+ * can reach them: `collections-admin` and webmaster's own collections panel depend on
7
+ * `cms-client`, which is a sibling of this package, not a consumer. They are re-exported here
8
+ * because the create pipeline reads as one thing.
9
+ *
10
+ * What stays is what only makes sense next to the create route: the form's starting
11
+ * frontmatter, the empty filter the request applies, and the keys the route injects.
12
+ *
13
+ * A check built on a second, drifted copy of any of this reports failures that cannot happen
14
+ * and misses the ones that can — which is why none of it may be reimplemented anywhere.
15
+ */
16
+
17
+ import { defaultValueForNewEntry, type WriteModelField } from '@nuasite/cms-types'
18
+
19
+ export {
20
+ blankRequiredFields,
21
+ defaultValueForNewEntry,
22
+ isBlankFieldValue,
23
+ newRepeaterItem,
24
+ type RepeaterItemField,
25
+ type RequiredGuardField,
26
+ type WriteModelField,
27
+ } from '@nuasite/cms-types'
28
+
29
+ /**
30
+ * The frontmatter the editor holds when "create entry" opens, before the user types.
31
+ *
32
+ * `title` is excluded because the create form carries it in its own header field, and
33
+ * hidden fields are excluded because the form cannot fill them in. Neither is missing from
34
+ * the finished entry — see `applyCreateRouteFields`, which is what puts `title` back.
35
+ */
36
+ export function newEntryFrontmatter(fields: WriteModelField[], today?: () => Date): Record<string, unknown> {
37
+ const frontmatter: Record<string, unknown> = {}
38
+ for (const field of fields) {
39
+ if (field.name === 'title' || field.hidden) continue
40
+ frontmatter[field.name] = defaultValueForNewEntry(field, today)
41
+ }
42
+ return frontmatter
43
+ }
44
+
45
+ /** Whether the create route treats a collection's files as markdown entries or as plain data. */
46
+ export type CollectionKind = 'markdown' | 'data'
47
+
48
+ /**
49
+ * The last step of a create: what the server adds before the file is written.
50
+ *
51
+ * A markdown entry gets the title from the form — which refuses to be blank — plus today's
52
+ * date, and the form's own frontmatter wins over both (`handlers/api-routes.ts`). A data
53
+ * entry is written verbatim, with the title already among its fields.
54
+ *
55
+ * Anything predicting a create has to apply this. Stopping at the editor's payload predicts
56
+ * an entry with no title, and then reports a required `title` as broken on every project.
57
+ */
58
+ export function applyCreateRouteFields(
59
+ frontmatter: Record<string, unknown>,
60
+ kind: CollectionKind,
61
+ today: () => Date = () => new Date(),
62
+ ): Record<string, unknown> {
63
+ const title = 'Untitled'
64
+ if (kind === 'data') return { title, ...frontmatter }
65
+ return { title, date: today().toISOString().split('T')[0], ...frontmatter }
66
+ }
67
+
68
+ /**
69
+ * What survives the create request.
70
+ *
71
+ * The editor drops empty strings and `undefined` rather than writing them, so a field
72
+ * the user left alone reaches the schema as *absent*, not as `''`. Anything predicting
73
+ * a create has to apply this — the two produce different validation errors, and only
74
+ * one of them is real.
75
+ */
76
+ export function omitEmptyOnCreate(frontmatter: Record<string, unknown>): Record<string, unknown> {
77
+ const out: Record<string, unknown> = {}
78
+ for (const [key, value] of Object.entries(frontmatter)) {
79
+ if (value !== undefined && value !== '') out[key] = value
80
+ }
81
+ return out
82
+ }
@@ -1,7 +1,9 @@
1
1
  import type { CollectionEntryInfo, ComponentDefinition, MutationResult } from '@nuasite/cms-types'
2
2
  import yaml from 'yaml'
3
+ import { assetBaseDir, resolveAssetCandidates } from '../asset-paths'
3
4
  import { scanCollections } from '../collection-scanner'
4
5
  import { type ParseCache, parseContentConfig } from '../content-config-ast'
6
+ import { blankRequiredFields, newRepeaterItem, type RepeaterItemField } from '../editor-write-model'
5
7
  import type { CmsFileSystem } from '../fs/types'
6
8
  import { mimeFromExt } from '../media/local'
7
9
  import { isPlainRecord, relativeImportPath, slugify } from '../shared'
@@ -84,46 +86,6 @@ async function resolveEntryPath(deps: EntryOpsDeps, collection: string, slug: st
84
86
  return null
85
87
  }
86
88
 
87
- /**
88
- * Resolve a stored asset value (as it appears in frontmatter) to candidate on-disk
89
- * paths, root-relative, in priority order. Handles the shapes that actually occur:
90
- *
91
- * - **Leading `/`** — a runtime URL (`/assets/x.jpeg`, `/uploads/x.webp`). Astro
92
- * serves the `public/` dir at the site root, so try `public/<path>` first, then
93
- * `<path>` from the project root (assets kept outside `public/`). `baseDir` is
94
- * irrelevant, so these resolve without an owning entry.
95
- * - **Relative** (`../../src/assets/x.webp`, `./x.png`, `x.png`) — an Astro
96
- * `image()` value, resolved against `baseDir` (the entry's directory), honoring
97
- * `.`/`..`.
98
- *
99
- * Returns `[]` when the path climbs above the project root, or is relative with no `baseDir`.
100
- */
101
- function resolveAssetCandidates(baseDir: string | undefined, rel: string): string[] {
102
- if (rel.startsWith('/')) {
103
- const fromRoot = normalizeSegments([], rel)
104
- if (fromRoot === null || fromRoot === '') return []
105
- return [`public/${fromRoot}`, fromRoot]
106
- }
107
- if (baseDir === undefined) return []
108
- const joined = normalizeSegments(baseDir.split('/').filter(Boolean), rel)
109
- return joined === null ? [] : [joined]
110
- }
111
-
112
- /** Join `rel` onto `base` segments, applying `.`/`..`; `null` on traversal above root. */
113
- function normalizeSegments(base: string[], rel: string): string | null {
114
- const out = base.slice()
115
- for (const seg of rel.replace(/^\/+/, '').split('/')) {
116
- if (seg === '' || seg === '.') continue
117
- if (seg === '..') {
118
- if (out.length === 0) return null
119
- out.pop()
120
- continue
121
- }
122
- out.push(seg)
123
- }
124
- return out.join('/')
125
- }
126
-
127
89
  /** First existing candidate read as bytes + content type, or `null` when none exist. */
128
90
  async function readAsset(deps: EntryOpsDeps, candidates: string[]): Promise<EntryAsset | null> {
129
91
  for (const candidate of candidates) {
@@ -160,9 +122,7 @@ export async function getEntryAsset(deps: EntryOpsDeps, collection: string, slug
160
122
  if (assetPath.startsWith('/')) return readAsset(deps, resolveAssetCandidates(undefined, assetPath))
161
123
  const sourcePath = await resolveEntryPath(deps, collection, slug)
162
124
  if (!sourcePath) return null
163
- const lastSlash = sourcePath.lastIndexOf('/')
164
- const baseDir = lastSlash >= 0 ? sourcePath.slice(0, lastSlash) : ''
165
- return readAsset(deps, resolveAssetCandidates(baseDir, assetPath))
125
+ return readAsset(deps, resolveAssetCandidates(assetBaseDir(sourcePath), assetPath))
166
126
  }
167
127
 
168
128
  /**
@@ -358,20 +318,12 @@ function isIndexStyleGlobPattern(pattern: string): boolean {
358
318
  // Required-field validation
359
319
  // ============================================================================
360
320
 
361
- /**
362
- * No value at all — as opposed to an empty collection or a falsy scalar.
363
- *
364
- * `false` and `0` are values and pass. `[]` and `{}` are a deliberate "nothing here"
365
- * and pass too. Deliberately identical to the editor-side check so the two sides can
366
- * never disagree about what "empty" means.
367
- */
368
- function isBlank(value: unknown): boolean {
369
- return value === undefined || value === null || value === ''
370
- }
371
-
372
321
  /**
373
322
  * Names of the collection's **schema-declared** required fields left empty by `frontmatter`.
374
323
  *
324
+ * The predicate itself lives in `editor-write-model.ts`, shared with the content check —
325
+ * see there for which fields the guard deliberately does not cover.
326
+ *
375
327
  * Note on where `required` comes from — this reads the content config, never the
376
328
  * scanner, and that is the whole point. `scanCollections` *infers* `required` as
377
329
  * "the field is present in every scanned entry" (`mergeFieldObservations` in
@@ -385,21 +337,13 @@ function isBlank(value: unknown): boolean {
385
337
  *
386
338
  * A collection absent from `content.config.ts` therefore yields `[]` — nobody declared
387
339
  * anything required there, so there is nothing to enforce and the write goes through.
388
- *
389
- * Only top-level fields are checked. Nested object/array members are left alone: a
390
- * required key *inside* an object says nothing about whether that object was meant to
391
- * be filled in at all, and rejecting on it would block partial edits.
392
- *
393
- * `hidden` fields are skipped — the form offers no way to fill them in.
394
340
  */
395
341
  async function missingRequiredFields(deps: EntryOpsDeps, collection: string, frontmatter: Record<string, unknown>): Promise<string[]> {
396
342
  const parsed = await parseContentConfig(deps.fs, deps.parseCache)
397
343
  const parsedCollection = parsed.get(collection)
398
344
  if (!parsedCollection) return []
399
345
 
400
- return parsedCollection.fields
401
- .filter(field => field.required && !field.layout?.hidden && isBlank(frontmatter[field.name]))
402
- .map(field => field.name)
346
+ return blankRequiredFields(parsedCollection.fields, frontmatter)
403
347
  }
404
348
 
405
349
  /** Name the offending fields — the text reaches the UI verbatim, where "validation failed" would be useless. */
@@ -661,6 +605,40 @@ async function writeEntryFrontmatter(
661
605
  await deps.fs.writeFile(loaded.sourcePath, serializeFrontmatter(loaded.frontmatter, loaded.body))
662
606
  }
663
607
 
608
+ /**
609
+ * The item fields a repeater declares in `content.config.ts`, or `[]` when it declares none.
610
+ *
611
+ * Only top-level repeaters are resolved, which is the only shape `addArrayItem` is called for.
612
+ */
613
+ async function repeaterItemFields(deps: EntryOpsDeps, collection: string, field: string): Promise<RepeaterItemField[]> {
614
+ const parsed = await parseContentConfig(deps.fs, deps.parseCache)
615
+ const declared = parsed.get(collection)?.fields.find(candidate => candidate.name === field)
616
+ if (!declared || declared.type !== 'array' || declared.itemType !== 'object') return []
617
+ return (declared.fields ?? []).map(item => ({
618
+ name: item.name,
619
+ type: item.type,
620
+ required: item.required,
621
+ hidden: item.layout?.hidden,
622
+ }))
623
+ }
624
+
625
+ /**
626
+ * Seed the required keys a client left out of an appended item.
627
+ *
628
+ * The backstop for the "+ Add" hole. Both first-party editors now send a seeded item, but this
629
+ * path is reachable by any client — an older editor, a script, the HTTP API directly — and an
630
+ * item missing a required key is frontmatter the next build refuses. Whatever the client did
631
+ * send wins: this only adds keys, never rewrites a value someone chose.
632
+ */
633
+ function seedItem(value: unknown, fields: RepeaterItemField[]): unknown {
634
+ if (fields.length === 0 || typeof value !== 'object' || value === null || Array.isArray(value)) return value
635
+ const item: Record<string, unknown> = { ...value }
636
+ for (const [key, seeded] of Object.entries(newRepeaterItem(fields))) {
637
+ if (!Object.hasOwn(item, key) || item[key] === undefined) item[key] = seeded
638
+ }
639
+ return item
640
+ }
641
+
664
642
  export async function addArrayItem(deps: EntryOpsDeps, input: AddArrayItemInput): Promise<MutationResult> {
665
643
  const loaded = await loadEntryFrontmatter(deps, input.collection, input.slug)
666
644
  if (!loaded) {
@@ -675,7 +653,7 @@ export async function addArrayItem(deps: EntryOpsDeps, input: AddArrayItemInput)
675
653
 
676
654
  const index = input.index ?? array.length
677
655
  const clamped = Math.max(0, Math.min(index, array.length))
678
- array.splice(clamped, 0, input.value)
656
+ array.splice(clamped, 0, seedItem(input.value, await repeaterItemFields(deps, input.collection, input.field)))
679
657
  loaded.frontmatter[input.field] = array
680
658
 
681
659
  try {
package/src/index.ts CHANGED
@@ -1,4 +1,18 @@
1
- export { checkContent, type CheckFinding, type CheckReport, type CheckSeverity, formatCheckReport } from './check'
1
+ export { resolveAssetCandidates } from './asset-paths'
2
+ export { checkContent, type CheckContentOptions, type CheckFinding, type CheckReport, type CheckSeverity, formatCheckReport } from './check'
3
+ export {
4
+ collectionKind,
5
+ entryStem,
6
+ loadCollections,
7
+ type LoadedCollection,
8
+ type LoadedCollections,
9
+ type LoadedEntry,
10
+ normalizeBase,
11
+ parseEntry,
12
+ } from './check-entries'
13
+ export { checkAgainstSchemas, type LiveCheckInput } from './check-live'
14
+ export { checkFieldShapes, type ShapeCheckInput } from './check-shape'
15
+ export { checkEditorWrites, type WriteCheckInput } from './check-write'
2
16
  export { scanCollections } from './collection-scanner'
3
17
  export { scanComponentDefinitions } from './component-registry'
4
18
  export {
@@ -12,6 +26,19 @@ export {
12
26
  } from './content-config-ast'
13
27
  export { createCmsCore } from './core'
14
28
  export type { CmsCore, CmsCoreOptions } from './core'
29
+ export {
30
+ applyCreateRouteFields,
31
+ blankRequiredFields,
32
+ type CollectionKind,
33
+ defaultValueForNewEntry,
34
+ isBlankFieldValue,
35
+ newEntryFrontmatter,
36
+ newRepeaterItem,
37
+ omitEmptyOnCreate,
38
+ type RepeaterItemField,
39
+ type RequiredGuardField,
40
+ type WriteModelField,
41
+ } from './editor-write-model'
15
42
  export { globToRegExp } from './fs/glob'
16
43
  export { createNodeFs } from './fs/node-fs'
17
44
  export type { CmsFileSystem } from './fs/types'
@@ -42,4 +69,6 @@ export {
42
69
  uploadsDirRelativeToRoot,
43
70
  } from './media/index'
44
71
  export { parseProjectCmsConfig, parseProjectCmsConfigSource } from './project-config-ast'
72
+ export { describeIssue, type LiveIssue, type LiveParseResult, type LiveSchema, type LiveSchemas, schemaFor } from './schema-port'
73
+ export { acceptsMissing, firstAcceptedEntry, governsPath, pointAt, type ProbePoint, rejectsValueAt } from './schema-probe'
45
74
  export { computePathnameFromSpec, escapeHtml, relativeImportPath, resolvePathnameFromSpec, slugify, slugifyHref } from './shared'
@@ -0,0 +1,46 @@
1
+ /**
2
+ * The port through which a project's real collection schemas reach the checker.
3
+ *
4
+ * `cms-core` deliberately does not load them. Getting a live schema means importing the
5
+ * project's `content.config.ts`, which executes project code, needs an `astro:content`
6
+ * stub installed process-wide, and caches the module for the life of the process — all
7
+ * fine in a one-shot CLI, none of it acceptable inside the long-running dev server and
8
+ * sidecar that also load this package. The CLI does the loading and injects the result.
9
+ *
10
+ * `safeParse` is async because that is how Astro validates content
11
+ * (`astro/dist/content/utils.js` calls `safeParseAsync`), so a schema carrying an async
12
+ * refinement is legal and a synchronous parse would throw on it.
13
+ */
14
+
15
+ export interface LiveIssue {
16
+ /** Path to the offending value, as zod reports it: `['stats', 0, 'label']`. */
17
+ path: (string | number)[]
18
+ message: string
19
+ }
20
+
21
+ export type LiveParseResult = { success: true } | { success: false; issues: LiveIssue[] }
22
+
23
+ export interface LiveSchema {
24
+ safeParse(value: unknown): Promise<LiveParseResult>
25
+ }
26
+
27
+ /** Keyed by collection name. A collection missing from here has no live schema and is skipped. */
28
+ export type LiveSchemas = Record<string, LiveSchema>
29
+
30
+ /**
31
+ * Render an issue as a finding's `field` and `message`.
32
+ *
33
+ * Shared so the two live checkers phrase the same rejection identically — they report
34
+ * different actions but the same schema verdict, and a reader comparing them should not
35
+ * have to wonder whether a wording difference means something.
36
+ */
37
+ export function describeIssue(issue: LiveIssue): { field?: string; message: string } {
38
+ if (issue.path.length === 0) return { message: issue.message }
39
+ const field = issue.path.join('.')
40
+ return { field, message: `${field}: ${issue.message}` }
41
+ }
42
+
43
+ /** A collection's live schema, if it has one. Guards against inherited `Object.prototype` keys. */
44
+ export function schemaFor(schemas: LiveSchemas, collection: string): LiveSchema | undefined {
45
+ return Object.hasOwn(schemas, collection) ? schemas[collection] : undefined
46
+ }
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Ask a live schema what it thinks of one field, without the rest of the record answering for it.
3
+ *
4
+ * The static rules read the config's source and the live rules read the schema's verdict on a
5
+ * whole entry. Neither can say what the schema believes about a *single* field, which is what the
6
+ * drift rules need: whether it insists on the key, whether it would take text there.
7
+ *
8
+ * The technique is the same for every question. Start from an entry the schema already accepts,
9
+ * change exactly one value, parse again, and look at where the issues land. Starting from an
10
+ * accepted entry is what makes the answer attributable — on a record the schema already rejects,
11
+ * every probe comes back "rejected" and means nothing. Reading the issue's *path* rather than
12
+ * overall success is the other half: a schema with a cross-field refinement can fail for reasons
13
+ * that have nothing to do with the field being probed.
14
+ *
15
+ * Every function here is total. A schema that throws answers "I don't know", which callers read
16
+ * as "report nothing" — a rule that cannot get evidence has to stay quiet rather than guess.
17
+ */
18
+
19
+ import type { LoadedEntry } from './check-entries'
20
+ import type { LiveSchema } from './schema-port'
21
+
22
+ /** One field in one record: the accepted entry to start from, and where the field sits in it. */
23
+ export interface ProbePoint {
24
+ /** Never mutated — every probe works on a clone. */
25
+ record: Record<string, unknown>
26
+ path: (string | number)[]
27
+ }
28
+
29
+ /** The point for a top-level field of `seed`. The probe sets the key, so the seed need not already carry it. */
30
+ export const pointAt = (seed: Record<string, unknown>, field: string): ProbePoint => ({ record: seed, path: [field] })
31
+
32
+ /**
33
+ * Values chosen so that no realistic schema accepts all four.
34
+ *
35
+ * They answer one question: does the schema have an opinion about this path at all? A field the
36
+ * parser invented, or one landing in a `passthrough()`/`catchall()` object, accepts anything and
37
+ * must not be reported — a rule firing on a field the schema never governs is a false positive on
38
+ * a project that is fine.
39
+ */
40
+ const GOVERNANCE_PROBES: unknown[] = [{ __nuaProbe: true }, ['__nua_probe__'], 918_273.456, null]
41
+
42
+ type Mutation = { set: unknown } | { remove: true }
43
+
44
+ const isContainer = (value: unknown): value is Record<string | number, unknown> => typeof value === 'object' && value !== null
45
+
46
+ /** A copy of the record with one value changed, or `null` when it cannot be built. */
47
+ function mutated(point: ProbePoint, mutation: Mutation): Record<string, unknown> | null {
48
+ let copy: Record<string, unknown>
49
+ try {
50
+ copy = structuredClone(point.record)
51
+ } catch {
52
+ // Frontmatter is plain data, so this should not happen — but an unclonable value must cost
53
+ // this one probe, not the run.
54
+ return null
55
+ }
56
+
57
+ let parent: unknown = copy
58
+ for (const segment of point.path.slice(0, -1)) {
59
+ if (!isContainer(parent)) return null
60
+ parent = parent[segment]
61
+ }
62
+ const last = point.path.at(-1)
63
+ if (last === undefined || !isContainer(parent)) return null
64
+
65
+ if ('remove' in mutation) delete parent[last]
66
+ else parent[last] = mutation.set
67
+ return copy
68
+ }
69
+
70
+ /** What one probe learned. `unknown` is a schema that threw, or a record that could not be built. */
71
+ type ProbeVerdict = 'accepted' | 'rejected-here' | 'rejected-elsewhere' | 'unknown'
72
+
73
+ async function probe(schema: LiveSchema, point: ProbePoint, mutation: Mutation): Promise<ProbeVerdict> {
74
+ const value = mutated(point, mutation)
75
+ if (value === null) return 'unknown'
76
+ try {
77
+ const result = await schema.safeParse(value)
78
+ if (result.success) return 'accepted'
79
+ const here = result.issues.some(issue => point.path.every((segment, index) => issue.path[index] === segment))
80
+ return here ? 'rejected-here' : 'rejected-elsewhere'
81
+ } catch {
82
+ return 'unknown'
83
+ }
84
+ }
85
+
86
+ /**
87
+ * Whether the schema constrains this path at all.
88
+ *
89
+ * True as soon as one probe value is refused *at the path*. False means either a schema that takes
90
+ * anything here or one that could not be asked; both are reasons to report nothing.
91
+ */
92
+ export async function governsPath(schema: LiveSchema, point: ProbePoint): Promise<boolean> {
93
+ for (const value of GOVERNANCE_PROBES) {
94
+ if (await probe(schema, point, { set: value }) === 'rejected-here') return true
95
+ }
96
+ return false
97
+ }
98
+
99
+ /**
100
+ * Whether the schema takes the record with this key removed.
101
+ *
102
+ * Deliberately strict — the whole record has to parse, not merely avoid an issue at this path. The
103
+ * claim built on it is that the editor blocks a save the build would accept, and a record failing
104
+ * elsewhere is not evidence the build would accept anything.
105
+ */
106
+ export async function acceptsMissing(schema: LiveSchema, point: ProbePoint): Promise<boolean> {
107
+ return await probe(schema, point, { remove: true }) === 'accepted'
108
+ }
109
+
110
+ /** Whether the schema refuses `value` *at this path*, as opposed to failing for some unrelated reason. */
111
+ export async function rejectsValueAt(schema: LiveSchema, point: ProbePoint, value: unknown): Promise<boolean> {
112
+ return await probe(schema, point, { set: value }) === 'rejected-here'
113
+ }
114
+
115
+ /**
116
+ * The first entry the schema accepts, or `undefined` when there is none.
117
+ *
118
+ * Shared with the write check so both mean the same thing by "a record the editor is really
119
+ * sitting on". Seeding from a rejected entry would blame every probe for that entry's own
120
+ * problems, which `check-live.ts` already reports.
121
+ */
122
+ export async function firstAcceptedEntry(schema: LiveSchema, entries: LoadedEntry[]): Promise<Record<string, unknown> | undefined> {
123
+ for (const entry of entries) {
124
+ if (!entry.frontmatter) continue
125
+ try {
126
+ const result = await schema.safeParse(entry.frontmatter)
127
+ if (result.success) return entry.frontmatter
128
+ } catch {
129
+ // A schema that throws on an entry has not accepted it; `check-live.ts` reports the throw.
130
+ }
131
+ }
132
+ return undefined
133
+ }
package/src/shared.ts CHANGED
@@ -86,26 +86,10 @@ export function isPlainRecord(value: unknown): value is Record<string, unknown>
86
86
  }
87
87
 
88
88
  /**
89
- * Slugify text for URL paths.
90
- * Folds diacritics, lowercases, strips non-word characters, collapses whitespace/underscores
91
- * to hyphens. Keeps `/`, so a nested entry path survives — that is the only thing separating
92
- * this from `slugifyHref` above.
93
- *
94
- * The fold matters because this names the file a new entry is written to: `[^\w\s\-/]` alone
95
- * deletes diacritics rather than folding them, turning "Vedra jako zdravotní i sociální
96
- * problém" into "vedra-jako-zdravotn-i-sociln-problm" — which is what any host deriving a
97
- * slug from a Czech title would have to write to disk.
89
+ * Re-exported from `@nuasite/cms-types` so the server and every client slugify identically —
90
+ * a host deriving a slug locally is predicting this write. See `cms-types/src/slug.ts`.
98
91
  */
99
- export function slugify(text: string): string {
100
- return text
101
- .normalize('NFD')
102
- .replace(/[\u0300-\u036f]/g, '')
103
- .toLowerCase()
104
- .trim()
105
- .replace(/[^\w\s\-/]/g, '')
106
- .replace(/[\s_]+/g, '-')
107
- .replace(/^[-/]+|[-/]+$/g, '')
108
- }
92
+ export { slugify } from '@nuasite/cms-types'
109
93
 
110
94
  /**
111
95
  * Escape HTML special characters to prevent injection.