@amalgm/live 0.2.81-main.47283630702 → 0.2.81-main.47321867862

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.
Files changed (47) hide show
  1. package/dist/apply/contracts.d.ts +1 -0
  2. package/dist/apply/fetch-ahead.js +1 -1
  3. package/dist/apply/journey.js +1 -1
  4. package/dist/apply/rail.js +1 -1
  5. package/dist/clash/bodmas.d.ts +2 -1
  6. package/dist/clash/bodmas.js +1 -1
  7. package/dist/clash/tetris.d.ts +2 -1
  8. package/dist/clash/tetris.js +1 -1
  9. package/dist/detection/removals.d.ts +1 -1
  10. package/dist/detection/removals.js +1 -1
  11. package/dist/drive/contracts.d.ts +1 -0
  12. package/dist/drive/held-removals.js +1 -1
  13. package/dist/drive/listing.js +1 -1
  14. package/dist/drive/map-index.js +1 -1
  15. package/dist/drive/where.d.ts +1 -0
  16. package/dist/drive/where.js +2 -2
  17. package/dist/entities/cloud.d.ts +1 -0
  18. package/dist/entities/cloud.js +1 -1
  19. package/dist/entities/placement-owed.d.ts +2 -0
  20. package/dist/entities/placement-owed.js +1 -1
  21. package/dist/entities/rules.d.ts +6 -2
  22. package/dist/entities/rules.js +1 -1
  23. package/dist/files/accepted-files.d.ts +1 -0
  24. package/dist/files/accepted-files.js +1 -1
  25. package/dist/files/cloud-files.js +1 -1
  26. package/dist/files/trash.d.ts +2 -1
  27. package/dist/files/trash.js +1 -1
  28. package/dist/git/checkout-view.d.ts +1 -0
  29. package/dist/git/checkout-view.js +1 -1
  30. package/dist-cjs/apply/fetch-ahead.js +1 -1
  31. package/dist-cjs/apply/journey.js +1 -1
  32. package/dist-cjs/apply/rail.js +1 -1
  33. package/dist-cjs/clash/bodmas.js +1 -1
  34. package/dist-cjs/clash/tetris.js +1 -1
  35. package/dist-cjs/detection/removals.js +1 -1
  36. package/dist-cjs/drive/held-removals.js +1 -1
  37. package/dist-cjs/drive/listing.js +1 -1
  38. package/dist-cjs/drive/map-index.js +1 -1
  39. package/dist-cjs/drive/where.js +2 -2
  40. package/dist-cjs/entities/cloud.js +1 -1
  41. package/dist-cjs/entities/placement-owed.js +1 -1
  42. package/dist-cjs/entities/rules.js +1 -1
  43. package/dist-cjs/files/accepted-files.js +1 -1
  44. package/dist-cjs/files/cloud-files.js +1 -1
  45. package/dist-cjs/files/trash.js +1 -1
  46. package/dist-cjs/git/checkout-view.js +1 -1
  47. package/package.json +4 -4
