viborm 1.4.1 → 1.4.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.
- package/dist/adapters.d.mts +1 -1
- package/dist/adapters.mjs +1 -1
- package/dist/bun-sql.d.mts +1 -1
- package/dist/bun-sql.mjs +1 -1
- package/dist/bun-sqlite.d.mts +1 -1
- package/dist/bun-sqlite.mjs +1 -1
- package/dist/cache/cloudflare-kv.d.mts +1 -1
- package/dist/cache/memory.d.mts +1 -1
- package/dist/cache.d.mts +1 -1
- package/dist/cli.mjs +1 -1
- package/dist/{client-3FqgR4eS.d.mts → client-D-XiaClb.d.mts} +1 -1
- package/dist/{client-DUulrWw5.mjs → client-DACEO6tS.mjs} +2 -2
- package/dist/client-DACEO6tS.mjs.map +1 -0
- package/dist/{client-sAey5P-I.mjs → client-LCeQ2fk4.mjs} +2 -2
- package/dist/{client-sAey5P-I.mjs.map → client-LCeQ2fk4.mjs.map} +1 -1
- package/dist/client.d.mts +1 -1
- package/dist/config.d.mts +1 -1
- package/dist/d1.d.mts +1 -1
- package/dist/d1.mjs +1 -1
- package/dist/d1.mjs.map +1 -1
- package/dist/driver.d.mts +1 -1
- package/dist/every-BHjQdTDc.mjs +2 -0
- package/dist/{every-CEQMQEdt.mjs.map → every-BHjQdTDc.mjs.map} +1 -1
- package/dist/{index-oVv9RLt5.d.mts → index-Ci8b13Lm.d.mts} +18 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +1 -1
- package/dist/instrumentation.d.mts +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/{libsql-DPrXWc_J.mjs → libsql-hJdKb24B.mjs} +2 -2
- package/dist/{libsql-DPrXWc_J.mjs.map → libsql-hJdKb24B.mjs.map} +1 -1
- package/dist/libsql.d.mts +1 -1
- package/dist/libsql.mjs +1 -1
- package/dist/{memory-DiTWROVS.mjs → memory-DDOrEvz9.mjs} +2 -2
- package/dist/{memory-DiTWROVS.mjs.map → memory-DDOrEvz9.mjs.map} +1 -1
- package/dist/migrations/mysql.d.mts +4 -4
- package/dist/migrations/mysql.mjs +1 -1
- package/dist/migrations/postgres.d.mts +4 -4
- package/dist/migrations/postgres.mjs +1 -1
- package/dist/migrations/sqlite.d.mts +4 -4
- package/dist/migrations/sqlite.mjs +1 -1
- package/dist/migrations/tenant.d.mts +2 -2
- package/dist/migrations/tenant.mjs +1 -1
- package/dist/migrations.d.mts +4 -4
- package/dist/migrations.mjs +1 -1
- package/dist/{mysql-fJlFIW7m.mjs → mysql-DkYmF0W9.mjs} +2 -2
- package/dist/{mysql-fJlFIW7m.mjs.map → mysql-DkYmF0W9.mjs.map} +1 -1
- package/dist/mysql2.d.mts +1 -1
- package/dist/mysql2.mjs +1 -1
- package/dist/neon-http.d.mts +1 -1
- package/dist/neon-http.mjs +1 -1
- package/dist/{object-store-C56-FLkl.d.mts → object-store-H7fJwgPR.d.mts} +3 -3
- package/dist/permissions.d.mts +1 -1
- package/dist/pg.d.mts +1 -1
- package/dist/pg.mjs +1 -1
- package/dist/pglite.d.mts +1 -1
- package/dist/pglite.mjs +1 -1
- package/dist/planetscale.d.mts +1 -1
- package/dist/planetscale.mjs +1 -1
- package/dist/{planner-C3KX6S85.d.mts → planner-CUcPdJwD.d.mts} +1 -1
- package/dist/{postgres-DD92WdFu.mjs → postgres-CmAdDKYn.mjs} +2 -2
- package/dist/{postgres-DD92WdFu.mjs.map → postgres-CmAdDKYn.mjs.map} +1 -1
- package/dist/postgres.d.mts +1 -1
- package/dist/postgres.mjs +1 -1
- package/dist/schema/json.d.mts +1 -1
- package/dist/schema.d.mts +1 -1
- package/dist/soft-delete.d.mts +1 -1
- package/dist/{sqlite-adapter-B3dRr5fl.mjs → sqlite-adapter-CLWY4B8w.mjs} +2 -2
- package/dist/sqlite-adapter-CLWY4B8w.mjs.map +1 -0
- package/dist/sqlite3.d.mts +1 -1
- package/dist/sqlite3.mjs +1 -1
- package/dist/validation.d.mts +1 -1
- package/dist/version-Cea9UfBO.mjs +2 -0
- package/dist/{version-B9azgPiR.mjs.map → version-Cea9UfBO.mjs.map} +1 -1
- package/package.json +1 -1
- package/dist/client-DUulrWw5.mjs.map +0 -1
- package/dist/every-CEQMQEdt.mjs +0 -2
- package/dist/sqlite-adapter-B3dRr5fl.mjs.map +0 -1
- package/dist/version-B9azgPiR.mjs +0 -2
|
@@ -45,5 +45,5 @@ ORDER BY control.position`,[boundNamespace(t),X.state,X.log]))}catch(e){throw th
|
|
|
45
45
|
|
|
46
46
|
`),ie=[...C.map(({review:e})=>e),renderMigrationReview(O,k,D.bytes,r.resolve?void 0:`Needs approval at generate`)].join(`
|
|
47
47
|
|
|
48
|
-
`),ae={stateId:ee.stateId,name:T,estateHash:c,snapshotHash:f.snapshotHash,sqlHash:D.sqlHash,operations:y,warnings:b,operationsByParent:x,sql:re,reviewSql:ie};if(r.dryRun)return{outcome:`preview`,...ae};o||await t.publishEstate(s);for(let{snapshot:e,sealed:n,encoded:r}of A)e.bytes&&await t.publishSnapshot(e.artifactHash,e.bytes),await t.publishSql(n.sqlHash,n.bytes),await t.publishState(r.stateId,r.bytes);return{outcome:`published`,...ae}}function sameSchema(e,t){return encodeSnapshot(orderFree(e)).snapshotHash===encodeSnapshot(orderFree(t)).snapshotHash}function orderFree(t){let n=e((e,t)=>e.name<t.name?-1:Number(e.name>t.name),`byName`);return{...t,tables:t.tables.map(e=>({...e,columns:[...e.columns].sort(n),indexes:[...e.indexes].sort(n),foreignKeys:[...e.foreignKeys].sort(n),uniqueConstraints:[...e.uniqueConstraints].sort(n)})).sort(n),enums:t.enums&&[...t.enums].sort(n)}}function sealState(e,t,n,r,i,a,o){let s=e.seal();assertArtifactExecutionSafe(s.dispatches.map(e=>sliceDispatch(s.bytes,e)),r,a);let c=t.map(e=>hashParent({...e,originChecks:rebindChecks(e.originChecks,s.dispatches),operations:rebindDispatches(e.operations,s.dispatches),rollback:rebindRollback(e.rollback,s.dispatches)})),l=rebindChecks(n,s.dispatches);return{sealed:s,hashedParents:c,destinationChecks:l,encoded:encodeStateManifest({format:`1`,estateHash:i,name:a,snapshotHash:o.snapshotHash,...o.artifactHash===o.snapshotHash?{}:{snapshotArtifactHash:o.artifactHash},sqlHash:s.sqlHash,destinationChecks:l,parents:c})}}function sealLowLockState(e,t,n,r,i,a,o){let s=new SqlAssembly,c=compileGeneratedTransition(i.operations,t,`artifact`,r.current,i.snapshot,s,a),l=o(i.snapshot,[r.from]),u=sealState(s,[sealParent(r.from,c,r.approvals)],[],t.target.dialect,e,n,l);return{...u,snapshot:l,review:renderMigrationReview(u.hashedParents,[],u.sealed.bytes),warnings:transitionWarnings(c)}}function transitionWarnings(e){return[...e.warnings??[],...e.rollback.kind===`irreversible`?[e.rollback.reason]:[]]}function assertManualParents(e,t){let n=new Set;for(let r of t){if(r.from===null){if(e.states.size>0)throw new f(`A second virtual-root transition is refused`,s.MIGRATION_INVALID_ESTATE)}else if(!e.states.has(r.from))throw new f(`Unknown parent state ${r.from}`,s.MIGRATION_NOT_FOUND);let t=r.from??`null`;if(n.has(t))throw new f(`A manual migration names a parent more than once`,s.MIGRATION_INVALID_ESTATE);n.add(t)}}function resolveParents(e,t,n){if(t.from!==void 0){if(t.from===null){let[t,...r]=e.leaves;if(t&&(r.length>0||!sameSchema(requireStateSnapshot(e,t),n)))throw new f(`A second virtual-root transition is an authored checkpoint: it must restate the schema of the estate's single leaf. Generate the change first, then the checkpoint.`,s.MIGRATION_INVALID_ESTATE);return[null]}if(!e.states.has(t.from))throw new f(`Unknown parent state ${t.from}`,s.MIGRATION_NOT_FOUND);return[t.from]}return e.states.size===0?[null]:[...e.leaves]}function emptyGraph(e,t){let n=encodeSnapshot(emptyManagedSnapshot()).snapshotHash;return{estateHash:e,descriptor:t,states:new Map,snapshots:new Map([[n,emptyManagedSnapshot()]]),snapshotArtifacts:new Map,sql:new Map,roots:[],leaves:[],emptySnapshotHash:n}}function ancestryHasCustom(e,t,n=new Set){if(t===null||n.has(t))return!1;n.add(t);let r=e.states.get(t);for(let t of r.parents)if(t.operations.some(e=>e.origin===`manual`)||t.requestedForwardBoundary!==null||ancestryHasCustom(e,t.fromState,n))return!0;return!1}function refuseUnprovedMerge(e,t,n){if(!(t.length<2||n)){for(let n of t)if(ancestryHasCustom(e,n))throw new f(`A custom or data transition cannot be merged structurally; supply manualMigration for every parent`,s.MIGRATION_INVALID_ESTATE)}}function normalizeDownOptions(e){let{steps:t,to:n,dryRun:r,expectRevision:i,resolve:a}=snapshotExactRecord(e,[`steps`,`to`,`dryRun`,`expectRevision`,`resolve`],`down options`,refuseDownOptions);if(t!==void 0&&n!==void 0)return refuseDownOptions(`down accepts either steps or to, not both`);let o=1;if(t!==void 0){if(typeof t!=`number`||!Number.isSafeInteger(t)||t<=0)return refuseDownOptions(`down steps must be a positive safe integer`);o=t}return r!==void 0&&typeof r!=`boolean`?refuseDownOptions(`down dryRun must be a boolean`):i!==void 0&&(typeof i!=`number`||!Number.isSafeInteger(i)||i<=0)?refuseDownOptions(`down expectRevision must be a positive safe integer`):a!==void 0&&!isResolveCallback(a)?refuseDownOptions(`down resolve must be a function`):Object.freeze({steps:o,...n===void 0?{}:{to:normalizeStateSelector(n)},dryRun:r===!0,...i===void 0?{}:{expectRevision:i},...a===void 0?{}:{resolve:a}})}function normalizeStateSelector(e){let t=snapshotExactRecord(e,[`id`,`prefix`,`name`],`down to`,refuseDownOptions),n=Object.keys(t);if(n.length!==1)return refuseDownOptions(`down to must contain exactly one selector key`);let r=n[0],i=t[r];return typeof i!=`string`||i.length===0?refuseDownOptions(`down to.${r} must be a non-empty string`):r===`id`?{id:i}:r===`prefix`?{prefix:i}:{name:i}}function isResolveCallback(e){return typeof e==`function`}function refuseDownOptions(e,t){throw new f(e,s.INVALID_INPUT,{cause:t})}async function resetV1(e,t,n={}){let r=await loadMigrationGraph(t),i=resolveStateSelector(r,n.to),a=selectRoute(r,null,i,n.via),o=n.dryRun===!0,c=openCommand(e,r,o?`read-only`:`effectful`,`reset()`);if(o){let t=await resolveCommandDriver(e.$driver,c),n=await planLiveNamespaceReset(e.$driver,t);return await t.preflightSchemaRequirements(a.map(e=>requireStateSnapshot(r,e)),(t,n)=>e.$driver._executeRaw(t,n),resetProgram(n,prepareResetReplay(e.$driver.supportsTransactions,t,r,a))),{preview:!0,path:a,tables:n.dropTables.map(e=>e.name)}}return withLockedMigrationProducer(e.$driver,c,async(t,n)=>{let o=await readCommandControl(t,n,!0),{marker:c,ledger:l}=o,u=o.presence.kind!==`present`,d=unfinishedAttempts(l),p=d.length===1&&d[0].kind===`reset-started`?d[0]:void 0;if(d.length>0&&!p)throw new f(`An unfinished migration attempt is blocking reset`,s.MIGRATION_UNFINISHED_ATTEMPT);let m=`${n.target.dialect}:${n.namespace??``}`,h=p?matchingResetPlan(p,r,i,a,m):void 0;p||refuseIncompatibleHistory(c,l);let g=requireStateSnapshot(r,i),_=r.states.get(i).snapshotHash,v=routeEdges(r,null,a).map(({to:e,transition:t})=>({stateId:e,transitionHash:t.transitionHash,baselineBoundary:!1})),y={estateHash:r.estateHash,snapshotHash:_,sqlHash:null,fromState:c?.stateId??null,toState:i,transitionHash:null,direction:`reset`};if(p&&h&&c&&resetMarkerProvesApplied(c,r,v,_,h)&&await fingerprintLive(await introspectManaged(t,n),n,t)===await fingerprintLive(g,n,t))return await appendLedger(t,n,attemptEvents({...y,fromState:p.fromState},p.attemptId).event(`reset-applied`,`committed`)),{preview:!1,path:a};if(p&&h&&!resetSourceMarkerMatches(c,p,h,r.emptySnapshotHash))throw new f(`The unfinished reset source marker no longer matches its plan`,s.MIGRATION_MARKER_CONFLICT);let b=p&&l.some(e=>e.attemptId===p.attemptId&&e.kind===`reset-step-confirmed`&&(e.fromState!==null||e.toState!==null||e.transitionHash!==null||e.operationId!==null))?void 0:await planLiveNamespaceReset(t,n),x=resetProgram(b,[]).map(e=>dispatchForClearSql(e));if(b&&n.target.dialect===`mysql`&&(b.dropForeignKeys.length>0||b.dropEnums.length>0))throw new f(`Stepwise reset refuses clear dispatches without driver-owned pre/post proof`,s.MIGRATION_UNSUPPORTED_PROVIDER);let S={estateHash:r.estateHash,targetIdentity:m,sourceRevision:c?.revision??0,sourceFingerprint:c?.snapshotHash??r.emptySnapshotHash,replayPath:a,clearDispatches:x,referencedStates:a},C=h;C&&b&&assertStoredResetPlan(C,S);let w=C?C.resetPlanHash:L(R.resetPlan,I(S)),T=C??{...S,resetPlanHash:w},E=prepareResetReplay(t.supportsTransactions,n,r,a),D=p?remainingResetReplay(r,E,p,T,l):E;await n.preflightSchemaRequirements([requireStateSnapshot(r,c?.stateId??null),...a.map(e=>requireStateSnapshot(r,e))],(e,n)=>t._executeRaw(e,n),resetProgram(b,D));let O=p?void 0:e=>appendLedger(e,n,attemptEvents({...y,resetPlan:T},w).event(`reset-started`,`none`)),finish=async e=>{await proveLive(e,n,r,_,()=>`Reset replay did not reach the target snapshot`),await advanceMarker(e,n,r.estateHash,c,v,_),await appendLedger(e,n,attemptEvents(y,w).event(`reset-applied`,`committed`))};return u&&(await ensureControlTables(t,n),await commitLockedTransaction(t,n)),await runProgram(t,n,void 0,i=>executeResetProgram(t,i,n,c,r,b,T,D,w,O,finish,e.$schema)),{preview:!1,path:a}})}function matchingResetPlan(e,t,n,r,i){let a=t.states.get(n),o=e.resetPlan,c=e.fromState===null?t.emptySnapshotHash:t.states.get(e.fromState)?.snapshotHash;if(!(a&&o)||e.direction!==`reset`||e.attemptId!==o.resetPlanHash||e.estateHash!==t.estateHash||e.snapshotHash!==a.snapshotHash||e.toState!==n||o.estateHash!==t.estateHash||o.targetIdentity!==i||o.sourceFingerprint!==c||!sameIds(o.replayPath,r)||!sameIds(o.referencedStates,r))throw new f(`The unfinished reset does not match the requested reset`,s.MIGRATION_INVALID_STATE);return o}function resetMarkerProvesApplied(e,t,n,r,i){let a=markerFromPath(t.estateHash,r,n,i.sourceRevision+1);return e.estateHash===a.estateHash&&e.stateId===a.stateId&&e.snapshotHash===a.snapshotHash&&sameMarker(e,a)}function resetSourceMarkerMatches(e,t,n,r){return e?e.stateId===t.fromState&&e.revision===n.sourceRevision&&e.snapshotHash===n.sourceFingerprint:t.fromState===null&&n.sourceRevision===0&&n.sourceFingerprint===r}function assertStoredResetPlan(e,t){if(e.estateHash!==t.estateHash)throw new f(`A stored reset plan does not match the current estate`,s.MIGRATION_INVALID_STATE);if(e.targetIdentity!==t.targetIdentity)throw new f(`A stored reset plan does not match the current target`,s.MIGRATION_INVALID_STATE);if(e.sourceRevision!==t.sourceRevision||e.sourceFingerprint!==t.sourceFingerprint)throw new f(`A stored reset plan does not match the current marker`,s.MIGRATION_INVALID_STATE);if(!sameIds(e.replayPath,t.replayPath))throw new f(`A stored reset plan does not match the requested replay path`,s.MIGRATION_INVALID_STATE);let n=new Set(e.clearDispatches.map(e=>e.dispatchId));for(let e of t.clearDispatches)if(!n.has(e.dispatchId))throw new f(`Live remaining reset clears are not in the stored reset plan`,s.MIGRATION_INVALID_STATE)}function sameIds(e,t){return e.length===t.length?e.every((e,n)=>e===t[n]):!1}function resetProgram(e,t){return[...e?.clear??[],...t.flatMap(({blob:e,operations:t})=>stepStatements(e,t))]}function dispatchForClearSql(e){let t=encodeSqlText(e),n=encodeSqlBlob(t);return{dispatchId:encodeDispatchIdentity(n,0,t.length,[]),sqlHash:n,offset:0,length:t.length,parameters:[]}}async function executeResetClear(e,t,n,r,i){for(let a of n.dropForeignKeys)await executeExactSql(e,a),await confirmResetStep(e,t,i,r,a);for(let a of n.dropTables){let n=tableExistsProbe(t,a.name,!0),o=tableExistsProbe(t,a.name,!1);if(!await evaluateProbe(e,n)){await confirmResetStep(e,t,i,r,a.sql);continue}if(await executeExactSql(e,a.sql),!await evaluateProbe(e,o))throw new f(`Reset clear did not drop table ${a.name}`,s.MIGRATION_PARTIAL_EFFECT);await confirmResetStep(e,t,i,r,a.sql)}for(let a of n.dropEnums)await executeExactSql(e,a),await confirmResetStep(e,t,i,r,a)}async function evaluateProbe(e,t){let n=await e._executeRaw(t.sql,t.parameters.map(e=>e.kind===`string`?e.value:null)),r=Object.values(n.rows[0]??{})[0];return(r===!0||r===1||r===`1`||r===`t`)===t.equals}async function confirmResetStep(e,t,n,r,i){await confirmResetDispatch(e,t,n,r,dispatchForClearSql(i))}async function confirmResetDispatch(e,t,n,r,i){await appendLedger(e,t,ledgerEvent({attemptId:r,kind:`reset-step-confirmed`,estateHash:n.estateHash,snapshotHash:n.emptySnapshotHash,sqlHash:i.sqlHash,fromState:null,toState:null,transitionHash:null,direction:`reset`,operationId:null,dispatchId:i.dispatchId,effectState:`committed`}))}function prepareResetReplay(e,t,n,r){return routeEdges(n,null,r).map(n=>{let r=n.transition.requestedForwardBoundary,i=classifyStoredAtomicity(t,r,n.transition.operations,n.blob);return assertTransactionalBoundaryHonored(e,r),refuseSqliteStepwise(t,r,n.to),{...n,boundary:i,operations:n.transition.operations}})}function remainingResetReplay(e,t,n,r,i){let a=new Map(r.clearDispatches.map((e,t)=>[e.dispatchId,t])),o=new Set,c=t.flatMap((e,t)=>e.operations.flatMap(n=>n.steps.map(r=>({edge:e,edgeIndex:t,operation:n,step:r})))),l=new Map(c.map((e,t)=>[e.step.execute.dispatchId,t])),u=new Set,d=new Set,p=!1;for(let t of i){if(t.attemptId!==n.attemptId||t.kind!==`reset-step-confirmed`)continue;if((t.direction!==`reset`||t.estateHash!==e.estateHash||!t.dispatchId)&&refuseResetProgress(`Reset progress does not match its authenticated plan`),t.fromState===null&&t.toState===null&&t.transitionHash===null&&t.operationId===null){let n=a.get(t.dispatchId);(n===void 0||t.sqlHash!==r.clearDispatches[n].sqlHash||t.snapshotHash!==e.emptySnapshotHash||t.effectState!==`committed`)&&refuseResetProgress(`Reset clear progress names an unknown dispatch`),o.add(n);continue}p=!0;let i=l.get(t.dispatchId);i===void 0&&refuseResetProgress(`Reset replay progress names an unknown dispatch`);let m=c[i];if((!m||t.fromState!==m.edge.from||t.toState!==m.edge.to||t.transitionHash!==m.edge.transition.transitionHash||t.snapshotHash!==m.edge.state.snapshotHash||t.sqlHash!==m.edge.state.sqlHash||t.operationId!==m.operation.id)&&refuseResetProgress(`Reset replay progress names an unknown dispatch`),t.effectState===`committed`)u.add(i);else if(t.effectState===`none`)m.step.retry===`proven`?u.add(i):d.add(i);else throw new f(`Reset replay progress has an ambiguous commit outcome`,s.MIGRATION_AMBIGUOUS_COMMIT)}if(confirmedPrefix(o,`Reset clear progress is not a contiguous dispatch prefix`),p&&o.size!==r.clearDispatches.length&&refuseResetProgress(`Reset replay progress exists before the clear prefix is complete`),!p)return t;let m=confirmedPrefix(u,`Reset replay progress is not a contiguous dispatch prefix`);[...d].some(e=>!u.has(e)&&e!==m)&&refuseResetProgress(`Reset replay progress is not contiguous`);let h=c[m];refuseAmbiguousNext(h?.step,h?.edge.boundary,d.has(m),`The next reset dispatch has an ambiguous commit outcome`);let g=m===0?void 0:c[m-1]?.edgeIndex,_=m;return t.flatMap((e,t)=>{let n=e.operations.reduce((e,t)=>e+t.steps.length,0);if(_>=n)return _-=n,t===g?[{...e,operations:[]}]:[];let r=sliceOperations(e.operations,_);return _=0,[{...e,operations:r}]})}function refuseResetProgress(e){throw new f(e,s.MIGRATION_CORRUPTION)}async function executeResetProgram(e,t,n,r,i,a,o,s,c,l,u,d){let f=groupContiguousAtomicity(s,e=>resetProgram(void 0,[e])),p=resetProgram(a,[]),m=new Set(p.map(e=>dispatchForClearSql(e).dispatchId)),h=p.length>0?a:void 0,g=a!==void 0,_=l,runBoundary=async(i,a,o)=>{let guarded=async t=>{await assertLockedSinceDecision(e,t,n,r,_===void 0),await o(t)};await(n.target.dialect===`mysql`?guarded(t):runProgram(e,n,{transactional:i===`transactional`,statements:a},guarded))},completeClearEvidence=async e=>{for(let t of o.clearDispatches)m.has(t.dispatchId)||await confirmResetDispatch(e,n,i,c,t)},admit=async e=>{let t=_;t&&(_=void 0,await t(e))};if(h&&f[0]?.boundary===`stepwise`){let e=h;h=void 0,await runBoundary(`transactional`,resetProgram(e,[]),async t=>{await admit(t),await executeResetClear(t,n,e,c,i),await completeClearEvidence(t),g=!1})}if(!h&&f[0]?.boundary===`stepwise`&&_&&await runBoundary(`transactional`,[],admit),f.length===0){await runBoundary(`transactional`,resetProgram(h,[]),async e=>{await admit(e),h&&await executeResetClear(e,n,h,c,i),g&&=(await completeClearEvidence(e),!1),await u(e)});return}for(let[e,t]of f.entries()){let r=resetProgram(h,t.items);await runBoundary(t.boundary,r,async r=>{await admit(r),h&&=(await executeResetClear(r,n,h,c,i),void 0),g&&=(await completeClearEvidence(r),!1);for(let e of t.items)await executeResetReplayEdge(r,n,i,e,c,d);e===f.length-1&&await u(r)})}}async function executeResetReplayEdge(e,t,n,r,i,a){let{from:o,to:s,transition:c,state:l,blob:u,boundary:d,operations:f}=r,p=attemptEvents({estateHash:n.estateHash,snapshotHash:l.snapshotHash,sqlHash:l.sqlHash,fromState:o,toState:s,transitionHash:c.transitionHash,direction:`reset`},i);await executeOperations(e,u,f,d,(n,r,i)=>appendLedger(e,t,p.event(`reset-step-confirmed`,r,n,i)),t.namespace),await canonicalizeSqliteStorage(e,f,a,requireStateSnapshot(n,s)),await assertAllChecks(e,u,l.destinationChecks,t.namespace,`Reset replay failed destination checks`)}async function statusV1(e,t){let n=await loadMigrationGraph(t),r=openCommand(e,n,`read-only`,`status()`),i=await resolveCommandDriver(e.$driver,r),a=await readCommandControl(e.$driver,i),o=await readInvalidIndexes(e.$driver,i),s=o.length===0?{}:{invalidIndexes:o};if(a.presence.kind!==`present`)return{control:`absent`,marker:null,pending:[...n.roots],unfinished:!1,...s};let{marker:c,ledger:l}=a,u=unfinishedAttempts(l).length>0,d;for(let e of l)e.kind===`failed`&&(d=e);let f=markerStanding(n,c),p=[];if(f===`known`&&n.leaves.length===1){let e=n.leaves[0];(c?.stateId??null)!==e&&(p=[...selectRoute(n,c?.stateId??null,e)])}return{control:`present`,marker:c,pending:p,unfinished:u,...f===`known`?{}:{markerState:f},...s,...d?{lastFailure:d}:{}}}async function verifyV1(e,t){let n=await loadMigrationGraph(t),r=openCommand(e,n,`effectful`,`verify()`);return withLockedMigrationProducer(e.$driver,r,async(e,t)=>{let r=await readCommandControl(e,t);if(r.presence.kind!==`present`)throw new f(`verify requires present control tables`,s.MIGRATION_NOT_FOUND);let{marker:i}=r;if(!i)throw new f(`verify requires a migration marker`,s.MIGRATION_NOT_FOUND);let a=markerStanding(n,i);if(a!==`known`)return{ok:!1,markerState:a};let o=requireStateSnapshot(n,i.stateId);return await t.preflightSchemaRequirements([o],(t,n)=>e._executeRaw(t,n),[]),await assertNoDrift(e,t,n,i),{ok:!0}})}async function logV1(e){let t=getPushMigrationDriver(e);admitLiveMigrationCapability(t,`read-only`,`log()`);let n=await resolveCommandDriver(e.$driver,t),r=await readControlState(e.$driver,n);if(r.presence.kind!==`present`)throw refusePartialControl(r.presence),new f(`log requires present control tables`,s.MIGRATION_NOT_FOUND);return r.ledger}async function baselineV1(e,t,n){let r=await loadMigrationGraph(t),i=openCommand(e,r,`effectful`,`baseline()`),a=resolveStateSelector(r,n.to),o=selectRoute(r,null,a,n.via);return withLockedMigrationProducer(e.$driver,i,async(e,t)=>{let n=await readCommandControl(e,t,!0),{marker:i,ledger:c}=n;if(i||unfinishedAttempts(c).length>0)throw new f(`baseline requires an unmarked database without an unfinished attempt`,s.MIGRATION_INVALID_STATE);return refuseIncompatibleHistory(i,c),assertStructuralRoute(r,o,`baseline`),await t.preflightSchemaRequirements([requireStateSnapshot(r,a)],(t,n)=>e._executeRaw(t,n),[]),n.presence.kind!==`present`&&(await ensureControlTables(e,t),await commitLockedTransaction(e,t),await assertLockedSinceDecision(e,e,t,null)),await proveLive(e,t,r,r.states.get(a).snapshotHash,async e=>`baseline requires exact live equality with the target snapshot. Differences: ${await e()}`),await adoptRoute(e,t,r,o,null),{stateId:a}})}async function reanchorV1(e,t,n={}){let r=await loadMigrationGraph(t),i=openCommand(e,r,`effectful`,`reanchor()`),a=n.to&&resolveStateSelector(r,n.to);return withLockedMigrationProducer(e.$driver,i,async(e,t)=>{let{marker:i,ledger:o}=await readCommandControl(e,t);if(!i||markerStanding(r,i)===`known`)throw new f(`reanchor moves only a marker naming a state this history does not hold; apply, verify and baseline handle the others`,s.MIGRATION_INVALID_STATE);if(unfinishedAttempts(o).length>0)throw new f(`reanchor refuses while an attempt is unfinished: resolve it first`,s.MIGRATION_INVALID_STATE);let c=await introspectManaged(e,t),l=await fingerprintLive(c,t,e),u=[];for(let n of a?[a]:r.states.keys())await fingerprintLive(requireStateSnapshot(r,n),t,e)===l&&u.push(n);let d=a??(r.leaves.length===1?r.leaves[0]:void 0);if(u.length===0)throw new f(`reanchor found no state of this history that the live schema matches.${d?` Differences from ${d}: ${JSON.stringify(await diff(c,requireStateSnapshot(r,d)))}`:``}`,s.MIGRATION_DRIFT);if(u.length>1)throw new f(`Several states of this history match the live schema (${u.join(`, `)}), and equal schemas never say which data the database holds: name one with reanchor({ to }).`,s.MIGRATION_INVALID_STATE);let p=u[0];if(i.path.some(e=>e.stateId===p))throw new f(`reanchor refuses ${p}: the marker passed through it, so the transitions lost after it changed no schema and may have moved data. Regenerate the lost states from the same documents instead: their ids come back identical.`,s.MIGRATION_INVALID_STATE);let m=selectRoute(r,null,p,n.via);return assertStructuralRoute(r,m,`reanchor`),await t.preflightSchemaRequirements([requireStateSnapshot(r,p)],(t,n)=>e._executeRaw(t,n),[]),await adoptRoute(e,t,r,m,i),{stateId:p}})}function assertStructuralRoute(e,t,n){for(let{from:r,transition:i,state:a}of routeEdges(e,null,t)){let t=r===null?e.emptySnapshotHash:e.states.get(r)?.snapshotHash;if(i.operations.some(e=>e.origin===`manual`||e.risk===`opaque`)||t===a.snapshotHash)throw new f(`${n} refuses a path containing manual, opaque, or data-only transitions`,s.MIGRATION_INVALID_STATE)}}async function adoptRoute(e,t,n,r,i){let a=routeEdges(n,null,r).map(({to:e,transition:t},n)=>({stateId:e,transitionHash:t.transitionHash,baselineBoundary:n===0})),o=r.at(-1),publish=async e=>{let r=await advanceMarker(e,t,n.estateHash,i,a,n.states.get(o).snapshotHash);await appendLedger(e,t,ledgerEvent({attemptId:r.pathHash,kind:i?`reanchored`:`baselined`,estateHash:n.estateHash,snapshotHash:r.snapshotHash,sqlHash:null,fromState:i?.stateId??null,toState:o,transitionHash:null,direction:`baseline`,operationId:null,dispatchId:null,effectState:`none`}))};e.supportsTransactions?await e.withTransaction(e=>publish(e)):await publish(e)}async function pruneV1(e,t){let n=await loadMigrationGraph(e),r=statesFrom(n,resolveStateSelector(n,t.checkpoint)),{into:i}=t;await i.publishEstate(await present(e.readEstate(),`estate.json`,I(n.descriptor)));let a=new Set;for(let t of r){let{snapshotHash:r,snapshotArtifactHash:o,sqlHash:c}=n.states.get(t),l=[],u=o??r;for(;u!==void 0&&!a.has(u);)l.push(u),u=n.snapshotArtifacts.get(u)?.baseArtifactHash;for(let t of l.reverse()){let r=n.snapshotArtifacts.get(t),o=r?.bytes??encodeSnapshot(requireStateSnapshot(n,null)).bytes;if(!ye(!r&&t===n.emptySnapshotHash?await e.readSnapshot(t)??o:await present(e.readSnapshot(t),t),o))throw new f(`Snapshot ${t} changed while prune copied it`,s.MIGRATION_CORRUPTION);await i.publishSnapshot(t,o.slice()),a.add(t)}await i.publishSql(c,n.sql.get(c)),await i.publishState(t,await present(e.readState(t),t,I(n.states.get(t))))}return{states:[...r]}}async function present(e,t,n){let r=await e;if(!r)throw new f(`${t} vanished from the history while prune copied it`,s.MIGRATION_CORRUPTION);if(n&&!ye(r,n))throw new f(`${t} changed while prune copied it`,s.MIGRATION_CORRUPTION);return n??r}async function downV1(e,t,n={}){let r=normalizeDownOptions(n),i=await loadMigrationGraph(t),a=openCommand(e,i,r.dryRun?`read-only`:`effectful`,`down()`);if(r.dryRun){let t=e.$driver,n=await resolveCommandDriver(t,a),{close:o,removed:s,refusal:c}=await planRollback(t,n,i,await readCommandControl(t,n),r,!0);return{path:o?[o.item.edge.stateId]:s.map(e=>e.stateId),preview:!0,edges:[...s].reverse().map(e=>previewRollbackEdge(i,e)),refusal:c}}return withLockedMigrationProducer(e.$driver,a,async(t,n)=>{let a=await readCommandControl(t,n),{close:o,removed:s,run:c}=await planRollback(t,n,i,a,r,!1);if(o)return await n.preflightSchemaRequirements([requireStateSnapshot(i,o.item.nextState)],(e,n)=>t._executeRaw(e,n),[]),await runProgram(t,n,void 0,e=>closeCompletedRollback(e,n,i,o.item,o.attempt,a.ledger,a.marker)),{path:[o.item.edge.stateId],preview:!1};if(!c)return{path:[],preview:!1};let{prepared:l,attempt:u}=c,statementsOf=e=>stepStatements(e.blob,e.rollback.operations),d=c.marker;for(let r of groupContiguousAtomicity(l,statementsOf))await runProgram(t,n,{transactional:r.boundary===`transactional`,statements:r.items.flatMap(statementsOf)},async o=>{await assertLockedSinceDecision(t,o,n,d,r.items[0]===l[0]&&u!==void 0);for(let t of r.items)d=await executeRollbackEdge(o,n,i,t,d,t===l[0]?u:void 0,a.ledger,e.$schema)});return{path:s.map(e=>e.stateId),preview:!1}})}async function planRollback(e,t,n,{marker:r,ledger:i},a,o){assertExpectedRevision(r,a);let c=null,l;try{l=admitRollbackAttempt(i)}catch(e){if(!o)throw e;c=refusalOf(e)}let{supportsTransactions:u}=e;if(l&&l.toState===(r?.stateId??null)){let e=prepareRollbackAttempt(n,t,u,l);return{refusal:c,close:{item:e,attempt:l},removed:[]}}if(!r){if(c)return{refusal:c,removed:[]};throw new f(`Nothing to roll back`,s.MIGRATION_NOT_FOUND)}let d=rollbackSlice(n,r,a);if(c||d.length===0)return{refusal:c,removed:d};try{let i=[...d].reverse();for(let e of i)assertReversibleEdge(n,e);let o=i.map(e=>prepareRollbackEdge(n,t,u,e));return await t.preflightSchemaRequirements([requireStateSnapshot(n,r.stateId),...o.map(e=>requireStateSnapshot(n,e.nextState))],(t,n)=>e._executeRaw(t,n),o.flatMap(e=>stepStatements(e.blob,e.rollback.operations))),l?assertResumesSelectedPath(n,t,u,l,o[0]):await assertNoDrift(e,t,n,r),await approveRollbackLosses(e,t,n,o,a.resolve),{refusal:c,removed:d,run:{marker:r,prepared:o,attempt:l}}}catch(e){if(!o)throw e;return{refusal:refusalOf(e),removed:d}}}async function resolveV1(e,t,n){let r=await loadMigrationGraph(t),i=openCommand(e,r,`effectful`,`resolve()`);return withLockedMigrationProducer(e.$driver,i,async(t,i)=>{let{ledger:a}=await readCommandControl(t,i),o=unfinishedAttempts(a);if(o.length!==1)throw new f(o.length===0?`resolve requires an unfinished attempt`:`resolve requires exactly one unfinished attempt`,s.MIGRATION_INVALID_STATE);let c=o[0];if(c.kind===`reset-started`)throw new f(`An unfinished reset can only be resumed by reset()`,s.MIGRATION_INVALID_STATE);if(c.direction===`rollback`)throw new f(`An unfinished rollback can only be resumed by down()`,s.MIGRATION_INVALID_STATE);let l=c.toState,u=c.fromState;if(!l)throw new f(`Unfinished attempt is missing its target state`,s.MIGRATION_CORRUPTION);let d=r.states.get(l);if(!d)throw new f(`Unfinished attempt target is absent from the estate`,s.MIGRATION_CORRUPTION);let p=r.sql.get(d.sqlHash),m=parentTransition(r,u,l),h=requireStateSnapshot(r,l),g=requireStateSnapshot(r,u),_=stepStatements(p,m.operations);await i.preflightSchemaRequirements([g,h],(e,n)=>t._executeRaw(e,n),n.outcome===`retry`?_:[]),n.outcome!==`retry`&&await repairInvalidIndexes(t,i,_,n.outcome===`complete`?h:g);let v=await fingerprintLive(await introspectManaged(t,i),i,t),y=v===await fingerprintLive(h,i,t)&&await evaluateAllChecks(t,p,d.destinationChecks,i.namespace),b=v===await fingerprintLive(g,i,t)&&await evaluateAllChecks(t,p,m.originChecks,i.namespace),x=m.operations.some(e=>e.origin===`manual`&&e.steps.some(e=>e.retry===`opaque`)),S={transactional:!0,statements:[]};if(n.outcome===`complete`){if(!y||x&&d.destinationChecks.length===0)throw new f(`resolve cannot mark complete without destination proof`,s.MIGRATION_INVALID_STATE);return await runProgram(t,i,S,async t=>{await canonicalizeSqliteStorage(t,m.operations,e.$schema,h),await finishResolve(t,i,r,c,`applied`,l)}),{outcome:`complete`}}if(n.outcome===`rolled-back`){if(refuseOpaqueEffect(m,p,c,a),!b||x&&m.originChecks.length===0)throw new f(`resolve cannot mark rolled back without origin proof`,s.MIGRATION_INVALID_STATE);return await runProgram(t,i,S,e=>finishResolve(e,i,r,c,`rolled-back`,u)),{outcome:`rolled-back`}}if(x)throw new f(`resolve cannot retry an opaque dispatch without origin or destination proof`,s.MIGRATION_INVALID_STATE);if(m.operations.some(e=>e.steps.some(e=>e.retry===`opaque`))&&!b)throw new f(`resolve cannot retry a generated structural transition except from the origin`,s.MIGRATION_INVALID_STATE);assertTransactionalBoundaryHonored(t.supportsTransactions,m.requestedForwardBoundary);let C=classifyStoredAtomicity(i,m.requestedForwardBoundary,m.operations,p);return await runProgram(t,i,{transactional:C===`transactional`,statements:_},async e=>{await executeOperations(e,p,m.operations,C,void 0,i.namespace,{fromState:u,toState:l}),await assertAllChecks(e,p,d.destinationChecks,i.namespace,`Retry did not reach the destination`),await proveLive(e,i,r,d.snapshotHash,()=>`Retry did not reach the destination`),await finishResolve(e,i,r,c,`applied`,l)}),{outcome:`retry`}})}const Hr=/\bINDEX\s+CONCURRENTLY\s+(?:IF\s+(?:NOT\s+)?EXISTS\s+)?(?!ON\b)(?:(?:"(?:[^"]|"")+"|[A-Za-z_][\w$]*)\s*\.\s*)?("(?:[^"]|"")+"|[A-Za-z_][\w$]*)/gi,Ur=/^_cc(?:new|old)\d*$/;async function repairInvalidIndexes(e,t,n,r){let i=n.flatMap(concurrentIndexNames);if(i.length!==0)for(let{table:n,index:a}of await readInvalidIndexes(e,t)){if(!i.some(e=>a===e||a.startsWith(e)&&Ur.test(a.slice(e.length))))continue;let o=r.tables.some(e=>e.name===n&&e.indexes.some(e=>e.name===a));await e._executeRaw(`${o?`REINDEX INDEX`:`DROP INDEX`} CONCURRENTLY ${qualifiedName(t,a)}`)}}function concurrentIndexNames(e){return[...e.matchAll(Hr)].map(([,e=``])=>e.startsWith(`"`)?e.slice(1,-1).replaceAll(`""`,`"`):e.toLowerCase())}async function finishResolve(e,t,n,r,i,a){let{marker:o}=await readCommandControl(e,t);if(i===`applied`&&a&&o?.stateId!==a){let i=parentTransition(n,r.fromState,a);await advanceMarker(e,t,n.estateHash,o,[...o?.path??[],{stateId:a,transitionHash:r.transitionHash??i.transitionHash,baselineBoundary:!1}],n.states.get(a).snapshotHash)}if(i===`rolled-back`&&o&&o.stateId===r.toState){let r=o.path.slice(0,-1);await advanceMarker(e,t,n.estateHash,o,r,snapshotHashOf(n,r.at(-1)?.stateId??null))}await appendLedger(e,t,ledgerEvent({attemptId:r.attemptId,kind:`resolved`,estateHash:n.estateHash,snapshotHash:snapshotHashOf(n,a),sqlHash:r.sqlHash,fromState:r.fromState,toState:a,transitionHash:r.transitionHash,direction:`resolve`,operationId:null,dispatchId:null,effectState:`none`}))}function snapshotHashOf(e,t){return t?e.states.get(t).snapshotHash:e.emptySnapshotHash}function prepareRollbackEdge(e,t,n,r){let i=e.states.get(r.stateId),a=i.parents.find(e=>e.transitionHash===r.transitionHash),o=e.sql.get(i.sqlHash),c=a.rollback;if(c.kind===`irreversible`)throw new f(c.reason,s.MIGRATION_DESTRUCTIVE_REJECTED);let l=c.kind===`manual`?c.requestedBoundary:null;return assertTransactionalBoundaryHonored(n,l),refuseSqliteStepwise(t,l,r.stateId),{edge:r,state:i,parent:a,blob:o,rollback:c,boundary:classifyStoredAtomicity(t,l,c.operations,o),nextState:a.fromState}}function previewRollbackEdge(e,t){let n=e.states.get(t.stateId),r=n?.parents.find(e=>e.transitionHash===t.transitionHash),i=n&&e.sql.get(n.sqlHash);if(!(r&&i))throw new f(`Rollback cannot find the arrival transition or its SQL`,s.MIGRATION_CORRUPTION);let{approvals:a,...o}=r;return{stateId:t.stateId,toState:r.fromState,sql:renderMigrationReview([{...o,originChecks:[],operations:[]}],[],i)}}function refusalOf(e){if(!(e instanceof f))throw e;return{code:e.code,message:e.message}}function admitRollbackAttempt(e){let t=unfinishedAttempts(e);if(t.length>1)throw new f(`Multiple unfinished migration attempts require manual repair`,s.MIGRATION_UNFINISHED_ATTEMPT);let n=t[0];if(n&&(n.kind!==`started`||n.direction!==`rollback`))throw new f(`An unfinished migration attempt is blocking ordinary work`,s.MIGRATION_UNFINISHED_ATTEMPT);return n}function assertResumesSelectedPath(e,t,n,r,i){let a=prepareRollbackAttempt(e,t,n,r);if(a.edge.stateId!==i.edge.stateId||a.nextState!==i.nextState||a.edge.transitionHash!==i.edge.transitionHash)throw new f(`An unfinished rollback does not match the selected reverse path`,s.MIGRATION_UNFINISHED_ATTEMPT)}function prepareRollbackAttempt(e,t,n,r){if(!(r.fromState&&r.transitionHash))throw new f(`Unfinished rollback is missing its authenticated edge identity`,s.MIGRATION_CORRUPTION);let i=prepareRollbackEdge(e,t,n,{stateId:r.fromState,transitionHash:r.transitionHash,baselineBoundary:!1});if(r.toState!==i.nextState||r.estateHash!==e.estateHash||r.snapshotHash!==i.state.snapshotHash||r.sqlHash!==i.state.sqlHash)throw new f(`Unfinished rollback does not match an authenticated estate edge`,s.MIGRATION_CORRUPTION);return i}async function executeRollbackEdge(e,t,n,r,i,a,o,c){let{edge:l,state:u,blob:d,rollback:p,boundary:m,nextState:h}=r;if(i.stateId!==l.stateId||i.path.at(-1)?.stateId!==l.stateId||i.path.at(-1)?.transitionHash!==l.transitionHash)throw new f(`Rollback marker does not name the authenticated edge being reversed`,s.MIGRATION_MARKER_CONFLICT);a||await assertAllChecks(e,d,u.destinationChecks,t.namespace,`Destination checks failed before rollback`);let g=attemptEvents(rollbackEventSeed(n,r),a?.attemptId);a||await appendLedger(e,t,g.event(`started`,`none`)),await executeOperations(e,d,a?remainingRollbackOperations(n,r,a,o):p.operations,m,(n,r,i)=>appendLedger(e,t,g.event(`step-confirmed`,r,n,i)),t.namespace,{fromState:l.stateId,toState:h}),await canonicalizeSqliteStorage(e,p.operations,c,requireStateSnapshot(n,h));let _=await proveRolledBack(e,t,n,r),v=await advanceMarker(e,t,n.estateHash,i,i.path.slice(0,-1),_);return await appendRolledBackEvent(e,t,n,r,g.attemptId),v}async function closeCompletedRollback(e,t,n,r,i,a,o){if(remainingRollbackOperations(n,r,i,a),o?o.stateId!==r.nextState:r.nextState!==null)throw new f(`Rollback marker is neither before nor after the unfinished edge`,s.MIGRATION_MARKER_CONFLICT);await proveRolledBack(e,t,n,r),await appendRolledBackEvent(e,t,n,r,i.attemptId)}async function proveRolledBack(e,t,n,{parent:r,blob:i,nextState:a}){await assertAllChecks(e,i,r.originChecks,t.namespace,`Origin checks failed after rollback`);let o=snapshotHashOf(n,a);return await proveLive(e,t,n,o,()=>`Rollback did not reach the parent snapshot`),o}function rollbackEventSeed(e,{edge:t,state:n,nextState:r}){return{estateHash:e.estateHash,snapshotHash:n.snapshotHash,sqlHash:n.sqlHash,fromState:t.stateId,toState:r,transitionHash:t.transitionHash,direction:`rollback`}}async function appendRolledBackEvent(e,t,n,r,i){await appendLedger(e,t,attemptEvents({...rollbackEventSeed(n,r),snapshotHash:snapshotHashOf(n,r.nextState)},i).event(`rolled-back`,`committed`))}function remainingRollbackOperations(e,t,n,r){return remainingSteps(r,n,{direction:`rollback`,estateHash:e.estateHash,fromState:t.edge.stateId,toState:t.nextState,transitionHash:t.edge.transitionHash,sqlHash:t.state.sqlHash,operations:t.rollback.operations,boundary:t.boundary},`Rollback`).operations}function assertReversibleEdge(e,t){let n=e.states.get(t.stateId);if(!n)throw new f(`Rollback target is missing from the estate`,s.MIGRATION_CORRUPTION);let r=n.parents.find(e=>e.transitionHash===t.transitionHash);if(!r)throw new f(`Rollback cannot find the arrival transition`,s.MIGRATION_CORRUPTION);if(r.rollback.kind===`irreversible`)throw new f(r.rollback.reason,s.MIGRATION_DESTRUCTIVE_REJECTED)}function assertExpectedRevision(e,t){if(!(t.expectRevision===void 0||e?.revision===t.expectRevision))throw new f(`down expected marker revision ${t.expectRevision}, but the marker is at revision ${e?.revision??`none`}: another command moved it`,s.MIGRATION_MARKER_CONFLICT)}async function approveRollbackLosses(e,t,n,r,i){let a=[];for(let i of r){if(!i.rollback.operations.some(e=>e.risk===`destructive`))continue;let{operations:r,ambiguousChanges:o}=await diff(requireStateSnapshot(n,i.edge.stateId),requireStateSnapshot(n,i.nextState));for(let n of[...r,...o.map(asDrop)])`tableName`in n&&isDestructiveOperation(n)&&await holdsRows(e,t,n.tableName)&&a.push(n)}a.length>0&&i&&await letLockGo(e),await approveDestructiveOperations(a,i,!1)}function asDrop(e){return e.type===`ambiguousTable`?{type:`dropTable`,tableName:e.droppedTable}:{type:`dropColumn`,tableName:e.tableName,columnName:e.droppedColumn.name}}async function holdsRows(e,t,n){return await isTableMissing(e,t,n)?!1:(await e._executeRaw(`SELECT 1 AS populated FROM ${qualifiedName(t,n)} LIMIT 1`)).rows.length>0}function refuseOpaqueEffect(e,t,n,r){let i=new Set(e.operations.flatMap(e=>e.steps.flatMap(n=>e.origin===`manual`&&n.retry===`opaque`&&concurrentIndexNames(sliceDispatch(t,n.execute)).length===0?[n.execute.dispatchId]:[]))),a=r.filter(e=>e.attemptId===n.attemptId&&e.kind===`step-confirmed`&&i.has(e.dispatchId??``)),o=new Map;for(let e of a)countUnanswered(o,e.dispatchId,e);let c=a.find(e=>e.effectState===`committed`)??a.find(e=>(o.get(e.dispatchId)??0)>0);if(c===void 0)return;let l=c.effectState===`committed`;throw new f(`resolve cannot mark this attempt rolled back: its opaque dispatch ${c.dispatchId} ${l?`committed`:`may have committed`} and nothing undid it. Finish the transition by hand and resolve({ outcome: "complete" }).`,l?s.MIGRATION_PARTIAL_EFFECT:s.MIGRATION_AMBIGUOUS_COMMIT,{meta:{...n.fromState?{fromState:n.fromState}:{},...n.toState?{toState:n.toState}:{},operationId:c.operationId??void 0,dispatchId:c.dispatchId??void 0,lastConfirmedStep:c.dispatchId??void 0,effectState:l?`committed`:`may-have-committed`,partial:!0}})}function rollbackSlice(e,t,n){if(t.path.length===0)throw new f(`Nothing to roll back`,s.MIGRATION_NOT_FOUND);let r=n.to?distanceTo(t.path.map(e=>e.stateId),resolveStateSelector(e,n.to)):n.steps,i=r===0?[]:t.path.slice(-r);if(i.some(e=>e.baselineBoundary))throw new f(`down cannot cross a baseline boundary`,s.MIGRATION_INVALID_STATE);return i}function distanceTo(e,t){let n=e.lastIndexOf(t);if(n<0)throw new f(`down target is not on the arrival path`,s.MIGRATION_NOT_FOUND);return e.length-1-n}const Wr=[`readEstate`,`listStates`,`listSnapshots`,`listSql`,`readState`,`readSnapshot`,`readSql`],Gr=[`publishEstate`,`publishSnapshot`,`publishSql`,`publishState`];function isMigrationStorageReader(e){return hasStorageMethods(e,Wr)}function isMigrationStorageWriter(e){return hasStorageMethods(e,Gr)}function hasStorageMethods(e,t){return e===null||typeof e!=`object`&&typeof e!=`function`?!1:t.every(t=>typeof Reflect.get(e,t)==`function`)}function createMigrationClient(e,t){let n=t===void 0?void 0:snapshotExactRecord(t,[`storage`,`tables`,`limits`],`migration client options`,refuseClientOptions),r=normalizeManagedTables(n?.tables),i=n?.limits===void 0?void 0:resolveMigrationLimits(n.limits),o=r===void 0&&i===void 0?e:{$driver:e.$driver,$schema:e.$schema,[yr]:r,[br]:i},s=Object.freeze({log:()=>logV1(o),push(e){return pushV1(o,e)}});if(n===void 0)return s;let c=n.storage;if(c===void 0)return r!==void 0||i!==void 0?s:refuseClientOptions(`migration client options must include storage, tables or limits when supplied`);let l;try{if(!isMigrationStorageReader(c))return refuseClientOptions(`migration client storage must implement MigrationStorageReader`);l=c}catch(e){return refuseClientOptions(`migration client storage could not be inspected`,a(e))}let u=Object.freeze({...s,check:()=>checkEstate(l),list:async()=>listMigrationStates(await loadMigrationGraph(l)),show:async e=>{let t=await loadMigrationGraph(l);return showMigrationState(t,resolveStateSelector(t,e))},graph:async()=>migrationGraphResult(await loadMigrationGraph(l)),status:()=>statusV1(o,l),verify:()=>verifyV1(o,l),apply:e=>applyV1(o,l,e),down:e=>downV1(o,l,e),baseline:e=>baselineV1(o,l,e),reanchor:e=>reanchorV1(o,l,e),prune:e=>pruneV1(l,e),resolve:e=>resolveV1(o,l,e)}),d;try{if(!isMigrationStorageWriter(l))return u;d=l}catch(e){return refuseClientOptions(`migration client storage could not be inspected`,a(e))}return Object.freeze({...u,generate:e=>generateV1(o,d,e),reset:e=>resetV1(o,d,e)})}function refuseClientOptions(e,t){throw new f(e,s.INVALID_INPUT,{cause:t})}export{sqliteDecimalStorageKind as $,qe as A,decimalConversionRequired as B,addDropResolver as C,encodeSqlBlob as D,rejectAllResolver as E,getSQLiteType as F,mysqlDecimalListFitsCheck as G,mysqlDecimalFitsCatalogCheck as H,mysqlEnumType as I,postgresDecimalFitsCheck as J,mysqlDecimalListMarker as K,mysqlStringLiteral as L,H as M,getMySQLType as N,derivedMigrationName as O,getPostgresType as P,sqliteDecimalCopyExpression as Q,parseMySqlEnumValues as R,isDestructiveOperation as S,lenientResolver as T,mysqlDecimalFitsCheck as U,describeDecimalStorageKind as V,mysqlDecimalListFitsCatalogCheck as W,readSqliteDecimalConstraint as X,readMysqlDecimalListMarker as Y,sqliteDecimalCheck as Z,foreignKeyPragmasCannotBeLifted as _,formatOperation as a,sqliteDefinitionKeywords as at,catalogCommitBoundaries as b,Z as c,readSqliteIdentifier as ct,sqliteDateTimeCopyExpression as d,Le as et,sqliteDateTimeTargetRequiresRecreation as f,throwIfCatalogRefusal as g,isSqliteStateControlDefinition as h,admitLiveMigrationCapability as i,sqliteGeoPointEncoding as it,U as j,applyNativeRename as k,sqliteCanonicalDateTimeExpression as l,skipSqlNonStructuralRegion as lt,MigrationDriver as m,renderMigrationReview as n,sqliteGeoPointCarrier as nt,loadMigrationGraph as o,sqliteTableDefinitions as ot,registerMigrationDriver as p,mysqlDecimalStorageKind as q,getPushMigrationDriver as r,sqliteGeoPointCheck as rt,auditStorage as s,isSqliteBareIdentifierCharacter as st,createMigrationClient as t,readSqliteGeoPointColumn as tt,sqliteCanonicalTimeExpression as u,V as ut,providerFacts as v,createPredefinedResolver as w,boundNamespace as x,tableRewrites as y,decimalConversionConstraintName as z};
|
|
49
|
-
//# sourceMappingURL=client-
|
|
48
|
+
`),ae={stateId:ee.stateId,name:T,estateHash:c,snapshotHash:f.snapshotHash,sqlHash:D.sqlHash,operations:y,warnings:b,operationsByParent:x,sql:re,reviewSql:ie};if(r.dryRun)return{outcome:`preview`,...ae};o||await t.publishEstate(s);for(let{snapshot:e,sealed:n,encoded:r}of A)e.bytes&&await t.publishSnapshot(e.artifactHash,e.bytes),await t.publishSql(n.sqlHash,n.bytes),await t.publishState(r.stateId,r.bytes);return{outcome:`published`,...ae}}function sameSchema(e,t){return encodeSnapshot(orderFree(e)).snapshotHash===encodeSnapshot(orderFree(t)).snapshotHash}function orderFree(t){let n=e((e,t)=>e.name<t.name?-1:Number(e.name>t.name),`byName`);return{...t,tables:t.tables.map(e=>({...e,columns:[...e.columns].sort(n),indexes:[...e.indexes].sort(n),foreignKeys:[...e.foreignKeys].sort(n),uniqueConstraints:[...e.uniqueConstraints].sort(n)})).sort(n),enums:t.enums&&[...t.enums].sort(n)}}function sealState(e,t,n,r,i,a,o){let s=e.seal();assertArtifactExecutionSafe(s.dispatches.map(e=>sliceDispatch(s.bytes,e)),r,a);let c=t.map(e=>hashParent({...e,originChecks:rebindChecks(e.originChecks,s.dispatches),operations:rebindDispatches(e.operations,s.dispatches),rollback:rebindRollback(e.rollback,s.dispatches)})),l=rebindChecks(n,s.dispatches);return{sealed:s,hashedParents:c,destinationChecks:l,encoded:encodeStateManifest({format:`1`,estateHash:i,name:a,snapshotHash:o.snapshotHash,...o.artifactHash===o.snapshotHash?{}:{snapshotArtifactHash:o.artifactHash},sqlHash:s.sqlHash,destinationChecks:l,parents:c})}}function sealLowLockState(e,t,n,r,i,a,o){let s=new SqlAssembly,c=compileGeneratedTransition(i.operations,t,`artifact`,r.current,i.snapshot,s,a),l=o(i.snapshot,[r.from]),u=sealState(s,[sealParent(r.from,c,r.approvals)],[],t.target.dialect,e,n,l);return{...u,snapshot:l,review:renderMigrationReview(u.hashedParents,[],u.sealed.bytes),warnings:transitionWarnings(c)}}function transitionWarnings(e){return[...e.warnings??[],...e.rollback.kind===`irreversible`?[e.rollback.reason]:[]]}function assertManualParents(e,t){let n=new Set;for(let r of t){if(r.from===null){if(e.states.size>0)throw new f(`A second virtual-root transition is refused`,s.MIGRATION_INVALID_ESTATE)}else if(!e.states.has(r.from))throw new f(`Unknown parent state ${r.from}`,s.MIGRATION_NOT_FOUND);let t=r.from??`null`;if(n.has(t))throw new f(`A manual migration names a parent more than once`,s.MIGRATION_INVALID_ESTATE);n.add(t)}}function resolveParents(e,t,n){if(t.from!==void 0){if(t.from===null){let[t,...r]=e.leaves;if(t&&(r.length>0||!sameSchema(requireStateSnapshot(e,t),n)))throw new f(`A second virtual-root transition is an authored checkpoint: it must restate the schema of the estate's single leaf. Generate the change first, then the checkpoint.`,s.MIGRATION_INVALID_ESTATE);return[null]}if(!e.states.has(t.from))throw new f(`Unknown parent state ${t.from}`,s.MIGRATION_NOT_FOUND);return[t.from]}return e.states.size===0?[null]:[...e.leaves]}function emptyGraph(e,t){let n=encodeSnapshot(emptyManagedSnapshot()).snapshotHash;return{estateHash:e,descriptor:t,states:new Map,snapshots:new Map([[n,emptyManagedSnapshot()]]),snapshotArtifacts:new Map,sql:new Map,roots:[],leaves:[],emptySnapshotHash:n}}function ancestryHasCustom(e,t,n=new Set){if(t===null||n.has(t))return!1;n.add(t);let r=e.states.get(t);for(let t of r.parents)if(t.operations.some(e=>e.origin===`manual`)||t.requestedForwardBoundary!==null||ancestryHasCustom(e,t.fromState,n))return!0;return!1}function refuseUnprovedMerge(e,t,n){if(!(t.length<2||n)){for(let n of t)if(ancestryHasCustom(e,n))throw new f(`A custom or data transition cannot be merged structurally; supply manualMigration for every parent`,s.MIGRATION_INVALID_ESTATE)}}function normalizeDownOptions(e){let{steps:t,to:n,dryRun:r,expectRevision:i,resolve:a}=snapshotExactRecord(e,[`steps`,`to`,`dryRun`,`expectRevision`,`resolve`],`down options`,refuseDownOptions);if(t!==void 0&&n!==void 0)return refuseDownOptions(`down accepts either steps or to, not both`);let o=1;if(t!==void 0){if(typeof t!=`number`||!Number.isSafeInteger(t)||t<=0)return refuseDownOptions(`down steps must be a positive safe integer`);o=t}return r!==void 0&&typeof r!=`boolean`?refuseDownOptions(`down dryRun must be a boolean`):i!==void 0&&(typeof i!=`number`||!Number.isSafeInteger(i)||i<=0)?refuseDownOptions(`down expectRevision must be a positive safe integer`):a!==void 0&&!isResolveCallback(a)?refuseDownOptions(`down resolve must be a function`):Object.freeze({steps:o,...n===void 0?{}:{to:normalizeStateSelector(n)},dryRun:r===!0,...i===void 0?{}:{expectRevision:i},...a===void 0?{}:{resolve:a}})}function normalizeStateSelector(e){let t=snapshotExactRecord(e,[`id`,`prefix`,`name`],`down to`,refuseDownOptions),n=Object.keys(t);if(n.length!==1)return refuseDownOptions(`down to must contain exactly one selector key`);let r=n[0],i=t[r];return typeof i!=`string`||i.length===0?refuseDownOptions(`down to.${r} must be a non-empty string`):r===`id`?{id:i}:r===`prefix`?{prefix:i}:{name:i}}function isResolveCallback(e){return typeof e==`function`}function refuseDownOptions(e,t){throw new f(e,s.INVALID_INPUT,{cause:t})}async function resetV1(e,t,n={}){let r=await loadMigrationGraph(t),i=resolveStateSelector(r,n.to),a=selectRoute(r,null,i,n.via),o=n.dryRun===!0,c=openCommand(e,r,o?`read-only`:`effectful`,`reset()`);if(o){let t=await resolveCommandDriver(e.$driver,c),n=await planLiveNamespaceReset(e.$driver,t);return await t.preflightSchemaRequirements(a.map(e=>requireStateSnapshot(r,e)),(t,n)=>e.$driver._executeRaw(t,n),resetProgram(n,prepareResetReplay(e.$driver.supportsTransactions,t,r,a))),{preview:!0,path:a,tables:n.dropTables.map(e=>e.name)}}return withLockedMigrationProducer(e.$driver,c,async(t,n)=>{let o=await readCommandControl(t,n,!0),{marker:c,ledger:l}=o,u=o.presence.kind!==`present`,d=unfinishedAttempts(l),p=d.length===1&&d[0].kind===`reset-started`?d[0]:void 0;if(d.length>0&&!p)throw new f(`An unfinished migration attempt is blocking reset`,s.MIGRATION_UNFINISHED_ATTEMPT);let m=`${n.target.dialect}:${n.namespace??``}`,h=p?matchingResetPlan(p,r,i,a,m):void 0;p||refuseIncompatibleHistory(c,l);let g=requireStateSnapshot(r,i),_=r.states.get(i).snapshotHash,v=routeEdges(r,null,a).map(({to:e,transition:t})=>({stateId:e,transitionHash:t.transitionHash,baselineBoundary:!1})),y={estateHash:r.estateHash,snapshotHash:_,sqlHash:null,fromState:c?.stateId??null,toState:i,transitionHash:null,direction:`reset`};if(p&&h&&c&&resetMarkerProvesApplied(c,r,v,_,h)&&await fingerprintLive(await introspectManaged(t,n),n,t)===await fingerprintLive(g,n,t))return await appendLedger(t,n,attemptEvents({...y,fromState:p.fromState},p.attemptId).event(`reset-applied`,`committed`)),{preview:!1,path:a};if(p&&h&&!resetSourceMarkerMatches(c,p,h,r.emptySnapshotHash))throw new f(`The unfinished reset source marker no longer matches its plan`,s.MIGRATION_MARKER_CONFLICT);let b=p&&l.some(e=>e.attemptId===p.attemptId&&e.kind===`reset-step-confirmed`&&(e.fromState!==null||e.toState!==null||e.transitionHash!==null||e.operationId!==null))?void 0:await planLiveNamespaceReset(t,n),x=resetProgram(b,[]).map(e=>dispatchForClearSql(e));if(b&&n.target.dialect===`mysql`&&(b.dropForeignKeys.length>0||b.dropEnums.length>0))throw new f(`Stepwise reset refuses clear dispatches without driver-owned pre/post proof`,s.MIGRATION_UNSUPPORTED_PROVIDER);let S={estateHash:r.estateHash,targetIdentity:m,sourceRevision:c?.revision??0,sourceFingerprint:c?.snapshotHash??r.emptySnapshotHash,replayPath:a,clearDispatches:x,referencedStates:a},C=h;C&&b&&assertStoredResetPlan(C,S);let w=C?C.resetPlanHash:L(R.resetPlan,I(S)),T=C??{...S,resetPlanHash:w},E=prepareResetReplay(t.supportsTransactions,n,r,a),D=p?remainingResetReplay(r,E,p,T,l):E,O=c?.stateId??null;await n.preflightSchemaRequirements([...O===null||r.states.has(O)?[requireStateSnapshot(r,O)]:[],...a.map(e=>requireStateSnapshot(r,e))],(e,n)=>t._executeRaw(e,n),resetProgram(b,D));let k=p?void 0:e=>appendLedger(e,n,attemptEvents({...y,resetPlan:T},w).event(`reset-started`,`none`)),finish=async e=>{await proveLive(e,n,r,_,()=>`Reset replay did not reach the target snapshot`),await advanceMarker(e,n,r.estateHash,c,v,_),await appendLedger(e,n,attemptEvents(y,w).event(`reset-applied`,`committed`))};return u&&(await ensureControlTables(t,n),await commitLockedTransaction(t,n)),await runProgram(t,n,void 0,i=>executeResetProgram(t,i,n,c,r,b,T,D,w,k,finish,e.$schema)),{preview:!1,path:a}})}function matchingResetPlan(e,t,n,r,i){let a=t.states.get(n),o=e.resetPlan,c=e.fromState===null?t.emptySnapshotHash:t.states.has(e.fromState)?t.states.get(e.fromState).snapshotHash:o?.sourceFingerprint;if(!(a&&o)||e.direction!==`reset`||e.attemptId!==o.resetPlanHash||e.estateHash!==t.estateHash||e.snapshotHash!==a.snapshotHash||e.toState!==n||o.estateHash!==t.estateHash||o.targetIdentity!==i||o.sourceFingerprint!==c||!sameIds(o.replayPath,r)||!sameIds(o.referencedStates,r))throw new f(`The unfinished reset does not match the requested reset`,s.MIGRATION_INVALID_STATE);return o}function resetMarkerProvesApplied(e,t,n,r,i){let a=markerFromPath(t.estateHash,r,n,i.sourceRevision+1);return e.estateHash===a.estateHash&&e.stateId===a.stateId&&e.snapshotHash===a.snapshotHash&&sameMarker(e,a)}function resetSourceMarkerMatches(e,t,n,r){return e?e.stateId===t.fromState&&e.revision===n.sourceRevision&&e.snapshotHash===n.sourceFingerprint:t.fromState===null&&n.sourceRevision===0&&n.sourceFingerprint===r}function assertStoredResetPlan(e,t){if(e.estateHash!==t.estateHash)throw new f(`A stored reset plan does not match the current estate`,s.MIGRATION_INVALID_STATE);if(e.targetIdentity!==t.targetIdentity)throw new f(`A stored reset plan does not match the current target`,s.MIGRATION_INVALID_STATE);if(e.sourceRevision!==t.sourceRevision||e.sourceFingerprint!==t.sourceFingerprint)throw new f(`A stored reset plan does not match the current marker`,s.MIGRATION_INVALID_STATE);if(!sameIds(e.replayPath,t.replayPath))throw new f(`A stored reset plan does not match the requested replay path`,s.MIGRATION_INVALID_STATE);let n=new Set(e.clearDispatches.map(e=>e.dispatchId));for(let e of t.clearDispatches)if(!n.has(e.dispatchId))throw new f(`Live remaining reset clears are not in the stored reset plan`,s.MIGRATION_INVALID_STATE)}function sameIds(e,t){return e.length===t.length?e.every((e,n)=>e===t[n]):!1}function resetProgram(e,t){return[...e?.clear??[],...t.flatMap(({blob:e,operations:t})=>stepStatements(e,t))]}function dispatchForClearSql(e){let t=encodeSqlText(e),n=encodeSqlBlob(t);return{dispatchId:encodeDispatchIdentity(n,0,t.length,[]),sqlHash:n,offset:0,length:t.length,parameters:[]}}async function executeResetClear(e,t,n,r,i){for(let a of n.dropForeignKeys)await executeExactSql(e,a),await confirmResetStep(e,t,i,r,a);for(let a of n.dropTables){let n=tableExistsProbe(t,a.name,!0),o=tableExistsProbe(t,a.name,!1);if(!await evaluateProbe(e,n)){await confirmResetStep(e,t,i,r,a.sql);continue}if(await executeExactSql(e,a.sql),!await evaluateProbe(e,o))throw new f(`Reset clear did not drop table ${a.name}`,s.MIGRATION_PARTIAL_EFFECT);await confirmResetStep(e,t,i,r,a.sql)}for(let a of n.dropEnums)await executeExactSql(e,a),await confirmResetStep(e,t,i,r,a)}async function evaluateProbe(e,t){let n=await e._executeRaw(t.sql,t.parameters.map(e=>e.kind===`string`?e.value:null)),r=Object.values(n.rows[0]??{})[0];return(r===!0||r===1||r===`1`||r===`t`)===t.equals}async function confirmResetStep(e,t,n,r,i){await confirmResetDispatch(e,t,n,r,dispatchForClearSql(i))}async function confirmResetDispatch(e,t,n,r,i){await appendLedger(e,t,ledgerEvent({attemptId:r,kind:`reset-step-confirmed`,estateHash:n.estateHash,snapshotHash:n.emptySnapshotHash,sqlHash:i.sqlHash,fromState:null,toState:null,transitionHash:null,direction:`reset`,operationId:null,dispatchId:i.dispatchId,effectState:`committed`}))}function prepareResetReplay(e,t,n,r){return routeEdges(n,null,r).map(n=>{let r=n.transition.requestedForwardBoundary,i=classifyStoredAtomicity(t,r,n.transition.operations,n.blob);return assertTransactionalBoundaryHonored(e,r),refuseSqliteStepwise(t,r,n.to),{...n,boundary:i,operations:n.transition.operations}})}function remainingResetReplay(e,t,n,r,i){let a=new Map(r.clearDispatches.map((e,t)=>[e.dispatchId,t])),o=new Set,c=t.flatMap((e,t)=>e.operations.flatMap(n=>n.steps.map(r=>({edge:e,edgeIndex:t,operation:n,step:r})))),l=new Map(c.map((e,t)=>[e.step.execute.dispatchId,t])),u=new Set,d=new Set,p=!1;for(let t of i){if(t.attemptId!==n.attemptId||t.kind!==`reset-step-confirmed`)continue;if((t.direction!==`reset`||t.estateHash!==e.estateHash||!t.dispatchId)&&refuseResetProgress(`Reset progress does not match its authenticated plan`),t.fromState===null&&t.toState===null&&t.transitionHash===null&&t.operationId===null){let n=a.get(t.dispatchId);(n===void 0||t.sqlHash!==r.clearDispatches[n].sqlHash||t.snapshotHash!==e.emptySnapshotHash||t.effectState!==`committed`)&&refuseResetProgress(`Reset clear progress names an unknown dispatch`),o.add(n);continue}p=!0;let i=l.get(t.dispatchId);i===void 0&&refuseResetProgress(`Reset replay progress names an unknown dispatch`);let m=c[i];if((!m||t.fromState!==m.edge.from||t.toState!==m.edge.to||t.transitionHash!==m.edge.transition.transitionHash||t.snapshotHash!==m.edge.state.snapshotHash||t.sqlHash!==m.edge.state.sqlHash||t.operationId!==m.operation.id)&&refuseResetProgress(`Reset replay progress names an unknown dispatch`),t.effectState===`committed`)u.add(i);else if(t.effectState===`none`)m.step.retry===`proven`?u.add(i):d.add(i);else throw new f(`Reset replay progress has an ambiguous commit outcome`,s.MIGRATION_AMBIGUOUS_COMMIT)}if(confirmedPrefix(o,`Reset clear progress is not a contiguous dispatch prefix`),p&&o.size!==r.clearDispatches.length&&refuseResetProgress(`Reset replay progress exists before the clear prefix is complete`),!p)return t;let m=confirmedPrefix(u,`Reset replay progress is not a contiguous dispatch prefix`);[...d].some(e=>!u.has(e)&&e!==m)&&refuseResetProgress(`Reset replay progress is not contiguous`);let h=c[m];refuseAmbiguousNext(h?.step,h?.edge.boundary,d.has(m),`The next reset dispatch has an ambiguous commit outcome`);let g=m===0?void 0:c[m-1]?.edgeIndex,_=m;return t.flatMap((e,t)=>{let n=e.operations.reduce((e,t)=>e+t.steps.length,0);if(_>=n)return _-=n,t===g?[{...e,operations:[]}]:[];let r=sliceOperations(e.operations,_);return _=0,[{...e,operations:r}]})}function refuseResetProgress(e){throw new f(e,s.MIGRATION_CORRUPTION)}async function executeResetProgram(e,t,n,r,i,a,o,s,c,l,u,d){let f=groupContiguousAtomicity(s,e=>resetProgram(void 0,[e])),p=resetProgram(a,[]),m=new Set(p.map(e=>dispatchForClearSql(e).dispatchId)),h=p.length>0?a:void 0,g=a!==void 0,_=l,runBoundary=async(i,a,o)=>{let guarded=async t=>{await assertLockedSinceDecision(e,t,n,r,_===void 0),await o(t)};await(n.target.dialect===`mysql`?guarded(t):runProgram(e,n,{transactional:i===`transactional`,statements:a},guarded))},completeClearEvidence=async e=>{for(let t of o.clearDispatches)m.has(t.dispatchId)||await confirmResetDispatch(e,n,i,c,t)},admit=async e=>{let t=_;t&&(_=void 0,await t(e))};if(h&&f[0]?.boundary===`stepwise`){let e=h;h=void 0,await runBoundary(`transactional`,resetProgram(e,[]),async t=>{await admit(t),await executeResetClear(t,n,e,c,i),await completeClearEvidence(t),g=!1})}if(!h&&f[0]?.boundary===`stepwise`&&_&&await runBoundary(`transactional`,[],admit),f.length===0){await runBoundary(`transactional`,resetProgram(h,[]),async e=>{await admit(e),h&&await executeResetClear(e,n,h,c,i),g&&=(await completeClearEvidence(e),!1),await u(e)});return}for(let[e,t]of f.entries()){let r=resetProgram(h,t.items);await runBoundary(t.boundary,r,async r=>{await admit(r),h&&=(await executeResetClear(r,n,h,c,i),void 0),g&&=(await completeClearEvidence(r),!1);for(let e of t.items)await executeResetReplayEdge(r,n,i,e,c,d);e===f.length-1&&await u(r)})}}async function executeResetReplayEdge(e,t,n,r,i,a){let{from:o,to:s,transition:c,state:l,blob:u,boundary:d,operations:f}=r,p=attemptEvents({estateHash:n.estateHash,snapshotHash:l.snapshotHash,sqlHash:l.sqlHash,fromState:o,toState:s,transitionHash:c.transitionHash,direction:`reset`},i);await executeOperations(e,u,f,d,(n,r,i)=>appendLedger(e,t,p.event(`reset-step-confirmed`,r,n,i)),t.namespace),await canonicalizeSqliteStorage(e,f,a,requireStateSnapshot(n,s)),await assertAllChecks(e,u,l.destinationChecks,t.namespace,`Reset replay failed destination checks`)}async function statusV1(e,t){let n=await loadMigrationGraph(t),r=openCommand(e,n,`read-only`,`status()`),i=await resolveCommandDriver(e.$driver,r),a=await readCommandControl(e.$driver,i),o=await readInvalidIndexes(e.$driver,i),s=o.length===0?{}:{invalidIndexes:o};if(a.presence.kind!==`present`)return{control:`absent`,marker:null,pending:[...n.roots],unfinished:!1,...s};let{marker:c,ledger:l}=a,u=unfinishedAttempts(l).length>0,d;for(let e of l)e.kind===`failed`&&(d=e);let f=markerStanding(n,c),p=[];if(f===`known`&&n.leaves.length===1){let e=n.leaves[0];(c?.stateId??null)!==e&&(p=[...selectRoute(n,c?.stateId??null,e)])}return{control:`present`,marker:c,pending:p,unfinished:u,...f===`known`?{}:{markerState:f},...s,...d?{lastFailure:d}:{}}}async function verifyV1(e,t){let n=await loadMigrationGraph(t),r=openCommand(e,n,`effectful`,`verify()`);return withLockedMigrationProducer(e.$driver,r,async(e,t)=>{let r=await readCommandControl(e,t);if(r.presence.kind!==`present`)throw new f(`verify requires present control tables`,s.MIGRATION_NOT_FOUND);let{marker:i}=r;if(!i)throw new f(`verify requires a migration marker`,s.MIGRATION_NOT_FOUND);let a=markerStanding(n,i);if(a!==`known`)return{ok:!1,markerState:a};let o=requireStateSnapshot(n,i.stateId);return await t.preflightSchemaRequirements([o],(t,n)=>e._executeRaw(t,n),[]),await assertNoDrift(e,t,n,i),{ok:!0}})}async function logV1(e){let t=getPushMigrationDriver(e);admitLiveMigrationCapability(t,`read-only`,`log()`);let n=await resolveCommandDriver(e.$driver,t),r=await readControlState(e.$driver,n);if(r.presence.kind!==`present`)throw refusePartialControl(r.presence),new f(`log requires present control tables`,s.MIGRATION_NOT_FOUND);return r.ledger}async function baselineV1(e,t,n){let r=await loadMigrationGraph(t),i=openCommand(e,r,`effectful`,`baseline()`),a=resolveStateSelector(r,n.to),o=selectRoute(r,null,a,n.via);return withLockedMigrationProducer(e.$driver,i,async(e,t)=>{let n=await readCommandControl(e,t,!0),{marker:i,ledger:c}=n;if(i||unfinishedAttempts(c).length>0)throw new f(`baseline requires an unmarked database without an unfinished attempt`,s.MIGRATION_INVALID_STATE);return refuseIncompatibleHistory(i,c),assertStructuralRoute(r,o,`baseline`),await t.preflightSchemaRequirements([requireStateSnapshot(r,a)],(t,n)=>e._executeRaw(t,n),[]),n.presence.kind!==`present`&&(await ensureControlTables(e,t),await commitLockedTransaction(e,t),await assertLockedSinceDecision(e,e,t,null)),await proveLive(e,t,r,r.states.get(a).snapshotHash,async e=>`baseline requires exact live equality with the target snapshot. Differences: ${await e()}`),await adoptRoute(e,t,r,o,null),{stateId:a}})}async function reanchorV1(e,t,n={}){let r=await loadMigrationGraph(t),i=openCommand(e,r,`effectful`,`reanchor()`),a=n.to&&resolveStateSelector(r,n.to);return withLockedMigrationProducer(e.$driver,i,async(e,t)=>{let{marker:i,ledger:o}=await readCommandControl(e,t);if(!i||markerStanding(r,i)===`known`)throw new f(`reanchor moves only a marker naming a state this history does not hold; apply, verify and baseline handle the others`,s.MIGRATION_INVALID_STATE);if(unfinishedAttempts(o).length>0)throw new f(`reanchor refuses while an attempt is unfinished: resolve it first`,s.MIGRATION_INVALID_STATE);let c=await introspectManaged(e,t),l=await fingerprintLive(c,t,e),u=[];for(let n of a?[a]:r.states.keys())await fingerprintLive(requireStateSnapshot(r,n),t,e)===l&&u.push(n);let d=a??(r.leaves.length===1?r.leaves[0]:void 0);if(u.length===0)throw new f(`reanchor found no state of this history that the live schema matches.${d?` Differences from ${d}: ${JSON.stringify(await diff(c,requireStateSnapshot(r,d)))}`:``}`,s.MIGRATION_DRIFT);if(u.length>1)throw new f(`Several states of this history match the live schema (${u.join(`, `)}), and equal schemas never say which data the database holds: name one with reanchor({ to }).`,s.MIGRATION_INVALID_STATE);let p=u[0];if(i.path.some(e=>e.stateId===p))throw new f(`reanchor refuses ${p}: the marker passed through it, so the transitions lost after it changed no schema and may have moved data. Regenerate the lost states from the same documents instead: their ids come back identical.`,s.MIGRATION_INVALID_STATE);let m=selectRoute(r,null,p,n.via);return assertStructuralRoute(r,m,`reanchor`),await t.preflightSchemaRequirements([requireStateSnapshot(r,p)],(t,n)=>e._executeRaw(t,n),[]),await adoptRoute(e,t,r,m,i),{stateId:p}})}function assertStructuralRoute(e,t,n){for(let{from:r,transition:i,state:a}of routeEdges(e,null,t)){let t=r===null?e.emptySnapshotHash:e.states.get(r)?.snapshotHash;if(i.operations.some(e=>e.origin===`manual`||e.risk===`opaque`)||t===a.snapshotHash)throw new f(`${n} refuses a path containing manual, opaque, or data-only transitions`,s.MIGRATION_INVALID_STATE)}}async function adoptRoute(e,t,n,r,i){let a=routeEdges(n,null,r).map(({to:e,transition:t},n)=>({stateId:e,transitionHash:t.transitionHash,baselineBoundary:n===0})),o=r.at(-1),publish=async e=>{let r=await advanceMarker(e,t,n.estateHash,i,a,n.states.get(o).snapshotHash);await appendLedger(e,t,ledgerEvent({attemptId:r.pathHash,kind:i?`reanchored`:`baselined`,estateHash:n.estateHash,snapshotHash:r.snapshotHash,sqlHash:null,fromState:i?.stateId??null,toState:o,transitionHash:null,direction:`baseline`,operationId:null,dispatchId:null,effectState:`none`}))};e.supportsTransactions?await e.withTransaction(e=>publish(e)):await publish(e)}async function pruneV1(e,t){let n=await loadMigrationGraph(e),r=statesFrom(n,resolveStateSelector(n,t.checkpoint)),{into:i}=t;await i.publishEstate(await present(e.readEstate(),`estate.json`,I(n.descriptor)));let a=new Set;for(let t of r){let{snapshotHash:r,snapshotArtifactHash:o,sqlHash:c}=n.states.get(t),l=[],u=o??r;for(;u!==void 0&&!a.has(u);)l.push(u),u=n.snapshotArtifacts.get(u)?.baseArtifactHash;for(let t of l.reverse()){let r=n.snapshotArtifacts.get(t),o=r?.bytes??encodeSnapshot(requireStateSnapshot(n,null)).bytes;if(!ye(!r&&t===n.emptySnapshotHash?await e.readSnapshot(t)??o:await present(e.readSnapshot(t),t),o))throw new f(`Snapshot ${t} changed while prune copied it`,s.MIGRATION_CORRUPTION);await i.publishSnapshot(t,o.slice()),a.add(t)}await i.publishSql(c,n.sql.get(c)),await i.publishState(t,await present(e.readState(t),t,I(n.states.get(t))))}return{states:[...r]}}async function present(e,t,n){let r=await e;if(!r)throw new f(`${t} vanished from the history while prune copied it`,s.MIGRATION_CORRUPTION);if(n&&!ye(r,n))throw new f(`${t} changed while prune copied it`,s.MIGRATION_CORRUPTION);return n??r}async function downV1(e,t,n={}){let r=normalizeDownOptions(n),i=await loadMigrationGraph(t),a=openCommand(e,i,r.dryRun?`read-only`:`effectful`,`down()`);if(r.dryRun){let t=e.$driver,n=await resolveCommandDriver(t,a),{close:o,removed:s,refusal:c}=await planRollback(t,n,i,await readCommandControl(t,n),r,!0);return{path:o?[o.item.edge.stateId]:s.map(e=>e.stateId),preview:!0,edges:[...s].reverse().map(e=>previewRollbackEdge(i,e)),refusal:c}}return withLockedMigrationProducer(e.$driver,a,async(t,n)=>{let a=await readCommandControl(t,n),{close:o,removed:s,run:c}=await planRollback(t,n,i,a,r,!1);if(o)return await n.preflightSchemaRequirements([requireStateSnapshot(i,o.item.nextState)],(e,n)=>t._executeRaw(e,n),[]),await runProgram(t,n,void 0,e=>closeCompletedRollback(e,n,i,o.item,o.attempt,a.ledger,a.marker)),{path:[o.item.edge.stateId],preview:!1};if(!c)return{path:[],preview:!1};let{prepared:l,attempt:u}=c,statementsOf=e=>stepStatements(e.blob,e.rollback.operations),d=c.marker;for(let r of groupContiguousAtomicity(l,statementsOf))await runProgram(t,n,{transactional:r.boundary===`transactional`,statements:r.items.flatMap(statementsOf)},async o=>{await assertLockedSinceDecision(t,o,n,d,r.items[0]===l[0]&&u!==void 0);for(let t of r.items)d=await executeRollbackEdge(o,n,i,t,d,t===l[0]?u:void 0,a.ledger,e.$schema)});return{path:s.map(e=>e.stateId),preview:!1}})}async function planRollback(e,t,n,{marker:r,ledger:i},a,o){assertExpectedRevision(r,a);let c=null,l;try{l=admitRollbackAttempt(i)}catch(e){if(!o)throw e;c=refusalOf(e)}let{supportsTransactions:u}=e;if(l&&l.toState===(r?.stateId??null)){let e=prepareRollbackAttempt(n,t,u,l);return{refusal:c,close:{item:e,attempt:l},removed:[]}}if(!r){if(c)return{refusal:c,removed:[]};throw new f(`Nothing to roll back`,s.MIGRATION_NOT_FOUND)}let d=rollbackSlice(n,r,a);if(c||d.length===0)return{refusal:c,removed:d};try{let i=[...d].reverse();for(let e of i)assertReversibleEdge(n,e);let o=i.map(e=>prepareRollbackEdge(n,t,u,e));return await t.preflightSchemaRequirements([requireStateSnapshot(n,r.stateId),...o.map(e=>requireStateSnapshot(n,e.nextState))],(t,n)=>e._executeRaw(t,n),o.flatMap(e=>stepStatements(e.blob,e.rollback.operations))),l?assertResumesSelectedPath(n,t,u,l,o[0]):await assertNoDrift(e,t,n,r),await approveRollbackLosses(e,t,n,o,a.resolve),{refusal:c,removed:d,run:{marker:r,prepared:o,attempt:l}}}catch(e){if(!o)throw e;return{refusal:refusalOf(e),removed:d}}}async function resolveV1(e,t,n){let r=await loadMigrationGraph(t),i=openCommand(e,r,`effectful`,`resolve()`);return withLockedMigrationProducer(e.$driver,i,async(t,i)=>{let{ledger:a}=await readCommandControl(t,i),o=unfinishedAttempts(a);if(o.length!==1)throw new f(o.length===0?`resolve requires an unfinished attempt`:`resolve requires exactly one unfinished attempt`,s.MIGRATION_INVALID_STATE);let c=o[0];if(c.kind===`reset-started`)throw new f(`An unfinished reset can only be resumed by reset()`,s.MIGRATION_INVALID_STATE);if(c.direction===`rollback`)throw new f(`An unfinished rollback can only be resumed by down()`,s.MIGRATION_INVALID_STATE);let l=c.toState,u=c.fromState;if(!l)throw new f(`Unfinished attempt is missing its target state`,s.MIGRATION_CORRUPTION);let d=r.states.get(l);if(!d)throw new f(`Unfinished attempt target is absent from the estate`,s.MIGRATION_CORRUPTION);let p=r.sql.get(d.sqlHash),m=parentTransition(r,u,l),h=requireStateSnapshot(r,l),g=requireStateSnapshot(r,u),_=stepStatements(p,m.operations);await i.preflightSchemaRequirements([g,h],(e,n)=>t._executeRaw(e,n),n.outcome===`retry`?_:[]),n.outcome!==`retry`&&await repairInvalidIndexes(t,i,_,n.outcome===`complete`?h:g);let v=await fingerprintLive(await introspectManaged(t,i),i,t),y=v===await fingerprintLive(h,i,t)&&await evaluateAllChecks(t,p,d.destinationChecks,i.namespace),b=v===await fingerprintLive(g,i,t)&&await evaluateAllChecks(t,p,m.originChecks,i.namespace),x=m.operations.some(e=>e.origin===`manual`&&e.steps.some(e=>e.retry===`opaque`)),S={transactional:!0,statements:[]};if(n.outcome===`complete`){if(!y||x&&d.destinationChecks.length===0)throw new f(`resolve cannot mark complete without destination proof`,s.MIGRATION_INVALID_STATE);return await runProgram(t,i,S,async t=>{await canonicalizeSqliteStorage(t,m.operations,e.$schema,h),await finishResolve(t,i,r,c,`applied`,l)}),{outcome:`complete`}}if(n.outcome===`rolled-back`){if(refuseOpaqueEffect(m,p,c,a),!b||x&&m.originChecks.length===0)throw new f(`resolve cannot mark rolled back without origin proof`,s.MIGRATION_INVALID_STATE);return await runProgram(t,i,S,e=>finishResolve(e,i,r,c,`rolled-back`,u)),{outcome:`rolled-back`}}if(x)throw new f(`resolve cannot retry an opaque dispatch without origin or destination proof`,s.MIGRATION_INVALID_STATE);if(m.operations.some(e=>e.steps.some(e=>e.retry===`opaque`))&&!b)throw new f(`resolve cannot retry a generated structural transition except from the origin`,s.MIGRATION_INVALID_STATE);assertTransactionalBoundaryHonored(t.supportsTransactions,m.requestedForwardBoundary);let C=classifyStoredAtomicity(i,m.requestedForwardBoundary,m.operations,p);return await runProgram(t,i,{transactional:C===`transactional`,statements:_},async e=>{await executeOperations(e,p,m.operations,C,void 0,i.namespace,{fromState:u,toState:l}),await assertAllChecks(e,p,d.destinationChecks,i.namespace,`Retry did not reach the destination`),await proveLive(e,i,r,d.snapshotHash,()=>`Retry did not reach the destination`),await finishResolve(e,i,r,c,`applied`,l)}),{outcome:`retry`}})}const Hr=/\bINDEX\s+CONCURRENTLY\s+(?:IF\s+(?:NOT\s+)?EXISTS\s+)?(?!ON\b)(?:(?:"(?:[^"]|"")+"|[A-Za-z_][\w$]*)\s*\.\s*)?("(?:[^"]|"")+"|[A-Za-z_][\w$]*)/gi,Ur=/^_cc(?:new|old)\d*$/;async function repairInvalidIndexes(e,t,n,r){let i=n.flatMap(concurrentIndexNames);if(i.length!==0)for(let{table:n,index:a}of await readInvalidIndexes(e,t)){if(!i.some(e=>a===e||a.startsWith(e)&&Ur.test(a.slice(e.length))))continue;let o=r.tables.some(e=>e.name===n&&e.indexes.some(e=>e.name===a));await e._executeRaw(`${o?`REINDEX INDEX`:`DROP INDEX`} CONCURRENTLY ${qualifiedName(t,a)}`)}}function concurrentIndexNames(e){return[...e.matchAll(Hr)].map(([,e=``])=>e.startsWith(`"`)?e.slice(1,-1).replaceAll(`""`,`"`):e.toLowerCase())}async function finishResolve(e,t,n,r,i,a){let{marker:o}=await readCommandControl(e,t);if(i===`applied`&&a&&o?.stateId!==a){let i=parentTransition(n,r.fromState,a);await advanceMarker(e,t,n.estateHash,o,[...o?.path??[],{stateId:a,transitionHash:r.transitionHash??i.transitionHash,baselineBoundary:!1}],n.states.get(a).snapshotHash)}if(i===`rolled-back`&&o&&o.stateId===r.toState){let r=o.path.slice(0,-1);await advanceMarker(e,t,n.estateHash,o,r,snapshotHashOf(n,r.at(-1)?.stateId??null))}await appendLedger(e,t,ledgerEvent({attemptId:r.attemptId,kind:`resolved`,estateHash:n.estateHash,snapshotHash:snapshotHashOf(n,a),sqlHash:r.sqlHash,fromState:r.fromState,toState:a,transitionHash:r.transitionHash,direction:`resolve`,operationId:null,dispatchId:null,effectState:`none`}))}function snapshotHashOf(e,t){return t?e.states.get(t).snapshotHash:e.emptySnapshotHash}function prepareRollbackEdge(e,t,n,r){let i=e.states.get(r.stateId),a=i.parents.find(e=>e.transitionHash===r.transitionHash),o=e.sql.get(i.sqlHash),c=a.rollback;if(c.kind===`irreversible`)throw new f(c.reason,s.MIGRATION_DESTRUCTIVE_REJECTED);let l=c.kind===`manual`?c.requestedBoundary:null;return assertTransactionalBoundaryHonored(n,l),refuseSqliteStepwise(t,l,r.stateId),{edge:r,state:i,parent:a,blob:o,rollback:c,boundary:classifyStoredAtomicity(t,l,c.operations,o),nextState:a.fromState}}function previewRollbackEdge(e,t){let n=e.states.get(t.stateId),r=n?.parents.find(e=>e.transitionHash===t.transitionHash),i=n&&e.sql.get(n.sqlHash);if(!(r&&i))throw new f(`Rollback cannot find the arrival transition or its SQL`,s.MIGRATION_CORRUPTION);let{approvals:a,...o}=r;return{stateId:t.stateId,toState:r.fromState,sql:renderMigrationReview([{...o,originChecks:[],operations:[]}],[],i)}}function refusalOf(e){if(!(e instanceof f))throw e;return{code:e.code,message:e.message}}function admitRollbackAttempt(e){let t=unfinishedAttempts(e);if(t.length>1)throw new f(`Multiple unfinished migration attempts require manual repair`,s.MIGRATION_UNFINISHED_ATTEMPT);let n=t[0];if(n&&(n.kind!==`started`||n.direction!==`rollback`))throw new f(`An unfinished migration attempt is blocking ordinary work`,s.MIGRATION_UNFINISHED_ATTEMPT);return n}function assertResumesSelectedPath(e,t,n,r,i){let a=prepareRollbackAttempt(e,t,n,r);if(a.edge.stateId!==i.edge.stateId||a.nextState!==i.nextState||a.edge.transitionHash!==i.edge.transitionHash)throw new f(`An unfinished rollback does not match the selected reverse path`,s.MIGRATION_UNFINISHED_ATTEMPT)}function prepareRollbackAttempt(e,t,n,r){if(!(r.fromState&&r.transitionHash))throw new f(`Unfinished rollback is missing its authenticated edge identity`,s.MIGRATION_CORRUPTION);let i=prepareRollbackEdge(e,t,n,{stateId:r.fromState,transitionHash:r.transitionHash,baselineBoundary:!1});if(r.toState!==i.nextState||r.estateHash!==e.estateHash||r.snapshotHash!==i.state.snapshotHash||r.sqlHash!==i.state.sqlHash)throw new f(`Unfinished rollback does not match an authenticated estate edge`,s.MIGRATION_CORRUPTION);return i}async function executeRollbackEdge(e,t,n,r,i,a,o,c){let{edge:l,state:u,blob:d,rollback:p,boundary:m,nextState:h}=r;if(i.stateId!==l.stateId||i.path.at(-1)?.stateId!==l.stateId||i.path.at(-1)?.transitionHash!==l.transitionHash)throw new f(`Rollback marker does not name the authenticated edge being reversed`,s.MIGRATION_MARKER_CONFLICT);a||await assertAllChecks(e,d,u.destinationChecks,t.namespace,`Destination checks failed before rollback`);let g=attemptEvents(rollbackEventSeed(n,r),a?.attemptId);a||await appendLedger(e,t,g.event(`started`,`none`)),await executeOperations(e,d,a?remainingRollbackOperations(n,r,a,o):p.operations,m,(n,r,i)=>appendLedger(e,t,g.event(`step-confirmed`,r,n,i)),t.namespace,{fromState:l.stateId,toState:h}),await canonicalizeSqliteStorage(e,p.operations,c,requireStateSnapshot(n,h));let _=await proveRolledBack(e,t,n,r),v=await advanceMarker(e,t,n.estateHash,i,i.path.slice(0,-1),_);return await appendRolledBackEvent(e,t,n,r,g.attemptId),v}async function closeCompletedRollback(e,t,n,r,i,a,o){if(remainingRollbackOperations(n,r,i,a),o?o.stateId!==r.nextState:r.nextState!==null)throw new f(`Rollback marker is neither before nor after the unfinished edge`,s.MIGRATION_MARKER_CONFLICT);await proveRolledBack(e,t,n,r),await appendRolledBackEvent(e,t,n,r,i.attemptId)}async function proveRolledBack(e,t,n,{parent:r,blob:i,nextState:a}){await assertAllChecks(e,i,r.originChecks,t.namespace,`Origin checks failed after rollback`);let o=snapshotHashOf(n,a);return await proveLive(e,t,n,o,()=>`Rollback did not reach the parent snapshot`),o}function rollbackEventSeed(e,{edge:t,state:n,nextState:r}){return{estateHash:e.estateHash,snapshotHash:n.snapshotHash,sqlHash:n.sqlHash,fromState:t.stateId,toState:r,transitionHash:t.transitionHash,direction:`rollback`}}async function appendRolledBackEvent(e,t,n,r,i){await appendLedger(e,t,attemptEvents({...rollbackEventSeed(n,r),snapshotHash:snapshotHashOf(n,r.nextState)},i).event(`rolled-back`,`committed`))}function remainingRollbackOperations(e,t,n,r){return remainingSteps(r,n,{direction:`rollback`,estateHash:e.estateHash,fromState:t.edge.stateId,toState:t.nextState,transitionHash:t.edge.transitionHash,sqlHash:t.state.sqlHash,operations:t.rollback.operations,boundary:t.boundary},`Rollback`).operations}function assertReversibleEdge(e,t){let n=e.states.get(t.stateId);if(!n)throw new f(`Rollback target is missing from the estate`,s.MIGRATION_CORRUPTION);let r=n.parents.find(e=>e.transitionHash===t.transitionHash);if(!r)throw new f(`Rollback cannot find the arrival transition`,s.MIGRATION_CORRUPTION);if(r.rollback.kind===`irreversible`)throw new f(r.rollback.reason,s.MIGRATION_DESTRUCTIVE_REJECTED)}function assertExpectedRevision(e,t){if(!(t.expectRevision===void 0||e?.revision===t.expectRevision))throw new f(`down expected marker revision ${t.expectRevision}, but the marker is at revision ${e?.revision??`none`}: another command moved it`,s.MIGRATION_MARKER_CONFLICT)}async function approveRollbackLosses(e,t,n,r,i){let a=[];for(let i of r){if(!i.rollback.operations.some(e=>e.risk===`destructive`))continue;let{operations:r,ambiguousChanges:o}=await diff(requireStateSnapshot(n,i.edge.stateId),requireStateSnapshot(n,i.nextState));for(let n of[...r,...o.map(asDrop)])`tableName`in n&&isDestructiveOperation(n)&&await holdsRows(e,t,n.tableName)&&a.push(n)}a.length>0&&i&&await letLockGo(e),await approveDestructiveOperations(a,i,!1)}function asDrop(e){return e.type===`ambiguousTable`?{type:`dropTable`,tableName:e.droppedTable}:{type:`dropColumn`,tableName:e.tableName,columnName:e.droppedColumn.name}}async function holdsRows(e,t,n){return await isTableMissing(e,t,n)?!1:(await e._executeRaw(`SELECT 1 AS populated FROM ${qualifiedName(t,n)} LIMIT 1`)).rows.length>0}function refuseOpaqueEffect(e,t,n,r){let i=new Set(e.operations.flatMap(e=>e.steps.flatMap(n=>e.origin===`manual`&&n.retry===`opaque`&&concurrentIndexNames(sliceDispatch(t,n.execute)).length===0?[n.execute.dispatchId]:[]))),a=r.filter(e=>e.attemptId===n.attemptId&&e.kind===`step-confirmed`&&i.has(e.dispatchId??``)),o=new Map;for(let e of a)countUnanswered(o,e.dispatchId,e);let c=a.find(e=>e.effectState===`committed`)??a.find(e=>(o.get(e.dispatchId)??0)>0);if(c===void 0)return;let l=c.effectState===`committed`;throw new f(`resolve cannot mark this attempt rolled back: its opaque dispatch ${c.dispatchId} ${l?`committed`:`may have committed`} and nothing undid it. Finish the transition by hand and resolve({ outcome: "complete" }).`,l?s.MIGRATION_PARTIAL_EFFECT:s.MIGRATION_AMBIGUOUS_COMMIT,{meta:{...n.fromState?{fromState:n.fromState}:{},...n.toState?{toState:n.toState}:{},operationId:c.operationId??void 0,dispatchId:c.dispatchId??void 0,lastConfirmedStep:c.dispatchId??void 0,effectState:l?`committed`:`may-have-committed`,partial:!0}})}function rollbackSlice(e,t,n){if(t.path.length===0)throw new f(`Nothing to roll back`,s.MIGRATION_NOT_FOUND);let r=n.to?distanceTo(t.path.map(e=>e.stateId),resolveStateSelector(e,n.to)):n.steps,i=r===0?[]:t.path.slice(-r);if(i.some(e=>e.baselineBoundary))throw new f(`down cannot cross a baseline boundary`,s.MIGRATION_INVALID_STATE);return i}function distanceTo(e,t){let n=e.lastIndexOf(t);if(n<0)throw new f(`down target is not on the arrival path`,s.MIGRATION_NOT_FOUND);return e.length-1-n}const Wr=[`readEstate`,`listStates`,`listSnapshots`,`listSql`,`readState`,`readSnapshot`,`readSql`],Gr=[`publishEstate`,`publishSnapshot`,`publishSql`,`publishState`];function isMigrationStorageReader(e){return hasStorageMethods(e,Wr)}function isMigrationStorageWriter(e){return hasStorageMethods(e,Gr)}function hasStorageMethods(e,t){return e===null||typeof e!=`object`&&typeof e!=`function`?!1:t.every(t=>typeof Reflect.get(e,t)==`function`)}function createMigrationClient(e,t){let n=t===void 0?void 0:snapshotExactRecord(t,[`storage`,`tables`,`limits`],`migration client options`,refuseClientOptions),r=normalizeManagedTables(n?.tables),i=n?.limits===void 0?void 0:resolveMigrationLimits(n.limits),o=r===void 0&&i===void 0?e:{$driver:e.$driver,$schema:e.$schema,[yr]:r,[br]:i},s=Object.freeze({log:()=>logV1(o),push(e){return pushV1(o,e)}});if(n===void 0)return s;let c=n.storage;if(c===void 0)return r!==void 0||i!==void 0?s:refuseClientOptions(`migration client options must include storage, tables or limits when supplied`);let l;try{if(!isMigrationStorageReader(c))return refuseClientOptions(`migration client storage must implement MigrationStorageReader`);l=c}catch(e){return refuseClientOptions(`migration client storage could not be inspected`,a(e))}let u=Object.freeze({...s,check:()=>checkEstate(l),list:async()=>listMigrationStates(await loadMigrationGraph(l)),show:async e=>{let t=await loadMigrationGraph(l);return showMigrationState(t,resolveStateSelector(t,e))},graph:async()=>migrationGraphResult(await loadMigrationGraph(l)),status:()=>statusV1(o,l),verify:()=>verifyV1(o,l),apply:e=>applyV1(o,l,e),down:e=>downV1(o,l,e),baseline:e=>baselineV1(o,l,e),reanchor:e=>reanchorV1(o,l,e),prune:e=>pruneV1(l,e),resolve:e=>resolveV1(o,l,e)}),d;try{if(!isMigrationStorageWriter(l))return u;d=l}catch(e){return refuseClientOptions(`migration client storage could not be inspected`,a(e))}return Object.freeze({...u,generate:e=>generateV1(o,d,e),reset:e=>resetV1(o,d,e)})}function refuseClientOptions(e,t){throw new f(e,s.INVALID_INPUT,{cause:t})}export{sqliteDecimalStorageKind as $,qe as A,decimalConversionRequired as B,addDropResolver as C,encodeSqlBlob as D,rejectAllResolver as E,getSQLiteType as F,mysqlDecimalListFitsCheck as G,mysqlDecimalFitsCatalogCheck as H,mysqlEnumType as I,postgresDecimalFitsCheck as J,mysqlDecimalListMarker as K,mysqlStringLiteral as L,H as M,getMySQLType as N,derivedMigrationName as O,getPostgresType as P,sqliteDecimalCopyExpression as Q,parseMySqlEnumValues as R,isDestructiveOperation as S,lenientResolver as T,mysqlDecimalFitsCheck as U,describeDecimalStorageKind as V,mysqlDecimalListFitsCatalogCheck as W,readSqliteDecimalConstraint as X,readMysqlDecimalListMarker as Y,sqliteDecimalCheck as Z,foreignKeyPragmasCannotBeLifted as _,formatOperation as a,sqliteDefinitionKeywords as at,catalogCommitBoundaries as b,Z as c,readSqliteIdentifier as ct,sqliteDateTimeCopyExpression as d,Le as et,sqliteDateTimeTargetRequiresRecreation as f,throwIfCatalogRefusal as g,isSqliteStateControlDefinition as h,admitLiveMigrationCapability as i,sqliteGeoPointEncoding as it,U as j,applyNativeRename as k,sqliteCanonicalDateTimeExpression as l,skipSqlNonStructuralRegion as lt,MigrationDriver as m,renderMigrationReview as n,sqliteGeoPointCarrier as nt,loadMigrationGraph as o,sqliteTableDefinitions as ot,registerMigrationDriver as p,mysqlDecimalStorageKind as q,getPushMigrationDriver as r,sqliteGeoPointCheck as rt,auditStorage as s,isSqliteBareIdentifierCharacter as st,createMigrationClient as t,readSqliteGeoPointColumn as tt,sqliteCanonicalTimeExpression as u,V as ut,providerFacts as v,createPredefinedResolver as w,boundNamespace as x,tableRewrites as y,decimalConversionConstraintName as z};
|
|
49
|
+
//# sourceMappingURL=client-LCeQ2fk4.mjs.map
|