UNPKG

open-agreements

Version:

Open-source legal template filling CLI and library

274 lines • 10.3 kB
import { ClosingChecklistSchema } from './schemas.js'; import { ChecklistPatchApplyRequestSchema } from './patch-schemas.js'; import { applyChecklistPatchOperations, computeChecklistPatchHash, getChecklistPatchValidationArtifact, getChecklistPatchValidationStore, } from './patch-validator.js'; class InMemoryChecklistAppliedPatchStore { map = new Map(); key(checklistId, patchId) { return `${checklistId}:${patchId}`; } async get(checklistId, patchId) { return this.map.get(this.key(checklistId, patchId)) ?? null; } async set(record) { this.map.set(this.key(record.checklist_id, record.patch_id), record); } } class InMemoryChecklistProposedPatchStore { map = new Map(); key(checklistId, patchId) { return `${checklistId}:${patchId}`; } async get(checklistId, patchId) { return this.map.get(this.key(checklistId, patchId)) ?? null; } async set(record) { this.map.set(this.key(record.checklist_id, record.patch_id), record); } } let appliedPatchStore = null; let proposedPatchStore = null; export function setChecklistAppliedPatchStore(store) { appliedPatchStore = store; } export function getChecklistAppliedPatchStore() { if (!appliedPatchStore) { appliedPatchStore = new InMemoryChecklistAppliedPatchStore(); } return appliedPatchStore; } export function setChecklistProposedPatchStore(store) { proposedPatchStore = store; } export function getChecklistProposedPatchStore() { if (!proposedPatchStore) { proposedPatchStore = new InMemoryChecklistProposedPatchStore(); } return proposedPatchStore; } function cloneValue(value) { if (typeof structuredClone === 'function') { return structuredClone(value); } return JSON.parse(JSON.stringify(value)); } function issuePath(path) { if (path.length === 0) return '<root>'; return path .map((segment) => (typeof segment === 'symbol' ? segment.toString() : String(segment))) .join('.'); } function parsedChecklistOrFailure(checklist) { const parsed = ClosingChecklistSchema.safeParse(checklist); if (parsed.success) { return { ok: true, checklist: parsed.data }; } return { ok: false, error_code: 'CHECKLIST_SCHEMA_INVALID', message: 'Checklist payload failed schema validation.', diagnostics: parsed.error.issues.map((issue) => ({ code: 'CHECKLIST_SCHEMA_INVALID', message: issue.message, path: issuePath(issue.path), })), }; } function parsedRequestOrFailure(request) { const parsed = ChecklistPatchApplyRequestSchema.safeParse(request); if (parsed.success) { return { ok: true, request: parsed.data }; } return { ok: false, error_code: 'APPLY_REQUEST_SCHEMA_INVALID', message: 'Patch apply request failed schema validation.', diagnostics: parsed.error.issues.map((issue) => ({ code: 'PATCH_SCHEMA_INVALID', message: issue.message, path: issuePath(issue.path), })), }; } export async function applyChecklistPatch(input) { const checklistParsed = parsedChecklistOrFailure(input.checklist); if (!checklistParsed.ok) return checklistParsed; const requestParsed = parsedRequestOrFailure(input.request); if (!requestParsed.ok) return requestParsed; const request = requestParsed.request; const mode = request.patch.mode; const patchHash = computeChecklistPatchHash(request.patch); const validationStore = input.validation_store ?? getChecklistPatchValidationStore(); const validationArtifact = await getChecklistPatchValidationArtifact(request.validation_id, { now_ms: input.now_ms, store: validationStore, }); if (!validationArtifact) { return { ok: false, error_code: 'VALIDATION_REQUIRED', message: 'Missing or expired validation_id. Re-run validate before apply.', diagnostics: [], }; } if (validationArtifact.checklist_id !== input.checklist_id) { return { ok: false, error_code: 'VALIDATION_MISMATCH', message: 'validation_id does not belong to this checklist.', diagnostics: [], }; } if (validationArtifact.patch_hash !== patchHash) { return { ok: false, error_code: 'VALIDATION_MISMATCH', message: 'Patch payload does not match the validated patch hash.', diagnostics: [], }; } if (validationArtifact.patch_id !== request.patch.patch_id) { return { ok: false, error_code: 'VALIDATION_MISMATCH', message: 'Patch ID does not match the validated patch.', diagnostics: [], }; } const appliedStore = input.applied_patch_store ?? getChecklistAppliedPatchStore(); const existing = await appliedStore.get(input.checklist_id, request.patch.patch_id); if (existing) { if (existing.patch_hash === patchHash) { return { ok: true, checklist: checklistParsed.checklist, previous_revision: input.current_revision, new_revision: input.current_revision, patch_id: request.patch.patch_id, patch_hash: patchHash, idempotent_replay: true, mode, applied: false, resolved_operations: validationArtifact.resolved_operations, }; } return { ok: false, error_code: 'PATCH_ID_CONFLICT', message: `patch_id "${request.patch.patch_id}" already exists with different payload hash.`, diagnostics: [], }; } if (mode === 'PROPOSED') { const proposedStore = input.proposed_patch_store ?? getChecklistProposedPatchStore(); const existingProposal = await proposedStore.get(input.checklist_id, request.patch.patch_id); if (existingProposal) { if (existingProposal.patch_hash === patchHash) { return { ok: true, checklist: checklistParsed.checklist, previous_revision: input.current_revision, new_revision: input.current_revision, patch_id: request.patch.patch_id, patch_hash: patchHash, idempotent_replay: true, mode, applied: false, resolved_operations: validationArtifact.resolved_operations, }; } return { ok: false, error_code: 'PATCH_ID_CONFLICT', message: `patch_id "${request.patch.patch_id}" already exists with different payload hash.`, diagnostics: [], }; } const proposedAt = input.now_ms ?? Date.now(); await proposedStore.set({ checklist_id: input.checklist_id, patch_id: request.patch.patch_id, patch_hash: patchHash, proposed_at_ms: proposedAt, expected_revision: request.patch.expected_revision, validation_id: request.validation_id, resolved_operations: validationArtifact.resolved_operations, }); return { ok: true, checklist: checklistParsed.checklist, previous_revision: input.current_revision, new_revision: input.current_revision, patch_id: request.patch.patch_id, patch_hash: patchHash, idempotent_replay: false, mode, applied: false, resolved_operations: validationArtifact.resolved_operations, }; } if (request.patch.expected_revision !== input.current_revision) { return { ok: false, error_code: 'REVISION_CONFLICT', message: `expected_revision ${request.patch.expected_revision} does not match current revision ${input.current_revision}.`, diagnostics: [], }; } if (validationArtifact.expected_revision !== input.current_revision) { return { ok: false, error_code: 'REVISION_CONFLICT', message: `Validated revision ${validationArtifact.expected_revision} does not match current revision ${input.current_revision}.`, diagnostics: [], }; } const updatedChecklist = cloneValue(checklistParsed.checklist); const applyResult = applyChecklistPatchOperations(updatedChecklist, request.patch.operations); if (!applyResult.ok) { return { ok: false, error_code: 'APPLY_OPERATION_FAILED', message: 'Patch operation failed during apply.', diagnostics: [applyResult.diagnostic], }; } const postPatch = ClosingChecklistSchema.safeParse(updatedChecklist); if (!postPatch.success) { return { ok: false, error_code: 'POST_PATCH_SCHEMA_INVALID', message: 'Patched checklist failed schema validation.', diagnostics: postPatch.error.issues.map((issue) => ({ code: 'POST_PATCH_SCHEMA_INVALID', message: issue.message, path: issuePath(issue.path), })), }; } const appliedAt = input.now_ms ?? Date.now(); await appliedStore.set({ checklist_id: input.checklist_id, patch_id: request.patch.patch_id, patch_hash: patchHash, applied_at_ms: appliedAt, revision_before: input.current_revision, revision_after: input.current_revision + 1, patch: request.patch, }); return { ok: true, checklist: postPatch.data, previous_revision: input.current_revision, new_revision: input.current_revision + 1, patch_id: request.patch.patch_id, patch_hash: patchHash, idempotent_replay: false, mode, applied: true, resolved_operations: applyResult.resolved_operations, }; } //# sourceMappingURL=patch-apply.js.map