@floless/app 0.134.2 → 0.134.3

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.
@@ -2397,7 +2397,9 @@ async function saveNow(){
2397
2397
  }
2398
2398
  if(revisionRequest === checkpointRequest){
2399
2399
  revisionRequest = '';
2400
- history.replaceState(null, '', location.pathname + PROJECT_QS);
2400
+ const url = new URL(location.href);
2401
+ url.searchParams.delete('revisionRequest');
2402
+ history.replaceState(null, '', url.pathname + url.search);
2401
2403
  }
2402
2404
  }
2403
2405
  // A newer request can become the required checkpoint after BOTH of A's writes succeeded. A's
@@ -0,0 +1,54 @@
1
+ /*
2
+ * One pure profile-colour identity seam for the browser editor and the server scene bake.
3
+ * Keep policy here: consumers choose neither a different canonicalizer nor a different alias winner.
4
+ */
5
+
6
+ export const canonicalProfile = (value) => String(value == null ? '' : value)
7
+ .trim().toUpperCase().replace(/×/g, 'X').replace(/\s*X\s*/g, 'X').replace(/^([A-Z]+)\s+/, '$1');
8
+
9
+ const warnedCollisions = new Set();
10
+
11
+ /** Exact canonical key first; otherwise the lexicographically first equivalent raw key. */
12
+ export function resolveProfileColour(profile, overrides, warn) {
13
+ const canonical = canonicalProfile(profile);
14
+ const map = overrides && typeof overrides === 'object' ? overrides : {};
15
+ const aliases = Object.keys(map).filter((key) => canonicalProfile(key) === canonical).sort();
16
+ if (!aliases.length) return { value: null, winnerKey: null, aliases: [], collision: false };
17
+ const winnerKey = Object.prototype.hasOwnProperty.call(map, canonical) ? canonical : aliases[0];
18
+ const collision = new Set(aliases.map((key) => map[key])).size > 1;
19
+ if (collision && typeof warn === 'function' && !warnedCollisions.has(canonical)) {
20
+ warnedCollisions.add(canonical);
21
+ warn(`Profile colour aliases collide for ${canonical}: ${aliases.join(', ')}. Using ${winnerKey}.`);
22
+ }
23
+ return { value: map[winnerKey], winnerKey, aliases, collision };
24
+ }
25
+
26
+ /** Mutates the persisted map into its canonical write shape: one key per profile identity. */
27
+ export function setCanonicalProfileColour(overrides, profile, colour) {
28
+ const canonical = canonicalProfile(profile);
29
+ if (!canonical || !overrides || typeof overrides !== 'object') return canonical;
30
+ for (const key of Object.keys(overrides)) if (canonicalProfile(key) === canonical) delete overrides[key];
31
+ overrides[canonical] = colour;
32
+ return canonical;
33
+ }
34
+
35
+ /** Native v2 owns one root member array; only the explicit legacy branch reads plan-local members. */
36
+ export function profileColourRank(model, weights) {
37
+ const members = model?.type === 'steel.model/v2'
38
+ ? (Array.isArray(model.members) ? model.members : [])
39
+ : (Array.isArray(model?.plans) ? model.plans.flatMap((plan) => Array.isArray(plan?.members) ? plan.members : []) : []);
40
+ return [...new Set([
41
+ ...members.map((member) => canonicalProfile(member?.profile)).filter(Boolean),
42
+ ...Object.keys(weights && typeof weights === 'object' ? weights : {}).map(canonicalProfile).filter(Boolean),
43
+ ])].sort();
44
+ }
45
+
46
+ export function profileColour(profile, overrides, rank, palette, warn) {
47
+ const canonical = canonicalProfile(profile);
48
+ const resolved = resolveProfileColour(canonical, overrides, warn);
49
+ if (resolved.value) return resolved.value;
50
+ const colours = Array.isArray(palette) && palette.length ? palette : [];
51
+ if (!colours.length) return null;
52
+ const index = rank.indexOf(canonical);
53
+ return colours[((index % colours.length) + colours.length) % colours.length];
54
+ }
@@ -0,0 +1,140 @@
1
+ /*
2
+ * Immutable drawing-read confidence for steel.model/v2.
3
+ *
4
+ * This module projects current observation evidence for display. It does not score members, infer
5
+ * confidence, or mutate the contract. Active binding parity is pinned against server/steel-model-read.
6
+ */
7
+
8
+ const FIELD_SPECS = Object.freeze([
9
+ Object.freeze({ key: 'role', label: 'Role', kind: 'text' }),
10
+ Object.freeze({ key: 'profile', label: 'Profile', kind: 'text' }),
11
+ Object.freeze({ key: 'mark', label: 'Mark', kind: 'text' }),
12
+ Object.freeze({ key: 'memberType', label: 'Member type', kind: 'text' }),
13
+ Object.freeze({ key: 'material', label: 'Material', kind: 'text' }),
14
+ Object.freeze({ key: 'fromZ', label: 'Start elevation', kind: 'elevation' }),
15
+ Object.freeze({ key: 'toZ', label: 'End elevation', kind: 'elevation' }),
16
+ ]);
17
+
18
+ const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
19
+ const finiteConfidence = (value) => Number.isFinite(value) && value >= 0 && value <= 100;
20
+ const validElevation = (value) => isObject(value) && (
21
+ (Number.isFinite(value.known) && !('unknown' in value))
22
+ || (value.unknown === true && !('known' in value) && (value.rfiRef === undefined || typeof value.rfiRef === 'string'))
23
+ );
24
+ const provenanceLabel = (value) => value === 'auto-read' ? 'Auto read'
25
+ : value === 'revision-read' ? 'Revision read'
26
+ : value === 'manual' ? 'Manual observation' : 'Recorded observation';
27
+
28
+ function readField(observed, spec, diagnostics, observationId) {
29
+ if (!Object.prototype.hasOwnProperty.call(observed, spec.key)) return null;
30
+ const record = observed[spec.key];
31
+ const valid = isObject(record) && finiteConfidence(record.confidence)
32
+ && (spec.kind === 'text' ? typeof record.value === 'string' : validElevation(record.value));
33
+ if (!valid) {
34
+ diagnostics.push(Object.freeze({ code: 'invalid-field', observationId, field: spec.key }));
35
+ return null;
36
+ }
37
+ // Elevations are structured contract values. Copy and freeze them as well as the surrounding field so
38
+ // a display consumer cannot accidentally rewrite the immutable observation evidence through this view.
39
+ const value = spec.kind === 'elevation' ? Object.freeze({ ...record.value }) : record.value;
40
+ return Object.freeze({ key: spec.key, label: spec.label, kind: spec.kind, value, confidence: record.confidence });
41
+ }
42
+
43
+ /**
44
+ * One canonical member row per model member. Observations remain separate and retain their mutable
45
+ * binding flags beside immutable field evidence. Malformed evidence is skipped with diagnostics.
46
+ */
47
+ export function projectReadConfidence(model) {
48
+ const members = Array.isArray(model?.members) ? model.members : [];
49
+ const rows = members.filter((member) => isObject(member) && typeof member.id === 'string').map((member) => ({
50
+ memberId: member.id,
51
+ observations: [],
52
+ }));
53
+ const byMember = new Map(rows.map((row) => [row.memberId, row]));
54
+ const diagnostics = [];
55
+
56
+ for (const plan of Array.isArray(model?.plans) ? model.plans : []) {
57
+ if (!isObject(plan)) continue;
58
+ for (const observation of Array.isArray(plan.memberObservations) ? plan.memberObservations : []) {
59
+ if (!isObject(observation) || !isObject(observation.binding) || observation.binding.status !== 'active') continue;
60
+ const observationId = typeof observation.id === 'string' ? observation.id : '';
61
+ const evidence = isObject(observation.evidence) ? observation.evidence : null;
62
+ const observed = evidence && isObject(evidence.observed) ? evidence.observed : {};
63
+ if (!observationId || !evidence) {
64
+ diagnostics.push(Object.freeze({ code: 'invalid-observation', observationId }));
65
+ continue;
66
+ }
67
+ const fields = FIELD_SPECS.map((spec) => readField(observed, spec, diagnostics, observationId)).filter(Boolean);
68
+ const source = isObject(evidence.source) ? evidence.source : {};
69
+ const group = Object.freeze({
70
+ observationId,
71
+ sheet: typeof source.sheet === 'string' && source.sheet.trim() ? source.sheet : (typeof plan.sheet === 'string' ? plan.sheet : ''),
72
+ provenance: typeof evidence.provenance === 'string' ? evidence.provenance : '',
73
+ provenanceLabel: provenanceLabel(evidence.provenance),
74
+ inherited: observation.binding.inherited === true,
75
+ verified: observation.binding.verified === true,
76
+ fields: Object.freeze(fields),
77
+ });
78
+ const memberIds = Array.isArray(observation.binding.memberIds) ? new Set(observation.binding.memberIds) : new Set();
79
+ for (const memberId of memberIds) {
80
+ const row = byMember.get(memberId);
81
+ if (row) row.observations.push(group);
82
+ else diagnostics.push(Object.freeze({ code: 'unresolved-member', observationId, memberId: String(memberId) }));
83
+ }
84
+ }
85
+ }
86
+
87
+ const frozenRows = rows.map((row) => {
88
+ const observations = Object.freeze(row.observations.slice());
89
+ const fields = observations.flatMap((observation) => observation.fields);
90
+ const minimum = fields.length ? Math.min(...fields.map((field) => field.confidence)) : null;
91
+ return Object.freeze({
92
+ memberId: row.memberId,
93
+ observations,
94
+ fieldCount: fields.length,
95
+ minimum,
96
+ state: observations.length === 0 ? 'unobserved' : fields.length === 0 ? 'unrecorded' : 'recorded',
97
+ });
98
+ });
99
+ return Object.freeze({ rows: Object.freeze(frozenRows), diagnostics: Object.freeze(diagnostics.slice()) });
100
+ }
101
+
102
+ /** Unique field records are counted once even when split evidence is bound to multiple members. */
103
+ export function summarizeReadConfidence(projection, target) {
104
+ const hasTarget = finiteConfidence(target);
105
+ const seenFields = new Set();
106
+ const belowFields = new Set();
107
+ const affectedMembers = new Set();
108
+ let lowest = null;
109
+ let notRecordedMembers = 0;
110
+ for (const row of projection?.rows || []) {
111
+ if (row.fieldCount === 0) notRecordedMembers++;
112
+ let memberBelow = false;
113
+ for (const observation of row.observations || []) {
114
+ for (const field of observation.fields || []) {
115
+ const key = `${observation.observationId}\u0000${field.key}`;
116
+ seenFields.add(key);
117
+ lowest = lowest === null ? field.confidence : Math.min(lowest, field.confidence);
118
+ if (hasTarget && field.confidence < target) { belowFields.add(key); memberBelow = true; }
119
+ }
120
+ }
121
+ if (memberBelow) affectedMembers.add(row.memberId);
122
+ }
123
+ return Object.freeze({
124
+ target: hasTarget ? target : null,
125
+ totalFields: seenFields.size,
126
+ belowFields: belowFields.size,
127
+ affectedMembers: affectedMembers.size,
128
+ affectedMemberIds: Object.freeze([...affectedMembers]),
129
+ notRecordedMembers,
130
+ lowest,
131
+ diagnosticCount: Array.isArray(projection?.diagnostics) ? projection.diagnostics.length : 0,
132
+ });
133
+ }
134
+
135
+ export function rowIsBelowTarget(row, target) {
136
+ return finiteConfidence(target) && (row?.observations || []).some((observation) =>
137
+ (observation.fields || []).some((field) => field.confidence < target));
138
+ }
139
+
140
+ export { FIELD_SPECS };
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Resolve the reviewed Drawing Filter raster that belongs under one native plan.
3
+ *
4
+ * The raster already lives in the working contract at `filter.sheets[].page.bg_b64`; copying it into
5
+ * `plans[].raster_b64` would duplicate confidential multi-megabyte evidence and create two values that
6
+ * can drift. Native plans do not yet carry a page id, so the schema-unique sheet label is the only
7
+ * available join. Ambiguity is therefore a refusal, never a first-match guess.
8
+ */
9
+
10
+ import { bgRect } from './steel-filter-core.js';
11
+
12
+ const sheetKey = (value) => String(value == null ? '' : value).trim().replace(/\s+/g, ' ').toUpperCase();
13
+ const validBase64 = (value) => typeof value === 'string' && value.length > 0
14
+ && value.length % 4 === 0 && /^[A-Za-z0-9+/]+={0,2}$/.test(value);
15
+
16
+ const refusal = (reason) => Object.freeze({ ok: false, reason });
17
+
18
+ /** Resolve the schema-unique Filter sheet for a plan, without requiring that it retained a raster. */
19
+ export function resolvePlanFilterSheet(plan, filter) {
20
+ const wanted = sheetKey(plan && plan.sheet);
21
+ if (!wanted) return refusal('plan-sheet-missing');
22
+
23
+ const matches = (Array.isArray(filter && filter.sheets) ? filter.sheets : [])
24
+ .filter((sheet) => sheetKey(sheet && sheet.sheet) === wanted);
25
+ if (matches.length === 0) return refusal('filter-sheet-missing');
26
+ if (matches.length !== 1) return refusal('filter-sheet-ambiguous');
27
+ return Object.freeze({ ok: true, sheet: matches[0] });
28
+ }
29
+
30
+ /**
31
+ * Return a frozen `{ok:true, rasterB64, rect, sheet}` descriptor or a frozen typed refusal.
32
+ * The returned `rasterB64` is the original string reference; this helper never decodes, clones, or
33
+ * writes the evidence bytes.
34
+ */
35
+ export function resolvePlanReferenceRaster(plan, filter) {
36
+ const resolved = resolvePlanFilterSheet(plan, filter);
37
+ if (!resolved.ok) return resolved;
38
+ const sheet = resolved.sheet;
39
+ const rasterB64 = sheet && sheet.page && sheet.page.bg_b64;
40
+ if (!validBase64(rasterB64)) return refusal('filter-raster-missing');
41
+
42
+ const box = bgRect(sheet);
43
+ const values = [box.x, box.y, box.w, box.h].map(Number);
44
+ if (!values.every(Number.isFinite) || !(values[2] > 0) || !(values[3] > 0)) {
45
+ return refusal('filter-raster-unregistered');
46
+ }
47
+
48
+ const rect = Object.freeze({ x: values[0], y: values[1], w: values[2], h: values[3] });
49
+ return Object.freeze({ ok: true, rasterB64, rect, sheet });
50
+ }
@@ -6,7 +6,7 @@
6
6
  * sanitised draft-only saved-view records. steel-editor.html owns the modal/persistence and
