@floless/app 0.138.1 → 0.139.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 (109) hide show
  1. package/autostart.mjs +6 -2
  2. package/desktop-access-production-manifest.mjs +7 -0
  3. package/dist/floless-server.cjs +157133 -70500
  4. package/dist/schemas/model.continuation.v1.schema.json +19 -0
  5. package/dist/schemas/model.continuation.v2.schema.json +19 -0
  6. package/dist/schemas/model.query-response.v1.schema.json +95 -0
  7. package/dist/schemas/model.query-response.v2.schema.json +80 -0
  8. package/dist/schemas/model.query.v1.schema.json +87 -0
  9. package/dist/schemas/model.query.v2.schema.json +87 -0
  10. package/dist/schemas/model.snap-candidate.v1.schema.json +48 -0
  11. package/dist/schemas/model.snap-constraint.v1.schema.json +18 -0
  12. package/dist/schemas/model.snap-query.v1.schema.json +24 -0
  13. package/dist/schemas/model.snap-result.v1.schema.json +33 -0
  14. package/dist/schemas/model.snapshot.v1.schema.json +136 -0
  15. package/dist/schemas/revit.model.v1.schema.json +24 -0
  16. package/dist/schemas/steel.model.v2.schema.json +45 -6
  17. package/dist/skills/floless-app-approval/SKILL.md +19 -5
  18. package/dist/skills/floless-app-bridge/SKILL.md +19 -6
  19. package/dist/skills/floless-app-knowledge/SKILL.md +22 -1
  20. package/dist/skills/floless-app-new-workflow/SKILL.md +31 -27
  21. package/dist/skills/floless-app-new-workflow/references/build-and-verify.md +13 -12
  22. package/dist/skills/floless-app-onboarding/SKILL.md +3 -3
  23. package/dist/skills/floless-app-onboarding/references/floless-app-tour.md +16 -9
  24. package/dist/skills/floless-app-steel-model/SKILL.md +11 -2
  25. package/dist/skills/floless-app-steel-model/references/detail-from-a-screenshot.md +95 -0
  26. package/dist/skills/floless-app-steel-takeoff/SKILL.md +146 -21
  27. package/dist/skills/floless-app-steel-takeoff/references/elevation-registration.md +19 -0
  28. package/dist/skills/floless-app-tweak-contract/SKILL.md +42 -8
  29. package/dist/skills/floless-app-vectorize/SKILL.md +19 -6
  30. package/dist/skills/floless-app-workflows/SKILL.md +30 -3
  31. package/dist/skills/floless-app-workflows/references/workspace-data.md +77 -4
  32. package/dist/templates/floless-workspace-model-report.flo +77 -0
  33. package/dist/templates/revit-model.flo +111 -0
  34. package/dist/web/app.css +415 -177
  35. package/dist/web/app.js +302 -51
  36. package/dist/web/aware.js +1430 -1040
  37. package/dist/web/chat.css +692 -0
  38. package/dist/web/chat.js +2651 -0
  39. package/dist/web/commands-revit.js +42 -0
  40. package/dist/web/commands-shell.js +536 -70
  41. package/dist/web/commands-steel.js +344 -146
  42. package/dist/web/commands.js +1 -1
  43. package/dist/web/index.html +283 -77
  44. package/dist/web/instructor.js +217 -36
  45. package/dist/web/left-pane.js +636 -0
  46. package/dist/web/model-artifact-loader.js +75 -0
  47. package/dist/web/model-authoring-gestures.js +141 -0
  48. package/dist/web/model-cad-tools.js +20 -0
  49. package/dist/web/model-clip-gesture.js +148 -0
  50. package/dist/web/model-clip-list.js +156 -0
  51. package/dist/web/model-clip-session.js +274 -0
  52. package/dist/web/model-clip-three-overlay.js +295 -0
  53. package/dist/web/model-clip-three-preview.js +59 -0
  54. package/dist/web/model-editor-contract.js +519 -0
  55. package/dist/web/model-editor-revit-adapter.js +139 -0
  56. package/dist/web/model-editor-shell.js +271 -0
  57. package/dist/web/model-editor-state-recovery.js +44 -0
  58. package/dist/web/model-editor-steel-adapter.js +410 -0
  59. package/dist/web/model-editor.css +268 -0
  60. package/dist/web/model-frame.js +192 -0
  61. package/dist/web/model-inspector.js +128 -0
  62. package/dist/web/model-measure.js +390 -0
  63. package/dist/web/model-navigation-controls.js +246 -0
  64. package/dist/web/model-orientation-overlay.js +217 -0
  65. package/dist/web/model-panel-bridge.js +230 -0
  66. package/dist/web/model-pointer-dock.js +164 -0
  67. package/dist/web/model-revit-module.js +83 -0
  68. package/dist/web/model-selection-coordinator.js +151 -0
  69. package/dist/web/model-selection-tools.js +290 -0
  70. package/dist/web/model-snap-contract.js +267 -0
  71. package/dist/web/model-snapping.js +497 -0
  72. package/dist/web/model-spatial-panel.js +294 -0
  73. package/dist/web/model-spatial-tools.js +249 -0
  74. package/dist/web/model-tree.js +47 -0
  75. package/dist/web/model-viewport-lighting.js +166 -0
  76. package/dist/web/model-viewport-revit-adapter.js +1224 -0
  77. package/dist/web/model-viewport-state.js +505 -0
  78. package/dist/web/model-viewport-steel-adapter.js +150 -0
  79. package/dist/web/model-viewport-toolbar.js +516 -0
  80. package/dist/web/model-viewport.js +717 -0
  81. package/dist/web/panels.js +8 -15
  82. package/dist/web/renderers.js +3 -0
  83. package/dist/web/revit-editor.css +35 -0
  84. package/dist/web/revit-editor.html +74 -0
  85. package/dist/web/revit-editor.js +845 -0
  86. package/dist/web/steel-3d-core.js +16 -44
  87. package/dist/web/steel-3d-view.js +1384 -633
  88. package/dist/web/steel-canvas-guidance.js +3 -1
  89. package/dist/web/steel-editor.html +2121 -1253
  90. package/dist/web/steel-filter.html +5 -1
  91. package/dist/web/steel-model-v2-commands.js +72 -1
  92. package/dist/web/steel-split-view.js +5 -39
  93. package/dist/web/steel-view-generation.js +107 -17
  94. package/dist/web/vector-3d.html +12 -0
  95. package/dist/web/workspaces.js +2190 -277
  96. package/distribution-profile-active.mjs +2 -0
  97. package/distribution-profile-production.mjs +47 -0
  98. package/distribution-profile-shared.mjs +8 -0
  99. package/distribution-profile.mjs +18 -0
  100. package/distribution-resource-inventory.mjs +81 -0
  101. package/launch.mjs +18 -10
  102. package/log.mjs +2 -1
  103. package/managed-runtime-policy.mjs +104 -0
  104. package/model-reader-policy-active.mjs +7 -0
  105. package/network-policy-active.mjs +6 -0
  106. package/package.json +17 -2
  107. package/post-update-marker.mjs +3 -1
  108. package/rvt-production-uat-authority.mjs +60 -0
  109. package/teardown.mjs +4 -3
