// The single chokepoint for SysMLModel mutations. // // Pure: (model, ops) → { model, idMapping, errors }. No DB / network here. // M5 in-memory: tempIds are used as canonical ids when free, otherwise // rewritten with a `_n` suffix. The DB layer (later) will replace this with // server-issued ids. // // applyOps is atomic per-batch: if any op fails validation, the entire // batch is rejected and the original model is returned unchanged. This is // the contract docs/sync.md §4 specifies. import type { SysMLModel, Block, Association, Constraint, Requirement } from "../sysml/model"; import type { ModelOp } from "./ops"; export interface ApplyResult { model: SysMLModel; /** Map of any tempId → assigned canonical id. */ idMapping: Record; errors: ApplyError[]; /** True iff the batch landed without errors. */ applied: boolean; } export interface ApplyError { opIndex: number; code: "DUPLICATE_ID" | "MISSING_ELEMENT" | "INVALID_PATCH"; message: string; } export function applyOps(model: SysMLModel, ops: ModelOp[]): ApplyResult { const idMapping: Record = {}; const errors: ApplyError[] = []; // Fail-fast working copy. We mutate this; if errors accumulate we throw it // away and return the original. let next = cloneModel(model); for (let i = 0; i < ops.length; i++) { const op = ops[i]!; try { next = applyOne(next, op, idMapping); } catch (err) { errors.push({ opIndex: i, code: classifyError(err), message: (err as Error).message }); } } if (errors.length > 0) { return { model, idMapping: {}, errors, applied: false }; } return { model: next, idMapping, errors: [], applied: true }; } // ─── Per-op application ────────────────────────────────────────────────── function applyOne(model: SysMLModel, op: ModelOp, idMapping: Record): SysMLModel { switch (op.kind) { case "add-block": { const id = resolveAddId(op.block.id, op.tempId, idMapping, model.blocks.map(b => b.id)); const block: Block = { ...op.block, id }; return { ...model, blocks: [...model.blocks, block] }; } case "update-block": { const realId = idMapping[op.blockId] ?? op.blockId; assertExists(model.blocks, realId, "block"); return { ...model, blocks: model.blocks.map(b => (b.id === realId ? { ...b, ...op.patch } : b)), }; } case "remove-block": { const realId = idMapping[op.blockId] ?? op.blockId; assertExists(model.blocks, realId, "block"); // Cascade: drop incident associations + requirement satisfiers + constraint applies-to return { ...model, blocks: model.blocks.filter(b => b.id !== realId), associations: model.associations.filter(a => a.fromBlockId !== realId && a.toBlockId !== realId), constraints: model.constraints.map(c => ({ ...c, appliesTo: c.appliesTo.filter(id => id !== realId) })), requirements: model.requirements.map(r => ({ ...r, relations: r.relations.filter(rel => rel.kind !== "satisfy" || rel.blockId !== realId), })), }; } case "add-property": { const blockId = idMapping[op.blockId] ?? op.blockId; const block = model.blocks.find(b => b.id === blockId); if (!block) throw missing("block", blockId); const propId = resolveAddId(op.property.id, op.tempId, idMapping, block.properties.map(p => p.id)); return { ...model, blocks: model.blocks.map(b => b.id === blockId ? { ...b, properties: [...b.properties, { ...op.property, id: propId }] } : b ), }; } case "update-property": { const blockId = idMapping[op.blockId] ?? op.blockId; return { ...model, blocks: model.blocks.map(b => b.id === blockId ? { ...b, properties: b.properties.map(p => (p.id === op.propertyId ? { ...p, ...op.patch } : p)) } : b ), }; } case "remove-property": { const blockId = idMapping[op.blockId] ?? op.blockId; return { ...model, blocks: model.blocks.map(b => b.id === blockId ? { ...b, properties: b.properties.filter(p => p.id !== op.propertyId) } : b ), }; } case "add-association": { const id = resolveAddId(op.association.id, op.tempId, idMapping, model.associations.map(a => a.id)); const association: Association = { ...op.association, id, fromBlockId: idMapping[op.association.fromBlockId] ?? op.association.fromBlockId, toBlockId: idMapping[op.association.toBlockId] ?? op.association.toBlockId, }; return { ...model, associations: [...model.associations, association] }; } case "update-association": { const realId = idMapping[op.associationId] ?? op.associationId; assertExists(model.associations, realId, "association"); return { ...model, associations: model.associations.map(a => (a.id === realId ? { ...a, ...op.patch } : a)), }; } case "remove-association": { const realId = idMapping[op.associationId] ?? op.associationId; assertExists(model.associations, realId, "association"); return { ...model, associations: model.associations.filter(a => a.id !== realId) }; } case "add-constraint": { const id = resolveAddId(op.constraint.id, op.tempId, idMapping, model.constraints.map(c => c.id)); const constraint: Constraint = { ...op.constraint, id, appliesTo: op.constraint.appliesTo.map(b => idMapping[b] ?? b), }; return { ...model, constraints: [...model.constraints, constraint] }; } case "update-constraint": { const realId = idMapping[op.constraintId] ?? op.constraintId; assertExists(model.constraints, realId, "constraint"); return { ...model, constraints: model.constraints.map(c => (c.id === realId ? { ...c, ...op.patch } : c)), }; } case "remove-constraint": { const realId = idMapping[op.constraintId] ?? op.constraintId; assertExists(model.constraints, realId, "constraint"); return { ...model, constraints: model.constraints.filter(c => c.id !== realId) }; } case "add-requirement": { const id = resolveAddId(op.requirement.id, op.tempId, idMapping, model.requirements.map(r => r.id)); const requirement: Requirement = { ...op.requirement, id }; return { ...model, requirements: [...model.requirements, requirement] }; } case "update-requirement": { const realId = idMapping[op.requirementId] ?? op.requirementId; assertExists(model.requirements, realId, "requirement"); return { ...model, requirements: model.requirements.map(r => (r.id === realId ? { ...r, ...op.patch } : r)), }; } case "remove-requirement": { const realId = idMapping[op.requirementId] ?? op.requirementId; assertExists(model.requirements, realId, "requirement"); return { ...model, requirements: model.requirements.filter(r => r.id !== realId) }; } case "add-relation": { const realId = idMapping[op.requirementId] ?? op.requirementId; assertExists(model.requirements, realId, "requirement"); return { ...model, requirements: model.requirements.map(r => r.id === realId ? { ...r, relations: [...r.relations, op.relation] } : r ), }; } case "remove-relation": { const realId = idMapping[op.requirementId] ?? op.requirementId; assertExists(model.requirements, realId, "requirement"); return { ...model, requirements: model.requirements.map(r => r.id === realId ? { ...r, relations: r.relations.filter((_, idx) => idx !== op.relationIndex) } : r ), }; } case "decide-element": { const realId = idMapping[op.element.id] ?? op.element.id; const flip = (arr: T[]): T[] => arr.map(e => e.id === realId ? { ...e, reviewStatus: "accepted" as const, reviewPinned: e.reviewStatus === "deprecated" ? true : !!e.reviewPinned, } : e ); switch (op.element.kind) { case "block": assertExists(model.blocks, realId, "block"); return { ...model, blocks: flip(model.blocks) }; case "association": assertExists(model.associations, realId, "association"); return { ...model, associations: flip(model.associations) }; case "constraint": assertExists(model.constraints, realId, "constraint"); return { ...model, constraints: flip(model.constraints) }; case "requirement": assertExists(model.requirements, realId, "requirement"); return { ...model, requirements: flip(model.requirements) }; } } } } // ─── Helpers ───────────────────────────────────────────────────────────── function cloneModel(model: SysMLModel): SysMLModel { // Shallow-clone collections; nested objects are immutable per our op contract. return { systemOfInterestId: model.systemOfInterestId, blocks: model.blocks.map(b => ({ ...b, properties: [...b.properties], stereotypes: [...b.stereotypes] })), associations: model.associations.map(a => ({ ...a })), constraints: model.constraints.map(c => ({ ...c, appliesTo: [...c.appliesTo] })), requirements: model.requirements.map(r => ({ ...r, relations: [...r.relations] })), }; } /** * Decide what id to use for a newly-added element. * - If the requested id is unused, it sticks. (Most common path.) * - Otherwise, append `_2`, `_3`, … until free, and record the mapping from * the requested id to the assigned id so subsequent ops in the same batch * can reference the new element by its tempId. */ function resolveAddId( desiredId: string, tempId: string | undefined, idMapping: Record, existing: string[] ): string { const taken = new Set(existing); if (!taken.has(desiredId)) { if (tempId) idMapping[tempId] = desiredId; return desiredId; } let suffix = 2; while (taken.has(`${desiredId}_${suffix}`)) suffix++; const final = `${desiredId}_${suffix}`; if (tempId) idMapping[tempId] = final; idMapping[desiredId] = final; return final; } function assertExists(items: T[], id: string, what: string): void { if (!items.find(i => i.id === id)) throw missing(what, id); } function missing(what: string, id: string): Error { return new Error(`${what} "${id}" not found`); } function classifyError(err: unknown): ApplyError["code"] { const msg = (err as Error).message ?? ""; if (msg.includes("not found")) return "MISSING_ELEMENT"; if (msg.includes("duplicate")) return "DUPLICATE_ID"; return "INVALID_PATCH"; }