@@ -303,6 +303,7 @@ export interface EntityApplyRailOptions {
303
303
  readonly effects: EntityApplyEffectsPort;
304
304
  readonly schedule: EntityApplySchedulePort;
305
305
  readonly sha256Hex: Sha256Hex;
306
+ readonly deliveryPosition?: (record: AcceptedEntityRecord) => number | undefined;
306
307
  readonly loops?: (record: AcceptedEntityRecord) => RefusedMove | undefined;
307
308
  readonly now: () => number;
308
309
  readonly concurrency?: number;
@@ -1 +1 @@
1
- var d=Object.defineProperty;var u=(i,n)=>d(i,"name",{value:n,configurable:!0});import{checkContentIndex as p,checkContentManifest as w}from"../contracts/content.js";import{ownChange as g}from"../detection/record-proposal.js";import{playChange as m}from"../clash/bodmas.js";import{judgeShowing as y}from"./showing.js";const x=256,v=128;function M(i,n,e,o=new Map){const a=i.at(-1)?.deliverySequence??0,c=u(t=>{const s=o.get(t);return s===void 0?n(t):s.place??void 0},"read"),f=u(t=>{const s=y(t,c);if(s==="leave"&&o.set(t.uuid,{place:null,through:a}),s!=="apply"&&s!=="enter")return!1;const r=c(t.uuid);return o.set(t.uuid,{through:a,place:r?.root?{...r,type:t.type}:{parentUUID:t.parentUUID,name:t.name,type:t.type,root:!1,available:!0,onDemand:!1,home:!1}}),!0},"show"),h=new Map;for(const{record:t}of i){const s=h.get(t.entityId),r=m(s?.row??null,t.change,e.sha256Hex,e.loops?.(t));r.row!==null&&(h.set(t.entityId,{row:r.row,payload:r.setsPayload?t:s?.payload??null}),f(r.row))}const l=new Map;for(const{row:t,payload:s}of h.values()){if(s===null||!f(t))continue;const r=A(s);r!==null&&!l.has(r.artifact.contentHash)&&l.set(r.artifact.contentHash,r)}return[...l.values()]}u(M,"cargoAhead");function A(i){const{result:n}=i.change,{replay:e,cargo:o}=g(i.change);if(o.length!==1)return null;const a=o[0];switch(e.kind){case"structure":case"link":case"secret":return null;case"file.text":return e.mode==="delta"?null:{artifact:a};case"repo.git":return{artifact:a};default:{const c=e.kind==="file.binary"?p(e.manifest,n.payloadVersion):w(e.manifest,n.payloadVersion);return c.ok?{artifact:a,manifest:c.value}:{artifact:a}}}}u(A,"cargoOf");class E{static{u(this,"FetchAhead")}#n;#a;#o=new Map;#e=new Set;#t=!1;constructor(n,e){this.#n=n,this.#a=e}advance(n,e){const o=this.#n;if(o===void 0||this.#t)return;const a=this.#s(n);for(const[h,l]of a.shown)l.through<e&&a.shown.delete(h);if(a.fetching)return;const c=Math.max(a.through,e-1);if(c-e+1>=x)return;a.fetching=!0;const f=this.#r(o,n,a,c).finally(()=>{a.fetching=!1,this.#e.delete(f)});this.#e.add(f)}async stop(){for(this.#t=!0;this.#e.size>0;)await Promise.allSettled([...this.#e])}#s(n){let e=this.#o.get(n);return e===void 0&&this.#o.set(n,e={through:0,fetching:!1,shown:new Map}),e}async#r(n,e,o,a){try{const{rows:c,shownPlace:f}=await n.readAhead(e,a,v),h=c.at(-1);if(h===void 0)return;o.through=Math.max(o.through,h.deliverySequence);const l=M(c,f,this.#a,o.shown);l.length>0&&!this.#t&&await n.fetch(l)}catch{}}}export{x as ENTITY_APPLY_FETCH_AHEAD,v as ENTITY_APPLY_FETCH_SET,E as FetchAhead,M as cargoAhead};
1
+ var p=Object.defineProperty;var u=(i,n)=>p(i,"name",{value:n,configurable:!0});import{checkContentIndex as w,checkContentManifest as g}from"../contracts/content.js";import{ownChange as y}from"../detection/record-proposal.js";import{playChange as m}from"../clash/bodmas.js";import{judgeShowing as v}from"./showing.js";const x=256,M=128;function S(i,n,e,o=new Map){const a=i.at(-1)?.deliverySequence??0,s=u(t=>{const r=o.get(t);return r===void 0?n(t):r.place??void 0},"read"),f=u(t=>{const r=v(t,s);if(r==="leave"&&o.set(t.uuid,{place:null,through:a}),r!=="apply"&&r!=="enter")return!1;const c=s(t.uuid);return o.set(t.uuid,{through:a,place:c?.root?{...c,type:t.type}:{parentUUID:t.parentUUID,name:t.name,type:t.type,root:!1,available:!0,onDemand:!1,home:!1}}),!0},"show"),l=new Map;for(const{record:t,deliverySequence:r}of i){const c=l.get(t.entityId),d=m(c?.row??null,t.change,e.sha256Hex,e.loops?.(t),()=>r);d.row!==null&&(l.set(t.entityId,{row:d.row,payload:d.setsPayload?t:c?.payload??null}),f(d.row))}const h=new Map;for(const{row:t,payload:r}of l.values()){if(r===null||!f(t))continue;const c=A(r);c!==null&&!h.has(c.artifact.contentHash)&&h.set(c.artifact.contentHash,c)}return[...h.values()]}u(S,"cargoAhead");function A(i){const{result:n}=i.change,{replay:e,cargo:o}=y(i.change);if(o.length!==1)return null;const a=o[0];switch(e.kind){case"structure":case"link":case"secret":return null;case"file.text":return e.mode==="delta"?null:{artifact:a};case"repo.git":return{artifact:a};default:{const s=e.kind==="file.binary"?w(e.manifest,n.payloadVersion):g(e.manifest,n.payloadVersion);return s.ok?{artifact:a,manifest:s.value}:{artifact:a}}}}u(A,"cargoOf");class H{static{u(this,"FetchAhead")}#n;#a;#o=new Map;#e=new Set;#t=!1;constructor(n,e){this.#n=n,this.#a=e}advance(n,e){const o=this.#n;if(o===void 0||this.#t)return;const a=this.#s(n);for(const[l,h]of a.shown)h.through<e&&a.shown.delete(l);if(a.fetching)return;const s=Math.max(a.through,e-1);if(s-e+1>=x)return;a.fetching=!0;const f=this.#r(o,n,a,s).finally(()=>{a.fetching=!1,this.#e.delete(f)});this.#e.add(f)}async stop(){for(this.#t=!0;this.#e.size>0;)await Promise.allSettled([...this.#e])}#s(n){let e=this.#o.get(n);return e===void 0&&this.#o.set(n,e={through:0,fetching:!1,shown:new Map}),e}async#r(n,e,o,a){try{const{rows:s,shownPlace:f}=await n.readAhead(e,a,M),l=s.at(-1);if(l===void 0)return;o.through=Math.max(o.through,l.deliverySequence);const h=S(s,f,this.#a,o.shown);h.length>0&&!this.#t&&await n.fetch(h)}catch{}}}export{x as ENTITY_APPLY_FETCH_AHEAD,M as ENTITY_APPLY_FETCH_SET,H as FetchAhead,S as cargoAhead};
@@ -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},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 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 +1 @@
1
- var E=Object.defineProperty;var d=(o,e)=>E(o,"name",{value:e,configurable:!0});import{UUID_PATTERN as u}from"../entities/types.js";import{FetchAhead as b}from"./fetch-ahead.js";import{EntityApplyJourney as P,outcomeOf as g,stepsAside as O}from"./journey.js";import{assertApplyLaneStep as v,createApplyLane as S}from"./lane.js";import{assertApplyDependency as $,assertApplyLineStep as q,createApplyLine as M,heldWait as c,releaseApplyLine as _}from"./line.js";import{windowEndForWait as m}from"./window.js";const x=8,B=1e3,A=3e4,p=3;class C{static{d(this,"EntityApplyRail")}#e;#g;#P;#_;#x;#o;#O;#d=!1;#t=!1;#a=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;#v=new Map;#y=null;constructor(e){this.#e=e,this.#g=e.concurrency??x,this.#P=e.laneConcurrency??this.#g,this.#_=e.onBackgroundError??(()=>{}),this.#x=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.#o=new P(e,()=>this.#A,()=>this.#t),this.#O=new b(e.cargo,{sha256Hex:e.sha256Hex,loops:e.loops})}async start(){if(this.#d)throw new Error("entity Apply rail already started");if(this.#t)throw new Error("entity Apply rail is stopped");this.#d=!0;const e=await this.#e.store.readOpenUnits();if(!Array.isArray(e)||new Set(e).size!==e.length||e.some(t=>!u.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.#B()}fetch(e,t){return this.#d?this.#t?Promise.reject(new Error("entity Apply rail is stopped")):u.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=d(()=>this.#e.schedule.schedule(t.stall,()=>{r.waiters.delete(l)&&(r.emptied&&![...r.waiters].some(a=>a.emptied)&&(r.emptied=!1),s(this.#K(r)))}),"arm");let h=n();const l={emptied:t.emptied===!0,answer:d(a=>{h.cancel(),s(a)},"answer"),fail:d(a=>{h.cancel(),i(a)},"fail"),moved:d(()=>{h.cancel(),h=n()},"moved")};r.waiters.add(l),r.waitsOn===null&&this.#T(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(!u.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.#b(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=>!u.test(t)))throw new Error("entity Apply owe needs entity UUIDs");if(!(!this.#d||this.#t)){for(const t of e)this.#S(t);this.#r()}}#I(){!this.#d||this.#t||(this.#n=!0,this.#r())}waiting(){return this.#w().flatMap(e=>c(e.held,y(e))??[])}async flush(){if(!this.#d)throw new Error("entity Apply rail has not started");this.#t||await this.#B()}async stop(){if(this.#t)return;this.#t=!0,this.#M();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.#R()>0||this.#h;)await Promise.allSettled([...this.#l.steps,...this.#u.steps,...this.#h?[this.#h]:[]]);await this.#O.stop();for(const t of this.#m.splice(0))t.resolve()}#B(){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.#J();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.#F(s,e)}if(this.#R()===0&&this.#h===null&&!this.#n&&this.#l.queue.length===0&&this.#u.queue.length===0){if(this.#v.clear(),this.#D(this.#e.now())){this.#r();return}this.#q();for(const e of this.#m.splice(0))e.resolve();this.#x()}}}#R(){return this.#l.steps.size+this.#u.steps.size}#w(){return[...this.#a.values(),...this.#s.values()]}#k(e){return e.kind==="line"?this.#a.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))}}#F(e,t){e.running=!0,e.again=!1;const s=(e.kind==="line"?this.#H(e):this.#V(e)).then(i=>{e.running=!1,t.steps.delete(s),(i||e.again)&&this.#k(e)&&(e.again=!1,this.#i(e)),this.#r()});t.steps.add(s)}async#J(){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.#a)!t.has(s)&&!i.running&&!i.queued&&this.#a.delete(s);for(const s of e){let i=this.#a.get(s);i||(i=M(s),this.#a.set(s,i)),this.#i(i)}}catch(e){this.#p=this.#e.now()+A;const t=this.#m.splice(0);t.length===0&&this.#$(e);for(const s of t)s.reject(e)}}async#H(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,e.endsBefore);if(q(e.authorityId,i),this.#t)return!1;if(i.kind==="end"){e.held=null;const r=e.endsBefore!==null;return e.endsBefore=null,r}return i.window.deliverySequence!==null&&this.#O.advance(e.authorityId,i.window.deliverySequence),await this.#U(e,i.window,s)}catch(t){return this.#C(e,t),!1}}async#V(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(v(e.unit,i),this.#t||!this.#k(e))return!1;if(e.waitsOn=null,i.kind==="unseen")return this.#N(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.#X(e,i.through,i.reason);case"prerequisite":return this.#G(e,i.unit,i.reason,s);case"window":return await this.#U(e,i.window,s)}}catch(t){return this.#C(e,t),!1}}async#X(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.#k(e)?!1:(e.through===t&&e.met.add(e.unit),this.#b(e.unit),!0))}#S(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=S(e,t,s),this.#s.set(e,i),this.#i(i)),i}#G(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.#N(e,{producer:"apply",entityIds:[t]},s,i):!1}#N(e,t,s,i){return e.held={entityId:null,target:null,kept:null,cutoff:null,attempt:1,notBefore:1/0,releaseOnProgress:!1,due:this.#z(t,i),reason:s,dependency:t},e.held.due}#T(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.#k(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.#b(e.unit),this.#c("apply",[e.unit]))}#b(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()}}#K(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#U(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.#Z(e,t))return!1;let r=await g(()=>this.#o.run(t,()=>e.kind==="lane"&&e.emptied?e.unit:null));if(e.kind==="line"&&typeof r=="object"&&r.kind==="park"&&m(t,r.dependency)===null&&this.#Q(e,t,r)&&(r=await g(()=>this.#o.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.#S(n.work.entityId);for(const n of t.members)n.unseen!==void 0&&this.#S(n.unseen);return this.#ee(e,r==="progress"?t.members.map(n=>n.work.entityId):[r.entityId])}if(r==="again")return e.held?.entityId===i&&(e.held=null),!0;if(r.advanced?.length&&this.#j(e,r.advanced),e.kind==="line"){const n=m(t,r.dependency);if(n!==null)return e.endsBefore=n,!0}return this.#te(e,t,r,s),e.kind==="lane"&&this.#T(e),e.held.due}#Q(e,t,s){const i=t.members[0].work.entityId;if(s.cause!==void 0||!O(t,i))return!1;const r=s.dependency?.entityIds??[i];return r.length===0||r.some(n=>n!==i)?!1:s.dependency?.producer==="capability"?!0:this.#Y(e,t)>=p}#Y(e,t){const s=e.held,i=t.members[0].work.entityId;return(s?.entityId===i&&s.target===this.#o.targetOf(t)?s.attempt:0)+1}async#Z(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.#o.targetOf(t)!==s.target||t.cutoff!==s.cutoff?!1:await this.#e.store.localWorkAfter(t.authorityId,i.work.entityId,s.kept??s.target)===null}#ee(e,t){return e.held&&(e.held.entityId===null||t.includes(e.held.entityId))&&(e.held=null),this.#j(e,t),!0}#j(e,t){e.kind==="lane"&&(this.#n=!0,this.#b(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))}#te(e,t,s,i){if(s.dependency&&$(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.#Y(e,t),l=this.#W(h),a=s.again===!0&&h<p,w={entityId:r,target:this.#o.targetOf(t),kept:t.members[0].work.kept,cutoff:t.cutoff,attempt:h,notBefore:s.dependency?1/0:this.#e.now()+(a?0:l),releaseOnProgress:s.releaseOnProgress,due:s.dependency?this.#z(s.dependency,s.comparedAt??i):a,reason:s.reason,...s.dependency?{dependency:s.dependency}:{},...s.blocker?{blocker:s.blocker}:{}};e.held=w,this.#q();const k=c(n,y(e)),f=c(w,y(e));f&&JSON.stringify(f)!==JSON.stringify(k)&&this.#e.onWaiting?.(f),!(!s.report&&(s.dependency!==void 0||h<p))&&this.#$(new Error(`${I(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 ${l}ms (attempt ${h}): ${s.reason}`,s.cause===void 0?void 0:{cause:s.cause}))}#C(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.#W(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.#q(),this.#$(new Error(`${I(e)} faulted and will retry in ${r}ms (attempt ${i}): ${n}`,{cause:t}))}#$(e){try{this.#_(e)}catch{}}#W(e){const t=Math.min(A,B*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.#v.set(`${e}:${i}`,s);for(const i of this.#w())_(i,e,t)&&this.#i(i)}#z(e,t){return["*",...e.entityIds].some(s=>(this.#v.get(`${e.producer}:${s}`)??0)>t)}#q(){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.#M();return}if(this.#y?.dueAt===e)return;this.#M();const t=Math.max(0,e-this.#e.now()),s=this.#e.schedule.schedule(t,()=>{this.#y=null,this.#D(e),this.#r()});this.#y={dueAt:e,cancel:d(()=>s.cancel(),"cancel")}}#D(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}#M(){this.#y?.cancel(),this.#y=null}}const y=d(o=>o.kind==="line"?o.authorityId:o.unit,"owner"),I=d(o=>o.kind==="line"?`entity Apply line ${o.authorityId}`:`entity Apply fetch of ${o.unit}`,"label");export{x as ENTITY_APPLY_DEFAULT_CONCURRENCY,B as ENTITY_APPLY_RETRY_BASE_MS,A as ENTITY_APPLY_RETRY_MAX_MS,p as ENTITY_APPLY_SAME_ANSWERS,C as EntityApplyRail};
1
+ var E=Object.defineProperty;var d=(o,e)=>E(o,"name",{value:e,configurable:!0});import{UUID_PATTERN as u}from"../entities/types.js";import{FetchAhead as b}from"./fetch-ahead.js";import{EntityApplyJourney as P,outcomeOf as g,stepsAside as v}from"./journey.js";import{assertApplyLaneStep as O,createApplyLane as S}from"./lane.js";import{assertApplyDependency as $,assertApplyLineStep as q,createApplyLine as M,heldWait as c,releaseApplyLine as _}from"./line.js";import{windowEndForWait as m}from"./window.js";const x=8,B=1e3,A=3e4,p=3;class C{static{d(this,"EntityApplyRail")}#e;#g;#P;#_;#x;#o;#v;#d=!1;#t=!1;#a=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(e){this.#e=e,this.#g=e.concurrency??x,this.#P=e.laneConcurrency??this.#g,this.#_=e.onBackgroundError??(()=>{}),this.#x=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.#o=new P(e,()=>this.#A,()=>this.#t),this.#v=new b(e.cargo,{sha256Hex:e.sha256Hex,loops:e.loops,deliveryPosition:e.deliveryPosition})}async start(){if(this.#d)throw new Error("entity Apply rail already started");if(this.#t)throw new Error("entity Apply rail is stopped");this.#d=!0;const e=await this.#e.store.readOpenUnits();if(!Array.isArray(e)||new Set(e).size!==e.length||e.some(t=>!u.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.#B()}fetch(e,t){return this.#d?this.#t?Promise.reject(new Error("entity Apply rail is stopped")):u.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=d(()=>this.#e.schedule.schedule(t.stall,()=>{r.waiters.delete(l)&&(r.emptied&&![...r.waiters].some(a=>a.emptied)&&(r.emptied=!1),s(this.#K(r)))}),"arm");let h=n();const l={emptied:t.emptied===!0,answer:d(a=>{h.cancel(),s(a)},"answer"),fail:d(a=>{h.cancel(),i(a)},"fail"),moved:d(()=>{h.cancel(),h=n()},"moved")};r.waiters.add(l),r.waitsOn===null&&this.#T(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(!u.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.#b(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=>!u.test(t)))throw new Error("entity Apply owe needs entity UUIDs");if(!(!this.#d||this.#t)){for(const t of e)this.#S(t);this.#r()}}#I(){!this.#d||this.#t||(this.#n=!0,this.#r())}waiting(){return this.#w().flatMap(e=>c(e.held,y(e))??[])}async flush(){if(!this.#d)throw new Error("entity Apply rail has not started");this.#t||await this.#B()}async stop(){if(this.#t)return;this.#t=!0,this.#M();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.#R()>0||this.#h;)await Promise.allSettled([...this.#l.steps,...this.#u.steps,...this.#h?[this.#h]:[]]);await this.#v.stop();for(const t of this.#m.splice(0))t.resolve()}#B(){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.#J();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.#F(s,e)}if(this.#R()===0&&this.#h===null&&!this.#n&&this.#l.queue.length===0&&this.#u.queue.length===0){if(this.#O.clear(),this.#D(this.#e.now())){this.#r();return}this.#q();for(const e of this.#m.splice(0))e.resolve();this.#x()}}}#R(){return this.#l.steps.size+this.#u.steps.size}#w(){return[...this.#a.values(),...this.#s.values()]}#k(e){return e.kind==="line"?this.#a.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))}}#F(e,t){e.running=!0,e.again=!1;const s=(e.kind==="line"?this.#H(e):this.#V(e)).then(i=>{e.running=!1,t.steps.delete(s),(i||e.again)&&this.#k(e)&&(e.again=!1,this.#i(e)),this.#r()});t.steps.add(s)}async#J(){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.#a)!t.has(s)&&!i.running&&!i.queued&&this.#a.delete(s);for(const s of e){let i=this.#a.get(s);i||(i=M(s),this.#a.set(s,i)),this.#i(i)}}catch(e){this.#p=this.#e.now()+A;const t=this.#m.splice(0);t.length===0&&this.#$(e);for(const s of t)s.reject(e)}}async#H(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,e.endsBefore);if(q(e.authorityId,i),this.#t)return!1;if(i.kind==="end"){e.held=null;const r=e.endsBefore!==null;return e.endsBefore=null,r}return i.window.deliverySequence!==null&&this.#v.advance(e.authorityId,i.window.deliverySequence),await this.#U(e,i.window,s)}catch(t){return this.#C(e,t),!1}}async#V(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(O(e.unit,i),this.#t||!this.#k(e))return!1;if(e.waitsOn=null,i.kind==="unseen")return this.#N(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.#X(e,i.through,i.reason);case"prerequisite":return this.#G(e,i.unit,i.reason,s);case"window":return await this.#U(e,i.window,s)}}catch(t){return this.#C(e,t),!1}}async#X(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.#k(e)?!1:(e.through===t&&e.met.add(e.unit),this.#b(e.unit),!0))}#S(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=S(e,t,s),this.#s.set(e,i),this.#i(i)),i}#G(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.#N(e,{producer:"apply",entityIds:[t]},s,i):!1}#N(e,t,s,i){return e.held={entityId:null,target:null,kept:null,cutoff:null,attempt:1,notBefore:1/0,releaseOnProgress:!1,due:this.#z(t,i),reason:s,dependency:t},e.held.due}#T(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.#k(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.#b(e.unit),this.#c("apply",[e.unit]))}#b(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()}}#K(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#U(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.#Z(e,t))return!1;let r=await g(()=>this.#o.run(t,()=>e.kind==="lane"&&e.emptied?e.unit:null));if(e.kind==="line"&&typeof r=="object"&&r.kind==="park"&&m(t,r.dependency)===null&&this.#Q(e,t,r)&&(r=await g(()=>this.#o.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.#S(n.work.entityId);for(const n of t.members)n.unseen!==void 0&&this.#S(n.unseen);return this.#ee(e,r==="progress"?t.members.map(n=>n.work.entityId):[r.entityId])}if(r==="again")return e.held?.entityId===i&&(e.held=null),!0;if(r.advanced?.length&&this.#j(e,r.advanced),e.kind==="line"){const n=m(t,r.dependency);if(n!==null)return e.endsBefore=n,!0}return this.#te(e,t,r,s),e.kind==="lane"&&this.#T(e),e.held.due}#Q(e,t,s){const i=t.members[0].work.entityId;if(s.cause!==void 0||!v(t,i))return!1;const r=s.dependency?.entityIds??[i];return r.length===0||r.some(n=>n!==i)?!1:s.dependency?.producer==="capability"?!0:this.#Y(e,t)>=p}#Y(e,t){const s=e.held,i=t.members[0].work.entityId;return(s?.entityId===i&&s.target===this.#o.targetOf(t)?s.attempt:0)+1}async#Z(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.#o.targetOf(t)!==s.target||t.cutoff!==s.cutoff?!1:await this.#e.store.localWorkAfter(t.authorityId,i.work.entityId,s.kept??s.target)===null}#ee(e,t){return e.held&&(e.held.entityId===null||t.includes(e.held.entityId))&&(e.held=null),this.#j(e,t),!0}#j(e,t){e.kind==="lane"&&(this.#n=!0,this.#b(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))}#te(e,t,s,i){if(s.dependency&&$(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.#Y(e,t),l=this.#W(h),a=s.again===!0&&h<p,w={entityId:r,target:this.#o.targetOf(t),kept:t.members[0].work.kept,cutoff:t.cutoff,attempt:h,notBefore:s.dependency?1/0:this.#e.now()+(a?0:l),releaseOnProgress:s.releaseOnProgress,due:s.dependency?this.#z(s.dependency,s.comparedAt??i):a,reason:s.reason,...s.dependency?{dependency:s.dependency}:{},...s.blocker?{blocker:s.blocker}:{}};e.held=w,this.#q();const k=c(n,y(e)),f=c(w,y(e));f&&JSON.stringify(f)!==JSON.stringify(k)&&this.#e.onWaiting?.(f),!(!s.report&&(s.dependency!==void 0||h<p))&&this.#$(new Error(`${I(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 ${l}ms (attempt ${h}): ${s.reason}`,s.cause===void 0?void 0:{cause:s.cause}))}#C(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.#W(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.#q(),this.#$(new Error(`${I(e)} faulted and will retry in ${r}ms (attempt ${i}): ${n}`,{cause:t}))}#$(e){try{this.#_(e)}catch{}}#W(e){const t=Math.min(A,B*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.#O.set(`${e}:${i}`,s);for(const i of this.#w())_(i,e,t)&&this.#i(i)}#z(e,t){return["*",...e.entityIds].some(s=>(this.#O.get(`${e.producer}:${s}`)??0)>t)}#q(){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.#M();return}if(this.#y?.dueAt===e)return;this.#M();const t=Math.max(0,e-this.#e.now()),s=this.#e.schedule.schedule(t,()=>{this.#y=null,this.#D(e),this.#r()});this.#y={dueAt:e,cancel:d(()=>s.cancel(),"cancel")}}#D(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}#M(){this.#y?.cancel(),this.#y=null}}const y=d(o=>o.kind==="line"?o.authorityId:o.unit,"owner"),I=d(o=>o.kind==="line"?`entity Apply line ${o.authorityId}`:`entity Apply fetch of ${o.unit}`,"label");export{x as ENTITY_APPLY_DEFAULT_CONCURRENCY,B as ENTITY_APPLY_RETRY_BASE_MS,A as ENTITY_APPLY_RETRY_MAX_MS,p as ENTITY_APPLY_SAME_ANSWERS,C as EntityApplyRail};
@@ -2,6 +2,7 @@ import type { ChangeFacet } from '../detection/record-proposal.js';
2
2
  import type { CloudEntityRecord } from '../entities/cloud.js';
3
3
  import { type Sha256Hex } from '../entities/types.js';
4
4
  export interface PlayableChange {
5
+ readonly deliverySequence?: number | undefined;
5
6
  readonly facets: readonly ChangeFacet[];
6
7
  readonly result: CloudEntityRecord;
7
8
  readonly joins?: string | undefined;
@@ -14,4 +15,4 @@ export interface RefusedMove {
14
15
  readonly keeps: string | null;
15
16
  }
16
17
  export declare const contentKind: (type: string) => string;
17
- export declare function playChange(previous: CloudEntityRecord | null, change: PlayableChange, sha256Hex: Sha256Hex, refused?: RefusedMove): Played;
18
+ export declare function playChange(previous: CloudEntityRecord | null, change: PlayableChange, sha256Hex: Sha256Hex, refused?: RefusedMove, readPosition?: () => number | undefined): Played;
@@ -1 +1 @@
1
- var P=Object.defineProperty;var n=(t,r)=>P(t,"name",{value:r,configurable:!0});import{canonicalVersion as p,validPortableFileMode as u,validPortableMtime as b}from"../entities/rules.js";import{fileAbsent as l}from"../git/checkout.js";import{CONTAINERS as w}from"../entities/types.js";const k=n(t=>w.has(t)?t:"file","contentKind");function D(t,r,i,f){const{facets:c,result:e}=r;if(r.joins!==void 0)return t!==null&&t.status!=="deleted"&&t.version===r.joins?{row:e,setsPayload:!0}:{row:t,setsPayload:!1};const d=f===void 0?e.parentUUID:f.keeps;if(t===null||c.includes("create")){if(t?.status==="deleted")return{row:t,setsPayload:!1};if(d===e.parentUUID)return{row:e,setsPayload:!0};const o={...e,parentUUID:d};return{row:{...o,version:p(o,i)},setsPayload:!0}}if(t.status==="deleted")return{row:t,setsPayload:!1};let a=t,m=!1;const s=n(o=>{a={...a,...o}},"set"),y=n(()=>{s({type:e.type,fileMode:l(e)||!u(e.type,a.fileMode)?e.fileMode:a.fileMode,mtime:l(e)||!b(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}),m=!0},"becomes");for(const o of c)switch(o){case"move":s({parentUUID:d});break;case"rename":s({name:e.name});break;case"retype":y();break;case"content":k(a.type)===k(e.type)&&y();break;case"mode":!l(a)&&u(a.type,e.fileMode)&&s({fileMode:e.fileMode});break;case"time":!l(a)&&b(a.type,e.mtime)&&s({mtime:e.mtime});break;case"trash":s({status:"trashed"});break;case"restore":a.status==="trashed"&&s({status:"active"});break;case"delete":s({status:"deleted"});break;case"create":break}return a===t?{row:t,setsPayload:!1}:U(a,e)?{row:e,setsPayload:m}:{row:{...a,version:p(a,i)},setsPayload:m}}n(D,"playChange");const M=["uuid","type","parentUUID","name","status","payloadVersion","fileMode","mtime","size","linkTarget","gitHomeEntity","gitHomePath","transportVersion"],U=n((t,r)=>M.every(i=>t[i]===r[i]),"sameFields");export{k as contentKind,D 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};
@@ -4,9 +4,10 @@ import type { AcceptedEntityRecord } from '../records/contracts.js';
4
4
  import { type RefusedMove } from './bodmas.js';
5
5
  export interface LinePlay {
6
6
  readonly sha256Hex: Sha256Hex;
7
+ readonly deliveryPosition?: ((record: AcceptedEntityRecord) => number | undefined) | undefined;
7
8
  readonly loops?: ((record: AcceptedEntityRecord) => RefusedMove | undefined) | undefined;
8
9
  }
9
- export declare function playRecords(from: CloudEntityRecord | null, records: readonly AcceptedEntityRecord[], { sha256Hex, loops }: LinePlay): {
10
+ export declare function playRecords(from: CloudEntityRecord | null, records: readonly AcceptedEntityRecord[], { sha256Hex, loops, deliveryPosition }: LinePlay): {
10
11
  readonly row: CloudEntityRecord | null;
11
12
  readonly payload: AcceptedEntityRecord | null;
12
13
  };
@@ -1 +1 @@
1
- var d=Object.defineProperty;var t=(o,r)=>d(o,"name",{value:r,configurable:!0});import{playChange as f}from"./bodmas.js";function i(o,r,{sha256Hex:c,loops:p}){let a=o,l=null;for(const e of r){const n=f(a,e.change,c,p?.(e));a=n.row,n.setsPayload&&(l=e)}return{row:a,payload:l}}t(i,"playRecords");export{i as playRecords};
1
+ var f=Object.defineProperty;var t=(r,a)=>f(r,"name",{value:a,configurable:!0});import{playChange as s}from"./bodmas.js";function u(r,a,{sha256Hex:c,loops:p,deliveryPosition:d}){let e=r,l=null;for(const o of a){const n=s(e,o.change,c,p?.(o),()=>d?.(o));e=n.row,n.setsPayload&&(l=o)}return{row:e,payload:l}}t(u,"playRecords");export{u as playRecords};
@@ -1,4 +1,4 @@
1
1
  import type { CloudEntityRecord } from '../entities/cloud.js';
2
2
  import type { Sha256Hex } from '../entities/types.js';
3
3
  import { type Steps } from '../steps.js';
4
- export declare function trashRemovedEntitiesSteps(records: Iterable<CloudEntityRecord>, absent: ReadonlySet<string>, sha256Hex: Sha256Hex): Steps<ReadonlyMap<string, CloudEntityRecord>>;
4
+ export declare function trashRemovedEntitiesSteps(records: Iterable<CloudEntityRecord>, absent: ReadonlySet<string>, sha256Hex: Sha256Hex, tracks?: (base: CloudEntityRecord) => boolean): Steps<ReadonlyMap<string, CloudEntityRecord>>;
@@ -1 +1 @@
1
- var h=Object.defineProperty;var U=(r,s)=>h(r,"name",{value:s,configurable:!0});import{canonicalVersion as d,membershipHash as w}from"../entities/rules.js";import{eachStep as c}from"../steps.js";function*D(r,s,o){const a=new Map,i=new Map;yield*c(r,e=>{if(a.set(e.uuid,e),e.parentUUID===null||e.status!=="active")return;const t=i.get(e.parentUUID)??[];t.push(e),i.set(e.parentUUID,t)});const p=new Map;return yield*c(s,e=>{const t=a.get(e);if(!t)throw new Error(`removed entity ${e} is unknown`);if(t.status!=="active")return;let n=t.parentUUID===null?void 0:a.get(t.parentUUID);const l=new Set([e]);let u=!1;for(;n;){if(l.has(n.uuid))throw new Error("removed entity ancestry has a cycle");if(l.add(n.uuid),n.status!=="active"||s.has(n.uuid)){u=!0;break}n=n.parentUUID===null?void 0:a.get(n.parentUUID)}if(u)return;const f=t.type==="workspace"||t.type==="folder"?w(i.get(e)??[],o):t.payloadVersion;p.set(e,Object.freeze({...t,status:"trashed",version:d({...t,status:"trashed",payloadVersion:f},o)}))}),p}U(D,"trashRemovedEntitiesSteps");export{D as trashRemovedEntitiesSteps};
1
+ var d=Object.defineProperty;var f=(a,s)=>d(a,"name",{value:s,configurable:!0});import{canonicalVersion as m,membershipHash as w}from"../entities/rules.js";import{eachStep as c}from"../steps.js";import{absentResult as y}from"../git/holds.js";function*g(a,s,i,U=()=>!1){const r=new Map,o=new Map;yield*c(a,e=>{if(r.set(e.uuid,e),e.parentUUID===null||e.status!=="active")return;const t=o.get(e.parentUUID)??[];t.push(e),o.set(e.parentUUID,t)});const p=new Map;return yield*c(s,e=>{const t=r.get(e);if(!t)throw new Error(`removed entity ${e} is unknown`);if(t.status!=="active")return;let n=t.parentUUID===null?void 0:r.get(t.parentUUID);const l=new Set([e]);let u=!1;for(;n;){if(l.has(n.uuid))throw new Error("removed entity ancestry has a cycle");if(l.add(n.uuid),n.status!=="active"||s.has(n.uuid)){u=!0;break}n=n.parentUUID===null?void 0:r.get(n.parentUUID)}if(u)return;if(U(t)){p.set(e,Object.freeze(y(t,i)));return}const h=t.type==="workspace"||t.type==="folder"?w(o.get(e)??[],i):t.payloadVersion;p.set(e,Object.freeze({...t,status:"trashed",version:m({...t,status:"trashed",payloadVersion:h},i)}))}),p}f(g,"trashRemovedEntitiesSteps");export{g as trashRemovedEntitiesSteps};
@@ -1,6 +1,7 @@
1
1
  import type { EntityStatus, EntityType, PortableFileMode, PortableMtime } from '../entities/types.js';
2
2
  import type { GitHome } from '../git/state.js';
3
3
  export interface MapEntity {
4
+ readonly slotPosition?: number;
4
5
  readonly uuid: string;
5
6
  readonly type: EntityType;
6
7
  readonly parentUUID: string | null;
@@ -1 +1 @@
1
- var u=Object.defineProperty;var o=(r,t)=>u(r,"name",{value:t,configurable:!0});import{detectedChangeProposal as d}from"../detection/record-proposal.js";import{trashRemovedEntitiesSteps as f}from"../detection/removals.js";import{createLocalEntityRecord as m}from"../records/contracts.js";import{RetryClock as p}from"../records/retry-clock.js";import{finishSteps as y}from"../steps.js";import{actRecord as g}from"./records.js";const w=250;class k{static{o(this,"HeldRemovals")}#t;#i;#e=new Map;#r=new Map;#s=null;#a=Promise.resolve();#n=!1;constructor(t){this.#t=t,this.#i=new p(t.schedule)}async hold(t,s,n=null){const e=h([t.base],this.#t).get(t.base.uuid);if(e===void 0)return null;const i={record:await g(t,e,this.#t),base:t.base,place:s};this.#o(i);try{await this.#t.store.hold(i,n)}catch(a){throw this.#c(i),a}return this.#t.localRecordsAvailable(),this.#l(),i.record}async free(t){this.#e.has(l(t))&&await this.release()}release(){this.#s?.cancel(),this.#s=null;const t=this.#a.then(()=>this.#h()).catch(s=>{throw this.#n||this.#i.arm(()=>{this.release().catch(this.#t.onError)}),s});return this.#a=t.catch(()=>{}),t}async close(){this.#n=!0,this.#i.cancel(),await this.release().catch(this.#t.onError)}async#h(){const t=await this.#t.store.held();for(const e of t)this.#o(e);if(t.length===0)return;const s=h(t.map(e=>e.base),this.#t),n=t.flatMap(({record:e})=>{const i=s.get(e.entityId);return i===void 0?[]:[m({mutationId:e.mutationId,authorityId:e.authorityId,lastSeenGlobalSequence:e.lastSeenGlobalSequence,change:i,createdAt:e.createdAt})]});await this.#t.store.release(n,t),this.#i.succeeded();for(const e of t)this.#c(e);this.#t.localRecordsAvailable(),this.#t.released(t)}#l(){this.#n||(this.#s?.cancel(),this.#s=this.#t.schedule.schedule(w,()=>{this.#s=null,this.release().catch(this.#t.onError)}))}#o(t){if(this.#r.has(t.record.mutationId))return;const s=l(t.place);this.#r.set(t.record.mutationId,s),this.#e.set(s,(this.#e.get(s)??0)+1)}#c(t){const s=this.#r.get(t.record.mutationId);if(s===void 0)return;this.#r.delete(t.record.mutationId);const n=(this.#e.get(s)??0)-1;n>0?this.#e.set(s,n):this.#e.delete(s)}}function h(r,t){const s=new Set(r.map(i=>i.uuid)),n=y(f(r,s,t.sha256Hex)),e=new Map;for(const i of r){const a=n.get(i.uuid),c=a===void 0?null:d({base:i,result:a,replay:{kind:"structure"},lifecycleAuthorization:"trash"});c!==null&&e.set(i.uuid,c)}return e}o(h,"trashOf");const l=o(r=>JSON.stringify([r.root,...r.address]),"placeKey");export{w as HELD_REMOVAL_QUIET_MS,k as HeldRemovals};
1
+ var u=Object.defineProperty;var a=(r,t)=>u(r,"name",{value:t,configurable:!0});import{detectedChangeProposal as d}from"../detection/record-proposal.js";import{trashRemovedEntitiesSteps as f}from"../detection/removals.js";import{checkoutFileOwner as m}from"../git/checkout.js";import{createLocalEntityRecord as p}from"../records/contracts.js";import{RetryClock as g}from"../records/retry-clock.js";import{finishSteps as y}from"../steps.js";import{actRecord as w}from"./records.js";const I=250;class H{static{a(this,"HeldRemovals")}#t;#i;#e=new Map;#r=new Map;#s=null;#o=Promise.resolve();#n=!1;constructor(t){this.#t=t,this.#i=new g(t.schedule)}async hold(t,s,n=null){const e=h([t.base],this.#t).get(t.base.uuid);if(e===void 0)return null;const i={record:await w(t,e,this.#t),base:t.base,place:s};this.#a(i);try{await this.#t.store.hold(i,n)}catch(o){throw this.#c(i),o}return this.#t.localRecordsAvailable(),this.#l(),i.record}async free(t){this.#e.has(l(t))&&await this.release()}release(){this.#s?.cancel(),this.#s=null;const t=this.#o.then(()=>this.#h()).catch(s=>{throw this.#n||this.#i.arm(()=>{this.release().catch(this.#t.onError)}),s});return this.#o=t.catch(()=>{}),t}async close(){this.#n=!0,this.#i.cancel(),await this.release().catch(this.#t.onError)}async#h(){const t=await this.#t.store.held();for(const e of t)this.#a(e);if(t.length===0)return;const s=h(t.map(e=>e.base),this.#t),n=t.flatMap(({record:e})=>{const i=s.get(e.entityId);return i===void 0?[]:[p({mutationId:e.mutationId,authorityId:e.authorityId,lastSeenGlobalSequence:e.lastSeenGlobalSequence,change:i,createdAt:e.createdAt})]});await this.#t.store.release(n,t),this.#i.succeeded();for(const e of t)this.#c(e);this.#t.localRecordsAvailable(),this.#t.released(t)}#l(){this.#n||(this.#s?.cancel(),this.#s=this.#t.schedule.schedule(I,()=>{this.#s=null,this.release().catch(this.#t.onError)}))}#a(t){if(this.#r.has(t.record.mutationId))return;const s=l(t.place);this.#r.set(t.record.mutationId,s),this.#e.set(s,(this.#e.get(s)??0)+1)}#c(t){const s=this.#r.get(t.record.mutationId);if(s===void 0)return;this.#r.delete(t.record.mutationId);const n=(this.#e.get(s)??0)-1;n>0?this.#e.set(s,n):this.#e.delete(s)}}function h(r,t){const s=new Set(r.map(i=>i.uuid)),n=y(f(r,s,t.sha256Hex,i=>m(i)==="git")),e=new Map;for(const i of r){const o=n.get(i.uuid),c=o===void 0?null:d({base:i,result:o,replay:{kind:"structure"},lifecycleAuthorization:"trash"});c!==null&&e.set(i.uuid,c)}return e}a(h,"trashOf");const l=a(r=>JSON.stringify([r.root,...r.address]),"placeKey");export{I as HELD_REMOVAL_QUIET_MS,H as HeldRemovals};
@@ -1 +1 @@
1
- var v=Object.defineProperty;var c=(i,a)=>v(i,"name",{value:a,configurable:!0});import{CONTAINERS as E}from"../entities/types.js";import{active as p,derivedNames as m,entryOf as w,gitEntry as S,rootOf as y,shows as k,unshown as b,where as x}from"./where.js";async function R(i,a){const r=c(n=>!b([...a,n]),"shown"),e=await x(i,a);switch(e.kind){case"shelf":{const n=await y(i,e.root);if(n===null)return{kind:"nowhere"};const s=n.shelf.names(e.address);if(s===null)return n.shelf.has(e.address)?{kind:"notdir"}:{kind:"nowhere"};const o=s.filter(r),l=new Set(s),f=(e.homes??[]).filter(t=>!l.has(t.name)&&r(t.name)),u={kind:"entries",root:e.root,address:e.address,shelf:o,entries:f,standing:[]};if(e.entity===null||!E.has(e.entity.type))return u;if(!await n.map.enter(e.entity.uuid))return{kind:"nowhere"};const h=m(p(n.map.children(e.entity.uuid))).filter(([t,d])=>k(t)!==null&&r(d)),N=h.filter(([t,d])=>!n.map.placed(t.uuid)&&!l.has(d)),O=h.filter(([t,d])=>n.map.placed(t.uuid)&&l.has(d)).map(([t,d])=>({name:d,uuid:t.uuid}));return{...u,entries:await g(i,N),standing:O}}case"listed":{if(e.entry.kind!=="directory")return{kind:"notdir"};const n=await y(i,e.root);if(n===null)return{kind:"nowhere"};if(!await n.map.enter(e.entry.uuid))return{kind:"nowhere"};const s=m(p(n.map.children(e.entry.uuid))).filter(([f,u])=>k(f)!==null&&r(u)),o=e.entry.type==="repo.git"?await S(n.map,e.entity):void 0;if(o===null)return{kind:"place-first",placing:e.placing};const l=[...await g(i,s),...o===void 0?[]:[o]];return{kind:"entries",root:e.root,address:e.address,shelf:[],entries:l,standing:[]}}case"door":return e.entry?.kind==="file"?{kind:"notdir"}:e.homes===void 0?{kind:"place-first",placing:e.placing}:{kind:"entries",root:e.root,address:e.address,shelf:[],entries:e.homes.filter(n=>r(n.name)),standing:[]};case"absent":return{kind:"nowhere"};default:return e}}c(R,"listing");async function g(i,a){const r=[];for(const[e,n]of a){const s=e.type==="reference"&&e.target!==null&&await i.top(e.target)!==null;r.push(s?w(e,n,"directory"):w(e,n))}return r}c(g,"entries");export{R as listing};
1
+ var v=Object.defineProperty;var c=(i,a)=>v(i,"name",{value:a,configurable:!0});import{CONTAINERS as E}from"../entities/types.js";import{active as p,derivedNames as m,entryOf as w,gitEntry as S,rootOf as y,showing as k,unshown as b,where as x}from"./where.js";async function R(i,a){const r=c(n=>!b([...a,n]),"shown"),e=await x(i,a);switch(e.kind){case"shelf":{const n=await y(i,e.root);if(n===null)return{kind:"nowhere"};const s=n.shelf.names(e.address);if(s===null)return n.shelf.has(e.address)?{kind:"notdir"}:{kind:"nowhere"};const o=s.filter(r),l=new Set(s),f=(e.homes??[]).filter(t=>!l.has(t.name)&&r(t.name)),u={kind:"entries",root:e.root,address:e.address,shelf:o,entries:f,standing:[]};if(e.entity===null||!E.has(e.entity.type))return u;if(!await n.map.enter(e.entity.uuid))return{kind:"nowhere"};const h=m(p(n.map.children(e.entity.uuid))).filter(([t,d])=>k(n.map,t)!==null&&r(d)),N=h.filter(([t,d])=>!n.map.placed(t.uuid)&&!l.has(d)),O=h.filter(([t,d])=>n.map.placed(t.uuid)&&l.has(d)).map(([t,d])=>({name:d,uuid:t.uuid}));return{...u,entries:await g(i,N),standing:O}}case"listed":{if(e.entry.kind!=="directory")return{kind:"notdir"};const n=await y(i,e.root);if(n===null)return{kind:"nowhere"};if(!await n.map.enter(e.entry.uuid))return{kind:"nowhere"};const s=m(p(n.map.children(e.entry.uuid))).filter(([f,u])=>k(n.map,f)!==null&&r(u)),o=e.entry.type==="repo.git"?await S(n.map,e.entity):void 0;if(o===null)return{kind:"place-first",placing:e.placing};const l=[...await g(i,s),...o===void 0?[]:[o]];return{kind:"entries",root:e.root,address:e.address,shelf:[],entries:l,standing:[]}}case"door":return e.entry?.kind==="file"?{kind:"notdir"}:e.homes===void 0?{kind:"place-first",placing:e.placing}:{kind:"entries",root:e.root,address:e.address,shelf:[],entries:e.homes.filter(n=>r(n.name)),standing:[]};case"absent":return{kind:"nowhere"};default:return e}}c(R,"listing");async function g(i,a){const r=[];for(const[e,n]of a){const s=e.type==="reference"&&e.target!==null&&await i.top(e.target)!==null;r.push(s?w(e,n,"directory"):w(e,n))}return r}c(g,"entries");export{R as listing};
@@ -1 +1 @@
1
- var l=Object.defineProperty;var r=(u,e)=>l(u,"name",{value:e,configurable:!0});import{membershipVersion as p,recordGitHome as c}from"../entities/rules.js";import{projectPath as g}from"../entities/units.js";import{DERIVED_PAYLOAD as m}from"../entities/types.js";import{checkoutAsksProject as w,checkoutDirectories as v,checkoutFileOwner as U,checkoutFolderStands as D,checkoutStands as I}from"../git/checkout.js";import{DriveError as k}from"./contracts.js";class O{static{r(this,"MapIndex")}#i;#g;#e=new Map;#s=new Map;#u=new Set;#r=new Set;#o=new Set;#d=new Set;#a=new Set;#t=new Map;#n=new Map;constructor(e,t){this.#i=e,this.#g=t}get rootUUID(){return this.#i}get size(){return this.#e.size}enter(e,t){if(!this.#e.has(e))return!1;if(this.#u.has(e))return!0;this.#u.add(e),this.#r.delete(e),this.#n.has(e)&&!this.#t.has(e)&&this.#o.add(e),this.#h(e);for(const i of t)this.accept(i);return!0}sizes(e,t,i,s){this.#e.get(e)?.version!==t||this.#n.get(e)!==i||(this.#o.delete(e),this.#t.set(e,{version:t,sizes:s,directories:s===null?void 0:v(s)}),this.#m(e))}#m(e){this.#h(e);const t=[e];for(let i=t.pop();i!==void 0;i=t.pop())for(const s of this.#s.get(i)?.values()??[])for(const n of o(s))(d(n)||n.type==="folder")&&this.#h(n.uuid),n.type==="folder"&&(this.entered(n.uuid)||this.#r.add(n.uuid),t.push(n.uuid))}sizesOwed(){const e=[];for(const t of this.#o){const i=this.#e.get(t),s=this.#n.get(t);i?.type!=="repo.git"||s===void 0||this.#t.get(t)?.version!==i.version&&e.push({uuid:t,version:i.version,transportVersion:s})}return e}entered(e){return this.#u.has(e)}accept(e){const t=A(e),i=this.#t.get(e.uuid);if(i&&(this.#n.get(e.uuid)!==(e.transportVersion??void 0)||i.version!==t.version)&&(this.#t.delete(e.uuid),this.#m(e.uuid)),e.type==="repo.git"&&e.transportVersion!==null?this.#n.set(e.uuid,e.transportVersion):this.#n.delete(e.uuid),this.#u.has(e.uuid)&&this.#n.has(e.uuid)&&!this.#t.has(e.uuid)?this.#o.add(e.uuid):this.#o.delete(e.uuid),t.uuid===this.#i){this.#e.set(t.uuid,t),this.#h(t.uuid);return}if(t.parentUUID===null||!this.#u.has(t.parentUUID)){this.remove(t.uuid);return}const s=this.#e.get(t.uuid);this.#e.set(t.uuid,t),s!==void 0&&(s.parentUUID!==t.parentUUID||s.name!==t.name)&&(this.#U(s),this.#c(s.parentUUID)),this.#v(t),t.type==="folder"&&!this.entered(t.uuid)&&this.#r.add(t.uuid),this.#h(t.uuid),this.#c(t.parentUUID)}remove(e){const t=this.#e.get(e);t!==void 0&&e!==this.#i&&this.#c(t.parentUUID);const i=[e];for(let s=i.pop();s!==void 0;s=i.pop()){const n=this.#e.get(s);if(n===void 0)continue;this.#e.delete(s),this.#t.delete(s),this.#n.delete(s),this.#u.delete(s),this.#r.delete(s),this.#o.delete(s),this.#d.delete(s),this.#a.add(s),n.uuid!==this.#i&&this.#U(n);const h=this.#s.get(s);if(h!==void 0){this.#s.delete(s);for(const a of h.values())for(const f of o(a))i.push(f.uuid)}}}has(e){return this.#e.has(e)}retained(e){return this.#e.get(e)}parentOf(e){return this.#e.get(e)?.parentUUID}root(){const e=this.#e.get(this.#i);if(e===void 0)throw new Error(`the map of ${this.#i} holds no root`);return this.#l(e)}retainedChildren(e){const t=[];for(const i of this.#s.get(e)?.values()??[])t.push(...o(i));return t}get(e){const t=this.#e.get(e);return t===void 0||!this.#f(t)?void 0:this.#l(t)}children(e){return this.retainedChildren(e).filter(t=>this.#f(t)).map(t=>this.#l(t))}holders(e,t){const i=this.#s.get(e)?.get(t);return i===void 0?[]:o(i).filter(s=>this.#f(s)).map(s=>this.#l(s))}foldersOwed(){const e=[];for(const t of this.#r){const i=this.#e.get(t);if(i===void 0||i.type!=="folder"||i.status!=="active"||this.entered(t))continue;const s=this.#p(i);if(!s)continue;const n=this.#t.get(s.project.uuid);n&&!n.directories?.has(s.path)&&e.push(i.uuid)}return this.#r.clear(),e}#w(e){if(e.status!=="active"||e.uuid===this.#i)return!0;const t=w(e)?this.#D(e):null,i=I(e,t);if(i!=="children")return i;const s=this.entered(e.uuid)?this.retainedChildren(e.uuid).filter(n=>n.status==="active").map(n=>this.#w(n)):void 0;return D(t,s)}#D(e){const t=this.#p(e);if(!t)return null;const i=this.#t.get(t.project.uuid);return{files:i?.sizes,directories:i?.directories,path:t.path}}#f(e){const t=this.#w(e);if(t!==void 0)return t;throw new k("unavailable",`Checkout membership is unavailable for ${e.name}`,{root:this.#i,uuid:e.uuid,type:e.type,address:[]})}takeTouched(){const e=this.#a;return this.#a=new Set,e}#c(e){this.#h(e);let t=this.#e.get(e);if(t?.type!=="folder")return;const i=this.#p(t);if(!i)return;const s=this.#t.get(i.project.uuid)?.directories;let n=i.path;for(;t?.type==="folder"&&t.parentUUID!==null&&!s?.has(n);)this.#h(t.parentUUID),t=this.#e.get(t.parentUUID),n=n.slice(0,Math.max(0,n.lastIndexOf("/")))}#h(e){const t=this.#e.get(e);t!==void 0&&(this.#a.add(e),m.has(t.type)&&this.#u.has(e)?this.#d.add(e):this.#d.delete(e))}#l(e){if(d(e))return this.#I(e);if(!this.#d.has(e.uuid))return e;const t=[];for(const n of this.#s.get(e.uuid)?.values()??[])for(const h of o(n))h.status==="active"&&this.#f(h)&&t.push(h);const i=p(e,t,this.#g);if(this.#d.delete(e.uuid),i===e.version)return e;const s={...e,version:i};return this.#e.set(s.uuid,s),s.uuid!==this.#i&&this.#v(s),s}#I(e){const t=this.#p(e),i=t?this.#t.get(t.project.uuid):void 0;if(!t||i===void 0||i.version!==t.project.version)return e;const s=i.sizes?.get(t.path)?.size;return s===void 0?e:{...e,size:s}}#p(e){return g(e,t=>this.#e.get(t))??null}#v(e){if(e.parentUUID===null)return;let t=this.#s.get(e.parentUUID);t===void 0&&(t=new Map,this.#s.set(e.parentUUID,t));const i=t.get(e.name);if(i===void 0||!Array.isArray(i)&&i.uuid===e.uuid)t.set(e.name,e);else if(!Array.isArray(i))t.set(e.name,[i,e]);else{const s=i.findIndex(n=>n.uuid===e.uuid);s===-1?i.push(e):i[s]=e}}#U(e){if(e.parentUUID===null)return;const t=this.#s.get(e.parentUUID),i=t?.get(e.name);if(!(t===void 0||i===void 0)){if(Array.isArray(i)){const s=i.filter(n=>n.uuid!==e.uuid);s.length!==i.length&&t.set(e.name,s.length===1?s[0]:s);return}i.uuid===e.uuid&&(t.delete(e.name),t.size===0&&this.#s.delete(e.parentUUID))}}}function o(u){return Array.isArray(u)?u:[u]}r(o,"holdersOf");const d=r(u=>U(u)==="git","gitHeld"),z=new Set(["file.text","file.binary","link"]);function A(u){return{uuid:u.uuid,type:u.type,parentUUID:u.parentUUID,name:u.name,status:u.status,version:u.version,fileMode:u.fileMode,mtime:u.mtime,size:u.size,target:u.type==="reference"?u.payloadVersion:u.type==="link"?u.linkTarget:null,payloadVersion:z.has(u.type)?u.payloadVersion:null,gitHome:c(u)}}r(A,"mapEntity");export{O as MapIndex,A as mapEntity};
1
+ var l=Object.defineProperty;var r=(u,e)=>l(u,"name",{value:e,configurable:!0});import{membershipVersion as p,recordGitHome as c}from"../entities/rules.js";import{projectPath as g}from"../entities/units.js";import{DERIVED_PAYLOAD as m}from"../entities/types.js";import{checkoutAsksProject as w,checkoutDirectories as v,checkoutFileOwner as U,checkoutFolderStands as D,checkoutStands as I}from"../git/checkout.js";import{DriveError as k}from"./contracts.js";class O{static{r(this,"MapIndex")}#i;#c;#e=new Map;#s=new Map;#u=new Set;#r=new Set;#o=new Set;#d=new Set;#a=new Set;#t=new Map;#n=new Map;constructor(e,t){this.#i=e,this.#c=t}get rootUUID(){return this.#i}get size(){return this.#e.size}enter(e,t){if(!this.#e.has(e))return!1;if(this.#u.has(e))return!0;this.#u.add(e),this.#r.delete(e),this.#n.has(e)&&!this.#t.has(e)&&this.#o.add(e),this.#h(e);for(const i of t)this.accept(i);return!0}sizes(e,t,i,s){this.#e.get(e)?.version!==t||this.#n.get(e)!==i||(this.#o.delete(e),this.#t.set(e,{version:t,sizes:s,directories:s===null?void 0:v(s)}),this.#g(e))}#g(e){this.#h(e);const t=[e];for(let i=t.pop();i!==void 0;i=t.pop())for(const s of this.#s.get(i)?.values()??[])for(const n of o(s))(d(n)||n.type==="folder")&&this.#h(n.uuid),n.type==="folder"&&(this.entered(n.uuid)||this.#r.add(n.uuid),t.push(n.uuid))}sizesOwed(){const e=[];for(const t of this.#o){const i=this.#e.get(t),s=this.#n.get(t);i?.type!=="repo.git"||s===void 0||this.#t.get(t)?.version!==i.version&&e.push({uuid:t,version:i.version,transportVersion:s})}return e}entered(e){return this.#u.has(e)}accept(e){const t=A(e),i=this.#t.get(e.uuid);if(i&&(this.#n.get(e.uuid)!==(e.transportVersion??void 0)||i.version!==t.version)&&(this.#t.delete(e.uuid),this.#g(e.uuid)),e.type==="repo.git"&&e.transportVersion!==null?this.#n.set(e.uuid,e.transportVersion):this.#n.delete(e.uuid),this.#u.has(e.uuid)&&this.#n.has(e.uuid)&&!this.#t.has(e.uuid)?this.#o.add(e.uuid):this.#o.delete(e.uuid),t.uuid===this.#i){this.#e.set(t.uuid,t),this.#h(t.uuid);return}if(t.parentUUID===null||!this.#u.has(t.parentUUID)){this.remove(t.uuid);return}const s=this.#e.get(t.uuid);this.#e.set(t.uuid,t),s!==void 0&&(s.parentUUID!==t.parentUUID||s.name!==t.name)&&(this.#U(s),this.#p(s.parentUUID)),this.#v(t),t.type==="folder"&&!this.entered(t.uuid)&&this.#r.add(t.uuid),this.#h(t.uuid),this.#p(t.parentUUID)}remove(e){const t=this.#e.get(e);t!==void 0&&e!==this.#i&&this.#p(t.parentUUID);const i=[e];for(let s=i.pop();s!==void 0;s=i.pop()){const n=this.#e.get(s);if(n===void 0)continue;this.#e.delete(s),this.#t.delete(s),this.#n.delete(s),this.#u.delete(s),this.#r.delete(s),this.#o.delete(s),this.#d.delete(s),this.#a.add(s),n.uuid!==this.#i&&this.#U(n);const h=this.#s.get(s);if(h!==void 0){this.#s.delete(s);for(const a of h.values())for(const f of o(a))i.push(f.uuid)}}}has(e){return this.#e.has(e)}retained(e){return this.#e.get(e)}parentOf(e){return this.#e.get(e)?.parentUUID}root(){const e=this.#e.get(this.#i);if(e===void 0)throw new Error(`the map of ${this.#i} holds no root`);return this.#f(e)}retainedChildren(e){const t=[];for(const i of this.#s.get(e)?.values()??[])t.push(...o(i));return t}get(e){const t=this.#e.get(e);return t===void 0||!this.#w(t)?void 0:this.#f(t)}children(e){return this.retainedChildren(e).map(t=>this.#f(t))}holders(e,t){const i=this.#s.get(e)?.get(t);return i===void 0?[]:o(i).map(s=>this.#f(s))}foldersOwed(){const e=[];for(const t of this.#r){const i=this.#e.get(t);if(i===void 0||i.type!=="folder"||i.status!=="active"||this.entered(t))continue;const s=this.#l(i);if(!s)continue;const n=this.#t.get(s.project.uuid);n&&!n.directories?.has(s.path)&&e.push(i.uuid)}return this.#r.clear(),e}#m(e){if(e.status!=="active"||e.uuid===this.#i)return!0;const t=w(e)?this.#D(e):null,i=I(e,t);if(i!=="children")return i;const s=this.entered(e.uuid)?this.retainedChildren(e.uuid).filter(n=>n.status==="active").map(n=>this.#m(n)):void 0;return D(t,s)}#D(e){const t=this.#l(e);if(!t)return null;const i=this.#t.get(t.project.uuid);return{files:i?.sizes,directories:i?.directories,path:t.path}}#w(e){const t=this.#m(e);if(t!==void 0)return t;throw new k("unavailable",`Checkout membership is unavailable for ${e.name}`,{root:this.#i,uuid:e.uuid,type:e.type,address:[]})}takeTouched(){const e=this.#a;return this.#a=new Set,e}#p(e){this.#h(e);let t=this.#e.get(e);if(t?.type!=="folder")return;const i=this.#l(t);if(!i)return;const s=this.#t.get(i.project.uuid)?.directories;let n=i.path;for(;t?.type==="folder"&&t.parentUUID!==null&&!s?.has(n);)this.#h(t.parentUUID),t=this.#e.get(t.parentUUID),n=n.slice(0,Math.max(0,n.lastIndexOf("/")))}#h(e){const t=this.#e.get(e);t!==void 0&&(this.#a.add(e),m.has(t.type)&&this.#u.has(e)?this.#d.add(e):this.#d.delete(e))}#f(e){if(d(e))return this.#I(e);if(!this.#d.has(e.uuid))return e;const t=[];for(const n of this.#s.get(e.uuid)?.values()??[])for(const h of o(n))h.status==="active"&&this.#w(h)&&t.push(h);const i=p(e,t,this.#c);if(this.#d.delete(e.uuid),i===e.version)return e;const s={...e,version:i};return this.#e.set(s.uuid,s),s.uuid!==this.#i&&this.#v(s),s}#I(e){const t=this.#l(e),i=t?this.#t.get(t.project.uuid):void 0;if(!t||i===void 0||i.version!==t.project.version)return e;const s=i.sizes?.get(t.path)?.size;return s===void 0?e:{...e,size:s}}#l(e){return g(e,t=>this.#e.get(t))??null}#v(e){if(e.parentUUID===null)return;let t=this.#s.get(e.parentUUID);t===void 0&&(t=new Map,this.#s.set(e.parentUUID,t));const i=t.get(e.name);if(i===void 0||!Array.isArray(i)&&i.uuid===e.uuid)t.set(e.name,e);else if(!Array.isArray(i))t.set(e.name,[i,e]);else{const s=i.findIndex(n=>n.uuid===e.uuid);s===-1?i.push(e):i[s]=e}}#U(e){if(e.parentUUID===null)return;const t=this.#s.get(e.parentUUID),i=t?.get(e.name);if(!(t===void 0||i===void 0)){if(Array.isArray(i)){const s=i.filter(n=>n.uuid!==e.uuid);s.length!==i.length&&t.set(e.name,s.length===1?s[0]:s);return}i.uuid===e.uuid&&(t.delete(e.name),t.size===0&&this.#s.delete(e.parentUUID))}}}function o(u){return Array.isArray(u)?u:[u]}r(o,"holdersOf");const d=r(u=>U(u)==="git","gitHeld"),z=new Set(["file.text","file.binary","link"]);function A(u){return{...u.slotPosition===void 0?{}:{slotPosition:u.slotPosition},uuid:u.uuid,type:u.type,parentUUID:u.parentUUID,name:u.name,status:u.status,version:u.version,fileMode:u.fileMode,mtime:u.mtime,size:u.size,target:u.type==="reference"?u.payloadVersion:u.type==="link"?u.linkTarget:null,payloadVersion:z.has(u.type)?u.payloadVersion:null,gitHome:c(u)}}r(A,"mapEntity");export{O as MapIndex,A as mapEntity};
@@ -71,6 +71,7 @@ export declare function unshown(path: readonly string[]): boolean;
71
71
  export declare function addressOnly(roots: RootsPort, path: readonly string[], at: Where | Place): boolean;
72
72
  export declare function childAt(map: MapPort, parentUUID: string, name: string): Promise<MapEntity | null>;
73
73
  export declare function shows(entity: MapEntity): MapEntity | null;
74
+ export declare function showing(map: MapPort, child: MapEntity): MapEntity | null;
74
75
  export declare function aloneInSlot(map: MapPort, entity: MapEntity): Promise<boolean>;
75
76
  export declare function freeName(map: MapPort, parentUUID: string, name: string, uuid: string): Promise<boolean>;
76
77
  export declare function outsideRepositories(map: MapPort, address: readonly string[]): Promise<boolean>;
@@ -1,2 +1,2 @@
1
- var U=Object.defineProperty;var l=(e,n)=>U(e,"name",{value:n,configurable:!0});import{LOCAL_DIR_NAME as _}from"@amalgm/core/identity";import{isRepositoryMetadataEntry as N,REPOSITORY_METADATA as y}from"../detection/classify.js";import{inGitDirectory as V}from"./homes.js";import{utf8Length as S}from"../entities/bytes.js";import{collisionBases as b,materializedSlotNames as P}from"../entities/rules.js";import{fileAbsent as $}from"../git/checkout.js";import{CONTAINERS as L}from"../entities/types.js";import{FILES_FOLDER as j}from"../registration/home-layout.js";function B(e){return e.kind==="directory"||e.size!==null}l(B,"described");async function ue(e,n){if(z(n))return{kind:"nowhere"};const t=[];let r=!1,u=e.home.uuid,s=e.home.shelf,i=e.home.map,o=i.root(),d=[],O=o.name,w=!1;const A=l(()=>w?!1:s.has(d)?!0:(w=!0,!1),"standing");for(let a=0;;a+=1){const E=a===n.length,h=l(f=>[...d,...n.slice(f)],"whole");let m=i.placed(o.uuid),g=A();if(o.type==="reference"&&o.target!==null&&m===g){const f=await e.top(o.target);f!==null&&(!m&&!r&&t.push(R(u,o,d)),u=f.uuid,s=f.shelf,i=null,o=f.entity,d=[],w=!1,m=f.placed,g=A())}if(m){if(E)return{kind:"shelf",root:u,address:d,entity:o};if(!g)return{kind:"shelf",root:u,address:h(a),entity:null}}else{if(g)return{kind:"shelf",root:u,address:h(a),entity:null};{const f=o.type==="repo.git";if((f||!r)&&t.push(R(u,o,d)),f&&(r=!0),E)return{kind:"listed",root:u,address:d,entity:o,entry:v(o,O),placing:t};if(!L.has(o.type))return{kind:"notdir"}}}if(i??=(await e.enter(u))?.map??null,i===null||!await i.enter(o.uuid))return{kind:"nowhere"};const p=n[a],I=await C(i,o.uuid,p);if(d=[...d,p],O=p,I===null){if(r&&o.type==="repo.git"&&N(p)){const f=await Y(i,o);return a+1===n.length?{kind:"door",root:u,address:h(a+1),entry:f,placing:t}:f?.kind==="file"?{kind:"notdir"}:{kind:"door",root:u,address:h(a+1),entry:null,placing:t}}return t.length===0?(o.type==="repo.git"&&o.gitHome===null&&N(p)&&s.has(d)?await V(i,s,u,o,d,n.slice(a+1)):null)??{kind:"shelf",root:u,address:h(a+1),entity:null}:a+1===n.length?{kind:"absent",root:u,address:d,placing:t}:{kind:"nowhere"}}o=I}}l(ue,"where");function oe(e){return e.kind!=="listed"&&e.kind!=="door"?e:e.entry!==null&&B(e.entry)?{...e,entry:e.entry}:null}l(oe,"glance");async function G(e,n){return n===e.home.uuid?e.home:await e.enter(n)}l(G,"rootOf");function le(e,n){return n.kind!=="listed"&&n.kind!=="shelf"||!n.entity||n.entity.type!=="file.text"&&n.entity.type!=="file.binary"?null:{root:n.root,uuid:n.entity.uuid,prefix:e.slice(0,e.length-n.address.length)}}l(le,"fileAt");async function se(e,n){const t=await G(e,n.root);if(!t)return null;const r=t.map;r.get(n.uuid)||await r.enter(n.uuid);const u=[],s=new Set;let i=r.get(n.uuid);for(;i&&i.uuid!==t.uuid;){if(i.status!=="active"||!x(i)||i.parentUUID===null||s.has(i.uuid))return null;s.add(i.uuid);const o=i.parentUUID;if(!await r.enter(o))return null;const d=T(r,i);if(d===null)return null;u.push(d),i=r.get(o)}return i?.uuid===t.uuid?[...n.prefix,...u.reverse()]:null}l(se,"pathOfFile");function R(e,n,t){return{root:e,uuid:n.uuid,type:n.type,address:t}}l(R,"unitOf");function z(e){return e.some(n=>n.toLowerCase()===_)}l(z,"unshown");function de(e,n,t){return z(n)?!0:"root"in t?t.root===e.home.uuid?t.address[0]===j:t.address.length===0:!1}l(de,"addressOnly");async function C(e,n,t){if(!await e.enter(n))return null;const r=c(e.holders(n,t));if(r.length===1)return x(r[0]);if(r.length===0&&!H(e,n,t))return null;for(const[u,s]of M(c(e.children(n))))if(s===t)return x(u);return null}l(C,"childAt");function x(e){return $(e)?null:e}l(x,"shows");async function fe(e,n){const t=n.parentUUID;return t!==null&&await e.enter(t)&&D(e,t,n)}l(fe,"aloneInSlot");function D(e,n,t){const r=c(e.holders(n,t.name));return r.length===1&&r[0]?.uuid===t.uuid&&!H(e,n,t.name)}l(D,"soleHolder");async function ae(e,n,t,r){if(!await e.enter(n))return!1;const u=k(t),s=new Map(b(t).map(i=>[k(i),0]));for(const i of c(e.children(n))){if(i.uuid===r)continue;const o=k(i.name);if(o===u)return!1;const d=s.get(o);d!==void 0&&s.set(o,d+1)}return[...s.values()].every(i=>i<2)}l(ae,"freeName");function k(e){return e.normalize("NFC").toLowerCase()}l(k,"folded");function H(e,n,t){return b(t).some(r=>c(e.holders(n,r)).length>1)}l(H,"derivable");async function ce(e,n){let t=e.root();for(const r of n){if(t.type==="repo.git")return!1;const u=await C(e,t.uuid,r);if(u===null)return!1;t=u}return t.type!=="repo.git"}l(ce,"outsideRepositories");function M(e){const n=P(e);return e.map(t=>[t,n.get(t.uuid)??t.name])}l(M,"derivedNames");function v(e,n,t=K(e.type)){const r=e.type==="link"?e.target:null;return{name:n,uuid:e.uuid,type:e.type,kind:t,mode:e.fileMode,mtime:e.mtime,size:r!==null?S(r):e.size,target:r,version:e.version,payloadVersion:e.payloadVersion}}l(v,"entryOf");async function Y(e,n){if(n.gitHome===null)return v(n,y,"directory");const t=await J(e,n),r=F(e,n);if(r===null||t===null)return null;const u=S(q(r,t));return{...v(n,y,"file"),size:u,payloadVersion:null}}l(Y,"gitEntry");function q(e,n){let t=0;for(;t<e.length&&t<n.length&&e[t]===n[t];)t+=1;return`gitdir: ${[...e.slice(t).map(()=>".."),...n.slice(t)].join("/")}
2
- `}l(q,"gitPointer");async function J(e,n){const t=[],r=new Set([n.uuid]);let u=n;for(;u.gitHome!==null;){const{entity:i,path:o}=u.gitHome;if(i===null||r.has(i))return null;r.add(i),t.push(o===""?[]:o.split("/"));const d=e.get(i)??(await e.enter(i)?e.get(i):void 0);if(d===void 0||d.type!=="repo.git"||d.status!=="active")return null;u=d}const s=F(e,u);return s===null?null:[...s,y,...t.reverse().flat()]}l(J,"gitDirectoryIn");function F(e,n){const t=e.root().uuid,r=[],u=new Set;for(let s=n;s.uuid!==t;){const i=s.parentUUID===null?void 0:e.get(s.parentUUID);if(i===void 0||u.has(s.uuid)||s.status!=="active")return null;u.add(s.uuid);const o=T(e,s);if(o===null)return null;r.push(o),s=i}return r.reverse()}l(F,"addressIn");function T(e,n){const t=n.parentUUID;if(D(e,t,n))return n.name;for(const[r,u]of M(c(e.children(t))))if(r.uuid===n.uuid)return u;return null}l(T,"shownName");function K(e){if(L.has(e))return"directory";if(e==="file.text"||e==="file.binary")return"file";if(e==="link"||e==="reference")return"link";throw new Error(`a ${e} cannot stand in a folder`)}l(K,"kindOf");function c(e){return e.filter(n=>n.status==="active")}l(c,"active");export{c as active,F as addressIn,de as addressOnly,fe as aloneInSlot,C as childAt,M as derivedNames,B as described,v as entryOf,le as fileAt,ae as freeName,Y as gitEntry,q as gitPointer,oe as glance,K as kindOf,ce as outsideRepositories,se as pathOfFile,G as rootOf,x as shows,z as unshown,ue as where};
1
+ var _=Object.defineProperty;var l=(e,n)=>_(e,"name",{value:n,configurable:!0});import{LOCAL_DIR_NAME as V}from"@amalgm/core/identity";import{isRepositoryMetadataEntry as I,REPOSITORY_METADATA as y}from"../detection/classify.js";import{inGitDirectory as P}from"./homes.js";import{utf8Length as N}from"../entities/bytes.js";import{collisionBases as S,materializedSlotNames as $}from"../entities/rules.js";import{fileAbsent as j}from"../git/checkout.js";import{CONTAINERS as b}from"../entities/types.js";import{FILES_FOLDER as B}from"../registration/home-layout.js";function G(e){return e.kind==="directory"||e.size!==null}l(G,"described");async function oe(e,n){if(R(n))return{kind:"nowhere"};const t=[];let r=!1,u=e.home.uuid,s=e.home.shelf,i=e.home.map,o=i.root(),d=[],v=o.name,w=!1;const O=l(()=>w?!1:s.has(d)?!0:(w=!0,!1),"standing");for(let a=0;;a+=1){const A=a===n.length,h=l(f=>[...d,...n.slice(f)],"whole");let m=i.placed(o.uuid),g=O();if(o.type==="reference"&&o.target!==null&&m===g){const f=await e.top(o.target);f!==null&&(!m&&!r&&t.push(L(u,o,d)),u=f.uuid,s=f.shelf,i=null,o=f.entity,d=[],w=!1,m=f.placed,g=O())}if(m){if(A)return{kind:"shelf",root:u,address:d,entity:o};if(!g)return{kind:"shelf",root:u,address:h(a),entity:null}}else{if(g)return{kind:"shelf",root:u,address:h(a),entity:null};{const f=o.type==="repo.git";if((f||!r)&&t.push(L(u,o,d)),f&&(r=!0),A)return{kind:"listed",root:u,address:d,entity:o,entry:k(o,v),placing:t};if(!b.has(o.type))return{kind:"notdir"}}}if(i??=(await e.enter(u))?.map??null,i===null||!await i.enter(o.uuid))return{kind:"nowhere"};const p=n[a],E=await z(i,o.uuid,p);if(d=[...d,p],v=p,E===null){if(r&&o.type==="repo.git"&&I(p)){const f=await q(i,o);return a+1===n.length?{kind:"door",root:u,address:h(a+1),entry:f,placing:t}:f?.kind==="file"?{kind:"notdir"}:{kind:"door",root:u,address:h(a+1),entry:null,placing:t}}return t.length===0?(o.type==="repo.git"&&o.gitHome===null&&I(p)&&s.has(d)?await P(i,s,u,o,d,n.slice(a+1)):null)??{kind:"shelf",root:u,address:h(a+1),entity:null}:a+1===n.length?{kind:"absent",root:u,address:d,placing:t}:{kind:"nowhere"}}o=E}}l(oe,"where");function le(e){return e.kind!=="listed"&&e.kind!=="door"?e:e.entry!==null&&G(e.entry)?{...e,entry:e.entry}:null}l(le,"glance");async function Y(e,n){return n===e.home.uuid?e.home:await e.enter(n)}l(Y,"rootOf");function se(e,n){return n.kind!=="listed"&&n.kind!=="shelf"||!n.entity||n.entity.type!=="file.text"&&n.entity.type!=="file.binary"?null:{root:n.root,uuid:n.entity.uuid,prefix:e.slice(0,e.length-n.address.length)}}l(se,"fileAt");async function de(e,n){const t=await Y(e,n.root);if(!t)return null;const r=t.map;r.get(n.uuid)||await r.enter(n.uuid);const u=[],s=new Set;let i=r.get(n.uuid);for(;i&&i.uuid!==t.uuid;){if(i.status!=="active"||!C(i)||i.parentUUID===null||s.has(i.uuid))return null;s.add(i.uuid);const o=i.parentUUID;if(!await r.enter(o))return null;const d=U(r,i);if(d===null)return null;u.push(d),i=r.get(o)}return i?.uuid===t.uuid?[...n.prefix,...u.reverse()]:null}l(de,"pathOfFile");function L(e,n,t){return{root:e,uuid:n.uuid,type:n.type,address:t}}l(L,"unitOf");function R(e){return e.some(n=>n.toLowerCase()===V)}l(R,"unshown");function fe(e,n,t){return R(n)?!0:"root"in t?t.root===e.home.uuid?t.address[0]===B:t.address.length===0:!1}l(fe,"addressOnly");async function z(e,n,t){if(!await e.enter(n))return null;const r=c(e.holders(n,t));if(r.length===1)return D(e,r[0]);if(r.length===0&&!M(e,n,t))return null;for(const[u,s]of F(c(e.children(n))))if(s===t)return D(e,u);return null}l(z,"childAt");function C(e){return j(e)?null:e}l(C,"shows");function D(e,n){const t=e.get(n.uuid);return t===void 0?null:C(t)}l(D,"showing");async function ae(e,n){const t=n.parentUUID;return t!==null&&await e.enter(t)&&H(e,t,n)}l(ae,"aloneInSlot");function H(e,n,t){const r=c(e.holders(n,t.name));return r.length===1&&r[0]?.uuid===t.uuid&&!M(e,n,t.name)}l(H,"soleHolder");async function ce(e,n,t,r){if(!await e.enter(n))return!1;const u=x(t),s=new Map(S(t).map(i=>[x(i),0]));for(const i of c(e.children(n))){if(i.uuid===r)continue;const o=x(i.name);if(o===u)return!1;const d=s.get(o);d!==void 0&&s.set(o,d+1)}return[...s.values()].every(i=>i<2)}l(ce,"freeName");function x(e){return e.normalize("NFC").toLowerCase()}l(x,"folded");function M(e,n,t){return S(t).some(r=>c(e.holders(n,r)).length>1)}l(M,"derivable");async function he(e,n){let t=e.root();for(const r of n){if(t.type==="repo.git")return!1;const u=await z(e,t.uuid,r);if(u===null)return!1;t=u}return t.type!=="repo.git"}l(he,"outsideRepositories");function F(e){const n=$(e);return e.map(t=>[t,n.get(t.uuid)??t.name])}l(F,"derivedNames");function k(e,n,t=Q(e.type)){const r=e.type==="link"?e.target:null;return{name:n,uuid:e.uuid,type:e.type,kind:t,mode:e.fileMode,mtime:e.mtime,size:r!==null?N(r):e.size,target:r,version:e.version,payloadVersion:e.payloadVersion}}l(k,"entryOf");async function q(e,n){if(n.gitHome===null)return k(n,y,"directory");const t=await K(e,n),r=T(e,n);if(r===null||t===null)return null;const u=N(J(r,t));return{...k(n,y,"file"),size:u,payloadVersion:null}}l(q,"gitEntry");function J(e,n){let t=0;for(;t<e.length&&t<n.length&&e[t]===n[t];)t+=1;return`gitdir: ${[...e.slice(t).map(()=>".."),...n.slice(t)].join("/")}
2
+ `}l(J,"gitPointer");async function K(e,n){const t=[],r=new Set([n.uuid]);let u=n;for(;u.gitHome!==null;){const{entity:i,path:o}=u.gitHome;if(i===null||r.has(i))return null;r.add(i),t.push(o===""?[]:o.split("/"));const d=e.get(i)??(await e.enter(i)?e.get(i):void 0);if(d===void 0||d.type!=="repo.git"||d.status!=="active")return null;u=d}const s=T(e,u);return s===null?null:[...s,y,...t.reverse().flat()]}l(K,"gitDirectoryIn");function T(e,n){const t=e.root().uuid,r=[],u=new Set;for(let s=n;s.uuid!==t;){const i=s.parentUUID===null?void 0:e.get(s.parentUUID);if(i===void 0||u.has(s.uuid)||s.status!=="active")return null;u.add(s.uuid);const o=U(e,s);if(o===null)return null;r.push(o),s=i}return r.reverse()}l(T,"addressIn");function U(e,n){const t=n.parentUUID;if(H(e,t,n))return n.name;for(const[r,u]of F(c(e.children(t))))if(r.uuid===n.uuid)return u;return null}l(U,"shownName");function Q(e){if(b.has(e))return"directory";if(e==="file.text"||e==="file.binary")return"file";if(e==="link"||e==="reference")return"link";throw new Error(`a ${e} cannot stand in a folder`)}l(Q,"kindOf");function c(e){return e.filter(n=>n.status==="active")}l(c,"active");export{c as active,T as addressIn,fe as addressOnly,ae as aloneInSlot,z as childAt,F as derivedNames,G as described,k as entryOf,se as fileAt,ce as freeName,q as gitEntry,J as gitPointer,le as glance,Q as kindOf,he as outsideRepositories,de as pathOfFile,Y as rootOf,D as showing,C as shows,R as unshown,oe as where};
@@ -3,6 +3,7 @@ import { type Steps } from '../steps.js';
3
3
  export declare const ENTITY_CLOUD_CONTRACT = "amalgm-entity-registry@12";
4
4
  export declare const ENTITY_CLOUD_SCHEMA_VERSION = 1;
5
5
  export interface CloudEntityRecord {
6
+ readonly slotPosition?: number;
6
7
  readonly uuid: string;
7
8
  readonly type: EntityType;
8
9
  readonly parentUUID: string | null;
@@ -1 +1 @@
1
- var V=Object.defineProperty;var p=(e,t)=>V(e,"name",{value:t,configurable:!0});import{CONTAINERS as w,DERIVED_PAYLOAD as k,ROOT_TYPES as z,STATUSES as C,TYPES as M,UUID_PATTERN as h}from"./types.js";import{bytesToBase64Url as N,hexToBytes as O,utf8Decode as A}from"./bytes.js";import{isName as _,validFileState as P,validGitHome as $,validLinkTarget as L,validPortableMtime as H,validPortableSize as Y}from"./rules.js";import{clashResolution as F}from"../clash/resolution.js";import{eachStep as f,finishSteps as y,ITEMS_PER_BOUNDARY as E,sortSteps as B}from"../steps.js";import{failure as J}from"../faults/need.js";const j="amalgm-entity-registry@12",S=1,D=/^[0-9a-f]{64}$/;function lt(e,t){return`pvr_${N(O(t(`private-user:${e}:${j}`))).slice(0,32)}`}p(lt,"privateEntityResourceId");function pt(e){return/^pvr_[A-Za-z0-9_-]{32}$/.test(e)}p(pt,"isPrivateEntityResourceId");const I=p(e=>JSON.stringify(e),"stableJson"),ct=p((e,t)=>I(e)===I(t),"sameRecord"),G=["uuid","type","parentUUID","name","status","version","payloadVersion","fileMode","mtime","size","linkTarget","gitHomeEntity","gitHomePath","transportVersion"];function R(e,t){const r=m(e).records,n=m(t).records;if(r.length!==n.length)return!1;for(let o=0;o<r.length;o+=1){const l=r[o],u=n[o];if(l!==u){for(const i of G)if(l[i]!==u[i])return!1}}return!0}p(R,"sameRecords");function W(e,t){const r=new Map(t.map(n=>[n.uuid,n]));return m(e).records.map(n=>{const o=r.get(n.uuid);return!o||o.type!==n.type||o.parentUUID!==n.parentUUID||o.name!==n.name||o.status!==n.status?n:F(n.type)==="play"?o:n})}p(W,"statedRecords");const T=new WeakSet;function Z(e){if(typeof e=="object"&&e!==null&&T.has(e))return e;const t=e;if(!t||typeof t!="object"||typeof t.uuid!="string"||!h.test(t.uuid)||typeof t.type!="string"||!M.has(t.type)||t.parentUUID!==null&&(typeof t.parentUUID!="string"||!h.test(t.parentUUID))||!_(t.name)||!C.has(t.status)||typeof t.version!="string"||!D.test(t.version)||t.payloadVersion!==null&&typeof t.payloadVersion!="string"||!P(t.type,t.payloadVersion,t.fileMode)||!H(t.type,t.mtime,t.payloadVersion===null&&t.fileMode===null)||!Y(t.type,t.payloadVersion,t.size)||!L(t.type,t.payloadVersion,t.linkTarget)||!$(t.type,t.gitHomeEntity??null,t.gitHomePath??null)||t.transportVersion!==void 0&&t.transportVersion!==null&&(typeof t.transportVersion!="string"||!D.test(t.transportVersion)))throw new Error("cloud entity snapshot has an invalid record");if(t.parentUUID===null&&!z.has(t.type))throw new Error(`cloud entity ${t.uuid} is not a valid tree root`);if(k.has(t.type)&&t.payloadVersion!==null)throw new Error("workspace and folder payloads are derived membership, never transported heads");const r=t.transportVersion??null;if(t.type!=="repo.git"&&r!==null)throw new Error("only a repository may declare a transport head");const n=Object.freeze({uuid:t.uuid.toLowerCase(),type:t.type,parentUUID:t.parentUUID===null?null:t.parentUUID.toLowerCase(),name:t.name,status:t.status,version:t.version,payloadVersion:t.payloadVersion,fileMode:t.fileMode,mtime:t.mtime,size:t.size,linkTarget:t.linkTarget,gitHomeEntity:t.gitHomeEntity??null,gitHomePath:t.gitHomePath??null,transportVersion:r});return T.add(n),n}p(Z,"assertRecord");function*q(e){const t=[],r=new Set;return yield*f(e,n=>{const o=Z(n);if(r.has(o.uuid))throw new Error("cloud entity snapshot has duplicate UUIDs");r.add(o.uuid),t.push(o)}),t}p(q,"assertedRecordsSteps");function*g(e){const t=yield*B(yield*q(e),(r,n)=>r.uuid<n.uuid?-1:r.uuid>n.uuid?1:0);return{schemaVersion:S,kind:"amalgm-entity-registry",records:t}}p(g,"snapshotFromRecordsSteps");function m(e){return y(g(e))}p(m,"snapshotFromRecords");function*b(e,t){const r=new Map;yield*f(e,i=>{if(i.parentUUID===null)return;const s=r.get(i.parentUUID);s?s.push(i):r.set(i.parentUUID,[i])});const n=new Set([t]),o=[t];let l=0;for(;o.length>0;){for(const i of r.get(o.pop())??[])n.has(i.uuid)||(n.add(i.uuid),o.push(i.uuid));++l%E===0&&(yield)}const u=[];return yield*f(e,i=>{n.has(i.uuid)&&u.push(i)}),u}p(b,"containedRecordsSteps");function dt(e,t){return y(b(e,t))}p(dt,"containedRecords");function*K(e,t){const r=yield*b((yield*g(e)).records,t),n=new Map;yield*f(r,a=>n.set(a.uuid,a));const o=n.get(t);if(!o||o.status!=="active")return[];if(!w.has(o.type))throw new Error(`cloud materialization root ${o.uuid} is not a container`);const l=new Map;yield*f(r,a=>{if(a.uuid===o.uuid)return;if(a.parentUUID===null)throw new Error(`cloud materialization entity ${a.uuid} escapes its selected root`);if(!n.get(a.parentUUID))throw new Error(`cloud materialization entity ${a.uuid} has incomplete ancestry`);const U=l.get(a.parentUUID);U?U.push(a):l.set(a.parentUUID,[a])});const u=new Set,i=[o];let s=0;for(;i.length>0;){const a=i.pop();if(!(a.status!=="active"||u.has(a.uuid))&&(u.add(a.uuid),!!w.has(a.type))){for(const d of l.get(a.uuid)??[])d.status==="active"&&i.push(d);++s%E===0&&(yield)}}const c=[];return yield*f(r,a=>{u.has(a.uuid)&&c.push(a)}),c}p(K,"materializableRecordsSteps");function Q(e,t){return y(K(e,t))}p(Q,"materializableRecords");function ft(e,t){const r=e??[];if(!Array.isArray(r)||r.some(o=>typeof o!="string"||!h.test(o)))throw new Error(`${t} names invalid waiting entities`);const n=r.map(o=>o.toLowerCase());if(new Set(n).size!==n.length)throw new Error(`${t} names a waiting entity twice`);return n}p(ft,"waitingEntities");function ht(e,t,r,n,o=[]){const l=W(e,r),u=Q(r,n),i=new Set(u.map(({uuid:s})=>s));return t.some(({uuid:s})=>i.has(s))?!1:R(l,X(u,n,o))&&R([...u,...t],r)}p(ht,"installedSubtree");function X(e,t,r){if(r.length===0)return e;const n=new Map(e.map(i=>[i.uuid,i])),o=new Set(r);for(const i of o)if(i===t||!n.has(i))throw new Error("a waiting entity is not one the placement places beneath its root");const l=new Map,u=p(i=>{const s=[];let c=i,a=!1;for(;c!==void 0;){const d=l.get(c.uuid);if(d!==void 0){a=d;break}if(o.has(c.uuid)){a=!0,s.push(c.uuid);break}s.push(c.uuid),c=c.parentUUID===null?void 0:n.get(c.parentUUID)}for(const d of s)l.set(d,a);return a},"waitsBeneath");return e.filter(i=>!u(i))}p(X,"withoutWaiting");const x=Symbol("parent cycle"),v=Symbol("incomplete ancestry");function tt(e){const t=new Map;return r=>{const n=[],o=new Set;let l=r,u;for(;;){const i=t.get(l.uuid);if(i!==void 0){u=i;break}if(l.parentUUID===null){u=l.uuid;break}if(o.has(l.uuid)){u=x;break}o.add(l.uuid),n.push(l.uuid);const s=e.get(l.parentUUID);if(!s){u=v;break}l=s}for(const i of n)t.set(i,u);return u}}p(tt,"createRootResolver");function yt(e,t){return y(et(e,t))}p(yt,"completeRootsFromRecords");function*et(e,t){if(e.length===0)throw new Error("cloud root set has no roots");const r=e.map(s=>{if(!h.test(s))throw new Error("cloud root set has an invalid root UUID");return s.toLowerCase()}).sort();if(new Set(r).size!==r.length)throw new Error("cloud root set has duplicate roots");const n=yield*g(t),o=new Map;yield*f(n.records,s=>{o.set(s.uuid,s)});const l=new Set(r),u=n.records.filter(s=>s.parentUUID===null).map(s=>s.uuid).sort();if(u.length!==r.length||u.some((s,c)=>s!==r[c]))throw new Error("cloud root set records do not exactly match its roots");const i=tt(o);return yield*f(n.records,s=>{if(s.parentUUID!==null){const a=o.get(s.parentUUID);if(!a||s.status==="active"&&!w.has(a.type))throw new Error(`cloud root set entity ${s.uuid} has no container parent`)}const c=i(s);if(c===x)throw J("cloud root set has a parent cycle","graph-cycle","parent-cycle");if(c===v)throw new Error(`cloud root set entity ${s.uuid} has incomplete ancestry`);if(!l.has(c))throw new Error(`cloud root set entity ${s.uuid} is outside its declared roots`)}),n.records}p(et,"completeRootsFromRecordsSteps");function mt(e){let t;try{t=JSON.parse(typeof e=="string"?e:A(e))}catch{throw new Error("cloud entity snapshot is not JSON")}if(t?.schemaVersion!==S||t?.kind!=="amalgm-entity-registry"||!Array.isArray(t.records))throw new Error("cloud entity snapshot has an unsupported shape");return m(t.records)}p(mt,"parseSnapshot");export{j as ENTITY_CLOUD_CONTRACT,S as ENTITY_CLOUD_SCHEMA_VERSION,Z as assertRecord,q as assertedRecordsSteps,yt as completeRootsFromRecords,et as completeRootsFromRecordsSteps,dt as containedRecords,b as containedRecordsSteps,ht as installedSubtree,pt as isPrivateEntityResourceId,Q as materializableRecords,K as materializableRecordsSteps,mt as parseSnapshot,lt as privateEntityResourceId,ct as sameRecord,R as sameRecords,m as snapshotFromRecords,g as snapshotFromRecordsSteps,I as stableJson,W as statedRecords,ft as waitingEntities,X as withoutWaiting};
1
+ var V=Object.defineProperty;var p=(e,t)=>V(e,"name",{value:t,configurable:!0});import{CONTAINERS as w,DERIVED_PAYLOAD as P,ROOT_TYPES as k,STATUSES as z,TYPES as N,UUID_PATTERN as h}from"./types.js";import{bytesToBase64Url as C,hexToBytes as M,utf8Decode as O}from"./bytes.js";import{isName as A,validFileState as _,validGitHome as $,validLinkTarget as L,validPortableMtime as H,validPortableSize as Y}from"./rules.js";import{clashResolution as F}from"../clash/resolution.js";import{eachStep as f,finishSteps as y,ITEMS_PER_BOUNDARY as E,sortSteps as B}from"../steps.js";import{failure as J}from"../faults/need.js";const j="amalgm-entity-registry@12",S=1,I=/^[0-9a-f]{64}$/;function lt(e,t){return`pvr_${C(M(t(`private-user:${e}:${j}`))).slice(0,32)}`}p(lt,"privateEntityResourceId");function pt(e){return/^pvr_[A-Za-z0-9_-]{32}$/.test(e)}p(pt,"isPrivateEntityResourceId");const D=p(e=>JSON.stringify(e),"stableJson"),ct=p((e,t)=>D(e)===D(t),"sameRecord"),G=["uuid","type","parentUUID","name","status","version","payloadVersion","fileMode","mtime","size","linkTarget","gitHomeEntity","gitHomePath","transportVersion"];function R(e,t){const r=m(e).records,n=m(t).records;if(r.length!==n.length)return!1;for(let o=0;o<r.length;o+=1){const l=r[o],u=n[o];if(l!==u){for(const i of G)if(l[i]!==u[i])return!1}}return!0}p(R,"sameRecords");function W(e,t){const r=new Map(t.map(n=>[n.uuid,n]));return m(e).records.map(n=>{const o=r.get(n.uuid);return!o||o.type!==n.type||o.parentUUID!==n.parentUUID||o.name!==n.name||o.status!==n.status?n:F(n.type)==="play"?o:n})}p(W,"statedRecords");const b=new WeakSet;function Z(e){if(typeof e=="object"&&e!==null&&b.has(e))return e;const t=e;if(!t||typeof t!="object"||typeof t.uuid!="string"||!h.test(t.uuid)||typeof t.type!="string"||!N.has(t.type)||t.parentUUID!==null&&(typeof t.parentUUID!="string"||!h.test(t.parentUUID))||!A(t.name)||!z.has(t.status)||typeof t.version!="string"||!I.test(t.version)||t.payloadVersion!==null&&typeof t.payloadVersion!="string"||t.slotPosition!==void 0&&(!Number.isSafeInteger(t.slotPosition)||t.slotPosition<0)||!_(t.type,t.payloadVersion,t.fileMode)||!H(t.type,t.mtime,t.payloadVersion===null&&t.fileMode===null)||!Y(t.type,t.payloadVersion,t.size)||!L(t.type,t.payloadVersion,t.linkTarget)||!$(t.type,t.gitHomeEntity??null,t.gitHomePath??null)||t.transportVersion!==void 0&&t.transportVersion!==null&&(typeof t.transportVersion!="string"||!I.test(t.transportVersion)))throw new Error("cloud entity snapshot has an invalid record");if(t.parentUUID===null&&!k.has(t.type))throw new Error(`cloud entity ${t.uuid} is not a valid tree root`);if(P.has(t.type)&&t.payloadVersion!==null)throw new Error("workspace and folder payloads are derived membership, never transported heads");const r=t.transportVersion??null;if(t.type!=="repo.git"&&r!==null)throw new Error("only a repository may declare a transport head");const n=Object.freeze({uuid:t.uuid.toLowerCase(),type:t.type,parentUUID:t.parentUUID===null?null:t.parentUUID.toLowerCase(),name:t.name,status:t.status,version:t.version,payloadVersion:t.payloadVersion,fileMode:t.fileMode,mtime:t.mtime,size:t.size,linkTarget:t.linkTarget,gitHomeEntity:t.gitHomeEntity??null,gitHomePath:t.gitHomePath??null,transportVersion:r,...t.slotPosition===void 0||t.status!=="active"||t.parentUUID===null?{}:{slotPosition:t.slotPosition}});return b.add(n),n}p(Z,"assertRecord");function*q(e){const t=[],r=new Set;return yield*f(e,n=>{const o=Z(n);if(r.has(o.uuid))throw new Error("cloud entity snapshot has duplicate UUIDs");r.add(o.uuid),t.push(o)}),t}p(q,"assertedRecordsSteps");function*U(e){const t=yield*B(yield*q(e),(r,n)=>r.uuid<n.uuid?-1:r.uuid>n.uuid?1:0);return{schemaVersion:S,kind:"amalgm-entity-registry",records:t}}p(U,"snapshotFromRecordsSteps");function m(e){return y(U(e))}p(m,"snapshotFromRecords");function*T(e,t){const r=new Map;yield*f(e,i=>{if(i.parentUUID===null)return;const s=r.get(i.parentUUID);s?s.push(i):r.set(i.parentUUID,[i])});const n=new Set([t]),o=[t];let l=0;for(;o.length>0;){for(const i of r.get(o.pop())??[])n.has(i.uuid)||(n.add(i.uuid),o.push(i.uuid));++l%E===0&&(yield)}const u=[];return yield*f(e,i=>{n.has(i.uuid)&&u.push(i)}),u}p(T,"containedRecordsSteps");function dt(e,t){return y(T(e,t))}p(dt,"containedRecords");function*K(e,t){const r=yield*T((yield*U(e)).records,t),n=new Map;yield*f(r,a=>n.set(a.uuid,a));const o=n.get(t);if(!o||o.status!=="active")return[];if(!w.has(o.type))throw new Error(`cloud materialization root ${o.uuid} is not a container`);const l=new Map;yield*f(r,a=>{if(a.uuid===o.uuid)return;if(a.parentUUID===null)throw new Error(`cloud materialization entity ${a.uuid} escapes its selected root`);if(!n.get(a.parentUUID))throw new Error(`cloud materialization entity ${a.uuid} has incomplete ancestry`);const g=l.get(a.parentUUID);g?g.push(a):l.set(a.parentUUID,[a])});const u=new Set,i=[o];let s=0;for(;i.length>0;){const a=i.pop();if(!(a.status!=="active"||u.has(a.uuid))&&(u.add(a.uuid),!!w.has(a.type))){for(const d of l.get(a.uuid)??[])d.status==="active"&&i.push(d);++s%E===0&&(yield)}}const c=[];return yield*f(r,a=>{u.has(a.uuid)&&c.push(a)}),c}p(K,"materializableRecordsSteps");function Q(e,t){return y(K(e,t))}p(Q,"materializableRecords");function ft(e,t){const r=e??[];if(!Array.isArray(r)||r.some(o=>typeof o!="string"||!h.test(o)))throw new Error(`${t} names invalid waiting entities`);const n=r.map(o=>o.toLowerCase());if(new Set(n).size!==n.length)throw new Error(`${t} names a waiting entity twice`);return n}p(ft,"waitingEntities");function ht(e,t,r,n,o=[]){const l=W(e,r),u=Q(r,n),i=new Set(u.map(({uuid:s})=>s));return t.some(({uuid:s})=>i.has(s))?!1:R(l,X(u,n,o))&&R([...u,...t],r)}p(ht,"installedSubtree");function X(e,t,r){if(r.length===0)return e;const n=new Map(e.map(i=>[i.uuid,i])),o=new Set(r);for(const i of o)if(i===t||!n.has(i))throw new Error("a waiting entity is not one the placement places beneath its root");const l=new Map,u=p(i=>{const s=[];let c=i,a=!1;for(;c!==void 0;){const d=l.get(c.uuid);if(d!==void 0){a=d;break}if(o.has(c.uuid)){a=!0,s.push(c.uuid);break}s.push(c.uuid),c=c.parentUUID===null?void 0:n.get(c.parentUUID)}for(const d of s)l.set(d,a);return a},"waitsBeneath");return e.filter(i=>!u(i))}p(X,"withoutWaiting");const v=Symbol("parent cycle"),x=Symbol("incomplete ancestry");function tt(e){const t=new Map;return r=>{const n=[],o=new Set;let l=r,u;for(;;){const i=t.get(l.uuid);if(i!==void 0){u=i;break}if(l.parentUUID===null){u=l.uuid;break}if(o.has(l.uuid)){u=v;break}o.add(l.uuid),n.push(l.uuid);const s=e.get(l.parentUUID);if(!s){u=x;break}l=s}for(const i of n)t.set(i,u);return u}}p(tt,"createRootResolver");function yt(e,t){return y(et(e,t))}p(yt,"completeRootsFromRecords");function*et(e,t){if(e.length===0)throw new Error("cloud root set has no roots");const r=e.map(s=>{if(!h.test(s))throw new Error("cloud root set has an invalid root UUID");return s.toLowerCase()}).sort();if(new Set(r).size!==r.length)throw new Error("cloud root set has duplicate roots");const n=yield*U(t),o=new Map;yield*f(n.records,s=>{o.set(s.uuid,s)});const l=new Set(r),u=n.records.filter(s=>s.parentUUID===null).map(s=>s.uuid).sort();if(u.length!==r.length||u.some((s,c)=>s!==r[c]))throw new Error("cloud root set records do not exactly match its roots");const i=tt(o);return yield*f(n.records,s=>{if(s.parentUUID!==null){const a=o.get(s.parentUUID);if(!a||s.status==="active"&&!w.has(a.type))throw new Error(`cloud root set entity ${s.uuid} has no container parent`)}const c=i(s);if(c===v)throw J("cloud root set has a parent cycle","graph-cycle","parent-cycle");if(c===x)throw new Error(`cloud root set entity ${s.uuid} has incomplete ancestry`);if(!l.has(c))throw new Error(`cloud root set entity ${s.uuid} is outside its declared roots`)}),n.records}p(et,"completeRootsFromRecordsSteps");function mt(e){let t;try{t=JSON.parse(typeof e=="string"?e:O(e))}catch{throw new Error("cloud entity snapshot is not JSON")}if(t?.schemaVersion!==S||t?.kind!=="amalgm-entity-registry"||!Array.isArray(t.records))throw new Error("cloud entity snapshot has an unsupported shape");return m(t.records)}p(mt,"parseSnapshot");export{j as ENTITY_CLOUD_CONTRACT,S as ENTITY_CLOUD_SCHEMA_VERSION,Z as assertRecord,q as assertedRecordsSteps,yt as completeRootsFromRecords,et as completeRootsFromRecordsSteps,dt as containedRecords,T as containedRecordsSteps,ht as installedSubtree,pt as isPrivateEntityResourceId,Q as materializableRecords,K as materializableRecordsSteps,mt as parseSnapshot,lt as privateEntityResourceId,ct as sameRecord,R as sameRecords,m as snapshotFromRecords,U as snapshotFromRecordsSteps,D as stableJson,W as statedRecords,ft as waitingEntities,X as withoutWaiting};
@@ -1,5 +1,6 @@
1
1
  import type { EntityStatus, EntityType } from './types.js';
2
2
  export interface PlacementFacts {
3
+ readonly slotPosition?: number | null;
3
4
  readonly parentUUID: string | null;
4
5
  readonly name: string;
5
6
  readonly status: EntityStatus;
@@ -12,6 +13,7 @@ export interface OwedSlot {
12
13
  export type SlotHolders = (slot: OwedSlot) => readonly string[];
13
14
  export declare function placementOwed(uuid: string, before: PlacementFacts | null, after: PlacementFacts | null, holders: SlotHolders): OwedSlot[];
14
15
  export interface SlotChild {
16
+ readonly slotPosition?: number | null;
15
17
  readonly uuid: string;
16
18
  readonly name: string;
17
19
  readonly type: EntityType;
@@ -1 +1 @@
1
- var g=Object.defineProperty;var l=(e,n)=>g(e,"name",{value:n,configurable:!0});import{collisionBases as c,materializedSlotNames as i}from"./rules.js";function I(e,n,t,u){const o=l(a=>a!==null&&a.status==="active"&&a.parentUUID!==null,"active");if(n&&t&&n.parentUUID===t.parentUUID&&n.name===t.name&&n.type===t.type&&o(n)===o(t))return[];const r=[];for(const a of[n,t]){if(!o(a)||r.some(s=>s.parentUUID===a.parentUUID&&s.name===a.name))continue;const{parentUUID:m,name:p}=a;(u({parentUUID:m,name:p}).some(s=>s!==e)||c(p).some(s=>u({parentUUID:m,name:s}).length>1))&&r.push({parentUUID:m,name:p})}return r}l(I,"placementOwed");function f(e,n){return n.holders(e.name).length<=1?e.name:i(n.group()).get(e.uuid)??e.name}l(f,"derivedSlotName");function w(e,n){const t=[];for(const u of new Set(e)){const o=c(u).length===0?n.holders(u):null;if(o===null||o.length>1){const r=n.group();return U(r,i(r))}t.push(...U(o,new Map))}return t}l(w,"owedRelocations");function U(e,n){return e.flatMap(({uuid:t,name:u,diskName:o})=>{const r=n.get(t)??u;return o!==null&&o!==r?[{uuid:t,from:o,to:r}]:[]})}l(U,"displaced");export{f as derivedSlotName,w as owedRelocations,I as placementOwed};
1
+ var g=Object.defineProperty;var l=(e,n)=>g(e,"name",{value:n,configurable:!0});import{collisionBases as p,materializedSlotNames as c}from"./rules.js";function I(e,n,t,u){const o=l(r=>r!==null&&r.status==="active"&&r.parentUUID!==null,"active");if(n&&t&&n.parentUUID===t.parentUUID&&n.name===t.name&&n.type===t.type&&n.slotPosition===t.slotPosition&&o(n)===o(t))return[];const s=[];for(const r of[n,t]){if(!o(r)||s.some(a=>a.parentUUID===r.parentUUID&&a.name===r.name))continue;const{parentUUID:i,name:m}=r;(u({parentUUID:i,name:m}).some(a=>a!==e)||p(m).some(a=>u({parentUUID:i,name:a}).length>1))&&s.push({parentUUID:i,name:m})}return s}l(I,"placementOwed");function w(e,n){return n.holders(e.name).length<=1?e.name:c(n.group()).get(e.uuid)??e.name}l(w,"derivedSlotName");function v(e,n){const t=[];for(const u of new Set(e)){const o=p(u).length===0?n.holders(u):null;if(o===null||o.length>1){const s=n.group();return U(s,c(s))}t.push(...U(o,new Map))}return t}l(v,"owedRelocations");function U(e,n){return e.flatMap(({uuid:t,name:u,diskName:o})=>{const s=n.get(t)??u;return o!==null&&o!==s?[{uuid:t,from:o,to:s}]:[]})}l(U,"displaced");export{w as derivedSlotName,v as owedRelocations,I as placementOwed};
@@ -29,10 +29,14 @@ export declare function ancestorsOf(parentUuid: string | null, byUuid: EntityRea
29
29
  export declare function effectiveStatusOf(row: Pick<EntityRow, 'status' | 'parentUuid'>, byUuid: EntityReadPort['byUuid']): EntityStatus;
30
30
  export declare function membershipHash(activeChildren: readonly Pick<EntityRow, 'uuid' | 'name'>[], sha256Hex: Sha256Hex): string;
31
31
  export declare function membershipVersion(container: Pick<CanonicalVersionInput, 'type' | 'parentUUID' | 'name' | 'status'>, activeChildren: readonly Pick<EntityRow, 'uuid' | 'name'>[], sha256Hex: Sha256Hex): string;
32
- export declare function materializedSlotNames(activeChildren: readonly Pick<EntityRow, 'uuid' | 'name' | 'type'>[]): Map<string, string>;
32
+ type SlotClaim = Pick<EntityRow, 'uuid' | 'name' | 'type'> & {
33
+ readonly slotPosition?: number | null;
34
+ };
35
+ export declare function materializedSlotNames(activeChildren: readonly SlotClaim[]): Map<string, string>;
33
36
  export interface SlotProjection {
34
37
  readonly names: Map<string, string>;
35
38
  readonly dependencies: Map<string, ReadonlySet<string>>;
36
39
  }
37
- export declare function materializedSlotProjectionSteps(activeChildren: readonly Pick<EntityRow, 'uuid' | 'name' | 'type'>[]): Steps<SlotProjection>;
40
+ export declare function materializedSlotProjectionSteps(activeChildren: readonly SlotClaim[]): Steps<SlotProjection>;
38
41
  export declare function collisionBases(name: string): string[];
42
+ export {};
@@ -1 +1 @@
1
- var M=Object.defineProperty;var r=(t,e)=>M(t,"name",{value:e,configurable:!0});import{eachStep as g,finishSteps as N,ITEMS_PER_BOUNDARY as y,sortSteps as E}from"../steps.js";import{isGitHome as U}from"../git/state.js";const p=new Set(["file.text","file.binary"]);function C(t,e){return p.has(t)?((e??0)&73)===0?420:493:null}r(C,"portableFileMode");function F(t,e){return p.has(t)?e===420||e===493:e===null}r(F,"validPortableFileMode");const H=/^(?:0|-?[1-9][0-9]{0,21})$/;function J(t,e){return p.has(t)?e.toString():null}r(J,"portableMtime");function T(t,e,n=!1){return!p.has(t)||n?e===null:typeof e=="string"&&H.test(e)}r(T,"validPortableMtime");function _(t,e,n){return F(t,n)||p.has(t)&&n===null&&e===null}r(_,"validFileState");function R(t,e,n){return p.has(t)&&e!==null?typeof n=="number"&&Number.isSafeInteger(n)&&n>=0:n===null}r(R,"validPortableSize");function X(t,e,n){return t==="link"&&e!==null?typeof n=="string":n===null}r(X,"validLinkTarget");function q(t,e,n){return e===null&&n===null||t==="repo.git"&&U({entity:e,path:n})}r(q,"validGitHome");const z=r(t=>t.gitHomePath==null?null:{entity:t.gitHomeEntity,path:t.gitHomePath},"recordGitHome");function I(t,e){const n=e(t);if(!n)throw new Error(`no entity ${t}`);return n}r(I,"mustGet");function k({type:t,parentUUID:e=null,name:n,status:o,payloadVersion:i=null,fileMode:l=null,mtime:d=null},S){if(!_(t,i,l))throw new Error(`canonical ${t} state has an invalid portable file mode`);if(!T(t,d,l===null&&i===null))throw new Error(`canonical ${t} state has an invalid portable modified time`);return S(JSON.stringify([t,e,n,o,l===null?i:[i,l,d]]))}r(k,"canonicalVersion");function A(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!t.includes("/")&&!t.includes("\0")}r(A,"isName");function G(t,e){const n=[],o=new Set;let i=t;for(;i!==null;){if(o.has(i))throw new Error(`registry corrupt: parent cycle at ${i}`);o.add(i),n.push(i),i=I(i,e).parentUuid}return n}r(G,"ancestorsOf");function K(t,e){const n=[t.status,...G(t.parentUuid,e).map(o=>I(o,e).status)];return n.includes("deleted")?"deleted":n.includes("trashed")?"trashed":t.status}r(K,"effectiveStatusOf");const w=r((t,e)=>t<e?-1:t>e?1:0,"codeUnitOrder");function L(t,e){const n=[...t].sort((o,i)=>w(o.uuid,i.uuid)).map(o=>[o.uuid,o.name]);return e(JSON.stringify(n))}r(L,"membershipHash");function Q(t,e,n){return k({type:t.type,parentUUID:t.parentUUID??null,name:t.name,status:t.status,payloadVersion:L(e,n)},n)}r(Q,"membershipVersion");const D=new Set(["file.text","file.binary","link"]);function V(t){return N(O(t,!1)).names}r(V,"materializedSlotNames");function W(t){return O(t,!0)}r(W,"materializedSlotProjectionSteps");function*O(t,e){const n=new Map;yield*g(t,s=>{const x=n.get(s.name);x?x.push(s):n.set(s.name,[s])});const o=new Map,i=new Map,l=[];yield*g(n,s=>{s[1].length>1?l.push(s):e&&i.set(s[1][0].uuid,new Set([s[1][0].uuid]))});const d=new Map;let S=0;for(const[s,x]of yield*E(l,([h],[f])=>w(h,f))){const h=yield*E(x,(u,a)=>w(u.uuid,a.uuid)),f=e?new Set(x.map(u=>u.uuid)):null;f&&i.set(h[0].uuid,f);for(const u of h.slice(1)){const a=f?new Set(f):null;let m=1,c=P(s,u.type,m);for(;n.has(c)||d.has(c);){if(a){const b=d.get(c);if(b!==void 0)a.add(b);else for(const v of n.get(c))a.add(v.uuid)}m+=1,c=P(s,u.type,m),++S%y===0&&(yield)}d.set(c,u.uuid),o.set(u.uuid,c),a&&i.set(u.uuid,a),++S%y===0&&(yield)}}return{names:o,dependencies:i}}r(O,"projectMaterializedSlotsSteps");function P(t,e,n){const o=D.has(e)?t.lastIndexOf("."):0;return o>0?`${t.slice(0,o)} (${n})${t.slice(o)}`:`${t} (${n})`}r(P,"collisionCandidate");const $=/ \(([1-9][0-9]*)\)$/;function Z(t){const e=new Set,n=$.exec(t);n&&n.index>0&&e.add(t.slice(0,n.index));const o=t.lastIndexOf("."),i=o>0?$.exec(t.slice(0,o)):null;return i&&i.index>0&&e.add(t.slice(0,i.index)+t.slice(o)),[...e]}r(Z,"collisionBases");export{G as ancestorsOf,k as canonicalVersion,Z as collisionBases,K as effectiveStatusOf,A as isName,V as materializedSlotNames,W as materializedSlotProjectionSteps,L as membershipHash,Q as membershipVersion,I as mustGet,C as portableFileMode,J as portableMtime,z as recordGitHome,_ as validFileState,q as validGitHome,X as validLinkTarget,F as validPortableFileMode,T as validPortableMtime,R as validPortableSize};
1
+ var N=Object.defineProperty;var i=(t,e)=>N(t,"name",{value:e,configurable:!0});import{eachStep as y,finishSteps as U,ITEMS_PER_BOUNDARY as g,sortSteps as E}from"../steps.js";import{isGitHome as F}from"../git/state.js";const p=new Set(["file.text","file.binary"]);function J(t,e){return p.has(t)?((e??0)&73)===0?420:493:null}i(J,"portableFileMode");function H(t,e){return p.has(t)?e===420||e===493:e===null}i(H,"validPortableFileMode");const T=/^(?:0|-?[1-9][0-9]{0,21})$/;function R(t,e){return p.has(t)?e.toString():null}i(R,"portableMtime");function _(t,e,n=!1){return!p.has(t)||n?e===null:typeof e=="string"&&T.test(e)}i(_,"validPortableMtime");function k(t,e,n){return H(t,n)||p.has(t)&&n===null&&e===null}i(k,"validFileState");function X(t,e,n){return p.has(t)&&e!==null?typeof n=="number"&&Number.isSafeInteger(n)&&n>=0:n===null}i(X,"validPortableSize");function q(t,e,n){return t==="link"&&e!==null?typeof n=="string":n===null}i(q,"validLinkTarget");function z(t,e,n){return e===null&&n===null||t==="repo.git"&&F({entity:e,path:n})}i(z,"validGitHome");const A=i(t=>t.gitHomePath==null?null:{entity:t.gitHomeEntity,path:t.gitHomePath},"recordGitHome");function I(t,e){const n=e(t);if(!n)throw new Error(`no entity ${t}`);return n}i(I,"mustGet");function G({type:t,parentUUID:e=null,name:n,status:o,payloadVersion:r=null,fileMode:a=null,mtime:d=null},S){if(!k(t,r,a))throw new Error(`canonical ${t} state has an invalid portable file mode`);if(!_(t,d,a===null&&r===null))throw new Error(`canonical ${t} state has an invalid portable modified time`);return S(JSON.stringify([t,e,n,o,a===null?r:[r,a,d]]))}i(G,"canonicalVersion");function K(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!t.includes("/")&&!t.includes("\0")}i(K,"isName");function L(t,e){const n=[],o=new Set;let r=t;for(;r!==null;){if(o.has(r))throw new Error(`registry corrupt: parent cycle at ${r}`);o.add(r),n.push(r),r=I(r,e).parentUuid}return n}i(L,"ancestorsOf");function Q(t,e){const n=[t.status,...L(t.parentUuid,e).map(o=>I(o,e).status)];return n.includes("deleted")?"deleted":n.includes("trashed")?"trashed":t.status}i(Q,"effectiveStatusOf");const w=i((t,e)=>t<e?-1:t>e?1:0,"codeUnitOrder");function D(t,e){const n=[...t].sort((o,r)=>w(o.uuid,r.uuid)).map(o=>[o.uuid,o.name]);return e(JSON.stringify(n))}i(D,"membershipHash");function V(t,e,n){return G({type:t.type,parentUUID:t.parentUUID??null,name:t.name,status:t.status,payloadVersion:D(e,n)},n)}i(V,"membershipVersion");const Y=new Set(["file.text","file.binary","link"]),P=i(t=>t.slotPosition===null?1/0:t.slotPosition??0,"claimOrder");function W(t){return U(O(t,!1)).names}i(W,"materializedSlotNames");function Z(t){return O(t,!0)}i(Z,"materializedSlotProjectionSteps");function*O(t,e){const n=new Map;yield*y(t,s=>{const x=n.get(s.name);x?x.push(s):n.set(s.name,[s])});const o=new Map,r=new Map,a=[];yield*y(n,s=>{s[1].length>1?a.push(s):e&&r.set(s[1][0].uuid,new Set([s[1][0].uuid]))});const d=new Map;let S=0;for(const[s,x]of yield*E(a,([h],[f])=>w(h,f))){const h=yield*E(x,(l,u)=>P(l)-P(u)||w(l.uuid,u.uuid)),f=e?new Set(x.map(l=>l.uuid)):null;f&&r.set(h[0].uuid,f);for(const l of h.slice(1)){const u=f?new Set(f):null;let m=1,c=$(s,l.type,m);for(;n.has(c)||d.has(c);){if(u){const b=d.get(c);if(b!==void 0)u.add(b);else for(const M of n.get(c))u.add(M.uuid)}m+=1,c=$(s,l.type,m),++S%g===0&&(yield)}d.set(c,l.uuid),o.set(l.uuid,c),u&&r.set(l.uuid,u),++S%g===0&&(yield)}}return{names:o,dependencies:r}}i(O,"projectMaterializedSlotsSteps");function $(t,e,n){const o=Y.has(e)?t.lastIndexOf("."):0;return o>0?`${t.slice(0,o)} (${n})${t.slice(o)}`:`${t} (${n})`}i($,"collisionCandidate");const v=/ \(([1-9][0-9]*)\)$/;function tt(t){const e=new Set,n=v.exec(t);n&&n.index>0&&e.add(t.slice(0,n.index));const o=t.lastIndexOf("."),r=o>0?v.exec(t.slice(0,o)):null;return r&&r.index>0&&e.add(t.slice(0,r.index)+t.slice(o)),[...e]}i(tt,"collisionBases");export{L as ancestorsOf,G as canonicalVersion,tt as collisionBases,Q as effectiveStatusOf,K as isName,W as materializedSlotNames,Z as materializedSlotProjectionSteps,D as membershipHash,V as membershipVersion,I as mustGet,J as portableFileMode,R as portableMtime,A as recordGitHome,k as validFileState,z as validGitHome,q as validLinkTarget,H as validPortableFileMode,_ as validPortableMtime,X as validPortableSize};
@@ -24,6 +24,7 @@ export interface AcceptedFilesHost {
24
24
  }): Promise<FilesBody>;
25
25
  }
26
26
  export interface StatedChange {
27
+ readonly deliverySequence?: number | undefined;
27
28
  readonly facets: readonly ChangeFacet[];
28
29
  readonly result: CloudEntityRecord;
29
30
  readonly joins?: string | undefined;
@@ -1 +1 @@
1
- var U=Object.defineProperty;var u=(n,a)=>U(n,"name",{value:a,configurable:!0});import{AcceptedView as E}from"../entities/accepted-view.js";import{utf8Encode as T}from"../entities/bytes.js";import{sameRecord as I}from"../entities/cloud.js";import{unpack as R}from"../entities/package-pages.js";import{materializedSlotNames as S}from"../entities/rules.js";import{CheckoutView as _}from"../git/checkout-view.js";import{findUserGroundRoot as x}from"../registration/user-ground.js";import{artifactForRecord as z}from"../transfer/artifacts.js";import{FilesRequestError as g,canonicalUserEmail as D}from"./browse-types.js";import{filesMediaType as C}from"./media-type.js";async function B(n,a,i){const f=u(r=>r.replay.kind==="package"?r.replay.pages??[]:[],"pagesOf"),c=new Map;for(const r of n)for(const l of f(r))c.set(l.sha256,l);const p=[...c.values()],w=await a(p);if(w.length!==p.length)throw new Error("package pages were read short");const m=new Map(p.map((r,l)=>[r.sha256,w[l]]));return n.flatMap(r=>r.replay.kind==="package"?R(r.result,f(r),l=>m.get(l.sha256),i).map(l=>({facets:["create"],result:l})):[{facets:r.facets,result:r.result,...r.joins===void 0?{}:{joins:r.joins}}])}u(B,"statedResults");function F(n,a,i){return i(`amalgm-files-accepted:${n}:${a}`)}u(F,"acceptedFilesChecksum");async function b(n,a){const i=new E(n.head,a);await i.advance(n.tail);const f=new Set(n.head.rootIds());for(const{result:c}of n.tail)c.parentUUID===null&&f.add(c.uuid);return{view:i,rows:await i.rows([...f])}}u(b,"acceptedRoots");async function J(n,a){const{view:i,rows:f}=await b(n,a),c=[];for(const p of f.values())p.parentUUID===null&&c.push(...await i.subtree(p.uuid));return c}u(J,"acceptedFilesRecords");function K(n,a,i){const f=D(n);let c=null,p=new Set;const w=[],m=new Map;let r;const l=u(async t=>{if(t==null)return null;const e=await r.presence(t);if(e===!1)return null;if(e===void 0)throw new g(503,"checkout_pending","The checkout index is unavailable.");return t},"shown"),k=u(async t=>(await Promise.all(t.map(l))).filter(e=>e!==null),"visibleChildren"),v=u(t=>{if(c===null||c.checksum!==t.checksum)throw new Error("cloud files asked about a head this port did not open");return c.view},"viewOf");return{async openActiveHead(){if(c!==null)throw new Error("a cloud files port opens one accepted state");const t=await a.open();if(!Number.isSafeInteger(t.through)||t.through<0)throw new Error("accepted files state has an invalid delivery position");const{view:e,rows:o}=await b(t,i),d=x(o.values(),f);if(d===null)throw new g(404,"ground_not_found","this account has no cloud files yet");const h=F(t.headChecksum,t.through,i);return c={checksum:h,view:e},r=new _({row:u(s=>e.row(s),"row"),children:u(s=>e.children(s),"children"),index:u(s=>s.transportVersion===null?null:a.checkout(s.transportVersion),"index")}),p=new Set([...o.values()].filter(s=>s.parentUUID===null).map(({uuid:s})=>s)),w.push(d),{checksum:h,version:t.through,root:o.get(d)}},async list({head:t,parentId:e}){const o=v(t),[d,h]=await Promise.all([o.row(e),o.children(e)]);return{directory:await l(d),entries:await k(h)}},async placementName({head:t,entity:e}){if(e.parentUUID===null)return e.name;const o=await v(t).children(e.parentUUID);return o.some(d=>d.status==="active"&&d.uuid!==e.uuid&&d.name===e.name)?S(await k(o)).get(e.uuid)??e.name:e.name},async entry({head:t,entityId:e}){const o=await v(t).row(e);return l(o)},async checkoutSize({head:t,entity:e}){return v(t),(await r.file(e))?.size??null},async read({head:t,entity:e}){const o=await l(await v(t).row(e.uuid));if(!o)throw new g(404,"entity_not_found","The file is absent at this revision.");if(!I(o,e))throw new g(409,"version_changed","The requested file version differs from this revision.");return M(o,a)},async referenceTo({head:t,targetId:e}){const o=v(t);for(;!m.has(e)&&w.length>0;){const d=w.shift(),h=new Set([d]);for(const s of await o.subtree(d)){if(s.status!=="active"||!h.has(s.parentUUID))continue;h.add(s.uuid);const y=s.type==="reference"?s.payloadVersion?.toLowerCase()??null:null;y===null||!p.has(y)||y===t.root.uuid||m.has(y)||(m.set(y,s),w.push(y))}}return m.get(e)??null}}}u(K,"acceptedFilesPort");async function M(n,a){if(n.type==="link"){const f=T(n.linkTarget??"");return{body:f,mediaType:"text/plain; charset=utf-8",bytes:f.byteLength,version:n.version}}const i=z(n);if(i===null||n.size===null)throw new g(409,"content_pending","this file's bytes are not in the cloud as a file");return{body:await a.content({contentHash:i.contentHash,bytes:n.size}),mediaType:C(n.name),bytes:n.size,version:n.version}}u(M,"readEntity");export{F as acceptedFilesChecksum,K as acceptedFilesPort,J as acceptedFilesRecords,B as statedResults};
1
+ var S=Object.defineProperty;var c=(n,a)=>S(n,"name",{value:a,configurable:!0});import{AcceptedView as E}from"../entities/accepted-view.js";import{utf8Encode as q}from"../entities/bytes.js";import{sameRecord as T}from"../entities/cloud.js";import{unpack as I}from"../entities/package-pages.js";import{materializedSlotNames as R}from"../entities/rules.js";import{CheckoutView as _}from"../git/checkout-view.js";import{findUserGroundRoot as x}from"../registration/user-ground.js";import{artifactForRecord as z}from"../transfer/artifacts.js";import{FilesRequestError as k,canonicalUserEmail as D}from"./browse-types.js";import{filesMediaType as C}from"./media-type.js";async function J(n,a,i){const d=c(r=>r.replay.kind==="package"?r.replay.pages??[]:[],"pagesOf"),u=new Map;for(const r of n)for(const l of d(r))u.set(l.sha256,l);const p=[...u.values()],h=await a(p);if(h.length!==p.length)throw new Error("package pages were read short");const m=new Map(p.map((r,l)=>[r.sha256,h[l]]));return n.flatMap(r=>r.replay.kind==="package"?I(r.result,d(r),l=>m.get(l.sha256),i).map(l=>({facets:["create"],result:l,...r.deliverySequence===void 0?{}:{deliverySequence:r.deliverySequence}})):[{facets:r.facets,result:r.result,...r.deliverySequence===void 0?{}:{deliverySequence:r.deliverySequence},...r.joins===void 0?{}:{joins:r.joins}}])}c(J,"statedResults");function F(n,a,i){return i(`amalgm-files-accepted:${n}:${a}`)}c(F,"acceptedFilesChecksum");async function g(n,a){const i=new E(n.head,a);await i.advance(n.tail);const d=new Set(n.head.rootIds());for(const{result:u}of n.tail)u.parentUUID===null&&d.add(u.uuid);return{view:i,rows:await i.rows([...d])}}c(g,"acceptedRoots");async function K(n,a){const{view:i,rows:d}=await g(n,a),u=[];for(const p of d.values())p.parentUUID===null&&u.push(...await i.subtree(p.uuid));return u}c(K,"acceptedFilesRecords");function Q(n,a,i){const d=D(n);let u=null,p=new Set;const h=[],m=new Map;let r;const l=c(async t=>{if(t==null)return null;const e=await r.presence(t);if(e===!1)return null;if(e===void 0)throw new k(503,"checkout_pending","The checkout index is unavailable.");return t},"shown"),b=c(t=>R(t.filter(e=>e.status==="active")),"slotNames"),U=c(async t=>(await Promise.all(t.map(l))).filter(e=>e!==null),"visibleChildren"),v=c(t=>{if(u===null||u.checksum!==t.checksum)throw new Error("cloud files asked about a head this port did not open");return u.view},"viewOf");return{async openActiveHead(){if(u!==null)throw new Error("a cloud files port opens one accepted state");const t=await a.open();if(!Number.isSafeInteger(t.through)||t.through<0)throw new Error("accepted files state has an invalid delivery position");const{view:e,rows:o}=await g(t,i),f=x(o.values(),d);if(f===null)throw new k(404,"ground_not_found","this account has no cloud files yet");const w=F(t.headChecksum,t.through,i);return u={checksum:w,view:e},r=new _({row:c(s=>e.row(s),"row"),children:c(s=>e.children(s),"children"),index:c(s=>s.transportVersion===null?null:a.checkout(s.transportVersion),"index")}),p=new Set([...o.values()].filter(s=>s.parentUUID===null).map(({uuid:s})=>s)),h.push(f),{checksum:w,version:t.through,root:o.get(f)}},async list({head:t,parentId:e}){const o=v(t),[f,w]=await Promise.all([o.row(e),o.children(e)]);return{directory:await l(f),entries:await U(w),names:Object.fromEntries(b(w))}},async placementName({head:t,entity:e}){if(e.parentUUID===null)return e.name;const o=await v(t).children(e.parentUUID);return o.some(f=>f.status==="active"&&f.uuid!==e.uuid&&f.name===e.name)?b(o).get(e.uuid)??e.name:e.name},async entry({head:t,entityId:e}){const o=await v(t).row(e);return l(o)},async checkoutSize({head:t,entity:e}){return v(t),(await r.file(e))?.size??null},async read({head:t,entity:e}){const o=await l(await v(t).row(e.uuid));if(!o)throw new k(404,"entity_not_found","The file is absent at this revision.");if(!T(o,e))throw new k(409,"version_changed","The requested file version differs from this revision.");return M(o,a)},async referenceTo({head:t,targetId:e}){const o=v(t);for(;!m.has(e)&&h.length>0;){const f=h.shift(),w=new Set([f]);for(const s of await o.subtree(f)){if(s.status!=="active"||!w.has(s.parentUUID))continue;w.add(s.uuid);const y=s.type==="reference"?s.payloadVersion?.toLowerCase()??null:null;y===null||!p.has(y)||y===t.root.uuid||m.has(y)||(m.set(y,s),h.push(y))}}return m.get(e)??null}}}c(Q,"acceptedFilesPort");async function M(n,a){if(n.type==="link"){const d=q(n.linkTarget??"");return{body:d,mediaType:"text/plain; charset=utf-8",bytes:d.byteLength,version:n.version}}const i=z(n);if(i===null||n.size===null)throw new k(409,"content_pending","this file's bytes are not in the cloud as a file");return{body:await a.content({contentHash:i.contentHash,bytes:n.size}),mediaType:C(n.name),bytes:n.size,version:n.version}}c(M,"readEntity");export{F as acceptedFilesChecksum,Q as acceptedFilesPort,K as acceptedFilesRecords,J as statedResults};
@@ -1 +1 @@
1
- var E=Object.defineProperty;var s=(i,e)=>E(i,"name",{value:e,configurable:!0});import{CONTAINERS as y,UUID_PATTERN as m,assertRecord as I,isName as U,materializedSlotNames as N,sameRecord as g}from"../entities/index.js";import{FilesRequestError as d,assertFilesContent as _,canonicalUserEmail as D}from"./browse-types.js";import{checkoutFileOwner as R}from"../git/checkout.js";import{isUserGroundRoot as b}from"../registration/user-ground.js";const z=/^[0-9a-f]{64}$/,S=new Set(["file.text","file.binary","link"]);class L{static{s(this,"CloudFiles")}port;userEmail;constructor(e,t){this.port=t,this.userEmail=D(e)}async open(){return new k(C(await this.port.openActiveHead(),this.userEmail),this.port)}}class k{static{s(this,"CloudFilesView")}head;port;constructor(e,t){this.head=e,this.port=t}async list(e){const t=e===void 0||!e.trim()?this.head.root.uuid:f(e,"parent entity id"),r=t===this.head.root.uuid?h(this.head.root,this.head.root.parentUUID):await this.resolveNode(t);if(!y.has(r.entity.type))throw new d(400,"not_a_directory","entity is not a directory");const n=await this.port.list({head:this.head,parentId:r.entity.uuid});if(!n||!Array.isArray(n.entries))throw new Error("cloud files returned an invalid directory");const c=u(n.directory,"cloud directory");if(c.uuid!==r.entity.uuid||!y.has(c.type))throw new Error("cloud files returned the wrong directory");if(!g(c,r.entity))throw new Error("cloud files directory does not match the opened head");const l=n.entries.map(a=>u(a,"cloud directory entry")),w=new Set;for(const a of l){if(a.parentUUID!==c.uuid)throw new Error("cloud directory entry has the wrong parent");if(w.has(a.uuid))throw new Error("cloud directory has duplicate entries");w.add(a.uuid)}const p=N(l),v=await Promise.all(l.map(a=>this.node(a,r.entryId,p.get(a.uuid)??a.name)));return{directory:r,entries:[...v].sort($)}}async entry(e){const t=f(e,"entity id");return(await this.resolveNode(t,!1)).entity}async place(e){const t=f(e,"entity id"),r=[];let o=t===this.head.root.uuid?h(this.head.root,this.head.root.parentUUID):await this.resolveNode(t);for(;o.entity.uuid!==this.head.root.uuid;){if(o.parentEntityId===null&&(o=await this.placedRoot(o.entity)),r.some(n=>n.entity.uuid===o.entity.uuid))throw new d(404,"entity_not_found","file is not in the active cloud head");r.unshift(o),o=o.parentEntityId===this.head.root.uuid?h(this.head.root,this.head.root.parentUUID):await this.resolveNode(o.parentEntityId)}return r}async placedRoot(e){const t=await this.port.referenceTo({head:this.head,targetId:e.uuid});if(t==null)throw new d(404,"entity_not_found","file is not in the active cloud head");const r=u(t,"cloud root reference");if(r.type!=="reference"||r.payloadVersion?.toLowerCase()!==e.uuid)throw new Error("cloud files returned the wrong reference");return this.node(r,r.parentUUID)}async resolveNode(e,t=!0){const r=await this.port.entry({head:this.head,entityId:e});if(r==null)throw new d(404,"entity_not_found","file does not exist in the active cloud head");const o=u(r,"cloud file");if(o.uuid!==e)throw new Error("cloud files returned the wrong entity");return this.node(o,o.parentUUID,t?void 0:o.name)}async node(e,t,r){const o=r??(t===null?e.name:await this.port.placementName({head:this.head,entity:e}));if(!U(o))throw new Error("cloud files returned an invalid placement name");const n=e.type==="reference"?await this.referenceNode(e,t):await this.direct(e,t);return o===n.name?n:{...n,name:o}}async direct(e,t){const r=h(e,t);if(R(e)!=="git")return r;const o=await this.port.checkoutSize({head:this.head,entity:e});if(o!==null&&(!Number.isSafeInteger(o)||o<0))throw new Error("invalid checkout file size");return{...r,size:o}}async referenceNode(e,t){if(typeof e.payloadVersion!="string")throw new Error(`cloud reference ${e.uuid} has no target`);const r=e.payloadVersion.toLowerCase();if(!m.test(r))throw new Error(`cloud reference ${e.uuid} has an invalid target UUID`);const o=await this.port.entry({head:this.head,entityId:r});if(o==null)throw new Error(`cloud reference ${e.uuid} has no active target`);const n=u(o,"cloud reference target");if(n.uuid!==r||n.type==="reference")throw new Error(`cloud reference ${e.uuid} has an invalid target`);return{entryId:e.uuid,size:(await this.direct(n,t)).size,entity:n,parentEntityId:t,name:e.name,referenceId:e.uuid}}async read(e){A(e);const t=_(await this.port.read({head:this.head,entity:e}),"cloud files port");if(t.version!==e.version)throw new Error("cloud content does not match the opened head");return t}}function A(i){if(!S.has(i.type))throw new d(400,"not_readable","entity does not have directly readable file content")}s(A,"assertReadable");function C(i,e){const t=i;if(!t||typeof t.checksum!="string"||!z.test(t.checksum)||!Number.isSafeInteger(t.version)||Number(t.version)<0)throw new Error("cloud files returned an invalid active head");const r=u(t.root,"cloud files root");if(!b(r,e))throw new Error("cloud files head does not name the authenticated user root");return{checksum:t.checksum,version:Number(t.version),root:r}}s(C,"assertHead");function u(i,e){const t=I(i);if(t.status!=="active")throw new Error(`${e} is not active`);return t}s(u,"activeRecord");function f(i,e){const t=i.trim().toLowerCase();if(!m.test(t))throw new d(400,"invalid_request",`${e} must be a UUID`);return t}s(f,"entityId");function h(i,e){return{entryId:i.uuid,size:i.size,entity:i,parentEntityId:e,name:i.name,referenceId:null}}s(h,"directNode");function $(i,e){return i.name!==e.name?i.name<e.name?-1:1:i.entryId<e.entryId?-1:i.entryId>e.entryId?1:0}s($,"compareEntries");export{L as CloudFiles,k as CloudFilesView,A as assertReadable};
1
+ var E=Object.defineProperty;var s=(o,e)=>E(o,"name",{value:e,configurable:!0});import{CONTAINERS as m,UUID_PATTERN as p,assertRecord as I,isName as U,sameRecord as N}from"../entities/index.js";import{FilesRequestError as d,assertFilesContent as g,canonicalUserEmail as b}from"./browse-types.js";import{checkoutFileOwner as _}from"../git/checkout.js";import{isUserGroundRoot as D}from"../registration/user-ground.js";const R=/^[0-9a-f]{64}$/,k=new Set(["file.text","file.binary","link"]);class q{static{s(this,"CloudFiles")}port;userEmail;constructor(e,t){this.port=t,this.userEmail=b(e)}async open(){return new z(S(await this.port.openActiveHead(),this.userEmail),this.port)}}class z{static{s(this,"CloudFilesView")}head;port;constructor(e,t){this.head=e,this.port=t}async list(e){const t=e===void 0||!e.trim()?this.head.root.uuid:l(e,"parent entity id"),r=t===this.head.root.uuid?h(this.head.root,this.head.root.parentUUID):await this.resolveNode(t);if(!m.has(r.entity.type))throw new d(400,"not_a_directory","entity is not a directory");const i=await this.port.list({head:this.head,parentId:r.entity.uuid});if(!i||!Array.isArray(i.entries))throw new Error("cloud files returned an invalid directory");if(typeof i.names!="object"||i.names===null||Object.values(i.names).some(a=>typeof a!="string"))throw new Error("cloud files returned invalid names");const c=u(i.directory,"cloud directory");if(c.uuid!==r.entity.uuid||!m.has(c.type))throw new Error("cloud files returned the wrong directory");if(!N(c,r.entity))throw new Error("cloud files directory does not match the opened head");const f=i.entries.map(a=>u(a,"cloud directory entry")),w=new Set;for(const a of f){if(a.parentUUID!==c.uuid)throw new Error("cloud directory entry has the wrong parent");if(w.has(a.uuid))throw new Error("cloud directory has duplicate entries");w.add(a.uuid)}const y=i.names,v=await Promise.all(f.map(a=>this.node(a,r.entryId,Object.hasOwn(y,a.uuid)?y[a.uuid]:a.name)));return{directory:r,entries:[...v].sort(C)}}async entry(e){const t=l(e,"entity id");return(await this.resolveNode(t,!1)).entity}async place(e){const t=l(e,"entity id"),r=[];let n=t===this.head.root.uuid?h(this.head.root,this.head.root.parentUUID):await this.resolveNode(t);for(;n.entity.uuid!==this.head.root.uuid;){if(n.parentEntityId===null&&(n=await this.placedRoot(n.entity)),r.some(i=>i.entity.uuid===n.entity.uuid))throw new d(404,"entity_not_found","file is not in the active cloud head");r.unshift(n),n=n.parentEntityId===this.head.root.uuid?h(this.head.root,this.head.root.parentUUID):await this.resolveNode(n.parentEntityId)}return r}async placedRoot(e){const t=await this.port.referenceTo({head:this.head,targetId:e.uuid});if(t==null)throw new d(404,"entity_not_found","file is not in the active cloud head");const r=u(t,"cloud root reference");if(r.type!=="reference"||r.payloadVersion?.toLowerCase()!==e.uuid)throw new Error("cloud files returned the wrong reference");return this.node(r,r.parentUUID)}async resolveNode(e,t=!0){const r=await this.port.entry({head:this.head,entityId:e});if(r==null)throw new d(404,"entity_not_found","file does not exist in the active cloud head");const n=u(r,"cloud file");if(n.uuid!==e)throw new Error("cloud files returned the wrong entity");return this.node(n,n.parentUUID,t?void 0:n.name)}async node(e,t,r){const n=r??(t===null?e.name:await this.port.placementName({head:this.head,entity:e}));if(!U(n))throw new Error("cloud files returned an invalid placement name");const i=e.type==="reference"?await this.referenceNode(e,t):await this.direct(e,t);return n===i.name?i:{...i,name:n}}async direct(e,t){const r=h(e,t);if(_(e)!=="git")return r;const n=await this.port.checkoutSize({head:this.head,entity:e});if(n!==null&&(!Number.isSafeInteger(n)||n<0))throw new Error("invalid checkout file size");return{...r,size:n}}async referenceNode(e,t){if(typeof e.payloadVersion!="string")throw new Error(`cloud reference ${e.uuid} has no target`);const r=e.payloadVersion.toLowerCase();if(!p.test(r))throw new Error(`cloud reference ${e.uuid} has an invalid target UUID`);const n=await this.port.entry({head:this.head,entityId:r});if(n==null)throw new Error(`cloud reference ${e.uuid} has no active target`);const i=u(n,"cloud reference target");if(i.uuid!==r||i.type==="reference")throw new Error(`cloud reference ${e.uuid} has an invalid target`);return{entryId:e.uuid,size:(await this.direct(i,t)).size,entity:i,parentEntityId:t,name:e.name,referenceId:e.uuid}}async read(e){A(e);const t=g(await this.port.read({head:this.head,entity:e}),"cloud files port");if(t.version!==e.version)throw new Error("cloud content does not match the opened head");return t}}function A(o){if(!k.has(o.type))throw new d(400,"not_readable","entity does not have directly readable file content")}s(A,"assertReadable");function S(o,e){const t=o;if(!t||typeof t.checksum!="string"||!R.test(t.checksum)||!Number.isSafeInteger(t.version)||Number(t.version)<0)throw new Error("cloud files returned an invalid active head");const r=u(t.root,"cloud files root");if(!D(r,e))throw new Error("cloud files head does not name the authenticated user root");return{checksum:t.checksum,version:Number(t.version),root:r}}s(S,"assertHead");function u(o,e){const t=I(o);if(t.status!=="active")throw new Error(`${e} is not active`);return t}s(u,"activeRecord");function l(o,e){const t=o.trim().toLowerCase();if(!p.test(t))throw new d(400,"invalid_request",`${e} must be a UUID`);return t}s(l,"entityId");function h(o,e){return{entryId:o.uuid,size:o.size,entity:o,parentEntityId:e,name:o.name,referenceId:null}}s(h,"directNode");function C(o,e){return o.name!==e.name?o.name<e.name?-1:1:o.entryId<e.entryId?-1:o.entryId>e.entryId?1:0}s(C,"compareEntries");export{q as CloudFiles,z as CloudFilesView,A as assertReadable};