@@ -0,0 +1,505 @@
1
+ /*
2
+ * Provider-neutral viewport data and transitions.
3
+ *
4
+ * This module is deliberately pure: no DOM and no rendering-library objects. The browser controller
5
+ * and each host adapter exchange copied serializable values through this boundary.
6
+ */
7
+
8
+ export const MODEL_VIEWPORT_STATE_SCHEMA = 'floless.model-viewport-state/v1';
9
+ export const MODEL_EDITOR_STATE_V1 = 'floless.model-editor-state/v1';
10
+ export const ENTITY_KEY_RAW_TUPLE_BYTES = 192;
11
+ export const ENTITY_SOURCE_ID_BYTES = 1024 * 1024;
12
+
13
+ export class ViewportStateError extends Error {
14
+ constructor(code, message) {
15
+ super(message);
16
+ this.name = 'ViewportStateError';
17
+ this.code = code;
18
+ }
19
+ }
20
+
21
+ const fail = (code, message) => { throw new ViewportStateError(code, message); };
22
+ const own = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
23
+ const textEncoder = new TextEncoder();
24
+
25
+ function copy(value) {
26
+ if (Array.isArray(value)) return value.map(copy);
27
+ if (value && typeof value === 'object') {
28
+ const out = {};
29
+ for (const [key, item] of Object.entries(value)) out[key] = copy(item);
30
+ return out;
31
+ }
32
+ return value;
33
+ }
34
+
35
+ function freeze(value) {
36
+ if (!value || typeof value !== 'object' || Object.isFrozen(value)) return value;
37
+ for (const item of Object.values(value)) freeze(item);
38
+ return Object.freeze(value);
39
+ }
40
+
41
+ const cloned = (value) => freeze(copy(value));
42
+ const finite3 = (value) => Array.isArray(value) && value.length === 3 && value.every(Number.isFinite);
43
+
44
+ /** The frozen provider-neutral snapshot consumed by shared editor chrome. */
45
+ export function createModelEditorState(value = {}) {
46
+ const count = (name) => {
47
+ const next = value[name];
48
+ if (!Number.isSafeInteger(next) || next < 0) fail('E_BAD_EDITOR_STATE', `${name} must be a non-negative safe integer`);
49
+ return next;
50
+ };
51
+ if (typeof value.ghostUnselected !== 'boolean' || typeof value.hasVisibilityFilter !== 'boolean') {
52
+ fail('E_BAD_EDITOR_STATE', 'editor visibility state must contain Boolean ghostUnselected and hasVisibilityFilter');
53
+ }
54
+ const selectionCount = count('selectionCount');
55
+ const actionableVisibilitySelectionCount = count('actionableVisibilitySelectionCount');
56
+ if (actionableVisibilitySelectionCount > selectionCount) {
57
+ fail('E_BAD_EDITOR_STATE', 'actionableVisibilitySelectionCount cannot exceed selectionCount');
58
+ }
59
+ return cloned({
60
+ schema: MODEL_EDITOR_STATE_V1,
61
+ selectionCount,
62
+ actionableVisibilitySelectionCount,
63
+ ghostUnselected: value.ghostUnselected,
64
+ hasVisibilityFilter: value.hasVisibilityFilter,
65
+ });
66
+ }
67
+
68
+ function normalizedCamera(value = {}) {
69
+ const camera = {
70
+ projection: value.projection ?? 'ortho',
71
+ position: copy(value.position ?? [1, -1, 1]),
72
+ target: copy(value.target ?? [0, 0, 0]),
73
+ up: copy(value.up ?? [0, 0, 1]),
74
+ orthoHeight: value.orthoHeight ?? 1,
75
+ zoom: value.zoom ?? 1,
76
+ near: value.near ?? 1,
77
+ far: value.far ?? 50_000_000,
78
+ };
79
+ if (!['persp', 'ortho'].includes(camera.projection)) fail('E_BAD_CAMERA', 'projection must be persp or ortho');
80
+ for (const name of ['position', 'target', 'up']) if (!finite3(camera[name])) fail('E_BAD_CAMERA', `${name} must be a finite 3-vector`);
81
+ for (const name of ['orthoHeight', 'zoom', 'near', 'far']) if (!Number.isFinite(camera[name]) || camera[name] <= 0) fail('E_BAD_CAMERA', `${name} must be positive and finite`);
82
+ return camera;
83
+ }
84
+
85
+ export function createViewportState(overrides = {}) {
86
+ const selectedKeys = copy(overrides.selectedKeys ?? []);
87
+ const state = {
88
+ schema: MODEL_VIEWPORT_STATE_SCHEMA,
89
+ phase: overrides.phase ?? 'new',
90
+ shown: overrides.shown === true,
91
+ inputActive: overrides.inputActive !== false,
92
+ cameraFitted: overrides.cameraFitted === true,
93
+ frameAllowed: overrides.frameAllowed === true,
94
+ camera: normalizedCamera(overrides.camera),
95
+ displayMode: overrides.displayMode ?? 'solid',
96
+ selectedKeys,
97
+ primaryKey: own(overrides, 'primaryKey') ? overrides.primaryKey : (selectedKeys.at(-1) ?? null),
98
+ hoverKey: overrides.hoverKey ?? null,
99
+ clipping: copy(overrides.clipping ?? []),
100
+ activeClipGesture: copy(overrides.activeClipGesture ?? null),
101
+ workPlane: copy(overrides.workPlane ?? null),
102
+ workArea: copy(overrides.workArea ?? null),
103
+ hasVisibilityFilter: overrides.hasVisibilityFilter === true,
104
+ ghostUnselected: overrides.ghostUnselected === true,
105
+ };
106
+ if (!['new', 'ready', 'hidden', 'disposed', 'failed'].includes(state.phase)) fail('E_BAD_PHASE', `unknown phase ${state.phase}`);
107
+ if (!Array.isArray(state.selectedKeys) || state.selectedKeys.some((key) => typeof key !== 'string') || new Set(state.selectedKeys).size !== state.selectedKeys.length) {
108
+ fail('E_BAD_SELECTION', 'selectedKeys must be unique strings');
109
+ }
110
+ if (state.primaryKey !== null && !state.selectedKeys.includes(state.primaryKey)) fail('E_BAD_SELECTION', 'primaryKey must occur in selectedKeys');
111
+ if ((state.primaryKey === null) !== (state.selectedKeys.length === 0)) fail('E_BAD_SELECTION', 'primaryKey is null exactly when selection is empty');
112
+ if (state.hoverKey !== null && typeof state.hoverKey !== 'string') fail('E_BAD_HOVER', 'hoverKey must be a string or null');
113
+ return cloned(state);
114
+ }
115
+
116
+ export function transitionViewportState(previous, action) {
117
+ if (!previous || previous.schema !== MODEL_VIEWPORT_STATE_SCHEMA) fail('E_BAD_STATE', 'state schema is invalid');
118
+ if (!action || typeof action.type !== 'string') fail('E_BAD_TRANSITION', 'transition needs a type');
119
+ if (previous.phase === 'disposed' && action.type !== 'dispose') fail('E_VIEWPORT_DISPOSED', 'a disposed viewport is terminal');
120
+ const next = copy(previous);
121
+ switch (action.type) {
122
+ case 'init':
123
+ if (previous.phase !== 'new') fail('E_BAD_TRANSITION', 'init is legal only for a new viewport');
124
+ next.phase = 'ready';
125
+ break;
126
+ case 'show':
127
+ if (!['ready', 'hidden'].includes(previous.phase)) fail('E_BAD_TRANSITION', 'show needs a ready or hidden viewport');
128
+ next.phase = 'ready'; next.shown = true; next.frameAllowed = previous.cameraFitted;
129
+ break;
130
+ case 'hide':
131
+ if (!['ready', 'hidden'].includes(previous.phase)) fail('E_BAD_TRANSITION', 'hide needs a live viewport');
132
+ next.phase = 'hidden'; next.shown = false; next.frameAllowed = false; next.activeClipGesture = null;
133
+ break;
134
+ case 'build-settled':
135
+ if (!['success', 'empty', 'failure'].includes(action.outcome)) fail('E_BAD_TRANSITION', 'unknown build outcome');
136
+ next.frameAllowed = true;
137
+ break;
138
+ case 'fit-complete':
139
+ next.cameraFitted = true; next.frameAllowed = true;
140
+ break;
141
+ case 'paint':
142
+ next.frameAllowed = action.allowed === true;
143
+ break;
144
+ case 'input':
145
+ next.inputActive = action.active !== false;
146
+ break;
147
+ case 'camera':
148
+ next.camera = normalizedCamera(action.camera);
149
+ break;
150
+ case 'display':
151
+ if (typeof action.mode !== 'string' || !action.mode) fail('E_BAD_DISPLAY_MODE', 'display mode must be a non-empty string');
152
+ next.displayMode = action.mode;
153
+ break;
154
+ case 'selection':
155
+ next.selectedKeys = copy(action.keys ?? []); next.primaryKey = action.primaryKey ?? null;
156
+ break;
157
+ case 'hover':
158
+ next.hoverKey = action.key ?? null;
159
+ break;
160
+ case 'section':
161
+ next.clipping = copy(action.clipping ?? []);
162
+ next.workPlane = copy(action.workPlane ?? null);
163
+ next.workArea = copy(action.workArea ?? null);
164
+ if (own(action, 'activeClipGesture')) next.activeClipGesture = copy(action.activeClipGesture);
165
+ break;
166
+ case 'visibility':
167
+ next.hasVisibilityFilter = action.filtered === true;
168
+ break;
169
+ case 'ghost':
170
+ next.ghostUnselected = action.enabled === true;
171
+ break;
172
+ case 'dispose':
173
+ next.phase = 'disposed'; next.shown = false; next.frameAllowed = false;
174
+ next.selectedKeys = []; next.primaryKey = null; next.hoverKey = null;
175
+ next.clipping = []; next.activeClipGesture = null; next.workPlane = null; next.workArea = null;
176
+ next.hasVisibilityFilter = false;
177
+ next.ghostUnselected = false;
178
+ break;
179
+ case 'fail':
180
+ next.phase = 'failed'; next.shown = false; next.frameAllowed = false;
181
+ break;
182
+ default:
183
+ fail('E_BAD_TRANSITION', `unknown transition ${action.type}`);
184
+ }
185
+ return createViewportState(next);
186
+ }
187
+
188
+ function assertVersionOne(value, name) {
189
+ if (!value || typeof value !== 'object') fail('E_BAD_CODEC', `${name} must be an object`);
190
+ if (value.v !== 1) fail('E_BAD_CODEC_VERSION', `${name} version must be 1`);
191
+ }
192
+
193
+ export function decodeCameraState(value) {
194
+ assertVersionOne(value, 'camera state');
195
+ if (!finite3(value.pos) || !finite3(value.target) || !['persp', 'ortho'].includes(value.proj)) fail('E_BAD_CODEC', 'camera state has invalid coordinates or projection');
196
+ const out = { v: 1, pos: copy(value.pos), target: copy(value.target), proj: value.proj };
197
+ if (own(value, 'orthoH')) out.orthoH = value.orthoH;
198
+ if (own(value, 'zoom')) out.zoom = value.zoom;
199
+ return cloned(out);
200
+ }
201
+
202
+ export function encodeCameraState(value) { return decodeCameraState(value); }
203
+
204
+ export function decodeSectionState(value) {
205
+ assertVersionOne(value, 'section state');
206
+ if (!Array.isArray(value.clips)) fail('E_BAD_CODEC', 'section clips must be an array');
207
+ return cloned({ v: 1, clips: value.clips, workPlane: value.workPlane ?? null, workArea: value.workArea ?? null });
208
+ }
209
+
210
+ export function encodeSectionState(value) { return decodeSectionState(value); }
211
+
212
+ function base64url(bytes) {
213
+ let binary = '';
214
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
215
+ if (typeof btoa === 'function') return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '');
216
+ return Buffer.from(bytes).toString('base64url');
217
+ }
218
+
219
+ async function defaultDigest(bytes) {
220
+ const subtle = globalThis.crypto && globalThis.crypto.subtle;
221
+ if (!subtle) fail('E_DIGEST_UNAVAILABLE', 'SHA-256 is unavailable in this runtime');
222
+ return new Uint8Array(await subtle.digest('SHA-256', bytes));
223
+ }
224
+
225
+ export function validEntityKey(key) {
226
+ return typeof key === 'string' && (
227
+ /^mvp1\.r\.[A-Za-z0-9_-]{1,256}$/.test(key)
228
+ || /^mvp1\.h\.[A-Za-z0-9_-]{43}$/.test(key)
229
+ ) && key.length <= 263;
230
+ }
231
+
232
+ export function createEntityKeyRegistry(options = {}) {
233
+ const digest = options.digest ?? defaultDigest;
234
+ // `identities` survives generation swaps. A provider id may be reused by a later model
235
+ // revision, so the canonical key is deliberately stable while the monotonically increasing
236
+ // generation and namespace qualify the particular scene that minted it.
237
+ const identities = new Map();
238
+ const active = new Map();
239
+ const pending = new Map();
240
+ const batches = new Map();
241
+ const usedNamespaces = new Set(['mvp1.ns.legacy']);
242
+ let namespaceSequence = 0;
243
+ let activeNamespace = 'mvp1.ns.legacy';
244
+ let generationRequired = false;
245
+
246
+ function validateIdentity(kind, sourceId) {
247
+ if (typeof kind !== 'string' || typeof sourceId !== 'string') fail('E_BAD_ENTITY_ID', 'kind and sourceId must be strings');
248
+ const sourceBytes = textEncoder.encode(sourceId);
249
+ if (sourceBytes.length > ENTITY_SOURCE_ID_BYTES) fail('E_ENTITY_KEY_TOO_LARGE', `sourceId exceeds ${ENTITY_SOURCE_ID_BYTES} UTF-8 bytes`);
250
+ return textEncoder.encode(JSON.stringify(['mvp1', kind, sourceId]));
251
+ }
252
+
253
+ function identityFor(key, kind, sourceId) {
254
+ if (!validEntityKey(key)) fail('E_BAD_ENTITY_KEY', 'generated entity key violates its envelope');
255
+ const existing = identities.get(key);
256
+ if (existing && (existing.kind !== kind || existing.sourceId !== sourceId)) fail('E_ENTITY_KEY_COLLISION', `entity key collision for ${key}`);
257
+ if (existing) return existing;
258
+ const created = { kind, sourceId, lastGeneration: 0 };
259
+ identities.set(key, created);
260
+ return created;
261
+ }
262
+
263
+ function activate(key, kind, sourceId) {
264
+ const identity = identityFor(key, kind, sourceId);
265
+ const existing = active.get(key);
266
+ if (existing && existing.namespace === activeNamespace) return cloned({ key, generation: existing.generation });
267
+ const generation = ++identity.lastGeneration;
268
+ active.set(key, { kind, sourceId, generation, namespace: activeNamespace });
269
+ return cloned({ key, generation });
270
+ }
271
+
272
+ function registerSync(kind, sourceId) {
273
+ const tuple = validateIdentity(kind, sourceId);
274
+ if (tuple.length > ENTITY_KEY_RAW_TUPLE_BYTES) fail('E_ENTITY_KEY_ASYNC_REQUIRED', 'long entity identity must be registered asynchronously');
275
+ return activate(`mvp1.r.${base64url(tuple)}`, kind, sourceId);
276
+ }
277
+
278
+ async function register(kind, sourceId) {
279
+ const tuple = validateIdentity(kind, sourceId);
280
+ const raw = tuple.length <= ENTITY_KEY_RAW_TUPLE_BYTES;
281
+ const compute = async () => raw ? `mvp1.r.${base64url(tuple)}` : `mvp1.h.${base64url(await digest(tuple))}`;
282
+ const pendingId = `${kind}\u0000${sourceId}`;
283
+ if (pending.has(pendingId)) return pending.get(pendingId);
284
+ const task = (async () => {
285
+ const key = await compute();
286
+ return activate(key, kind, sourceId);
287
+ })();
288
+ pending.set(pendingId, task);
289
+ try { return await task; } finally { pending.delete(pendingId); }
290
+ }
291
+
292
+ function createBatch(namespace) {
293
+ if (namespace !== undefined && (typeof namespace !== 'string' || !namespace)) fail('E_BAD_ENTITY_NAMESPACE', 'generation namespace must be a non-empty string');
294
+ const token = `mvp1.batch.${++namespaceSequence}`;
295
+ const nextNamespace = namespace ?? `mvp1.ns.${namespaceSequence}`;
296
+ if (usedNamespaces.has(nextNamespace)) fail('E_ENTITY_NAMESPACE_REUSED', `generation namespace ${nextNamespace} was already used`);
297
+ usedNamespaces.add(nextNamespace);
298
+ const staged = new Map();
299
+ const batchPending = new Map();
300
+ const batch = { token, namespace: nextNamespace, state: 'prepared', staged, pending: batchPending };
301
+ batches.set(token, batch);
302
+
303
+ const ensurePrepared = () => {
304
+ if (batch.state !== 'prepared') fail('E_ENTITY_GENERATION_CLOSED', `generation batch is ${batch.state}`);
305
+ };
306
+ const stageKey = (key, kind, sourceId) => {
307
+ ensurePrepared();
308
+ const prior = staged.get(key);
309
+ if (prior) {
310
+ if (prior.kind !== kind || prior.sourceId !== sourceId) fail('E_ENTITY_KEY_COLLISION', `entity key collision for ${key}`);
311
+ return cloned({ key, generation: prior.generation, namespace: nextNamespace });
312
+ }
313
+ const identity = identityFor(key, kind, sourceId);
314
+ const record = { kind, sourceId, generation: ++identity.lastGeneration, namespace: nextNamespace };
315
+ staged.set(key, record);
316
+ return cloned({ key, generation: record.generation, namespace: nextNamespace });
317
+ };
318
+ const registerSyncInBatch = (kind, sourceId) => {
319
+ const tuple = validateIdentity(kind, sourceId);
320
+ if (tuple.length > ENTITY_KEY_RAW_TUPLE_BYTES) fail('E_ENTITY_KEY_ASYNC_REQUIRED', 'long entity identity must be registered asynchronously');
321
+ return stageKey(`mvp1.r.${base64url(tuple)}`, kind, sourceId);
322
+ };
323
+ const registerInBatch = async (kind, sourceId) => {
324
+ const tuple = validateIdentity(kind, sourceId);
325
+ const pendingId = `${kind}\u0000${sourceId}`;
326
+ if (batchPending.has(pendingId)) return batchPending.get(pendingId);
327
+ const task = (async () => {
328
+ const key = tuple.length <= ENTITY_KEY_RAW_TUPLE_BYTES
329
+ ? `mvp1.r.${base64url(tuple)}`
330
+ : `mvp1.h.${base64url(await digest(tuple))}`;
331
+ return stageKey(key, kind, sourceId);
332
+ })();
333
+ batchPending.set(pendingId, task);
334
+ try { return await task; } finally { batchPending.delete(pendingId); }
335
+ };
336
+ return Object.freeze({
337
+ token, namespace: nextNamespace, register: registerInBatch, registerSync: registerSyncInBatch,
338
+ lookup(key) {
339
+ const record = staged.get(key);
340
+ return record ? cloned({ kind: record.kind, sourceId: record.sourceId, generation: record.generation, namespace: record.namespace }) : null;
341
+ },
342
+ has(key) { return staged.has(key); },
343
+ hasReceipt(receipt) {
344
+ const record = receipt && staged.get(receipt.key);
345
+ return !!record && receipt.namespace === nextNamespace && receipt.generation === record.generation;
346
+ },
347
+ get size() { return staged.size; },
348
+ });
349
+ }
350
+
351
+ function resolveBatch(value) {
352
+ const token = typeof value === 'string' ? value : value?.token;
353
+ const batch = token && batches.get(token);
354
+ if (!batch) fail('E_UNKNOWN_ENTITY_GENERATION', 'generation batch is unknown');
355
+ return batch;
356
+ }
357
+
358
+ function validateBatchForCommit(value) {
359
+ const batch = resolveBatch(value);
360
+ if (batch.state !== 'prepared') fail('E_ENTITY_GENERATION_CLOSED', `generation batch is ${batch.state}`);
361
+ if (batch.pending.size) fail('E_ENTITY_GENERATION_PENDING', 'generation batch still has pending identity work');
362
+ return batch;
363
+ }
364
+
365
+ return Object.freeze({
366
+ register, registerSync,
367
+ prepareGeneration(options = {}) { return createBatch(options.namespace); },
368
+ validateGeneration(value) { validateBatchForCommit(value); return true; },
369
+ commitGeneration(value) {
370
+ const batch = validateBatchForCommit(value);
371
+ batch.state = 'committed';
372
+ active.clear();
373
+ for (const [key, record] of batch.staged) active.set(key, { ...record });
374
+ activeNamespace = batch.namespace;
375
+ generationRequired = true;
376
+ batches.delete(batch.token);
377
+ return cloned({ namespace: activeNamespace, size: active.size });
378
+ },
379
+ discardGeneration(value) {
380
+ const batch = resolveBatch(value);
381
+ if (batch.state !== 'prepared') return false;
382
+ batch.state = 'discarded'; batch.staged.clear(); batches.delete(batch.token); return true;
383
+ },
384
+ lookup(key) {
385
+ const record = active.get(key);
386
+ return record ? cloned({ kind: record.kind, sourceId: record.sourceId, generation: record.generation }) : null;
387
+ },
388
+ lookupQualified(receipt) {
389
+ const record = receipt && active.get(receipt.key);
390
+ return record && receipt.namespace === record.namespace && receipt.generation === record.generation
391
+ ? cloned({ kind: record.kind, sourceId: record.sourceId, generation: record.generation, namespace: record.namespace }) : null;
392
+ },
393
+ has(key, qualifier) {
394
+ const record = active.get(key);
395
+ if (!record) return false;
396
+ if (!qualifier) return true;
397
+ return qualifier.namespace === record.namespace && qualifier.generation === record.generation;
398
+ },
399
+ hasReceipt(receipt) {
400
+ const record = receipt && active.get(receipt.key);
401
+ return !!record && receipt.namespace === record.namespace && receipt.generation === record.generation;
402
+ },
403
+ generationOf(key) { return active.get(key)?.generation ?? null; },
404
+ namespaceOf(key) { return active.get(key)?.namespace ?? null; },
405
+ currentNamespace() { return activeNamespace; },
406
+ generationQualificationRequired() { return generationRequired; },
407
+ retire(key, generation) {
408
+ const record = active.get(key);
409
+ if (!record || record.generation !== generation) return false;
410
+ active.delete(key); return true;
411
+ },
412
+ get size() { return active.size; },
413
+ clear() { identities.clear(); active.clear(); pending.clear(); batches.clear(); usedNamespaces.clear(); usedNamespaces.add('mvp1.ns.legacy'); activeNamespace = 'mvp1.ns.legacy'; generationRequired = false; },
414
+ });
415
+ }
416
+
417
+ const ORIGINS = new Set(['tree', 'mesh', 'inspector', 'programmatic']);
418
+ const OPERATIONS = new Set(['replace', 'add', 'toggle', 'clear']);
419
+
420
+ function checkedKeys(keys, registry, field = 'keys', receipts = null) {
421
+ if (!Array.isArray(keys) || keys.some((key) => typeof key !== 'string' || !validEntityKey(key))) fail('E_BAD_SELECTION', `${field} must contain canonical keys`);
422
+ if (new Set(keys).size !== keys.length) fail('E_BAD_SELECTION', `${field} contains duplicates`);
423
+ if (registry && keys.length > registry.size) fail('E_UNKNOWN_ENTITY_KEY', `${field} exceeds the current registry`);
424
+ if (registry) for (const key of keys) if (!registry.has(key)) fail('E_UNKNOWN_ENTITY_KEY', `${field} contains an unknown or retired key`);
425
+ if (receipts !== null) {
426
+ if (!Array.isArray(receipts) || receipts.length !== keys.length) fail('E_STALE_ENTITY_GENERATION', `${field} receipts must match every key`);
427
+ for (let index = 0; index < keys.length; index++) {
428
+ const receipt = receipts[index];
429
+ if (!receipt || receipt.key !== keys[index] || !registry?.lookupQualified?.(receipt)) {
430
+ fail('E_STALE_ENTITY_GENERATION', `${field} contains a stale entity generation`);
431
+ }
432
+ }
433
+ }
434
+ return [...keys];
435
+ }
436
+
437
+ export function validateSelectionCommit(commit, { previousRevision, registry } = {}) {
438
+ if (!commit || typeof commit !== 'object') fail('E_BAD_SELECTION', 'selection commit must be an object');
439
+ if (!Number.isSafeInteger(commit.revision) || commit.revision < 0) fail('E_BAD_SELECTION_REVISION', 'revision must be a non-negative safe integer');
440
+ if (Number.isSafeInteger(previousRevision) && commit.revision !== previousRevision + 1) fail('E_BAD_SELECTION_REVISION', 'revision must advance exactly once');
441
+ if (!ORIGINS.has(commit.origin)) fail('E_BAD_SELECTION_ORIGIN', 'selection origin is invalid');
442
+ if (!OPERATIONS.has(commit.operation)) fail('E_BAD_SELECTION_OPERATION', 'selection operation is invalid');
443
+ const receipts = own(commit, 'receipts') ? commit.receipts : null;
444
+ const keys = checkedKeys(commit.keys, registry, 'keys', receipts);
445
+ const primaryKey = commit.primaryKey ?? null;
446
+ if ((primaryKey === null) !== (keys.length === 0)) fail('E_BAD_SELECTION_PRIMARY', 'primaryKey is null exactly when keys is empty');
447
+ if (primaryKey !== null && !keys.includes(primaryKey)) fail('E_BAD_SELECTION_PRIMARY', 'primaryKey must occur in keys');
448
+ if (commit.operation === 'clear' && keys.length) fail('E_BAD_SELECTION_OPERATION', 'clear requires an empty selection');
449
+ return cloned({ revision: commit.revision, origin: commit.origin, operation: commit.operation, keys, primaryKey });
450
+ }
451
+
452
+ export function applySelectionProposal(previous, proposal, registry) {
453
+ if (!previous || !Number.isSafeInteger(previous.revision)) fail('E_BAD_SELECTION', 'previous commit is invalid');
454
+ if (!proposal || proposal.baseRevision !== previous.revision) fail('E_STALE_SELECTION', 'proposal revision is stale');
455
+ if (proposal.origin !== 'mesh') fail('E_BAD_SELECTION_ORIGIN', 'a viewport proposal must originate from mesh interaction');
456
+ if (!OPERATIONS.has(proposal.operation)) fail('E_BAD_SELECTION_OPERATION', 'proposal operation is invalid');
457
+ const qualificationRequired = registry?.generationQualificationRequired?.() === true;
458
+ if (qualificationRequired && proposal.namespace !== registry.currentNamespace?.()) fail('E_STALE_ENTITY_GENERATION', 'proposal namespace is stale');
459
+ const operandReceipts = own(proposal, 'operandReceipts') ? proposal.operandReceipts : null;
460
+ if (qualificationRequired && (proposal.operandKeys ?? []).length && operandReceipts === null) fail('E_STALE_ENTITY_GENERATION', 'proposal operands need generation receipts');
461
+ const operands = checkedKeys(proposal.operandKeys ?? [], registry, 'operandKeys', operandReceipts);
462
+ const keys = [...previous.keys];
463
+ let primaryKey = previous.primaryKey;
464
+ if (proposal.operation === 'replace') {
465
+ keys.splice(0, keys.length, ...operands); primaryKey = keys.at(-1) ?? null;
466
+ } else if (proposal.operation === 'clear') {
467
+ if (operands.length) fail('E_BAD_SELECTION_OPERATION', 'clear accepts no operands');
468
+ keys.splice(0); primaryKey = null;
469
+ } else if (proposal.operation === 'add') {
470
+ let added = null;
471
+ for (const key of operands) if (!keys.includes(key)) { keys.push(key); added = key; }
472
+ if (added !== null) primaryKey = added;
473
+ } else {
474
+ let lastAdded = null;
475
+ for (const key of operands) {
476
+ const index = keys.indexOf(key);
477
+ if (index >= 0) keys.splice(index, 1);
478
+ else { keys.push(key); lastAdded = key; }
479
+ }
480
+ if (!keys.length) primaryKey = null;
481
+ else if (lastAdded !== null) primaryKey = lastAdded;
482
+ else if (!keys.includes(primaryKey)) primaryKey = keys.at(-1);
483
+ }
484
+ return validateSelectionCommit({ revision: previous.revision + 1, origin: proposal.origin, operation: proposal.operation, keys, primaryKey }, { previousRevision: previous.revision, registry });
485
+ }
486
+
487
+ /** Clip a segment against convex half-spaces without mutating either endpoint. */
488
+ export function clipSegmentToPlanes(a, b, planes = []) {
489
+ let lo = 0, hi = 1;
490
+ for (const plane of planes) {
491
+ const n = plane && plane.normal;
492
+ if (!n) continue;
493
+ const c = Number(plane.constant) || 0;
494
+ const da = n[0] * a[0] + n[1] * a[1] + n[2] * a[2] + c;
495
+ const db = n[0] * b[0] + n[1] * b[1] + n[2] * b[2] + c;
496
+ if (da < 0 && db < 0) return null;
497
+ if (da < 0 || db < 0) {
498
+ const t = da / (da - db);
499
+ if (da < 0) lo = Math.max(lo, t); else hi = Math.min(hi, t);
500
+ if (lo > hi) return null;
501
+ }
502
+ }
503
+ const mix = (t) => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t];
504
+ return [mix(lo), mix(hi)];
505
+ }
@@ -0,0 +1,150 @@
1
+ /*
2
+ * Steel's scene binding for the shared viewport controller.
3
+ *
4
+ * The adapter translates neutral lifecycle, camera, selection and visibility requests into the
5
+ * existing Steel renderer hooks. Geometry construction and every authoring tool remain here-side.
6
+ */
7
+
8
+ const requiredHooks = Object.freeze([
9
+ 'rebuild', 'bounds', 'fit', 'setPaintAllowed', 'setSelectionState',
10
+ 'setProjection', 'setDisplayMode', 'displayMode', 'applyView', 'cameraState', 'setCameraState', 'sectionState',
11
+ 'setSectionState', 'objectsState', 'applyObjectsState', 'hideSelection', 'isolateSelection',
12
+ 'clearVisibility', 'hasVisibilityFilter', 'show', 'hide', 'dispose',
13
+ ]);
14
+
15
+ function assertHooks(hooks) {
16
+ if (!hooks || typeof hooks !== 'object') throw new Error('createSteelViewportAdapter: hooks are required');
17
+ for (const name of requiredHooks) if (typeof hooks[name] !== 'function') throw new Error(`createSteelViewportAdapter: hook ${name} is required`);
18
+ }
19
+
20
+ const clone = (value) => {
21
+ if (Array.isArray(value)) return value.map(clone);
22
+ if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, clone(item)]));
23
+ return value;
24
+ };
25
+
26
+ const positive = (value, fallback) => Number.isFinite(value) && value > 0 ? value : fallback;
27
+ const neutralCamera = (value = {}) => ({
28
+ projection: value.proj ?? value.projection ?? 'ortho',
29
+ position: clone(value.pos ?? value.position ?? [1, -1, 1]),
30
+ target: clone(value.target ?? [0, 0, 0]),
31
+ up: clone(value.up ?? [0, 0, 1]),
32
+ orthoHeight: positive(value.orthoH ?? value.orthoHeight, 1),
33
+ zoom: positive(value.zoom, 1),
34
+ near: positive(value.near, 1),
35
+ far: positive(value.far, 50_000_000),
36
+ });
37
+
38
+ const legacyCamera = (value = {}) => ({
39
+ v: 1, pos: clone(value.position), target: clone(value.target), proj: value.projection,
40
+ orthoH: value.orthoHeight, zoom: value.zoom, up: clone(value.up), near: value.near, far: value.far,
41
+ });
42
+
43
+ /** Create the real provider adapter over an explicit set of Steel-owned hooks. */
44
+ /** @param {{hooks: any, identityRegistry?: any}} options */
45
+ export function createSteelViewportAdapter({ hooks, identityRegistry = null }) {
46
+ assertHooks(hooks);
47
+ let mountContext = null;
48
+ let renderEpoch = 0;
49
+ let disposed = false;
50
+ let releaseGestureInterceptor = null;
51
+
52
+ const publish = () => {
53
+ if (!mountContext || disposed || typeof hooks.renderRecords !== 'function') return;
54
+ mountContext.replaceRenderRecords({
55
+ instanceToken: mountContext.instanceToken,
56
+ renderEpoch: ++renderEpoch,
57
+ records: hooks.renderRecords().map((record) => Object.freeze({ ...record })),
58
+ });
59
+ };
60
+
61
+ const source = (key) => identityRegistry?.lookup(key) ?? null;
62
+ const neutralHit = (hit) => hit ? ({
63
+ providerToken: hit.providerToken, key: hit.key,
64
+ instanceIndex: Number.isInteger(hit.instanceIndex) ? hit.instanceIndex
65
+ : (Number.isInteger(hit.batchId) ? hit.batchId : (Number.isInteger(hit.instanceId) ? hit.instanceId : null)),
66
+ point: hit.point, normal: hit.normal, distance: hit.distance,
67
+ }) : null;
68
+ /** @param {{selectedKeys?: string[], primaryKey?: string|null, hoverKey?: string|null}} presentation */
69
+ const applyTypedSelection = ({ selectedKeys = [], hoverKey = null, ghostUnselected = false }) => {
70
+ if (!identityRegistry) { hooks.applyPresentation?.({ selectedKeys, hoverKey, ghostUnselected }); return; }
71
+ const nativeIds = [], gridIds = [];
72
+ let referenceId = null, referenceObject = null;
73
+ for (const key of selectedKeys) {
74
+ const item = source(key); if (!item) continue;
75
+ if (item.kind === 'native') nativeIds.push(item.sourceId);
76
+ else if (item.kind === 'grid') gridIds.push(item.sourceId);
77
+ else if (item.kind === 'reference') referenceId = item.sourceId;
78
+ else if (item.kind === 'reference-object') {
79
+ try { referenceObject = JSON.parse(item.sourceId); } catch (_) { referenceObject = null; }
80
+ }
81
+ }
82
+ hooks.setSelectionState(nativeIds, gridIds, ghostUnselected);
83
+ if (referenceObject && Array.isArray(referenceObject) && referenceObject.length >= 2) {
84
+ if (typeof hooks.selectReferenceObjectReceipt === 'function') hooks.selectReferenceObjectReceipt(referenceObject[0], referenceObject[1]);
85
+ else if (Number.isInteger(referenceObject[2])) hooks.selectReferenceObject?.(referenceObject[0], referenceObject[2]);
86
+ } else hooks.selectReference?.(referenceId);
87
+ const hover = hoverKey ? source(hoverKey) : null;
88
+ hooks.setHover?.(hover?.kind === 'native' ? hover.sourceId : null);
89
+ };
90
+
91
+ return Object.freeze({
92
+ mount(context) {
93
+ if (disposed) throw new Error('Steel viewport adapter is disposed');
94
+ mountContext = context;
95
+ hooks.mount?.(context);
96
+ publish();
97
+ if (context.gestureBroker && typeof hooks.gestureInterceptor === 'function') {
98
+ releaseGestureInterceptor = context.gestureBroker.register(hooks.gestureInterceptor());
99
+ }
100
+ },
101
+ unmount() {
102
+ releaseGestureInterceptor?.(); releaseGestureInterceptor = null;
103
+ hooks.unmount?.(); mountContext = null;
104
+ },
105
+ async rebuild(context) { const result = await hooks.rebuild(context.fit, context); publish(); return result ?? { empty: false }; },
106
+ bounds(purpose, keys) { return hooks.bounds(purpose, keys); },
107
+ fit(payload) { return hooks.fit(payload); },
108
+ pick(payload) { return neutralHit(hooks.pick?.(payload) ?? null); },
109
+ raycastRecords(event, filters) {
110
+ return (hooks.raycastRecords?.(event, filters) ?? []).map(neutralHit);
111
+ },
112
+ applyCamera(value) { return hooks.setCameraState(legacyCamera(value)); },
113
+ applyOrientation(value) { return hooks.applyView(value); },
114
+ applyDisplayMode(value) { return hooks.setDisplayMode(value); },
115
+ applyClipState(value) { return hooks.setSectionState(clone(value)); },
116
+ applyPresentation: applyTypedSelection,
117
+ beforeRender(time) { hooks.beforeRender?.(time); },
118
+ render(time) { hooks.render?.(time); },
119
+ afterRender(time) { hooks.afterRender?.(time); },
120
+ setPaintAllowed(on) { hooks.setPaintAllowed(on === true); },
121
+ snapshotVisibility() { return clone(hooks.objectsState()); },
122
+ applyVisibilitySnapshot(value) { return hooks.applyObjectsState(clone(value)); },
123
+ hideSelection(keys = []) {
124
+ const actionable = keys.filter((key) => { const kind = source(key)?.kind; return kind === 'native' || kind === 'grid'; });
125
+ const count = Number(hooks.hideSelection()) || 0;
126
+ return Object.freeze({ count, hiddenKeys: Object.freeze(actionable.slice(0, count)) });
127
+ },
128
+ isolateSelection() { return hooks.isolateSelection(); },
129
+ // Steel keeps an isolation apart from its hidden sets, so lifting it brings back only what it hid.
130
+ isIsolated() { return hooks.isIsolated?.() === true; },
131
+ clearIsolation() { return hooks.clearIsolation?.(); },
132
+ clearVisibility() { return hooks.clearVisibility(); },
133
+ hasVisibilityFilter() { return hooks.hasVisibilityFilter(); },
134
+ isVisibilityActionable(key) { const kind = source(key)?.kind; return kind === 'native' || kind === 'grid'; },
135
+ show() { return hooks.show(); },
136
+ hide() { return hooks.hide(); },
137
+ resize(value) { return hooks.resize(value); },
138
+ blockOrbit(reason) { return hooks.blockOrbit?.(reason) ?? (() => {}); },
139
+ snapData: typeof hooks.snapData === 'function' ? (...args) => hooks.snapData(...args) : undefined,
140
+ workingPlaneData: typeof hooks.workingPlaneData === 'function' ? (...args) => hooks.workingPlaneData(...args) : undefined,
141
+ cameraState() { return neutralCamera(hooks.cameraState()); },
142
+ displayMode() { return hooks.displayMode(); },
143
+ sectionState() {
144
+ const value = hooks.sectionState();
145
+ return clone({ clipping: value.clipping ?? value.clips ?? [], workPlane: value.workPlane ?? null, workArea: value.workArea ?? null, activeClipGesture: value.activeClipGesture ?? null });
146
+ },
147
+ publishRenderRecords: publish,
148
+ dispose() { if (disposed) return; disposed = true; hooks.dispose(); mountContext = null; },
149
+ });
150
+ }