7
7
  * steel-3d-view.js owns the camera/mesh intersection.
8
8
  */
9
- import { parseLen, fmtLen } from './grid-core.js';
9
+ import { parseLen, fmtLen, parseSpacings } from './grid-core.js';
10
10
 
11
11
  /**
12
12
  * Display modes a saved view may carry. Must stay a superset of the 3D toolbar's `#m3dMode`
@@ -20,22 +20,52 @@ export const VIEW_MODES = ['solid', 'wire', 'xray', 'realistic', 'shadowed'];
20
20
  const finite = (n) => typeof n === 'number' && Number.isFinite(n);
21
21
  const positive = (n) => finite(n) && n > 0;
22
22
  const vec3 = (v) => Array.isArray(v) && v.length === 3 && v.every(finite);
23
+ /** What the contract means by `type: object` — `typeof` alone calls both null and [] an object. */
24
+ const plain = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
23
25
 
24
- /** Convert resolved display-space grid geometry to world-mm sources. */
25
- export function sourcesFromGrid(geo, mmPerDisplayPx, sheet) {
26
+ /**
27
+ * Convert resolved display-space grid geometry to world-mm sources, paired to the model grid's
28
+ * stable axis identities. A direction whose parsed rows cannot be paired exactly is omitted: a
29
+ * selectable source without an axis id can only produce a view the contract refuses to save.
30
+ */
31
+ export function sourcesFromGrid(geo, mmPerDisplayPx, sheet, grid) {
26
32
  if (!geo || !positive(mmPerDisplayPx)) return { x: [], y: [], levels: [] };
27
33
  const sh = typeof sheet === 'string' ? sheet : '';
28
- const x = Array.isArray(geo.v) ? geo.v.map((line, index) => ({
29
- kind: 'grid-x', sheet: sh, index, label: String(line?.label ?? index + 1),
30
- at: Number(line?.x) * mmPerDisplayPx,
34
+ const axes = Array.isArray(grid?.axes) ? grid.axes : [];
35
+ const axesFor = (dir, rows) => {
36
+ if (!Array.isArray(rows)) return null;
37
+ const found = axes.filter((axis) => axis?.dir === dir);
38
+ return found.length === rows.length && found.every((axis) => typeof axis?.id === 'string' && axis.id.length) ? found : null;
39
+ };
40
+ // Match grid-core's axisLabelsFor rule: an authored axis label is trimmed, and blank falls back to
41
+ // the already-resolved display label. This keeps the saved name identical to the bubble users saw.
42
+ const labelFor = (axis, fallback) => String(axis?.label ?? '').trim() || String(fallback ?? '');
43
+ // X/Y cuts live in canonical world space. Display coordinates include the plan registration's datum,
44
+ // rotation and scale, so multiplying an absolute sheet pixel by mm/px cuts the wrong location whenever
45
+ // the sheet datum is not the world origin. Resolve the same authored spacings the stable axes describe.
46
+ const origin = Array.isArray(grid?.origin) && grid.origin.length === 2 && grid.origin.every(finite) ? grid.origin : null;
47
+ const xOffsets = parseSpacings(grid?.x).offsets;
48
+ const yOffsets = parseSpacings(grid?.y).offsets;
49
+ const xAxes = axesFor('x', geo.v);
50
+ const x = origin && xAxes && xOffsets.length === xAxes.length ? geo.v.map((line, index) => ({
51
+ kind: 'grid-x', sheet: sh, index, axisId: xAxes[index].id,
52
+ label: labelFor(xAxes[index], line?.label ?? index + 1), at: origin[0] + xOffsets[index],
31
53
  })).filter((s) => finite(s.at)) : [];
32
- // Display Y grows down the sheet; the 3D scene is Z-up with +Y up the plan.
33
- const y = Array.isArray(geo.h) ? geo.h.map((line, index) => ({
34
- kind: 'grid-y', sheet: sh, index, label: String(line?.label ?? index + 1),
35
- at: -Number(line?.y) * mmPerDisplayPx,
54
+ const yAxes = axesFor('y', geo.h);
55
+ const y = origin && yAxes && yOffsets.length === yAxes.length ? geo.h.map((line, index) => ({
56
+ kind: 'grid-y', sheet: sh, index, axisId: yAxes[index].id,
57
+ label: labelFor(yAxes[index], line?.label ?? index + 1), at: origin[1] + yOffsets[index],
36
58
  })).filter((s) => finite(s.at)) : [];
37
- const levels = Array.isArray(geo.zs) ? geo.zs.map((level, index) => ({
38
- kind: 'level', sheet: sh, index, label: String(level?.label ?? ''), at: Number(level?.mm),
59
+ const zAxes = axesFor('z', geo.zs);
60
+ let levelAxisId = null;
61
+ if (zAxes) {
62
+ levelAxisId = new Map();
63
+ [...geo.zs].sort((a, b) => Number(a?.sourceIndex) - Number(b?.sourceIndex))
64
+ .forEach((level, index) => levelAxisId.set(level, zAxes[index]));
65
+ }
66
+ const levels = levelAxisId ? geo.zs.map((level, index) => ({
67
+ kind: 'level', sheet: sh, index, axisId: levelAxisId.get(level).id,
68
+ label: labelFor(levelAxisId.get(level), level?.label), at: Number(level?.mm),
39
69
  })).filter((s) => finite(s.at)).sort((a, b) => a.at - b.at) : [];
40
70
  return { x, y, levels };
41
71
  }
@@ -100,7 +130,7 @@ function saneBounds(bounds) {
100
130
  * `direction` points FROM the target TO the camera, matching steel-3d-view fitCamera().
101
131
  */
102
132
  export function cutForSource(source, depths, look, sceneBounds) {
103
- if (!source || !finite(source.at) || !saneBounds(sceneBounds)) return null;
133
+ if (!source || !finite(source.at) || typeof source.axisId !== 'string' || !source.axisId || !saneBounds(sceneBounds)) return null;
104
134
  const min = sceneBounds.min.slice(), max = sceneBounds.max.slice();
105
135
  const diag = Math.hypot(max[0] - min[0], max[1] - min[1], max[2] - min[2]);
106
136
  const pad = Math.max(1, diag * 1e-6);
@@ -113,7 +143,7 @@ export function cutForSource(source, depths, look, sceneBounds) {
113
143
  max[axis] = source.at + (positiveLook ? depths.ahead : depths.behind);
114
144
  direction = axis === 0 ? [positiveLook ? -1 : 1, 0, 0] : [0, positiveLook ? -1 : 1, 0];
115
145
  generated = {
116
- v: 1, kind: source.kind, sheet: String(source.sheet || ''), label: String(source.label || ''),
146
+ v: 1, kind: source.kind, sheet: String(source.sheet || ''), axisId: source.axisId, label: String(source.label || ''),
117
147
  at: source.at, look: positiveLook ? 'positive' : 'negative',
118
148
  ahead: depths.ahead, behind: depths.behind,
119
149
  };
@@ -123,7 +153,7 @@ export function cutForSource(source, depths, look, sceneBounds) {
123
153
  max[2] = source.at + depths.above;
124
154
  direction = [0, 0, 1];
125
155
  generated = {
126
- v: 1, kind: 'level', sheet: String(source.sheet || ''), label: String(source.label || ''),
156
+ v: 1, kind: 'level', sheet: String(source.sheet || ''), axisId: source.axisId, label: String(source.label || ''),
127
157
  at: source.at, look: 'down', above: depths.above, below: depths.below,
128
158
  };
129
159
  } else return null;
@@ -142,13 +172,31 @@ export function nameForSource(source) {
142
172
  : `Elevation — Grid ${String(source.label || '')}`;
143
173
  }
144
174
 
175
+ /**
176
+ * Normalise one generated view's provenance, or return null when it cannot be trusted.
177
+ *
178
+ * NOTHING SCHEMA-VALID IS ALTERED HERE. Once this feeds the draft-restore registry, whatever it
179
+ * changes it changes in the user's own saved work, silently and then permanently on the next
180
+ * autosave — so it may reject what `$defs.viewGenerated` cannot hold and nothing else.
181
+ *
182
+ * BOTH IDENTITY-BEARING STRINGS ARE CARRIED BYTE-FOR-BYTE. `axisId` resolves against
183
+ * `grid.axes[].id` and `sheet` against the plan sheets (`checkModelReferences` →
184
+ * `view-generated-unresolved` for either), and neither carries a `maxLength`, so clamping one turns
185
+ * a reference that resolved into one the server refuses. That is the same narrowing this file's
186
+ * neighbours were corrected for — the clamped id, the trimmed id (#853) — and the earlier revision
187
+ * of THIS function clamped `sheet` at 120 while its own comment argued ids must not be (Codex, #854).
188
+ *
189
+ * `label` is a display-text CACHE and the schema leaves it optional, so a missing or unusable one
190
+ * costs the label alone; dropping the whole provenance over it would throw away the axis link, the
191
+ * datum and the cut depths — everything that makes the view regenerable — to fix a caption.
192
+ */
145
193
  export function sanitizeGenerated(value) {
146
194
  if (!value || typeof value !== 'object' || value.v !== 1 || !finite(value.at)
147
- || typeof value.sheet !== 'string' || typeof value.label !== 'string') return null;
195
+ || typeof value.sheet !== 'string' || !value.sheet
196
+ || typeof value.axisId !== 'string' || !value.axisId) return null;
148
197
  const kind = value.kind;
149
- const base = {
150
- v: 1, kind, sheet: value.sheet.slice(0, 120), label: value.label.slice(0, 80), at: value.at,
151
- };
198
+ const base = { v: 1, kind, sheet: value.sheet, axisId: value.axisId, at: value.at };
199
+ if (typeof value.label === 'string') base.label = value.label;
152
200
  if ((kind === 'grid-x' || kind === 'grid-y')
153
201
  && (value.look === 'positive' || value.look === 'negative')
154
202
  && positive(value.ahead) && positive(value.behind)) {
@@ -160,24 +208,68 @@ export function sanitizeGenerated(value) {
160
208
  return null;
161
209
  }
162
210
 
163
- /** Normalise the unlimited draft-only saved-view library. */
211
+ /**
212
+ * Normalise the unlimited draft-only saved-view library.
213
+ *
214
+ * ITS OUTPUT HAS TO SURVIVE THE NEXT SAVE, which is the whole reason a sanitiser sits on the
215
+ * draft-restore path, and for a long time this one's did not — so it had no call site at all and
216
+ * could not be given one (#854). It minted a root `projection` against a `$defs.view` that is
217
+ * `additionalProperties: false`, and wrote `camera`/`clips`/`objects` as `null` where the schema
218
+ * types each as an object. Either is enough to refuse the very save the restore leads to.
219
+ *
220
+ * `projection` is gone rather than added to the contract: `camera.proj` is the single authoritative
221
+ * projection setting (the schema's own words), nothing ever read the root key, and
222
+ * `createGeneratedViews` already omits it. An ABSENT sub-snapshot is now OMITTED rather than nulled
223
+ * — a key the schema types as an object is not the place to record "there wasn't one".
224
+ *
225
+ * It still knows nothing of `$defs.view` itself, and must not: the schema is asked directly at the
226
+ * call site (`DRAFT_SANITIZERS` in steel-editor.html), so a view carrying a key this file has never
227
+ * heard of is refused by the contract rather than by a restatement of it here.
228
+ *
229
+ * WHAT IT MAY DECIDE is what is MISSING — a minted id, the 'View' fallback, 'solid' for a mode the
230
+ * dropdown no longer offers, an ordinal. What it may NOT do is alter a value the schema accepts:
231
+ * `name` is `type: string` with no `maxLength`, so the 80-character clamp that used to sit here only
232
+ * ever shortened a name the contract would have taken whole (Codex, #854).
233
+ */
164
234
  export function sanitizeViews(value, makeId = () => `v${Math.random().toString(36).slice(2, 9)}`) {
165
235
  if (!Array.isArray(value)) return [];
166
236
  const out = [];
237
+ // A LIBRARY-level invariant, which is why it lives here and not at the call site: `$defs.view` is a
238
+ // per-ROW schema, so two rows sharing an id both validate and `rowsOk` cannot see the collision — but
239
+ // `checkModelReferences` runs a cross-row count (`$.views` → `id-duplicate`, steel-model-v2.ts) over
240
+ // the finished document. A restore that let both through would therefore poison EVERY later autosave,
241
+ // including saves of work that never touched a view, which is the exact failure this registry entry
242
+ // exists to prevent. First occurrence wins; the drop is reported by the call site's length check.
243
+ // Minted ids join the set too, so a fresh one cannot collide with an explicit id further down
244
+ // (Codex, #854).
245
+ const takenIds = new Set();
167
246
  for (const raw of value) {
168
- if (!raw || typeof raw !== 'object') continue;
247
+ // ONE predicate for the row and its sub-snapshots, because `typeof` alone answers this wrong twice:
248
+ // `typeof null` and `typeof []` are both 'object', while the schema reads them as `got null|array`.
249
+ // A sub-snapshot that fails it is omitted; a ROW that fails it is skipped outright, and that
250
+ // asymmetry is the point. Every field below reads through `raw.<key>`, which on an array is
251
+ // uniformly `undefined` — so the row would not be sanitised, it would be INVENTED: a minted id, the
252
+ // 'View' fallback, an ordinal, 'solid'. That fabrication satisfies `$defs.view`, so `rowsOk` cannot
253
+ // drop it either, and `views: [[]]` in a corrupted draft restores as a phantom saved view and
254
+ // autosaves. There is nothing in an array row to preserve, so nothing is lost by refusing it here
255
+ // (Codex, #854).
256
+ if (!plain(raw)) continue;
257
+ const id = typeof raw.id === 'string' && raw.id ? raw.id : makeId();
258
+ if (takenIds.has(id)) continue;
259
+ takenIds.add(id);
169
260
  const generated = sanitizeGenerated(raw.generated);
170
261
  const view = {
171
262
  v: generated ? 2 : 1,
172
- id: typeof raw.id === 'string' && raw.id ? raw.id : makeId(),
173
- name: typeof raw.name === 'string' && raw.name.trim() ? raw.name.trim().slice(0, 80) : 'View',
263
+ id,
264
+ // Any string is a legal name — `$defs.view.name` sets no `minLength`, so `''` and `' '` are the
265
+ // user's data, not malformed input, and renaming them here would be a silent edit made permanent by
266
+ // the next autosave. 'View' is synthesised only when there is genuinely nothing to keep: an absent
267
+ // name, or one that is not a string at all (Codex, #854).
268
+ name: typeof raw.name === 'string' ? raw.name : 'View',
174
269
  order: finite(raw.order) ? raw.order : out.length,
175
- camera: raw.camera && typeof raw.camera === 'object' ? raw.camera : null,
176
- projection: raw.projection === 'ortho' ? 'ortho' : 'persp',
177
270
  mode: VIEW_MODES.includes(raw.mode) ? raw.mode : 'solid',
178
- clips: raw.clips && typeof raw.clips === 'object' ? raw.clips : null,
179
- objects: raw.objects && typeof raw.objects === 'object' ? raw.objects : null,
180
271
  };
272
+ for (const key of ['camera', 'clips', 'objects']) if (plain(raw[key])) view[key] = raw[key];
181
273
  if (generated) view.generated = generated;
182
274
  out.push(view);
183
275
  }