Repository navigation
Expand file tree
/
Copy pathauthoring-key-lint.ts
More file actions
289 lines (275 loc) · 17.3 KB
/
Copy pathauthoring-key-lint.ts
File metadata and controls
289 lines (275 loc) · 17.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
/**
* **Unknown authoring keys, reported instead of swallowed** (#3786).
*
* `ObjectSchema` and `FieldSchema` are deliberately not `.strict()`, so a key
* they do not declare parses clean and is **stripped on the way to storage**.
* The author gets no error; the capability they thought they configured simply
* is not there. That is the ADR-0104 failure class the `FieldSchema` prune
* tombstone already describes in prose, and #4120 found five live instances of
* it inside this very package — a `pii` toggle, an `indexed` toggle and a
* `cascadeDelete` select that had been rendering in Studio for releases while
* saving nothing.
*
* ## Why a lint and not `.strict()`
*
* Making these two schemas strict is the eventual destination — it is the
* enforce side of ADR-0049 and the tier programme #4001 started on the flow and
* permission schemas. But `object` and `field` are the two most-authored
* surfaces in the protocol, so flipping them rejects metadata that parses today:
* a migration event for every consumer, and one that should be scheduled on
* evidence rather than guessed at. This rule produces that evidence while
* costing nobody a migration — it reports, it never rejects.
*
* ## Why it lives in `@objectstack/spec` and not `@objectstack/lint`
*
* `@objectstack/lint`'s rules are `(stack) => Finding[]` over a **schema-parsed**
* stack. By then the unknown keys are gone — the parse is what ate them. This
* has to run **pre-parse**, on the authored input, which is the same seam the
* ADR-0087 D2 conversion notices already use in `defineStack`.
*
* ## Why this file is only the CORE
*
* This module carries the comparator, the finding shape and the curated guidance
* tables — deliberately nothing heavier. The stack WALKER
* (`lintUnknownAuthoringKeys`) lives in `kernel/metadata-authoring-lint.ts`,
* because covering every metadata type means importing every schema, and this
* file is re-exported from the `/data` subpath that frontend bundles consume
* (objectui reads `REFERENCE_VALUE_TYPES` and friends from it). Pulling the
* whole schema universe into that chunk to run a build-time lint would be its
* own regression. The kernel already is the everything-imports zone.
*
* @see ADR-0049 enforce-or-remove · ADR-0104 · #4001 (the strict tiers)
*/
import { suggestRename } from '../shared/rename-guess';
/**
* Which authoring surface a finding came from — a metadata type machine name
* (`'object'`, `'page'`, `'agent'`, …) or `'field'` for the one nested surface
* the walker descends into (an object's `fields` record).
*/
export type AuthoringKeySurface = string;
/** One unknown key on one authored object or field. */
export interface UnknownAuthoringKeyFinding {
/** Dotted path to the offending key, e.g. `objects.crm_case.fields.owner.pii`. */
path: string;
surface: AuthoringKeySurface;
/** The key the schema does not declare. */
key: string;
/**
* The canonical key this is a recognisable spelling of, when one is known.
* Comes from {@link FIELD_KEY_GUIDANCE} / {@link OBJECT_KEY_GUIDANCE} first,
* then from an edit-distance match against the declared keys.
*/
suggestion?: string;
/**
* Prescriptive sentence for a key that was RETIRED rather than renamed —
* where "did you mean X" would be wrong because there is no X.
*/
guidance?: string;
}
/**
* The route for a typed list, shared by the sub-field rows below. Module-private:
* the rows are the published face, and `@objectstack/lint` words its own finding.
*/
const EMBEDDED_JSON_TYPED_LIST =
'An object-level `composite` / `repeater` stores untyped JSON — no per-column labels, types, '
+ 'options or required flags. A list that needs typed columns is a child object whose '
+ '`master_detail` field points back at this object; a field group on this object whose '
+ '`relatedList` names that child edits its rows as an inline grid on this object\'s form.';
/**
* Semantic near-misses on `FieldSchema` — a different **word** for the same
* intent, or a key that was retired outright.
*
* Every entry here was found in the wild. The rename half is what `object.metadata-form.ts`
* had drifted into by #4120; the retired half is the `auditTrail` / `dataQuality`
* / `encryptionConfig` family pruned in 2026-06 plus the field-level `index` flag
* removed in the 16.x line (#2377). Edit distance cannot reach most of these
* (`cascadeDelete` → `deleteBehavior` is 11 apart), which is exactly why they are
* named rather than left to the fallback.
*
* A `to` names a declared `FieldSchema` key; a `why` marks a retirement with no
* successor. `authoring-key-lint.test.ts` asserts every `to` really is declared,
* so this table cannot rot into advice pointing at keys that no longer exist.
*/
export const FIELD_KEY_GUIDANCE: Readonly<
Record<string, { to?: string; why?: string }>
> = Object.freeze({
// ── Renamed: the concept survives under a different key ──
referenceFilter: { to: 'lookupFilters' },
cascadeDelete: { to: 'deleteBehavior' },
formula: { to: 'expression' },
displayFormat: { to: 'autonumberFormat' },
summaryType: { to: 'summaryOperations' },
summaryField: { to: 'summaryOperations' },
// NOTE: no entry for `conditionalRequired`. It was removed as an alias in
// protocol 17 (#3855) but is still DECLARED on FieldSchema as a `retiredKey()`
// tombstone, so the schema rejects it with its own prescription. An entry here
// would be dead weight the lint never reaches — the test below enforces that.
index: { why: 'field-level index flags built no index and were removed in the 16.x line under ADR-0049 enforce-or-remove, which deletes a key no runtime reads — declare the index in the object\'s `indexes[]` instead.' },
// ── Retired: no successor key ──
indexed: { why: 'never a FieldSchema key; the field-level `index` flag built no index and was removed for it. Declare the index in the object\'s `indexes[]`.' },
immutable: { why: 'never a FieldSchema key. Use the `readonlyWhen` predicate to lock a field after creation.' },
filterable: { why: 'never a FieldSchema key — every declared column is filterable. `sortable` and `searchable` are the real knobs.' },
// NOTE: no entry for `placeholder`. It sat here as a retirement ("never a
// FieldSchema key") until the 2026-08-16 maintainer ruling on objectui#4676
// (#9019) declared it: four shipped objectui render surfaces apply an
// object-field-level `placeholder` at render time, so `FieldSchema` now
// declares the key and an entry here would be advice to delete a live key —
// the "no guidance entry names a key the schema now declares" test enforces
// the absence.
startingNumber: { why: 'never a FieldSchema key. An autonumber counter resets per rendered prefix, which `autonumberFormat` itself determines.' },
validation: { why: 'field-level predicates are not a FieldSchema key — author a `validation` metadata item on the object, which carries its own message.' },
errorMessage: { why: 'pairs with the `validation` key that never existed; a `validation` metadata item carries its own message.' },
audit: { why: 'the `auditTrail` family was pruned in 2026-06 as dead in both layers. Delete the key: a changed field\'s old → new values already show on the record activity timeline by default, and `fieldHistory: false` is this field\'s off switch (`fieldHistory: true` opts a media or structured-JSON field in).' },
auditTrail: { why: 'pruned in 2026-06 as dead in both layers. Delete the key: a changed field\'s old → new values already show on the record activity timeline by default, and `fieldHistory: false` is this field\'s off switch (`fieldHistory: true` opts a media or structured-JSON field in).' },
pii: { why: 'the `dataQuality` governance family was pruned in 2026-06 as dead in both layers — it enforced nothing.' },
dataQuality: { why: 'pruned in 2026-06 as dead in both layers, and its leftover `DataQualityRules` schema was deleted from the public API too — it enforced nothing.' },
encrypted: { why: 'the `encryptionConfig` family was pruned in 2026-06: it implied at-rest protection that never happened. The real channel is `type: \'secret\'`.' },
encryptionConfig: { why: 'pruned in 2026-06 — it implied at-rest protection that never happened. The real channel is `type: \'secret\'`.' },
// NOTE: no entry for `maskingRule`. It sat here as a retirement ("pruned in
// 2026-06 as dead in both layers — masking was never applied") until the
// 2026-08-16 maintainer ruling on #8993 re-introduced the key WITH its
// runtime consumer (plugin-security's FieldMasker applies partial masking on
// the read/export path), so `FieldSchema` now declares it and an entry here
// would be advice to delete a live key — the "no guidance entry names a key
// the schema now declares" test enforces the absence.
cached: { why: 'computed-field caching was pruned in 2026-06 and its leftover `ComputedFieldCache` schema was deleted with it; nothing read it, and it returns only together with a runtime consumer.' },
// The one snake_case key in this table, and the spelling is LOAD-BEARING.
// The two channels this table feeds do not agree on the key face: a `to`
// becomes a `strictObject` ALIAS, matched through `aliasProbe` (case folded,
// `_` / `-` / space stripped), so one camelCase row covers every separator
// spelling. A `why` becomes strict GUIDANCE, and that channel is documented
// and implemented as an exact, case-SENSITIVE match on the authored spelling
// (`shared/suggestions.zod.ts`), as is this file's own comparator
// (`guidance[key]`). So a camelCase row here would never be reached by the
// key authors actually write, and every test in this file would still pass —
// none of them asks whether an entry is ever consulted.
// ⛔ Do not "normalise" this to `idField` to match its neighbours; the
// reachability test in `authoring-key-lint.test.ts` fails if you do.
id_field: { why: '`id_field` was never a FieldSchema key: a lookup stores the referenced record\'s id, and which field holds that value is not an authored per-field choice — the picker resolves record identity itself. Use `displayField` to change which field is SHOWN as a candidate\'s label, and a seed dataset\'s `externalId` to author references by a portable natural key. The live `idField` is the one on an `inlineColumns` entry — the GridColumn mirror in `field.zod.ts`, which is a DIFFERENT schema.' },
// ── A typed list declared on an embedded-JSON field (ruling 6386744473) ──
// An object-level `composite` / `repeater` is untyped JSON BY RULING: no
// sub-field member is added, and a list that needs typed columns is a child
// object. These are the spellings an author reaches for when they expect one
// (the three the ruling names; objectui's structured cell documents `fields` /
// `subFields` as refused). Without a row the parse names the key and nothing
// else, so the author learns the key is wrong but not where the list goes.
// `@objectstack/lint`'s `field/embedded-sub-fields` says the same on the doors
// that never parse. A form view's `fields` sub-rows are a different schema.
fields: { why: `\`fields\` is not a field key: a field declares no sub-fields. ${EMBEDDED_JSON_TYPED_LIST}` },
subFields: { why: `\`subFields\` is not a field key: a field declares no sub-fields. ${EMBEDDED_JSON_TYPED_LIST}` },
columns: { why: `\`columns\` is not a field key. A lookup's picker columns are \`lookupColumns\`; a \`master_detail\` field's related-list columns are \`relatedListColumns\` and its inline-grid columns \`inlineColumns\`. ${EMBEDDED_JSON_TYPED_LIST}` },
});
/**
* Semantic near-misses on `ObjectSchema`. Smaller than the field table because
* the object surface has drifted less — `capabilities` is the one #4120 caught,
* and it had silenced an entire seven-toggle section of the metadata form.
*/
export const OBJECT_KEY_GUIDANCE: Readonly<
Record<string, { to?: string; why?: string }>
> = Object.freeze({
capabilities: { to: 'enable' },
features: { to: 'enable' },
namespace: { why: 'deprecated and removed — the object `name` is the canonical id everywhere. For module grouping embed a prefix in the name (`sys_user`).' },
tableName: { why: 'removed — the table name always equals the object `name`.' },
});
/**
* Semantic near-misses on the stack's own TOP-LEVEL keys
* (`ObjectStackDefinitionSchema`).
*
* Same silent-drop mechanism as the two tables above, one level up. The walker
* covers every metadata COLLECTION; this covers the envelope those collections
* sit in, which is where the silence is easiest to miss — an undeclared
* top-level key reads as configuration that took effect.
*
* `storage` is the worked example (#4167): `os serve` honoured it only on the
* one boot path that skips `defineStack`, so the same key configured a backend
* in one place and vanished in every other. A stack asking for S3 could
* silently get local disk.
*/
export const STACK_KEY_GUIDANCE: Readonly<
Record<string, { to?: string; why?: string }>
> = Object.freeze({
storage: {
why: 'the file-storage backend is a deployment concern, not an application declaration. '
+ 'Configure it with the OS_STORAGE_* environment variables, or per-deployment in Setup → Audit & Data → File Storage '
+ '(which also holds credentials — a stack definition would commit them to git and to any published artifact).',
},
});
/**
* Authored TOP-LEVEL members the **runtime executes off the bundle**.
*
* `onEnable` is a function. It cannot survive `dist/objectstack.json` (JSON
* has no functions), yet it is not lost: `AppPlugin` reads it off the authored
* bundle and calls it at `start()`, and on the artifact-boot path the CLI
* grafts it back (#4095). It is the documented place to register action
* handlers, and `examples/app-todo` and `examples/app-showcase` both ship it.
*
* HISTORY: until #8687 the stack schema deliberately did NOT declare
* `onEnable`, and this list existed to keep the top-level lint from calling a
* working handler registration "dropped at load" — "not declared" and
* "dropped at load" are different claims, and this was the one surface where
* they came apart. #8687 closed `ObjectStackDefinitionSchema` against unknown
* keys, which forced the honest resolution: both members are now DECLARED
* (`declared = honoured`), the strict parse accepts them, and the lint goes
* quiet on the whole strict surface by its own posture rule. The list stays
* because the CLI's graft derives from it (see below); each member also
* self-excludes from the lint the way `functions` always did.
*
* `onDisable` is deliberately ABSENT: no kernel, runtime or service ever
* called it (the protocol declared it until #4212 retired the whole uninvoked
* lifecycle family), so a value written there really does go nowhere — the
* strict parse now refuses it with that prescription.
*
* Single source of truth — the CLI's `GRAFTABLE_RUNTIME_MEMBERS` is derived
* from this, so the list that decides what gets grafted and the list that
* decides what the lint stays quiet about cannot drift apart.
*/
export const STACK_RUNTIME_MEMBERS = Object.freeze(['onEnable', 'functions'] as const);
/** A plain object — the only shape an authored metadata item can take. */
export function isPlainRecord(v: unknown): v is Record<string, unknown> {
return !!v && typeof v === 'object' && !Array.isArray(v);
}
/**
* Compare one authored record's keys against a declared key set, appending a
* finding per unknown key. The single comparator behind every surface the
* walker covers.
*
* Keys starting with `_` are skipped: they are the packaging/provenance channel
* (`_packageId`, `_lock`, `_provenance`) that tooling stamps onto artifacts, and
* a stray one is a tooling concern, not an authoring mistake.
*/
export function lintAuthoredRecordKeys(
record: Record<string, unknown>,
declared: ReadonlySet<string>,
guidance: Readonly<Record<string, { to?: string; why?: string }>>,
surface: AuthoringKeySurface,
basePath: string,
out: UnknownAuthoringKeyFinding[],
): void {
const candidates = [...declared];
for (const key of Object.keys(record)) {
if (declared.has(key) || key.startsWith('_')) continue;
const hint = guidance[key];
// A retirement (`why`, no `to`) deliberately suppresses the edit-distance
// fallback: there IS no successor, and the nearest declared key by spelling
// is noise — `pii` is 3 edits from `min`, which would read as real advice.
// The fallback is the package's one rename rule (`shared/rename-guess.ts`):
// a flat distance of 3 answered a short key with anything three edits away.
const suggestion = hint?.to ?? (hint?.why ? undefined : suggestRename(key, candidates));
out.push({
path: `${basePath}.${key}`,
surface,
key,
...(suggestion ? { suggestion } : {}),
...(hint?.why ? { guidance: hint.why } : {}),
});
}
}
/** One human-readable line for a finding — shared by `defineStack` and the CLI. */
export function formatUnknownAuthoringKey(f: UnknownAuthoringKeyFinding): string {
const head = `${f.path}: '${f.key}' is not a declared ${f.surface} key, so its value is dropped at load`;
if (f.guidance) return `${head} — ${f.guidance}`;
if (f.suggestion) return `${head} — did you mean '${f.suggestion}'?`;
return `${head}.`;
}