Files
road-compiler/test/workbench-edit-api.js
T

676 lines
28 KiB
JavaScript

'use strict';
const assert = require('assert/strict');
const fs = require('fs');
const os = require('os');
const path = require('path');
const { compileInput } = require('../src/compile/compiler');
const { compileRoadModel, loadOverrides } = require('../src/compile/native-road');
const { ensureRevisionStore } = require('../src/compile/road-revisions');
const {
editPreview,
editState,
rebaseEdits,
saveEdits,
state: browseState,
selectionFrom,
} = require('../workbench/server');
const { snapshot: outputSnapshot } = require('./fixture-baseline');
const workspace = fs.mkdtempSync(path.join(os.tmpdir(), 'workbench-edit-api-'));
const input = {
areaId: 'edit-api-test',
osmFile: path.join(workspace, 'source.osm'),
outDir: path.join(workspace, 'outputs', 'native-road'),
stagingDir: path.join(workspace, 'outputs', '_pipeline'),
overridesFile: path.join(workspace, 'native-road-overrides.json'),
trafficSignalsFile: path.join(workspace, 'native-traffic-signals.json'),
options: { edgeLines: false, junctionTemplates: { enabled: false, references: [] } },
};
fs.copyFileSync(path.join(__dirname, 'fixtures', 'fengshu-er-road.osm'), input.osmFile);
fs.writeFileSync(input.overridesFile, `${JSON.stringify({ schema: 'native-road-overrides/v1', overrides: [] })}\n`);
fs.writeFileSync(
input.trafficSignalsFile,
`${JSON.stringify({ schema: 'native-traffic-signals/v1', provenance: 'empty', assemblies: { type: 'FeatureCollection', features: [] } })}\n`,
);
const initialized = ensureRevisionStore(workspace, input.options);
const area = compileInput({
...input,
areaConfigSnapshotFile: initialized.paths.activeAreaConfig,
editsFile: initialized.paths.activeEdits,
}).area;
const state = editState(area);
assert.equal(state.active, true);
assert.equal(state.documentVersion, 0);
assert.equal(state.handles.schema, 'road-edit-handles/v1');
assert.equal(state.activeRevisionId, 'rev-0001');
const trackedFiles = [
initialized.paths.activeEdits,
initialized.paths.activeState,
initialized.paths.activeAreaConfig,
].map((file) => ({
file,
bytes: fs.readFileSync(file),
mtimeMs: fs.statSync(file).mtimeMs,
}));
const preview = editPreview(area, { previewSeq: 17, document: state.document });
assert.equal(preview.ok, true);
assert.equal(preview.previewSeq, 17);
assert.equal(preview.degraded, false);
assert.equal(preview.handles.schema, 'road-edit-handles/v1');
assert.ok(preview.layers.roadSurface);
for (const tracked of trackedFiles) {
assert.deepEqual(fs.readFileSync(tracked.file), tracked.bytes, `${tracked.file} bytes unchanged by preview`);
assert.equal(fs.statSync(tracked.file).mtimeMs, tracked.mtimeMs, `${tracked.file} mtime unchanged by preview`);
}
const saved = saveEdits(area, { expectedDocumentVersion: 0, document: state.document });
assert.equal(saved.documentVersion, 1);
const beforeConflict = fs.readFileSync(initialized.paths.activeEdits);
assert.throws(
() => saveEdits(area, { expectedDocumentVersion: 0, document: state.document }),
(error) => error.statusCode === 409 && error.current.documentVersion === 1,
);
assert.deepEqual(fs.readFileSync(initialized.paths.activeEdits), beforeConflict, '409 does not write the document');
const checkpoint = require('../src/compile/road-revisions').createCheckpoint(workspace, 'Preview checkpoint');
assert.equal(checkpoint.manifest.id, 'rev-0002');
const rebased = rebaseEdits(area, checkpoint.manifest.id);
assert.equal(rebased.counts.exact, 0);
assert.deepEqual(rebased.constraints, []);
// The map saves `constraints` + `operations`, not a whole document. That merge path
// is what the client actually exercises, and leaving the operations out is exactly
// how the first wiring produced a 400.
const edgeHandle = state.handles.handles.find((handle) => handle.kind === 'road-edge-offset');
assert.ok(edgeHandle, 'the fixture must publish a road edge handle');
const clientConstraint = {
id: `constraint:${edgeHandle.handleId}`,
kind: 'road-edge-offset',
anchor: edgeHandle.anchor,
anchorSnapshot: {
coordinate: edgeHandle.position,
tangentAzimuth: 0,
roadLengthMeters: 120,
osmNodeIds: ['1'],
},
value: { offsetMeters: 0.5, transition: 'smoothstep' },
enabled: true,
status: 'exact',
provenance: { operationId: 'operation:client:1', createdAt: '2026-08-27T00:00:00.000Z' },
};
const clientOperation = {
id: clientConstraint.provenance.operationId,
createdAt: clientConstraint.provenance.createdAt,
constraintIds: [clientConstraint.id],
};
assert.throws(
() => saveEdits(area, { expectedDocumentVersion: 1, constraints: [clientConstraint], operations: [] }),
/provenance\.operationId/,
'a constraint saved without its operation must be rejected, not written',
);
const clientSaved = saveEdits(area, {
expectedDocumentVersion: 1,
constraints: [clientConstraint],
operations: [clientOperation],
});
assert.equal(clientSaved.documentVersion, 2);
// JunctionTools uses the same preview and compile solver. Exercise a real
// junction approach handle so a geometry edit cannot be preview-only: the
// published intersection layer must be byte-equivalent after a save/recompile.
const junctionHandle = state.handles.handles.find((handle) => handle.kind === 'junction-approach-width');
assert.ok(junctionHandle, 'the fixture must publish a junction approach width handle');
const junctionModel = compileRoadModel(fs.readFileSync(input.osmFile, 'utf8'), loadOverrides(input.overridesFile));
const approach = junctionModel.roads.find((road) => road.segmentId === junctionHandle.anchor.segmentId);
assert.ok(approach, 'the junction handle must resolve to a model road');
const junctionConstraint = {
id: `constraint:${junctionHandle.handleId}`,
kind: 'junction-approach-width',
anchor: junctionHandle.anchor,
anchorSnapshot: {
coordinate: junctionHandle.position,
tangentAzimuth: junctionHandle.axisAzimuth,
roadLengthMeters: 120,
osmNodeIds: approach.sourceNodeIds,
},
value: { widthMeters: junctionHandle.value.current + 0.25 },
enabled: true,
status: 'exact',
provenance: { operationId: 'operation:client:junction-1', createdAt: '2026-08-27T00:00:01.000Z' },
};
const junctionOperation = {
id: junctionConstraint.provenance.operationId,
createdAt: junctionConstraint.provenance.createdAt,
constraintIds: [junctionConstraint.id],
};
const junctionConstraints = [clientConstraint, junctionConstraint];
const junctionOperations = [clientOperation, junctionOperation];
const junctionPreview = editPreview(area, {
previewSeq: 23,
constraints: junctionConstraints,
operations: junctionOperations,
});
assert.equal(junctionPreview.ok, true);
assert.ok(junctionPreview.layers.intersectionSurface);
const junctionSaved = saveEdits(area, {
expectedDocumentVersion: 2,
constraints: junctionConstraints,
operations: junctionOperations,
});
assert.equal(junctionSaved.documentVersion, 3);
assert.throws(
() =>
saveEdits(area, {
expectedDocumentVersion: 3,
constraints: [{ ...junctionConstraint, value: { widthMeters: 1 } }],
operations: [junctionOperation],
}),
(error) => error.statusCode === 400 && /不能小于/.test(error.message),
'blocking junction geometry diagnostics must prevent saving',
);
const junctionCompiled = compileInput({
...input,
outDir: path.join(workspace, 'outputs', 'junction-with-edits'),
stagingDir: path.join(workspace, 'outputs', '_junction-with-edits'),
areaConfigSnapshotFile: initialized.paths.activeAreaConfig,
editsFile: initialized.paths.activeEdits,
});
const publishedJunction = JSON.parse(
fs.readFileSync(
path.join(junctionCompiled.area.outputs.nativeRoadDir, 'layers', 'intersection_surface.geojson'),
'utf8',
),
);
assert.deepEqual(
publishedJunction,
junctionPreview.layers.intersectionSurface,
'formal compile must publish the same junction geometry returned by preview',
);
// A save that does not survive a reload as `exact` was cosmetic.
const reloaded = editState(area);
assert.equal(reloaded.documentVersion, 3);
assert.deepEqual(
reloaded.document.constraints.map((item) => item.id),
[clientConstraint.id, junctionConstraint.id],
);
assert.equal(reloaded.constraintStates[0].status, 'exact');
assert.equal(reloaded.constraintStates[0].applied, true);
// A saved document has to reach the geometry, not just the file. `compileInput()`
// is the only caller that passes `editsFile`, and the workbench serves the outputs
// it wrote — so a stage that ignored the document would make a save look successful
// while a refresh still showed the pre-edit map. The existing identity test cannot
// catch that: an ignored document and an empty one produce the same output.
const noEdits = {
...input,
outDir: path.join(workspace, 'outputs', 'no-edits'),
stagingDir: path.join(workspace, 'outputs', '_no-edits'),
areaConfigSnapshotFile: initialized.paths.activeAreaConfig,
};
const withEdits = {
...input,
outDir: path.join(workspace, 'outputs', 'with-edits'),
stagingDir: path.join(workspace, 'outputs', '_with-edits'),
areaConfigSnapshotFile: initialized.paths.activeAreaConfig,
editsFile: initialized.paths.activeEdits,
};
compileInput(noEdits);
compileInput(withEdits);
assert.notDeepEqual(
outputSnapshot(withEdits).files,
outputSnapshot(noEdits).files,
'a saved constraint must change the compiled output, or saving cannot survive a refresh',
);
// Typed scope must survive parsing and cannot silently choose the first key.
assert.deepEqual(selectionFrom(new URLSearchParams('cluster=fixture-five-arm')), {
type: 'cluster',
id: 'fixture-five-arm',
});
assert.deepEqual(selectionFrom({ junction: '8005332807' }), { type: 'junction', id: '8005332807' });
for (const invalid of [
{ cluster: 'one', junction: 'two' },
{ cluster: '' },
{ cluster: {} },
new URLSearchParams('cluster=one&cluster=two'),
]) {
assert.throws(() => selectionFrom(invalid), /selection/);
}
assert.throws(() => editPreview(area, { selection: { cluster: 'one', segment: 'two' } }), /selection/);
const cluster = {
id: 'fixture-five-arm',
template: 'complex-junction-v1',
nodeIds: ['8005332807', '8024512135', '8024512145', '8024512147', '8613058676'],
coreRadiusMeters: 24,
};
const complexInput = {
...input,
outDir: path.join(workspace, 'outputs', 'complex'),
stagingDir: path.join(workspace, 'outputs', '_complex'),
options: { edgeLines: false, junctionTemplates: { enabled: true, clusters: [cluster] } },
};
const unsourcedComplexArea = compileInput(complexInput).area;
const unsourcedState = editState(unsourcedComplexArea, selectionFrom({ cluster: cluster.id }));
const unsourcedPreview = editPreview(unsourcedComplexArea, {
document: { ...unsourcedState.document, constraints: [], operations: [] },
selection: { cluster: cluster.id },
});
assert.equal(
unsourcedPreview.layers.crosswalks.features.some((feature) => feature.properties.kind === 'complex-crosswalk'),
true,
'complex junctions default to crossings when pavement is available',
);
for (const response of [unsourcedState, unsourcedPreview])
assert.equal(
response.handles.handles.some((handle) => handle.kind === 'cluster-crossing-inset'),
false,
);
assert.ok(unsourcedPreview.diagnostics.some((item) => item.rule === 'complex-junction-crossing-source-missing'));
// Supply an actual crossing node on the source way near its inferred stop line.
// Keep this input separate so the default fixture continues to test unknown evidence.
const inferredStopLine = unsourcedPreview.layers.vehicleStopLines.features.find(
(feature) => feature.properties.kind === 'complex-stop-line',
);
assert.ok(inferredStopLine);
const crossingCoordinate = inferredStopLine.geometry.coordinates[0]
.slice(0, -1)
.reduce((center, point) => [center[0] + point[0] / 4, center[1] + point[1] / 4], [0, 0]);
const originalXml = fs.readFileSync(input.osmFile, 'utf8');
const sourceModel = compileRoadModel(originalXml, loadOverrides(input.overridesFile));
const sourceRoad = sourceModel.roads.find((road) => road.id === inferredStopLine.properties.road_id);
const distanceSquared = (point) =>
((point[0] - crossingCoordinate[0]) * Math.cos((point[1] * Math.PI) / 180)) ** 2 +
(point[1] - crossingCoordinate[1]) ** 2;
const attribute = (attributes, name) => new RegExp(`\\b${name}\\s*=\\s*['"]([^'"]+)['"]`).exec(attributes)?.[1];
const sourceNodes = new Map(
[...originalXml.matchAll(/<node\b([^>]*)>/g)].map((match) => [
attribute(match[1], 'id'),
[Number(attribute(match[1], 'lon')), Number(attribute(match[1], 'lat'))],
]),
);
const sourcedOsmFile = path.join(workspace, 'source-with-crossing.osm');
const crossingNodeId = 'known-complex-crossing';
let insertedCrossing = false;
const sourcedXml = originalXml
.replace(/<way\b([^>]*)>([\s\S]*?)<\/way>/g, (way, attributes) => {
const wayId = attribute(attributes, 'id');
if (!sourceRoad.osmWayIds.includes(wayId)) return way;
const refs = [...way.matchAll(/<nd\b([^>]*)\/>/g)].map((match) => attribute(match[1], 'ref'));
const insertionSegment = refs
.slice(1)
.map((ref, index) => ({
index,
distance: distanceSquared(sourceNodes.get(ref)) + distanceSquared(sourceNodes.get(refs[index])),
}))
.sort((first, second) => first.distance - second.distance)[0].index;
const followingNode = refs[insertionSegment + 1];
return way.replace(new RegExp(`<nd\\s+ref=['"]${followingNode}['"]\\s*/>`), (node) => {
insertedCrossing = true;
return `<nd ref="${crossingNodeId}"/>${node}`;
});
})
.replace(
'</osm>',
`<node id="${crossingNodeId}" lon="${crossingCoordinate[0]}" lat="${crossingCoordinate[1]}"><tag k="highway" v="crossing"/></node></osm>`,
);
assert.ok(insertedCrossing);
fs.writeFileSync(sourcedOsmFile, sourcedXml);
const sourcedModel = compileRoadModel(sourcedXml, loadOverrides(input.overridesFile));
const sourceCrossing = sourcedModel.crossings.find((crossing) => crossing.id === crossingNodeId);
assert.deepEqual(sourceCrossing.coordinate, crossingCoordinate);
assert.ok(sourceCrossing.osmWayIds.some((id) => sourceRoad.osmWayIds.includes(id)));
const complexArea = compileInput({
...complexInput,
osmFile: sourcedOsmFile,
outDir: path.join(workspace, 'outputs', 'complex-sourced'),
stagingDir: path.join(workspace, 'outputs', '_complex-sourced'),
}).area;
const clusterState = editState(complexArea, selectionFrom({ cluster: cluster.id }));
assert.ok(
clusterState.handles.handles.every((handle) =>
[
'cluster-carriageway-width',
'cluster-carriageway-cutback',
'cluster-carriageway-transition-length',
'cluster-carriageway-position',
'cluster-carriageway-direction',
'cluster-carriageway-edge-offset',
'cluster-corner-radius',
'cluster-crossing-inset',
'cluster-stop-line-offset',
].includes(handle.kind),
),
'cluster selection publishes only scoped complex geometry handles',
);
assert.ok(clusterState.handles.handles.length, 'the complex fixture must publish editable carriageways');
assert.deepEqual(clusterState.junctionStructure.junctionRef, { type: 'cluster', id: cluster.id });
assert.equal(clusterState.junctionStructure.shape.effectiveArmCount, 5);
assert.equal(
clusterState.junctionStructure.capability.editable,
false,
'structure capability opens with the frontend stage',
);
const complexTracked = trackedFiles.map(({ file }) => ({
file,
bytes: fs.readFileSync(file),
mtimeMs: fs.statSync(file).mtimeMs,
}));
const emptyDocument = { ...clusterState.document, constraints: [], operations: [] };
const clusterPreview = editPreview(complexArea, { document: emptyDocument, selection: { cluster: cluster.id } });
assert.deepEqual(clusterPreview.handles.handles, clusterState.handles.handles);
assert.deepEqual(
clusterPreview.junctionStructure,
clusterState.junctionStructure,
'preview and persisted compiler structure agree',
);
const complexWidthHandle = clusterState.handles.handles.find(
(handle) =>
handle.kind === 'cluster-carriageway-width' &&
handle.anchor.sourceRoadIds.includes(inferredStopLine.properties.road_id) &&
clusterPreview.layers.vehicleStopLines.features.some(
(feature) => feature.properties.carriageway_key === handle.anchor.carriagewayKey,
),
);
const complexWidthConstraint = {
id: 'constraint:complex-width',
kind: 'cluster-carriageway-width',
anchor: complexWidthHandle.anchor,
anchorSnapshot: {
coordinate: complexWidthHandle.position,
tangentAzimuth: complexWidthHandle.axisAzimuth,
roadLengthMeters: 120,
osmNodeIds: complexWidthHandle.anchor.sourceNodeIds,
},
value: { widthMeters: complexWidthHandle.value.current + 0.25 },
enabled: true,
status: 'exact',
provenance: { operationId: 'operation:complex-width', createdAt: '2026-09-08T00:00:00.000Z' },
};
const widenedClusterPreview = editPreview(complexArea, {
document: {
...emptyDocument,
constraints: [complexWidthConstraint],
operations: [
{
id: 'operation:complex-width',
createdAt: '2026-09-08T00:00:00.000Z',
constraintIds: [complexWidthConstraint.id],
},
],
},
selection: { cluster: cluster.id },
});
const complexSurface = (preview) =>
preview.layers.roadSurface.features.find(
(feature) => feature.properties.carriageway_key === complexWidthHandle.anchor.carriagewayKey,
);
assert.notDeepEqual(
complexSurface(widenedClusterPreview).geometry,
complexSurface(clusterPreview).geometry,
'a cluster carriageway constraint must change compiled complex geometry',
);
const baselineApproachRing = complexSurface(clusterPreview).geometry.coordinates[0];
const widenedApproachRing = complexSurface(widenedClusterPreview).geometry.coordinates[0];
assert.deepEqual(
[widenedApproachRing[0], widenedApproachRing[3]],
[baselineApproachRing[0], baselineApproachRing[3]],
'a local width correction must preserve the source-road outer seam',
);
assert.notDeepEqual(
[widenedApproachRing[1], widenedApproachRing[2]],
[baselineApproachRing[1], baselineApproachRing[2]],
'a local width correction must taper into the edited inner section',
);
const editedArmKey = complexSurface(clusterPreview).properties.arm_key;
const crosswalkForArm = (preview) =>
preview.layers.crosswalks.features.find((feature) => feature.properties.arm_key === editedArmKey);
const stopLineForCarriageway = (preview) =>
preview.layers.vehicleStopLines.features.find(
(feature) => feature.properties.carriageway_key === complexWidthHandle.anchor.carriagewayKey,
);
assert.ok(crosswalkForArm(clusterPreview), 'the edited arm must retain a crosswalk envelope');
assert.notEqual(
crosswalkForArm(widenedClusterPreview).properties.span_m,
crosswalkForArm(clusterPreview).properties.span_m,
'a local width correction must update its final crosswalk envelope',
);
assert.ok(stopLineForCarriageway(clusterPreview), 'the edited carriageway must retain its stop line');
assert.notDeepEqual(
stopLineForCarriageway(widenedClusterPreview).geometry,
stopLineForCarriageway(clusterPreview).geometry,
'a local width correction must update its final stop-line geometry',
);
const transitionHandle = clusterState.handles.handles.find(
(handle) =>
handle.kind === 'cluster-carriageway-transition-length' &&
handle.anchor.carriagewayKey === complexWidthHandle.anchor.carriagewayKey,
);
assert.ok(transitionHandle);
const transitionConstraint = {
...complexWidthConstraint,
kind: 'cluster-carriageway-transition-length',
value: { transitionLengthMeters: transitionHandle.value.max - 1 },
};
const transitionPreview = editPreview(complexArea, {
document: {
...emptyDocument,
constraints: [transitionConstraint],
operations: [
{
id: 'operation:complex-width',
createdAt: '2026-09-08T00:00:00.000Z',
constraintIds: [transitionConstraint.id],
},
],
},
selection: { cluster: cluster.id },
});
assert.equal(transitionPreview.constraintStates[0].applied, true);
const transitionedRing = complexSurface(transitionPreview).geometry.coordinates[0];
assert.deepEqual(
[transitionedRing[0], transitionedRing[3]],
[baselineApproachRing[0], baselineApproachRing[3]],
'transition edit must preserve the outer seam',
);
assert.ok(
Math.abs(
complexSurface(transitionPreview).properties.transition_length_m -
transitionConstraint.value.transitionLengthMeters,
) <= 0.1,
'compiled transition length must match the requested meters',
);
assert.notDeepEqual(complexSurface(transitionPreview).geometry, complexSurface(clusterPreview).geometry);
const complexCrossingHandle = clusterState.handles.handles.find((handle) => handle.kind === 'cluster-crossing-inset');
assert.ok(complexCrossingHandle, 'the complex fixture must publish grouped crossing handles');
const renderedComplexCrosswalk = clusterPreview.layers.crosswalks.features.find(
(feature) => feature.properties.crossing_key === complexCrossingHandle.anchor.crossingKey,
);
assert.equal(renderedComplexCrosswalk.properties.facility_evidence, 'source-crossing-node');
assert.deepEqual(renderedComplexCrosswalk.properties.source_crossing_node_ids, [crossingNodeId]);
const crossingHandleLatitudeScale = 111320 * Math.cos((complexCrossingHandle.position[1] * Math.PI) / 180);
assert.ok(
Math.hypot(
(complexCrossingHandle.position[0] - renderedComplexCrosswalk.properties.frame_center[0]) *
crossingHandleLatitudeScale,
(complexCrossingHandle.position[1] - renderedComplexCrosswalk.properties.frame_center[1]) * 111320,
) < 2,
'the complex crossing handle must remain on the rendered crossing frame',
);
const complexCrossingConstraint = {
id: 'constraint:complex-crossing',
kind: 'cluster-crossing-inset',
anchor: complexCrossingHandle.anchor,
anchorSnapshot: {
coordinate: complexCrossingHandle.position,
tangentAzimuth: complexCrossingHandle.axisAzimuth,
roadLengthMeters: 120,
osmNodeIds: cluster.nodeIds,
},
value: { insetMeters: complexCrossingHandle.value.max },
enabled: true,
status: 'exact',
provenance: { operationId: 'operation:complex-crossing', createdAt: '2026-09-08T00:00:00.000Z' },
};
const movedCrossingPreview = editPreview(complexArea, {
document: {
...emptyDocument,
constraints: [complexCrossingConstraint],
operations: [
{
id: 'operation:complex-crossing',
createdAt: '2026-09-08T00:00:00.000Z',
constraintIds: [complexCrossingConstraint.id],
},
],
},
selection: { cluster: cluster.id },
});
const crossingGeometry = (preview) =>
preview.layers.crosswalks.features.find(
(feature) => feature.properties.crossing_key === complexCrossingHandle.anchor.crossingKey,
)?.geometry;
assert.deepEqual(
movedCrossingPreview.constraintStates?.map((state) => state.applied),
[true],
JSON.stringify(movedCrossingPreview.constraintStates),
);
assert.notDeepEqual(
crossingGeometry(movedCrossingPreview),
crossingGeometry(clusterPreview),
'a complex crossing inset must move only its keyed stripe group',
);
const complexCornerHandle = clusterState.handles.handles.find((handle) => handle.kind === 'cluster-corner-radius');
assert.ok(complexCornerHandle, 'the complex fixture must publish stable corner-radius handles');
const complexCornerConstraint = {
id: 'constraint:complex-corner',
kind: 'cluster-corner-radius',
anchor: complexCornerHandle.anchor,
anchorSnapshot: {
coordinate: complexCornerHandle.position,
tangentAzimuth: complexCornerHandle.axisAzimuth,
roadLengthMeters: 120,
osmNodeIds: cluster.nodeIds,
},
value: { radiusMeters: complexCornerHandle.value.min },
enabled: true,
status: 'exact',
provenance: { operationId: 'operation:complex-corner', createdAt: '2026-09-08T00:00:00.000Z' },
};
const roundedClusterPreview = editPreview(complexArea, {
document: {
...emptyDocument,
constraints: [complexCornerConstraint],
operations: [
{
id: 'operation:complex-corner',
createdAt: '2026-09-08T00:00:00.000Z',
constraintIds: [complexCornerConstraint.id],
},
],
},
selection: { cluster: cluster.id },
});
assert.deepEqual(
roundedClusterPreview.constraintStates?.map((state) => state.applied),
[true],
);
const complexCorner = (preview) =>
preview.layers.roadSurface.features.find(
(feature) => feature.properties.corner_key === complexCornerHandle.anchor.cornerKey,
);
assert.ok(complexCorner(clusterPreview), 'the corner handle must identify a compiled corner surface');
assert.equal(
complexCorner(roundedClusterPreview).properties.corner_radius_m,
complexCornerConstraint.value.radiusMeters,
'the compiled corner must consume its scoped radius value',
);
assert.notDeepEqual(
complexCorner(roundedClusterPreview).geometry,
complexCorner(clusterPreview).geometry,
'a cluster corner constraint must change its compiled corner geometry',
);
const browsing = browseState(complexArea);
const unavailableStructureArea = {
...complexArea,
nativeRoad: {
...complexArea.nativeRoad,
junctionTemplates: {
...complexArea.nativeRoad.junctionTemplates,
clusters: [
...complexArea.nativeRoad.junctionTemplates.clusters,
{ id: 'not-compiled', template: 'complex-junction-v1', nodeIds: ['missing-1', 'missing-2'] },
],
},
},
};
const unavailableStructureState = browseState(unavailableStructureArea);
assert.equal(unavailableStructureState.junctionStructures['cluster:not-compiled'], undefined);
const unavailableEditState = editState(unavailableStructureArea, selectionFrom({ cluster: 'not-compiled' }));
assert.equal(unavailableEditState.junctionStructure, null);
assert.deepEqual(unavailableEditState.handles.handles, []);
const unavailablePreview = editPreview(unavailableStructureArea, {
document: emptyDocument,
selection: { cluster: 'not-compiled' },
});
assert.equal(unavailablePreview.junctionStructure, null);
assert.deepEqual(unavailablePreview.handles.handles, []);
assert.ok(browsing.standardsDiagnostics.length, 'browse state retains structure diagnostics');
assert.equal(new Set(browsing.standardsDiagnostics.map((item) => item.id)).size, browsing.standardsDiagnostics.length);
assert.ok(
Object.values(browsing.junctionStructures).every(Boolean),
'the structure index contains only available structures',
);
assert.deepEqual(browsing.junctionStructures[`cluster:${cluster.id}`], clusterState.junctionStructure);
const simpleKey = Object.keys(browsing.junctionStructures).find(
(key) => key.startsWith('node:') && !cluster.nodeIds.includes(key.slice(5)),
);
assert.ok(simpleKey, 'fixture includes a simple junction outside the cluster');
const simpleState = editState(complexArea, selectionFrom({ junction: simpleKey.slice(5) }));
assert.deepEqual(simpleState.junctionStructure, browsing.junctionStructures[simpleKey]);
assert.equal(simpleState.junctionStructure.junctionRef.type, 'node');
for (const item of clusterState.standardsDiagnostics) {
assert.ok(browsing.standardsDiagnostics.some((candidate) => candidate.id === item.id));
}
assert.ok(simpleState.handles.handles.length);
for (const type of ['cluster', 'junction']) {
const missing = editState(complexArea, selectionFrom({ [type]: 'missing-junction' }));
assert.equal(missing.junctionStructure, null);
assert.deepEqual(missing.handles.handles, []);
assert.deepEqual(missing.standardsDiagnostics, []);
assert.equal(
editPreview(complexArea, { document: emptyDocument, selection: { [type]: 'missing-junction' } }).junctionStructure,
null,
);
}
for (const tracked of complexTracked) {
assert.deepEqual(fs.readFileSync(tracked.file), tracked.bytes, 'scoped reads and previews preserve active files');
assert.equal(fs.statSync(tracked.file).mtimeMs, tracked.mtimeMs);
}
const transitionSaved = saveEdits(complexArea, {
expectedDocumentVersion: emptyDocument.documentVersion,
constraints: [transitionConstraint],
operations: [
{ id: 'operation:complex-width', createdAt: '2026-09-08T00:00:00.000Z', constraintIds: [transitionConstraint.id] },
],
});
assert.ok(transitionSaved.documentVersion > emptyDocument.documentVersion);
const transitionReloaded = editState(complexArea, selectionFrom({ cluster: cluster.id }));
const replayedTransition = editPreview(complexArea, {
document: transitionReloaded.document,
selection: { cluster: cluster.id },
});
assert.equal(replayedTransition.constraintStates[0].applied, true);
assert.deepEqual(complexSurface(replayedTransition).geometry, complexSurface(transitionPreview).geometry);
fs.rmSync(workspace, { recursive: true, force: true });
console.log('workbench edit API tests passed');