@amalgm/live 0.2.81-preview.47434148097 → 0.2.81-preview.47446204525

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.
@@ -1,5 +1,5 @@
1
1
  import { type ApplyBlocker, type ApplyDependency, type ApplyWindow, type EntityApplyRailOptions, type WindowMember } from './contracts.js';
2
- export type HeadOutcome = 'progress' | 'again' | {
2
+ export type HeadOutcome = 'progress' | {
3
3
  readonly kind: 'alone';
4
4
  readonly entityId: string;
5
5
  } | {
@@ -1 +1 @@
1
- var j=Object.defineProperty;var w=(l,e)=>j(l,"name",{value:e,configurable:!0});import{createApplyIntent as F,createApplyWindowIntent as x}from"./contracts.js";import{planSelectedEntityApply as E}from"./plans.js";import{Recovering as M}from"../faults/recover.js";import{groundMoved as O}from"../faults/classify.js";import{localWorkWins as S}from"../clash/local-work.js";import{selectEntityApply as P}from"./selection.js";import{isSettlement as W}from"./settling.js";import{revealOrder as D}from"./window.js";function q(l,e){return l.unit===null&&l.authorityId!==e}w(q,"stepsAside");const H=w(l=>l.kind==="captured-local"||l.kind==="rejudge","drops");function v(l){return l.kind==="retry"?{kind:"park",reason:l.reason??"machine truth is unsettled",releaseOnProgress:!1,report:!1}:l.kind==="dependency"?{kind:"park",reason:l.reason,releaseOnProgress:l.waitFor===void 0,report:!1,...l.waitFor?{dependency:l.waitFor}:{},...l.blocker?{blocker:l.blocker}:{},..."comparedAt"in l?{comparedAt:l.comparedAt}:{}}:l.kind==="conflict"?{kind:"park",reason:l.reason,releaseOnProgress:!0,report:!0}:null}w(v,"parkFor");async function B(l){try{return await l()}catch(e){return{kind:"park",reason:e instanceof Error?e.message:String(e),releaseOnProgress:!1,report:!O(e),cause:e}}}w(B,"outcomeOf");const I=w(l=>W(l.judgment)?{kind:"settled",settlement:l.judgment}:null,"settled");class C{static{w(this,"EntityApplyJourney")}#e;#a;#r;#n;constructor(e,t,i){this.#e=e,this.#a={sha256Hex:e.sha256Hex,loops:e.loops,deliveryPosition:e.deliveryPosition},this.#r=t,this.#n=i}targetOf(e){const t=e.members[0];return t===void 0?null:e.intent?.members.find(i=>i.entityId===t.work.entityId)?.throughSequence??(t.work.kept===null?t.work.records.at(-1)?.globalSequence:t.work.resolvedThrough)??null}async run(e,t){if(e.intent!==null)return this.#p(e,e.intent);const i={member:null};try{return await this.#d(e,t,i)}catch(a){if(i.member===null||this.#n())throw a;if(O(a))return{kind:"park",reason:a instanceof Error?a.message:String(a),releaseOnProgress:!1,report:!1};if(q(e,i.member.work.entityId))return this.alone(i.member);if(a instanceof M)return{kind:"park",reason:a.message,releaseOnProgress:!1,report:!1,dependency:{producer:"capability",entityIds:a.need.subject===null?[]:[a.need.subject.id]}};throw a}}async alone(e){const t=await this.#t(null,[e],[{kind:"settled",settlement:"waiting"}]);return t==="progress"?{kind:"alone",entityId:e.work.entityId}:t}async#d(e,t,i){const a=this.#e.newIntentId(),n=this.#e.now(),o=t(),s=new Map;for(const c of e.members){if(I(c))continue;const{work:f}=c,m=P(f,this.#a),b=F({attemptId:a,work:f,target:m.target,unit:e.unit,cutoff:e.cutoff,createdAt:n,emptied:f.entityId===o&&f.play==="enter"&&(m.target.result.type==="file.text"||m.target.result.type==="file.binary")}),k=E(f,m,this.#e.sha256Hex);s.set(f.entityId,{member:c,intent:b,plan:k,adapter:this.#e.effects.adapterFor(k.target.type),look:"safe"})}const{active:d,blocked:h}=await this.#o(e.members,s,"look",i);if(d.length===0)return h??"again";const g=d.flatMap(c=>s.get(c.work.entityId)??[]);if(g.length===0)return this.#t(null,d,d.map(c=>I(c)));const y=x({attemptId:a,authorityId:e.authorityId,unit:e.unit,cutoff:e.cutoff,createdAt:n,members:g.map(c=>c.intent)});try{const c=await this.#u(d,s,i),f=c.active.flatMap(r=>s.get(r.work.entityId)??[]);if(f.length===0)return await this.#e.effects.discard(y),c.active.length===0?c.blocked??"again":this.#t(null,c.active,c.active.map(r=>I(r)));const m=f.length===g.length?y:x({...y,members:f.map(r=>r.intent)}),b=await this.#e.effects.hold(m,f.map(r=>r.plan));let k,A;try{k=await this.#o(c.active,s,"final",i),A=await this.#c(m,k,s,t)}finally{b()}return k.unseen!==null&&k.active.length===0?this.#h(k.unseen):A}catch(c){throw await this.#e.effects.discard(y),c}}async#c(e,{active:t,blocked:i},a,n){const o=t.flatMap(r=>a.get(r.work.entityId)??[]);if(o.length===0)return await this.#e.effects.discard(e),t.length===0?i??"again":this.#t(null,t,t.map(r=>I(r)));const s=x({...e,members:o.map(r=>r.intent)}),d=o.filter(r=>r.look==="safe");if(d.length>0){if(this.#n()||o.some(p=>p.intent.emptied&&n()!==p.intent.entityId))return await this.#e.effects.discard(e),"again";const r=await this.#e.store.bindWindow(s);if(r)return await this.#e.effects.discard(e),r.kind==="stale"?"again":v({...r,comparedAt:this.#r()})}const h=new Map,g=new Map,y=w((r,p,u=null)=>{h.set(r,{kind:"owed",reason:p}),u!==null&&g.set(r,u)},"owe"),c=w(r=>v(r.kind==="dependency"?{...r,comparedAt:this.#r()}:r),"waitFrom"),{order:f,cycle:m}=D(d.map(r=>({entityId:r.intent.entityId,play:r.plan.play,type:r.plan.target.type,parentUUID:r.plan.target.parentUUID}))),b="its parent chain closes among the window's members";for(const r of m)y(r,b,{kind:"park",reason:b,releaseOnProgress:!1,report:!0});for(const r of f){const p=a.get(r),u=await p.adapter.apply.reveal(p.intent,p.plan);u&&y(r,u.reason,u.kind==="dependency"?c(u):null)}for(const r of o){const p=r.intent.entityId;if(h.has(p))continue;const u=await r.adapter.verify.verify(r.intent,r.plan);u.kind==="match"?h.set(p,{kind:"materialized"}):u.kind==="local-change"?y(p,"a person's version stands in its place"):u.kind==="rejudge"||u.kind==="missing-target"?y(p,u.kind):y(p,u.reason??u.kind,c(u))}const k=t.map(r=>I(r)??h.get(r.work.entityId));if(d.length>0)return this.#s(s,t,k,g);const A=await this.#s(null,t,k,g);return await this.#e.effects.discard(e),A}async#s(e,t,i,a){const n=await this.#t(e,t,i),o=i[0];return n!=="progress"||o.kind!=="owed"?n:{...a.get(t[0].work.entityId)??{kind:"park",reason:o.reason,releaseOnProgress:!1,report:!1,again:!0},advanced:t.filter((d,h)=>i[h].kind!=="owed").map(d=>d.work.entityId)}}async#o(e,t,i,a){const n=[];for(const o of e){const s=t.get(o.work.entityId);if(!s){n.push(o);continue}let d;try{d=await this.#i(s.intent)?{kind:"captured-local"}:i==="look"?await this.#f(s):await s.adapter.apply.guard(s.intent,s.plan,i)}catch(g){if(n.length>0&&!this.#n())return{active:n,blocked:null,unseen:null};throw a.member=o,g}if(d.kind==="local-change"||d.kind==="unsettled-ground")return{active:n,blocked:n.length===0?"again":null,unseen:s};if(H(d))return{active:n,blocked:n.length===0?"again":null,unseen:null};const h=v(d);if(h)return{active:n,blocked:h,unseen:null};s.look=d.kind,n.push(o)}return{active:n,blocked:null,unseen:null}}async#u(e,t,i){for(const[a,n]of e.entries()){const o=t.get(n.work.entityId);if(!(!o||o.look!=="safe"))try{const s=await o.adapter.apply.prepare(o.intent,o.plan);if(s)return{active:e.slice(0,a),blocked:v(s)}}catch(s){if(a>0&&!this.#n())return{active:e.slice(0,a),blocked:null};throw i.member=n,s}}return{active:[...e],blocked:null}}async#p(e,t){const i=t.members.map(n=>{const o=e.members.find(d=>d.work.entityId===n.entityId);if(!o)return null;const s=n.kept===null?o.work:{...o.work,records:[],kept:n.kept};return s.records.length===0&&s.kept===null?null:E(s,P(s,this.#a,n),this.#e.sha256Hex)}),a=await this.#e.effects.recover(t,i);if(a.length!==t.members.length)throw new Error("Apply recovery answered for a different window");return this.#t(t,e.members,e.members.map(n=>I(n)??a[t.members.findIndex(o=>o.entityId===n.work.entityId)]??{kind:"owed",reason:"not a member of the bound window"}))}async#t(e,t,i){const a=await this.#e.store.endWindow(e,t,i);if(!a)return"progress";if(a.kind!=="stale"||!a.reason)throw new Error("Apply end commit returned an unknown refusal");return"again"}async#i(e){return S(e.targetType,await this.#e.store.localWorkAfter(e.authorityId,e.entityId,e.kept??e.throughSequence))}async#f(e){const{intent:t,plan:i,adapter:a}=e,n=await a.apply.guard(t,i,"look");if(n.kind!=="local-change"&&n.kind!=="unsettled-ground")return n;const o=await this.#l(t,i);if(o.kind!=="observed")return o;const s=await a.apply.guard(t,i,"look");return s.kind==="local-change"||s.kind==="unsettled-ground"?{kind:"retry",reason:"Ground still needs observation after Detect; this member cannot reveal."}:s}async#h(e){const t=await this.#l(e.intent,e.plan);return t.kind==="captured-local"?"again":v(t.kind==="observed"?{kind:"retry",reason:"Its final guard found ground Detect had not recorded; it is judged again after Detect looks."}:t)}async#l(e,t){if(await this.#i(e))return{kind:"captured-local"};let i,a=!0;const n=await this.#e.effects.captureLocal(e,t,()=>{if(!a||i!==void 0)throw new Error("Apply capture comparison must be marked exactly once");i=this.#r()}).finally(()=>{a=!1});if(!n||!["settled","local-only","retry"].includes(n.kind))throw new Error("Apply capture returned no explicit observation outcome");if(await this.#i(e))return{kind:"captured-local"};if(n.kind==="retry")return n;if(n.kind==="local-only"){if(i===void 0)throw new Error("local-only capture requires a synchronous comparison fence");if(!n.reason||n.entityIds.length===0||n.entityIds.some(o=>!o))throw new Error("local-only capture must name the retained ground and its releasing condition");return{kind:"dependency",reason:n.reason,comparedAt:i,waitFor:{producer:"detect",entityIds:n.entityIds}}}return{kind:"observed"}}}export{C as EntityApplyJourney,B as outcomeOf,q as stepsAside};
1
+ var j=Object.defineProperty;var m=(l,e)=>j(l,"name",{value:e,configurable:!0});import{createApplyIntent as F,createApplyWindowIntent as O}from"./contracts.js";import{planSelectedEntityApply as P}from"./plans.js";import{Recovering as M}from"../faults/recover.js";import{groundMoved as S}from"../faults/classify.js";import{localWorkWins as W}from"../clash/local-work.js";import{selectEntityApply as E}from"./selection.js";import{isSettlement as q}from"./settling.js";import{revealOrder as D}from"./window.js";function H(l,e){return l.unit===null&&l.authorityId!==e}m(H,"stepsAside");const I={kind:"park",reason:"its window ended with its head unplaced and named no wait",releaseOnProgress:!1,report:!1,again:!0},U=m(l=>l.kind==="captured-local"||l.kind==="rejudge","drops");function A(l){return l.kind==="retry"?{kind:"park",reason:l.reason??"machine truth is unsettled",releaseOnProgress:!1,report:!1}:l.kind==="dependency"?{kind:"park",reason:l.reason,releaseOnProgress:l.waitFor===void 0,report:!1,...l.waitFor?{dependency:l.waitFor}:{},...l.blocker?{blocker:l.blocker}:{},..."comparedAt"in l?{comparedAt:l.comparedAt}:{}}:l.kind==="conflict"?{kind:"park",reason:l.reason,releaseOnProgress:!0,report:!0}:null}m(A,"parkFor");async function B(l){try{return await l()}catch(e){return{kind:"park",reason:e instanceof Error?e.message:String(e),releaseOnProgress:!1,report:!S(e),cause:e}}}m(B,"outcomeOf");const v=m(l=>q(l.judgment)?{kind:"settled",settlement:l.judgment}:null,"settled");class C{static{m(this,"EntityApplyJourney")}#e;#r;#a;#n;constructor(e,t,i){this.#e=e,this.#r={sha256Hex:e.sha256Hex,loops:e.loops,deliveryPosition:e.deliveryPosition},this.#a=t,this.#n=i}targetOf(e){const t=e.members[0];return t===void 0?null:e.intent?.members.find(i=>i.entityId===t.work.entityId)?.throughSequence??(t.work.kept===null?t.work.records.at(-1)?.globalSequence:t.work.resolvedThrough)??null}async run(e,t){if(e.intent!==null)return this.#p(e,e.intent);const i={member:null};try{return await this.#d(e,t,i)}catch(a){if(i.member===null||this.#n())throw a;if(S(a))return{kind:"park",reason:a instanceof Error?a.message:String(a),releaseOnProgress:!1,report:!1};if(H(e,i.member.work.entityId))return this.alone(i.member);if(a instanceof M)return{kind:"park",reason:a.message,releaseOnProgress:!1,report:!1,dependency:{producer:"capability",entityIds:a.need.subject===null?[]:[a.need.subject.id]}};throw a}}async alone(e){const{target:t}=E(e.work,this.#r),i=await this.#i({authorityId:e.work.authorityId,entityId:e.work.entityId,targetType:t.result.type,kept:t.record===null?t.result:null,throughSequence:t.throughSequence}),a=await this.#t(null,[e],[{kind:"settled",settlement:i?"superseded":"waiting"}]);return a==="progress"&&!i?{kind:"alone",entityId:e.work.entityId}:a}async#d(e,t,i){const a=this.#e.newIntentId(),n=this.#e.now(),o=t(),s=new Map;for(const c of e.members){if(v(c))continue;const{work:f}=c,w=E(f,this.#r),b=F({attemptId:a,work:f,target:w.target,unit:e.unit,cutoff:e.cutoff,createdAt:n,emptied:f.entityId===o&&f.play==="enter"&&(w.target.result.type==="file.text"||w.target.result.type==="file.binary")}),k=P(f,w,this.#e.sha256Hex);s.set(f.entityId,{member:c,intent:b,plan:k,adapter:this.#e.effects.adapterFor(k.target.type),look:"safe"})}const{active:d,blocked:h}=await this.#o(e.members,s,"look",i);if(d.length===0)return h??I;const g=d.flatMap(c=>s.get(c.work.entityId)??[]);if(g.length===0)return this.#t(null,d,d.map(c=>v(c)));const y=O({attemptId:a,authorityId:e.authorityId,unit:e.unit,cutoff:e.cutoff,createdAt:n,members:g.map(c=>c.intent)});try{const c=await this.#u(d,s,i),f=c.active.flatMap(r=>s.get(r.work.entityId)??[]);if(f.length===0)return await this.#e.effects.discard(y),c.active.length===0?c.blocked??I:this.#t(null,c.active,c.active.map(r=>v(r)));const w=f.length===g.length?y:O({...y,members:f.map(r=>r.intent)}),b=await this.#e.effects.hold(w,f.map(r=>r.plan));let k,x;try{k=await this.#o(c.active,s,"final",i),x=await this.#c(w,k,s,t)}finally{b()}return k.unseen!==null&&k.active.length===0?this.#h(k.unseen):x}catch(c){throw await this.#e.effects.discard(y),c}}async#c(e,{active:t,blocked:i},a,n){const o=t.flatMap(r=>a.get(r.work.entityId)??[]);if(o.length===0)return await this.#e.effects.discard(e),t.length===0?i??I:this.#t(null,t,t.map(r=>v(r)));const s=O({...e,members:o.map(r=>r.intent)}),d=o.filter(r=>r.look==="safe");if(d.length>0){if(this.#n()||o.some(p=>p.intent.emptied&&n()!==p.intent.entityId))return await this.#e.effects.discard(e),I;const r=await this.#e.store.bindWindow(s);if(r)return await this.#e.effects.discard(e),r.kind==="stale"?I:A({...r,comparedAt:this.#a()})}const h=new Map,g=new Map,y=m((r,p,u=null)=>{h.set(r,{kind:"owed",reason:p}),u!==null&&g.set(r,u)},"owe"),c=m(r=>A(r.kind==="dependency"?{...r,comparedAt:this.#a()}:r),"waitFrom"),{order:f,cycle:w}=D(d.map(r=>({entityId:r.intent.entityId,play:r.plan.play,type:r.plan.target.type,parentUUID:r.plan.target.parentUUID}))),b="its parent chain closes among the window's members";for(const r of w)y(r,b,{kind:"park",reason:b,releaseOnProgress:!1,report:!0});for(const r of f){const p=a.get(r),u=await p.adapter.apply.reveal(p.intent,p.plan);u&&y(r,u.reason,u.kind==="dependency"?c(u):null)}for(const r of o){const p=r.intent.entityId;if(h.has(p))continue;const u=await r.adapter.verify.verify(r.intent,r.plan);u.kind==="match"?h.set(p,{kind:"materialized"}):u.kind==="local-change"?y(p,"a person's version stands in its place"):u.kind==="rejudge"||u.kind==="missing-target"?y(p,u.kind):y(p,u.reason??u.kind,c(u))}const k=t.map(r=>v(r)??h.get(r.work.entityId));if(d.length>0)return this.#s(s,t,k,g);const x=await this.#s(null,t,k,g);return await this.#e.effects.discard(e),x}async#s(e,t,i,a){const n=await this.#t(e,t,i),o=i[0];return n!=="progress"||o.kind!=="owed"?n:{...a.get(t[0].work.entityId)??{kind:"park",reason:o.reason,releaseOnProgress:!1,report:!1,again:!0},advanced:t.filter((d,h)=>i[h].kind!=="owed").map(d=>d.work.entityId)}}async#o(e,t,i,a){const n=[];for(const o of e){const s=t.get(o.work.entityId);if(!s){n.push(o);continue}let d;try{d=await this.#i(s.intent)?{kind:"captured-local"}:i==="look"?await this.#f(s):await s.adapter.apply.guard(s.intent,s.plan,i)}catch(g){if(n.length>0&&!this.#n())return{active:n,blocked:null,unseen:null};throw a.member=o,g}if(d.kind==="local-change"||d.kind==="unsettled-ground")return{active:n,blocked:n.length===0?I:null,unseen:s};if(U(d))return{active:n,blocked:n.length===0?I:null,unseen:null};const h=A(d);if(h)return{active:n,blocked:h,unseen:null};s.look=d.kind,n.push(o)}return{active:n,blocked:null,unseen:null}}async#u(e,t,i){for(const[a,n]of e.entries()){const o=t.get(n.work.entityId);if(!(!o||o.look!=="safe"))try{const s=await o.adapter.apply.prepare(o.intent,o.plan);if(s)return{active:e.slice(0,a),blocked:A(s)}}catch(s){if(a>0&&!this.#n())return{active:e.slice(0,a),blocked:null};throw i.member=n,s}}return{active:[...e],blocked:null}}async#p(e,t){const i=t.members.map(n=>{const o=e.members.find(d=>d.work.entityId===n.entityId);if(!o)return null;const s=n.kept===null?o.work:{...o.work,records:[],kept:n.kept};return s.records.length===0&&s.kept===null?null:P(s,E(s,this.#r,n),this.#e.sha256Hex)}),a=await this.#e.effects.recover(t,i);if(a.length!==t.members.length)throw new Error("Apply recovery answered for a different window");return this.#t(t,e.members,e.members.map(n=>v(n)??a[t.members.findIndex(o=>o.entityId===n.work.entityId)]??{kind:"owed",reason:"not a member of the bound window"}))}async#t(e,t,i){const a=await this.#e.store.endWindow(e,t,i);if(!a)return"progress";if(a.kind!=="stale"||!a.reason)throw new Error("Apply end commit returned an unknown refusal");return I}async#i(e){return W(e.targetType,await this.#e.store.localWorkAfter(e.authorityId,e.entityId,e.kept??e.throughSequence))}async#f(e){const{intent:t,plan:i,adapter:a}=e,n=await a.apply.guard(t,i,"look");if(n.kind!=="local-change"&&n.kind!=="unsettled-ground")return n;const o=await this.#l(t,i);if(o.kind!=="observed")return o;const s=await a.apply.guard(t,i,"look");return s.kind==="local-change"||s.kind==="unsettled-ground"?{kind:"retry",reason:"Ground still needs observation after Detect; this member cannot reveal."}:s}async#h(e){const t=await this.#l(e.intent,e.plan);return t.kind==="captured-local"?I:A(t.kind==="observed"?{kind:"retry",reason:"Its final guard found ground Detect had not recorded; it is judged again after Detect looks."}:t)}async#l(e,t){if(await this.#i(e))return{kind:"captured-local"};let i,a=!0;const n=await this.#e.effects.captureLocal(e,t,()=>{if(!a||i!==void 0)throw new Error("Apply capture comparison must be marked exactly once");i=this.#a()}).finally(()=>{a=!1});if(!n||!["settled","local-only","retry"].includes(n.kind))throw new Error("Apply capture returned no explicit observation outcome");if(await this.#i(e))return{kind:"captured-local"};if(n.kind==="retry")return n;if(n.kind==="local-only"){if(i===void 0)throw new Error("local-only capture requires a synchronous comparison fence");if(!n.reason||n.entityIds.length===0||n.entityIds.some(o=>!o))throw new Error("local-only capture must name the retained ground and its releasing condition");return{kind:"dependency",reason:n.reason,comparedAt:i,waitFor:{producer:"detect",entityIds:n.entityIds}}}return{kind:"observed"}}}export{C as EntityApplyJourney,B as outcomeOf,H as stepsAside};
@@ -1 +1 @@
1
- var I=Object.defineProperty;var a=(o,t)=>I(o,"name",{value:t,configurable:!0});import{UUID_PATTERN as u}from"../entities/types.js";import{FetchAhead as k}from"./fetch-ahead.js";import{EntityApplyJourney as b,outcomeOf as w,stepsAside as E}from"./journey.js";import{assertApplyLaneStep as P,createApplyLane as v}from"./lane.js";import{assertApplyDependency as O,assertApplyLineStep as $,createApplyLine as S,heldWait as c,releaseApplyLine as q}from"./line.js";const M=8,x=1e3,g=3e4;function _(o,t){return t.cause===void 0&&E(o,o.members[0].work.entityId)}a(_,"stuck");class j{static{a(this,"EntityApplyRail")}#t;#g;#P;#x;#_;#o;#v;#a=!1;#e=!1;#d=new Map;#s=new Map;#l={queue:[],steps:new Set};#u={queue:[],steps:new Set};#n=!1;#h=null;#p=1/0;#m=[];#A=0;#O=new Map;#y=null;constructor(t){this.#t=t,this.#g=t.concurrency??M,this.#P=t.laneConcurrency??this.#g,this.#x=t.onBackgroundError??(()=>{}),this.#_=t.onIdle??(()=>{});for(const[e,s]of[["concurrency",this.#g],["lane concurrency",this.#P]])if(!Number.isSafeInteger(s)||s<1)throw new Error(`entity Apply ${e} must be a positive integer`);this.#o=new b(t,()=>this.#A,()=>this.#e),this.#v=new k(t.cargo,{sha256Hex:t.sha256Hex,loops:t.loops,deliveryPosition:t.deliveryPosition})}async start(){if(this.#a)throw new Error("entity Apply rail already started");if(this.#e)throw new Error("entity Apply rail is stopped");this.#a=!0;const t=await this.#t.store.readOpenUnits();if(!Array.isArray(t)||new Set(t).size!==t.length||t.some(e=>!u.test(e)))throw new Error("entity Apply store returned an invalid open unit list");for(const e of t)this.#b(e,null);await this.#R()}fetch(t,e){return this.#a?this.#e?Promise.reject(new Error("entity Apply rail is stopped")):u.test(t)?!Number.isFinite(e.stall)||e.stall<0?Promise.reject(new Error("entity Apply fetch needs a non-negative stall")):e.emptied!==void 0&&typeof e.emptied!="boolean"?Promise.reject(new Error("entity Apply fetch emptied must be a boolean")):new Promise((s,i)=>{const r=this.#b(t,null,e.emptied===!0),n=a(()=>this.#t.schedule.schedule(e.stall,()=>{r.waiters.delete(l)&&(r.emptied&&![...r.waiters].some(d=>d.emptied)&&(r.emptied=!1),s(this.#G(r)))}),"arm");let h=n();const l={emptied:e.emptied===!0,answer:a(d=>{h.cancel(),s(d)},"answer"),fail:a(d=>{h.cancel(),i(d)},"fail"),moved:a(()=>{h.cancel(),h=n()},"moved")};r.waiters.add(l),r.waitsOn===null&&this.#N(r),this.#r()}):Promise.reject(new Error("entity Apply fetch needs a unit UUID")):Promise.reject(new Error("entity Apply rail has not started"))}progressed(t,e){if(!u.test(t))throw new Error("entity Apply progress needs a unit UUID");if(!Number.isSafeInteger(e)||e<0)throw new Error("entity Apply progress needs a byte count");e>0&&!this.#e&&this.#E(t)}recordsAvailable(){this.#I()}localStateChanged(t){this.#c("detect",t),this.#c("apply",t),this.#I()}sendAccepted(t){this.#c("send",t),this.#I()}capabilityChanged(t){this.#c("capability",t),this.#I()}owe(t){if(t.some(e=>!u.test(e)))throw new Error("entity Apply owe needs entity UUIDs");if(!(!this.#a||this.#e)){for(const e of t)this.#$(e);this.#r()}}#I(){!this.#a||this.#e||(this.#n=!0,this.#r())}waiting(){return this.#w().flatMap(t=>c(t.held,p(t))??[])}async flush(){if(!this.#a)throw new Error("entity Apply rail has not started");this.#e||await this.#R()}async stop(){if(this.#e)return;this.#e=!0,this.#M();for(const e of[this.#l,this.#u])for(const s of e.queue.splice(0))s.queued=!1;const t=new Error("entity Apply rail stopped before the fetch answered");for(const e of this.#s.values())for(const s of e.waiters)s.fail(t);for(this.#s.clear();this.#B()>0||this.#h;)await Promise.allSettled([...this.#l.steps,...this.#u.steps,...this.#h?[this.#h]:[]]);await this.#v.stop();for(const e of this.#m.splice(0))e.resolve()}#R(){return new Promise((t,e)=>{this.#m.push({resolve:t,reject:e}),this.#n=!0,this.#r()})}#r(){if(!this.#e){if(this.#n&&this.#h===null){this.#n=!1;const t=this.#F();this.#h=t,t.then(()=>{this.#h=null,this.#r()})}for(const[t,e]of[[this.#u,this.#P],[this.#l,this.#g]])for(;t.steps.size<e&&t.queue.length>0;){const s=t.queue.shift();s.queued=!1,this.#W(s,t)}if(this.#B()===0&&this.#h===null&&!this.#n&&this.#l.queue.length===0&&this.#u.queue.length===0){if(this.#O.clear(),this.#D(this.#t.now())){this.#r();return}this.#q();for(const t of this.#m.splice(0))t.resolve();this.#_()}}}#B(){return this.#l.steps.size+this.#u.steps.size}#w(){return[...this.#d.values(),...this.#s.values()]}#k(t){return t.kind==="line"?this.#d.get(t.authorityId)===t:this.#s.get(t.unit)===t}#i(t){if(!this.#e){if(t.running){t.again=!0;return}t.queued||(t.queued=!0,(t.kind==="line"?this.#l:this.#u).queue.push(t))}}#W(t,e){t.running=!0,t.again=!1;const s=(t.kind==="line"?this.#J(t):this.#H(t)).then(i=>{t.running=!1,e.steps.delete(s),(i||t.again)&&this.#k(t)&&(t.again=!1,this.#i(t)),this.#r()});e.steps.add(s)}async#F(){try{const t=await this.#t.store.readApplyAuthorities();if(!Array.isArray(t)||new Set(t).size!==t.length||t.some(s=>typeof s!="string"||s.length===0))throw new Error("entity Apply store returned an invalid authority list");this.#p=1/0;const e=new Set(t);for(const[s,i]of this.#d)!e.has(s)&&!i.running&&!i.queued&&this.#d.delete(s);for(const s of t){let i=this.#d.get(s);i||(i=S(s),this.#d.set(s,i)),this.#i(i)}}catch(t){this.#p=this.#t.now()+g;const e=this.#m.splice(0);e.length===0&&this.#S(t);for(const s of e)s.reject(t)}}async#J(t){try{const e=t.held;if(e&&e.entityId===null&&!e.due&&e.notBefore>this.#t.now())return!1;const s=this.#A,i=await this.#t.store.readApplyWindow(t.authorityId);return $(t.authorityId,i),this.#e?!1:i.kind==="end"?(t.held=null,!1):(i.window.deliverySequence!==null&&this.#v.advance(t.authorityId,i.window.deliverySequence),await this.#U(t,i.window,s))}catch(e){return this.#Y(t,e),!1}}async#H(t){try{const e=t.held;if(e&&e.entityId===null&&!e.due&&e.notBefore>this.#t.now())return!1;const s=this.#A,i=await this.#t.store.readFetchWindow(t.unit,t.toPrefix?null:t.through);if(P(t.unit,i),this.#e||!this.#k(t))return!1;if(t.waitsOn=null,i.kind==="unseen")return this.#L(t,{producer:"detect",entityIds:[t.unit]},i.reason,s);if(!t.again&&(i.kind!=="window"||i.window.intent===null)&&(t.toPrefix=!1),t.through!==null&&i.through>t.through&&t.met.clear(),t.through=Math.max(t.through??0,i.through),i.kind!=="window"&&(t.held=null),t.again&&(i.kind==="end"||i.kind==="nowhere"))return!0;switch(i.kind){case"end":return this.#f(t,{kind:"placed"}),!1;case"nowhere":return this.#f(t,{kind:"nowhere",reason:i.reason}),!1;case"root":return await this.#V(t,i.through,i.reason);case"prerequisite":return this.#X(t,i.unit,i.reason,s);case"window":return await this.#U(t,i.window,s)}}catch(e){return this.#Y(t,e),!1}}async#V(t,e,s){return t.met.has(t.unit)?(this.#f(t,{kind:"held",unit:t.unit,reason:`${t.unit} entered and still not held: ${s}`}),!1):(await this.#t.effects.enterRoot(t.unit,e),this.#e||!this.#k(t)?!1:(t.through===e&&t.met.add(t.unit),this.#E(t.unit),!0))}#$(t){const e=this.#b(t,null);e.toPrefix=!0,e.met.clear(),this.#i(e)}#b(t,e,s=!1){let i=this.#s.get(t);return i?e!==null&&(i.through===null||i.through<e)&&(i.through=e,i.met.clear(),this.#i(i)):(i=v(t,e,s),this.#s.set(t,i),this.#i(i)),i}#X(t,e,s,i){return t.met.has(e)?(this.#f(t,{kind:"held",unit:e,reason:`${e} placed and still needed: ${s}`}),!1):this.#T(t,e,s)?this.#L(t,{producer:"apply",entityIds:[e]},s,i):!1}#L(t,e,s,i){return t.held={entityId:null,target:null,kept:null,cutoff:null,attempt:1,notBefore:1/0,releaseOnProgress:!1,due:this.#z(e,i),reason:s,dependency:e},t.held.due}#N(t){const e=t.held;if(e?.dependency?.producer==="apply"){for(const s of e.dependency.entityIds)if(s!==t.unit&&!t.met.has(s)&&!this.#T(t,s,e.reason))return}}#T(t,e,s){const i=[t];let r=this.#s.get(e);for(;r&&r!==t&&!i.includes(r);)i.push(r),r=r.waitsOn===null?void 0:this.#s.get(r.waitsOn);if(r===t){for(const n of i)this.#f(n,{kind:"held",unit:e,reason:`prerequisite cycle through ${e}: ${s}`});return!1}return t.waitsOn??=e,this.#i(this.#b(e,t.through)),!0}#f(t,e){if(!this.#k(t))return;for(const i of t.waiters)i.answer(e);t.waiters.clear(),t.waitsOn=null,(e.kind==="placed"||t.held?.entityId==null)&&this.#s.delete(t.unit);const s=e.kind==="placed"||e.kind==="held"?e:{kind:"held",unit:t.unit,reason:`${t.unit} is nowhere here: ${e.reason}`};for(const i of[...this.#s.values()])if(i.waitsOn===t.unit){if(e.kind!=="placed"){this.#f(i,s);continue}i.met.add(t.unit)}e.kind==="placed"&&(this.#E(t.unit),this.#c("apply",[t.unit]))}#E(t){const e=new Map([[t,!0]]);for(const s of this.#s.values()){const i=new Set;let r=s.unit;for(;r!==null&&!e.has(r)&&!i.has(r);)i.add(r),r=this.#s.get(r)?.waitsOn??null;const n=r!==null&&e.get(r)===!0;for(const h of i)e.set(h,n);if(n)for(const h of s.waiters)h.moved()}}#G(t){let e=t;const s=new Set([t]);for(let i=t.waitsOn===null?void 0:this.#s.get(t.waitsOn);i&&!s.has(i);i=i.waitsOn===null?void 0:this.#s.get(i.waitsOn))s.add(i),e=i;return{kind:"held",unit:e.unit,reason:e.held?.reason??"still placing"}}async#U(t,e,s){const i=e.members[0]?.work.entityId??null;if(t.held&&t.held.entityId!==null&&t.held.entityId!==i&&(t.held=null),await this.#Q(t,e))return!1;let r=await w(()=>this.#o.run(e,()=>t.kind==="lane"&&t.emptied?t.unit:null));if(t.kind==="line"&&typeof r=="object"&&r.kind==="park"&&_(e,r)&&(r=await w(()=>this.#o.alone(e.members[0]))),r==="progress"||typeof r=="object"&&r.kind==="alone"){if(t.kind==="line")for(const n of e.members)(n.judgment==="waiting"||r!=="progress"&&n.work.entityId===r.entityId)&&this.#$(n.work.entityId);for(const n of e.members)n.unseen!==void 0&&this.#$(n.unseen);return this.#Z(t,r==="progress"?e.members.map(n=>n.work.entityId):[r.entityId])}return r==="again"?(t.held?.entityId===i&&(t.held=null),!0):(r.advanced?.length&&this.#j(t,r.advanced),this.#tt(t,e,r,s),t.kind==="lane"&&this.#N(t),t.held.due)}#K(t,e){const s=t.held,i=e.members[0].work.entityId;return(s?.entityId===i&&s.target===this.#o.targetOf(e)?s.attempt:0)+1}async#Q(t,e){const s=t.held,i=e.members[0];return!s||i===void 0||s.entityId!==i.work.entityId||s.due||s.notBefore<=this.#t.now()||this.#o.targetOf(e)!==s.target||e.cutoff!==s.cutoff?!1:await this.#t.store.localWorkAfter(e.authorityId,i.work.entityId,s.kept??s.target)===null}#Z(t,e){return t.held&&(t.held.entityId===null||e.includes(t.held.entityId))&&(t.held=null),this.#j(t,e),!0}#j(t,e){t.kind==="lane"&&(this.#n=!0,this.#E(t.unit)),this.#c("apply",e);for(const s of this.#w())s!==t&&s.held?.releaseOnProgress&&!s.held.due&&(s.held.due=!0,this.#i(s))}#tt(t,e,s,i){if(s.dependency&&O(s.dependency),s.blocker&&!s.dependency)throw new Error("Apply blocker must name the dependency that releases it");const r=e.members[0].work.entityId,n=t.held,h=this.#K(t,e),l=this.#C(h),d=s.again===!0&&h===1,y={entityId:r,target:this.#o.targetOf(e),kept:e.members[0].work.kept,cutoff:e.cutoff,attempt:h,notBefore:s.dependency?1/0:this.#t.now()+(d?0:l),releaseOnProgress:s.releaseOnProgress,due:s.dependency?this.#z(s.dependency,s.comparedAt??i):d,reason:s.reason,...s.dependency?{dependency:s.dependency}:{},...s.blocker?{blocker:s.blocker}:{}};t.held=y,this.#q();const A=c(n,p(t)),f=c(y,p(t));f&&JSON.stringify(f)!==JSON.stringify(A)&&this.#t.onWaiting?.(f),!(!s.report&&(s.dependency!==void 0||h===1))&&this.#S(new Error(`${m(t)} holds at ${r}, which ${s.releaseOnProgress?"is parked on a conflict":s.report?"failed":s.again?"keeps ending unplaced":"stands on ground that keeps moving"}, and will retry in ${l}ms (attempt ${h}): ${s.reason}`,s.cause===void 0?void 0:{cause:s.cause}))}#Y(t,e){if(t.kind==="lane"){for(const h of t.waiters)h.fail(e);t.waiters.clear()}const s=t.held,i=(s?.entityId===null?s.attempt:0)+1,r=this.#C(i),n=e instanceof Error?e.message:String(e);t.held={entityId:null,target:null,kept:null,cutoff:null,attempt:i,notBefore:this.#t.now()+r,releaseOnProgress:!1,due:!1,reason:n},this.#q(),this.#S(new Error(`${m(t)} faulted and will retry in ${r}ms (attempt ${i}): ${n}`,{cause:e}))}#S(t){try{this.#x(t)}catch{}}#C(t){const e=Math.min(g,x*2**Math.min(t-1,16)),s=Math.max(0,Math.min(1,this.#t.schedule.random()));return Math.round(e*(.5+s))}#c(t,e){const s=++this.#A;for(const i of e??["*"])this.#O.set(`${t}:${i}`,s);for(const i of this.#w())q(i,t,e)&&this.#i(i)}#z(t,e){return["*",...t.entityIds].some(s=>(this.#O.get(`${t.producer}:${s}`)??0)>e)}#q(){if(this.#e)return;let t=this.#p;for(const i of this.#w())i.held&&!i.held.due&&(t=Math.min(t,i.held.notBefore));if(t===1/0){this.#M();return}if(this.#y?.dueAt===t)return;this.#M();const e=Math.max(0,t-this.#t.now()),s=this.#t.schedule.schedule(e,()=>{this.#y=null,this.#D(t),this.#r()});this.#y={dueAt:t,cancel:a(()=>s.cancel(),"cancel")}}#D(t){let e=!1;for(const s of this.#w())s.held&&!s.held.due&&s.held.notBefore<=t&&(s.held.due=!0,this.#i(s),e=!0);return this.#p<=t&&(this.#p=1/0,this.#n=!0,e=!0),e}#M(){this.#y?.cancel(),this.#y=null}}const p=a(o=>o.kind==="line"?o.authorityId:o.unit,"owner"),m=a(o=>o.kind==="line"?`entity Apply line ${o.authorityId}`:`entity Apply fetch of ${o.unit}`,"label");export{M as ENTITY_APPLY_DEFAULT_CONCURRENCY,x as ENTITY_APPLY_RETRY_BASE_MS,g as ENTITY_APPLY_RETRY_MAX_MS,j as EntityApplyRail};
1
+ var I=Object.defineProperty;var a=(o,t)=>I(o,"name",{value:t,configurable:!0});import{UUID_PATTERN as u}from"../entities/types.js";import{FetchAhead as k}from"./fetch-ahead.js";import{EntityApplyJourney as b,outcomeOf as w,stepsAside as E}from"./journey.js";import{assertApplyLaneStep as P,createApplyLane as v}from"./lane.js";import{assertApplyDependency as O,assertApplyLineStep as $,createApplyLine as S,heldWait as c,releaseApplyLine as q}from"./line.js";const M=8,x=1e3,g=3e4;function _(o,t){return t.cause===void 0&&E(o,o.members[0].work.entityId)}a(_,"stuck");class j{static{a(this,"EntityApplyRail")}#t;#g;#P;#x;#_;#o;#v;#a=!1;#e=!1;#d=new Map;#s=new Map;#l={queue:[],steps:new Set};#u={queue:[],steps:new Set};#n=!1;#h=null;#p=1/0;#m=[];#A=0;#O=new Map;#y=null;constructor(t){this.#t=t,this.#g=t.concurrency??M,this.#P=t.laneConcurrency??this.#g,this.#x=t.onBackgroundError??(()=>{}),this.#_=t.onIdle??(()=>{});for(const[e,s]of[["concurrency",this.#g],["lane concurrency",this.#P]])if(!Number.isSafeInteger(s)||s<1)throw new Error(`entity Apply ${e} must be a positive integer`);this.#o=new b(t,()=>this.#A,()=>this.#e),this.#v=new k(t.cargo,{sha256Hex:t.sha256Hex,loops:t.loops,deliveryPosition:t.deliveryPosition})}async start(){if(this.#a)throw new Error("entity Apply rail already started");if(this.#e)throw new Error("entity Apply rail is stopped");this.#a=!0;const t=await this.#t.store.readOpenUnits();if(!Array.isArray(t)||new Set(t).size!==t.length||t.some(e=>!u.test(e)))throw new Error("entity Apply store returned an invalid open unit list");for(const e of t)this.#b(e,null);await this.#R()}fetch(t,e){return this.#a?this.#e?Promise.reject(new Error("entity Apply rail is stopped")):u.test(t)?!Number.isFinite(e.stall)||e.stall<0?Promise.reject(new Error("entity Apply fetch needs a non-negative stall")):e.emptied!==void 0&&typeof e.emptied!="boolean"?Promise.reject(new Error("entity Apply fetch emptied must be a boolean")):new Promise((s,i)=>{const r=this.#b(t,null,e.emptied===!0),n=a(()=>this.#t.schedule.schedule(e.stall,()=>{r.waiters.delete(l)&&(r.emptied&&![...r.waiters].some(d=>d.emptied)&&(r.emptied=!1),s(this.#G(r)))}),"arm");let h=n();const l={emptied:e.emptied===!0,answer:a(d=>{h.cancel(),s(d)},"answer"),fail:a(d=>{h.cancel(),i(d)},"fail"),moved:a(()=>{h.cancel(),h=n()},"moved")};r.waiters.add(l),r.waitsOn===null&&this.#N(r),this.#r()}):Promise.reject(new Error("entity Apply fetch needs a unit UUID")):Promise.reject(new Error("entity Apply rail has not started"))}progressed(t,e){if(!u.test(t))throw new Error("entity Apply progress needs a unit UUID");if(!Number.isSafeInteger(e)||e<0)throw new Error("entity Apply progress needs a byte count");e>0&&!this.#e&&this.#E(t)}recordsAvailable(){this.#I()}localStateChanged(t){this.#c("detect",t),this.#c("apply",t),this.#I()}sendAccepted(t){this.#c("send",t),this.#I()}capabilityChanged(t){this.#c("capability",t),this.#I()}owe(t){if(t.some(e=>!u.test(e)))throw new Error("entity Apply owe needs entity UUIDs");if(!(!this.#a||this.#e)){for(const e of t)this.#$(e);this.#r()}}#I(){!this.#a||this.#e||(this.#n=!0,this.#r())}waiting(){return this.#w().flatMap(t=>c(t.held,p(t))??[])}async flush(){if(!this.#a)throw new Error("entity Apply rail has not started");this.#e||await this.#R()}async stop(){if(this.#e)return;this.#e=!0,this.#M();for(const e of[this.#l,this.#u])for(const s of e.queue.splice(0))s.queued=!1;const t=new Error("entity Apply rail stopped before the fetch answered");for(const e of this.#s.values())for(const s of e.waiters)s.fail(t);for(this.#s.clear();this.#B()>0||this.#h;)await Promise.allSettled([...this.#l.steps,...this.#u.steps,...this.#h?[this.#h]:[]]);await this.#v.stop();for(const e of this.#m.splice(0))e.resolve()}#R(){return new Promise((t,e)=>{this.#m.push({resolve:t,reject:e}),this.#n=!0,this.#r()})}#r(){if(!this.#e){if(this.#n&&this.#h===null){this.#n=!1;const t=this.#F();this.#h=t,t.then(()=>{this.#h=null,this.#r()})}for(const[t,e]of[[this.#u,this.#P],[this.#l,this.#g]])for(;t.steps.size<e&&t.queue.length>0;){const s=t.queue.shift();s.queued=!1,this.#W(s,t)}if(this.#B()===0&&this.#h===null&&!this.#n&&this.#l.queue.length===0&&this.#u.queue.length===0){if(this.#O.clear(),this.#D(this.#t.now())){this.#r();return}this.#q();for(const t of this.#m.splice(0))t.resolve();this.#_()}}}#B(){return this.#l.steps.size+this.#u.steps.size}#w(){return[...this.#d.values(),...this.#s.values()]}#k(t){return t.kind==="line"?this.#d.get(t.authorityId)===t:this.#s.get(t.unit)===t}#i(t){if(!this.#e){if(t.running){t.again=!0;return}t.queued||(t.queued=!0,(t.kind==="line"?this.#l:this.#u).queue.push(t))}}#W(t,e){t.running=!0,t.again=!1;const s=(t.kind==="line"?this.#J(t):this.#H(t)).then(i=>{t.running=!1,e.steps.delete(s),(i||t.again)&&this.#k(t)&&(t.again=!1,this.#i(t)),this.#r()});e.steps.add(s)}async#F(){try{const t=await this.#t.store.readApplyAuthorities();if(!Array.isArray(t)||new Set(t).size!==t.length||t.some(s=>typeof s!="string"||s.length===0))throw new Error("entity Apply store returned an invalid authority list");this.#p=1/0;const e=new Set(t);for(const[s,i]of this.#d)!e.has(s)&&!i.running&&!i.queued&&this.#d.delete(s);for(const s of t){let i=this.#d.get(s);i||(i=S(s),this.#d.set(s,i)),this.#i(i)}}catch(t){this.#p=this.#t.now()+g;const e=this.#m.splice(0);e.length===0&&this.#S(t);for(const s of e)s.reject(t)}}async#J(t){try{const e=t.held;if(e&&e.entityId===null&&!e.due&&e.notBefore>this.#t.now())return!1;const s=this.#A,i=await this.#t.store.readApplyWindow(t.authorityId);return $(t.authorityId,i),this.#e?!1:i.kind==="end"?(t.held=null,!1):(i.window.deliverySequence!==null&&this.#v.advance(t.authorityId,i.window.deliverySequence),await this.#U(t,i.window,s))}catch(e){return this.#Y(t,e),!1}}async#H(t){try{const e=t.held;if(e&&e.entityId===null&&!e.due&&e.notBefore>this.#t.now())return!1;const s=this.#A,i=await this.#t.store.readFetchWindow(t.unit,t.toPrefix?null:t.through);if(P(t.unit,i),this.#e||!this.#k(t))return!1;if(t.waitsOn=null,i.kind==="unseen")return this.#L(t,{producer:"detect",entityIds:[t.unit]},i.reason,s);if(!t.again&&(i.kind!=="window"||i.window.intent===null)&&(t.toPrefix=!1),t.through!==null&&i.through>t.through&&t.met.clear(),t.through=Math.max(t.through??0,i.through),i.kind!=="window"&&(t.held=null),t.again&&(i.kind==="end"||i.kind==="nowhere"))return!0;switch(i.kind){case"end":return this.#f(t,{kind:"placed"}),!1;case"nowhere":return this.#f(t,{kind:"nowhere",reason:i.reason}),!1;case"root":return await this.#V(t,i.through,i.reason);case"prerequisite":return this.#X(t,i.unit,i.reason,s);case"window":return await this.#U(t,i.window,s)}}catch(e){return this.#Y(t,e),!1}}async#V(t,e,s){return t.met.has(t.unit)?(this.#f(t,{kind:"held",unit:t.unit,reason:`${t.unit} entered and still not held: ${s}`}),!1):(await this.#t.effects.enterRoot(t.unit,e),this.#e||!this.#k(t)?!1:(t.through===e&&t.met.add(t.unit),this.#E(t.unit),!0))}#$(t){const e=this.#b(t,null);e.toPrefix=!0,e.met.clear(),this.#i(e)}#b(t,e,s=!1){let i=this.#s.get(t);return i?e!==null&&(i.through===null||i.through<e)&&(i.through=e,i.met.clear(),this.#i(i)):(i=v(t,e,s),this.#s.set(t,i),this.#i(i)),i}#X(t,e,s,i){return t.met.has(e)?(this.#f(t,{kind:"held",unit:e,reason:`${e} placed and still needed: ${s}`}),!1):this.#T(t,e,s)?this.#L(t,{producer:"apply",entityIds:[e]},s,i):!1}#L(t,e,s,i){return t.held={entityId:null,target:null,kept:null,cutoff:null,attempt:1,notBefore:1/0,releaseOnProgress:!1,due:this.#z(e,i),reason:s,dependency:e},t.held.due}#N(t){const e=t.held;if(e?.dependency?.producer==="apply"){for(const s of e.dependency.entityIds)if(s!==t.unit&&!t.met.has(s)&&!this.#T(t,s,e.reason))return}}#T(t,e,s){const i=[t];let r=this.#s.get(e);for(;r&&r!==t&&!i.includes(r);)i.push(r),r=r.waitsOn===null?void 0:this.#s.get(r.waitsOn);if(r===t){for(const n of i)this.#f(n,{kind:"held",unit:e,reason:`prerequisite cycle through ${e}: ${s}`});return!1}return t.waitsOn??=e,this.#i(this.#b(e,t.through)),!0}#f(t,e){if(!this.#k(t))return;for(const i of t.waiters)i.answer(e);t.waiters.clear(),t.waitsOn=null,(e.kind==="placed"||t.held?.entityId==null)&&this.#s.delete(t.unit);const s=e.kind==="placed"||e.kind==="held"?e:{kind:"held",unit:t.unit,reason:`${t.unit} is nowhere here: ${e.reason}`};for(const i of[...this.#s.values()])if(i.waitsOn===t.unit){if(e.kind!=="placed"){this.#f(i,s);continue}i.met.add(t.unit)}e.kind==="placed"&&(this.#E(t.unit),this.#c("apply",[t.unit]))}#E(t){const e=new Map([[t,!0]]);for(const s of this.#s.values()){const i=new Set;let r=s.unit;for(;r!==null&&!e.has(r)&&!i.has(r);)i.add(r),r=this.#s.get(r)?.waitsOn??null;const n=r!==null&&e.get(r)===!0;for(const h of i)e.set(h,n);if(n)for(const h of s.waiters)h.moved()}}#G(t){let e=t;const s=new Set([t]);for(let i=t.waitsOn===null?void 0:this.#s.get(t.waitsOn);i&&!s.has(i);i=i.waitsOn===null?void 0:this.#s.get(i.waitsOn))s.add(i),e=i;return{kind:"held",unit:e.unit,reason:e.held?.reason??"still placing"}}async#U(t,e,s){const i=e.members[0]?.work.entityId??null;if(t.held&&t.held.entityId!==null&&t.held.entityId!==i&&(t.held=null),await this.#Q(t,e))return!1;let r=await w(()=>this.#o.run(e,()=>t.kind==="lane"&&t.emptied?t.unit:null));if(t.kind==="line"&&!this.#e&&typeof r=="object"&&r.kind==="park"&&_(e,r)&&(r=await w(()=>this.#o.alone(e.members[0]))),r==="progress"||typeof r=="object"&&r.kind==="alone"){if(t.kind==="line")for(const n of e.members)(n.judgment==="waiting"||r!=="progress"&&n.work.entityId===r.entityId)&&this.#$(n.work.entityId);for(const n of e.members)n.unseen!==void 0&&this.#$(n.unseen);return this.#Z(t,r==="progress"?e.members.map(n=>n.work.entityId):[r.entityId])}return r.advanced?.length&&this.#j(t,r.advanced),this.#tt(t,e,r,s),t.kind==="lane"&&this.#N(t),t.held.due}#K(t,e){const s=t.held,i=e.members[0].work.entityId;return(s?.entityId===i&&s.target===this.#o.targetOf(e)?s.attempt:0)+1}async#Q(t,e){const s=t.held,i=e.members[0];return!s||i===void 0||s.entityId!==i.work.entityId||s.due||s.notBefore<=this.#t.now()||this.#o.targetOf(e)!==s.target||e.cutoff!==s.cutoff?!1:await this.#t.store.localWorkAfter(e.authorityId,i.work.entityId,s.kept??s.target)===null}#Z(t,e){return t.held&&(t.held.entityId===null||e.includes(t.held.entityId))&&(t.held=null),this.#j(t,e),!0}#j(t,e){t.kind==="lane"&&(this.#n=!0,this.#E(t.unit)),this.#c("apply",e);for(const s of this.#w())s!==t&&s.held?.releaseOnProgress&&!s.held.due&&(s.held.due=!0,this.#i(s))}#tt(t,e,s,i){if(s.dependency&&O(s.dependency),s.blocker&&!s.dependency)throw new Error("Apply blocker must name the dependency that releases it");const r=e.members[0].work.entityId,n=t.held,h=this.#K(t,e),l=this.#C(h),d=s.again===!0&&h===1,y={entityId:r,target:this.#o.targetOf(e),kept:e.members[0].work.kept,cutoff:e.cutoff,attempt:h,notBefore:s.dependency?1/0:this.#t.now()+(d?0:l),releaseOnProgress:s.releaseOnProgress,due:s.dependency?this.#z(s.dependency,s.comparedAt??i):d,reason:s.reason,...s.dependency?{dependency:s.dependency}:{},...s.blocker?{blocker:s.blocker}:{}};t.held=y,this.#q();const A=c(n,p(t)),f=c(y,p(t));f&&JSON.stringify(f)!==JSON.stringify(A)&&this.#t.onWaiting?.(f),!(!s.report&&(s.dependency!==void 0||h===1))&&this.#S(new Error(`${m(t)} holds at ${r}, which ${s.releaseOnProgress?"is parked on a conflict":s.report?"failed":s.again?"keeps ending unplaced":"stands on ground that keeps moving"}, and will retry in ${l}ms (attempt ${h}): ${s.reason}`,s.cause===void 0?void 0:{cause:s.cause}))}#Y(t,e){if(t.kind==="lane"){for(const h of t.waiters)h.fail(e);t.waiters.clear()}const s=t.held,i=(s?.entityId===null?s.attempt:0)+1,r=this.#C(i),n=e instanceof Error?e.message:String(e);t.held={entityId:null,target:null,kept:null,cutoff:null,attempt:i,notBefore:this.#t.now()+r,releaseOnProgress:!1,due:!1,reason:n},this.#q(),this.#S(new Error(`${m(t)} faulted and will retry in ${r}ms (attempt ${i}): ${n}`,{cause:e}))}#S(t){try{this.#x(t)}catch{}}#C(t){const e=Math.min(g,x*2**Math.min(t-1,16)),s=Math.max(0,Math.min(1,this.#t.schedule.random()));return Math.round(e*(.5+s))}#c(t,e){const s=++this.#A;for(const i of e??["*"])this.#O.set(`${t}:${i}`,s);for(const i of this.#w())q(i,t,e)&&this.#i(i)}#z(t,e){return["*",...t.entityIds].some(s=>(this.#O.get(`${t.producer}:${s}`)??0)>e)}#q(){if(this.#e)return;let t=this.#p;for(const i of this.#w())i.held&&!i.held.due&&(t=Math.min(t,i.held.notBefore));if(t===1/0){this.#M();return}if(this.#y?.dueAt===t)return;this.#M();const e=Math.max(0,t-this.#t.now()),s=this.#t.schedule.schedule(e,()=>{this.#y=null,this.#D(t),this.#r()});this.#y={dueAt:t,cancel:a(()=>s.cancel(),"cancel")}}#D(t){let e=!1;for(const s of this.#w())s.held&&!s.held.due&&s.held.notBefore<=t&&(s.held.due=!0,this.#i(s),e=!0);return this.#p<=t&&(this.#p=1/0,this.#n=!0,e=!0),e}#M(){this.#y?.cancel(),this.#y=null}}const p=a(o=>o.kind==="line"?o.authorityId:o.unit,"owner"),m=a(o=>o.kind==="line"?`entity Apply line ${o.authorityId}`:`entity Apply fetch of ${o.unit}`,"label");export{M as ENTITY_APPLY_DEFAULT_CONCURRENCY,x as ENTITY_APPLY_RETRY_BASE_MS,g as ENTITY_APPLY_RETRY_MAX_MS,j as EntityApplyRail};
@@ -16,3 +16,4 @@ export interface RefusedMove {
16
16
  }
17
17
  export declare const contentKind: (type: string) => string;
18
18
  export declare function playChange(previous: CloudEntityRecord | null, change: PlayableChange, sha256Hex: Sha256Hex, refused?: RefusedMove, readPosition?: () => number | undefined): Played;
19
+ export declare const sameFields: (left: CloudEntityRecord, right: CloudEntityRecord) => boolean;
@@ -1 +1 @@
1
- var w=Object.defineProperty;var l=(t,o)=>w(t,"name",{value:o,configurable:!0});import{canonicalVersion as u,validPortableFileMode as p,validPortableMtime as P}from"../entities/rules.js";import{fileAbsent as y}from"../git/checkout.js";import{CONTAINERS as b}from"../entities/types.js";const U=l(t=>b.has(t)?t:"file","contentKind");function E(t,o,r,c,f){const e=k(t,o,r,c),s=e.row;if(s===null)return e;const a=t?.status==="active"&&s.parentUUID===t.parentUUID&&s.name===t.name,i=s.status!=="active"||s.parentUUID===null?void 0:a?t.slotPosition:o.deliverySequence??f?.();if(s.slotPosition===i)return e;const{slotPosition:n,...m}=s;return{...e,row:i===void 0?m:{...m,slotPosition:i}}}l(E,"playChange");function k(t,o,r,c){const{facets:f,result:e}=o;if(o.joins!==void 0)return t!==null&&t.status!=="deleted"&&t.version===o.joins?{row:e,setsPayload:!0}:{row:t,setsPayload:!1};const s=c===void 0?e.parentUUID:c.keeps;if(t===null||f.includes("create")){if(t?.status==="deleted")return{row:t,setsPayload:!1};if(s===e.parentUUID)return{row:e,setsPayload:!0};const d={...e,parentUUID:s};return{row:{...d,version:u(d,r)},setsPayload:!0}}if(t.status==="deleted")return{row:t,setsPayload:!1};let a=t,i=!1;const n=l(d=>{a={...a,...d}},"set"),m=l(()=>{n({type:e.type,fileMode:y(e)||!p(e.type,a.fileMode)?e.fileMode:a.fileMode,mtime:y(e)||!P(e.type,a.mtime)?e.mtime:a.mtime,payloadVersion:e.payloadVersion,size:e.size,linkTarget:e.linkTarget,gitHomeEntity:e.gitHomeEntity,gitHomePath:e.gitHomePath,transportVersion:e.transportVersion}),i=!0},"becomes");for(const d of f)switch(d){case"move":n({parentUUID:s});break;case"rename":n({name:e.name});break;case"retype":m();break;case"content":U(a.type)===U(e.type)&&m();break;case"mode":!y(a)&&p(a.type,e.fileMode)&&n({fileMode:e.fileMode});break;case"time":!y(a)&&P(a.type,e.mtime)&&n({mtime:e.mtime});break;case"trash":n({status:"trashed"});break;case"restore":a.status==="trashed"&&n({status:"active"});break;case"delete":n({status:"deleted"});break;case"create":break}return a===t?{row:t,setsPayload:!1}:M(a,e)?{row:e,setsPayload:i}:{row:{...a,version:u(a,r)},setsPayload:i}}l(k,"playFacets");const I=["uuid","type","parentUUID","name","status","payloadVersion","fileMode","mtime","size","linkTarget","gitHomeEntity","gitHomePath","transportVersion"],M=l((t,o)=>I.every(r=>t[r]===o[r]),"sameFields");export{U as contentKind,E as playChange};
1
+ var w=Object.defineProperty;var l=(t,o)=>w(t,"name",{value:o,configurable:!0});import{canonicalVersion as u,validPortableFileMode as p,validPortableMtime as P}from"../entities/rules.js";import{fileAbsent as y}from"../git/checkout.js";import{CONTAINERS as b}from"../entities/types.js";const U=l(t=>b.has(t)?t:"file","contentKind");function E(t,o,r,c,f){const e=k(t,o,r,c),s=e.row;if(s===null)return e;const a=t?.status==="active"&&s.parentUUID===t.parentUUID&&s.name===t.name,i=s.status!=="active"||s.parentUUID===null?void 0:a?t.slotPosition:o.deliverySequence??f?.();if(s.slotPosition===i)return e;const{slotPosition:n,...m}=s;return{...e,row:i===void 0?m:{...m,slotPosition:i}}}l(E,"playChange");function k(t,o,r,c){const{facets:f,result:e}=o;if(o.joins!==void 0)return t!==null&&t.status!=="deleted"&&t.version===o.joins?{row:e,setsPayload:!0}:{row:t,setsPayload:!1};const s=c===void 0?e.parentUUID:c.keeps;if(t===null||f.includes("create")){if(t?.status==="deleted")return{row:t,setsPayload:!1};if(s===e.parentUUID)return{row:e,setsPayload:!0};const d={...e,parentUUID:s};return{row:{...d,version:u(d,r)},setsPayload:!0}}if(t.status==="deleted")return{row:t,setsPayload:!1};let a=t,i=!1;const n=l(d=>{a={...a,...d}},"set"),m=l(()=>{n({type:e.type,fileMode:y(e)||!p(e.type,a.fileMode)?e.fileMode:a.fileMode,mtime:y(e)||!P(e.type,a.mtime)?e.mtime:a.mtime,payloadVersion:e.payloadVersion,size:e.size,linkTarget:e.linkTarget,gitHomeEntity:e.gitHomeEntity,gitHomePath:e.gitHomePath,transportVersion:e.transportVersion}),i=!0},"becomes");for(const d of f)switch(d){case"move":n({parentUUID:s});break;case"rename":n({name:e.name});break;case"retype":m();break;case"content":U(a.type)===U(e.type)&&m();break;case"mode":!y(a)&&p(a.type,e.fileMode)&&n({fileMode:e.fileMode});break;case"time":!y(a)&&P(a.type,e.mtime)&&n({mtime:e.mtime});break;case"trash":n({status:"trashed"});break;case"restore":a.status==="trashed"&&n({status:"active"});break;case"delete":n({status:"deleted"});break;case"create":break}return a===t?{row:t,setsPayload:!1}:M(a,e)?{row:e,setsPayload:i}:{row:{...a,version:u(a,r)},setsPayload:i}}l(k,"playFacets");const I=["uuid","type","parentUUID","name","status","payloadVersion","fileMode","mtime","size","linkTarget","gitHomeEntity","gitHomePath","transportVersion"],M=l((t,o)=>I.every(r=>t[r]===o[r]),"sameFields");export{U as contentKind,E as playChange,M as sameFields};
@@ -11,7 +11,7 @@ export interface GitIndexSide {
11
11
  }
12
12
  export interface GitPlayGit {
13
13
  builtOn(commit: string, base: string): Promise<boolean>;
14
- playIndex(line: GitIndexSide, basis: GitIndexSide | null, record: GitIndexSide, to: string | null): Promise<{
14
+ playIndex(line: GitIndexSide, basis: GitIndexSide | null, record: GitIndexSide | null, to: string | null): Promise<{
15
15
  readonly meaning: string;
16
16
  readonly bytes: Uint8Array;
17
17
  } | null>;
package/dist/git/play.js CHANGED
@@ -1,4 +1,4 @@
1
- var se=Object.defineProperty;var r=(t,a)=>se(t,"name",{value:a,configurable:!0});import{utf8Decode as ie,utf8Encode as ae}from"../entities/bytes.js";import{GIT_ALTERNATES_PATH as fe}from"./alternates.js";import{gitBlobId as Y}from"./artifact.js";import{gitChainReflog as re,gitDropPackedRefs as ce,gitLooseRef as le,gitPackedRefs as de,gitReflogPlay as me,gitReflogTop as Z}from"./refs.js";import{gitBytesForm as ue,gitSelfHeld as he,gitSharesGitDir as ge,gitSharesObjects as pe,gitTreeOf as we,isGitOid as ee}from"./state.js";import{compareGitText as z}from"./text.js";function ye(t){return t.facets.some(c=>c==="create"||c==="retype"||c==="content")&&t.result.status==="active"?t.result.transportVersion:null}r(ye,"gitOwnChange");function Pe(t){let a=[],c=!1;for(const u of t){if(u.result.type!=="repo.git"){a=[],c=!0;continue}const p=ye(u);p!==null&&a.push(p)}return{reached:a,ended:c}}r(Pe,"gitLineChanges");function $e({line:t,basis:a,record:c}){const u=r(l=>l.files.find(f=>f.path===fe)?.oid??null,"borrowed"),p=r(l=>l.files.some(f=>f.path==="reftable"),"reftable");return t.format===c.format&&(a===null||a.format===c.format)&&!pe(t)&&!he(t.home)&&!ge(t.home)&&t.home?.entity===c.home?.entity&&t.home?.path===c.home?.path&&u(t)===u(c)&&![t,c,...a?[a]:[]].some(l=>p(l)||ue(l))}r($e,"gitPlayable");const B="040000",F=r(t=>new Map(t.map(a=>[a.path,a])),"byPath"),N=r((t,a)=>t===void 0?a===void 0:a!==void 0&&t.mode===a.mode&&t.oid===a.oid,"same"),te=r(t=>{const a=[];for(let c=t.indexOf("/");c>0;c=t.indexOf("/",c+1))a.push(t.slice(0,c));return a},"parents");function ke(t,a,c){const u=new Set;for(const l of t.keys()){const f=te(l).find(x=>t.has(x)&&t.get(x).mode!==B);f!==void 0&&u.add(f)}const p=r(l=>u.has(l)||te(l).some(f=>u.has(f)),"clashed");if(u.size>0){for(const l of[...t.keys()])p(l)&&t.delete(l);for(const[l,f]of a)p(l)&&t.set(l,f)}return we(t.values(),c)}r(ke,"asTree");const E=["line","basis","record"],R=r(t=>t.mode!==B&&(t.path==="HEAD"||t.path.startsWith("refs/")),"isLooseRef"),ne=r(t=>R(t)||t.path==="packed-refs","isRefFile"),xe=r(t=>t.startsWith("logs/"),"isReflogPath"),j="refs/stash",V="refs/heads/",q=`${V}amalgm`,be=7,Ee=/^[0-9a-f]{7,}$/,J=r((t,a)=>t.startsWith(`${a}/`),"beneath");async function Te(t,a,c,u){const p={format:t.record.format,home:t.record.home,files:[],index:null},l={line:t.line,basis:t.basis??p,record:t.record},f={line:F(l.line.files),basis:F(l.basis.files),record:F(l.record.files)},x=new Map,D=r((e,n)=>{const o=ae(n),i=Y(o,u);return x.set(i,o),{path:e,mode:"100644",oid:i}},"make"),w=r(async e=>e?.oid?ie(x.get(e.oid)??await a(e.oid)):"","read"),H=new Map,I=r(e=>(H.has(e)||H.set(e,w(f[e].get("packed-refs")).then(de)),H.get(e)),"packedOf"),y=r(async(e,n)=>{const o=f[e].get(n);return o!==void 0&&R(o)?le(await w(o)):n==="HEAD"?null:(await I(e)).get(n)??null},"value"),P=r(e=>!N(f.basis.get(e),f.record.get(e)),"recordChanged"),m=new Map;for(const e of new Set([...f.line.keys(),...f.basis.keys(),...f.record.keys()])){const n=P(e)?f.record.get(e):f.line.get(e);n!==void 0&&m.set(e,n)}const $=new Set;for(const e of new Set(E.flatMap(n=>[...f[n].keys()]))){const[n,o,i]=E.map(s=>f[s].get(e));if(!(N(n,o)&&N(o,i)))if(e==="packed-refs")for(const s of E)for(const d of(await I(s)).keys())$.add(d);else[n,o,i].some(s=>s!==void 0&&R(s))&&$.add(e)}const K=r(async e=>{const[n,o,i]=E.map(s=>f[s].get(e));return[n,o,i].some(s=>s?.mode===B)?w(n):me(await w(o),await w(i),await w(n))},"playLog"),b=`logs/${j}`;let S=null;P(b)&&(S=re(await K(b)),S===""?m.delete(b):m.set(b,D(b,S)));const g=new Map,T=[];for(const e of[...$].sort(z)){const[n,o,i]=await Promise.all(E.map(d=>y(d,e)));let s=o!==i?i:n;if(e===j){if(S===null)continue;s=Z(S)}else e.startsWith(V)&&n!==null&&n!==o&&s!==n&&[n,i].every(d=>d===null||ee(t.record.format,d))&&(i===null||!await c.builtOn(i,n))&&(s=n,i!==null&&!await c.builtOn(n,i)&&T.push({name:e,basis:o,record:i}));s!==n&&g.set(e,s)}const Q=[];if(T.length>0){const e=new Map;for(const o of new Set([...f.line.keys(),...(await I("line")).keys(),...g.keys()])){if(o!==q&&!J(o,q))continue;const i=g.has(o)?g.get(o):await y("line",o);i!==null&&e.set(o,i)}const n=r((o,i)=>(e.get(o)??i)===i&&![...e.keys()].some(s=>J(o,s)||J(s,o)),"free");for(const{name:o,basis:i,record:s}of T){const d=`${q}/${o.slice(V.length)}-`;let h=[...e.keys()].sort(z).find(k=>e.get(k)===i&&k.startsWith(d)&&Ee.test(k.slice(d.length)));for(let k=be;h===void 0&&k<=s.length;k+=1)n(d+s.slice(0,k),s)&&(h=d+s.slice(0,k));h!==void 0&&(await y("line",h)!==s&&g.set(h,s),e.set(h,s),Q.push({branch:h,from:o,commit:s}))}}for(const[e,n]of[...m])ne(n)&&m.delete(e);for(const e of l.line.files)ne(e)&&m.set(e.path,e);const M=new Set;for(const[e,n]of g)n!==null?m.set(e,D(e,`${n}
2
- `)):(m.has(e)&&R(m.get(e))&&m.delete(e),M.add(e));const U=f.line.get("packed-refs");if(M.size>0&&U!==void 0){const e=await w(U),n=ce(e,M);n!==e&&m.set("packed-refs",D("packed-refs",n))}const L=r(e=>g.has(e)?Promise.resolve(g.get(e)):y("line",e),"final"),v=r(async(e,n)=>e?.startsWith("ref: ")?n(e.slice(5)):e,"commitOf"),A=await v(await L("HEAD"),L),O=new Set;for(const e of E)for(const n of f[e].keys())xe(n)&&n!==b&&O.add(n);for(const e of g.keys())e!==j&&O.add(`logs/${e}`);A!==await v(await y("line","HEAD"),e=>y("line",e))&&O.add("logs/HEAD");for(const e of[...O].sort(z)){const n=e.slice(5),o=n==="HEAD"?A:await L(n),i=P(e);if(!i&&(o===null||n!=="HEAD"&&!g.has(n)||!f.line.has(e)))continue;let s=i?await K(e):await w(f.line.get(e));const d=Z(s);if(o!==null&&d!==null&&d!==o&&ee(t.record.format,o)){const h=s.trimEnd().split(`
1
+ var re=Object.defineProperty;var f=(t,i)=>re(t,"name",{value:i,configurable:!0});import{utf8Decode as fe,utf8Encode as ce}from"../entities/bytes.js";import{GIT_ALTERNATES_PATH as le}from"./alternates.js";import{gitBlobId as Z}from"./artifact.js";import{gitChainReflog as de,gitDropPackedRefs as me,gitLooseRef as ue,gitPackedRefs as he,gitReflogPlay as ge,gitReflogTop as ee}from"./refs.js";import{gitBytesForm as pe,gitSelfHeld as we,gitSharesGitDir as ye,gitSharesObjects as ke,gitTreeOf as be,isGitOid as te}from"./state.js";import{compareGitText as z}from"./text.js";function xe(t){return t.facets.some(c=>c==="create"||c==="retype"||c==="content")&&t.result.status==="active"?t.result.transportVersion:null}f(xe,"gitOwnChange");function Me(t){let i=[],c=!1;for(const u of t){if(u.result.type!=="repo.git"){i=[],c=!0;continue}const p=xe(u);p!==null&&i.push(p)}return{reached:i,ended:c}}f(Me,"gitLineChanges");function Le({line:t,basis:i,record:c}){const u=f(l=>l.files.find(a=>a.path===le)?.oid??null,"borrowed"),p=f(l=>l.files.some(a=>a.path==="reftable"),"reftable");return t.format===c.format&&(i===null||i.format===c.format)&&!ke(t)&&!we(t.home)&&!ye(t.home)&&t.home?.entity===c.home?.entity&&t.home?.path===c.home?.path&&u(t)===u(c)&&![t,c,...i?[i]:[]].some(l=>p(l)||pe(l))}f(Le,"gitPlayable");const B="040000",F=f(t=>new Map(t.map(i=>[i.path,i])),"byPath"),N=f((t,i)=>t===void 0?i===void 0:i!==void 0&&t.mode===i.mode&&t.oid===i.oid,"same"),ne=f(t=>{const i=[];for(let c=t.indexOf("/");c>0;c=t.indexOf("/",c+1))i.push(t.slice(0,c));return i},"parents");function Ee(t,i,c){const u=new Set;for(const l of t.keys()){const a=ne(l).find(b=>t.has(b)&&t.get(b).mode!==B);a!==void 0&&u.add(a)}const p=f(l=>u.has(l)||ne(l).some(a=>u.has(a)),"clashed");if(u.size>0){for(const l of[...t.keys()])p(l)&&t.delete(l);for(const[l,a]of i)p(l)&&t.set(l,a)}return be(t.values(),c)}f(Ee,"asTree");const E=["line","basis","record"],R=f(t=>t.mode!==B&&(t.path==="HEAD"||t.path.startsWith("refs/")),"isLooseRef"),oe=f(t=>R(t)||t.path==="packed-refs","isRefFile"),Se=f(t=>t.startsWith("logs/"),"isReflogPath"),j="refs/stash",V="refs/heads/",q=`${V}amalgm`,De=7,Ae=/^[0-9a-f]{7,}$/,J=f((t,i)=>t.startsWith(`${i}/`),"beneath");async function ve(t,i,c,u){const p={format:t.record.format,home:t.record.home,files:[],index:null},l={line:t.line,basis:t.basis??p,record:t.record},a={line:F(l.line.files),basis:F(l.basis.files),record:F(l.record.files)},b=new Map,A=f((e,n)=>{const o=ce(n),r=Z(o,u);return b.set(r,o),{path:e,mode:"100644",oid:r}},"make"),w=f(async e=>e?.oid?fe(b.get(e.oid)??await i(e.oid)):"","read"),I=new Map,P=f(e=>(I.has(e)||I.set(e,w(a[e].get("packed-refs")).then(he)),I.get(e)),"packedOf"),y=f(async(e,n)=>{const o=a[e].get(n);return o!==void 0&&R(o)?ue(await w(o)):n==="HEAD"?null:(await P(e)).get(n)??null},"value"),$=f(e=>!N(a.basis.get(e),a.record.get(e)),"recordChanged"),m=new Map;for(const e of new Set([...a.line.keys(),...a.basis.keys(),...a.record.keys()])){const n=$(e)?a.record.get(e):a.line.get(e);n!==void 0&&m.set(e,n)}const T=new Set;for(const e of new Set(E.flatMap(n=>[...a[n].keys()]))){const[n,o,r]=E.map(s=>a[s].get(e));if(!(N(n,o)&&N(o,r)))if(e==="packed-refs")for(const s of E)for(const d of(await P(s)).keys())T.add(d);else[n,o,r].some(s=>s!==void 0&&R(s))&&T.add(e)}const K=f(async e=>{const[n,o,r]=E.map(s=>a[s].get(e));return[n,o,r].some(s=>s?.mode===B)?w(n):ge(await w(o),await w(r),await w(n))},"playLog"),x=`logs/${j}`;let S=null;$(x)&&(S=de(await K(x)),S===""?m.delete(x):m.set(x,A(x,S)));const g=new Map,M=[];for(const e of[...T].sort(z)){const[n,o,r]=await Promise.all(E.map(d=>y(d,e)));let s=o!==r?r:n;if(e===j){if(S===null)continue;s=ee(S)}else e.startsWith(V)&&n!==null&&n!==o&&s!==n&&[n,r].every(d=>d===null||te(t.record.format,d))&&(r===null||!await c.builtOn(r,n))&&(s=n,r!==null&&!await c.builtOn(n,r)&&M.push({name:e,basis:o,record:r}));s!==n&&g.set(e,s)}const Q=[];if(M.length>0){const e=new Map;for(const o of new Set([...a.line.keys(),...(await P("line")).keys(),...g.keys()])){if(o!==q&&!J(o,q))continue;const r=g.has(o)?g.get(o):await y("line",o);r!==null&&e.set(o,r)}const n=f((o,r)=>(e.get(o)??r)===r&&![...e.keys()].some(s=>J(o,s)||J(s,o)),"free");for(const{name:o,basis:r,record:s}of M){const d=`${q}/${o.slice(V.length)}-`;let h=[...e.keys()].sort(z).find(k=>e.get(k)===r&&k.startsWith(d)&&Ae.test(k.slice(d.length)));for(let k=De;h===void 0&&k<=s.length;k+=1)n(d+s.slice(0,k),s)&&(h=d+s.slice(0,k));h!==void 0&&(await y("line",h)!==s&&g.set(h,s),e.set(h,s),Q.push({branch:h,from:o,commit:s}))}}for(const[e,n]of[...m])oe(n)&&m.delete(e);for(const e of l.line.files)oe(e)&&m.set(e.path,e);const L=new Set;for(const[e,n]of g)n!==null?m.set(e,A(e,`${n}
2
+ `)):(m.has(e)&&R(m.get(e))&&m.delete(e),L.add(e));const U=a.line.get("packed-refs");if(L.size>0&&U!==void 0){const e=await w(U),n=me(e,L);n!==e&&m.set("packed-refs",A("packed-refs",n))}const v=f(e=>g.has(e)?Promise.resolve(g.get(e)):y("line",e),"final"),C=f(async(e,n)=>e?.startsWith("ref: ")?n(e.slice(5)):e,"commitOf"),O=await C(await v("HEAD"),v),H=new Set;for(const e of E)for(const n of a[e].keys())Se(n)&&n!==x&&H.add(n);for(const e of g.keys())e!==j&&H.add(`logs/${e}`);O!==await C(await y("line","HEAD"),e=>y("line",e))&&H.add("logs/HEAD");for(const e of[...H].sort(z)){const n=e.slice(5),o=n==="HEAD"?O:await v(n),r=$(e);if(!r&&(o===null||n!=="HEAD"&&!g.has(n)||!a.line.has(e)))continue;let s=r?await K(e):await w(a.line.get(e));const d=ee(s);if(o!==null&&d!==null&&d!==o&&te(t.record.format,o)){const h=s.trimEnd().split(`
3
3
  `).at(-1);s+=`${d} ${o}${h.slice(h.indexOf(" ",h.indexOf(" ")+1))}
4
- `}s===""?m.delete(e):m.set(e,D(e,s))}const oe=r(e=>y(e,"HEAD").then(n=>v(n,o=>y(e,o))),"headOf"),C=r(async e=>{const n=t[e]?.index;return n?.files.length===1?{index:await a(n.files[0].oid),head:await oe(e)}:null},"indexOf"),[W,X,G]=await Promise.all([C("line"),C("basis"),C("record")]);let _=t.record.index;if(W!==null&&G!==null){const e=t.record.index.meaning===t.basis?.index?.meaning&&G.head===X?.head,n=e&&W.head===A?null:await c.playIndex(W,X,G,A);if(e&&n===null)_=t.line.index;else if(n!==null){const o=n.bytes,i=Y(o,u);x.set(i,o),_={meaning:n.meaning,files:[{path:"index",mode:"100644",oid:i}]}}}return{state:{format:t.record.format,home:t.record.home,files:ke(m,f.record,t.record.home),index:_},made:x,aside:Q}}r(Te,"gitPlayRecord");export{Pe as gitLineChanges,ye as gitOwnChange,Te as gitPlayRecord,$e as gitPlayable};
4
+ `}s===""?m.delete(e):m.set(e,A(e,s))}const W=f(e=>y(e,"HEAD").then(n=>C(n,o=>y(e,o))),"headOf"),G=f(async e=>{const n=t[e]?.index;return n?.files.length===1?{index:await i(n.files[0].oid),head:await W(e)}:null},"indexOf"),[_,se,X,ie,ae]=await Promise.all([G("line"),G("basis"),G("record"),t.basis?W("basis"):null,W("record")]),D=t.record.index?.meaning===t.basis?.index?.meaning&&ae===ie;let Y=D?t.line.index:t.record.index;if(_!==null&&(D||X!==null)&&!(D&&_.head===O)){const e=await c.playIndex(_,D?null:se,D?null:X,O);if(e!==null){const n=e.bytes,o=Z(n,u);b.set(o,n),Y={meaning:e.meaning,files:[{path:"index",mode:"100644",oid:o}]}}}return{state:{format:t.record.format,home:t.record.home,files:Ee(m,a.record,t.record.home),index:Y},made:b,aside:Q}}f(ve,"gitPlayRecord");export{Me as gitLineChanges,xe as gitOwnChange,ve as gitPlayRecord,Le as gitPlayable};
@@ -1 +1 @@
1
- "use strict";var P=Object.defineProperty;var m=(l,e)=>P(l,"name",{value:e,configurable:!0});Object.defineProperty(exports,"__esModule",{value:!0}),exports.EntityApplyJourney=void 0,exports.stepsAside=q,exports.outcomeOf=D;const _=require("./contracts.js"),j=require("./plans.js"),x=require("../faults/recover.js"),E=require("../faults/classify.js"),M=require("../clash/local-work.js"),O=require("./selection.js"),W=require("./settling.js"),S=require("./window.js");function q(l,e){return l.unit===null&&l.authorityId!==e}m(q,"stepsAside");const F=m(l=>l.kind==="captured-local"||l.kind==="rejudge","drops");function v(l){return l.kind==="retry"?{kind:"park",reason:l.reason??"machine truth is unsettled",releaseOnProgress:!1,report:!1}:l.kind==="dependency"?{kind:"park",reason:l.reason,releaseOnProgress:l.waitFor===void 0,report:!1,...l.waitFor?{dependency:l.waitFor}:{},...l.blocker?{blocker:l.blocker}:{},..."comparedAt"in l?{comparedAt:l.comparedAt}:{}}:l.kind==="conflict"?{kind:"park",reason:l.reason,releaseOnProgress:!0,report:!0}:null}m(v,"parkFor");async function D(l){try{return await l()}catch(e){return{kind:"park",reason:e instanceof Error?e.message:String(e),releaseOnProgress:!1,report:!(0,E.groundMoved)(e),cause:e}}}m(D,"outcomeOf");const I=m(l=>(0,W.isSettlement)(l.judgment)?{kind:"settled",settlement:l.judgment}:null,"settled");class H{static{m(this,"EntityApplyJourney")}#e;#a;#r;#n;constructor(e,t,i){this.#e=e,this.#a={sha256Hex:e.sha256Hex,loops:e.loops,deliveryPosition:e.deliveryPosition},this.#r=t,this.#n=i}targetOf(e){const t=e.members[0];return t===void 0?null:e.intent?.members.find(i=>i.entityId===t.work.entityId)?.throughSequence??(t.work.kept===null?t.work.records.at(-1)?.globalSequence:t.work.resolvedThrough)??null}async run(e,t){if(e.intent!==null)return this.#p(e,e.intent);const i={member:null};try{return await this.#d(e,t,i)}catch(a){if(i.member===null||this.#n())throw a;if((0,E.groundMoved)(a))return{kind:"park",reason:a instanceof Error?a.message:String(a),releaseOnProgress:!1,report:!1};if(q(e,i.member.work.entityId))return this.alone(i.member);if(a instanceof x.Recovering)return{kind:"park",reason:a.message,releaseOnProgress:!1,report:!1,dependency:{producer:"capability",entityIds:a.need.subject===null?[]:[a.need.subject.id]}};throw a}}async alone(e){const t=await this.#t(null,[e],[{kind:"settled",settlement:"waiting"}]);return t==="progress"?{kind:"alone",entityId:e.work.entityId}:t}async#d(e,t,i){const a=this.#e.newIntentId(),n=this.#e.now(),o=t(),s=new Map;for(const c of e.members){if(I(c))continue;const{work:f}=c,w=(0,O.selectEntityApply)(f,this.#a),b=(0,_.createApplyIntent)({attemptId:a,work:f,target:w.target,unit:e.unit,cutoff:e.cutoff,createdAt:n,emptied:f.entityId===o&&f.play==="enter"&&(w.target.result.type==="file.text"||w.target.result.type==="file.binary")}),h=(0,j.planSelectedEntityApply)(f,w,this.#e.sha256Hex);s.set(f.entityId,{member:c,intent:b,plan:h,adapter:this.#e.effects.adapterFor(h.target.type),look:"safe"})}const{active:d,blocked:y}=await this.#o(e.members,s,"look",i);if(d.length===0)return y??"again";const g=d.flatMap(c=>s.get(c.work.entityId)??[]);if(g.length===0)return this.#t(null,d,d.map(c=>I(c)));const k=(0,_.createApplyWindowIntent)({attemptId:a,authorityId:e.authorityId,unit:e.unit,cutoff:e.cutoff,createdAt:n,members:g.map(c=>c.intent)});try{const c=await this.#u(d,s,i),f=c.active.flatMap(r=>s.get(r.work.entityId)??[]);if(f.length===0)return await this.#e.effects.discard(k),c.active.length===0?c.blocked??"again":this.#t(null,c.active,c.active.map(r=>I(r)));const w=f.length===g.length?k:(0,_.createApplyWindowIntent)({...k,members:f.map(r=>r.intent)}),b=await this.#e.effects.hold(w,f.map(r=>r.plan));let h,A;try{h=await this.#o(c.active,s,"final",i),A=await this.#c(w,h,s,t)}finally{b()}return h.unseen!==null&&h.active.length===0?this.#y(h.unseen):A}catch(c){throw await this.#e.effects.discard(k),c}}async#c(e,{active:t,blocked:i},a,n){const o=t.flatMap(r=>a.get(r.work.entityId)??[]);if(o.length===0)return await this.#e.effects.discard(e),t.length===0?i??"again":this.#t(null,t,t.map(r=>I(r)));const s=(0,_.createApplyWindowIntent)({...e,members:o.map(r=>r.intent)}),d=o.filter(r=>r.look==="safe");if(d.length>0){if(this.#n()||o.some(p=>p.intent.emptied&&n()!==p.intent.entityId))return await this.#e.effects.discard(e),"again";const r=await this.#e.store.bindWindow(s);if(r)return await this.#e.effects.discard(e),r.kind==="stale"?"again":v({...r,comparedAt:this.#r()})}const y=new Map,g=new Map,k=m((r,p,u=null)=>{y.set(r,{kind:"owed",reason:p}),u!==null&&g.set(r,u)},"owe"),c=m(r=>v(r.kind==="dependency"?{...r,comparedAt:this.#r()}:r),"waitFrom"),{order:f,cycle:w}=(0,S.revealOrder)(d.map(r=>({entityId:r.intent.entityId,play:r.plan.play,type:r.plan.target.type,parentUUID:r.plan.target.parentUUID}))),b="its parent chain closes among the window's members";for(const r of w)k(r,b,{kind:"park",reason:b,releaseOnProgress:!1,report:!0});for(const r of f){const p=a.get(r),u=await p.adapter.apply.reveal(p.intent,p.plan);u&&k(r,u.reason,u.kind==="dependency"?c(u):null)}for(const r of o){const p=r.intent.entityId;if(y.has(p))continue;const u=await r.adapter.verify.verify(r.intent,r.plan);u.kind==="match"?y.set(p,{kind:"materialized"}):u.kind==="local-change"?k(p,"a person's version stands in its place"):u.kind==="rejudge"||u.kind==="missing-target"?k(p,u.kind):k(p,u.reason??u.kind,c(u))}const h=t.map(r=>I(r)??y.get(r.work.entityId));if(d.length>0)return this.#s(s,t,h,g);const A=await this.#s(null,t,h,g);return await this.#e.effects.discard(e),A}async#s(e,t,i,a){const n=await this.#t(e,t,i),o=i[0];return n!=="progress"||o.kind!=="owed"?n:{...a.get(t[0].work.entityId)??{kind:"park",reason:o.reason,releaseOnProgress:!1,report:!1,again:!0},advanced:t.filter((d,y)=>i[y].kind!=="owed").map(d=>d.work.entityId)}}async#o(e,t,i,a){const n=[];for(const o of e){const s=t.get(o.work.entityId);if(!s){n.push(o);continue}let d;try{d=await this.#i(s.intent)?{kind:"captured-local"}:i==="look"?await this.#f(s):await s.adapter.apply.guard(s.intent,s.plan,i)}catch(g){if(n.length>0&&!this.#n())return{active:n,blocked:null,unseen:null};throw a.member=o,g}if(d.kind==="local-change"||d.kind==="unsettled-ground")return{active:n,blocked:n.length===0?"again":null,unseen:s};if(F(d))return{active:n,blocked:n.length===0?"again":null,unseen:null};const y=v(d);if(y)return{active:n,blocked:y,unseen:null};s.look=d.kind,n.push(o)}return{active:n,blocked:null,unseen:null}}async#u(e,t,i){for(const[a,n]of e.entries()){const o=t.get(n.work.entityId);if(!(!o||o.look!=="safe"))try{const s=await o.adapter.apply.prepare(o.intent,o.plan);if(s)return{active:e.slice(0,a),blocked:v(s)}}catch(s){if(a>0&&!this.#n())return{active:e.slice(0,a),blocked:null};throw i.member=n,s}}return{active:[...e],blocked:null}}async#p(e,t){const i=t.members.map(n=>{const o=e.members.find(d=>d.work.entityId===n.entityId);if(!o)return null;const s=n.kept===null?o.work:{...o.work,records:[],kept:n.kept};return s.records.length===0&&s.kept===null?null:(0,j.planSelectedEntityApply)(s,(0,O.selectEntityApply)(s,this.#a,n),this.#e.sha256Hex)}),a=await this.#e.effects.recover(t,i);if(a.length!==t.members.length)throw new Error("Apply recovery answered for a different window");return this.#t(t,e.members,e.members.map(n=>I(n)??a[t.members.findIndex(o=>o.entityId===n.work.entityId)]??{kind:"owed",reason:"not a member of the bound window"}))}async#t(e,t,i){const a=await this.#e.store.endWindow(e,t,i);if(!a)return"progress";if(a.kind!=="stale"||!a.reason)throw new Error("Apply end commit returned an unknown refusal");return"again"}async#i(e){return(0,M.localWorkWins)(e.targetType,await this.#e.store.localWorkAfter(e.authorityId,e.entityId,e.kept??e.throughSequence))}async#f(e){const{intent:t,plan:i,adapter:a}=e,n=await a.apply.guard(t,i,"look");if(n.kind!=="local-change"&&n.kind!=="unsettled-ground")return n;const o=await this.#l(t,i);if(o.kind!=="observed")return o;const s=await a.apply.guard(t,i,"look");return s.kind==="local-change"||s.kind==="unsettled-ground"?{kind:"retry",reason:"Ground still needs observation after Detect; this member cannot reveal."}:s}async#y(e){const t=await this.#l(e.intent,e.plan);return t.kind==="captured-local"?"again":v(t.kind==="observed"?{kind:"retry",reason:"Its final guard found ground Detect had not recorded; it is judged again after Detect looks."}:t)}async#l(e,t){if(await this.#i(e))return{kind:"captured-local"};let i,a=!0;const n=await this.#e.effects.captureLocal(e,t,()=>{if(!a||i!==void 0)throw new Error("Apply capture comparison must be marked exactly once");i=this.#r()}).finally(()=>{a=!1});if(!n||!["settled","local-only","retry"].includes(n.kind))throw new Error("Apply capture returned no explicit observation outcome");if(await this.#i(e))return{kind:"captured-local"};if(n.kind==="retry")return n;if(n.kind==="local-only"){if(i===void 0)throw new Error("local-only capture requires a synchronous comparison fence");if(!n.reason||n.entityIds.length===0||n.entityIds.some(o=>!o))throw new Error("local-only capture must name the retained ground and its releasing condition");return{kind:"dependency",reason:n.reason,comparedAt:i,waitFor:{producer:"detect",entityIds:n.entityIds}}}return{kind:"observed"}}}exports.EntityApplyJourney=H;
1
+ "use strict";var x=Object.defineProperty;var m=(l,e)=>x(l,"name",{value:e,configurable:!0});Object.defineProperty(exports,"__esModule",{value:!0}),exports.EntityApplyJourney=void 0,exports.stepsAside=P,exports.outcomeOf=H;const j=require("./contracts.js"),q=require("./plans.js"),S=require("../faults/recover.js"),O=require("../faults/classify.js"),M=require("../clash/local-work.js"),E=require("./selection.js"),W=require("./settling.js"),F=require("./window.js");function P(l,e){return l.unit===null&&l.authorityId!==e}m(P,"stepsAside");const I={kind:"park",reason:"its window ended with its head unplaced and named no wait",releaseOnProgress:!1,report:!1,again:!0},D=m(l=>l.kind==="captured-local"||l.kind==="rejudge","drops");function A(l){return l.kind==="retry"?{kind:"park",reason:l.reason??"machine truth is unsettled",releaseOnProgress:!1,report:!1}:l.kind==="dependency"?{kind:"park",reason:l.reason,releaseOnProgress:l.waitFor===void 0,report:!1,...l.waitFor?{dependency:l.waitFor}:{},...l.blocker?{blocker:l.blocker}:{},..."comparedAt"in l?{comparedAt:l.comparedAt}:{}}:l.kind==="conflict"?{kind:"park",reason:l.reason,releaseOnProgress:!0,report:!0}:null}m(A,"parkFor");async function H(l){try{return await l()}catch(e){return{kind:"park",reason:e instanceof Error?e.message:String(e),releaseOnProgress:!1,report:!(0,O.groundMoved)(e),cause:e}}}m(H,"outcomeOf");const v=m(l=>(0,W.isSettlement)(l.judgment)?{kind:"settled",settlement:l.judgment}:null,"settled");class U{static{m(this,"EntityApplyJourney")}#e;#r;#s;#n;constructor(e,t,i){this.#e=e,this.#r={sha256Hex:e.sha256Hex,loops:e.loops,deliveryPosition:e.deliveryPosition},this.#s=t,this.#n=i}targetOf(e){const t=e.members[0];return t===void 0?null:e.intent?.members.find(i=>i.entityId===t.work.entityId)?.throughSequence??(t.work.kept===null?t.work.records.at(-1)?.globalSequence:t.work.resolvedThrough)??null}async run(e,t){if(e.intent!==null)return this.#p(e,e.intent);const i={member:null};try{return await this.#d(e,t,i)}catch(s){if(i.member===null||this.#n())throw s;if((0,O.groundMoved)(s))return{kind:"park",reason:s instanceof Error?s.message:String(s),releaseOnProgress:!1,report:!1};if(P(e,i.member.work.entityId))return this.alone(i.member);if(s instanceof S.Recovering)return{kind:"park",reason:s.message,releaseOnProgress:!1,report:!1,dependency:{producer:"capability",entityIds:s.need.subject===null?[]:[s.need.subject.id]}};throw s}}async alone(e){const{target:t}=(0,E.selectEntityApply)(e.work,this.#r),i=await this.#i({authorityId:e.work.authorityId,entityId:e.work.entityId,targetType:t.result.type,kept:t.record===null?t.result:null,throughSequence:t.throughSequence}),s=await this.#t(null,[e],[{kind:"settled",settlement:i?"superseded":"waiting"}]);return s==="progress"&&!i?{kind:"alone",entityId:e.work.entityId}:s}async#d(e,t,i){const s=this.#e.newIntentId(),n=this.#e.now(),o=t(),a=new Map;for(const c of e.members){if(v(c))continue;const{work:f}=c,w=(0,E.selectEntityApply)(f,this.#r),b=(0,j.createApplyIntent)({attemptId:s,work:f,target:w.target,unit:e.unit,cutoff:e.cutoff,createdAt:n,emptied:f.entityId===o&&f.play==="enter"&&(w.target.result.type==="file.text"||w.target.result.type==="file.binary")}),h=(0,q.planSelectedEntityApply)(f,w,this.#e.sha256Hex);a.set(f.entityId,{member:c,intent:b,plan:h,adapter:this.#e.effects.adapterFor(h.target.type),look:"safe"})}const{active:d,blocked:y}=await this.#o(e.members,a,"look",i);if(d.length===0)return y??I;const g=d.flatMap(c=>a.get(c.work.entityId)??[]);if(g.length===0)return this.#t(null,d,d.map(c=>v(c)));const k=(0,j.createApplyWindowIntent)({attemptId:s,authorityId:e.authorityId,unit:e.unit,cutoff:e.cutoff,createdAt:n,members:g.map(c=>c.intent)});try{const c=await this.#u(d,a,i),f=c.active.flatMap(r=>a.get(r.work.entityId)??[]);if(f.length===0)return await this.#e.effects.discard(k),c.active.length===0?c.blocked??I:this.#t(null,c.active,c.active.map(r=>v(r)));const w=f.length===g.length?k:(0,j.createApplyWindowIntent)({...k,members:f.map(r=>r.intent)}),b=await this.#e.effects.hold(w,f.map(r=>r.plan));let h,_;try{h=await this.#o(c.active,a,"final",i),_=await this.#c(w,h,a,t)}finally{b()}return h.unseen!==null&&h.active.length===0?this.#y(h.unseen):_}catch(c){throw await this.#e.effects.discard(k),c}}async#c(e,{active:t,blocked:i},s,n){const o=t.flatMap(r=>s.get(r.work.entityId)??[]);if(o.length===0)return await this.#e.effects.discard(e),t.length===0?i??I:this.#t(null,t,t.map(r=>v(r)));const a=(0,j.createApplyWindowIntent)({...e,members:o.map(r=>r.intent)}),d=o.filter(r=>r.look==="safe");if(d.length>0){if(this.#n()||o.some(p=>p.intent.emptied&&n()!==p.intent.entityId))return await this.#e.effects.discard(e),I;const r=await this.#e.store.bindWindow(a);if(r)return await this.#e.effects.discard(e),r.kind==="stale"?I:A({...r,comparedAt:this.#s()})}const y=new Map,g=new Map,k=m((r,p,u=null)=>{y.set(r,{kind:"owed",reason:p}),u!==null&&g.set(r,u)},"owe"),c=m(r=>A(r.kind==="dependency"?{...r,comparedAt:this.#s()}:r),"waitFrom"),{order:f,cycle:w}=(0,F.revealOrder)(d.map(r=>({entityId:r.intent.entityId,play:r.plan.play,type:r.plan.target.type,parentUUID:r.plan.target.parentUUID}))),b="its parent chain closes among the window's members";for(const r of w)k(r,b,{kind:"park",reason:b,releaseOnProgress:!1,report:!0});for(const r of f){const p=s.get(r),u=await p.adapter.apply.reveal(p.intent,p.plan);u&&k(r,u.reason,u.kind==="dependency"?c(u):null)}for(const r of o){const p=r.intent.entityId;if(y.has(p))continue;const u=await r.adapter.verify.verify(r.intent,r.plan);u.kind==="match"?y.set(p,{kind:"materialized"}):u.kind==="local-change"?k(p,"a person's version stands in its place"):u.kind==="rejudge"||u.kind==="missing-target"?k(p,u.kind):k(p,u.reason??u.kind,c(u))}const h=t.map(r=>v(r)??y.get(r.work.entityId));if(d.length>0)return this.#a(a,t,h,g);const _=await this.#a(null,t,h,g);return await this.#e.effects.discard(e),_}async#a(e,t,i,s){const n=await this.#t(e,t,i),o=i[0];return n!=="progress"||o.kind!=="owed"?n:{...s.get(t[0].work.entityId)??{kind:"park",reason:o.reason,releaseOnProgress:!1,report:!1,again:!0},advanced:t.filter((d,y)=>i[y].kind!=="owed").map(d=>d.work.entityId)}}async#o(e,t,i,s){const n=[];for(const o of e){const a=t.get(o.work.entityId);if(!a){n.push(o);continue}let d;try{d=await this.#i(a.intent)?{kind:"captured-local"}:i==="look"?await this.#f(a):await a.adapter.apply.guard(a.intent,a.plan,i)}catch(g){if(n.length>0&&!this.#n())return{active:n,blocked:null,unseen:null};throw s.member=o,g}if(d.kind==="local-change"||d.kind==="unsettled-ground")return{active:n,blocked:n.length===0?I:null,unseen:a};if(D(d))return{active:n,blocked:n.length===0?I:null,unseen:null};const y=A(d);if(y)return{active:n,blocked:y,unseen:null};a.look=d.kind,n.push(o)}return{active:n,blocked:null,unseen:null}}async#u(e,t,i){for(const[s,n]of e.entries()){const o=t.get(n.work.entityId);if(!(!o||o.look!=="safe"))try{const a=await o.adapter.apply.prepare(o.intent,o.plan);if(a)return{active:e.slice(0,s),blocked:A(a)}}catch(a){if(s>0&&!this.#n())return{active:e.slice(0,s),blocked:null};throw i.member=n,a}}return{active:[...e],blocked:null}}async#p(e,t){const i=t.members.map(n=>{const o=e.members.find(d=>d.work.entityId===n.entityId);if(!o)return null;const a=n.kept===null?o.work:{...o.work,records:[],kept:n.kept};return a.records.length===0&&a.kept===null?null:(0,q.planSelectedEntityApply)(a,(0,E.selectEntityApply)(a,this.#r,n),this.#e.sha256Hex)}),s=await this.#e.effects.recover(t,i);if(s.length!==t.members.length)throw new Error("Apply recovery answered for a different window");return this.#t(t,e.members,e.members.map(n=>v(n)??s[t.members.findIndex(o=>o.entityId===n.work.entityId)]??{kind:"owed",reason:"not a member of the bound window"}))}async#t(e,t,i){const s=await this.#e.store.endWindow(e,t,i);if(!s)return"progress";if(s.kind!=="stale"||!s.reason)throw new Error("Apply end commit returned an unknown refusal");return I}async#i(e){return(0,M.localWorkWins)(e.targetType,await this.#e.store.localWorkAfter(e.authorityId,e.entityId,e.kept??e.throughSequence))}async#f(e){const{intent:t,plan:i,adapter:s}=e,n=await s.apply.guard(t,i,"look");if(n.kind!=="local-change"&&n.kind!=="unsettled-ground")return n;const o=await this.#l(t,i);if(o.kind!=="observed")return o;const a=await s.apply.guard(t,i,"look");return a.kind==="local-change"||a.kind==="unsettled-ground"?{kind:"retry",reason:"Ground still needs observation after Detect; this member cannot reveal."}:a}async#y(e){const t=await this.#l(e.intent,e.plan);return t.kind==="captured-local"?I:A(t.kind==="observed"?{kind:"retry",reason:"Its final guard found ground Detect had not recorded; it is judged again after Detect looks."}:t)}async#l(e,t){if(await this.#i(e))return{kind:"captured-local"};let i,s=!0;const n=await this.#e.effects.captureLocal(e,t,()=>{if(!s||i!==void 0)throw new Error("Apply capture comparison must be marked exactly once");i=this.#s()}).finally(()=>{s=!1});if(!n||!["settled","local-only","retry"].includes(n.kind))throw new Error("Apply capture returned no explicit observation outcome");if(await this.#i(e))return{kind:"captured-local"};if(n.kind==="retry")return n;if(n.kind==="local-only"){if(i===void 0)throw new Error("local-only capture requires a synchronous comparison fence");if(!n.reason||n.entityIds.length===0||n.entityIds.some(o=>!o))throw new Error("local-only capture must name the retained ground and its releasing condition");return{kind:"dependency",reason:n.reason,comparedAt:i,waitFor:{producer:"detect",entityIds:n.entityIds}}}return{kind:"observed"}}}exports.EntityApplyJourney=U;
@@ -1 +1 @@
1
- "use strict";var I=Object.defineProperty;var o=(a,e)=>I(a,"name",{value:e,configurable:!0});Object.defineProperty(exports,"__esModule",{value:!0}),exports.EntityApplyRail=exports.ENTITY_APPLY_RETRY_MAX_MS=exports.ENTITY_APPLY_RETRY_BASE_MS=exports.ENTITY_APPLY_DEFAULT_CONCURRENCY=void 0;const f=require("../entities/types.js"),_=require("./fetch-ahead.js"),c=require("./journey.js"),g=require("./lane.js"),l=require("./line.js");exports.ENTITY_APPLY_DEFAULT_CONCURRENCY=8,exports.ENTITY_APPLY_RETRY_BASE_MS=1e3,exports.ENTITY_APPLY_RETRY_MAX_MS=3e4;function E(a,e){return e.cause===void 0&&(0,c.stepsAside)(a,a.members[0].work.entityId)}o(E,"stuck");class k{static{o(this,"EntityApplyRail")}#e;#g;#P;#Y;#M;#a;#T;#o=!1;#t=!1;#d=new Map;#s=new Map;#l={queue:[],steps:new Set};#u={queue:[],steps:new Set};#n=!1;#h=null;#p=1/0;#m=[];#A=0;#b=new Map;#y=null;constructor(e){this.#e=e,this.#g=e.concurrency??exports.ENTITY_APPLY_DEFAULT_CONCURRENCY,this.#P=e.laneConcurrency??this.#g,this.#Y=e.onBackgroundError??(()=>{}),this.#M=e.onIdle??(()=>{});for(const[t,s]of[["concurrency",this.#g],["lane concurrency",this.#P]])if(!Number.isSafeInteger(s)||s<1)throw new Error(`entity Apply ${t} must be a positive integer`);this.#a=new c.EntityApplyJourney(e,()=>this.#A,()=>this.#t),this.#T=new _.FetchAhead(e.cargo,{sha256Hex:e.sha256Hex,loops:e.loops,deliveryPosition:e.deliveryPosition})}async start(){if(this.#o)throw new Error("entity Apply rail already started");if(this.#t)throw new Error("entity Apply rail is stopped");this.#o=!0;const e=await this.#e.store.readOpenUnits();if(!Array.isArray(e)||new Set(e).size!==e.length||e.some(t=>!f.UUID_PATTERN.test(t)))throw new Error("entity Apply store returned an invalid open unit list");for(const t of e)this.#E(t,null);await this.#N()}fetch(e,t){return this.#o?this.#t?Promise.reject(new Error("entity Apply rail is stopped")):f.UUID_PATTERN.test(e)?!Number.isFinite(t.stall)||t.stall<0?Promise.reject(new Error("entity Apply fetch needs a non-negative stall")):t.emptied!==void 0&&typeof t.emptied!="boolean"?Promise.reject(new Error("entity Apply fetch emptied must be a boolean")):new Promise((s,i)=>{const r=this.#E(e,null,t.emptied===!0),n=o(()=>this.#e.schedule.schedule(t.stall,()=>{r.waiters.delete(u)&&(r.emptied&&![...r.waiters].some(d=>d.emptied)&&(r.emptied=!1),s(this.#G(r)))}),"arm");let h=n();const u={emptied:t.emptied===!0,answer:o(d=>{h.cancel(),s(d)},"answer"),fail:o(d=>{h.cancel(),i(d)},"fail"),moved:o(()=>{h.cancel(),h=n()},"moved")};r.waiters.add(u),r.waitsOn===null&&this.#U(r),this.#r()}):Promise.reject(new Error("entity Apply fetch needs a unit UUID")):Promise.reject(new Error("entity Apply rail has not started"))}progressed(e,t){if(!f.UUID_PATTERN.test(e))throw new Error("entity Apply progress needs a unit UUID");if(!Number.isSafeInteger(t)||t<0)throw new Error("entity Apply progress needs a byte count");t>0&&!this.#t&&this.#k(e)}recordsAvailable(){this.#I()}localStateChanged(e){this.#c("detect",e),this.#c("apply",e),this.#I()}sendAccepted(e){this.#c("send",e),this.#I()}capabilityChanged(e){this.#c("capability",e),this.#I()}owe(e){if(e.some(t=>!f.UUID_PATTERN.test(t)))throw new Error("entity Apply owe needs entity UUIDs");if(!(!this.#o||this.#t)){for(const t of e)this.#O(t);this.#r()}}#I(){!this.#o||this.#t||(this.#n=!0,this.#r())}waiting(){return this.#w().flatMap(e=>(0,l.heldWait)(e.held,y(e))??[])}async flush(){if(!this.#o)throw new Error("entity Apply rail has not started");this.#t||await this.#N()}async stop(){if(this.#t)return;this.#t=!0,this.#S();for(const t of[this.#l,this.#u])for(const s of t.queue.splice(0))s.queued=!1;const e=new Error("entity Apply rail stopped before the fetch answered");for(const t of this.#s.values())for(const s of t.waiters)s.fail(e);for(this.#s.clear();this.#$()>0||this.#h;)await Promise.allSettled([...this.#l.steps,...this.#u.steps,...this.#h?[this.#h]:[]]);await this.#T.stop();for(const t of this.#m.splice(0))t.resolve()}#N(){return new Promise((e,t)=>{this.#m.push({resolve:e,reject:t}),this.#n=!0,this.#r()})}#r(){if(!this.#t){if(this.#n&&this.#h===null){this.#n=!1;const e=this.#F();this.#h=e,e.then(()=>{this.#h=null,this.#r()})}for(const[e,t]of[[this.#u,this.#P],[this.#l,this.#g]])for(;e.steps.size<t&&e.queue.length>0;){const s=e.queue.shift();s.queued=!1,this.#z(s,e)}if(this.#$()===0&&this.#h===null&&!this.#n&&this.#l.queue.length===0&&this.#u.queue.length===0){if(this.#b.clear(),this.#W(this.#e.now())){this.#r();return}this.#v();for(const e of this.#m.splice(0))e.resolve();this.#M()}}}#$(){return this.#l.steps.size+this.#u.steps.size}#w(){return[...this.#d.values(),...this.#s.values()]}#_(e){return e.kind==="line"?this.#d.get(e.authorityId)===e:this.#s.get(e.unit)===e}#i(e){if(!this.#t){if(e.running){e.again=!0;return}e.queued||(e.queued=!0,(e.kind==="line"?this.#l:this.#u).queue.push(e))}}#z(e,t){e.running=!0,e.again=!1;const s=(e.kind==="line"?this.#X(e):this.#J(e)).then(i=>{e.running=!1,t.steps.delete(s),(i||e.again)&&this.#_(e)&&(e.again=!1,this.#i(e)),this.#r()});t.steps.add(s)}async#F(){try{const e=await this.#e.store.readApplyAuthorities();if(!Array.isArray(e)||new Set(e).size!==e.length||e.some(s=>typeof s!="string"||s.length===0))throw new Error("entity Apply store returned an invalid authority list");this.#p=1/0;const t=new Set(e);for(const[s,i]of this.#d)!t.has(s)&&!i.running&&!i.queued&&this.#d.delete(s);for(const s of e){let i=this.#d.get(s);i||(i=(0,l.createApplyLine)(s),this.#d.set(s,i)),this.#i(i)}}catch(e){this.#p=this.#e.now()+exports.ENTITY_APPLY_RETRY_MAX_MS;const t=this.#m.splice(0);t.length===0&&this.#R(e);for(const s of t)s.reject(e)}}async#X(e){try{const t=e.held;if(t&&t.entityId===null&&!t.due&&t.notBefore>this.#e.now())return!1;const s=this.#A,i=await this.#e.store.readApplyWindow(e.authorityId);return(0,l.assertApplyLineStep)(e.authorityId,i),this.#t?!1:i.kind==="end"?(e.held=null,!1):(i.window.deliverySequence!==null&&this.#T.advance(e.authorityId,i.window.deliverySequence),await this.#j(e,i.window,s))}catch(t){return this.#B(e,t),!1}}async#J(e){try{const t=e.held;if(t&&t.entityId===null&&!t.due&&t.notBefore>this.#e.now())return!1;const s=this.#A,i=await this.#e.store.readFetchWindow(e.unit,e.toPrefix?null:e.through);if((0,g.assertApplyLaneStep)(e.unit,i),this.#t||!this.#_(e))return!1;if(e.waitsOn=null,i.kind==="unseen")return this.#q(e,{producer:"detect",entityIds:[e.unit]},i.reason,s);if(!e.again&&(i.kind!=="window"||i.window.intent===null)&&(e.toPrefix=!1),e.through!==null&&i.through>e.through&&e.met.clear(),e.through=Math.max(e.through??0,i.through),i.kind!=="window"&&(e.held=null),e.again&&(i.kind==="end"||i.kind==="nowhere"))return!0;switch(i.kind){case"end":return this.#f(e,{kind:"placed"}),!1;case"nowhere":return this.#f(e,{kind:"nowhere",reason:i.reason}),!1;case"root":return await this.#H(e,i.through,i.reason);case"prerequisite":return this.#V(e,i.unit,i.reason,s);case"window":return await this.#j(e,i.window,s)}}catch(t){return this.#B(e,t),!1}}async#H(e,t,s){return e.met.has(e.unit)?(this.#f(e,{kind:"held",unit:e.unit,reason:`${e.unit} entered and still not held: ${s}`}),!1):(await this.#e.effects.enterRoot(e.unit,t),this.#t||!this.#_(e)?!1:(e.through===t&&e.met.add(e.unit),this.#k(e.unit),!0))}#O(e){const t=this.#E(e,null);t.toPrefix=!0,t.met.clear(),this.#i(t)}#E(e,t,s=!1){let i=this.#s.get(e);return i?t!==null&&(i.through===null||i.through<t)&&(i.through=t,i.met.clear(),this.#i(i)):(i=(0,g.createApplyLane)(e,t,s),this.#s.set(e,i),this.#i(i)),i}#V(e,t,s,i){return e.met.has(t)?(this.#f(e,{kind:"held",unit:t,reason:`${t} placed and still needed: ${s}`}),!1):this.#L(e,t,s)?this.#q(e,{producer:"apply",entityIds:[t]},s,i):!1}#q(e,t,s,i){return e.held={entityId:null,target:null,kept:null,cutoff:null,attempt:1,notBefore:1/0,releaseOnProgress:!1,due:this.#x(t,i),reason:s,dependency:t},e.held.due}#U(e){const t=e.held;if(t?.dependency?.producer==="apply"){for(const s of t.dependency.entityIds)if(s!==e.unit&&!e.met.has(s)&&!this.#L(e,s,t.reason))return}}#L(e,t,s){const i=[e];let r=this.#s.get(t);for(;r&&r!==e&&!i.includes(r);)i.push(r),r=r.waitsOn===null?void 0:this.#s.get(r.waitsOn);if(r===e){for(const n of i)this.#f(n,{kind:"held",unit:t,reason:`prerequisite cycle through ${t}: ${s}`});return!1}return e.waitsOn??=t,this.#i(this.#E(t,e.through)),!0}#f(e,t){if(!this.#_(e))return;for(const i of e.waiters)i.answer(t);e.waiters.clear(),e.waitsOn=null,(t.kind==="placed"||e.held?.entityId==null)&&this.#s.delete(e.unit);const s=t.kind==="placed"||t.kind==="held"?t:{kind:"held",unit:e.unit,reason:`${e.unit} is nowhere here: ${t.reason}`};for(const i of[...this.#s.values()])if(i.waitsOn===e.unit){if(t.kind!=="placed"){this.#f(i,s);continue}i.met.add(e.unit)}t.kind==="placed"&&(this.#k(e.unit),this.#c("apply",[e.unit]))}#k(e){const t=new Map([[e,!0]]);for(const s of this.#s.values()){const i=new Set;let r=s.unit;for(;r!==null&&!t.has(r)&&!i.has(r);)i.add(r),r=this.#s.get(r)?.waitsOn??null;const n=r!==null&&t.get(r)===!0;for(const h of i)t.set(h,n);if(n)for(const h of s.waiters)h.moved()}}#G(e){let t=e;const s=new Set([e]);for(let i=e.waitsOn===null?void 0:this.#s.get(e.waitsOn);i&&!s.has(i);i=i.waitsOn===null?void 0:this.#s.get(i.waitsOn))s.add(i),t=i;return{kind:"held",unit:t.unit,reason:t.held?.reason??"still placing"}}async#j(e,t,s){const i=t.members[0]?.work.entityId??null;if(e.held&&e.held.entityId!==null&&e.held.entityId!==i&&(e.held=null),await this.#Q(e,t))return!1;let r=await(0,c.outcomeOf)(()=>this.#a.run(t,()=>e.kind==="lane"&&e.emptied?e.unit:null));if(e.kind==="line"&&typeof r=="object"&&r.kind==="park"&&E(t,r)&&(r=await(0,c.outcomeOf)(()=>this.#a.alone(t.members[0]))),r==="progress"||typeof r=="object"&&r.kind==="alone"){if(e.kind==="line")for(const n of t.members)(n.judgment==="waiting"||r!=="progress"&&n.work.entityId===r.entityId)&&this.#O(n.work.entityId);for(const n of t.members)n.unseen!==void 0&&this.#O(n.unseen);return this.#Z(e,r==="progress"?t.members.map(n=>n.work.entityId):[r.entityId])}return r==="again"?(e.held?.entityId===i&&(e.held=null),!0):(r.advanced?.length&&this.#C(e,r.advanced),this.#ee(e,t,r,s),e.kind==="lane"&&this.#U(e),e.held.due)}#K(e,t){const s=e.held,i=t.members[0].work.entityId;return(s?.entityId===i&&s.target===this.#a.targetOf(t)?s.attempt:0)+1}async#Q(e,t){const s=e.held,i=t.members[0];return!s||i===void 0||s.entityId!==i.work.entityId||s.due||s.notBefore<=this.#e.now()||this.#a.targetOf(t)!==s.target||t.cutoff!==s.cutoff?!1:await this.#e.store.localWorkAfter(t.authorityId,i.work.entityId,s.kept??s.target)===null}#Z(e,t){return e.held&&(e.held.entityId===null||t.includes(e.held.entityId))&&(e.held=null),this.#C(e,t),!0}#C(e,t){e.kind==="lane"&&(this.#n=!0,this.#k(e.unit)),this.#c("apply",t);for(const s of this.#w())s!==e&&s.held?.releaseOnProgress&&!s.held.due&&(s.held.due=!0,this.#i(s))}#ee(e,t,s,i){if(s.dependency&&(0,l.assertApplyDependency)(s.dependency),s.blocker&&!s.dependency)throw new Error("Apply blocker must name the dependency that releases it");const r=t.members[0].work.entityId,n=e.held,h=this.#K(e,t),u=this.#D(h),d=s.again===!0&&h===1,w={entityId:r,target:this.#a.targetOf(t),kept:t.members[0].work.kept,cutoff:t.cutoff,attempt:h,notBefore:s.dependency?1/0:this.#e.now()+(d?0:u),releaseOnProgress:s.releaseOnProgress,due:s.dependency?this.#x(s.dependency,s.comparedAt??i):d,reason:s.reason,...s.dependency?{dependency:s.dependency}:{},...s.blocker?{blocker:s.blocker}:{}};e.held=w,this.#v();const A=(0,l.heldWait)(n,y(e)),p=(0,l.heldWait)(w,y(e));p&&JSON.stringify(p)!==JSON.stringify(A)&&this.#e.onWaiting?.(p),!(!s.report&&(s.dependency!==void 0||h===1))&&this.#R(new Error(`${m(e)} holds at ${r}, which ${s.releaseOnProgress?"is parked on a conflict":s.report?"failed":s.again?"keeps ending unplaced":"stands on ground that keeps moving"}, and will retry in ${u}ms (attempt ${h}): ${s.reason}`,s.cause===void 0?void 0:{cause:s.cause}))}#B(e,t){if(e.kind==="lane"){for(const h of e.waiters)h.fail(t);e.waiters.clear()}const s=e.held,i=(s?.entityId===null?s.attempt:0)+1,r=this.#D(i),n=t instanceof Error?t.message:String(t);e.held={entityId:null,target:null,kept:null,cutoff:null,attempt:i,notBefore:this.#e.now()+r,releaseOnProgress:!1,due:!1,reason:n},this.#v(),this.#R(new Error(`${m(e)} faulted and will retry in ${r}ms (attempt ${i}): ${n}`,{cause:t}))}#R(e){try{this.#Y(e)}catch{}}#D(e){const t=Math.min(exports.ENTITY_APPLY_RETRY_MAX_MS,exports.ENTITY_APPLY_RETRY_BASE_MS*2**Math.min(e-1,16)),s=Math.max(0,Math.min(1,this.#e.schedule.random()));return Math.round(t*(.5+s))}#c(e,t){const s=++this.#A;for(const i of t??["*"])this.#b.set(`${e}:${i}`,s);for(const i of this.#w())(0,l.releaseApplyLine)(i,e,t)&&this.#i(i)}#x(e,t){return["*",...e.entityIds].some(s=>(this.#b.get(`${e.producer}:${s}`)??0)>t)}#v(){if(this.#t)return;let e=this.#p;for(const i of this.#w())i.held&&!i.held.due&&(e=Math.min(e,i.held.notBefore));if(e===1/0){this.#S();return}if(this.#y?.dueAt===e)return;this.#S();const t=Math.max(0,e-this.#e.now()),s=this.#e.schedule.schedule(t,()=>{this.#y=null,this.#W(e),this.#r()});this.#y={dueAt:e,cancel:o(()=>s.cancel(),"cancel")}}#W(e){let t=!1;for(const s of this.#w())s.held&&!s.held.due&&s.held.notBefore<=e&&(s.held.due=!0,this.#i(s),t=!0);return this.#p<=e&&(this.#p=1/0,this.#n=!0,t=!0),t}#S(){this.#y?.cancel(),this.#y=null}}exports.EntityApplyRail=k;const y=o(a=>a.kind==="line"?a.authorityId:a.unit,"owner"),m=o(a=>a.kind==="line"?`entity Apply line ${a.authorityId}`:`entity Apply fetch of ${a.unit}`,"label");
1
+ "use strict";var I=Object.defineProperty;var o=(a,e)=>I(a,"name",{value:e,configurable:!0});Object.defineProperty(exports,"__esModule",{value:!0}),exports.EntityApplyRail=exports.ENTITY_APPLY_RETRY_MAX_MS=exports.ENTITY_APPLY_RETRY_BASE_MS=exports.ENTITY_APPLY_DEFAULT_CONCURRENCY=void 0;const f=require("../entities/types.js"),_=require("./fetch-ahead.js"),c=require("./journey.js"),g=require("./lane.js"),l=require("./line.js");exports.ENTITY_APPLY_DEFAULT_CONCURRENCY=8,exports.ENTITY_APPLY_RETRY_BASE_MS=1e3,exports.ENTITY_APPLY_RETRY_MAX_MS=3e4;function E(a,e){return e.cause===void 0&&(0,c.stepsAside)(a,a.members[0].work.entityId)}o(E,"stuck");class k{static{o(this,"EntityApplyRail")}#e;#g;#P;#Y;#M;#a;#T;#o=!1;#t=!1;#d=new Map;#s=new Map;#l={queue:[],steps:new Set};#u={queue:[],steps:new Set};#n=!1;#h=null;#p=1/0;#m=[];#A=0;#b=new Map;#y=null;constructor(e){this.#e=e,this.#g=e.concurrency??exports.ENTITY_APPLY_DEFAULT_CONCURRENCY,this.#P=e.laneConcurrency??this.#g,this.#Y=e.onBackgroundError??(()=>{}),this.#M=e.onIdle??(()=>{});for(const[t,s]of[["concurrency",this.#g],["lane concurrency",this.#P]])if(!Number.isSafeInteger(s)||s<1)throw new Error(`entity Apply ${t} must be a positive integer`);this.#a=new c.EntityApplyJourney(e,()=>this.#A,()=>this.#t),this.#T=new _.FetchAhead(e.cargo,{sha256Hex:e.sha256Hex,loops:e.loops,deliveryPosition:e.deliveryPosition})}async start(){if(this.#o)throw new Error("entity Apply rail already started");if(this.#t)throw new Error("entity Apply rail is stopped");this.#o=!0;const e=await this.#e.store.readOpenUnits();if(!Array.isArray(e)||new Set(e).size!==e.length||e.some(t=>!f.UUID_PATTERN.test(t)))throw new Error("entity Apply store returned an invalid open unit list");for(const t of e)this.#E(t,null);await this.#N()}fetch(e,t){return this.#o?this.#t?Promise.reject(new Error("entity Apply rail is stopped")):f.UUID_PATTERN.test(e)?!Number.isFinite(t.stall)||t.stall<0?Promise.reject(new Error("entity Apply fetch needs a non-negative stall")):t.emptied!==void 0&&typeof t.emptied!="boolean"?Promise.reject(new Error("entity Apply fetch emptied must be a boolean")):new Promise((s,i)=>{const r=this.#E(e,null,t.emptied===!0),n=o(()=>this.#e.schedule.schedule(t.stall,()=>{r.waiters.delete(u)&&(r.emptied&&![...r.waiters].some(d=>d.emptied)&&(r.emptied=!1),s(this.#G(r)))}),"arm");let h=n();const u={emptied:t.emptied===!0,answer:o(d=>{h.cancel(),s(d)},"answer"),fail:o(d=>{h.cancel(),i(d)},"fail"),moved:o(()=>{h.cancel(),h=n()},"moved")};r.waiters.add(u),r.waitsOn===null&&this.#U(r),this.#r()}):Promise.reject(new Error("entity Apply fetch needs a unit UUID")):Promise.reject(new Error("entity Apply rail has not started"))}progressed(e,t){if(!f.UUID_PATTERN.test(e))throw new Error("entity Apply progress needs a unit UUID");if(!Number.isSafeInteger(t)||t<0)throw new Error("entity Apply progress needs a byte count");t>0&&!this.#t&&this.#k(e)}recordsAvailable(){this.#I()}localStateChanged(e){this.#c("detect",e),this.#c("apply",e),this.#I()}sendAccepted(e){this.#c("send",e),this.#I()}capabilityChanged(e){this.#c("capability",e),this.#I()}owe(e){if(e.some(t=>!f.UUID_PATTERN.test(t)))throw new Error("entity Apply owe needs entity UUIDs");if(!(!this.#o||this.#t)){for(const t of e)this.#O(t);this.#r()}}#I(){!this.#o||this.#t||(this.#n=!0,this.#r())}waiting(){return this.#w().flatMap(e=>(0,l.heldWait)(e.held,y(e))??[])}async flush(){if(!this.#o)throw new Error("entity Apply rail has not started");this.#t||await this.#N()}async stop(){if(this.#t)return;this.#t=!0,this.#S();for(const t of[this.#l,this.#u])for(const s of t.queue.splice(0))s.queued=!1;const e=new Error("entity Apply rail stopped before the fetch answered");for(const t of this.#s.values())for(const s of t.waiters)s.fail(e);for(this.#s.clear();this.#$()>0||this.#h;)await Promise.allSettled([...this.#l.steps,...this.#u.steps,...this.#h?[this.#h]:[]]);await this.#T.stop();for(const t of this.#m.splice(0))t.resolve()}#N(){return new Promise((e,t)=>{this.#m.push({resolve:e,reject:t}),this.#n=!0,this.#r()})}#r(){if(!this.#t){if(this.#n&&this.#h===null){this.#n=!1;const e=this.#F();this.#h=e,e.then(()=>{this.#h=null,this.#r()})}for(const[e,t]of[[this.#u,this.#P],[this.#l,this.#g]])for(;e.steps.size<t&&e.queue.length>0;){const s=e.queue.shift();s.queued=!1,this.#z(s,e)}if(this.#$()===0&&this.#h===null&&!this.#n&&this.#l.queue.length===0&&this.#u.queue.length===0){if(this.#b.clear(),this.#W(this.#e.now())){this.#r();return}this.#v();for(const e of this.#m.splice(0))e.resolve();this.#M()}}}#$(){return this.#l.steps.size+this.#u.steps.size}#w(){return[...this.#d.values(),...this.#s.values()]}#_(e){return e.kind==="line"?this.#d.get(e.authorityId)===e:this.#s.get(e.unit)===e}#i(e){if(!this.#t){if(e.running){e.again=!0;return}e.queued||(e.queued=!0,(e.kind==="line"?this.#l:this.#u).queue.push(e))}}#z(e,t){e.running=!0,e.again=!1;const s=(e.kind==="line"?this.#X(e):this.#J(e)).then(i=>{e.running=!1,t.steps.delete(s),(i||e.again)&&this.#_(e)&&(e.again=!1,this.#i(e)),this.#r()});t.steps.add(s)}async#F(){try{const e=await this.#e.store.readApplyAuthorities();if(!Array.isArray(e)||new Set(e).size!==e.length||e.some(s=>typeof s!="string"||s.length===0))throw new Error("entity Apply store returned an invalid authority list");this.#p=1/0;const t=new Set(e);for(const[s,i]of this.#d)!t.has(s)&&!i.running&&!i.queued&&this.#d.delete(s);for(const s of e){let i=this.#d.get(s);i||(i=(0,l.createApplyLine)(s),this.#d.set(s,i)),this.#i(i)}}catch(e){this.#p=this.#e.now()+exports.ENTITY_APPLY_RETRY_MAX_MS;const t=this.#m.splice(0);t.length===0&&this.#R(e);for(const s of t)s.reject(e)}}async#X(e){try{const t=e.held;if(t&&t.entityId===null&&!t.due&&t.notBefore>this.#e.now())return!1;const s=this.#A,i=await this.#e.store.readApplyWindow(e.authorityId);return(0,l.assertApplyLineStep)(e.authorityId,i),this.#t?!1:i.kind==="end"?(e.held=null,!1):(i.window.deliverySequence!==null&&this.#T.advance(e.authorityId,i.window.deliverySequence),await this.#j(e,i.window,s))}catch(t){return this.#B(e,t),!1}}async#J(e){try{const t=e.held;if(t&&t.entityId===null&&!t.due&&t.notBefore>this.#e.now())return!1;const s=this.#A,i=await this.#e.store.readFetchWindow(e.unit,e.toPrefix?null:e.through);if((0,g.assertApplyLaneStep)(e.unit,i),this.#t||!this.#_(e))return!1;if(e.waitsOn=null,i.kind==="unseen")return this.#q(e,{producer:"detect",entityIds:[e.unit]},i.reason,s);if(!e.again&&(i.kind!=="window"||i.window.intent===null)&&(e.toPrefix=!1),e.through!==null&&i.through>e.through&&e.met.clear(),e.through=Math.max(e.through??0,i.through),i.kind!=="window"&&(e.held=null),e.again&&(i.kind==="end"||i.kind==="nowhere"))return!0;switch(i.kind){case"end":return this.#f(e,{kind:"placed"}),!1;case"nowhere":return this.#f(e,{kind:"nowhere",reason:i.reason}),!1;case"root":return await this.#H(e,i.through,i.reason);case"prerequisite":return this.#V(e,i.unit,i.reason,s);case"window":return await this.#j(e,i.window,s)}}catch(t){return this.#B(e,t),!1}}async#H(e,t,s){return e.met.has(e.unit)?(this.#f(e,{kind:"held",unit:e.unit,reason:`${e.unit} entered and still not held: ${s}`}),!1):(await this.#e.effects.enterRoot(e.unit,t),this.#t||!this.#_(e)?!1:(e.through===t&&e.met.add(e.unit),this.#k(e.unit),!0))}#O(e){const t=this.#E(e,null);t.toPrefix=!0,t.met.clear(),this.#i(t)}#E(e,t,s=!1){let i=this.#s.get(e);return i?t!==null&&(i.through===null||i.through<t)&&(i.through=t,i.met.clear(),this.#i(i)):(i=(0,g.createApplyLane)(e,t,s),this.#s.set(e,i),this.#i(i)),i}#V(e,t,s,i){return e.met.has(t)?(this.#f(e,{kind:"held",unit:t,reason:`${t} placed and still needed: ${s}`}),!1):this.#L(e,t,s)?this.#q(e,{producer:"apply",entityIds:[t]},s,i):!1}#q(e,t,s,i){return e.held={entityId:null,target:null,kept:null,cutoff:null,attempt:1,notBefore:1/0,releaseOnProgress:!1,due:this.#x(t,i),reason:s,dependency:t},e.held.due}#U(e){const t=e.held;if(t?.dependency?.producer==="apply"){for(const s of t.dependency.entityIds)if(s!==e.unit&&!e.met.has(s)&&!this.#L(e,s,t.reason))return}}#L(e,t,s){const i=[e];let r=this.#s.get(t);for(;r&&r!==e&&!i.includes(r);)i.push(r),r=r.waitsOn===null?void 0:this.#s.get(r.waitsOn);if(r===e){for(const n of i)this.#f(n,{kind:"held",unit:t,reason:`prerequisite cycle through ${t}: ${s}`});return!1}return e.waitsOn??=t,this.#i(this.#E(t,e.through)),!0}#f(e,t){if(!this.#_(e))return;for(const i of e.waiters)i.answer(t);e.waiters.clear(),e.waitsOn=null,(t.kind==="placed"||e.held?.entityId==null)&&this.#s.delete(e.unit);const s=t.kind==="placed"||t.kind==="held"?t:{kind:"held",unit:e.unit,reason:`${e.unit} is nowhere here: ${t.reason}`};for(const i of[...this.#s.values()])if(i.waitsOn===e.unit){if(t.kind!=="placed"){this.#f(i,s);continue}i.met.add(e.unit)}t.kind==="placed"&&(this.#k(e.unit),this.#c("apply",[e.unit]))}#k(e){const t=new Map([[e,!0]]);for(const s of this.#s.values()){const i=new Set;let r=s.unit;for(;r!==null&&!t.has(r)&&!i.has(r);)i.add(r),r=this.#s.get(r)?.waitsOn??null;const n=r!==null&&t.get(r)===!0;for(const h of i)t.set(h,n);if(n)for(const h of s.waiters)h.moved()}}#G(e){let t=e;const s=new Set([e]);for(let i=e.waitsOn===null?void 0:this.#s.get(e.waitsOn);i&&!s.has(i);i=i.waitsOn===null?void 0:this.#s.get(i.waitsOn))s.add(i),t=i;return{kind:"held",unit:t.unit,reason:t.held?.reason??"still placing"}}async#j(e,t,s){const i=t.members[0]?.work.entityId??null;if(e.held&&e.held.entityId!==null&&e.held.entityId!==i&&(e.held=null),await this.#Q(e,t))return!1;let r=await(0,c.outcomeOf)(()=>this.#a.run(t,()=>e.kind==="lane"&&e.emptied?e.unit:null));if(e.kind==="line"&&!this.#t&&typeof r=="object"&&r.kind==="park"&&E(t,r)&&(r=await(0,c.outcomeOf)(()=>this.#a.alone(t.members[0]))),r==="progress"||typeof r=="object"&&r.kind==="alone"){if(e.kind==="line")for(const n of t.members)(n.judgment==="waiting"||r!=="progress"&&n.work.entityId===r.entityId)&&this.#O(n.work.entityId);for(const n of t.members)n.unseen!==void 0&&this.#O(n.unseen);return this.#Z(e,r==="progress"?t.members.map(n=>n.work.entityId):[r.entityId])}return r.advanced?.length&&this.#C(e,r.advanced),this.#ee(e,t,r,s),e.kind==="lane"&&this.#U(e),e.held.due}#K(e,t){const s=e.held,i=t.members[0].work.entityId;return(s?.entityId===i&&s.target===this.#a.targetOf(t)?s.attempt:0)+1}async#Q(e,t){const s=e.held,i=t.members[0];return!s||i===void 0||s.entityId!==i.work.entityId||s.due||s.notBefore<=this.#e.now()||this.#a.targetOf(t)!==s.target||t.cutoff!==s.cutoff?!1:await this.#e.store.localWorkAfter(t.authorityId,i.work.entityId,s.kept??s.target)===null}#Z(e,t){return e.held&&(e.held.entityId===null||t.includes(e.held.entityId))&&(e.held=null),this.#C(e,t),!0}#C(e,t){e.kind==="lane"&&(this.#n=!0,this.#k(e.unit)),this.#c("apply",t);for(const s of this.#w())s!==e&&s.held?.releaseOnProgress&&!s.held.due&&(s.held.due=!0,this.#i(s))}#ee(e,t,s,i){if(s.dependency&&(0,l.assertApplyDependency)(s.dependency),s.blocker&&!s.dependency)throw new Error("Apply blocker must name the dependency that releases it");const r=t.members[0].work.entityId,n=e.held,h=this.#K(e,t),u=this.#D(h),d=s.again===!0&&h===1,w={entityId:r,target:this.#a.targetOf(t),kept:t.members[0].work.kept,cutoff:t.cutoff,attempt:h,notBefore:s.dependency?1/0:this.#e.now()+(d?0:u),releaseOnProgress:s.releaseOnProgress,due:s.dependency?this.#x(s.dependency,s.comparedAt??i):d,reason:s.reason,...s.dependency?{dependency:s.dependency}:{},...s.blocker?{blocker:s.blocker}:{}};e.held=w,this.#v();const A=(0,l.heldWait)(n,y(e)),p=(0,l.heldWait)(w,y(e));p&&JSON.stringify(p)!==JSON.stringify(A)&&this.#e.onWaiting?.(p),!(!s.report&&(s.dependency!==void 0||h===1))&&this.#R(new Error(`${m(e)} holds at ${r}, which ${s.releaseOnProgress?"is parked on a conflict":s.report?"failed":s.again?"keeps ending unplaced":"stands on ground that keeps moving"}, and will retry in ${u}ms (attempt ${h}): ${s.reason}`,s.cause===void 0?void 0:{cause:s.cause}))}#B(e,t){if(e.kind==="lane"){for(const h of e.waiters)h.fail(t);e.waiters.clear()}const s=e.held,i=(s?.entityId===null?s.attempt:0)+1,r=this.#D(i),n=t instanceof Error?t.message:String(t);e.held={entityId:null,target:null,kept:null,cutoff:null,attempt:i,notBefore:this.#e.now()+r,releaseOnProgress:!1,due:!1,reason:n},this.#v(),this.#R(new Error(`${m(e)} faulted and will retry in ${r}ms (attempt ${i}): ${n}`,{cause:t}))}#R(e){try{this.#Y(e)}catch{}}#D(e){const t=Math.min(exports.ENTITY_APPLY_RETRY_MAX_MS,exports.ENTITY_APPLY_RETRY_BASE_MS*2**Math.min(e-1,16)),s=Math.max(0,Math.min(1,this.#e.schedule.random()));return Math.round(t*(.5+s))}#c(e,t){const s=++this.#A;for(const i of t??["*"])this.#b.set(`${e}:${i}`,s);for(const i of this.#w())(0,l.releaseApplyLine)(i,e,t)&&this.#i(i)}#x(e,t){return["*",...e.entityIds].some(s=>(this.#b.get(`${e.producer}:${s}`)??0)>t)}#v(){if(this.#t)return;let e=this.#p;for(const i of this.#w())i.held&&!i.held.due&&(e=Math.min(e,i.held.notBefore));if(e===1/0){this.#S();return}if(this.#y?.dueAt===e)return;this.#S();const t=Math.max(0,e-this.#e.now()),s=this.#e.schedule.schedule(t,()=>{this.#y=null,this.#W(e),this.#r()});this.#y={dueAt:e,cancel:o(()=>s.cancel(),"cancel")}}#W(e){let t=!1;for(const s of this.#w())s.held&&!s.held.due&&s.held.notBefore<=e&&(s.held.due=!0,this.#i(s),t=!0);return this.#p<=e&&(this.#p=1/0,this.#n=!0,t=!0),t}#S(){this.#y?.cancel(),this.#y=null}}exports.EntityApplyRail=k;const y=o(a=>a.kind==="line"?a.authorityId:a.unit,"owner"),m=o(a=>a.kind==="line"?`entity Apply line ${a.authorityId}`:`entity Apply fetch of ${a.unit}`,"label");
@@ -1 +1 @@
1
- "use strict";var b=Object.defineProperty;var l=(t,s)=>b(t,"name",{value:s,configurable:!0});Object.defineProperty(exports,"__esModule",{value:!0}),exports.contentKind=void 0,exports.playChange=U;const c=require("../entities/rules.js"),y=require("../git/checkout.js"),P=require("../entities/types.js"),p=l(t=>P.CONTAINERS.has(t)?t:"file","contentKind");exports.contentKind=p;function U(t,s,i,m,u){const e=k(t,s,i,m),a=e.row;if(a===null)return e;const n=t?.status==="active"&&a.parentUUID===t.parentUUID&&a.name===t.name,r=a.status!=="active"||a.parentUUID===null?void 0:n?t.slotPosition:s.deliverySequence??u?.();if(a.slotPosition===r)return e;const{slotPosition:o,...f}=a;return{...e,row:r===void 0?f:{...f,slotPosition:r}}}l(U,"playChange");function k(t,s,i,m){const{facets:u,result:e}=s;if(s.joins!==void 0)return t!==null&&t.status!=="deleted"&&t.version===s.joins?{row:e,setsPayload:!0}:{row:t,setsPayload:!1};const a=m===void 0?e.parentUUID:m.keeps;if(t===null||u.includes("create")){if(t?.status==="deleted")return{row:t,setsPayload:!1};if(a===e.parentUUID)return{row:e,setsPayload:!0};const d={...e,parentUUID:a};return{row:{...d,version:(0,c.canonicalVersion)(d,i)},setsPayload:!0}}if(t.status==="deleted")return{row:t,setsPayload:!1};let n=t,r=!1;const o=l(d=>{n={...n,...d}},"set"),f=l(()=>{o({type:e.type,fileMode:(0,y.fileAbsent)(e)||!(0,c.validPortableFileMode)(e.type,n.fileMode)?e.fileMode:n.fileMode,mtime:(0,y.fileAbsent)(e)||!(0,c.validPortableMtime)(e.type,n.mtime)?e.mtime:n.mtime,payloadVersion:e.payloadVersion,size:e.size,linkTarget:e.linkTarget,gitHomeEntity:e.gitHomeEntity,gitHomePath:e.gitHomePath,transportVersion:e.transportVersion}),r=!0},"becomes");for(const d of u)switch(d){case"move":o({parentUUID:a});break;case"rename":o({name:e.name});break;case"retype":f();break;case"content":(0,exports.contentKind)(n.type)===(0,exports.contentKind)(e.type)&&f();break;case"mode":!(0,y.fileAbsent)(n)&&(0,c.validPortableFileMode)(n.type,e.fileMode)&&o({fileMode:e.fileMode});break;case"time":!(0,y.fileAbsent)(n)&&(0,c.validPortableMtime)(n.type,e.mtime)&&o({mtime:e.mtime});break;case"trash":o({status:"trashed"});break;case"restore":n.status==="trashed"&&o({status:"active"});break;case"delete":o({status:"deleted"});break;case"create":break}return n===t?{row:t,setsPayload:!1}:M(n,e)?{row:e,setsPayload:r}:{row:{...n,version:(0,c.canonicalVersion)(n,i)},setsPayload:r}}l(k,"playFacets");const w=["uuid","type","parentUUID","name","status","payloadVersion","fileMode","mtime","size","linkTarget","gitHomeEntity","gitHomePath","transportVersion"],M=l((t,s)=>w.every(i=>t[i]===s[i]),"sameFields");
1
+ "use strict";var b=Object.defineProperty;var l=(t,n)=>b(t,"name",{value:n,configurable:!0});Object.defineProperty(exports,"__esModule",{value:!0}),exports.sameFields=exports.contentKind=void 0,exports.playChange=U;const c=require("../entities/rules.js"),y=require("../git/checkout.js"),P=require("../entities/types.js"),p=l(t=>P.CONTAINERS.has(t)?t:"file","contentKind");exports.contentKind=p;function U(t,n,i,m,u){const e=k(t,n,i,m),a=e.row;if(a===null)return e;const s=t?.status==="active"&&a.parentUUID===t.parentUUID&&a.name===t.name,r=a.status!=="active"||a.parentUUID===null?void 0:s?t.slotPosition:n.deliverySequence??u?.();if(a.slotPosition===r)return e;const{slotPosition:o,...f}=a;return{...e,row:r===void 0?f:{...f,slotPosition:r}}}l(U,"playChange");function k(t,n,i,m){const{facets:u,result:e}=n;if(n.joins!==void 0)return t!==null&&t.status!=="deleted"&&t.version===n.joins?{row:e,setsPayload:!0}:{row:t,setsPayload:!1};const a=m===void 0?e.parentUUID:m.keeps;if(t===null||u.includes("create")){if(t?.status==="deleted")return{row:t,setsPayload:!1};if(a===e.parentUUID)return{row:e,setsPayload:!0};const d={...e,parentUUID:a};return{row:{...d,version:(0,c.canonicalVersion)(d,i)},setsPayload:!0}}if(t.status==="deleted")return{row:t,setsPayload:!1};let s=t,r=!1;const o=l(d=>{s={...s,...d}},"set"),f=l(()=>{o({type:e.type,fileMode:(0,y.fileAbsent)(e)||!(0,c.validPortableFileMode)(e.type,s.fileMode)?e.fileMode:s.fileMode,mtime:(0,y.fileAbsent)(e)||!(0,c.validPortableMtime)(e.type,s.mtime)?e.mtime:s.mtime,payloadVersion:e.payloadVersion,size:e.size,linkTarget:e.linkTarget,gitHomeEntity:e.gitHomeEntity,gitHomePath:e.gitHomePath,transportVersion:e.transportVersion}),r=!0},"becomes");for(const d of u)switch(d){case"move":o({parentUUID:a});break;case"rename":o({name:e.name});break;case"retype":f();break;case"content":(0,exports.contentKind)(s.type)===(0,exports.contentKind)(e.type)&&f();break;case"mode":!(0,y.fileAbsent)(s)&&(0,c.validPortableFileMode)(s.type,e.fileMode)&&o({fileMode:e.fileMode});break;case"time":!(0,y.fileAbsent)(s)&&(0,c.validPortableMtime)(s.type,e.mtime)&&o({mtime:e.mtime});break;case"trash":o({status:"trashed"});break;case"restore":s.status==="trashed"&&o({status:"active"});break;case"delete":o({status:"deleted"});break;case"create":break}return s===t?{row:t,setsPayload:!1}:(0,exports.sameFields)(s,e)?{row:e,setsPayload:r}:{row:{...s,version:(0,c.canonicalVersion)(s,i)},setsPayload:r}}l(k,"playFacets");const w=["uuid","type","parentUUID","name","status","payloadVersion","fileMode","mtime","size","linkTarget","gitHomeEntity","gitHomePath","transportVersion"],M=l((t,n)=>w.every(i=>t[i]===n[i]),"sameFields");exports.sameFields=M;
@@ -1,4 +1,4 @@
1
- "use strict";var ae=Object.defineProperty;var r=(t,a)=>ae(t,"name",{value:a,configurable:!0});Object.defineProperty(exports,"__esModule",{value:!0}),exports.gitOwnChange=ne,exports.gitLineChanges=re,exports.gitPlayable=fe,exports.gitPlayRecord=ge;const ee=require("../entities/bytes.js"),ce=require("./alternates.js"),te=require("./artifact.js"),x=require("./refs.js"),E=require("./state.js"),B=require("./text.js");function ne(t){return t.facets.some(f=>f==="create"||f==="retype"||f==="content")&&t.result.status==="active"?t.result.transportVersion:null}r(ne,"gitOwnChange");function re(t){let a=[],f=!1;for(const h of t){if(h.result.type!=="repo.git"){a=[],f=!0;continue}const p=ne(h);p!==null&&a.push(p)}return{reached:a,ended:f}}r(re,"gitLineChanges");function fe({line:t,basis:a,record:f}){const h=r(l=>l.files.find(c=>c.path===ce.GIT_ALTERNATES_PATH)?.oid??null,"borrowed"),p=r(l=>l.files.some(c=>c.path==="reftable"),"reftable");return t.format===f.format&&(a===null||a.format===f.format)&&!(0,E.gitSharesObjects)(t)&&!(0,E.gitSelfHeld)(t.home)&&!(0,E.gitSharesGitDir)(t.home)&&t.home?.entity===f.home?.entity&&t.home?.path===f.home?.path&&h(t)===h(f)&&![t,f,...a?[a]:[]].some(l=>p(l)||(0,E.gitBytesForm)(l))}r(fe,"gitPlayable");const z="040000",F=r(t=>new Map(t.map(a=>[a.path,a])),"byPath"),N=r((t,a)=>t===void 0?a===void 0:a!==void 0&&t.mode===a.mode&&t.oid===a.oid,"same"),se=r(t=>{const a=[];for(let f=t.indexOf("/");f>0;f=t.indexOf("/",f+1))a.push(t.slice(0,f));return a},"parents");function le(t,a,f){const h=new Set;for(const l of t.keys()){const c=se(l).find(k=>t.has(k)&&t.get(k).mode!==z);c!==void 0&&h.add(c)}const p=r(l=>h.has(l)||se(l).some(c=>h.has(c)),"clashed");if(h.size>0){for(const l of[...t.keys()])p(l)&&t.delete(l);for(const[l,c]of a)p(l)&&t.set(l,c)}return(0,E.gitTreeOf)(t.values(),f)}r(le,"asTree");const D=["line","basis","record"],P=r(t=>t.mode!==z&&(t.path==="HEAD"||t.path.startsWith("refs/")),"isLooseRef"),oe=r(t=>P(t)||t.path==="packed-refs","isRefFile"),de=r(t=>t.startsWith("logs/"),"isReflogPath"),V="refs/stash",J="refs/heads/",K=`${J}amalgm`,ue=7,he=/^[0-9a-f]{7,}$/,Q=r((t,a)=>t.startsWith(`${a}/`),"beneath");async function ge(t,a,f,h){const p={format:t.record.format,home:t.record.home,files:[],index:null},l={line:t.line,basis:t.basis??p,record:t.record},c={line:F(l.line.files),basis:F(l.basis.files),record:F(l.record.files)},k=new Map,_=r((e,n)=>{const s=(0,ee.utf8Encode)(n),i=(0,te.gitBlobId)(s,h);return k.set(i,s),{path:e,mode:"100644",oid:i}},"make"),w=r(async e=>e?.oid?(0,ee.utf8Decode)(k.get(e.oid)??await a(e.oid)):"","read"),H=new Map,I=r(e=>(H.has(e)||H.set(e,w(c[e].get("packed-refs")).then(x.gitPackedRefs)),H.get(e)),"packedOf"),y=r(async(e,n)=>{const s=c[e].get(n);return s!==void 0&&P(s)?(0,x.gitLooseRef)(await w(s)):n==="HEAD"?null:(await I(e)).get(n)??null},"value"),T=r(e=>!N(c.basis.get(e),c.record.get(e)),"recordChanged"),u=new Map;for(const e of new Set([...c.line.keys(),...c.basis.keys(),...c.record.keys()])){const n=T(e)?c.record.get(e):c.line.get(e);n!==void 0&&u.set(e,n)}const $=new Set;for(const e of new Set(D.flatMap(n=>[...c[n].keys()]))){const[n,s,i]=D.map(o=>c[o].get(e));if(!(N(n,s)&&N(s,i)))if(e==="packed-refs")for(const o of D)for(const d of(await I(o)).keys())$.add(d);else[n,s,i].some(o=>o!==void 0&&P(o))&&$.add(e)}const U=r(async e=>{const[n,s,i]=D.map(o=>c[o].get(e));return[n,s,i].some(o=>o?.mode===z)?w(n):(0,x.gitReflogPlay)(await w(s),await w(i),await w(n))},"playLog"),S=`logs/${V}`;let O=null;T(S)&&(O=(0,x.gitChainReflog)(await U(S)),O===""?u.delete(S):u.set(S,_(S,O)));const m=new Map,M=[];for(const e of[...$].sort(B.compareGitText)){const[n,s,i]=await Promise.all(D.map(d=>y(d,e)));let o=s!==i?i:n;if(e===V){if(O===null)continue;o=(0,x.gitReflogTop)(O)}else e.startsWith(J)&&n!==null&&n!==s&&o!==n&&[n,i].every(d=>d===null||(0,E.isGitOid)(t.record.format,d))&&(i===null||!await f.builtOn(i,n))&&(o=n,i!==null&&!await f.builtOn(n,i)&&M.push({name:e,basis:s,record:i}));o!==n&&m.set(e,o)}const X=[];if(M.length>0){const e=new Map;for(const s of new Set([...c.line.keys(),...(await I("line")).keys(),...m.keys()])){if(s!==K&&!Q(s,K))continue;const i=m.has(s)?m.get(s):await y("line",s);i!==null&&e.set(s,i)}const n=r((s,i)=>(e.get(s)??i)===i&&![...e.keys()].some(o=>Q(s,o)||Q(o,s)),"free");for(const{name:s,basis:i,record:o}of M){const d=`${K}/${s.slice(J.length)}-`;let g=[...e.keys()].sort(B.compareGitText).find(b=>e.get(b)===i&&b.startsWith(d)&&he.test(b.slice(d.length)));for(let b=ue;g===void 0&&b<=o.length;b+=1)n(d+o.slice(0,b),o)&&(g=d+o.slice(0,b));g!==void 0&&(await y("line",g)!==o&&m.set(g,o),e.set(g,o),X.push({branch:g,from:s,commit:o}))}}for(const[e,n]of[...u])oe(n)&&u.delete(e);for(const e of l.line.files)oe(e)&&u.set(e.path,e);const j=new Set;for(const[e,n]of m)n!==null?u.set(e,_(e,`${n}
2
- `)):(u.has(e)&&P(u.get(e))&&u.delete(e),j.add(e));const Y=c.line.get("packed-refs");if(j.size>0&&Y!==void 0){const e=await w(Y),n=(0,x.gitDropPackedRefs)(e,j);n!==e&&u.set("packed-refs",_("packed-refs",n))}const C=r(e=>m.has(e)?Promise.resolve(m.get(e)):y("line",e),"final"),L=r(async(e,n)=>e?.startsWith("ref: ")?n(e.slice(5)):e,"commitOf"),A=await L(await C("HEAD"),C),R=new Set;for(const e of D)for(const n of c[e].keys())de(n)&&n!==S&&R.add(n);for(const e of m.keys())e!==V&&R.add(`logs/${e}`);A!==await L(await y("line","HEAD"),e=>y("line",e))&&R.add("logs/HEAD");for(const e of[...R].sort(B.compareGitText)){const n=e.slice(5),s=n==="HEAD"?A:await C(n),i=T(e);if(!i&&(s===null||n!=="HEAD"&&!m.has(n)||!c.line.has(e)))continue;let o=i?await U(e):await w(c.line.get(e));const d=(0,x.gitReflogTop)(o);if(s!==null&&d!==null&&d!==s&&(0,E.isGitOid)(t.record.format,s)){const g=o.trimEnd().split(`
1
+ "use strict";var fe=Object.defineProperty;var c=(t,i)=>fe(t,"name",{value:i,configurable:!0});Object.defineProperty(exports,"__esModule",{value:!0}),exports.gitOwnChange=se,exports.gitLineChanges=de,exports.gitPlayable=ue,exports.gitPlayRecord=we;const te=require("../entities/bytes.js"),le=require("./alternates.js"),ne=require("./artifact.js"),x=require("./refs.js"),E=require("./state.js"),B=require("./text.js");function se(t){return t.facets.some(f=>f==="create"||f==="retype"||f==="content")&&t.result.status==="active"?t.result.transportVersion:null}c(se,"gitOwnChange");function de(t){let i=[],f=!1;for(const h of t){if(h.result.type!=="repo.git"){i=[],f=!0;continue}const p=se(h);p!==null&&i.push(p)}return{reached:i,ended:f}}c(de,"gitLineChanges");function ue({line:t,basis:i,record:f}){const h=c(l=>l.files.find(a=>a.path===le.GIT_ALTERNATES_PATH)?.oid??null,"borrowed"),p=c(l=>l.files.some(a=>a.path==="reftable"),"reftable");return t.format===f.format&&(i===null||i.format===f.format)&&!(0,E.gitSharesObjects)(t)&&!(0,E.gitSelfHeld)(t.home)&&!(0,E.gitSharesGitDir)(t.home)&&t.home?.entity===f.home?.entity&&t.home?.path===f.home?.path&&h(t)===h(f)&&![t,f,...i?[i]:[]].some(l=>p(l)||(0,E.gitBytesForm)(l))}c(ue,"gitPlayable");const z="040000",F=c(t=>new Map(t.map(i=>[i.path,i])),"byPath"),N=c((t,i)=>t===void 0?i===void 0:i!==void 0&&t.mode===i.mode&&t.oid===i.oid,"same"),oe=c(t=>{const i=[];for(let f=t.indexOf("/");f>0;f=t.indexOf("/",f+1))i.push(t.slice(0,f));return i},"parents");function he(t,i,f){const h=new Set;for(const l of t.keys()){const a=oe(l).find(k=>t.has(k)&&t.get(k).mode!==z);a!==void 0&&h.add(a)}const p=c(l=>h.has(l)||oe(l).some(a=>h.has(a)),"clashed");if(h.size>0){for(const l of[...t.keys()])p(l)&&t.delete(l);for(const[l,a]of i)p(l)&&t.set(l,a)}return(0,E.gitTreeOf)(t.values(),f)}c(he,"asTree");const D=["line","basis","record"],P=c(t=>t.mode!==z&&(t.path==="HEAD"||t.path.startsWith("refs/")),"isLooseRef"),ie=c(t=>P(t)||t.path==="packed-refs","isRefFile"),ge=c(t=>t.startsWith("logs/"),"isReflogPath"),V="refs/stash",J="refs/heads/",K=`${J}amalgm`,me=7,pe=/^[0-9a-f]{7,}$/,Q=c((t,i)=>t.startsWith(`${i}/`),"beneath");async function we(t,i,f,h){const p={format:t.record.format,home:t.record.home,files:[],index:null},l={line:t.line,basis:t.basis??p,record:t.record},a={line:F(l.line.files),basis:F(l.basis.files),record:F(l.record.files)},k=new Map,A=c((e,n)=>{const s=(0,te.utf8Encode)(n),r=(0,ne.gitBlobId)(s,h);return k.set(r,s),{path:e,mode:"100644",oid:r}},"make"),w=c(async e=>e?.oid?(0,te.utf8Decode)(k.get(e.oid)??await i(e.oid)):"","read"),I=new Map,T=c(e=>(I.has(e)||I.set(e,w(a[e].get("packed-refs")).then(x.gitPackedRefs)),I.get(e)),"packedOf"),y=c(async(e,n)=>{const s=a[e].get(n);return s!==void 0&&P(s)?(0,x.gitLooseRef)(await w(s)):n==="HEAD"?null:(await T(e)).get(n)??null},"value"),$=c(e=>!N(a.basis.get(e),a.record.get(e)),"recordChanged"),u=new Map;for(const e of new Set([...a.line.keys(),...a.basis.keys(),...a.record.keys()])){const n=$(e)?a.record.get(e):a.line.get(e);n!==void 0&&u.set(e,n)}const M=new Set;for(const e of new Set(D.flatMap(n=>[...a[n].keys()]))){const[n,s,r]=D.map(o=>a[o].get(e));if(!(N(n,s)&&N(s,r)))if(e==="packed-refs")for(const o of D)for(const d of(await T(o)).keys())M.add(d);else[n,s,r].some(o=>o!==void 0&&P(o))&&M.add(e)}const U=c(async e=>{const[n,s,r]=D.map(o=>a[o].get(e));return[n,s,r].some(o=>o?.mode===z)?w(n):(0,x.gitReflogPlay)(await w(s),await w(r),await w(n))},"playLog"),S=`logs/${V}`;let O=null;$(S)&&(O=(0,x.gitChainReflog)(await U(S)),O===""?u.delete(S):u.set(S,A(S,O)));const m=new Map,j=[];for(const e of[...M].sort(B.compareGitText)){const[n,s,r]=await Promise.all(D.map(d=>y(d,e)));let o=s!==r?r:n;if(e===V){if(O===null)continue;o=(0,x.gitReflogTop)(O)}else e.startsWith(J)&&n!==null&&n!==s&&o!==n&&[n,r].every(d=>d===null||(0,E.isGitOid)(t.record.format,d))&&(r===null||!await f.builtOn(r,n))&&(o=n,r!==null&&!await f.builtOn(n,r)&&j.push({name:e,basis:s,record:r}));o!==n&&m.set(e,o)}const X=[];if(j.length>0){const e=new Map;for(const s of new Set([...a.line.keys(),...(await T("line")).keys(),...m.keys()])){if(s!==K&&!Q(s,K))continue;const r=m.has(s)?m.get(s):await y("line",s);r!==null&&e.set(s,r)}const n=c((s,r)=>(e.get(s)??r)===r&&![...e.keys()].some(o=>Q(s,o)||Q(o,s)),"free");for(const{name:s,basis:r,record:o}of j){const d=`${K}/${s.slice(J.length)}-`;let g=[...e.keys()].sort(B.compareGitText).find(b=>e.get(b)===r&&b.startsWith(d)&&pe.test(b.slice(d.length)));for(let b=me;g===void 0&&b<=o.length;b+=1)n(d+o.slice(0,b),o)&&(g=d+o.slice(0,b));g!==void 0&&(await y("line",g)!==o&&m.set(g,o),e.set(g,o),X.push({branch:g,from:s,commit:o}))}}for(const[e,n]of[...u])ie(n)&&u.delete(e);for(const e of l.line.files)ie(e)&&u.set(e.path,e);const C=new Set;for(const[e,n]of m)n!==null?u.set(e,A(e,`${n}
2
+ `)):(u.has(e)&&P(u.get(e))&&u.delete(e),C.add(e));const Y=a.line.get("packed-refs");if(C.size>0&&Y!==void 0){const e=await w(Y),n=(0,x.gitDropPackedRefs)(e,C);n!==e&&u.set("packed-refs",A("packed-refs",n))}const L=c(e=>m.has(e)?Promise.resolve(m.get(e)):y("line",e),"final"),v=c(async(e,n)=>e?.startsWith("ref: ")?n(e.slice(5)):e,"commitOf"),R=await v(await L("HEAD"),L),H=new Set;for(const e of D)for(const n of a[e].keys())ge(n)&&n!==S&&H.add(n);for(const e of m.keys())e!==V&&H.add(`logs/${e}`);R!==await v(await y("line","HEAD"),e=>y("line",e))&&H.add("logs/HEAD");for(const e of[...H].sort(B.compareGitText)){const n=e.slice(5),s=n==="HEAD"?R:await L(n),r=$(e);if(!r&&(s===null||n!=="HEAD"&&!m.has(n)||!a.line.has(e)))continue;let o=r?await U(e):await w(a.line.get(e));const d=(0,x.gitReflogTop)(o);if(s!==null&&d!==null&&d!==s&&(0,E.isGitOid)(t.record.format,s)){const g=o.trimEnd().split(`
3
3
  `).at(-1);o+=`${d} ${s}${g.slice(g.indexOf(" ",g.indexOf(" ")+1))}
4
- `}o===""?u.delete(e):u.set(e,_(e,o))}const ie=r(e=>y(e,"HEAD").then(n=>L(n,s=>y(e,s))),"headOf"),v=r(async e=>{const n=t[e]?.index;return n?.files.length===1?{index:await a(n.files[0].oid),head:await ie(e)}:null},"indexOf"),[G,Z,q]=await Promise.all([v("line"),v("basis"),v("record")]);let W=t.record.index;if(G!==null&&q!==null){const e=t.record.index.meaning===t.basis?.index?.meaning&&q.head===Z?.head,n=e&&G.head===A?null:await f.playIndex(G,Z,q,A);if(e&&n===null)W=t.line.index;else if(n!==null){const s=n.bytes,i=(0,te.gitBlobId)(s,h);k.set(i,s),W={meaning:n.meaning,files:[{path:"index",mode:"100644",oid:i}]}}}return{state:{format:t.record.format,home:t.record.home,files:le(u,c.record,t.record.home),index:W},made:k,aside:X}}r(ge,"gitPlayRecord");
4
+ `}o===""?u.delete(e):u.set(e,A(e,o))}const G=c(e=>y(e,"HEAD").then(n=>v(n,s=>y(e,s))),"headOf"),q=c(async e=>{const n=t[e]?.index;return n?.files.length===1?{index:await i(n.files[0].oid),head:await G(e)}:null},"indexOf"),[W,ae,Z,re,ce]=await Promise.all([q("line"),q("basis"),q("record"),t.basis?G("basis"):null,G("record")]),_=t.record.index?.meaning===t.basis?.index?.meaning&&ce===re;let ee=_?t.line.index:t.record.index;if(W!==null&&(_||Z!==null)&&!(_&&W.head===R)){const e=await f.playIndex(W,_?null:ae,_?null:Z,R);if(e!==null){const n=e.bytes,s=(0,ne.gitBlobId)(n,h);k.set(s,n),ee={meaning:e.meaning,files:[{path:"index",mode:"100644",oid:s}]}}}return{state:{format:t.record.format,home:t.record.home,files:he(u,a.record,t.record.home),index:ee},made:k,aside:X}}c(we,"gitPlayRecord");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amalgm/live",
3
- "version": "0.2.81-preview.47434148097",
3
+ "version": "0.2.81-preview.47446204525",
4
4
  "description": "Portable realtime SDK for Amalgm — wire contracts, mutation discipline, and delivery state machines behind host-injected adapters.",
5
5
  "type": "module",
6
6
  "main": "./dist-cjs/index.js",
@@ -133,11 +133,11 @@
133
133
  "dependencies": {
134
134
  "@amalgm/core": "0.5.1-preview.46345295340"
135
135
  },
136
- "gitHead": "d82290d920ec01eb0de52c6d6b1878c944bc3bf7",
136
+ "gitHead": "1bd1d2b8fe47f06a11faf8be4f7397d77bc03db1",
137
137
  "amalgmSource": {
138
138
  "repository": "amalgm-inc/amalgm-live",
139
139
  "branch": "preview",
140
- "commit": "d82290d920ec01eb0de52c6d6b1878c944bc3bf7",
141
- "occurrence": "47434148097"
140
+ "commit": "1bd1d2b8fe47f06a11faf8be4f7397d77bc03db1",
141
+ "occurrence": "47446204525"
142
142
  }
143
143
  }