@hyperscale0/cli 1.0.0-beta.6 → 1.0.0-beta.7

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 (2) hide show
  1. package/hyperscale.js +19 -19
  2. package/package.json +1 -1
package/hyperscale.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- var De=["advance","captured_payment","conditional_disbursement","credit_facility","deposit","funding_round","held_payment","instant_transfer","metered","pooled_split","premium_forward","recurring_collection","rotating_pool","scheduled","settlement_batch","swap","weighted_distribution"],$e={advance:{eventCap:2,keys:["against","amount","count","every","fee","first_due","funder","to"],referenceableExits:[],required:["funder","to","amount"]},captured_payment:{eventCap:4,keys:["amount","capture_mode","correction","correction_mode","external_reversal","fees","negative_position","payee","payer","reserve_until","timeout"],referenceableExits:[],required:["payer","payee","amount","capture_mode","reserve_until","correction","external_reversal","correction_mode","negative_position","timeout"]},conditional_disbursement:{eventCap:1,keys:["amount","cap","decision","destination","recovery_policy","reopen_policy","source"],referenceableExits:[],required:["source","destination","cap","amount","decision","reopen_policy","recovery_policy"]},credit_facility:{eventCap:1,keys:["availability_policy","borrower","close_policy","draw_destination","expires_at","expiry_policy","lender","limit","obligation"],referenceableExits:[],required:["lender","borrower","draw_destination","limit","expires_at","obligation","availability_policy","expiry_policy","close_policy"]},deposit:{eventCap:1,keys:["amount","claim","holder","payer","return"],referenceableExits:[],required:["payer","holder","amount","claim","return"]},funding_round:{eventCap:4,keys:["beneficiary","cancel_policy","close_by","close_policy","commitment","contributor","fail_policy","max_contributors","overfund_policy","target"],referenceableExits:[],required:["contributor","beneficiary","target","commitment","max_contributors","close_by","close_policy","overfund_policy","cancel_policy","fail_policy"]},held_payment:{eventCap:7,keys:["amount","fees","on_cancel","payer","payee","release"],referenceableExits:["release"],required:["payer","payee","amount","release"]},instant_transfer:{eventCap:3,keys:["amount","fees","payer","payee"],referenceableExits:[],required:["payer","payee","amount"]},metered:{eventCap:14,keys:["close_by","payer","payee","rates"],maxRates:14,referenceableExits:[],required:["payer","payee","rates","close_by"]},pooled_split:{eventCap:14,keys:["amount","payer","payout_due","split"],maxRecipients:7,referenceableExits:[],required:["payer","amount","split","payout_due"]},premium_forward:{eventCap:6,keys:["amount","bind","carrier","commission","endorsement","endorsement_policy","lapse_policy","on_cancel","payer","policy_ref","renewal_due","renewal_policy"],referenceableExits:[],required:["payer","carrier","amount","bind"]},recurring_collection:{eventCap:0,keys:["attempt_policy","failure_policy","mandate","obligation","period_idempotency","retry_policy"],referenceableExits:[],required:["obligation","mandate","attempt_policy","period_idempotency","retry_policy","failure_policy"]},rotating_pool:{eventCap:3,keys:["contribution","count","default_policy","every","exit_policy","first_due","guarantee_policy","guarantor","members","payout_order"],referenceableExits:[],required:["members","contribution","count","every","first_due","payout_order","default_policy","guarantee_policy","exit_policy"]},scheduled:{eventCap:3,keys:["advance_to","amount","count","debtor","delinquency_policy","every","first_due","month_end","mode","partial_payment","period_liability","payer","payee","refund_policy","repayment_matching","reschedule_policy","termination_drain","timeout","until"],referenceableExits:["obligation"],required:["payer","payee","amount","every","first_due"]},settlement_batch:{eventCap:1,keys:["cadence","close_trigger","external_reversal_offsets","fee_entries","negative_position","payout_destination","payout_acknowledgement","payout_beneficiary_ref","settlement_account","source_capture_refs"],referenceableExits:[],required:["settlement_account","source_capture_refs","fee_entries","external_reversal_offsets","close_trigger","payout_destination","negative_position","payout_acknowledgement","payout_beneficiary_ref"]},swap:{eventCap:10,keys:["amounts","between","dispute","fees","release"],referenceableExits:[],required:["between","amounts","release"]},weighted_distribution:{eventCap:1,keys:["amount","correction_policy","max_recipients","recipient","record_at","rounding_policy","snapshot","source","weight","withholding_policy"],referenceableExits:[],required:["source","recipient","amount","weight","max_recipients","record_at","snapshot","rounding_policy","withholding_policy","correction_policy"]}};var wn=["business","person"],vn=["access","claim","good","service","ticket"];var tt=["count","every","first_due"],Ze=/^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/,_e=/^[a-z][A-Za-z0-9]*$/,rt=/^[A-Z]{3}$/,Ne=1e4;function ot(e){let t=[],n=(i,p)=>{t.push({message:p,severity:"error",span:i})},r=(i,p)=>{t.push({message:p,severity:"warning",span:i})},o=[],a=e.decls.filter(i=>i.kind==="program"),c=a[0];c||n({end:0,start:0},'the file needs a program header naming the company, like: program used_car_escrow "Used-car escrow"');for(let i of a.slice(1))n(i.span,"a file declares exactly one program");c&&!Ze.test(c.name.name)&&n(c.name.span,`the program name must be snake_case, like used_car_escrow; "${c.name.name}" is not`);let s=new Map;for(let i of e.decls)if(i.kind==="import"){if(i.from.value!=="settlement"){n(i.from.span,`"${i.from.value}" is not an importable module; the settlement algebra lives in "settlement"`);continue}for(let p of i.names){if(!De.includes(p.name)){n(p.span,`"settlement" has no archetype named ${p.name}; it offers ${De.join(", ")}`);continue}s.has(p.name)&&r(p.span,`${p.name} is imported more than once`),s.set(p.name,p.span)}}let l=new Map,u=(i,p)=>{if(i.name==="platform"||i.name==="escrow")return n(i.span,`the name ${i.name} is reserved: the platform and each settlement's escrow are always present without being declared`),!1;let d=l.get(i.name);return d?(n(i.span,`the name ${i.name} is already taken by a ${d.kind}; every party, asset, settlement, and port needs its own name`),!1):Ze.test(i.name)?(l.set(i.name,{kind:p,span:i.span}),!0):(n(i.span,`${p} names are snake_case; "${i.name}" is not`),!1)},f=new Map,v=new Map;for(let i of e.decls){if(i.kind==="party"){if(!u(i.name,"party"))continue;if(!wn.includes(i.partyKind.name)){n(i.partyKind.span,`a party is a ${wn.join(" or a ")}; "${i.partyKind.name}" is neither`);continue}i.attrs&&n(i.attrs.span,`party ${i.name.name} takes no attribute block yet`),f.set(i.name.name,{kind:i.partyKind.name,name:i.name.name,origin:i.span})}if(i.kind==="asset"){if(!u(i.name,"asset"))continue;if(!vn.includes(i.assetKind.name)){n(i.assetKind.span,`an asset is one of ${vn.join(", ")}; "${i.assetKind.name}" is none of those`);continue}let p="on_platform";for(let d of i.attrs?.entries??[]){if(d.key.name!=="title_transfer"){n(d.key.span,`asset ${i.name.name} does not understand "${d.key.name}"; the only attribute is title_transfer`);continue}let b=d.value;b.kind==="ident"&&(b.name==="off_platform"||b.name==="on_platform")?p=b.name:n(b.span,"title_transfer is either on_platform or off_platform")}v.set(i.name.name,{kind:i.assetKind.name,name:i.name.name,origin:i.span,titleTransfer:p})}}let x=e.decls.filter(i=>i.kind==="port"),k=e.decls.filter(i=>i.kind==="settlement");for(let i of k)u(i.name,"settlement");let T=new Set;for(let i of x)u(i.name,"port")&&T.add(i.name.name);let R=(i,p,d)=>{let b=new Map;for(let A of i.entries){if(!p.includes(A.key.name)){n(A.key.span,`${d} does not understand "${A.key.name}"; it takes ${p.join(", ")}`);continue}if(b.has(A.key.name)){n(A.key.span,`${d} sets ${A.key.name} twice`);continue}b.set(A.key.name,A)}return b},C=(i,p)=>{i.qualifiers.length>0&&n(i.span,`${i.key.name} on ${p} takes no ( ... ) qualifier`)},Q=new Set,B=(i,p)=>{if(i.kind==="ident"&&f.has(i.name))return Q.add(i.name),i.name;n(i.span,i.kind==="ident"?`${p} must name a declared party; there is no party named ${i.name}`:`${p} must name a declared party`)},W=new Set,H=[],ue=new Map,X=new Set(["currency","feeAmount","repayableAmount","serviceFeeAmount","clawbackAt","carvedFeeAmount","netOfCarvedFeeAmount","sideAServiceFeeAmount","sideBServiceFeeAmount"]),$=[/^piece\d+Amount$/,/^installment\d+Amount$/,/^repayment\d+Amount$/,/^carve(?:Hold|Recourse\d+)Id$/,/ShareAmount$/,/AccountId$/],D=(i,p,d)=>X.has(i)||$.some(b=>b.test(i))?(n(p,`${d} names a field ${i}, but the compiler reserves that name for a generated field; pick another name`),!0):!1,K=(i,p)=>{if(!i)return;C(i,p);let d=i.value;if(d.kind==="binding"&&d.type.kind==="call"&&d.type.callee.name==="money"&&(d.type.args.length===1||d.type.args.length===2)&&d.type.args[0]?.kind==="ident"&&(d.type.args.length===1||d.type.args[1]?.kind==="number")){let b=d.type.args[0].name,A=d.type.args.length===2&&d.type.args[1]?.kind==="number"?d.type.args[1].raw:void 0,m=A?Number(A):void 0;if(!_e.test(d.name.name))n(d.name.span,`the ${i.key.name} field is a camelCase name like price; "${d.name.name}" is not`);else if(!rt.test(b))n(d.type.args[0].span,`"${b}" is not a currency code; use three capital letters like SAR`);else if(A!==void 0&&(!/^[1-9][0-9]{0,17}$/.test(A)||!Number.isSafeInteger(m)))n(d.type.args[1].span,`${p} fixes ${i.key.name} to a positive safe integer in minor units`);else if(!D(d.name.name,d.name.span,p))return{currency:b,...m!==void 0?{fixedAmount:m}:{},name:d.name.name,origin:d.span};return}n(d.span,`${p} declares ${i.key.name} as a typed field, like: ${i.key.name}: price: money(SAR)`)},re=(i,p,d,b=!1)=>{if(!i)return;C(i,p);let A=i.value;if(A.kind!=="port_ref"){n(A.span,`${p} needs a ${d} decision, like: ${i.key.name}: port ${i.key.name}_decided`);return}if(A.within){n(A.within.span,`${i.key.name} on ${p} has no time window; only dispute accepts "within <duration>"`);return}if(A.deadline&&!b){n(A.deadline.span,`${i.key.name} on ${p} has no date default; only a held payment's release falls back to a date`);return}if(!T.has(A.name.name)){n(A.name.span,`${p} decides ${d} through port ${A.name.name}, but no port with that name is declared`);return}let m;if(A.deadline){if(!_e.test(A.deadline.name)){n(A.deadline.span,`at( ... ) names a camelCase date field, like at(releaseDueAt); "${A.deadline.name}" is not`);return}if(D(A.deadline.name,A.deadline.span,p))return;m=A.deadline.name}return W.add(A.name.name),{...m?{deadlineField:m}:{},origin:A.span,port:A.name.name}},ee=(i,p,d="dispute")=>{if(!i)return;C(i,p);let b=i.value;if(b.kind!=="port_ref"){n(b.span,`${p} needs one ${d} decision through a fixed windowed port`);return}if(!T.has(b.name.name)){n(b.name.span,`${p} routes ${d} through port ${b.name.name}, but no port with that name is declared`);return}if(!b.within){n(b.span,`${p} ${d} needs a fixed window, like: ${i.key.name}: port ${b.name.name} within P14D`);return}let A=b.within.name,m=/^P([1-9]\d{0,3})([DW])$/.exec(A);if(!m){n(b.within.span,`${d} on ${p} uses a fixed duration in days or weeks, like P14D; calendar months cannot define an exact money deadline`);return}let O=Number(m[1]),J=m[2]==="W"?O*7:O;return W.add(b.name.name),{origin:b.span,port:b.name.name,window:{days:J,raw:A}}},U=(i,p,d)=>{if(i){if(C(i,p),i.value.kind!=="percent"){n(i.value.span,`${d} on ${p} must be a percent`);return}if(i.value.bps>=Ne){n(i.value.span,`a ${i.value.raw}% ${d} consumes the whole amount; it stays under 100%`);return}return i.value.bps===0&&r(i.value.span,`${d} on ${p} is 0%; drop the entry if none is meant`),i.value.bps}},F=(i,p,d,b,A,m)=>{let O=[];if(!i)return O;if(C(i,p),i.value.kind!=="block")return n(i.value.span,"fees is a block of party rules, like: fees { buyer: 1% }"),O;let J=(w,h)=>{if(w.value.kind!=="binding"){n(w.value.span,`${p} exact fee for ${h} declares immutable money in place, like feeAmount: money(SAR); it cannot reference a mutable field`);return}let E=K(w,`${p} fee for ${h}`);if(!E)return;let P=b.get(h);return P&&E.currency!==P.currency&&n(E.origin,`${p} fee field ${E.name} must use the base currency ${P.currency}`),A.has(E.name)?n(E.origin,`${p} fee field ${E.name} reuses another field declared by the settlement; every settlement field needs a distinct name`):A.add(E.name),{amount:E,kind:"exact"}},z=(w,h)=>{if(w.value.kind==="percent"){if(w.value.bps>=Ne){n(w.value.span,`a ${w.value.raw}% fee consumes the whole amount; fees stay under 100%`);return}if(w.value.bps===0){n(w.value.span,`the fee for ${h} is 0%; drop the entry if no fee is meant`);return}return{bps:w.value.bps,kind:"bps"}}return J(w,h)},g=(w,h,E)=>{if(w){if(w.value.kind!=="number"||!/^(0|[1-9][0-9]{0,17})$/.test(w.value.raw)){n(w.value.span,`tier ${E} for ${h} must be a non-negative integer minor-unit amount`);return}return BigInt(w.value.raw).toString()}},_=(w,h)=>{if(w.value.kind!=="block")return;let E=w.value.entries.filter(L=>L.key.name==="tier");for(let L of w.value.entries.filter(I=>I.key.name!=="tier"))n(L.key.span,`the tiered fee for ${h} contains only repeated tier blocks`);if(E.length===0){n(w.value.span,`the tiered fee for ${h} needs a tier`);return}let P=[];for(let L of E){if(L.value.kind!=="block"){n(L.value.span,`tier for ${h} must be a block`);continue}let I=L.value.entries.filter(pe=>pe.key.name==="from"),j=L.value.entries.filter(pe=>pe.key.name==="to"),V=L.value.entries.filter(pe=>pe.key.name==="fee");for(let pe of L.value.entries.filter(ke=>!["fee","from","to"].includes(ke.key.name)))n(pe.key.span,`tier for ${h} contains only from, optional to, and one fee`);I.length!==1&&n(L.span,`tier for ${h} needs exactly one from threshold`),j.length>1&&n(L.span,`tier for ${h} sets its exclusive to threshold twice`),V.length!==1&&n(L.span,`tier for ${h} selects exactly one fee value`);let G=g(I[0],h,"from"),oe=g(j[0],h,"to"),ie=V[0]?z(V[0],h):void 0;!G||!ie||P.push({fromInclusive:G,origin:L.span,rule:ie,...oe?{toExclusive:oe}:{}})}for(let[L,I]of P.entries()){L===0&&I.fromInclusive!=="0"&&n(I.origin,`the first tier for ${h} must begin at 0`),I.toExclusive!==void 0&&BigInt(I.toExclusive)<=BigInt(I.fromInclusive)&&n(I.origin,`tier for ${h} must end after its from threshold`);let j=P[L-1];if(j){if(j.toExclusive===void 0)n(I.origin,`only the final tier for ${h} may be open-ended`);else if(j.toExclusive!==I.fromInclusive){let V=BigInt(j.toExclusive)<BigInt(I.fromInclusive)?"gap":"overlap";n(I.origin,`tiers for ${h} have ${V==="overlap"?"an":"a"} ${V}: expected from ${j.toExclusive}, found ${I.fromInclusive}`)}}}let N=P.at(-1);return N?.toExclusive!==void 0&&n(N.origin,`the final tier for ${h} must be open-ended to cover every amount`),P.length===E.length?{kind:"tiered",tiers:P}:void 0};for(let w of i.value.entries){let h=w.key.name;if(!d.includes(h)){n(w.key.span,`fees are borne by this settlement's parties; ${h} is neither an allowed bearer nor part of this settlement`);continue}if(O.some(P=>P.bearer===h)){n(w.key.span,`${p} sets a fee for ${h} twice`);continue}let E=w.value.kind==="block"?_(w,h):z(w,h);E&&O.push({bearer:h,origin:w.span,position:m(h),rule:E})}return O},M=(i,p,d,b,A)=>{if(i.value.kind!=="block"){n(i.value.span,`${i.key.name} on ${p} is a block of percent shares, like: { ${d[0]??"party"}: 100% }`);return}let m=[],O,J=0,z=!0;for(let g of i.value.entries){let _=g.key.name;if(_==="remainder_to"){if(!A){n(g.key.span,`${p} does not take remainder_to here; the first share carries the integer remainder`),z=!1;continue}if(g.value.kind!=="ident"){n(g.value.span,"remainder_to names one of the recipients"),z=!1;continue}if(O){n(g.key.span,`${p} sets remainder_to twice`),z=!1;continue}O={name:g.value.name,span:g.value.span};continue}if(!d.includes(_)){n(g.key.span,`the ${i.key.name} split goes to ${b}; ${_} is not among them`),z=!1;continue}if(Q.add(_),m.some(w=>w.to===_)){n(g.key.span,`${p} splits to ${_} twice`),z=!1;continue}if(g.value.kind!=="percent"){n(g.value.span,`the share for ${_} must be a percent`),z=!1;continue}if(g.value.bps===0){n(g.value.span,`the share for ${_} is 0%; drop ${_} from the split instead of giving it nothing`),z=!1;continue}m.push({bps:g.value.bps,origin:g.span,to:_}),J+=g.value.bps}if(z&&J!==Ne&&(n(i.value.span,`the ${i.key.name} split must account for exactly 100%; these shares total ${(J/100).toFixed(2).replace(/\.?0+$/,"")}%`),z=!1),O&&!m.some(g=>g.to===O?.name)&&(n(O.span,`remainder_to must name one of the split's recipients; ${O.name} holds no share`),z=!1),!(!z||m.length===0))return{...O?{remainderTo:O.name}:{},shares:m}},ce=(i,p,d,b)=>{if(!i)return;let A=i.qualifiers[0];if(i.qualifiers.length!==1||A?.name!=="funded"){n(i.span,"on_cancel states the phase it covers; today that is on_cancel(funded)");return}let m=M(i,p,d,b,!1);if(m)return{origin:i.span,shares:m.shares,when:"funded"}},ae=(i,p)=>{if(i){if(C(i,p),i.value.kind==="ident"&&_e.test(i.value.name))return D(i.value.name,i.value.span,p)?void 0:i.value.name;n(i.value.span,`${i.key.name} on ${p} names a camelCase date field, like: ${i.key.name}: dueDate`)}},ge=(i,p)=>{if(i){if(C(i,p),i.value.kind==="ident"&&_e.test(i.value.name))return D(i.value.name,i.value.span,p)?void 0:i.value.name;n(i.value.span,`${i.key.name} on ${p} names a camelCase lineage field, like: ${i.key.name}: captureReference`)}},ne=(i,p,d,b)=>i?(C(i,p),i.value.kind==="ident"&&i.value.name===d?!0:(n(i.value.span,`${i.key.name} on ${p} is ${d}; ${b}`),!1)):!1,Gn=(i,p,d,b,A)=>{if(!i)return;C(i,p);let m=i.value.kind==="number"?Number(i.value.raw):Number.NaN;if(Number.isInteger(m)&&m>=b&&m<=A)return m;n(i.value.span,`${d} on ${p} is a literal integer from ${b} through ${A}`)},Xn=(i,p,d,b,A)=>{if(!i)return;if(C(i,p),i.value.kind!=="list"||i.value.items.length<b||i.value.items.length>A){n(i.value.span,`${d} on ${p} lists ${b} through ${A} declared parties`);return}let m=i.value.items.map(O=>B(O,`${p} ${d}`)).filter(O=>O!==void 0);if(new Set(m).size!==m.length){n(i.value.span,`${d} on ${p} must not repeat a party`);return}return m.length===i.value.items.length?m:void 0},Zn=(i,p,d,b=12,A=!1)=>{let m=i.get("count"),O=i.get("every"),J;if(m){C(m,p);let I=m.value,j=I.kind==="number"?Number(I.raw):Number.NaN;Number.isInteger(j)&&j>=2&&j<=b?J=j:n(I.span,`count on ${p} is a literal number of anchors between 2 and ${b}; the schedule stays finite by construction`)}let z,g;if(O){C(O,p);let I=O.value,j=I.kind==="ident"?I.name:I.kind==="string"?I.value:void 0,V=j?/^P([1-9]\d{0,3})([DW])$/.exec(j):null;if(V&&j){let G=Number(V[1]);z={days:V[2]==="W"?G*7:G,raw:j}}else if(j&&/^P([1-9]\d{0,3})M$/.test(j)){let G=Number(/^P([1-9]\d{0,3})M$/.exec(j)?.[1]);A?g={months:G,raw:j}:n(I.span,`every on ${p} uses calendar months, which only an open scheduled obligation may use`)}else n(I.span,`every on ${p} is P<n>D, P<n>W, or P<n>M on an open scheduled obligation`)}let _=ae(i.get("first_due"),p);if(!g)return z&&!m&&n(d,`${p} has a finite schedule without count`),J===void 0||!z||!_?void 0:{count:J,every:z,firstDueField:_,kind:"finite",origin:d};m&&n(m.span,`${p} combines count with an open monthly recurrence; use count for a finite schedule or until for an open schedule`);let w=i.get("until"),h;if(!w)n(d,`${p} has an open recurrence without until`);else{C(w,p);let I=w.value;if(I.kind==="port_ref")if(I.deadline||I.within)n(I.span,`until on ${p} is ambiguous; choose one port or one stored date`);else{let j=re(w,p,"termination");j&&(h={kind:"port",port:j})}else I.kind==="call"&&I.callee.name==="at"&&I.args.length===1&&I.args[0]?.kind==="ident"&&_e.test(I.args[0].name)?h={field:I.args[0].name,kind:"stored_date",origin:I.span}:n(I.span,`until on ${p} names one termination: port <name> or at(<storedDateField>)`)}for(let I of["month_end","period_liability","termination_drain"])i.has(I)||n(d,`${p} is missing ${I}`);let E=ne(i.get("month_end"),p,"clamp_to_last_day","calendar months need an explicit rule for anchors whose day is absent"),P=ne(i.get("period_liability"),p,"one_open","a new period cannot open while the prior period remains liable"),N=i.get("termination_drain"),L;if(N){C(N,p);let I=N.value,j=h?.kind==="port"?h.port.port:"cancel_period";I.kind==="ident"&&Ze.test(I.name)&&I.name===j?L=I.name:n(I.span,`termination_drain on ${p} must name its actual cancel action ${j}`)}if(i.has("timeout")&&n(i.get("timeout").span,`${p} pairs recurrence with a timeout money move; time may open or cancel a period but never collect money`),!(!_||!h||!E||!P||!L||m||i.has("timeout")))return{every:g,firstDueField:_,kind:"open",monthEnd:"clamp_to_last_day",origin:d,periodLiability:"one_open",termination:h,terminationDrain:L}},Qn=(i,p,d,b=12)=>{let A=Zn(i,p,d,b);return A?.kind==="finite"?A:void 0},gn=(i,p)=>{C(i,p);let d=i.value;if(d.kind!=="settlement_ref"){n(d.span,`${p} draws against a held payment's release, like: against: retention.release`);return}let b=d.owner.name,A=k.find(J=>J.name.name===b);if(!A){let J=l.get(b);n(d.owner.span,J?`${p} references ${b}, which is a ${J.kind}; settlement exits belong to settlements`:`${p} references ${b}, but no settlement with that name is declared`);return}let m=A.archetype.name;if(!De.includes(m))return;let O=$e[m].referenceableExits;if(!O.includes(d.member.name)){let J=O.length>0?`it exposes ${O.join(", ")}`:"it exposes no referenceable exits";n(d.member.span,`${p} references ${b}.${d.member.name}, but ${m} does not expose that exit; ${J}`);return}return{exit:d.member.name,origin:d.span,settlement:b,targetArchetype:m}},Zt=(i,p,d)=>{let b=i.get("against"),A=tt.filter(O=>i.has(O));if(b&&A.length>0){n(b.span,`${p} is repaid by a carve and by its own schedule (${A.join(", ")}); an advance draws on one source`);return}if(!b){if(A.length===0){n(d,`${p} needs a repayment source: against: <hold>.release carves it out of a hold's release, or count + every + first_due collects it on a schedule`);return}for(let J of tt)i.has(J)||n(d,`${p} is missing ${J}`);let O=Qn(i,p,d);return O?{kind:"schedule",schedule:O}:void 0}let m=gn(b,p);return m?{kind:"carve",...m}:void 0};for(let i of k){let p=i.archetype.name;if(!s.has(p)){n(i.archetype.span,De.includes(p)?`${p} must be imported first: import { ${p} } from "settlement"`:`there is no settlement archetype named ${p}`);continue}let d=`settlement ${i.name.name}`,b=new Set,A=$e[p],m=R(i.body,[...A.keys,...p==="deposit"?["claim_amount"]:[],"derived_amount"],d);for(let g of A.required)m.has(g)||n(i.span,`${d} is missing ${g}`);p==="scheduled"&&!m.has("count")&&!m.has("every")&&n(i.span,`${d} is missing count`);let O=(g,_)=>{let w=m.get(g);if(w)return C(w,d),B(w.value,`${d} ${_}`)},J=(g,_,w)=>g&&_&&g===_?(n(i.span,`${d} ${w}`),!1):!0,z=m.get("derived_amount");if(z)if(C(z,d),z.value.kind!=="block")n(z.value.span,"derived_amount is a block with field, source, rule, and bearer");else{let g=R(z.value,["field","source","rule","bearer"],`${d} derived_amount`);for(let I of["field","source","rule","bearer"])g.has(I)||n(z.span,`${d} derived_amount is missing ${I}`);let _=g.get("field")?.value,w=g.get("source")?.value,h=g.get("rule")?.value,E=g.get("bearer")?.value,P=_?.kind==="ident"?_.name:void 0,N=w?.kind==="ident"?w.name:void 0,L=E?B(E,`${d} derived amount bearer`):void 0;_&&_.kind!=="ident"&&n(_.span,"derived amount field must be a camelCase identifier"),w&&w.kind!=="ident"&&n(w.span,"derived amount source must name one stored money field"),h&&h.kind!=="percent"&&n(h.span,"derived_amount proves percentage-of rules only; fixed and tiered rules are refused"),h?.kind==="percent"&&(h.bps<=0||h.bps>=Ne)&&n(h.span,"derived amount percentage must be above 0% and below 100%"),P&&!_e.test(P)&&n(_.span,`derived amount field ${P} must be camelCase`),P&&_e.test(P)&&b.add(P),N&&!_e.test(N)&&n(w.span,`derived amount source ${N} must be camelCase`),P&&N&&P===N&&n(z.span,"derived amount field must differ from its source field"),P&&N&&L&&h?.kind==="percent"&&h.bps>0&&h.bps<Ne&&o.push({baseField:N,bearer:L,bps:h.bps,field:P,origin:z.span,settlement:i.name.name})}switch(p){case"captured_payment":{let g=O("payer","payer"),_=O("payee","payee"),w=J(g,_,`pays ${g} from ${g}; payer and payee must differ`),h=K(m.get("amount"),d),E=ae(m.get("reserve_until"),d),P=re(m.get("correction"),d,"payee correction"),N=ee(m.get("external_reversal"),d,"external reversal"),L=ne(m.get("capture_mode"),d,"partial_then_full","capture calls must leave a remainder and settle posts the final remainder"),I=ne(m.get("correction_mode"),d,"full_only","repeated partial corrections are not representable yet, so the checker refuses them"),j=ne(m.get("negative_position"),d,"reject","a correction or reversal must fail when the payee cannot fund it"),V=ne(m.get("timeout"),d,"reject","a timeout records no money movement; only a confirmed decision may reverse funds");if(m.has("fees")&&n(m.get("fees").span,`${d} does not price fees inside captured_payment; compose a separate fee settlement so capture and correction amounts stay exact`),h&&E===h.name){n(m.get("reserve_until")?.span??i.span,`${d} uses ${h.name} as both the reserved amount and reserve_until date field; they need distinct names`);break}g&&_&&h&&E&&P&&N&&L&&I&&j&&V&&w&&H.push({amount:h,archetype:"captured_payment",correction:P,externalReversal:N,name:i.name.name,origin:i.span,payee:_,payer:g,reserveUntilField:E});break}case"settlement_batch":{let g=O("settlement_account","settlement account"),_=O("payout_destination","payout destination"),w=J(g,_,`routes payout from ${g} back to itself; settlement account and payout destination must differ`),h=ge(m.get("source_capture_refs"),d),E=ge(m.get("fee_entries"),d),P=ge(m.get("external_reversal_offsets"),d),N=ae(m.get("close_trigger"),d),L=m.get("cadence"),I;if(L){C(L,d);let ie=L.value,pe=ie.kind==="ident"?/^P([1-9]\d{0,3})([DW])$/.exec(ie.name):null;if(!pe)n(ie.span,`${d} cadence uses a fixed duration in days or weeks, like P7D`);else{let ke=Number(pe[1]);I={days:pe[2]==="W"?ke*7:ke,raw:pe.input}}}let j=re(m.get("payout_acknowledgement"),d,"payout acknowledgement"),V=ge(m.get("payout_beneficiary_ref"),d),G=ne(m.get("negative_position"),d,"reject","offsets beyond gross capture entries must stop calculation and post no payout"),oe=[h,E,P,N,V].filter(ie=>ie!==void 0);if(new Set(oe).size!==oe.length){n(i.span,`${d} needs distinct source_capture_refs, fee_entries, external_reversal_offsets, close_trigger, and payout_beneficiary_ref field names`);break}g&&_&&h&&E&&P&&N&&j&&V&&G&&w&&H.push({archetype:"settlement_batch",...I?{cadence:I}:{},closeTriggerField:N,externalReversalReferenceField:P,feeReferenceField:E,name:i.name.name,origin:i.span,payoutDestination:_,payoutAcknowledgement:j,payoutBeneficiaryReferenceField:V,settlementAccount:g,sourceCaptureReferenceField:h});break}case"funding_round":{let g=O("contributor","contributor"),_=O("beneficiary","beneficiary"),w=K(m.get("target"),d),h=K(m.get("commitment"),d),E=Gn(m.get("max_contributors"),d,"max_contributors",2,1e4),P=ae(m.get("close_by"),d),N=[ne(m.get("close_policy"),d,"threshold","close must follow the locked committed sum at the stored close date"),ne(m.get("overfund_policy"),d,"reject","a commitment past the remaining target headroom must refuse"),ne(m.get("cancel_policy"),d,"before_close","a commitment may cancel only while its parent remains open"),ne(m.get("fail_policy"),d,"whole_commitment_refund","failure refunds each stored commitment whole")].every(Boolean),L=J(g,_,`uses ${g} as both contributor and beneficiary; the roles must differ`);w&&h&&w.currency!==h.currency&&n(h.origin,`${d} mixes ${w.currency} and ${h.currency}; target and commitment need one currency`),w&&h&&w.name===h.name&&n(h.origin,`${d} uses ${w.name} for both target and commitment; the parent and child amounts need distinct fields`),g&&_&&w&&h&&w.currency===h.currency&&w.name!==h.name&&E&&P&&N&&L&&H.push({archetype:"funding_round",beneficiary:_,cancelPolicy:"before_close",closeByField:P,closePolicy:"threshold",commitment:h,contributor:g,failPolicy:"whole_commitment_refund",maxContributors:E,name:i.name.name,origin:i.span,overfundPolicy:"reject",target:w});break}case"weighted_distribution":{let g=O("source","source"),_=O("recipient","recipient template"),w=K(m.get("amount"),d),h=K(m.get("weight"),d),E=Gn(m.get("max_recipients"),d,"max_recipients",2,1e4),P=ae(m.get("record_at"),d),N=re(m.get("snapshot"),d,"entitlement snapshot"),L=[ne(m.get("rounding_policy"),d,"largest_remainder","floor shares use a deterministic largest-remainder allocation with instrument id as the tie-break"),ne(m.get("withholding_policy"),d,"refuse","withholding needs its own proved retained-amount mechanism"),ne(m.get("correction_policy"),d,"new_distribution","post-payout correction is a new linked distribution, never a rewrite or caller amount")].every(Boolean),I=J(g,_,`uses ${g} as both source and recipient; the roles must differ`);w&&h&&w.currency!==h.currency&&n(h.origin,`${d} mixes ${w.currency} and ${h.currency}; pool and stored weights need one denomination`),w&&h&&w.name===h.name&&n(h.origin,`${d} uses ${w.name} for both pool and weight; the fields must differ`),g&&_&&w&&h&&w.currency===h.currency&&w.name!==h.name&&E&&P&&N&&L&&I&&H.push({amount:w,archetype:"weighted_distribution",correctionPolicy:"new_distribution",maxRecipients:E,name:i.name.name,origin:i.span,recipient:_,recordAtField:P,roundingPolicy:"largest_remainder",snapshot:N,source:g,weight:h,withholdingPolicy:"refuse"});break}case"credit_facility":{let g=O("lender","lender"),_=O("borrower","borrower"),w=O("draw_destination","draw destination"),h=K(m.get("limit"),d),E=ae(m.get("expires_at"),d),P=m.get("obligation"),N=P?gn(P,d):void 0,L=m.get("availability_policy"),I;L?.value.kind==="ident"&&(L.value.name==="revolving"||L.value.name==="non_revolving")?I=L.value.name:L&&n(L.value.span,`availability_policy on ${d} is revolving or non_revolving; the factpack does not justify an implicit choice`);let j=[ne(m.get("expiry_policy"),d,"freeze_draws","expiry stops new draws without closing linked debt"),ne(m.get("close_policy"),d,"no_open_draws","the facility closes only after every linked obligation resolves")].every(Boolean),V=[J(g,_,`uses ${g} as both lender and borrower; the roles must differ`),J(g,w,`draws back to its lender ${g}; draw_destination must differ`)].every(Boolean);g&&_&&w&&h&&E&&N&&I&&j&&V&&H.push({archetype:"credit_facility",availabilityPolicy:I,borrower:_,closePolicy:"no_open_draws",drawDestination:w,expiresAtField:E,expiryPolicy:"freeze_draws",lender:g,limit:h,name:i.name.name,obligation:N,origin:i.span});break}case"recurring_collection":{let g=m.get("obligation"),_=g?gn(g,d):void 0,w=re(m.get("mandate"),d,"mandate evidence"),h=[ne(m.get("attempt_policy"),d,"explicit","every attempt is a separate receipted call"),ne(m.get("period_idempotency"),d,"obligation_and_anchor","the parent obligation and stored anchor form the period identity"),ne(m.get("retry_policy"),d,"explicit_attempt","PRINCIPLES.md bans hidden retries; a retry needs a new explicit idempotency key"),ne(m.get("failure_policy"),d,"parent_delinquency","the scheduled obligation owns due state and delinquency")].every(Boolean);_&&w&&h&&H.push({archetype:"recurring_collection",attemptPolicy:"explicit",failurePolicy:"parent_delinquency",mandate:w,name:i.name.name,obligation:_,origin:i.span,periodIdempotency:"obligation_and_anchor",retryPolicy:"explicit_attempt"});break}case"conditional_disbursement":{let g=O("source","source"),_=O("destination","destination"),w=K(m.get("cap"),d),h=K(m.get("amount"),d),E=re(m.get("decision"),d,"capped disbursement decision"),P=[ne(m.get("reopen_policy"),d,"refuse","a closed decision cannot be reopened; create a new linked disbursement"),ne(m.get("recovery_policy"),d,"separate_transfer","recovery is a new money movement with its own receipt")].every(Boolean),N=J(g,_,`pays ${g} from itself; source and destination must differ`);w&&h&&w.currency!==h.currency&&n(h.origin,`${d} mixes ${w.currency} and ${h.currency}; cap and approved amount need one currency`),w&&h&&w.name===h.name&&n(h.origin,`${d} uses ${w.name} for both cap and approved amount; the fields must differ`),g&&_&&w&&h&&w.currency===h.currency&&w.name!==h.name&&E&&P&&N&&H.push({amount:h,archetype:"conditional_disbursement",cap:w,decision:E,destination:_,name:i.name.name,origin:i.span,recoveryPolicy:"separate_transfer",reopenPolicy:"refuse",source:g});break}case"rotating_pool":{let g=Xn(m.get("members"),d,"members",2,5),_=Xn(m.get("payout_order"),d,"payout_order",2,5),w=K(m.get("contribution"),d),h=Qn(m,d,i.span,12),E=m.has("guarantor")?O("guarantor","guarantor"):void 0,P=[ne(m.get("default_policy"),d,"due_condition","default follows an unmet stored contribution due condition"),ne(m.get("guarantee_policy"),d,"funded_only","a guarantee changes money only through an explicit funded contribution"),ne(m.get("exit_policy"),d,"before_activation_only","membership and order freeze before the first contribution")].every(Boolean),N=!0;if(g&&_){let L=new Set(g);(_.length!==g.length||_.some(I=>!L.has(I)))&&(n(m.get("payout_order")?.span??i.span,`${d} payout_order must contain every member exactly once`),N=!1)}g&&h&&h.count!==g.length&&(n(m.get("count")?.span??i.span,`${d} count ${h.count} must equal its ${g.length}-member roster`),N=!1),g&&E&&g.includes(E)&&(n(m.get("guarantor")?.span??i.span,`${d} guarantor must differ from every member`),N=!1),g&&E&&g.length>4&&(n(m.get("members")?.span??i.span,`${d} supports at most 4 members with a guarantor so every generated child binding stays within the 8-entry cap`),N=!1),g&&_&&w&&h&&P&&N&&H.push({archetype:"rotating_pool",contribution:w,defaultPolicy:"due_condition",exitPolicy:"before_activation_only",guaranteePolicy:"funded_only",...E?{guarantor:E}:{},members:g,name:i.name.name,origin:i.span,payoutOrder:_,schedule:h});break}case"swap":{let g=m.get("between"),_,w;g&&(C(g,d),g.value.kind!=="list"||g.value.items.length!==2?n(g.value.span,`${d} swaps between exactly two parties, like: between: [buyer, seller]`):(_=B(g.value.items[0],`${d} first side`),w=B(g.value.items[1],`${d} second side`),J(_,w,`names ${_} on both sides; the two swap parties must differ`)));let h=new Map,E=m.get("amounts");if(E)if(C(E,d),E.value.kind!=="block")n(E.value.span,`${d} amounts is a two-party block, like: amounts { buyer: buyerPays: money(SAR), seller: sellerPays: money(SAR) }`);else for(let V of E.value.entries){let G=V.key.name;if(G!==_&&G!==w){n(V.key.span,`${d} amount belongs to one of its two parties; ${G} is not in between`);continue}if(h.has(G)){n(V.key.span,`${d} declares more than one amount for ${G}`);continue}let oe=K(V,d);oe&&(h.set(G,oe),b.add(oe.name))}let P=_?h.get(_):void 0,N=w?h.get(w):void 0;_&&!P&&n(E?.span??i.span,`${d} needs exactly one funded amount for ${_}`),w&&!N&&n(E?.span??i.span,`${d} needs exactly one funded amount for ${w}`),P&&N&&P.currency!==N.currency&&n(E?.span??i.span,`${d} cannot link ${P.currency} and ${N.currency} in one atomic ledger batch; both amounts need one currency`);let L=re(m.get("release"),d,"whole-trade release"),I=ee(m.get("dispute"),d),j=F(m.get("fees"),d,[_,w].filter(V=>V!==void 0),h,b,()=>"on_top");if(_&&w&&P&&N&&P.currency===N.currency&&L){let V=j.find(oe=>oe.bearer===_),G=j.find(oe=>oe.bearer===w);H.push({archetype:"swap",...I?{dispute:I}:{},name:i.name.name,origin:i.span,release:L,sides:[{amount:P,...V?{fee:V}:{},party:_},{amount:N,...G?{fee:G}:{},party:w}]})}break}case"held_payment":{let g=O("payer","payer"),_=O("payee","payee"),w=J(g,_,`pays ${g} from ${g}; payer and payee must differ`),h=K(m.get("amount"),d),E=re(m.get("release"),d,"release",!0);h&&b.add(h.name),E?.deadlineField&&b.add(E.deadlineField);let P=F(m.get("fees"),d,[g,_].filter(I=>I!==void 0),new Map(h&&g&&_?[[g,h],[_,h]]:[]),b,I=>I===_?"carved":"on_top"),N=ce(m.get("on_cancel"),d,[g,_].filter(I=>I!==void 0),"this settlement's payer or payee"),L=P.find(I=>I.position==="carved"&&I.rule.kind!=="bps");if(L&&n(L.origin,`${d} supports exact and tiered carved fees on straight-through payments; held_payment currently requires a bps carved fee so cancellation and release share one fixed partition`),h&&E?.deadlineField===h.name){n(E.origin,`${d} uses ${h.name} as both the held amount and the release date field; they need distinct names`);break}g&&_&&h&&E&&w&&!L&&H.push({amount:h,archetype:"held_payment",fees:P,name:i.name.name,...N?{onCancel:N}:{},origin:i.span,payee:_,payer:g,release:{origin:E.origin,port:E.port},...E.deadlineField?{releaseDeadlineField:E.deadlineField}:{}});break}case"instant_transfer":{let g=O("payer","payer"),_=O("payee","payee"),w=J(g,_,`pays ${g} from ${g}; payer and payee must differ`),h=K(m.get("amount"),d);h&&b.add(h.name);let E=F(m.get("fees"),d,[g,_].filter(P=>P!==void 0),new Map(h&&g&&_?[[g,h],[_,h]]:[]),b,P=>P===_?"carved":"on_top");g&&_&&h&&w&&H.push({amount:h,archetype:"instant_transfer",fees:E,name:i.name.name,origin:i.span,payee:_,payer:g});break}case"premium_forward":{let g=O("payer","payer"),_=O("carrier","carrier"),w=J(g,_,`forwards the premium from ${g} to ${g}; payer and carrier must differ`),h=K(m.get("amount"),d),E=re(m.get("bind"),d,"binding"),P=U(m.get("commission"),d,"commission")??0,N=ce(m.get("on_cancel"),d,[g,_].filter(ie=>ie!==void 0),"this settlement's payer or carrier"),L=["policy_ref","renewal_due","renewal_policy","endorsement","endorsement_policy","lapse_policy"],I=L.some(ie=>m.has(ie));if(I)for(let ie of L)m.has(ie)||n(i.span,`${d} is missing ${ie}`);let j=I?ge(m.get("policy_ref"),d):void 0,V=I?ae(m.get("renewal_due"),d):void 0,G=I?re(m.get("endorsement"),d,"endorsement evidence"):void 0,oe=I?[ne(m.get("renewal_policy"),d,"explicit_new_forward","each renewal creates a new premium_forward instead of moving money from policy state"),ne(m.get("endorsement_policy"),d,"non_money_only","a money adjustment needs a separate corrected movement"),ne(m.get("lapse_policy"),d,"due_condition","lapse follows the stored renewal due condition")].every(Boolean):!0;if(g&&_&&h&&E&&w&&oe&&(!I||j&&V&&G)){let ie={amount:h,archetype:"premium_forward",bind:E,carrier:_,commissionBps:P,...G?{endorsement:G}:{},...I&&j&&V&&G?{endorsementPolicy:"non_money_only",lapsePolicy:"due_condition",policyReferenceField:j,renewalDueField:V,renewalPolicy:"explicit_new_forward"}:{},name:i.name.name,...N?{onCancel:N}:{},origin:i.span,payer:g};H.push(ie)}break}case"deposit":{let g=O("payer","payer"),_=O("holder","holder"),w=J(g,_,`holds ${g}'s deposit for ${g}; payer and holder must differ`),h=K(m.get("amount"),d),E=re(m.get("claim"),d,"claim"),P=re(m.get("return"),d,"return"),N=m.get("claim_amount"),L;if(N){C(N,d);let I=N.value;if(I.kind!=="decided_amount")n(I.span,`${d} claim_amount must be decided { field: <portMoneyField>, bound: ${h?.name??"<depositAmount>"}, remainder: return }`);else{let j=`${d} decided claim_amount`,V=R(I.body,["field","bound","remainder"],j);for(let pe of["field","bound","remainder"])V.has(pe)||n(I.span,`${j} is missing ${pe}`);let G=V.get("field")?.value,oe=V.get("bound")?.value,ie=V.get("remainder")?.value;G&&G.kind!=="ident"&&n(G.span,`${j} field must name a port field`),oe&&oe.kind!=="ident"&&n(oe.span,`${j} bound must name the stored deposit amount`),ie&&ie.kind!=="ident"&&n(ie.span,`${j} remainder must name the return exit`),G?.kind==="ident"&&oe?.kind==="ident"&&ie?.kind==="ident"&&(L={boundField:oe.name,boundOrigin:oe.span,field:G.name,fieldOrigin:G.span,origin:I.span,remainderExit:ie.name,remainderOrigin:ie.span})}}if(E&&P&&E.port===P.port){n(P.origin,`${d} claims and returns through the same port ${E.port}; the two exits need their own ports`);break}if(g&&_&&h&&E&&P&&w){let I={amount:h,archetype:"deposit",claim:E,holder:_,name:i.name.name,origin:i.span,payer:g,return:P};H.push(I),L&&ue.set(I,L)}break}case"scheduled":{let g=O("payer","payer"),_=O("payee","payee"),w=J(g,_,`pays ${g} from ${g}; payer and payee must differ`),h=K(m.get("amount"),d),E=m.get("mode")?.value,P=E?.kind==="ident"&&E.name==="obligation",N=Zn(m,d,i.span,P?7:12,!0);if(N?.kind==="open"&&!P&&n(N.origin,`${d} uses an open recurrence without mode: obligation; open periods need explicit liability and delinquency state`),h&&N&&h.name===N.firstDueField){n(N.origin,`${d} uses ${h.name} as both the amount and the first_due date field; they need distinct names`);break}let L=m.get("mode"),j=["advance_to","debtor","delinquency_policy","partial_payment","refund_policy","repayment_matching","reschedule_policy"].some(ke=>m.has(ke));if(!L&&j){n(i.span,`${d} uses obligation policies without mode: obligation`);break}if(!L){g&&_&&h&&N&&w&&H.push({amount:h,archetype:"scheduled",mode:"transfer",name:i.name.name,origin:i.span,payee:_,payer:g,schedule:N});break}if(!ne(L,d,"obligation","omit mode for a fixed transfer schedule"))break;let V=["debtor","partial_payment","repayment_matching","refund_policy","reschedule_policy","delinquency_policy"];for(let ke of V)m.has(ke)||n(i.span,`${d} is missing ${ke}`);let G=O("debtor","debtor"),oe=m.has("advance_to")?O("advance_to","advance recipient"):void 0,ie=[ne(m.get("partial_payment"),d,"anchor_bound","payments must bind to one stored installment anchor"),ne(m.get("repayment_matching"),d,"obligation_and_anchor","each payment must name both the obligation and its installment anchor; fuzzy or balance-wide matching is refused"),ne(m.get("refund_policy"),d,"full_payment_only","a refund reverses one stored payment whole so it cannot exceed that payment"),ne(m.get("reschedule_policy"),d,"refuse","forward-version carryover is not mechanically proven; create a new obligation after closing this one"),ne(m.get("delinquency_policy"),d,"due_condition","delinquency must come from an unmet stored due anchor")].every(Boolean),pe=[J(G,_,`${d} names ${G} as both debtor and settlement recipient; they must differ`),oe?J(oe,G,`${d} advances to its debtor ${G}; advance_to must name a distinct recipient`):!0].every(Boolean);g&&_&&h&&N&&w&&G&&ie&&pe&&H.push({...oe?{advanceTo:oe}:{},amount:h,archetype:"scheduled",debtor:G,mode:"obligation",name:i.name.name,origin:i.span,payee:_,payer:g,schedule:N});break}case"advance":{let g=O("funder","funder"),_=O("to","advanced party"),w=J(g,_,`advances ${g} their own money; funder and advanced party must differ`),h=K(m.get("amount"),d),E=U(m.get("fee"),d,"fee")??0,P=Zt(m,d,i.span);if(h&&P?.kind==="schedule"&&h.name===P.schedule.firstDueField){n(P.schedule.origin,`${d} uses ${h.name} as both the amount and the first_due date field; they need distinct names`);break}g&&_&&h&&P&&w&&H.push({advanced:_,amount:h,archetype:"advance",feeBps:E,funder:g,name:i.name.name,origin:i.span,source:P});break}case"metered":{let g=O("payer","payer"),_=O("payee","payee"),w=J(g,_,`meters ${g} against ${g}; payer and payee must differ`),h=ae(m.get("close_by"),d),E=[],P=m.get("rates"),N=!0;if(P)if(C(P,d),P.value.kind!=="block")n(P.value.span,"rates is a block of per-unit prices, like: rates { api_call: unitFee: money(SAR) }");else{let L=$e.metered.maxRates??$e.metered.eventCap;P.value.entries.length>L&&(n(P.value.span,`${d} prices ${P.value.entries.length} meters, but metered allows at most ${L} so one settlement stays within its ${$e.metered.eventCap}-event cap`),N=!1);for(let I of P.value.entries){if(!Ze.test(I.key.name)){n(I.key.span,`meter names are snake_case; "${I.key.name}" is not`);continue}if(E.some(G=>G.meter===I.key.name)){n(I.key.span,`${d} prices meter ${I.key.name} twice`);continue}let j=K(I,d);if(!j)continue;if(E.some(G=>G.field.name===j.name)){n(j.origin,`${d} reuses the field ${j.name} for two meters`);continue}let V=E[0]?.field.currency;if(V&&V!==j.currency){n(j.origin,`${d} mixes ${V} and ${j.currency}; one settlement meters in one currency`);continue}E.push({field:j,meter:I.key.name,origin:I.span})}P.value.entries.length===0&&n(P.value.span,`${d} prices no meters`)}if(h&&E.some(L=>L.field.name===h)){n(i.span,`${d} uses ${h} as both a rate field and the close_by date field; they need distinct names`);break}g&&_&&h&&E.length>0&&w&&N&&H.push({archetype:"metered",closeByField:h,name:i.name.name,origin:i.span,payee:_,payer:g,rates:E});break}case"pooled_split":{let g=O("payer","payer"),_=K(m.get("amount"),d),w=ae(m.get("payout_due"),d),h=m.get("split"),E=[...f.keys()].filter(I=>I!==g),P=h?M(h,d,E,"declared parties other than the funder",!0):void 0;if(P&&P.shares.length<2){n(h.value.span,`${d} splits to a single recipient; a pool distributes between at least two`);break}let N=$e.pooled_split.maxRecipients??Math.floor($e.pooled_split.eventCap/2),L=!P||P.shares.length<=N;if(L||n(h.value.span,`${d} splits to ${P.shares.length} recipients, but pooled_split allows at most ${N} so funding and payout stay within its ${$e.pooled_split.eventCap}-event cap`),P){let I=new Map;for(let j of P.shares){let[V="",...G]=j.to.split("_"),oe=`${V+G.map(pe=>pe.charAt(0).toUpperCase()+pe.slice(1)).join("")}ShareAmount`,ie=I.get(oe);ie&&n(j.origin,`${d} splits to ${ie} and ${j.to}, whose generated share fields both come out as ${oe}; rename one party`),I.set(oe,j.to)}}if(_&&w&&_.name===w){n(i.span,`${d} uses ${_.name} as both the amount and the payout_due date field; they need distinct names`);break}g&&_&&w&&P&&L&&H.push({amount:_,archetype:"pooled_split",distributeDueField:w,name:i.name.name,origin:i.span,payer:g,remainderTo:P.remainderTo??P.shares[0].to,shares:P.shares});break}}}let $n=[];for(let i of x){let p=`port ${i.name.name}`,d=R(i.body,["allowed","shape"],p);d.has("allowed")||n(i.span,`${p} is missing allowed`);let b=[],A=d.get("allowed");if(A){C(A,p);let J=A.value;if(J.kind!=="list"||J.items.length===0)n(J.span,"allowed lists who may ask this question, like: allowed: [buyer]");else for(let z of J.items){let g=B(z,`${p} allowed`);if(g){if(b.includes(g)){n(z.span,`${p} allows ${g} twice`);continue}b.push(g)}}}let m=[],O=d.get("shape");if(O)if(C(O,p),O.value.kind!=="block")n(O.value.span,"shape is a block of typed fields, like: shape { vehicleId: id(vehicle) }");else for(let J of O.value.entries){if(!_e.test(J.key.name)){n(J.key.span,`shape fields are camelCase names; "${J.key.name}" is not`);continue}if(m.some(g=>g.name===J.key.name)){n(J.key.span,`${p} declares ${J.key.name} twice`);continue}let z=er(J.value);if(!z){n(J.value.span,`${J.key.name} needs a type: id(<asset>), money(<CUR>), text, or date`);continue}if(z.kind==="asset_id"&&!v.has(z.asset)){n(J.value.span,`id(${z.asset}) points at an asset that is not declared`);continue}if(z.kind==="money"&&!rt.test(z.currency)){n(J.value.span,`"${z.currency}" is not a currency code; use three capital letters like SAR`);continue}m.push({name:J.key.name,origin:J.span,type:z})}b.length>0&&$n.push({allowed:b,fields:m,name:i.name.name,origin:i.span})}let be=new Map($n.map(i=>[i.name,i]));for(let[i,p]of ue){let b=be.get(i.claim.port)?.fields.find(J=>J.name===p.field),A=!0;if(b?b.type.kind!=="money"?(n(p.fieldOrigin,`settlement ${i.name} decided claim_amount field ${p.field} must be money`),A=!1):b.type.currency!==i.amount.currency&&(n(p.fieldOrigin,`settlement ${i.name} decided claim_amount mixes ${b.type.currency} and ${i.amount.currency}; decided value and bound need one currency`),A=!1):(n(p.fieldOrigin,`settlement ${i.name} decided claim_amount names ${p.field}, but claim port ${i.claim.port} has no such field`),A=!1),p.boundField!==i.amount.name&&(n(p.boundOrigin,`settlement ${i.name} decided claim_amount bound must name immutable stored amount ${i.amount.name}; ${p.boundField} is not that bound`),A=!1),p.remainderExit!=="return"&&(n(p.remainderOrigin,`settlement ${i.name} decided claim_amount remainder must name its return exit; ${p.remainderExit} would strand the unclaimed amount`),A=!1),!A)continue;let m={boundField:p.boundField,boundOrigin:p.boundOrigin,field:p.field,fieldOrigin:p.fieldOrigin,origin:p.origin,remainderExit:"return",remainderOrigin:p.remainderOrigin},O=H.indexOf(i);H[O]={...i,claimAmount:m}}for(let i of H){if(i.archetype==="captured_payment"){let b=be.get(i.correction.port);b&&(b.allowed.length!==1||b.allowed[0]!==i.payee)&&n(b.origin,`captured_payment ${i.name} correction port ${b.name} must allow only its payee ${i.payee}`);let A=be.get(i.externalReversal.port);A&&!A.fields.some(m=>m.name==="externalReference"&&m.type.kind==="text")&&n(A.origin,`captured_payment ${i.name} external reversal port ${A.name} needs shape { externalReference: text }`);continue}if(i.archetype==="settlement_batch"){let b=be.get(i.payoutAcknowledgement.port);b&&!b.fields.some(A=>A.name==="acknowledgementReference"&&A.type.kind==="text")&&n(b.origin,`settlement_batch ${i.name} payout acknowledgement port ${b.name} needs shape { acknowledgementReference: text }`);continue}if(i.archetype==="weighted_distribution"){let b=be.get(i.snapshot.port);b&&!b.fields.some(A=>A.name==="evidenceReference"&&A.type.kind==="text")&&n(b.origin,`weighted_distribution ${i.name} snapshot port ${b.name} needs shape { evidenceReference: text }`);continue}if(i.archetype==="recurring_collection"){let b=be.get(i.mandate.port);b&&!b.fields.some(A=>A.name==="evidenceReference"&&A.type.kind==="text")&&n(b.origin,`recurring_collection ${i.name} mandate port ${b.name} needs shape { evidenceReference: text }`);continue}if(i.archetype==="conditional_disbursement"){let b=be.get(i.decision.port);b&&(!b.fields.some(A=>A.name==="evidenceReference"&&A.type.kind==="text")||b.allowed.length!==1||b.allowed[0]!==i.source)&&n(b.origin,`conditional_disbursement ${i.name} decision port ${b.name} must allow only ${i.source} and needs shape { evidenceReference: text }`);continue}if(i.archetype==="premium_forward"&&i.endorsement){let b=be.get(i.endorsement.port);b&&!b.fields.some(A=>A.name==="evidenceReference"&&A.type.kind==="text")&&n(b.origin,`premium_forward ${i.name} endorsement port ${b.name} needs shape { evidenceReference: text }`);continue}if(i.archetype!=="swap")continue;let p=new Set(i.sides.map(b=>b.party)),d=[{label:"release",portRef:i.release},...i.dispute?[{label:"dispute",portRef:i.dispute}]:[]];for(let b of d){let A=be.get(b.portRef.port);if(A)for(let m of A.allowed)p.has(m)||n(A.origin,`swap ${i.name} ${b.label} port ${A.name} allows ${m}, but whole-trade decisions belong only to ${i.sides.map(O=>O.party).join(" or ")}`)}}let et=new Map(H.filter(i=>i.archetype==="scheduled"&&i.mode==="obligation").map(i=>[i.name,i])),bn=new Map;for(let i of H){if(i.archetype!=="credit_facility"&&i.archetype!=="recurring_collection")continue;let p=et.get(i.obligation.settlement),d=`settlement ${i.name}`;if(!p){n(i.obligation.origin,`${d} must compose with scheduled in mode: obligation; ${i.obligation.settlement} is not one`);continue}if(i.archetype==="credit_facility"){p.advanceTo&&n(i.obligation.origin,`${d} references ${p.name}, which already owns an advance; facility draws and obligation repayment must have one disbursement owner`),(p.payee!==i.lender||p.debtor!==i.borrower||p.amount.currency!==i.limit.currency)&&n(i.obligation.origin,`${d} must link an obligation whose payee is ${i.lender}, debtor is ${i.borrower}, and currency is ${i.limit.currency}`);continue}let b=be.get(i.mandate.port),A=bn.get(p.name);A?n(i.obligation.origin,`${d} and settlement ${A} both collect ${p.name}; one obligation may have one collection policy owner`):bn.set(p.name,i.name),b&&(b.allowed.length!==1||b.allowed[0]!==p.payer)&&n(b.origin,`${d} mandate port ${b.name} must allow only the obligation payer ${p.payer}`)}for(let i of et.values())i.schedule.kind==="open"&&!bn.has(i.name)&&n(i.schedule.origin,`settlement ${i.name} has an open recurrence without recurring_collection; open-period failures must reuse failure_policy: parent_delinquency`);let Qt=new Map(H.filter(i=>i.archetype==="held_payment").map(i=>[i.name,i])),nt=new Map;for(let i of H){if(i.archetype!=="advance"||i.source.kind!=="carve")continue;let p=`settlement ${i.name}`,d=i.source.settlement,b=i.source.origin;if(i.source.targetArchetype!=="held_payment"||i.source.exit!=="release"){n(b,`${p} can only carve held_payment.release; ${d}.${i.source.exit} is a ${i.source.targetArchetype} exit`);continue}let A=Qt.get(d);if(!A)continue;if(A.payee!==i.advanced){n(b,`${p} advances ${i.advanced}, but ${d} releases to ${A.payee}; an advance carves the release of the party it finances`);continue}if(A.amount.name!==i.amount.name){n(b,`${p} advances field ${i.amount.name}, but ${d}.release carries ${A.amount.name}; a carve must name the same money field`);continue}if(A.amount.currency!==i.amount.currency){n(b,`${p} advances ${i.amount.currency}, but ${d}.release carries ${A.amount.currency}; a carve must use one currency`);continue}if(i.feeBps>0){n(b,`${p} adds a fee to a carved advance, but ${d}.release can only prove repayment of the principal field; use a fee-free carve or a scheduled advance`);continue}if(A.fees.some(z=>z.bearer===A.payee&&(z.rule.kind!=="bps"||z.rule.bps>0))){n(b,`${p} carves ${d}.release after a payee fee reduces it; a carved hold must release the full principal field to the funder`);continue}if(A.payer===i.funder){n(b,`${i.funder} funds ${d} and finances it too; the party who pays the hold cannot be the funder its release repays`);continue}let m=nt.get(d);if(m){n(b,`${p} and settlement ${m} both draw against ${d}; one release repays one advance`);continue}if(nt.set(d,i.name),H.some(z=>z.archetype==="scheduled"&&z.mode==="transfer"&&z.payer===i.advanced&&z.payee===i.funder&&z.amount.name===i.amount.name&&z.amount.currency===i.amount.currency))continue;let J=`add a scheduled settlement collecting from the ${i.advanced.replaceAll("_"," ")} to the ${i.funder.replaceAll("_"," ")}`;if(A.onCancel){n(b,`${p} has no repayment path when ${d} is refunded instead of released; ${J}`);continue}r(b,`${p} has no repayment path if ${d} is abandoned before it funds; ${J}`)}for(let[i,p]of f)Q.has(i)||r(p.origin,`party ${i} is declared but no settlement or port involves them`);for(let i of x)T.has(i.name.name)&&!W.has(i.name.name)&&r(i.span,`port ${i.name.name} is declared but nothing releases through it`);for(let[i,p]of s)k.some(b=>b.archetype.name===i)||r(p,`${i} is imported but never instantiated`);return t.some(i=>i.severity==="error")||!c?{diagnostics:t}:{diagnostics:t,program:{assets:[...v.values()],derivedAmounts:o,name:c.name.name,origin:e.span,parties:[...f.values()],ports:$n,settlements:H,title:c.title?.value??nr(c.name.name)}}}function er(e){if(e.kind==="ident"&&e.name==="text")return{kind:"text"};if(e.kind==="ident"&&e.name==="date")return{kind:"date"};if(e.kind==="call"&&e.args.length===1&&e.args[0]?.kind==="ident"){let t=e.args[0].name;if(e.callee.name==="id")return{asset:t,kind:"asset_id"};if(e.callee.name==="money")return{currency:t,kind:"money"}}}function nr(e){let t=e.replaceAll("_"," ");return t.charAt(0).toUpperCase()+t.slice(1)}function at(e){let t=[0];for(let n=0;n<e.length;n+=1)e.charCodeAt(n)===10&&t.push(n+1);return{length:e.length,starts:t}}function kn(e,t){let n=Math.max(0,Math.min(t,e.length)),r=0,o=e.starts.length-1;for(;r<o;){let a=Math.floor((r+o+1)/2);e.starts[a]<=n?r=a:o=a-1}return{column:n-e.starts[r]+1,line:r+1}}var it=20,st=48,_n=10000n;function tr(e){if(!e)return{amountDependencies:[],amountMode:"fixed"};switch(e.kind){case"bounded_by_reference":return{amountDependencies:[Y(e.reference)],amountMode:"runtime_bounded"};case"net_of_offsets":{if(e.offsets.length===0)throw new Error("net_of_offsets requires at least one offset event");return{amountDependencies:ct(e.source,e.offsets),amountMode:"runtime_bounded"}}case"percent_of_reference":if(!Number.isInteger(e.bps)||e.bps<=0||e.bps>1e4)throw new Error("percent_of_reference bps must be an integer between 1 and 10000");return{amountDependencies:[Y(e.reference)],amountMode:"runtime_bounded"};case"remainder":{if(e.consumed.length===0)throw new Error("remainder requires at least one consumed event");return{amountDependencies:ct(e.source,e.consumed),amountMode:"remaining_balance"}}}}function ct(e,t){let n=[e,...t].map(Y);if(new Set(n).size!==n.length)throw new Error("amount dependency event keys must be distinct");return n}var dt=160,rr=new Set(["amount","design","detail","headline","label","summary","title","trigger","why"]);function An(e,t){return typeof e=="string"?t!==void 0&&rr.has(t)&&e.length>dt?`${e.slice(0,dt-3)}...`:e:Array.isArray(e)?e.map(n=>An(n,t)):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,An(r,n)])):e}function or(e){return An(e)}function Y(e){if(e.length<=40)return e;let t=2166136261;for(let n=0;n<e.length;n+=1)t=Math.imul(t^e.charCodeAt(n),16777619);return`${e.slice(0,33)}_${(t>>>0).toString(36).slice(0,6)}`}function ar(e){let t=e.amountDependency;if(!t)return e.amount;switch(t.kind){case"bounded_by_reference":return`Bounded by ${t.reference}: ${e.amount}`;case"net_of_offsets":return`Net of ${t.source} after ${t.offsets.join(", ")}: ${e.amount}`;case"percent_of_reference":return`${le(t.bps)} of ${t.reference}: ${e.amount}`;case"remainder":return`Remainder of ${t.source} after ${t.consumed.join(", ")}: ${e.amount}`}}function te(e){return{allocationTotalBps:0,amount:ar(e),...tr(e.amountDependency),amountSchedule:[],distribution:"single",fromActor:e.fromActor,key:Y(e.key),kind:e.kind,label:e.trigger,occurrence:e.occurrence??"once",timing:e.timing??"on_lifecycle",toActor:e.toActor,trigger:e.trigger}}function Ie(e,t,n,r){return e.map((o,a)=>({from:a===0?t:`${r}_${a}`,to:a===e.length-1?n:`${r}_${a+1}`}))}function Je(e,t,n,r){let o=new Set;for(let a of t){if(a==="create"||o.has(a))return r.push({message:`settlement ${e} generates two actions named "${a}"; rename the colliding port`,span:n}),!1;o.add(a)}return!0}function Ae(e,t){return t.length>=2?[{pieces:[...t],total:e}]:[]}function Ce(e){return e.length>0?{partitions:[...e]}:{}}function Z(e){return{desc:e,type:"money"}}function je(e,t){return e.fixedAmount===void 0?Z(t):{desc:t,type:`money:${e.currency}:${e.fixedAmount}`}}function rn(e){return e.kind==="exact"?[e.amount]:e.kind==="bps"?[]:e.tiers.flatMap(t=>rn(t.rule))}function ut(e){switch(e.kind){case"bps":return{bps:e.bps,kind:"bps"};case"exact":return{currencyField:"currency",field:e.amount.name,kind:"exact"};case"tiered":return{kind:"tiered",tiers:e.tiers.map(t=>({fromInclusive:t.fromInclusive,...t.toExclusive?{toExclusive:t.toExclusive}:{},rule:ut(t.rule)}))}}}function Qe(e,t){return e.rule.kind==="exact"?e.rule.amount.name:t}function en(e,t,n){return{amountField:n,baseField:t,bearer:e.bearer,position:e.position,rule:ut(e.rule)}}function he(e){switch(e.kind){case"bps":return le(e.bps);case"exact":return`Exact ${e.amount.name}`;case"tiered":return`${e.tiers.length}-tier fee`}}function me(e){return{desc:e,type:"date"}}function ir(e){return{desc:e,type:"date?"}}function pt(e){return Object.fromEntries(e.fields.map(t=>[t.name,t.type.kind==="asset_id"?{...t.type}:t.type.kind]))}function sr(e){if(typeof e.prefix=="string")return e.prefix;let t=e.id,n=t.split("_");return(n.length>1?n.map(o=>o[0]).join(""):t.slice(0,4)).slice(0,8).padEnd(2,"x")}function cr(e,t){let n=new Set(e.filter(a=>!t.has(a.id)).map(sr)),r=0,o=()=>{for(;;){let a=String.fromCharCode(97+Math.floor(r/26)),c=String.fromCharCode(97+r%26);r+=1;let s=`zz${a}${c}`;if(!n.has(s))return n.add(s),s}};return e.map(a=>t.has(a.id)?{...a,prefix:o()}:a)}function mt(e){let t=[],n=[],r=[],o=[],a=[],c=[],s=[],l=[],u=[],f=new Set,v=new Map,x=new Map(e.ports.map($=>[$.name,$])),k=($,D,K)=>{let re=x.get(D);return re||t.push({message:`settlement ${$.name} decides through an unknown port; the checker should have refused this program`,span:K}),re},T=new Map(e.settlements.flatMap($=>$.archetype==="advance"&&$.source.kind==="carve"?[[$.source.settlement,$.funder]]:[])),R=new Map(e.settlements.flatMap($=>{if($.archetype!=="advance"||$.source.kind!=="carve")return[];let D=e.settlements.filter(K=>K.archetype==="scheduled"&&K.mode==="transfer"&&K.payer===$.advanced&&K.payee===$.funder&&K.amount.name===$.amount.name&&K.amount.currency===$.amount.currency);return[[$.name,D]]})),C=new Map(e.settlements.flatMap($=>$.archetype==="recurring_collection"?[[$.obligation.settlement,$]]:[]));for(let $ of e.settlements){let D;switch($.archetype){case"held_payment":{let U=k($,$.release.port,$.release.origin);if(!U)continue;D=vr($,U,T.get($.name),t);break}case"captured_payment":{let U=k($,$.correction.port,$.correction.origin),F=k($,$.externalReversal.port,$.externalReversal.origin);if(!U||!F)continue;D=Ar($,U,F,t);break}case"settlement_batch":{let U=k($,$.payoutAcknowledgement.port,$.payoutAcknowledgement.origin);if(!U)continue;D=xr($,U,t);break}case"funding_round":D=Ir($);break;case"weighted_distribution":{let U=k($,$.snapshot.port,$.snapshot.origin);if(!U)continue;D=Pr($,U);break}case"credit_facility":D=Cr($);break;case"recurring_collection":continue;case"conditional_disbursement":{let U=k($,$.decision.port,$.decision.origin);if(!U)continue;D=Er($,U);break}case"rotating_pool":D=Tr($);break;case"premium_forward":{let U=k($,$.bind.port,$.bind.origin),F=$.endorsement?k($,$.endorsement.port,$.endorsement.origin):void 0;if(!U||$.endorsement&&!F)continue;D=kr($,U,F,t);break}case"deposit":{let U=k($,$.claim.port,$.claim.origin),F=k($,$.return.port,$.return.origin);if(!U||!F)continue;D=Sr($,U,F,t);break}case"instant_transfer":D=_r($);break;case"scheduled":if($.mode==="obligation"){let U=C.get($.name),F=U?k(U,U.mandate.port,U.mandate.origin):void 0;if($.schedule.kind==="open"){let M=$.schedule.termination.kind==="port"?k($,$.schedule.termination.port.port,$.schedule.termination.port.origin):void 0;if(!U||!F||$.schedule.termination.kind==="port"&&!M)continue;D=Rr({...$,schedule:$.schedule},U,F,t,M)}else D=Fr({...$,schedule:$.schedule},U,F)}else{if($.schedule.kind==="open")continue;D=Or({...$,schedule:$.schedule})}break;case"advance":D=Dr($,R.get($.name)??[]);break;case"metered":D=jr($);break;case"pooled_split":D=Br($);break;case"swap":{let U=k($,$.release.port,$.release.origin),F=$.dispute?k($,$.dispute.port,$.dispute.origin):void 0;if(!U||$.dispute&&!F)continue;D=wr($,U,F);break}}if(!D)continue;let K=(e.derivedAmounts??[]).filter(U=>U.settlement===$.name);if(K.length>0&&(D=fr(D,$,K,t),!D))continue;let re=$e[$.archetype].eventCap+K.length;if(D.moneyEvents.length>re){t.push({message:`settlement ${$.name} emits ${D.moneyEvents.length} money events, but ${$.archetype} carries a local cap of ${re}`,span:$.origin});continue}for(let U of[...D.moneyEvents,...D.rules]){let F=U.key,M=v.get(F);M&&t.push({message:`settlements ${M} and ${$.name} both generate the internal key ${F}; rename one settlement (or its port or meter) so the generated keys stay distinct`,span:$.origin}),v.set(F,$.name)}n.push(D.settlement);let ee=[D.instrument,...D.extraInstruments??[]];for(let U of ee){let F=U.actions;for(let[M,ce]of Object.entries(F)){if(Object.hasOwn(ce,"due")||Object.hasOwn(ce,"requiresSettlement"))continue;let ae=ft(U.id,M);ae.length<=st||t.push({message:`settlement ${$.name} generates public action "${ae}" with ${ae.length} characters; rename the settlement so each public action fits the ${st}-character camelName limit`,span:$.origin})}}r.push(...ee),o.push(...ee.map(()=>({lowered:D.settlement,settlement:$})));for(let U of D.generatedPrefixInstrumentIds??[])f.add(U);a.push(...D.moneyEvents),c.push(...D.rules),s.push(...D.design),l.push(...D.feeLines),D.repeatableCounterparty&&u.push(D.repeatableCounterparty)}a.length>it&&t.push({message:`this program needs ${a.length} money events but a Business Frame carries at most ${it}; simplify the fee or cancellation terms, or drop a settlement`,span:e.settlements[0]?.origin??{end:0,start:0}}),t.push(...hr(a,e.settlements[0]?.origin??{end:0,start:0}));let Q=yr(e,u);if(t.push(...Q.issues),t.length>0)return{issues:t,ok:!1};let B=mr(cr(r,f)),W=e.assets.map($=>({kind:$.name,title:q($.name),value:"optional"})),H={hsx:1,instruments:B,product:e.name,...W.length>0?{subjects:W}:{},title:e.title},ue=dr(H,e,o),X={actors:Q.actors,confidence:"high",conservationGroups:[],design:s,feePolicy:l.length>0?"defined":"none",fees:l,headline:e.title,mechanics:br(e.settlements),moneyEvents:a,offPlatform:e.assets.filter($=>$.titleTransfer==="off_platform").map($=>({label:`${q($.name)} title transfer`,why:`Ownership of the ${$.name.replaceAll("_"," ")} changes hands outside the platform`})),openQuestions:[],rules:c,subjects:e.assets.map($=>({kind:$.name,title:q($.name)})),summary:Jr(e)};return{ok:!0,value:{document:H,frame:or(X),originMap:ue,settlements:n}}}function dr(e,t,n){let r=[{path:"$",span:t.origin}];for(let[o,a]of e.instruments.entries()){let c=n[o];if(!c)continue;let s=lt(c,t),l=`$.instruments[${o}]`;r.push({path:l,span:c.settlement.origin});for(let[u,f]of Object.entries(a))tn(f,xn(l,u),c.settlement.origin,s,r);if(c.settlement.archetype==="deposit"){let u=c.settlement.claimAmount;if(u){let f=xn(`${l}.actions`,c.settlement.claim.port);Re(r,`${f}.decidedAmount`,u.origin),Re(r,`${f}.decidedAmount.field`,u.fieldOrigin),Re(r,`${f}.decidedAmount.boundField`,u.boundOrigin),Re(r,`${f}.decidedAmount.remainderAction`,u.remainderOrigin),Re(r,`${f}.moves[0].amount`,u.fieldOrigin),Re(r,`${f}.moves[1]`,u.remainderOrigin)}}}for(let[o,a]of(e.subjects??[]).entries()){let c=t.assets[o];tn(a,`$.subjects[${o}]`,c?.origin??t.origin,c?lt(c,t):[],r)}return r}function Re(e,t,n){let r=e.findIndex(o=>o.path===t);r>=0?e[r]={path:t,span:n}:e.push({path:t,span:n})}function lt(e,t){let n=[],r="settlement"in e?e.settlement:e;if(Fe(r,[],n),"lowered"in e)for(let o of e.lowered.pieces)n.push({labels:[],span:o.origin,tokens:[o.field]});for(let o of t.ports)Fe(o,["port"],n);for(let o of t.parties)Fe(o,["party"],n);for(let o of t.derivedAmounts)"settlement"in e&&o.settlement===e.settlement.name&&Fe(o,["derivedAmounts"],n);return n}function Fe(e,t,n){if(!e||typeof e!="object")return;if(Array.isArray(e)){for(let o of e)Fe(o,t,n);return}let r=e;pr(r.origin)&&n.push({labels:t,span:r.origin,tokens:nn(r)});for(let[o,a]of Object.entries(r))o!=="origin"&&Fe(a,[...t,o],n)}function nn(e){return typeof e=="string"||typeof e=="number"?[String(e)]:!e||typeof e!="object"?[]:Array.isArray(e)?e.flatMap(nn):Object.entries(e).flatMap(([t,n])=>t==="origin"?[]:nn(n))}function tn(e,t,n,r,o){let a=t.slice(t.lastIndexOf(".")+1),s=(/\.actions\.[^.[]+$/.test(t)?lr(a,r):ur([a,...nn(e)],r))??n;if(o.push({path:t,span:s}),!(!e||typeof e!="object")){if(Array.isArray(e)){for(let[l,u]of e.entries())tn(u,`${t}[${l}]`,s,r,o);return}for(let[l,u]of Object.entries(e))tn(u,xn(t,l),s,r,o)}}function lr(e,t){let n=Se(e),r=t.filter(a=>a.tokens.some(c=>Se(c)===n));if(r.length>0)return Le(r);if(n==="settle"){let a=t.filter(c=>c.labels.some(s=>Se(s)==="source"));if(a.length>0)return Le(a)}let o=t.filter(a=>a.labels.some(c=>{let s=Se(c);return s.length>=4&&(n.includes(s)||n!=="create"&&n.length>=5&&s.startsWith(n))}));if(o.length>0)return Le(o);if(/collect|installment|repayment|delinquent/.test(n)){let a=t.filter(c=>c.labels.some(s=>Se(s)==="schedule"));if(a.length>0)return Le(a)}if(/cancel|refund|unfund|abandon/.test(n)){let a=t.filter(c=>c.labels.some(s=>Se(s)==="oncancel"));if(a.length>0)return Le(a)}}function Le(e){return e.reduce((t,n)=>{let r=n.span.end-n.span.start,o=t.end-t.start;return r<o||r===o&&n.span.start<t.start?n.span:t},e[0].span)}function ur(e,t){let n=e.map(Se).filter(Boolean),r;for(let o of t){let a=[...o.tokens,...o.labels].map(Se),c=0;for(let u of n)for(let f of a)f.length<2||(u===f?c=Math.max(c,4):(u.includes(f)||f.includes(u))&&(c=Math.max(c,1)));if(c===0)continue;let s=o.span.end-o.span.start,l=r?r.span.end-r.span.start:1/0;(!r||c>r.score||c===r.score&&s<l||c===r.score&&s===l&&o.span.start<r.span.start)&&(r={score:c,span:o.span})}return r?.span}function Se(e){return e.replace(/[^A-Za-z0-9]/g,"").toLowerCase()}function xn(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function pr(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.start=="number"&&typeof t.end=="number"}function mr(e){return e.map(t=>{let n=t.actions;return{...t,actions:Object.fromEntries(Object.entries(n).map(([r,o])=>[r,Object.hasOwn(o,"due")||Object.hasOwn(o,"requiresSettlement")?o:{...o,publicAction:ft(t.id,r)}]))}})}function ft(e,t){let n=de(e),r=n.charAt(0).toUpperCase()+n.slice(1);return`${de(t)}${r}`}function fr(e,t,n,r){let o=e.instrument,a={...o.fields??{}},c={...o.actions??{}},s={...c.create??{}},l=[...s.moves??[]],u={...o.actors??{}},f=[],v=[...e.moneyEvents],x=[...e.feeLines];for(let k of n){let T=a[k.baseField];if(T===void 0||T.type!=="money"){r.push({message:`settlement ${t.name} derives ${k.field} from ${T===void 0?"unknown ":"non-money "}field ${k.baseField}; from must name a stored money field on the settlement owner`,span:k.origin});return}if(a[k.field]!==void 0){r.push({message:`settlement ${t.name} derives into existing field ${k.field}; choose a new derived amount field`,span:k.origin});return}let R=Y(`${t.name}_derived_amount`);a[k.field]=Z(`Machine-computed ${le(k.bps)} of ${k.baseField}; callers never supply it`),u[k.bearer]===void 0&&(u[k.bearer]="payer"),u.platform="beneficiary",f.push({field:k.field,rounding:"floor",rule:{bps:k.bps,kind:"percentage_of"},sourceField:k.baseField}),l.push({amount:k.field,from:k.bearer,key:"derived_amount",moneyEvent:R,operation:"create",to:"platform"}),v.push(te({amount:`The machine-computed ${k.field}`,fromActor:k.bearer,key:R,kind:"charge",toActor:"platform",trigger:`Collect ${k.field} with settlement creation`})),x.push({label:q(k.field),on:`each ${t.name.replaceAll("_"," ")}`,structure:`${le(k.bps)} of stored ${k.baseField}, computed by the runtime`})}return s.moves=l,c.create=s,{...e,design:[...e.design,`${t.name}: derived amounts are machine-computed from stored source fields before create movements; fixed and tiered rules are refused`],feeLines:x,moneyEvents:v,instrument:{...o,actors:u,derivedAmounts:f,fields:a,actions:c}}}function yr(e,t=[]){let n=gr(e.settlements),r=new Set(e.parties.map(s=>s.name)),o=new Map,a=[];for(let s of t){if(!r.has(s.key)){a.push({message:`repeatable counterparty ${s.key} is not a declared party`,span:s.origin});continue}let l=n.get(s.key);if(!l){a.push({message:`repeatable counterparty ${s.key} is not used by any settlement`,span:s.origin});continue}if(l!==s.role){a.push({message:`repeatable counterparty ${s.key} declares role ${s.role}, but its settlement uses role ${l}`,span:s.origin});continue}if(s.label.trim().length===0||s.label.length>160){a.push({message:`repeatable counterparty ${s.key} label must contain 1 through 160 characters`,span:s.origin});continue}if(!Number.isInteger(s.minCount)||!Number.isInteger(s.maxCount)||s.minCount<1||s.maxCount>1e4){a.push({message:`repeatable counterparty ${s.key} counts must be integers from 1 through 10000`,span:s.origin});continue}if(s.minCount>s.maxCount){a.push({message:`repeatable counterparty ${s.key} has minCount ${s.minCount} above maxCount ${s.maxCount}`,span:s.origin});continue}if(o.has(s.key)){a.push({message:`repeatable counterparty ${s.key} is declared twice`,span:s.origin});continue}o.set(s.key,s)}return{actors:[...e.parties.filter(s=>n.has(s.name)).map(s=>{let l=o.get(s.name);return l?{key:l.key,label:l.label,maxCount:l.maxCount,minCount:l.minCount,role:l.role}:{key:s.name,label:q(s.name),maxCount:1,minCount:1,role:n.get(s.name)}}),{key:"platform",label:"Platform",maxCount:1,minCount:1,role:"platform"}],issues:a}}function hr(e,t){let n=[],r=new Map;for(let l of e){if(typeof l.key!="string")continue;let u=Array.isArray(l.amountDependencies)?l.amountDependencies.filter(f=>typeof f=="string"):[];r.set(l.key,u)}for(let[l,u]of r)for(let f of u){if(f===l){n.push({message:`money event ${l} cannot depend on itself`,span:t});continue}r.has(f)||n.push({message:`money event ${l} depends on missing money event ${f}`,span:t})}let o=new Set,a=new Set,c=new Set,s=l=>{if(!(a.has(l)||c.has(l))){if(o.has(l)){c.add(l);return}o.add(l);for(let u of r.get(l)??[])r.has(u)&&s(u),c.has(u)&&c.add(l);o.delete(l),a.add(l)}};for(let l of r.keys())s(l);return c.size>0&&n.push({message:`money event amount dependencies contain a cycle through ${[...c].sort().join(", ")}`,span:t}),n}function gr(e){let t=new Set,n=new Set,r=new Set,o=new Set;for(let s of e)switch(s.archetype){case"held_payment":case"captured_payment":case"instant_transfer":case"metered":t.add(s.payer),n.add(s.payee);break;case"scheduled":t.add(s.payer),n.add(s.payee),s.mode==="obligation"&&(t.add(s.debtor),s.advanceTo&&n.add(s.advanceTo));break;case"premium_forward":t.add(s.payer),r.add(s.carrier);break;case"deposit":t.add(s.payer),o.add(s.holder);break;case"advance":t.add(s.funder),n.add(s.advanced);break;case"pooled_split":t.add(s.payer);for(let l of s.shares)n.add(l.to);break;case"settlement_batch":t.add(s.settlementAccount),n.add(s.payoutDestination);break;case"funding_round":t.add(s.contributor),n.add(s.beneficiary);break;case"weighted_distribution":t.add(s.source),n.add(s.recipient);break;case"credit_facility":t.add(s.lender),n.add(s.borrower),n.add(s.drawDestination);break;case"recurring_collection":break;case"conditional_disbursement":t.add(s.source),n.add(s.destination);break;case"rotating_pool":for(let l of s.members)t.add(l),n.add(l);s.guarantor&&t.add(s.guarantor);break;case"swap":t.add(s.sides[0].party),n.add(s.sides[1].party);break}let a=new Map,c=(s,l)=>{for(let u of s)a.has(u)||a.set(u,l)};return c(t,"payer"),c(r,"provider"),c(o,"holder"),c(n,"beneficiary"),a}var $r={advance:"credit",captured_payment:"escrow",conditional_disbursement:"marketplace",credit_facility:"credit",deposit:"escrow",funding_round:"credit",held_payment:"escrow",instant_transfer:"marketplace",metered:"recurring_billing",pooled_split:"marketplace",premium_forward:"insurance",recurring_collection:"recurring_billing",rotating_pool:"recurring_billing",scheduled:"recurring_billing",settlement_batch:"marketplace",swap:"escrow",weighted_distribution:"marketplace"};function br(e){let t=new Set(e.map(n=>n.archetype==="scheduled"&&n.mode==="obligation"?"credit":$r[n.archetype]));return t.size>0?[...t]:["escrow"]}function wr(e,t,n){let r=e.name,[o,a]=e.sides,c=e.dispute?.window,s=c!==void 0&&c.days>0,l=Y(`${r}_clawback_maturity`),u=[],f=(re,ee,U,F,M,ce)=>{let ae=Y(`${r}_${re}`);return u.push(te({amount:U,fromActor:F,key:ae,kind:ee,toActor:M,trigger:ce})),ae},v=f("side_a_fund","charge",`The full ${o.amount.name}`,o.party,"escrow",`Fund ${o.amount.name} into the shared trade escrow`),x=f("side_b_fund","charge",`The full ${a.amount.name}`,a.party,"escrow",`Fund ${a.amount.name} into the shared trade escrow`),k=f("side_a_release","payout",`The full ${o.amount.name}`,"escrow",a.party,`Release ${o.amount.name} across to ${a.party.replaceAll("_"," ")}`),T=f("side_b_release","payout",`The full ${a.amount.name}`,"escrow",o.party,`Release ${a.amount.name} across to ${o.party.replaceAll("_"," ")}`),R=f("side_a_cancel","refund",`The full ${o.amount.name}`,"escrow",o.party,`Return ${o.amount.name} to its original funder on cancellation`),C=f("side_b_cancel","refund",`The full ${a.amount.name}`,"escrow",a.party,`Return ${a.amount.name} to its original funder on cancellation`),Q=s?f("side_a_clawback","refund",`The full ${o.amount.name}`,"escrow",o.party,`Return ${o.amount.name} after the whole trade is disputed`):void 0,B=s?f("side_b_clawback","refund",`The full ${a.amount.name}`,"escrow",a.party,`Return ${a.amount.name} after the whole trade is disputed`):void 0,W={[o.amount.name]:Z(`Side A amount in ${o.amount.currency} minor units, held against the whole trade`),[a.amount.name]:Z(`Side B amount in ${a.amount.currency} minor units, held against the whole trade`),...s?{clawbackAt:{type:"date?",desc:`Machine-owned end of the ${c?.raw??"fixed"} whole-trade dispute window`}}:{}},H=[{amount:o.amount.name,from:o.party,key:"side_a_principal",moneyEvent:v,operation:"create",to:"escrow"},{amount:a.amount.name,from:a.party,key:"side_b_principal",moneyEvent:x,operation:"create",to:"escrow"}],ue=[],X=[];for(let[re,ee]of e.sides.entries()){if(!ee.fee)continue;let U=Qe(ee.fee,re===0?"sideAServiceFeeAmount":"sideBServiceFeeAmount");for(let M of rn(ee.fee.rule))W[M.name]=Z(`Immutable exact ${ee.party.replaceAll("_"," ")} service fee in ${M.currency} minor units`);ee.fee.rule.kind!=="exact"&&(W[U]=Z(`Machine-owned ${ee.party.replaceAll("_"," ")} service fee computed from ${ee.amount.name}`)),X.push(en(ee.fee,ee.amount.name,U));let F=f(re===0?"side_a_service_fee":"side_b_service_fee","charge",`${he(ee.fee.rule)} of ${ee.amount.name}, on top`,ee.party,"platform",`Collect the ${ee.party.replaceAll("_"," ")} custody fee at funding`);H.push({amount:U,from:ee.party,key:re===0?"side_a_service_fee":"side_b_service_fee",moneyEvent:F,operation:"create",to:"platform"}),ue.push({label:`${q(ee.party)} custody fee`,on:`each funded ${r.replaceAll("_"," ")}`,structure:`${he(ee.fee.rule)}, on top`})}let $=[{amount:o.amount.name,from:"escrow",key:"side_a",moneyEvent:k,operation:s?"reserve":"create",to:a.party},{amount:a.amount.name,from:"escrow",key:"side_b",moneyEvent:T,operation:s?"reserve":"create",to:o.party}],D={abandon:{from:["created"],requiresDrainedAccount:{path:"refs.escrowAccountId"},summary:"Abandon the trade before its atomic funding batch",to:"abandoned"},cancel:{from:["funded"],moves:[{amount:o.amount.name,from:"escrow",key:"side_a_refund",moneyEvent:R,operation:"create",to:o.party},{amount:a.amount.name,from:"escrow",key:"side_b_refund",moneyEvent:C,operation:"create",to:a.party}],summary:"Cancel and return both trade principals atomically",to:"cancelled"},create:{summary:`Create a ${q(r).toLowerCase()} atomic trade`,to:"created"},fund:{from:["created"],moves:H,summary:"Fund both trade sides and collect on-top fees atomically",to:"funded"},release:{from:["funded"],moves:$,port:{allowed:[...t.allowed]},...s?{setsAt:{field:"clawbackAt",offset:c?.raw}}:{},summary:s?"Reserve both cross-payments for the whole-trade clawback window":"Post both cross-payments atomically",to:s?"released":"settled"}};s&&e.dispute&&n&&Q&&B&&(D.post={due:{field:"clawbackAt",rule:l},from:["released"],moves:[{key:"side_a",operation:"post",reservation:"release_side_a"},{key:"side_b",operation:"post",reservation:"release_side_b"}],summary:"Post both trade reservations when the clawback window matures",to:"settled"},D.dispute={deadline:{field:"clawbackAt"},from:["released"],moves:[{key:"side_a_void",operation:"void",reason:"Whole trade disputed inside the clawback window",reservation:"release_side_a"},{key:"side_b_void",operation:"void",reason:"Whole trade disputed inside the clawback window",reservation:"release_side_b"},{amount:o.amount.name,clawbackOf:"release_side_a",from:"escrow",key:"side_a_refund",moneyEvent:Q,operation:"create",to:o.party},{amount:a.amount.name,clawbackOf:"release_side_b",from:"escrow",key:"side_b_refund",moneyEvent:B,operation:"create",to:a.party}],port:{allowed:[...n.allowed]},summary:"Void both reservations, then refund both principals atomically",to:"clawed_back"});let K=[{allowedActors:[...t.allowed],detail:`${t.allowed.map(q).join(" or ")} confirms the whole exchange through ${t.name}`,dueDriven:!1,enforcement:"tenant_app",gatesEvent:k,key:Y(`${r}_${t.name}_gate`),kind:"release_condition",label:`Whole trade released through ${t.name}`,tenantTunable:!1}];return s&&e.dispute&&n&&K.push({allowedActors:[],detail:`Both pending trade payouts post together at the immutable ${e.dispute.window.raw} cutoff`,dueDriven:!0,enforcement:"platform",gatesEvent:null,key:l,kind:"deadline",label:"Whole trade posts when its clawback window matures",tenantTunable:!1},{allowedActors:[...n.allowed],detail:`${n.allowed.map(q).join(" or ")} may dispute only before the immutable cutoff`,dueDriven:!1,enforcement:"tenant_app",gatesEvent:Q??null,key:Y(`${r}_${n.name}_gate`),kind:"release_condition",label:`Whole trade disputed through ${n.name}`,tenantTunable:!1}),{design:[`${r}: exactly two parties, two same-currency principals, one escrow, and one linked batch per phase`,s?`${r}: ${c?.raw} whole-trade clawback; release reserves both legs, then exactly one grouped post or grouped void-and-refund wins`:`${r}: no clawback window; release posts both legs directly and exposes no pending or dispute surface`],feeLines:ue,moneyEvents:u,instrument:{actors:{[o.party]:"payer",[a.party]:"beneficiary",...ue.length>0?{platform:"party"}:{}},desc:`Atomic swap between ${o.party.replaceAll("_"," ")} and ${a.party.replaceAll("_"," ")}; half-funded and half-released states do not exist`,distinctParties:!0,escrow:!0,...X.length>0?{feeRules:X}:{},fields:W,id:r,summary:`Two-party atomic trade between ${o.party.replaceAll("_"," ")} and ${a.party.replaceAll("_"," ")}`,title:q(r),actions:D},rules:K,settlement:{name:r,pieces:[{bps:1e4,cancelTo:o.party,field:o.amount.name,origin:o.amount.origin,releaseTo:a.party},{bps:1e4,cancelTo:a.party,field:a.amount.name,origin:a.amount.origin,releaseTo:o.party}]}}}function vr(e,t,n,r){let o=e.fees.find(s=>s.bearer===e.payer),a=e.fees.find(s=>s.bearer===e.payee),c=yt({amount:e.amount,carveTo:n,deadlineField:e.releaseDeadlineField,fundEventKind:"charge",fundTrigger:(s,l)=>`Fund piece ${s+1} of ${l} into escrow`,name:e.name,onCancel:e.onCancel,payee:e.payee,payeeFeeBps:a?.rule.kind==="bps"?a.rule.bps:0,payeeFeeRule:a,payer:e.payer,payerFeeBps:o?.rule.kind==="bps"?o.rule.bps:void 0,payerFeeRule:o,port:t,releaseWord:"release"},r);if(c)return{...c,feeLines:[...o?[{label:`${q(e.payer)} service fee`,on:`each funded ${e.name.replaceAll("_"," ")}`,structure:`${he(o.rule)} of the ${e.amount.name}, on top`}]:[],...a?[{label:`${q(e.payee)} fee`,on:`each released ${e.name.replaceAll("_"," ")}`,structure:`${he(a.rule)} of the ${e.amount.name}, deducted from the payout`}]:[]],instrument:{...c.instrument,desc:`Held payment: the ${e.payer.replaceAll("_"," ")} funds ${e.amount.name} into this settlement's own escrow; ${t.allowed.map(s=>s.replaceAll("_"," ")).join(" or ")} confirms through ${t.name} to release${n?` to the ${n.replaceAll("_"," ")}, whose advance the ${e.payee.replaceAll("_"," ")} repays out of it`:""}`,summary:`Escrow-held payment from ${e.payer.replaceAll("_"," ")} to ${e.payee.replaceAll("_"," ")}`}}}function kr(e,t,n,r){let o=yt({amount:e.amount,carveTo:void 0,deadlineField:void 0,fundEventKind:"premium",fundTrigger:(u,f)=>f===1?"Collect the premium into escrow":`Collect premium piece ${u+1} of ${f} into escrow`,name:e.name,onCancel:e.onCancel,payee:e.carrier,payeeFeeBps:e.commissionBps,payeeFeeRule:void 0,payer:e.payer,payerFeeBps:void 0,payerFeeRule:void 0,port:t,releaseWord:"forward"},r);if(!o)return;let a=o.instrument,c={...a.fields??{}},s={...a.actions??{}},l=[...o.rules];if(e.policyReferenceField&&e.renewalDueField&&e.endorsement&&n){c[e.policyReferenceField]={desc:"Immutable external policy reference recorded with this forward",type:"text"},c[e.renewalDueField]=me("Stored renewal due condition for the forwarded policy"),s[e.endorsement.port]={captureInput:{endorsementEvidenceReference:"evidenceReference"},from:["released"],port:{allowed:n.allowed,fields:{evidenceReference:"text"}},summary:"Record one non-money endorsement from external evidence",to:"endorsed"};let u=Y(`${e.name}_renewal_due`);s.lapse={due:{field:e.renewalDueField,rule:u},from:["released","endorsed"],requiresDrainedAccount:{path:"refs.escrowAccountId"},summary:"Mark the forwarded policy lapsed at its stored renewal due condition",to:"lapsed"},l.push({allowedActors:[],detail:"The stored renewal due condition changes policy state without moving money",dueDriven:!0,enforcement:"platform",gatesEvent:null,key:u,kind:"deadline",label:"Policy lapses at its stored renewal due condition",tenantTunable:!1})}return{...o,design:[`${e.name}: premium forwards to the ${e.carrier.replaceAll("_"," ")} exactly once on ${t.name}; ${le(e.commissionBps)} commission retained by the platform`,...e.policyReferenceField?[`${e.name}: extends premium_forward with stored policy reference, non-money endorsement evidence, and a due-only lapse; renewal creates a new forward`]:[]],feeLines:e.commissionBps>0?[{label:"Platform commission",on:`each bound ${e.name.replaceAll("_"," ")}`,structure:`${le(e.commissionBps)} of the ${e.amount.name}, deducted at forwarding`}]:[],instrument:{...o.instrument,fields:c,actions:s,desc:`Premium forward: the ${e.payer.replaceAll("_"," ")} funds the ${e.amount.name} into this settlement's own escrow; binding through ${t.name} forwards it to the ${e.carrier.replaceAll("_"," ")} exactly once, minus the platform commission`,summary:`Premium held for the ${e.carrier.replaceAll("_"," ")} until the policy binds`},rules:l}}function yt(e,t){let n=e.amount.name,r=ht(e),o=r.length===1?r.map(F=>({...F,field:n})):r,a=e.name,c=e.carveTo??e.payee,s=c.replaceAll("_"," "),l=e.payerFeeRule?Qe(e.payerFeeRule,"serviceFeeAmount"):void 0,u={[n]:je(e.amount,o.length===1?`The held amount in ${e.amount.currency} minor units, funded and paid out whole`:`The gross held amount in ${e.amount.currency} minor units; the piece fields below partition it exactly`)};for(let[F,M]of o.entries())M.field!==n&&(u[M.field]=Z(gt(M,F,n,e.amount.currency)));if(e.deadlineField&&(u[e.deadlineField]=me(`The date an undecided hold releases to the ${s} on; ${e.port.name} and cancellation decide only before it`)),e.payerFeeRule&&l){for(let F of rn(e.payerFeeRule.rule))u[F.name]=Z(`Immutable exact ${e.payer.replaceAll("_"," ")}-side service fee in ${F.currency} minor units`);e.payerFeeRule.rule.kind!=="exact"&&(u[l]=Z(`Machine-owned ${he(e.payerFeeRule.rule)} service fee computed from ${n}; charged on top at funding`))}let f=o.filter(F=>F.releaseTo==="platform"),v=f.length===1?f[0].field:f.length>1?"carvedFeeAmount":void 0;v==="carvedFeeAmount"&&(u.carvedFeeAmount=Z(`Machine-owned total of the ${f.length} carved platform fee pieces`));let x=[...e.payerFeeRule&&l?[en(e.payerFeeRule,n,l)]:[],...e.payeeFeeRule&&v?[en(e.payeeFeeRule,n,v)]:[]],k=[...Ae(n,o.map(F=>F.field)),...v==="carvedFeeAmount"?Ae(v,f.map(F=>F.field)):[]],T=o.map((F,M)=>`fund_piece_${M+1}`);e.payerFeeRule&&T.push("collect_service_fee");let R=o.map((F,M)=>M===0?e.port.name:`${e.releaseWord}_piece_${M+1}`),C=e.onCancel?o.map((F,M)=>M===0?"cancel":`refund_piece_${M+1}`):[],Q=e.deadlineField?`${e.releaseWord}_on_deadline`:void 0,B=Y(`${a}_${e.releaseWord}_deadline`),W=T.length-1,H=Array.from({length:W},(F,M)=>`unfund_piece_${M+1}`);if(!Je(e.name,[...T,...R,...Q?[Q]:[],...C,"abandon",...H],e.port.origin,t))return;let ue=Ie(T,"created","funded","funding"),X=Ie(R,"funded","released","releasing"),$=Ie(C,"funded","cancelled","cancelling"),D=[],K={},re=`${a}_fund`;D.push(te({amount:o.length===1?`The full ${n}`:`The ${n}, funded piece by piece`,fromActor:e.payer,key:re,kind:e.fundEventKind,...o.length>1?{occurrence:"repeatable"}:{},toActor:"escrow",trigger:e.fundTrigger(0,o.length)}));for(let[F,M]of o.entries())K[T[F]]={from:[ue[F]?.from],moneyEvent:re,moves:[{key:"transfer",operation:"create",amount:M.field,from:e.payer,to:"escrow"}],summary:`Fund piece ${F+1} of the held amount into escrow`,to:ue[F]?.to};if(e.payerFeeRule&&l){let F=T.length-1,M=`${a}_service_fee`;D.push(te({amount:`${he(e.payerFeeRule.rule)} of the ${n}, on top`,fromActor:e.payer,key:M,kind:"charge",toActor:"platform",trigger:"Collect the service fee at funding"})),K.collect_service_fee={from:[ue[F]?.from],moneyEvent:M,moves:[{key:"transfer",operation:"create",amount:l,from:e.payer,to:"platform"}],summary:"Collect the payer-side service fee",to:ue[F]?.to}}let ee=new Map;for(let F of o)ee.set(F.releaseTo,(ee.get(F.releaseTo)??0)+1);for(let[F,M]of ee){let ce=o.filter(ae=>ae.releaseTo===F).reduce((ae,ge)=>ae+ge.bps,0);D.push(te({amount:`${le(ce)} of the ${n}`,fromActor:"escrow",key:`${a}_release_${F}`,kind:"payout",...M>1?{occurrence:"repeatable"}:{},toActor:F,trigger:`Release to the ${F.replaceAll("_"," ")}`}))}for(let[F,M]of o.entries())K[R[F]]={...F===0&&e.deadlineField?{deadline:{field:e.deadlineField}}:{},from:[X[F]?.from],moneyEvent:Y(`${a}_release_${M.releaseTo}`),moves:[{key:"transfer",operation:"create",amount:M.field,from:"escrow",to:M.releaseTo}],...F===0?{port:{allowed:[...e.port.allowed],fields:Object.fromEntries(e.port.fields.map(ce=>[ce.name,"text"]))}}:{},summary:F===0?`Confirm through ${e.port.name} and start the ${e.releaseWord} payout`:`${q(e.releaseWord)} piece ${F+1} of the held amount`,to:X[F]?.to};if(Q&&e.deadlineField){let F=o[0];K[Q]={due:{field:e.deadlineField,rule:B},from:[X[0]?.from],moneyEvent:Y(`${a}_release_${F.releaseTo}`),moves:[{key:"transfer",operation:"create",amount:F.field,from:"escrow",to:F.releaseTo}],summary:`Release to the ${F.releaseTo.replaceAll("_"," ")} when ${e.deadlineField} arrives undecided`,to:X[0]?.to}}if(e.onCancel){let F=new Map;for(let M of o){let ce=M.cancelTo;F.set(ce,(F.get(ce)??0)+1)}for(let[M,ce]of F){let ae=o.filter(ge=>ge.cancelTo===M).reduce((ge,ne)=>ge+ne.bps,0);D.push(te({amount:`${le(ae)} of the ${n}`,fromActor:"escrow",key:`${a}_cancel_${M}`,kind:M===e.payer?"refund":"penalty",...ce>1?{occurrence:"repeatable"}:{},toActor:M,trigger:`Return to the ${M.replaceAll("_"," ")} on cancellation`}))}for(let[M,ce]of o.entries())K[C[M]]={...M===0&&e.deadlineField?{deadline:{field:e.deadlineField}}:{},from:[$[M]?.from],moneyEvent:Y(`${a}_cancel_${ce.cancelTo}`),moves:[{key:"transfer",operation:"create",amount:ce.field,from:"escrow",to:ce.cancelTo}],summary:M===0?"Cancel the settlement and start the unwind":`Return piece ${M+1} on cancellation`,to:$[M]?.to}}if(H.length>0){let F=`${a}_abandon`;D.push(te({amount:`The funded pieces of the ${n}, returned exactly`,fromActor:"escrow",key:F,kind:"refund",...H.length>1?{occurrence:"repeatable"}:{},toActor:e.payer,trigger:`Return the held pieces to the ${e.payer.replaceAll("_"," ")} on abandonment`}));for(let[M,ce]of H.entries()){let ae=M+1;K[ce]={from:[`funding_${ae}`,...ae<W?[`abandoning_${ae}`]:[]],moneyEvent:Y(F),moves:[{key:"transfer",operation:"create",amount:o[M].field,from:"escrow",to:e.payer}],summary:`Return piece ${ae} to the ${e.payer.replaceAll("_"," ")} on abandonment`,to:ae===1?"abandoned":`abandoning_${ae-1}`}}}K.abandon={from:["created"],requiresDrainedAccount:{path:"refs.escrowAccountId"},summary:"Abandon the settlement before any money is held",to:"abandoned"},K.create={summary:`Create a ${q(e.name).toLowerCase()} settlement`,to:"created"};let U=[{allowedActors:[...e.port.allowed],detail:`${e.port.allowed.map(q).join(" or ")} confirms through the tenant backend before ${e.deadlineField?`${e.deadlineField}, to decide ahead of it`:"any payout"}`,dueDriven:!1,enforcement:"tenant_app",gatesEvent:Y(`${a}_release_${o[0].releaseTo}`),key:Y(`${a}_${e.port.name}_gate`),kind:"release_condition",label:`${q(e.releaseWord)} decided through ${e.port.name}`,tenantTunable:!1}];return e.deadlineField&&U.push({allowedActors:[],detail:`A hold nobody decided releases to the ${s} on its stored ${e.deadlineField}, exactly once`,dueDriven:!0,enforcement:"platform",gatesEvent:null,key:B,kind:"deadline",label:`Undecided holds release on ${e.deadlineField}`,tenantTunable:!1}),{design:[`${a}: own escrow; ${o.length}-piece partition of ${n} (${o.map(F=>le(F.bps)).join(" + ")}); every exit drains every piece; abandonable before funded (created closes directly, funding states unwind piece by piece to the ${e.payer})`,...e.deadlineField?[`${a}: undecided holds release to the ${c} on ${e.deadlineField}; the port and the cancel decide only before that anchor`]:[],...e.carveTo?[`${a}: the ${e.payee}'s whole release share is carved to the ${e.carveTo}, who financed it; the platform fee and the cancellation split are untouched`]:[],...e.payerFeeRule?[`${a}: ${he(e.payerFeeRule.rule)} ${e.payer} service fee on top, straight to platform at funding`]:[]],feeLines:[],moneyEvents:D,instrument:{actors:{[e.payer]:"payer",[e.payee]:"beneficiary",...e.carveTo?{[e.carveTo]:"party"}:{},platform:"party"},desc:`Held amount from ${e.payer.replaceAll("_"," ")} to ${e.payee.replaceAll("_"," ")}${e.carveTo?`, released to the ${s} against the advance it secures`:""}`,escrow:!0,...x.length>0?{feeRules:x}:{},fields:u,id:e.name,...Ce(k),summary:`Escrow-held amount from ${e.payer.replaceAll("_"," ")}`,title:q(e.name),actions:K},rules:U,settlement:{name:e.name,pieces:o,...e.payerFeeBps!==void 0?{serviceFee:{bps:e.payerFeeBps,field:"serviceFeeAmount"}}:{}}}}function _r(e){let t=e.fees.find(B=>B.bearer===e.payer),n=e.fees.find(B=>B.bearer===e.payee),r=e.amount.name,o=n?.rule.kind==="bps"?n.rule.bps:void 0,a=n&&n.rule.kind!=="bps"?n:void 0,c=a?Qe(a,"carvedFeeAmount"):void 0,s=ht({amount:e.amount,payee:e.payee,payeeFeeBps:o??0}),l=c?[{bps:1e4,field:"netOfCarvedFeeAmount",origin:a?.origin??e.origin,releaseTo:e.payee},{bps:0,field:c,origin:a?.origin??e.origin,releaseTo:"platform"}]:s.length===1?s.map(B=>({...B,field:r})):s,u=e.name,f=t?Qe(t,"serviceFeeAmount"):void 0,v={[r]:je(e.amount,l.length===1?`The amount in ${e.amount.currency} minor units, paid through whole`:`The gross amount in ${e.amount.currency} minor units; the piece fields below partition it exactly`)};for(let[B,W]of l.entries())W.field!==r&&(v[W.field]=Z(a&&W.releaseTo===e.payee?`The remainder of ${r} after the carved platform fee`:a&&W.releaseTo==="platform"?`The carved platform fee selected from ${r}`:gt(W,B,r,e.amount.currency)));for(let B of e.fees)for(let W of rn(B.rule))v[W.name]=je(W,`Immutable exact ${B.bearer.replaceAll("_"," ")} fee in ${W.currency} minor units`);t&&f&&t.rule.kind!=="exact"&&(v[f]=Z(`Machine-owned ${he(t.rule)} service fee computed from ${r}; charged on top`));let x=e.fees.flatMap(B=>{let W=B.position==="carved"?c??l.find(H=>H.releaseTo==="platform")?.field:f;return W?[en(B,r,W)]:[]}),k=l.map((B,W)=>`pay_piece_${W+1}`);t&&k.push("collect_service_fee");let T=Ie(k,"created","paid","paying"),R=[],C={create:{summary:`Create a ${q(u).toLowerCase()} payment`,to:"created"}};for(let[B,W]of l.entries()){let H=`${u}_pay_${B+1}`,ue=a?W.releaseTo===e.payee?`The remainder of ${r} after the carved fee`:`${he(a.rule)} selected from ${r}`:`${le(W.bps)} of the ${r}`;R.push(te({amount:ue,fromActor:e.payer,key:H,kind:"charge",toActor:W.releaseTo,trigger:`Pay piece ${B+1} straight to the ${W.releaseTo.replaceAll("_"," ")}`})),C[k[B]]={from:[T[B]?.from],moneyEvent:H,moves:[{key:"transfer",operation:"create",amount:W.field,from:e.payer,to:W.releaseTo}],summary:`Pay piece ${B+1} of the amount through`,to:T[B]?.to}}if(t&&f){let B=k.length-1,W=`${u}_service_fee`;R.push(te({amount:`${he(t.rule)} of the ${r}, on top`,fromActor:e.payer,key:W,kind:"charge",toActor:"platform",trigger:"Collect the service fee with the payment"})),C.collect_service_fee={from:[T[B]?.from],moneyEvent:W,moves:[{key:"transfer",operation:"create",amount:f,from:e.payer,to:"platform"}],summary:"Collect the payer-side service fee",to:T[B]?.to}}let Q=t!==void 0||l.some(B=>B.releaseTo==="platform");return{design:[a?`${u}: instant pass-through; ${r} partitions into the selected carved fee and its exact remainder; no custody`:`${u}: instant pass-through; ${l.length}-piece partition of ${r} (${l.map(B=>le(B.bps)).join(" + ")}); no custody`],feeLines:[...t?[{label:`${q(e.payer)} service fee`,on:`each ${u.replaceAll("_"," ")}`,structure:`${he(t.rule)} of the ${r}, on top`}]:[],...n?[{label:`${q(e.payee)} fee`,on:`each ${u.replaceAll("_"," ")}`,structure:`${he(n.rule)} of the ${r}, deducted from the payout`}]:[]],moneyEvents:R,instrument:{actors:{[e.payer]:"payer",[e.payee]:"beneficiary",...Q?{platform:"party"}:{}},desc:`Instant transfer: the ${e.payer.replaceAll("_"," ")} pays ${r} straight through to the ${e.payee.replaceAll("_"," ")}, no custody`,...x.length>0?{feeRules:x}:{},fields:v,id:u,...Ce(Ae(r,l.map(B=>B.field))),summary:`Instant payment from ${e.payer.replaceAll("_"," ")} to ${e.payee.replaceAll("_"," ")}`,title:q(u),actions:C},rules:[],settlement:{name:u,pieces:l,...t?.rule.kind==="bps"&&f?{serviceFee:{bps:t.rule.bps,field:f}}:{}}}}function Ar(e,t,n,r){let o=e.name,a=e.amount.name,c="authorize_reservation",s="capturedAmount",l="reversalUntil",f=["authorize",...["capture","capture_more"],"settle","void","expire","settle_on_expiry",e.correction.port,e.externalReversal.port];if(!Je(o,f,e.origin,r))return;let v=Y(`${o}_reserve`),x=Y(`${o}_capture`),k=Y(`${o}_correction`),T=Y(`${o}_external_reversal`),R=Y(`${o}_reservation_expiry`),C=H=>({amount:"captureAmount",capture:{[s]:"postedAmount"},key:"post",operation:"post",...H?{partialOnly:!0}:{},reservation:c}),Q=()=>({amount:`refs.${s}`,clawbackOf:c,from:e.payee,key:"transfer",operation:"create",to:e.payer}),B={create:{summary:`Create a ${q(o).toLowerCase()}`,to:"created"},authorize:{from:["created"],moneyEvent:v,moves:[{amount:a,from:e.payer,key:"reservation",operation:"reserve",to:e.payee}],summary:`Reserve the ${a} until ${e.reserveUntilField}`,to:"authorized"},capture:{deadline:{field:e.reserveUntilField},from:["authorized"],moneyEvent:x,moves:[C(!0)],summary:"Post one strict partial capture slice",to:"partially_captured"},capture_more:{deadline:{field:e.reserveUntilField},from:["partially_captured"],moneyEvent:x,moves:[C(!0)],summary:"Post another strict partial capture slice",to:"partially_captured"},settle:{deadline:{field:e.reserveUntilField},from:["authorized","partially_captured"],moneyEvent:x,moves:[{capture:{[s]:"postedAmount"},key:"post",operation:"post",reservation:c}],summary:"Post the full reserved remainder and settle",setsAt:{field:l,offset:e.externalReversal.window.raw},to:"settled"},void:{from:["authorized"],moves:[{key:"void",operation:"void",reason:"Reservation voided before any capture",reservation:c}],summary:"Release an entirely uncaptured reservation",to:"voided"},expire:{due:{field:e.reserveUntilField,rule:R},from:["authorized"],moves:[{key:"void",operation:"void",reason:"Uncaptured reservation expired",reservation:c}],summary:"Release an uncaptured reservation at expiry",to:"expired"},settle_on_expiry:{due:{field:e.reserveUntilField,rule:R},from:["partially_captured"],moves:[{key:"void",operation:"void",reason:"Uncaptured remainder released at expiry",reservation:c}],summary:"Release the uncaptured remainder and settle captured slices",setsAt:{field:l,offset:e.externalReversal.window.raw},to:"settled"},[e.correction.port]:{from:["settled"],moneyEvent:k,moves:[Q()],port:{allowed:t.allowed},summary:"Return the full captured amount on payee correction",to:"corrected"},[e.externalReversal.port]:{captureInput:{externalReference:"externalReference"},deadline:{field:l},from:["settled"],moneyEvent:T,moves:[Q()],port:{allowed:n.allowed,fields:{externalReference:"text"}},summary:"Return the full captured amount on an external reversal",to:"reversed"}},W=[te({amount:`The full ${a}`,fromActor:e.payer,key:v,kind:"hold",toActor:e.payee,trigger:`Reserve ${a} until ${e.reserveUntilField}`}),te({amount:`Each posted slice, never more than the remaining ${a}`,amountDependency:{kind:"bounded_by_reference",reference:v},fromActor:e.payer,key:x,kind:"payout",occurrence:"repeatable",toActor:e.payee,trigger:"Post a capture slice or the final remainder"}),te({amount:"100% of the cumulative captured amount",amountDependency:{bps:1e4,kind:"percent_of_reference",reference:x},fromActor:e.payee,key:k,kind:"refund",toActor:e.payer,trigger:"Apply one full payee correction"}),te({amount:"100% of the cumulative captured amount",amountDependency:{bps:1e4,kind:"percent_of_reference",reference:x},fromActor:e.payee,key:T,kind:"refund",toActor:e.payer,trigger:"Apply one full externally decided reversal"})];return{design:[`${o}: reserve ${a} until ${e.reserveUntilField}; capture in strict partial slices; post the remainder to settle; expiry releases only the uncaptured remainder`,`${o}: correction and external reversal each return the full captured amount once; insufficient payee funds reject the move instead of creating a negative position`],feeLines:[],moneyEvents:W,instrument:{actors:{[e.payer]:"payer",[e.payee]:"beneficiary"},desc:"Payer reservation captured by the payee in slices within a fixed window",fields:{[a]:Z(`Maximum captured amount in ${e.amount.currency} minor units`),[e.reserveUntilField]:me("Reservation expiry that releases any uncaptured remainder"),[l]:{desc:"Machine-owned external reversal cutoff anchored when settlement completes",type:"date?"}},id:o,summary:`Capture reservation from ${e.payer.replaceAll("_"," ")} to ${e.payee.replaceAll("_"," ")}`,title:q(o),actions:B},rules:[{allowedActors:[],detail:`At ${e.reserveUntilField}, the platform releases the uncaptured remainder and preserves any posted slices`,dueDriven:!0,enforcement:"platform",gatesEvent:null,key:R,kind:"deadline",label:`Uncaptured remainder releases on ${e.reserveUntilField}`,tenantTunable:!1},{allowedActors:[...t.allowed],detail:"The payee may return the full captured amount once",dueDriven:!1,enforcement:"tenant_app",gatesEvent:k,key:Y(`${o}_${e.correction.port}_gate`),kind:"release_condition",label:"Full correction confirmed through the tenant backend",tenantTunable:!1},{allowedActors:[...n.allowed],detail:`A confirmed external decision may reverse the full captured amount within ${e.externalReversal.window.raw}; timeout moves nothing`,dueDriven:!1,enforcement:"tenant_app",gatesEvent:T,key:Y(`${o}_${e.externalReversal.port}_gate`),kind:"release_condition",label:"External reversal confirmed through the tenant backend",tenantTunable:!1}],settlement:{name:o,pieces:[]}}}function xr(e,t,n){let r=e.name,o=`${r}_capture_entry`,a=`${r}_credit_adjustment`,c=`${r}_debit_adjustment`,s=`${r.replaceAll(/_([a-z])/g,(T,R)=>R.toUpperCase())}Id`,l=Y(`${r}_payout`),u=Y(`${r}_close`);if(!Je(r,["close","calculate","approve","instruct","reconcile",e.payoutAcknowledgement.port],e.origin,n))return;let f={[s]:{match:{"fields.currency":"fields.currency"},statuses:["open"]}},v={desc:"One gross capture entry linked to an open payout batch",fields:{amount:Z("Gross captured amount in minor units"),currency:{desc:"ISO 4217 currency shared with the payout batch",type:"currency"},[s]:{desc:"Open batch this capture entry accrues into",type:`ref:${r}`},[e.sourceCaptureReferenceField]:{desc:"Immutable source capture reference",type:"text"}},id:o,summary:"Gross capture lineage entry",title:`${q(r)} Capture Entry`,actions:{create:{requires:f,summary:"Create a capture lineage entry on an open batch",to:"created"},accrue:{from:["created"],requires:f,summary:"Accrue the capture entry into the open batch",to:"accrued"}}},x=(T,R)=>({desc:`One ${R} adjustment linked to an open payout batch; closed batches stay unchanged`,fields:{amount:Z(`${q(R)} adjustment amount in minor units`),currency:{desc:"ISO 4217 currency shared with the payout batch",type:"currency"},adjustmentReference:{desc:"Immutable explicit adjustment reference",type:"text"},[s]:{desc:"Open batch this adjustment applies to",type:`ref:${r}`},[e.externalReversalReferenceField]:{desc:"Optional externally decided reversal reference",type:"text?"},[e.feeReferenceField]:{desc:"Optional fee entry reference",type:"text?"},[e.sourceCaptureReferenceField]:{desc:"Original capture reference that this adjustment corrects",type:"text"}},id:T,summary:`${q(R)} adjustment with capture lineage`,title:`${q(r)} ${q(R)} Adjustment`,actions:{create:{requires:f,summary:`Create a ${R} adjustment on an open batch`,to:"created"},adjust:{from:["created"],requires:f,summary:`Apply the ${R} adjustment to the open batch`,to:"applied"},correct:{from:["created"],requires:f,summary:"Record a later correction on this open batch instead of changing the closed source batch",to:"applied"}}}),k={create:{...e.cadence?{setsAt:{field:e.closeTriggerField,offset:e.cadence.raw}}:{},summary:`Open a ${q(r).toLowerCase()}`,to:"open"},close:{due:{field:e.closeTriggerField,rule:u},from:["open"],summary:"Freeze the batch and stop all new entries",to:"closed"},calculate:{from:["closed"],signedSum:{amountRef:"netPayable",onNegative:"refuse",onZero:"refuse",sources:[{amountField:"amount",instrumentId:o,refField:s,sign:"add",statuses:["accrued"],subtotalRef:"grossCaptureAmount"},{amountField:"amount",instrumentId:a,refField:s,sign:"add",statuses:["applied"],subtotalRef:"creditAdjustmentAmount"},{amountField:"amount",instrumentId:c,refField:s,sign:"subtract",statuses:["applied"],subtotalRef:"debitAdjustmentAmount"}]},summary:"Prove and freeze the one signed net payable amount",to:"calculated"},approve:{from:["calculated"],summary:"Approve the frozen payable without recomputing it",to:"approved"},instruct:{from:["approved"],moneyEvent:l,payout:{amount:"refs.netPayable",beneficiaryField:e.payoutBeneficiaryReferenceField,beneficiaryPartyField:`${de(e.payoutDestination)}AccountId`,capture:"payoutId",currencyField:"currency",sourceAccountField:`${de(e.settlementAccount)}AccountId`,speed:"standard"},summary:"Create one idempotent payout from the frozen net payable",to:"instructed"},[e.payoutAcknowledgement.port]:{captureInput:{acknowledgementReference:"acknowledgementReference"},from:["instructed"],port:{allowed:t.allowed,fields:{acknowledgementReference:"text"}},summary:"Record the tenant's payout acknowledgement in the receipt",to:"acknowledged"},reconcile:{from:["instructed","acknowledged"],requiresSettlement:{capture:"settlementEvidenceId",payoutRef:"payoutId"},summary:"Record durable evidence that the payout settled",to:"reconciled"}};return{design:[`${r}: capture entries plus signed adjustments freeze at ${e.closeTriggerField}; calculate persists gross, credit, debit, and net refs; negative or zero net refuses`,`${r}: instruct creates one payout intent for the frozen refs.netPayable; only matched settlement evidence can reconcile it`],extraInstruments:[v,x(a,"credit"),x(c,"debit")],feeLines:[],moneyEvents:[te({amount:"The frozen signed sum of gross capture entries plus credit adjustments minus debit adjustments",fromActor:e.settlementAccount,key:l,kind:"payout",toActor:e.payoutDestination,trigger:"Instruct the approved batch payout exactly once"})],instrument:{actors:{[e.payoutDestination]:"beneficiary",[e.settlementAccount]:"payer"},desc:"Immutable batch of capture lineage and signed adjustments that creates one payout",fields:{[e.closeTriggerField]:me("Date the open batch freezes against later entries"),currency:{desc:"ISO 4217 currency shared by the batch and payout instruction",type:"currency"},[e.payoutBeneficiaryReferenceField]:{desc:"Beneficiary ID for the payout instruction",type:"beneficiary"}},id:r,summary:`Payout batch from ${e.settlementAccount.replaceAll("_"," ")} to ${e.payoutDestination.replaceAll("_"," ")}`,title:q(r),actions:k},rules:[{allowedActors:[],detail:`At ${e.closeTriggerField}, the platform closes the batch and every child reference gate refuses later entries`,dueDriven:!0,enforcement:"platform",gatesEvent:null,key:u,kind:"deadline",label:`Batch freezes on ${e.closeTriggerField}`,tenantTunable:!1}],settlement:{name:r,pieces:[]}}}function Sr(e,t,n,r){let o=e.name,a=e.amount.name;if(!Je(o,["place_deposit",t.name,n.name],e.origin,r))return;let c=`${o}_hold_1`,s=e.claimAmount,l=[te({amount:`The full ${a}`,fromActor:e.payer,key:c,kind:"hold",toActor:e.holder,trigger:`Reserve the ${a} in the ${e.holder.replaceAll("_"," ")}'s favor`})],u={create:{summary:`Create a ${q(o).toLowerCase()}`,to:"created"},place_deposit:{from:["created"],moves:[{key:"reservation",operation:"reserve",amount:a,from:e.payer,to:e.holder}],moneyEvent:c,summary:`Reserve the ${a} against the ${e.payer.replaceAll("_"," ")}'s account`,to:"held"},[t.name]:{...s?{decidedAmount:{boundField:s.boundField,field:s.field,remainderAction:n.name},port:{allowed:[...t.allowed],fields:pt(t)}}:{},from:["held"],moves:[{...s?{amount:s.field}:{},key:"post",operation:"post",...s?{partialOnly:!0}:{},reservation:"place_deposit_reservation"},...s?[{key:"remainder",operation:"void",reason:"Return the unclaimed deposit remainder",reservation:"place_deposit_reservation"}]:[]],summary:`Claim the deposit for the ${e.holder.replaceAll("_"," ")} through ${t.name}`,to:"claimed"},[n.name]:{from:["held"],summary:`Return the deposit to the ${e.payer.replaceAll("_"," ")} through ${n.name}`,to:"returned",moves:[{key:"void",operation:"void",reason:"Deposit returned in full",reservation:"place_deposit_reservation"}]}},f=(v,x)=>({allowedActors:[...v.allowed],detail:`${v.allowed.map(q).join(" or ")} decides through the tenant backend`,dueDriven:!1,enforcement:"tenant_app",gatesEvent:null,key:Y(`${o}_${v.name}_gate`),kind:"release_condition",label:`${x} decided through ${v.name}`,tenantTunable:!1});return{design:[s?`${o}: ${a} held as a reservation on the ${e.payer.replaceAll("_"," ")}'s account; ${s.field} claimed through ${t.name} and its exact remainder returned, or the full amount returned through ${n.name}`:`${o}: ${a} held as a reservation on the ${e.payer.replaceAll("_"," ")}'s account; claimed whole through ${t.name} or returned whole through ${n.name}`],feeLines:[],moneyEvents:l,instrument:{actors:{[e.payer]:"payer",[e.holder]:"beneficiary"},desc:s?`Deposit: the ${a} is reserved against the ${e.payer.replaceAll("_"," ")}'s account in the ${e.holder.replaceAll("_"," ")}'s favor, then ${s.field} is claimed and the exact remainder returned, or the deposit is returned in full`:`Deposit: the ${a} is reserved against the ${e.payer.replaceAll("_"," ")}'s account in the ${e.holder.replaceAll("_"," ")}'s favor, then claimed or returned in full`,fields:{[a]:je(e.amount,`The deposit amount in ${e.amount.currency} minor units, reserved in full and fully accounted on claim or return`)},id:o,summary:`Refundable deposit from ${e.payer.replaceAll("_"," ")} held for ${e.holder.replaceAll("_"," ")}`,title:q(o),actions:u},rules:[f(t,"Claim"),f(n,"Return")],settlement:{name:o,pieces:[]}}}function Sn(e){let t=Math.floor(Number(_n)/e),n=Array.from({length:e},()=>t);return n[0]=Number(_n)-t*(e-1),n}function Ir(e){let t=e.name,n=`${t}_commitment`,r=`${de(t)}Id`,o=Y(`${t}_commit`),a=Y(`${t}_cancel`),c=Y(`${t}_collect`),s=Y(`${t}_refund`),l=Y(`${t}_close`),u=x=>[{check:{amountField:"amount",kind:x,targetField:e.target.name},instrumentId:n,over:"children",refField:r,statuses:["committed"]}],f=x=>({[r]:{bind:{currency:"fields.currency",[`${de(e.beneficiary)}AccountId`]:`fields.${de(e.beneficiary)}AccountId`},statuses:x}}),v=x=>({[r]:{match:{"fields.currency":"fields.currency",[`fields.${de(e.beneficiary)}AccountId`]:`fields.${de(e.beneficiary)}AccountId`},statuses:x}});return{design:[`${t}: reuses the catalog funding round and commitment mechanism; the parent lock caps committed rows by target and contributor count`,`${t}: the stored close anchor chooses threshold activation or failure; each commitment then moves whole from its own custody`],extraInstruments:[{actors:{[e.beneficiary]:"beneficiary",[e.contributor]:"payer"},desc:`One whole commitment linked to ${t}`,escrow:!0,fields:{amount:Z("One whole commitment amount"),currency:{desc:"Currency derived from the funding round",type:"currency"},[r]:{desc:`The exact ${t}`,type:`ref:${t}`}},id:n,summary:`Whole commitment to ${t}`,title:`${q(t)} Commitment`,actions:{create:{moneyEvent:o,moves:[{amount:"amount",from:e.contributor,key:"commit",operation:"create",to:"escrow"}],requires:f(["open"]),requiresExposure:[{amountField:"amount",anchorField:r,capField:e.target.name,capOnAnchor:!0,childInstrumentId:n,statuses:["committed"]}],summary:"Store one whole commitment without exceeding the round target",to:"committed"},cancel:{from:["committed"],moneyEvent:a,moves:[{amount:"amount",from:"escrow",key:"cancel",operation:"create",to:e.contributor}],requires:v(["open"]),summary:"Cancel one commitment while the round is open",to:"cancelled"},collect:{from:["committed"],moneyEvent:c,moves:[{amount:"amount",from:"escrow",key:"collect",operation:"create",to:e.beneficiary}],requires:v(["active"]),summary:"Collect one successful commitment whole",to:"collected"},refund:{from:["committed"],moneyEvent:s,moves:[{amount:"amount",from:"escrow",key:"refund",operation:"create",to:e.contributor}],requires:v(["failed"]),summary:"Refund one failed-round commitment whole",to:"refunded"}}}],generatedPrefixInstrumentIds:[n],feeLines:[],moneyEvents:[te({amount:"One stored commitment",fromActor:e.contributor,key:o,kind:"charge",occurrence:"repeatable",toActor:"escrow",trigger:"Create one target-capped commitment"}),te({amount:"One stored commitment whole",fromActor:"escrow",key:a,kind:"refund",occurrence:"repeatable",toActor:e.contributor,trigger:"Cancel before close"}),te({amount:"One stored commitment whole",fromActor:"escrow",key:c,kind:"payout",occurrence:"repeatable",toActor:e.beneficiary,trigger:"Collect after threshold close"}),te({amount:"One stored commitment whole",fromActor:"escrow",key:s,kind:"refund",occurrence:"repeatable",toActor:e.contributor,trigger:"Refund after failed close"})],instrument:{actors:{[e.beneficiary]:"beneficiary"},aggregateInvariants:[{childField:"amount",childInstrumentId:n,childRefField:r,childStatuses:["committed"],parentField:e.target.name},{count:!0,childInstrumentId:n,childRefField:r,childStatuses:["committed"],parentField:"maxContributors"}],desc:"All-or-nothing aggregate funding threshold",fields:{currency:{desc:`Currency fixed to ${e.target.currency}`,type:"currency"},[e.target.name]:Z(`Funding target in ${e.target.currency} minor units`),[e.closeByField]:me("Stored close anchor"),maxContributors:{desc:`Exactly ${e.maxContributors} admitted contributors`,type:`const:${e.maxContributors}`}},id:t,summary:`Threshold funding round for ${e.beneficiary.replaceAll("_"," ")}`,title:q(t),actions:{create:{summary:"Open the funding round",to:"open"},activate:{due:{field:e.closeByField,rule:l},from:["open"],requiresAggregate:u("sum_at_least"),summary:"Activate when commitments meet the target",to:"active"},fail:{due:{field:e.closeByField,rule:l},from:["open"],requiresAggregate:u("sum_below"),summary:"Fail when commitments remain below target",to:"failed"},close:{from:["active"],requiresAggregate:[{check:{kind:"all_in"},instrumentId:n,over:"children",refField:r,statuses:["cancelled","collected"]}],summary:"Settle after every admitted row is collected or was cancelled before activation",to:"settled"}}},rules:[{allowedActors:[],detail:"The stored close anchor compares committed rows with the target",dueDriven:!0,enforcement:"platform",gatesEvent:null,key:l,kind:"deadline",label:"Round closes against its stored threshold",tenantTunable:!1}],settlement:{name:t,pieces:[]}}}function Pr(e,t){let n=e.name,r=`${n}_entitlement`,o=`${de(n)}Id`,a=Y(`${n}_payout`),c=s=>({[o]:{bind:{currency:"fields.currency",[`${de(e.source)}AccountId`]:`fields.${de(e.source)}AccountId`},statuses:s}});return{design:[`${n}: reuses the catalog largest-remainder distribution; the evidence port freezes the claimant set before any payout`],extraInstruments:[{actors:{[e.recipient]:"beneficiary",[e.source]:"payer"},desc:`One frozen weighted entitlement in ${n}`,fields:{currency:{desc:"Currency derived from the distribution",type:"currency"},[o]:{desc:`The exact ${n}`,type:`ref:${n}`},[e.weight.name]:Z("Stored non-negative entitlement weight")},id:r,summary:`Frozen entitlement in ${n}`,title:`${q(n)} Entitlement`,actions:{create:{requires:c(["open"]),summary:"Record one entitlement before snapshot",to:"recorded"},payout:{distribute:{amountRef:"payoutShare",onZero:"skip_steps",pool:{from:"parent",path:`fields.${e.amount.name}`},refField:o,statuses:["recorded","paid"],weightField:e.weight.name},from:["recorded"],moneyEvent:a,moves:[{amount:"refs.payoutShare",from:e.source,key:"payout",operation:"create",to:e.recipient}],requires:{[o]:{match:{"fields.currency":"fields.currency",[`fields.${de(e.source)}AccountId`]:`fields.${de(e.source)}AccountId`},statuses:["snapshotted"]}},summary:"Pay the deterministic largest-remainder share once",to:"paid"}}}],generatedPrefixInstrumentIds:[r],feeLines:[],moneyEvents:[te({amount:"A deterministic largest-remainder share of the stored pool",fromActor:e.source,key:a,kind:"payout",occurrence:"repeatable",toActor:e.recipient,trigger:"Pay one frozen entitlement"})],instrument:{actors:{[e.source]:"payer"},aggregateInvariants:[{count:!0,childInstrumentId:r,childRefField:o,childStatuses:["recorded","paid"],parentField:"maxRecipients"}],desc:"Evidence-frozen weighted distribution",fields:{currency:{desc:`Currency fixed to ${e.amount.currency}`,type:"currency"},[e.amount.name]:Z(`Distribution pool in ${e.amount.currency} minor units`),[e.recordAtField]:me("Stored record date"),maxRecipients:{desc:`Exactly ${e.maxRecipients} frozen entitlement rows`,type:`const:${e.maxRecipients}`}},id:n,summary:"Frozen largest-remainder distribution",title:q(n),actions:{create:{summary:"Open entitlement recording",to:"open"},[e.snapshot.port]:{captureInput:{snapshotEvidenceReference:"evidenceReference"},from:["open"],port:{allowed:t.allowed,fields:{evidenceReference:"text"}},summary:"Freeze the entitlement set from stored evidence",to:"snapshotted"}}},rules:[],settlement:{name:n,pieces:[]}}}function Cr(e){let t=e.name,n=`${t}_draw`,r=`${de(t)}Id`,o=`${de(e.obligation.settlement)}Id`,a=Y(`${t}_draw`),c=Y(`${t}_expiry`),s=e.availabilityPolicy==="revolving"?["drawn"]:["drawn","resolved"];return{design:[`${t}: owns reusable draw capacity only; ${e.obligation.settlement} remains the sole repayment and delinquency owner`],extraInstruments:[{actors:{[e.drawDestination]:"beneficiary",[e.lender]:"payer"},desc:`One capacity-capped draw linked to ${e.obligation.settlement}`,fields:{amount:Z("One draw amount"),currency:{desc:"Currency derived from the facility",type:"currency"},[r]:{desc:`The exact ${t}`,type:`ref:${t}`},[o]:{desc:"The sole repayment obligation",type:`ref:${e.obligation.settlement}`}},id:n,summary:`Draw from ${t}`,title:`${q(t)} Draw`,actions:{create:{moneyEvent:a,moves:[{amount:"amount",from:e.lender,key:"draw",operation:"create",to:e.drawDestination}],requires:{[r]:{bind:{currency:"fields.currency",[`${de(e.drawDestination)}AccountId`]:`fields.${de(e.drawDestination)}AccountId`,[`${de(e.lender)}AccountId`]:`fields.${de(e.lender)}AccountId`},statuses:["active"]},[o]:{statuses:["active"],unique:!0}},requiresExposure:[{amountField:"amount",anchorField:r,capField:e.limit.name,capOnAnchor:!0,childInstrumentId:n,statuses:s}],summary:"Create one draw under the locked facility capacity",to:"drawn"},resolve:{from:["drawn"],requires:{[o]:["repaid","written_off"]},summary:"Release revolving capacity only after the linked obligation resolves",to:"resolved"}}}],generatedPrefixInstrumentIds:[n],feeLines:[],moneyEvents:[te({amount:"One draw under the stored facility limit",fromActor:e.lender,key:a,kind:"payout",occurrence:"repeatable",toActor:e.drawDestination,trigger:"Admit one linked draw"})],instrument:{actors:{[e.borrower]:"party",[e.drawDestination]:"beneficiary",[e.lender]:"payer"},desc:"Reusable capacity with repayment delegated to one scheduled obligation",fields:{currency:{desc:`Currency fixed to ${e.limit.currency}`,type:"currency"},[e.limit.name]:Z(`Facility limit in ${e.limit.currency} minor units`),[e.expiresAtField]:me("Stored draw expiry")},id:t,summary:`Draw capacity for ${e.borrower.replaceAll("_"," ")}`,title:q(t),actions:{create:{summary:"Open the facility",to:"active"},freeze:{due:{field:e.expiresAtField,rule:c},from:["active"],summary:"Freeze new draws at expiry",to:"frozen"},close:{from:["active","frozen"],requiresAggregate:[{check:{kind:"all_in"},instrumentId:n,over:"children",refField:r,statuses:["resolved"]}],summary:"Close only when every admitted draw resolved",to:"closed"}}},rules:[{allowedActors:[],detail:"The stored expiry freezes new draws without changing repayment state",dueDriven:!0,enforcement:"platform",gatesEvent:null,key:c,kind:"deadline",label:"Facility freezes at expiry",tenantTunable:!1}],settlement:{name:t,pieces:[]}}}function Er(e,t){let n=e.name,r=`${n}_approved_amount`,o=`${de(n)}Id`,a=Y(`${n}_payout`),c=`${de(e.source)}AccountId`,s=`${de(e.destination)}AccountId`,l={[o]:{match:{"fields.currency":"fields.currency",[`fields.${s}`]:`fields.${s}`,[`fields.${c}`]:`fields.${c}`},statuses:["submitted"]}};return{design:[`${n}: a stored external decision may approve one amount under the cap; recovery requires a separate transfer`],extraInstruments:[{actors:{[e.destination]:"beneficiary",[e.source]:"payer"},desc:`One evidence-gated amount under ${n}`,fields:{amount:Z("Approved amount under the parent cap"),currency:{desc:"Currency derived from the parent cap",type:"currency"},[o]:{desc:`The exact ${n}`,type:`ref:${n}`}},id:r,summary:`Approved amount under ${n}`,title:`${q(n)} Approved Amount`,actions:{create:{requires:{[o]:{bind:{currency:"fields.currency",[s]:`fields.${s}`,[c]:`fields.${c}`},statuses:["submitted"],unique:!0}},summary:"Create one candidate amount under the parent",to:"created"},approve:{captureInput:{decisionEvidenceReference:"evidenceReference"},from:["created"],port:{allowed:t.allowed,fields:{evidenceReference:"text"}},requires:l,requiresExposure:[{amountField:"amount",anchorField:o,capField:e.cap.name,capOnAnchor:!0,childInstrumentId:r,statuses:["approved","paid"]}],summary:"Store one externally approved amount under the cap",to:"approved"},pay:{from:["approved"],moneyEvent:a,moves:[{amount:"amount",from:e.source,key:"payout",operation:"create",to:e.destination}],requires:l,summary:"Pay the stored approved amount once",to:"paid"}}}],generatedPrefixInstrumentIds:[r],feeLines:[],moneyEvents:[te({amount:"The stored approved amount under the cap",fromActor:e.source,key:a,kind:"payout",occurrence:"repeatable",toActor:e.destination,trigger:"Pay one approved amount"})],instrument:{actors:{[e.destination]:"beneficiary",[e.source]:"payer"},desc:"Capped disbursement controlled by stored external evidence",fields:{currency:{desc:`Currency fixed to ${e.cap.currency}`,type:"currency"},[e.cap.name]:Z(`Disbursement cap in ${e.cap.currency} minor units`)},id:n,summary:`Capped disbursement to ${e.destination.replaceAll("_"," ")}`,title:q(n),actions:{create:{summary:"Submit the capped disbursement",to:"submitted"},deny:{captureInput:{decisionEvidenceReference:"evidenceReference"},from:["submitted"],port:{allowed:t.allowed,fields:{evidenceReference:"text"}},requiresAggregate:[{check:{kind:"all_in"},instrumentId:r,over:"children",refField:o,statuses:["created"]}],summary:"Record a denial without moving money",to:"denied"}}},rules:[],settlement:{name:n,pieces:[]}}}function Tr(e){let t=e.name,n=`${de(t)}Id`,r=Y(`${t}_contribution`),o=Y(`${t}_guarantee_contribution`),a=Y(`${t}_payout`),c=[...new Set([...e.members,...e.payoutOrder,...e.guarantor?[e.guarantor]:[]])],s=Object.fromEntries(c.map(v=>{let x=`${de(v)}AccountId`;return[x,`fields.${x}`]})),l=e.members.map(v=>`${t}_${v}_contribution`),u=e.members.map((v,x)=>{let k=l[x],T={create:{requires:{[n]:{bind:{currency:"fields.currency",...s,[e.schedule.firstDueField]:`fields.${e.schedule.firstDueField}`,[e.contribution.name]:`fields.${e.contribution.name}`},statuses:["forming"],unique:!0}},summary:`Create the fixed contribution row for ${v.replaceAll("_"," ")}`,to:"cycle_1_due"}};for(let R=0;R<e.schedule.count;R+=1){let C=R+1,Q=`cycle_${C}_due`,B=`cycle_${C}_defaulted`,W=`cycle_${C}_funded`,H=`cycle_${C}_guaranteed`,ue=C===e.schedule.count?"final_paid":`cycle_${C+1}_due`,X=Y(`${t}_cycle_${C}_due`),$=e.contribution.name,D=e.contribution.name,K={field:e.schedule.firstDueField,rule:X,...Be(e.schedule,R)};T[`contribute_cycle_${C}`]={due:K,from:[Q],moneyEvent:r,moves:[{amount:$,from:v,key:"contribution",operation:"create",to:"escrow"}],requires:{[n]:[`active_cycle_${C}`]},summary:`Fund ${v.replaceAll("_"," ")}'s cycle ${C} contribution`,to:W},T[`mark_default_cycle_${C}`]={due:K,from:[Q],requires:{[n]:[`active_cycle_${C}`]},summary:`Mark the stored cycle ${C} due condition`,to:B},e.guarantor&&(T[`guarantee_cycle_${C}`]={from:[B],moneyEvent:o,moves:[{amount:D,from:e.guarantor,key:"guarantee",operation:"create",to:"escrow"}],requires:{[n]:[`active_cycle_${C}`]},summary:`Fund the defaulted cycle ${C} amount before payout`,to:H}),T[`pay_cycle_${C}`]={from:[W],moneyEvent:a,moves:[{amount:$,from:"escrow",key:"payout",operation:"create",to:e.payoutOrder[R]}],requires:{[n]:[`cycle_${C}_ready`]},summary:`Pay this member's stored contribution into cycle ${C}'s shared pot recipient`,to:ue},e.guarantor&&(T[`pay_guaranteed_cycle_${C}`]={from:[H],moneyEvent:a,moves:[{amount:D,from:"escrow",key:"payout",operation:"create",to:e.payoutOrder[R]}],requires:{[n]:[`cycle_${C}_ready`]},summary:`Pay the funded default into cycle ${C}'s stored recipient`,to:ue})}return T.close={from:["final_paid"],requiresDrainedAccount:{path:"refs.escrowAccountId"},summary:"Complete after the final payout drains this member custody",to:"completed"},{actors:Object.fromEntries([[v,"payer"],...e.guarantor?[[e.guarantor,"payer"]]:[],...e.payoutOrder.map(R=>[R,"beneficiary"])]),desc:`Fixed contribution row for ${v.replaceAll("_"," ")}`,escrow:!0,fields:{[e.contribution.name]:Z("Exact contribution amount shared by every cycle"),currency:{desc:"Currency derived from the pool",type:"currency"},[e.schedule.firstDueField]:me("First due anchor derived from the pool"),[n]:{desc:`The exact ${t}`,type:`ref:${t}`}},id:k,summary:`${v.replaceAll("_"," ")} contribution row`,title:`${q(t)} ${q(v)} Contribution`,actions:T}}),f={create:{summary:"Create the fixed roster before activation",to:"forming"},cancel:{from:["forming"],summary:"Cancel before activation without moving money",to:"cancelled"},activate:{from:["forming"],requiresAggregate:l.map(v=>({check:{kind:"count_equals_field",field:"one"},instrumentId:v,over:"children",refField:n,statuses:["cycle_1_due"]})),summary:"Activate only after every fixed member row exists once",to:"active_cycle_1"}};for(let v=0;v<e.schedule.count;v+=1){let x=v+1;f[`ready_cycle_${x}`]={from:[`active_cycle_${x}`],requiresAggregate:l.map(k=>({check:{kind:"all_in"},instrumentId:k,over:"children",refField:n,statuses:[`cycle_${x}_funded`,...e.guarantor?[`cycle_${x}_guaranteed`]:[]]})),summary:`Lock cycle ${x} only after every member row is funded or guaranteed`,to:`cycle_${x}_ready`},f[`advance_cycle_${x}`]={from:[`cycle_${x}_ready`],requiresAggregate:l.map(k=>({check:{kind:"all_in"},instrumentId:k,over:"children",refField:n,statuses:[x===e.schedule.count?"completed":`cycle_${x+1}_due`]})),summary:x===e.schedule.count?"Complete after the final shared pot pays":`Advance after every cycle ${x} contribution pays`,to:x===e.schedule.count?"completed":`active_cycle_${x+1}`}}return{design:[`${t}: fixed roster and stored payout order; one member-specific row per member avoids tuple identity and keeps each cycle idempotent`],extraInstruments:u,generatedPrefixInstrumentIds:l,feeLines:[],moneyEvents:[te({amount:"One exact member contribution",fromActor:e.members[0],key:r,kind:"charge",occurrence:"repeatable",toActor:"escrow",trigger:"Fund one member and cycle"}),...e.guarantor?[te({amount:"One exact defaulted contribution",fromActor:e.guarantor,key:o,kind:"charge",occurrence:"repeatable",toActor:"escrow",trigger:"Fund one defaulted member and cycle"})]:[],te({amount:"One exact member contribution from the cycle pot",fromActor:"escrow",key:a,kind:"payout",occurrence:"repeatable",toActor:e.payoutOrder[0],trigger:"Pay the stored cycle recipient"})],instrument:{actors:Object.fromEntries([...e.members.map(v=>[v,"party"]),...e.guarantor?[[e.guarantor,"payer"]]:[]]),desc:"Fixed rotating contribution and payout order",fields:{currency:{desc:`Currency fixed to ${e.contribution.currency}`,type:"currency"},[e.contribution.name]:Z(`Exact contribution in ${e.contribution.currency} minor units`),[e.schedule.firstDueField]:me("Stored first contribution due date"),one:{desc:"Exact fixed member-row count",type:"const:1"}},id:t,summary:`${e.members.length}-member rotating pool`,title:q(t),actions:f},rules:Array.from({length:e.schedule.count},(v,x)=>({allowedActors:[],detail:`Cycle ${x+1} default follows its stored due condition`,dueDriven:!0,enforcement:"platform",gatesEvent:null,key:Y(`${t}_cycle_${x+1}_due`),kind:"deadline",label:`Cycle ${x+1} due condition`,tenantTunable:!1})),settlement:{name:t,pieces:[]}}}function Be(e,t){return t===0?{}:{offset:`P${e.every.days*t}D`}}function Rr(e,t,n,r,o){let a=e.name,c=e.schedule,s=e.amount.name,l=Y(`${a}_period_collection`),u=Y(`${a}_period_open`),f=c.terminationDrain;if(!Je(a,["open_period","collect_period",f],e.origin,r))return;let v={drainAction:f,delinquency:"parent_policy",liability:"one_open",period:{calendar:"gregorian",monthEnd:"clamp_to_last_day",months:c.every.months},...c.termination.kind==="stored_date"?{untilField:c.termination.field}:{untilAction:f}},x=c.termination.kind==="stored_date"?{due:{field:c.termination.field,rule:Y(`${a}_termination`)}}:{},k=c.termination.kind==="port"&&o?{captureInput:Object.fromEntries(o.fields.map(T=>[T.name,T.name])),port:{allowed:o.allowed,fields:pt(o)}}:{};return{design:[`${a}: one ${c.every.raw} calendar period may be open; the due action opens liability without moving money`,`${a}: recurring_collection ${t.name} owns explicit collection attempts and parent delinquency; only collect_period moves ${s}`,`${a}: ${f} cancels active or open liability and prevents later recurrence dispatch`],feeLines:[],moneyEvents:[te({amount:`One ${s} period charge`,fromActor:e.payer,key:l,kind:"installment",occurrence:"repeatable",toActor:e.payee,trigger:"Collect one explicitly opened period liability"})],instrument:{actors:{[e.debtor]:"party",[e.payee]:"beneficiary",[e.payer]:"payer"},desc:`Open monthly obligation for ${e.debtor.replaceAll("_"," ")}; one period liability at a time`,fields:{[s]:je(e.amount,`Exact charge for one ${c.every.raw} period in ${e.amount.currency} minor units`),currency:{desc:`Currency fixed to ${e.amount.currency}`,type:`currency:${e.amount.currency}`},[c.firstDueField]:me("First period anchor; missing Gregorian month days clamp to the target month's final day"),...c.termination.kind==="stored_date"&&c.termination.field!==c.firstDueField?{[c.termination.field]:me("Stored termination date that bars later period anchors")}:{}},id:a,summary:`Open ${c.every.raw} obligation for ${e.debtor.replaceAll("_"," ")}`,title:q(a),actions:{create:{summary:"Create the open obligation before its first anchor",to:"active"},open_period:{due:{every:v,field:c.firstDueField,rule:u},from:["active"],summary:"Open exactly one period liability without moving money",to:"period_open"},collect_period:{captureInput:{mandateEvidenceReference:"evidenceReference"},from:["period_open"],moneyEvent:l,moves:[{amount:s,from:e.payer,key:"period_collection",operation:"create",to:e.payee}],port:{allowed:n.allowed,fields:{evidenceReference:"text"}},summary:"Collect one authored period charge with mandate evidence",to:"active"},[f]:{...x,...k,from:["active","period_open"],summary:"Cancel the open schedule and drain any period liability",to:"canceled"}}},rules:[{allowedActors:[],detail:"The recurrence action opens one liability only from active; it never moves money",dueDriven:!0,enforcement:"platform",gatesEvent:null,key:u,kind:"deadline",label:"One deterministic period occurrence opens liability",tenantTunable:!1},...c.termination.kind==="stored_date"?[{allowedActors:[],detail:"The stored termination date invokes the declared cancel path without moving money",dueDriven:!0,enforcement:"platform",gatesEvent:null,key:Y(`${a}_termination`),kind:"deadline",label:"Stored termination drains the open schedule",tenantTunable:!1}]:[]],settlement:{name:a,pieces:[]}}}function Fr(e,t,n){let r=e.name,o=e.amount.name,a=`${r.replaceAll(/_([a-z])/g,(X,$)=>$.toUpperCase())}Id`,c=Sn(e.schedule.count),s=c.map((X,$)=>`installment${$+1}Amount`),l=c.map((X,$)=>`${r}_installment_${$+1}_payment`),u="active",f=X=>`installment_${X+1}_delinquent`,v=c.map((X,$)=>f($)),x=[u,...v],k=Y(`${r}_repayment`),T=Y(`${r}_refund`),R=Y(`${r}_advance`),C={currency:{desc:`Currency fixed to ${e.amount.currency}`,type:"currency"},[o]:Z(`The principal in ${e.amount.currency} minor units; the stored installment anchors partition it exactly`),[e.schedule.firstDueField]:me(`Due date of the first installment; later anchors use fixed offsets of ${e.schedule.every.raw}`)};for(let[X,$]of s.entries())C[$]=Z(`Stored amount for installment ${X+1} of ${e.schedule.count}${X===0?" (carries the integer-division remainder)":""}`),C[`installment${X+1}DelinquentAfter`]=ir(`Machine-set marker proving installment ${X+1} reached its stored due date while unpaid`);let Q=l.map((X,$)=>({childField:"amount",childInstrumentId:X,childRefField:a,childStatuses:["paid"],parentField:s[$]})),B={create:{summary:`Create a ${q(r).toLowerCase()} obligation`,to:"draft"},approve:{from:["draft"],summary:"Approve the immutable principal partition and stored anchors",to:e.advanceTo?"approved":u},...e.advanceTo?{advance:{from:["approved"],moneyEvent:R,moves:[{amount:o,from:e.payee,key:"advance",operation:"create",to:e.advanceTo}],summary:`Advance the principal to the ${e.advanceTo.replaceAll("_"," ")}; the internal ledger receipt is the confirmation`,to:u}}:{},write_off:{from:["draft",...e.advanceTo?["approved"]:[],...x],summary:"Write off the remaining exposure without moving money",to:"written_off"}},W=[];for(let[X,$]of l.entries()){let D=X+1,K=Y(`${r}_installment_${D}_due`),re={field:e.schedule.firstDueField,rule:K,...Be(e.schedule,X)},ee=U=>[{check:{amountField:"amount",kind:U,targetField:s[X]},instrumentId:$,over:"children",refField:a,statuses:["paid"]}];B[`mark_installment_${D}_delinquent`]={due:re,from:x.filter(U=>U!==f(X)),requiresAggregate:ee("sum_below"),setsAt:{field:`installment${D}DelinquentAfter`,marker:!0,offset:"PT1S"},summary:`Mark installment ${D} delinquent only when its due anchor is unmet`,to:f(X)},B[`collect_installment_${D}`]={due:re,from:v,requiresAggregate:ee("sum_exactly"),summary:`Close delinquent installment ${D} after linked payments reach its stored amount`,to:u},W.push({allowedActors:[],detail:`At stored anchor ${D}, the platform compares paid child rows with ${s[X]} and chooses paid or delinquent`,dueDriven:!0,enforcement:"platform",gatesEvent:null,key:K,kind:"deadline",label:`Installment ${D} resolves from its stored due condition`,tenantTunable:!1})}let H=Y(`${r}_completion_due`);B.complete={due:{field:e.schedule.firstDueField,rule:H,...Be(e.schedule,c.length-1)},from:x,requiresAggregate:l.map((X,$)=>({check:{amountField:"amount",kind:"sum_exactly",targetField:s[$]},instrumentId:X,over:"children",refField:a,statuses:["paid"]})),summary:"Close the obligation only after every stored anchor is paid exactly",to:"repaid"},W.push({allowedActors:[],detail:"After the final stored anchor, the platform closes only when every anchor is paid exactly",dueDriven:!0,enforcement:"platform",gatesEvent:null,key:H,kind:"deadline",label:"Obligation completion follows exact aggregate repayment",tenantTunable:!1});let ue=X=>{let $=X+1,D=l[X],K=x,re=`${e.payer.replaceAll(/_([a-z])/g,(M,ce)=>ce.toUpperCase())}AccountId`,ee=`${e.payee.replaceAll(/_([a-z])/g,(M,ce)=>ce.toUpperCase())}AccountId`,U={[a]:{bind:{currency:"fields.currency",[re]:`fields.${re}`,[ee]:`fields.${ee}`},statuses:K}},F={[a]:{match:{"fields.currency":"fields.currency",[`fields.${re}`]:`fields.${re}`,[`fields.${ee}`]:`fields.${ee}`},statuses:K}};return{actors:{[e.payee]:"beneficiary",[e.payer]:"payer"},desc:`One partial or full payment bound to installment ${$} of ${r}; the operation name fixes the anchor and ${a} fixes the obligation`,fields:{amount:Z(`Positive payment amount capped with its paid siblings at ${s[X]}`),currency:{desc:"ISO 4217 currency derived from the obligation",type:"currency"},[a]:{desc:`The exact ${r.replaceAll("_"," ")} this payment belongs to`,type:`ref:${r}`}},id:D,summary:`Anchor-bound payment for installment ${$}`,title:`${q(r)} Installment ${$} Payment`,actions:{create:{requires:U,summary:`Create a payment record for installment ${$}`,to:"created"},repay:{...t&&n?{captureInput:{mandateEvidenceReference:"evidenceReference"},port:{allowed:n.allowed,fields:{evidenceReference:"text"}}}:{},from:["created"],moneyEvent:k,moves:[{amount:"amount",from:e.payer,key:"repayment",operation:"create",to:e.payee}],requires:F,requiresExposure:[{amountField:"amount",anchorField:a,capField:s[X],capOnAnchor:!0,childInstrumentId:D,statuses:["paid"]}],summary:`Pay a partial or full amount against installment ${$}`,to:"paid"},refund:{from:["paid"],moneyEvent:T,moves:[{amount:"amount",from:e.payee,key:"refund",operation:"create",to:e.payer}],requires:F,summary:`Refund this one stored installment ${$} payment whole`,to:"refunded"}}}};return{design:[`${r}: existing scheduled mechanism in obligation mode; principal partitions into ${e.schedule.count} stored anchors; each payment operation names one anchor and one obligation`,`${r}: partial and early payments serialize under per-anchor aggregate caps; each refund reverses one paid row whole; rescheduling is refused by the checker`,`${r}: due-only delinquency and write-off change state without money; ${e.advanceTo?"advance is an internal ledger movement with no provider claim":"no advance is emitted"}`,...t?[`${t.name}: explicit collection attempts reuse ${r}'s anchor-bound repayment actions; mandate evidence is captured per attempt; failures remain receipted failures and delinquency stays on ${r}`]:[]],extraInstruments:l.map((X,$)=>ue($)),generatedPrefixInstrumentIds:l,feeLines:[],moneyEvents:[...e.advanceTo?[te({amount:`The full ${o}`,fromActor:e.payee,key:R,kind:"payout",toActor:e.advanceTo,trigger:"Advance the approved principal once"})]:[],te({amount:"A positive amount capped by its stored installment anchor",fromActor:e.payer,key:k,kind:"installment",occurrence:"repeatable",toActor:e.payee,trigger:"Pay one anchor-bound partial or full installment amount"}),te({amount:"Exactly one stored paid installment payment",fromActor:e.payee,key:T,kind:"refund",occurrence:"repeatable",toActor:e.payer,trigger:"Refund one linked paid installment payment whole"})],instrument:{actors:{...e.advanceTo?{[e.advanceTo]:"beneficiary"}:{},[e.payee]:"beneficiary",[e.payer]:"payer",[e.debtor]:"party"},aggregateInvariants:Q,desc:`Installment obligation for ${e.debtor.replaceAll("_"," ")}; ${e.payer.replaceAll("_"," ")} pays ${e.payee.replaceAll("_"," ")} against exact stored anchors`,fields:C,id:r,...Ce(Ae(o,s)),summary:`${e.schedule.count}-anchor obligation for ${e.debtor.replaceAll("_"," ")}`,title:q(r),actions:B},rules:W,settlement:{name:r,pieces:[]}}}function Or(e){let t=e.name,n=e.amount.name,{schedule:r}=e,o=`${t}_schedule`,a=Sn(r.count),c={[n]:Z(`The total scheduled amount in ${e.amount.currency} minor units; the installment fields below partition it exactly`),[r.firstDueField]:me(`Due date of the first installment; installment k falls ${r.every.raw} after its predecessor`)},s=a.map((k,T)=>{let R=`installment${T+1}Amount`;return c[R]=Z(`Installment ${T+1} of ${r.count}${T===0?" (carries the integer-division remainder)":""}: about ${le(a[T])} of ${n}, collected on its own stored-date anchor`),R}),l=a.map((k,T)=>`pay_installment_${T+1}`),u=Ie(l,"active","settled","collecting"),f=`${t}_installments`,v=[te({amount:`The ${n}, partitioned into ${r.count} installments`,fromActor:e.payer,key:f,kind:"installment",occurrence:"repeatable",toActor:e.payee,trigger:`Collect each of the ${r.count} installments on its stored due date`})],x={create:{summary:`Create a ${q(t).toLowerCase()} plan`,to:"active"}};for(let[k,T]of s.entries())x[l[k]]={due:{field:r.firstDueField,rule:o,...Be(r,k)},from:[u[k]?.from],moneyEvent:f,moves:[{key:"transfer",operation:"create",amount:T,from:e.payer,to:e.payee}],summary:`Collect installment ${k+1} of ${r.count}`,to:u[k]?.to};return{design:[`${t}: ${r.count} installments every ${r.every.raw} from ${r.firstDueField}; finite by construction, one idempotent anchor per installment`],feeLines:[],moneyEvents:v,instrument:{actors:{[e.payer]:"payer",[e.payee]:"beneficiary"},desc:`Scheduled payment: the ${e.payer.replaceAll("_"," ")} pays ${n} to the ${e.payee.replaceAll("_"," ")} in ${r.count} installments, one every ${r.every.raw}`,fields:c,id:t,...Ce(Ae(n,s)),summary:`${r.count}-installment schedule from ${e.payer.replaceAll("_"," ")} to ${e.payee.replaceAll("_"," ")}`,title:q(t),actions:x},rules:[{allowedActors:[],detail:`Each of the ${r.count} installments is collected once from its stored due date`,dueDriven:!0,enforcement:"platform",gatesEvent:null,key:o,kind:"deadline",label:"Installments collected on their stored due dates",tenantTunable:!1}],settlement:{name:t,pieces:[]}}}function Dr(e,t){return e.source.kind==="carve"?Nr(e,e.source.settlement,t):Lr(e,e.source.schedule)}function Nr(e,t,n){let r=e.name,o=e.amount.name,a=e.feeBps>0,c=e.advanced.replaceAll("_"," "),s=e.funder.replaceAll("_"," "),l=t.replaceAll("_"," "),f=[{field:"carveHoldId",statuses:["funded"],target:t},...n.map((x,k)=>({field:`carveRecourse${k+1}Id`,statuses:["active"],target:x.name}))],v={[o]:Z(`The advanced amount in ${e.amount.currency} minor units, disbursed to the ${c} up front`),...Object.fromEntries(f.map(x=>[x.field,{desc:`The ${x.target.replaceAll("_"," ")} bound to this advance`,type:`ref:${x.target}`}])),...a?{feeAmount:Z(`${le(e.feeBps)} of ${o}, the funder's discount owed on top of the advance`),repayableAmount:Z(`${o} + feeAmount: what the ${l} release owes the ${s}`)}:{}};return{design:[`${r}: ${o} advanced to the ${e.advanced} up front and repaid by carving the ${t} release${a?`; repayableAmount = ${o} + ${le(e.feeBps)} fee`:""}`],feeLines:a?[{label:`${q(e.funder)} discount`,on:`each ${r.replaceAll("_"," ")}`,structure:`${le(e.feeBps)} of the ${o}, owed on top out of the ${l} release`}]:[],moneyEvents:[te({amount:`The full ${o}`,fromActor:e.funder,key:`${r}_disburse`,kind:"payout",toActor:e.advanced,trigger:`Disburse the advance to the ${c}`})],instrument:{actors:{[e.advanced]:"beneficiary",[e.funder]:"payer"},desc:`Advance: the ${s} disburses ${o} to the ${c} and is repaid out of the ${l} release, which pays the ${s} in the ${c}'s place${a?", plus the funder's discount":""}`,fields:v,id:r,...Ce(a?Ae("repayableAmount",[o,"feeAmount"]):[]),summary:`Advance to the ${c} repaid by carving the ${l} release`,title:q(r),actions:{create:{summary:`Create a ${q(r).toLowerCase()}`,to:"created"},disburse:{from:["created"],moneyEvent:`${r}_disburse`,moves:[{key:"transfer",operation:"create",amount:o,from:e.funder,to:e.advanced}],requires:Object.fromEntries(f.map(x=>[x.field,{match:{[`fields.${o}`]:`fields.${o}`,"fields.currency":"fields.currency"},statuses:x.statuses}])),summary:`Disburse the ${o} to the ${c}`,to:"advanced"},settle:{from:["advanced"],summary:`Close the advance once the ${l} has released to the ${s}`,to:"repaid"}}},rules:[{allowedActors:[],detail:`The ${l} releases the ${c}'s whole share to the ${s} instead of to the ${c}; the advance is repaid out of that release and never out of new money`,dueDriven:!1,enforcement:"platform",gatesEvent:null,key:`${r}_carve`,kind:"release_condition",label:`Repaid by carving the ${l} release`,tenantTunable:!1}],settlement:{name:r,pieces:[]}}}function Lr(e,t){let n=e.name,r=e.amount.name,o=`${n}_schedule`,a=Sn(t.count),c=e.feeBps>0,s=c?"repayableAmount":r,l={[r]:Z(`The advanced amount in ${e.amount.currency} minor units, disbursed to the ${e.advanced.replaceAll("_"," ")} up front`),...c?{feeAmount:Z(`${le(e.feeBps)} of ${r}, the funder's discount repaid on top of the advance`),repayableAmount:Z(`${r} + feeAmount: the total the repayment fields below partition exactly`)}:{},[t.firstDueField]:me(`Due date of the first repayment; repayment k falls ${t.every.raw} after its predecessor`)},u=a.map((R,C)=>{let Q=`repayment${C+1}Amount`;return l[Q]=Z(`Repayment ${C+1} of ${t.count}${C===0?" (carries the integer-division remainder)":""}: about ${le(a[C])} of ${s}, collected on its own stored-date anchor`),Q}),f=a.map((R,C)=>`collect_repayment_${C+1}`),v=Ie(f,"advanced","repaid","repaying"),x=[te({amount:`The full ${r}`,fromActor:e.funder,key:`${n}_disburse`,kind:"payout",toActor:e.advanced,trigger:`Disburse the advance to the ${e.advanced.replaceAll("_"," ")}`})],k={create:{summary:`Create a ${q(n).toLowerCase()}`,to:"created"},disburse:{from:["created"],moneyEvent:`${n}_disburse`,moves:[{key:"transfer",operation:"create",amount:r,from:e.funder,to:e.advanced}],summary:`Disburse the ${r} to the ${e.advanced.replaceAll("_"," ")}`,to:"advanced"}},T=`${n}_repayments`;x.push(te({amount:`The ${s}, partitioned into ${t.count} repayments`,fromActor:e.advanced,key:T,kind:"installment",occurrence:"repeatable",toActor:e.funder,trigger:`Collect each of the ${t.count} repayments on its stored due date`}));for(let[R,C]of u.entries()){let Q=T;k[f[R]]={due:{field:t.firstDueField,rule:o,...Be(t,R)},from:[v[R]?.from],moneyEvent:Q,moves:[{key:"transfer",operation:"create",amount:C,from:e.advanced,to:e.funder}],summary:`Collect repayment ${R+1} of ${t.count}`,to:v[R]?.to}}return{design:[`${n}: ${r} advanced up front; ${t.count} repayments every ${t.every.raw} conserve against ${s}${c?` (advance + ${le(e.feeBps)} fee)`:""}`],feeLines:c?[{label:`${q(e.funder)} discount`,on:`each ${n.replaceAll("_"," ")}`,structure:`${le(e.feeBps)} of the ${r}, repaid on top of the advance`}]:[],moneyEvents:x,instrument:{actors:{[e.funder]:"payer",[e.advanced]:"beneficiary"},desc:`Advance: the ${e.funder.replaceAll("_"," ")} disburses ${r} to the ${e.advanced.replaceAll("_"," ")}, repaid over ${t.count} scheduled repayments${c?" plus the funder's discount":""}`,fields:l,id:n,...Ce([...Ae(s,u),...c?Ae("repayableAmount",[r,"feeAmount"]):[]]),summary:`Advance to ${e.advanced.replaceAll("_"," ")} repaid over ${t.count} anchors`,title:q(n),actions:k},rules:[{allowedActors:[],detail:`Each of the ${t.count} repayments is collected once from its stored due date`,dueDriven:!0,enforcement:"platform",gatesEvent:null,key:o,kind:"deadline",label:"Repayments collected on their stored due dates",tenantTunable:!1}],settlement:{name:n,pieces:[]}}}function jr(e){let t=e.name,n=`${t}_period`,r=e.rates[0]?.field.currency??"SAR",o={[e.closeByField]:me("End of this metering period; the close makes further charges unreachable")};for(let s of e.rates)o[s.field.name]=Z(`Per-unit price of ${s.meter.replaceAll("_"," ")} in ${r} minor units, committed at period open`);let a=[],c={close_period:{due:{field:e.closeByField,rule:n},from:["open"],summary:"Close the metering period; no further usage can be charged",to:"closed"},create:{summary:`Open a ${q(t).toLowerCase()} period with its committed rate card`,to:"open"}};for(let s of e.rates){let l=Y(`${t}_${s.meter}`);a.push(te({amount:`The committed ${s.field.name} per unit`,fromActor:e.payer,key:l,kind:"charge",occurrence:"repeatable",timing:"external_schedule",toActor:e.payee,trigger:`Charge one ${s.meter.replaceAll("_"," ")} at the committed rate`})),c[`charge_${s.meter}`]={from:["open"],moneyEvent:l,moves:[{key:"transfer",operation:"create",amount:s.field.name,from:e.payer,to:e.payee}],summary:`Charge one metered ${s.meter.replaceAll("_"," ")}; the emission is the transfer itself`,to:"open"}}return{design:[`${t}: committed rate card (${e.rates.map(s=>s.meter).join(", ")}); each usage charge IS the ledger transfer; period closes on ${e.closeByField}`],feeLines:[],moneyEvents:a,instrument:{actors:{[e.payer]:"payer",[e.payee]:"beneficiary"},desc:`Metered usage: the ${e.payer.replaceAll("_"," ")} is charged per unit at the committed rate card until the period closes on its stored end date`,fields:o,id:t,summary:`Metered charges from ${e.payer.replaceAll("_"," ")} on a committed rate card`,title:q(t),actions:c},rules:[{allowedActors:[],detail:"The period closes once from its stored end date",dueDriven:!0,enforcement:"platform",gatesEvent:null,key:n,kind:"deadline",label:"Period closed on its stored end date",tenantTunable:!1}],settlement:{name:t,pieces:[]}}}function Br(e){let t=e.name,n=e.amount.name,r=`${t}_payout`,o=e.shares.findIndex(k=>k.to===e.remainderTo),a=e.shares.map(k=>({bps:k.bps,field:`${de(k.to)}ShareAmount`,origin:k.origin,releaseTo:k.to})),c={[n]:Z(`The pooled period total in ${e.amount.currency} minor units; the share fields below partition it exactly`),[e.distributeDueField]:me("The period's payout date; the pool distributes from it")};for(let[k,T]of a.entries()){let R=k===Math.max(o,0)?" (carries the integer-division remainder)":"";c[T.field]=Z(`${le(T.bps)} of ${n}${R}: the ${T.releaseTo.replaceAll("_"," ")}'s share. Computed as floor(${n} * ${T.bps} / 10000) in ${e.amount.currency} minor units`)}let s=a.map((k,T)=>`fund_share_${T+1}`),l=a.map((k,T)=>`distribute_share_${T+1}`),u=Ie(s,"created","pooled","pooling"),f=Ie(l,"pooled","distributed","distributing"),v=[],x={create:{summary:`Open a ${q(t).toLowerCase()} period`,to:"created"}};for(let[k,T]of a.entries()){let R=`${t}_pool_${k+1}`;v.push(te({amount:`${le(T.bps)} of the ${n}`,fromActor:e.payer,key:R,kind:"charge",toActor:"escrow",trigger:`Pool the ${T.releaseTo.replaceAll("_"," ")}'s share for the period`})),x[s[k]]={from:[u[k]?.from],moneyEvent:R,moves:[{key:"transfer",operation:"create",amount:T.field,from:e.payer,to:"escrow"}],summary:`Pool share ${k+1} of the period total`,to:u[k]?.to}}for(let[k,T]of a.entries()){let R=`${t}_payout_${k+1}`;v.push(te({amount:`${le(T.bps)} of the ${n}`,fromActor:"escrow",key:R,kind:"payout",toActor:T.releaseTo,trigger:`Distribute the ${T.releaseTo.replaceAll("_"," ")}'s share on the payout date`})),x[l[k]]={due:{field:e.distributeDueField,rule:r},from:[f[k]?.from],moneyEvent:R,moves:[{key:"transfer",operation:"create",amount:T.field,from:"escrow",to:T.releaseTo}],summary:`Distribute the ${T.releaseTo.replaceAll("_"," ")}'s share of the pool`,to:f[k]?.to}}return{design:[`${t}: pool of ${n} partitioned ${a.map(k=>`${le(k.bps)} ${k.releaseTo}`).join(" + ")}; distributes in full on ${e.distributeDueField}; remainder to ${e.remainderTo}`],feeLines:[],moneyEvents:v,instrument:{actors:{[e.payer]:"payer",...Object.fromEntries(e.shares.map(k=>[k.to,"beneficiary"]))},desc:`Pooled split: the ${e.payer.replaceAll("_"," ")} pools the period's ${n} share by share; the pool distributes to every recipient in full on the stored payout date`,escrow:!0,fields:c,id:t,...Ce(Ae(n,a.map(k=>k.field))),summary:`Period pool from ${e.payer.replaceAll("_"," ")} split ${e.shares.length} ways`,title:q(t),actions:x},rules:[{allowedActors:[],detail:"Every share of the pool distributes once from the stored payout date",dueDriven:!0,enforcement:"platform",gatesEvent:null,key:r,kind:"deadline",label:"Pool distributed on its stored payout date",tenantTunable:!1}],settlement:{name:t,pieces:a}}}function ht(e){let t=Number(_n),n=e.carveTo??e.payee,r=[];e.payeeFeeBps<t&&r.push({end:t-e.payeeFeeBps,to:n}),e.payeeFeeBps>0&&r.push({end:t,to:"platform"});let o=[],a=0;for(let f of e.onCancel?.shares??[])a+=f.bps,o.push({end:a,origin:f.origin,to:f.to});let c=[...new Set([...r.map(f=>f.end),...o.map(f=>f.end),t])].sort((f,v)=>f-v),s=(f,v)=>f.find(x=>v<x.end),l=[],u=0;for(let f of c){if(f<=u)continue;let v=s(r,u),x=s(o,u);l.push({bps:f-u,...x?{cancelTo:x.to}:{},field:`piece${l.length+1}Amount`,origin:x?.origin??e.amount.origin,releaseTo:v?.to??n}),u=f}return l}function gt(e,t,n,r){let o=e.cancelTo?`; on cancellation to the ${e.cancelTo.replaceAll("_"," ")}`:"",a=t===0?" (carries the integer-division remainder)":"";return`${le(e.bps)} of ${n}${a}: released to the ${e.releaseTo.replaceAll("_"," ")}${o}. Computed as floor(${n} * ${e.bps} / 10000) in ${r} minor units`}function le(e){let t=e/100;return`${Number.isInteger(t)?t:t.toFixed(2).replace(/0$/,"")}%`}function Jr(e){let t=new Map(e.settlements.flatMap(r=>r.archetype==="advance"&&r.source.kind==="carve"?[[r.source.settlement,r.funder]]:[]));return`${e.settlements.map(r=>{switch(r.archetype){case"held_payment":{let o=r.onCancel?`; cancellation splits the held amount ${r.onCancel.shares.map(s=>`${le(s.bps)} to the ${s.to.replaceAll("_"," ")}`).join(" and ")}`:"",a=t.get(r.name),c=a?`the ${a.replaceAll("_"," ")} is paid on confirmed release, in the ${r.payee.replaceAll("_"," ")}'s place`:`the ${r.payee.replaceAll("_"," ")} is paid on confirmed release`;return`The ${r.payer.replaceAll("_"," ")} funds ${r.amount.name} into escrow and ${c}${o}`}case"captured_payment":return`The ${r.payer.replaceAll("_"," ")}'s ${r.amount.name} is reserved until ${r.reserveUntilField}, captured by the ${r.payee.replaceAll("_"," ")} in strict partial slices, then settled or released`;case"instant_transfer":return`The ${r.payer.replaceAll("_"," ")} pays ${r.amount.name} straight through to the ${r.payee.replaceAll("_"," ")}`;case"premium_forward":return`The ${r.payer.replaceAll("_"," ")}'s ${r.amount.name} forwards to the ${r.carrier.replaceAll("_"," ")} exactly once on binding`;case"deposit":return`The ${r.payer.replaceAll("_"," ")}'s ${r.amount.name} is reserved for the ${r.holder.replaceAll("_"," ")} until claimed or returned`;case"scheduled":return r.schedule.kind==="open"?r.mode==="obligation"?`The ${r.debtor.replaceAll("_"," ")} owes one ${r.amount.name} charge every ${r.schedule.every.raw} until the declared cancellation path closes the obligation`:"The open schedule is invalid without obligation mode":r.mode==="obligation"?`The ${r.debtor.replaceAll("_"," ")} owes ${r.amount.name}; ${r.advanceTo?`the ${r.payee.replaceAll("_"," ")} advances it to the ${r.advanceTo.replaceAll("_"," ")}, then `:""}the ${r.payer.replaceAll("_"," ")} repays the ${r.payee.replaceAll("_"," ")} over ${r.schedule.count} anchor-bound installments`:`The ${r.payer.replaceAll("_"," ")} pays ${r.amount.name} to the ${r.payee.replaceAll("_"," ")} over ${r.schedule.count} scheduled installments`;case"advance":return r.source.kind==="carve"?`The ${r.funder.replaceAll("_"," ")} advances ${r.amount.name} to the ${r.advanced.replaceAll("_"," ")}, repaid out of the ${r.source.settlement.replaceAll("_"," ")} release`:`The ${r.funder.replaceAll("_"," ")} advances ${r.amount.name} to the ${r.advanced.replaceAll("_"," ")}, repaid over ${r.source.schedule.count} anchors`;case"metered":return`The ${r.payer.replaceAll("_"," ")} is charged per metered unit at a committed rate card until the period closes`;case"pooled_split":return`The ${r.payer.replaceAll("_"," ")} pools ${r.amount.name} and it distributes ${r.shares.length} ways on the payout date`;case"settlement_batch":return`The ${r.settlementAccount.replaceAll("_"," ")} freezes capture lineage and pays one signed net amount to the ${r.payoutDestination.replaceAll("_"," ")}`;case"funding_round":return`The ${r.contributor.replaceAll("_"," ")} commits under ${r.target.name} until the stored close anchor activates or fails the round`;case"weighted_distribution":return`The ${r.source.replaceAll("_"," ")} pays a frozen claimant set by deterministic largest remainder`;case"credit_facility":return`The ${r.lender.replaceAll("_"," ")} admits draws under ${r.limit.name}; ${r.obligation.settlement.replaceAll("_"," ")} owns repayment`;case"recurring_collection":return`${r.name.replaceAll("_"," ")} adds explicit mandate evidence to ${r.obligation.settlement.replaceAll("_"," ")} repayment attempts`;case"conditional_disbursement":return`The ${r.source.replaceAll("_"," ")} pays one evidence-approved amount under ${r.cap.name} to the ${r.destination.replaceAll("_"," ")}`;case"rotating_pool":return`${r.members.length} fixed members contribute one exact amount per cycle in a stored payout order`;case"swap":return`The ${r.sides[0].party.replaceAll("_"," ")} and ${r.sides[1].party.replaceAll("_"," ")} fund one shared escrow and the entire two-sided trade releases or reverses together`}}).join(". ")}.`.slice(0,400)}function de(e){let[t,...n]=e.split("_");return(t??"")+n.map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join("")}function q(e){let t=e.replaceAll("_"," ");return t.charAt(0).toUpperCase()+t.slice(1)}var Mr=["asset","from","import","party","port","program","settlement"],$t=new Set(["{","}","(",")","[","]",":",",","=","|","."]),qr=new Set(Mr),Ur=e=>/[A-Za-z]/.test(e),Kr=e=>/[A-Za-z0-9_]/.test(e),on=e=>e>="0"&&e<="9";function bt(e){let t=[],n=[],r=0,o=(a,c,s,l=s)=>{t.push({kind:a,span:{end:r,start:c},text:s,value:l})};for(;r<e.length;){let a=e[r];if(a===" "||a===" "||a==="\r"||a===`
2
+ var De=["advance","captured_payment","conditional_disbursement","credit_facility","deposit","funding_round","held_payment","instant_transfer","metered","pooled_split","premium_forward","recurring_collection","rotating_pool","scheduled","settlement_batch","swap","weighted_distribution"],$e={advance:{eventCap:2,keys:["against","amount","count","every","fee","first_due","funder","to"],referenceableExits:[],required:["funder","to","amount"]},captured_payment:{eventCap:4,keys:["amount","capture_mode","correction","correction_mode","external_reversal","fees","negative_position","payee","payer","reserve_until","timeout"],referenceableExits:[],required:["payer","payee","amount","capture_mode","reserve_until","correction","external_reversal","correction_mode","negative_position","timeout"]},conditional_disbursement:{eventCap:1,keys:["amount","cap","decision","destination","recovery_policy","reopen_policy","source"],referenceableExits:[],required:["source","destination","cap","amount","decision","reopen_policy","recovery_policy"]},credit_facility:{eventCap:1,keys:["availability_policy","borrower","close_policy","draw_destination","expires_at","expiry_policy","lender","limit","obligation"],referenceableExits:[],required:["lender","borrower","draw_destination","limit","expires_at","obligation","availability_policy","expiry_policy","close_policy"]},deposit:{eventCap:1,keys:["amount","claim","holder","payer","return"],referenceableExits:[],required:["payer","holder","amount","claim","return"]},funding_round:{eventCap:4,keys:["beneficiary","cancel_policy","close_by","close_policy","commitment","contributor","fail_policy","max_contributors","overfund_policy","target"],referenceableExits:[],required:["contributor","beneficiary","target","commitment","max_contributors","close_by","close_policy","overfund_policy","cancel_policy","fail_policy"]},held_payment:{eventCap:7,keys:["amount","fees","on_cancel","payer","payee","release"],referenceableExits:["release"],required:["payer","payee","amount","release"]},instant_transfer:{eventCap:3,keys:["amount","fees","payer","payee"],referenceableExits:[],required:["payer","payee","amount"]},metered:{eventCap:14,keys:["close_by","payer","payee","rates"],maxRates:14,referenceableExits:[],required:["payer","payee","rates","close_by"]},pooled_split:{eventCap:14,keys:["amount","payer","payout_due","split"],maxRecipients:7,referenceableExits:[],required:["payer","amount","split","payout_due"]},premium_forward:{eventCap:6,keys:["amount","bind","carrier","commission","endorsement","endorsement_policy","lapse_policy","on_cancel","payer","policy_ref","renewal_due","renewal_policy"],referenceableExits:[],required:["payer","carrier","amount","bind"]},recurring_collection:{eventCap:0,keys:["attempt_policy","failure_policy","mandate","obligation","period_idempotency","retry_policy"],referenceableExits:[],required:["obligation","mandate","attempt_policy","period_idempotency","retry_policy","failure_policy"]},rotating_pool:{eventCap:3,keys:["contribution","count","default_policy","every","exit_policy","first_due","guarantee_policy","guarantor","members","payout_order"],referenceableExits:[],required:["members","contribution","count","every","first_due","payout_order","default_policy","guarantee_policy","exit_policy"]},scheduled:{eventCap:3,keys:["advance_to","amount","count","debtor","delinquency_policy","every","first_due","month_end","mode","partial_payment","period_liability","payer","payee","refund_policy","repayment_matching","reschedule_policy","termination_drain","timeout","until"],referenceableExits:["obligation"],required:["payer","payee","amount","every","first_due"]},settlement_batch:{eventCap:1,keys:["cadence","close_trigger","external_reversal_offsets","fee_entries","negative_position","payout_destination","payout_acknowledgement","payout_beneficiary_ref","settlement_account","source_capture_refs"],referenceableExits:[],required:["settlement_account","source_capture_refs","fee_entries","external_reversal_offsets","close_trigger","payout_destination","negative_position","payout_acknowledgement","payout_beneficiary_ref"]},swap:{eventCap:10,keys:["amounts","between","dispute","fees","release"],referenceableExits:[],required:["between","amounts","release"]},weighted_distribution:{eventCap:1,keys:["amount","correction_policy","max_recipients","recipient","record_at","rounding_policy","snapshot","source","weight","withholding_policy"],referenceableExits:[],required:["source","recipient","amount","weight","max_recipients","record_at","snapshot","rounding_policy","withholding_policy","correction_policy"]}};var wn=["business","person"],vn=["access","claim","good","service","ticket"];var tt=["count","every","first_due"],Ze=/^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/,_e=/^[a-z][A-Za-z0-9]*$/,rt=/^[A-Z]{3}$/,Ne=1e4;function ot(e){let t=[],n=(i,p)=>{t.push({message:p,severity:"error",span:i})},r=(i,p)=>{t.push({message:p,severity:"warning",span:i})},o=[],a=e.decls.filter(i=>i.kind==="program"),c=a[0];c||n({end:0,start:0},'the file needs a program header naming the company, like: program used_car_escrow "Used-car escrow"');for(let i of a.slice(1))n(i.span,"a file declares exactly one program");c&&!Ze.test(c.name.name)&&n(c.name.span,`the program name must be snake_case, like used_car_escrow; "${c.name.name}" is not`);let s=new Map;for(let i of e.decls)if(i.kind==="import"){if(i.from.value!=="settlement"){n(i.from.span,`"${i.from.value}" is not an importable module; the settlement algebra lives in "settlement"`);continue}for(let p of i.names){if(!De.includes(p.name)){n(p.span,`"settlement" has no archetype named ${p.name}; it offers ${De.join(", ")}`);continue}s.has(p.name)&&r(p.span,`${p.name} is imported more than once`),s.set(p.name,p.span)}}let l=new Map,u=(i,p)=>{if(i.name==="platform"||i.name==="escrow")return n(i.span,`the name ${i.name} is reserved: the platform and each settlement's escrow are always present without being declared`),!1;let d=l.get(i.name);return d?(n(i.span,`the name ${i.name} is already taken by a ${d.kind}; every party, asset, settlement, and port needs its own name`),!1):Ze.test(i.name)?(l.set(i.name,{kind:p,span:i.span}),!0):(n(i.span,`${p} names are snake_case; "${i.name}" is not`),!1)},f=new Map,v=new Map;for(let i of e.decls){if(i.kind==="party"){if(!u(i.name,"party"))continue;if(!wn.includes(i.partyKind.name)){n(i.partyKind.span,`a party is a ${wn.join(" or a ")}; "${i.partyKind.name}" is neither`);continue}i.attrs&&n(i.attrs.span,`party ${i.name.name} takes no attribute block yet`),f.set(i.name.name,{kind:i.partyKind.name,name:i.name.name,origin:i.span})}if(i.kind==="asset"){if(!u(i.name,"asset"))continue;if(!vn.includes(i.assetKind.name)){n(i.assetKind.span,`an asset is one of ${vn.join(", ")}; "${i.assetKind.name}" is none of those`);continue}let p="on_platform";for(let d of i.attrs?.entries??[]){if(d.key.name!=="title_transfer"){n(d.key.span,`asset ${i.name.name} does not understand "${d.key.name}"; the only attribute is title_transfer`);continue}let b=d.value;b.kind==="ident"&&(b.name==="off_platform"||b.name==="on_platform")?p=b.name:n(b.span,"title_transfer is either on_platform or off_platform")}v.set(i.name.name,{kind:i.assetKind.name,name:i.name.name,origin:i.span,titleTransfer:p})}}let x=e.decls.filter(i=>i.kind==="port"),k=e.decls.filter(i=>i.kind==="settlement");for(let i of k)u(i.name,"settlement");let T=new Set;for(let i of x)u(i.name,"port")&&T.add(i.name.name);let R=(i,p,d)=>{let b=new Map;for(let A of i.entries){if(!p.includes(A.key.name)){n(A.key.span,`${d} does not understand "${A.key.name}"; it takes ${p.join(", ")}`);continue}if(b.has(A.key.name)){n(A.key.span,`${d} sets ${A.key.name} twice`);continue}b.set(A.key.name,A)}return b},C=(i,p)=>{i.qualifiers.length>0&&n(i.span,`${i.key.name} on ${p} takes no ( ... ) qualifier`)},Q=new Set,B=(i,p)=>{if(i.kind==="ident"&&f.has(i.name))return Q.add(i.name),i.name;n(i.span,i.kind==="ident"?`${p} must name a declared party; there is no party named ${i.name}`:`${p} must name a declared party`)},W=new Set,H=[],ue=new Map,X=new Set(["currency","feeAmount","repayableAmount","serviceFeeAmount","clawbackAt","carvedFeeAmount","netOfCarvedFeeAmount","sideAServiceFeeAmount","sideBServiceFeeAmount"]),$=[/^piece\d+Amount$/,/^installment\d+Amount$/,/^repayment\d+Amount$/,/^carve(?:Hold|Recourse\d+)Id$/,/ShareAmount$/,/AccountId$/],D=(i,p,d)=>X.has(i)||$.some(b=>b.test(i))?(n(p,`${d} names a field ${i}, but the compiler reserves that name for a generated field; pick another name`),!0):!1,K=(i,p)=>{if(!i)return;C(i,p);let d=i.value;if(d.kind==="binding"&&d.type.kind==="call"&&d.type.callee.name==="money"&&(d.type.args.length===1||d.type.args.length===2)&&d.type.args[0]?.kind==="ident"&&(d.type.args.length===1||d.type.args[1]?.kind==="number")){let b=d.type.args[0].name,A=d.type.args.length===2&&d.type.args[1]?.kind==="number"?d.type.args[1].raw:void 0,m=A?Number(A):void 0;if(!_e.test(d.name.name))n(d.name.span,`the ${i.key.name} field is a camelCase name like price; "${d.name.name}" is not`);else if(!rt.test(b))n(d.type.args[0].span,`"${b}" is not a currency code; use three capital letters like SAR`);else if(A!==void 0&&(!/^[1-9][0-9]{0,17}$/.test(A)||!Number.isSafeInteger(m)))n(d.type.args[1].span,`${p} fixes ${i.key.name} to a positive safe integer in minor units`);else if(!D(d.name.name,d.name.span,p))return{currency:b,...m!==void 0?{fixedAmount:m}:{},name:d.name.name,origin:d.span};return}n(d.span,`${p} declares ${i.key.name} as a typed field, like: ${i.key.name}: price: money(SAR)`)},re=(i,p,d,b=!1)=>{if(!i)return;C(i,p);let A=i.value;if(A.kind!=="port_ref"){n(A.span,`${p} needs a ${d} decision, like: ${i.key.name}: port ${i.key.name}_decided`);return}if(A.within){n(A.within.span,`${i.key.name} on ${p} has no time window; only dispute accepts "within <duration>"`);return}if(A.deadline&&!b){n(A.deadline.span,`${i.key.name} on ${p} has no date default; only a held payment's release falls back to a date`);return}if(!T.has(A.name.name)){n(A.name.span,`${p} decides ${d} through port ${A.name.name}, but no port with that name is declared`);return}let m;if(A.deadline){if(!_e.test(A.deadline.name)){n(A.deadline.span,`at( ... ) names a camelCase date field, like at(releaseDueAt); "${A.deadline.name}" is not`);return}if(D(A.deadline.name,A.deadline.span,p))return;m=A.deadline.name}return W.add(A.name.name),{...m?{deadlineField:m}:{},origin:A.span,port:A.name.name}},ee=(i,p,d="dispute")=>{if(!i)return;C(i,p);let b=i.value;if(b.kind!=="port_ref"){n(b.span,`${p} needs one ${d} decision through a fixed windowed port`);return}if(!T.has(b.name.name)){n(b.name.span,`${p} routes ${d} through port ${b.name.name}, but no port with that name is declared`);return}if(!b.within){n(b.span,`${p} ${d} needs a fixed window, like: ${i.key.name}: port ${b.name.name} within P14D`);return}let A=b.within.name,m=/^P([1-9]\d{0,3})([DW])$/.exec(A);if(!m){n(b.within.span,`${d} on ${p} uses a fixed duration in days or weeks, like P14D; calendar months cannot define an exact money deadline`);return}let O=Number(m[1]),J=m[2]==="W"?O*7:O;return W.add(b.name.name),{origin:b.span,port:b.name.name,window:{days:J,raw:A}}},U=(i,p,d)=>{if(i){if(C(i,p),i.value.kind!=="percent"){n(i.value.span,`${d} on ${p} must be a percent`);return}if(i.value.bps>=Ne){n(i.value.span,`a ${i.value.raw}% ${d} consumes the whole amount; it stays under 100%`);return}return i.value.bps===0&&r(i.value.span,`${d} on ${p} is 0%; drop the entry if none is meant`),i.value.bps}},F=(i,p,d,b,A,m)=>{let O=[];if(!i)return O;if(C(i,p),i.value.kind!=="block")return n(i.value.span,"fees is a block of party rules, like: fees { buyer: 1% }"),O;let J=(w,h)=>{if(w.value.kind!=="binding"){n(w.value.span,`${p} exact fee for ${h} declares immutable money in place, like feeAmount: money(SAR); it cannot reference a mutable field`);return}let E=K(w,`${p} fee for ${h}`);if(!E)return;let P=b.get(h);return P&&E.currency!==P.currency&&n(E.origin,`${p} fee field ${E.name} must use the base currency ${P.currency}`),A.has(E.name)?n(E.origin,`${p} fee field ${E.name} reuses another field declared by the settlement; every settlement field needs a distinct name`):A.add(E.name),{amount:E,kind:"exact"}},z=(w,h)=>{if(w.value.kind==="percent"){if(w.value.bps>=Ne){n(w.value.span,`a ${w.value.raw}% fee consumes the whole amount; fees stay under 100%`);return}if(w.value.bps===0){n(w.value.span,`the fee for ${h} is 0%; drop the entry if no fee is meant`);return}return{bps:w.value.bps,kind:"bps"}}return J(w,h)},g=(w,h,E)=>{if(w){if(w.value.kind!=="number"||!/^(0|[1-9][0-9]{0,17})$/.test(w.value.raw)){n(w.value.span,`tier ${E} for ${h} must be a non-negative integer minor-unit amount`);return}return BigInt(w.value.raw).toString()}},_=(w,h)=>{if(w.value.kind!=="block")return;let E=w.value.entries.filter(L=>L.key.name==="tier");for(let L of w.value.entries.filter(S=>S.key.name!=="tier"))n(L.key.span,`the tiered fee for ${h} contains only repeated tier blocks`);if(E.length===0){n(w.value.span,`the tiered fee for ${h} needs a tier`);return}let P=[];for(let L of E){if(L.value.kind!=="block"){n(L.value.span,`tier for ${h} must be a block`);continue}let S=L.value.entries.filter(pe=>pe.key.name==="from"),j=L.value.entries.filter(pe=>pe.key.name==="to"),V=L.value.entries.filter(pe=>pe.key.name==="fee");for(let pe of L.value.entries.filter(ke=>!["fee","from","to"].includes(ke.key.name)))n(pe.key.span,`tier for ${h} contains only from, optional to, and one fee`);S.length!==1&&n(L.span,`tier for ${h} needs exactly one from threshold`),j.length>1&&n(L.span,`tier for ${h} sets its exclusive to threshold twice`),V.length!==1&&n(L.span,`tier for ${h} selects exactly one fee value`);let G=g(S[0],h,"from"),oe=g(j[0],h,"to"),ie=V[0]?z(V[0],h):void 0;!G||!ie||P.push({fromInclusive:G,origin:L.span,rule:ie,...oe?{toExclusive:oe}:{}})}for(let[L,S]of P.entries()){L===0&&S.fromInclusive!=="0"&&n(S.origin,`the first tier for ${h} must begin at 0`),S.toExclusive!==void 0&&BigInt(S.toExclusive)<=BigInt(S.fromInclusive)&&n(S.origin,`tier for ${h} must end after its from threshold`);let j=P[L-1];if(j){if(j.toExclusive===void 0)n(S.origin,`only the final tier for ${h} may be open-ended`);else if(j.toExclusive!==S.fromInclusive){let V=BigInt(j.toExclusive)<BigInt(S.fromInclusive)?"gap":"overlap";n(S.origin,`tiers for ${h} have ${V==="overlap"?"an":"a"} ${V}: expected from ${j.toExclusive}, found ${S.fromInclusive}`)}}}let N=P.at(-1);return N?.toExclusive!==void 0&&n(N.origin,`the final tier for ${h} must be open-ended to cover every amount`),P.length===E.length?{kind:"tiered",tiers:P}:void 0};for(let w of i.value.entries){let h=w.key.name;if(!d.includes(h)){n(w.key.span,`fees are borne by this settlement's parties; ${h} is neither an allowed bearer nor part of this settlement`);continue}if(O.some(P=>P.bearer===h)){n(w.key.span,`${p} sets a fee for ${h} twice`);continue}let E=w.value.kind==="block"?_(w,h):z(w,h);E&&O.push({bearer:h,origin:w.span,position:m(h),rule:E})}return O},M=(i,p,d,b,A)=>{if(i.value.kind!=="block"){n(i.value.span,`${i.key.name} on ${p} is a block of percent shares, like: { ${d[0]??"party"}: 100% }`);return}let m=[],O,J=0,z=!0;for(let g of i.value.entries){let _=g.key.name;if(_==="remainder_to"){if(!A){n(g.key.span,`${p} does not take remainder_to here; the first share carries the integer remainder`),z=!1;continue}if(g.value.kind!=="ident"){n(g.value.span,"remainder_to names one of the recipients"),z=!1;continue}if(O){n(g.key.span,`${p} sets remainder_to twice`),z=!1;continue}O={name:g.value.name,span:g.value.span};continue}if(!d.includes(_)){n(g.key.span,`the ${i.key.name} split goes to ${b}; ${_} is not among them`),z=!1;continue}if(Q.add(_),m.some(w=>w.to===_)){n(g.key.span,`${p} splits to ${_} twice`),z=!1;continue}if(g.value.kind!=="percent"){n(g.value.span,`the share for ${_} must be a percent`),z=!1;continue}if(g.value.bps===0){n(g.value.span,`the share for ${_} is 0%; drop ${_} from the split instead of giving it nothing`),z=!1;continue}m.push({bps:g.value.bps,origin:g.span,to:_}),J+=g.value.bps}if(z&&J!==Ne&&(n(i.value.span,`the ${i.key.name} split must account for exactly 100%; these shares total ${(J/100).toFixed(2).replace(/\.?0+$/,"")}%`),z=!1),O&&!m.some(g=>g.to===O?.name)&&(n(O.span,`remainder_to must name one of the split's recipients; ${O.name} holds no share`),z=!1),!(!z||m.length===0))return{...O?{remainderTo:O.name}:{},shares:m}},ce=(i,p,d,b)=>{if(!i)return;let A=i.qualifiers[0];if(i.qualifiers.length!==1||A?.name!=="funded"){n(i.span,"on_cancel states the phase it covers; today that is on_cancel(funded)");return}let m=M(i,p,d,b,!1);if(m)return{origin:i.span,shares:m.shares,when:"funded"}},ae=(i,p)=>{if(i){if(C(i,p),i.value.kind==="ident"&&_e.test(i.value.name))return D(i.value.name,i.value.span,p)?void 0:i.value.name;n(i.value.span,`${i.key.name} on ${p} names a camelCase date field, like: ${i.key.name}: dueDate`)}},ge=(i,p)=>{if(i){if(C(i,p),i.value.kind==="ident"&&_e.test(i.value.name))return D(i.value.name,i.value.span,p)?void 0:i.value.name;n(i.value.span,`${i.key.name} on ${p} names a camelCase lineage field, like: ${i.key.name}: captureReference`)}},ne=(i,p,d,b)=>i?(C(i,p),i.value.kind==="ident"&&i.value.name===d?!0:(n(i.value.span,`${i.key.name} on ${p} is ${d}; ${b}`),!1)):!1,Gn=(i,p,d,b,A)=>{if(!i)return;C(i,p);let m=i.value.kind==="number"?Number(i.value.raw):Number.NaN;if(Number.isInteger(m)&&m>=b&&m<=A)return m;n(i.value.span,`${d} on ${p} is a literal integer from ${b} through ${A}`)},Xn=(i,p,d,b,A)=>{if(!i)return;if(C(i,p),i.value.kind!=="list"||i.value.items.length<b||i.value.items.length>A){n(i.value.span,`${d} on ${p} lists ${b} through ${A} declared parties`);return}let m=i.value.items.map(O=>B(O,`${p} ${d}`)).filter(O=>O!==void 0);if(new Set(m).size!==m.length){n(i.value.span,`${d} on ${p} must not repeat a party`);return}return m.length===i.value.items.length?m:void 0},Zn=(i,p,d,b=12,A=!1)=>{let m=i.get("count"),O=i.get("every"),J;if(m){C(m,p);let S=m.value,j=S.kind==="number"?Number(S.raw):Number.NaN;Number.isInteger(j)&&j>=2&&j<=b?J=j:n(S.span,`count on ${p} is a literal number of anchors between 2 and ${b}; the schedule stays finite by construction`)}let z,g;if(O){C(O,p);let S=O.value,j=S.kind==="ident"?S.name:S.kind==="string"?S.value:void 0,V=j?/^P([1-9]\d{0,3})([DW])$/.exec(j):null;if(V&&j){let G=Number(V[1]);z={days:V[2]==="W"?G*7:G,raw:j}}else if(j&&/^P([1-9]\d{0,3})M$/.test(j)){let G=Number(/^P([1-9]\d{0,3})M$/.exec(j)?.[1]);A?g={months:G,raw:j}:n(S.span,`every on ${p} uses calendar months, which only an open scheduled obligation may use`)}else n(S.span,`every on ${p} is P<n>D, P<n>W, or P<n>M on an open scheduled obligation`)}let _=ae(i.get("first_due"),p);if(!g)return z&&!m&&n(d,`${p} has a finite schedule without count`),J===void 0||!z||!_?void 0:{count:J,every:z,firstDueField:_,kind:"finite",origin:d};m&&n(m.span,`${p} combines count with an open monthly recurrence; use count for a finite schedule or until for an open schedule`);let w=i.get("until"),h;if(!w)n(d,`${p} has an open recurrence without until`);else{C(w,p);let S=w.value;if(S.kind==="port_ref")if(S.deadline||S.within)n(S.span,`until on ${p} is ambiguous; choose one port or one stored date`);else{let j=re(w,p,"termination");j&&(h={kind:"port",port:j})}else S.kind==="call"&&S.callee.name==="at"&&S.args.length===1&&S.args[0]?.kind==="ident"&&_e.test(S.args[0].name)?h={field:S.args[0].name,kind:"stored_date",origin:S.span}:n(S.span,`until on ${p} names one termination: port <name> or at(<storedDateField>)`)}for(let S of["month_end","period_liability","termination_drain"])i.has(S)||n(d,`${p} is missing ${S}`);let E=ne(i.get("month_end"),p,"clamp_to_last_day","calendar months need an explicit rule for anchors whose day is absent"),P=ne(i.get("period_liability"),p,"one_open","a new period cannot open while the prior period remains liable"),N=i.get("termination_drain"),L;if(N){C(N,p);let S=N.value,j=h?.kind==="port"?h.port.port:"cancel_period";S.kind==="ident"&&Ze.test(S.name)&&S.name===j?L=S.name:n(S.span,`termination_drain on ${p} must name its actual cancel action ${j}`)}if(i.has("timeout")&&n(i.get("timeout").span,`${p} pairs recurrence with a timeout money move; time may open or cancel a period but never collect money`),!(!_||!h||!E||!P||!L||m||i.has("timeout")))return{every:g,firstDueField:_,kind:"open",monthEnd:"clamp_to_last_day",origin:d,periodLiability:"one_open",termination:h,terminationDrain:L}},Qn=(i,p,d,b=12)=>{let A=Zn(i,p,d,b);return A?.kind==="finite"?A:void 0},gn=(i,p)=>{C(i,p);let d=i.value;if(d.kind!=="settlement_ref"){n(d.span,`${p} draws against a held payment's release, like: against: retention.release`);return}let b=d.owner.name,A=k.find(J=>J.name.name===b);if(!A){let J=l.get(b);n(d.owner.span,J?`${p} references ${b}, which is a ${J.kind}; settlement exits belong to settlements`:`${p} references ${b}, but no settlement with that name is declared`);return}let m=A.archetype.name;if(!De.includes(m))return;let O=$e[m].referenceableExits;if(!O.includes(d.member.name)){let J=O.length>0?`it exposes ${O.join(", ")}`:"it exposes no referenceable exits";n(d.member.span,`${p} references ${b}.${d.member.name}, but ${m} does not expose that exit; ${J}`);return}return{exit:d.member.name,origin:d.span,settlement:b,targetArchetype:m}},Zt=(i,p,d)=>{let b=i.get("against"),A=tt.filter(O=>i.has(O));if(b&&A.length>0){n(b.span,`${p} is repaid by a carve and by its own schedule (${A.join(", ")}); an advance draws on one source`);return}if(!b){if(A.length===0){n(d,`${p} needs a repayment source: against: <hold>.release carves it out of a hold's release, or count + every + first_due collects it on a schedule`);return}for(let J of tt)i.has(J)||n(d,`${p} is missing ${J}`);let O=Qn(i,p,d);return O?{kind:"schedule",schedule:O}:void 0}let m=gn(b,p);return m?{kind:"carve",...m}:void 0};for(let i of k){let p=i.archetype.name;if(!s.has(p)){n(i.archetype.span,De.includes(p)?`${p} must be imported first: import { ${p} } from "settlement"`:`there is no settlement archetype named ${p}`);continue}let d=`settlement ${i.name.name}`,b=new Set,A=$e[p],m=R(i.body,[...A.keys,...p==="deposit"?["claim_amount"]:[],"derived_amount"],d);for(let g of A.required)m.has(g)||n(i.span,`${d} is missing ${g}`);p==="scheduled"&&!m.has("count")&&!m.has("every")&&n(i.span,`${d} is missing count`);let O=(g,_)=>{let w=m.get(g);if(w)return C(w,d),B(w.value,`${d} ${_}`)},J=(g,_,w)=>g&&_&&g===_?(n(i.span,`${d} ${w}`),!1):!0,z=m.get("derived_amount");if(z)if(C(z,d),z.value.kind!=="block")n(z.value.span,"derived_amount is a block with field, source, rule, and bearer");else{let g=R(z.value,["field","source","rule","bearer"],`${d} derived_amount`);for(let S of["field","source","rule","bearer"])g.has(S)||n(z.span,`${d} derived_amount is missing ${S}`);let _=g.get("field")?.value,w=g.get("source")?.value,h=g.get("rule")?.value,E=g.get("bearer")?.value,P=_?.kind==="ident"?_.name:void 0,N=w?.kind==="ident"?w.name:void 0,L=E?B(E,`${d} derived amount bearer`):void 0;_&&_.kind!=="ident"&&n(_.span,"derived amount field must be a camelCase identifier"),w&&w.kind!=="ident"&&n(w.span,"derived amount source must name one stored money field"),h&&h.kind!=="percent"&&n(h.span,"derived_amount proves percentage-of rules only; fixed and tiered rules are refused"),h?.kind==="percent"&&(h.bps<=0||h.bps>=Ne)&&n(h.span,"derived amount percentage must be above 0% and below 100%"),P&&!_e.test(P)&&n(_.span,`derived amount field ${P} must be camelCase`),P&&_e.test(P)&&b.add(P),N&&!_e.test(N)&&n(w.span,`derived amount source ${N} must be camelCase`),P&&N&&P===N&&n(z.span,"derived amount field must differ from its source field"),P&&N&&L&&h?.kind==="percent"&&h.bps>0&&h.bps<Ne&&o.push({baseField:N,bearer:L,bps:h.bps,field:P,origin:z.span,settlement:i.name.name})}switch(p){case"captured_payment":{let g=O("payer","payer"),_=O("payee","payee"),w=J(g,_,`pays ${g} from ${g}; payer and payee must differ`),h=K(m.get("amount"),d),E=ae(m.get("reserve_until"),d),P=re(m.get("correction"),d,"payee correction"),N=ee(m.get("external_reversal"),d,"external reversal"),L=ne(m.get("capture_mode"),d,"partial_then_full","capture calls must leave a remainder and settle posts the final remainder"),S=ne(m.get("correction_mode"),d,"full_only","repeated partial corrections are not representable yet, so the checker refuses them"),j=ne(m.get("negative_position"),d,"reject","a correction or reversal must fail when the payee cannot fund it"),V=ne(m.get("timeout"),d,"reject","a timeout records no money movement; only a confirmed decision may reverse funds");if(m.has("fees")&&n(m.get("fees").span,`${d} does not price fees inside captured_payment; compose a separate fee settlement so capture and correction amounts stay exact`),h&&E===h.name){n(m.get("reserve_until")?.span??i.span,`${d} uses ${h.name} as both the reserved amount and reserve_until date field; they need distinct names`);break}g&&_&&h&&E&&P&&N&&L&&S&&j&&V&&w&&H.push({amount:h,archetype:"captured_payment",correction:P,externalReversal:N,name:i.name.name,origin:i.span,payee:_,payer:g,reserveUntilField:E});break}case"settlement_batch":{let g=O("settlement_account","settlement account"),_=O("payout_destination","payout destination"),w=J(g,_,`routes payout from ${g} back to itself; settlement account and payout destination must differ`),h=ge(m.get("source_capture_refs"),d),E=ge(m.get("fee_entries"),d),P=ge(m.get("external_reversal_offsets"),d),N=ae(m.get("close_trigger"),d),L=m.get("cadence"),S;if(L){C(L,d);let ie=L.value,pe=ie.kind==="ident"?/^P([1-9]\d{0,3})([DW])$/.exec(ie.name):null;if(!pe)n(ie.span,`${d} cadence uses a fixed duration in days or weeks, like P7D`);else{let ke=Number(pe[1]);S={days:pe[2]==="W"?ke*7:ke,raw:pe.input}}}let j=re(m.get("payout_acknowledgement"),d,"payout acknowledgement"),V=ge(m.get("payout_beneficiary_ref"),d),G=ne(m.get("negative_position"),d,"reject","offsets beyond gross capture entries must stop calculation and post no payout"),oe=[h,E,P,N,V].filter(ie=>ie!==void 0);if(new Set(oe).size!==oe.length){n(i.span,`${d} needs distinct source_capture_refs, fee_entries, external_reversal_offsets, close_trigger, and payout_beneficiary_ref field names`);break}g&&_&&h&&E&&P&&N&&j&&V&&G&&w&&H.push({archetype:"settlement_batch",...S?{cadence:S}:{},closeTriggerField:N,externalReversalReferenceField:P,feeReferenceField:E,name:i.name.name,origin:i.span,payoutDestination:_,payoutAcknowledgement:j,payoutBeneficiaryReferenceField:V,settlementAccount:g,sourceCaptureReferenceField:h});break}case"funding_round":{let g=O("contributor","contributor"),_=O("beneficiary","beneficiary"),w=K(m.get("target"),d),h=K(m.get("commitment"),d),E=Gn(m.get("max_contributors"),d,"max_contributors",2,1e4),P=ae(m.get("close_by"),d),N=[ne(m.get("close_policy"),d,"threshold","close must follow the locked committed sum at the stored close date"),ne(m.get("overfund_policy"),d,"reject","a commitment past the remaining target headroom must refuse"),ne(m.get("cancel_policy"),d,"before_close","a commitment may cancel only while its parent remains open"),ne(m.get("fail_policy"),d,"whole_commitment_refund","failure refunds each stored commitment whole")].every(Boolean),L=J(g,_,`uses ${g} as both contributor and beneficiary; the roles must differ`);w&&h&&w.currency!==h.currency&&n(h.origin,`${d} mixes ${w.currency} and ${h.currency}; target and commitment need one currency`),w&&h&&w.name===h.name&&n(h.origin,`${d} uses ${w.name} for both target and commitment; the parent and child amounts need distinct fields`),g&&_&&w&&h&&w.currency===h.currency&&w.name!==h.name&&E&&P&&N&&L&&H.push({archetype:"funding_round",beneficiary:_,cancelPolicy:"before_close",closeByField:P,closePolicy:"threshold",commitment:h,contributor:g,failPolicy:"whole_commitment_refund",maxContributors:E,name:i.name.name,origin:i.span,overfundPolicy:"reject",target:w});break}case"weighted_distribution":{let g=O("source","source"),_=O("recipient","recipient template"),w=K(m.get("amount"),d),h=K(m.get("weight"),d),E=Gn(m.get("max_recipients"),d,"max_recipients",2,1e4),P=ae(m.get("record_at"),d),N=re(m.get("snapshot"),d,"entitlement snapshot"),L=[ne(m.get("rounding_policy"),d,"largest_remainder","floor shares use a deterministic largest-remainder allocation with instrument id as the tie-break"),ne(m.get("withholding_policy"),d,"refuse","withholding needs its own proved retained-amount mechanism"),ne(m.get("correction_policy"),d,"new_distribution","post-payout correction is a new linked distribution, never a rewrite or caller amount")].every(Boolean),S=J(g,_,`uses ${g} as both source and recipient; the roles must differ`);w&&h&&w.currency!==h.currency&&n(h.origin,`${d} mixes ${w.currency} and ${h.currency}; pool and stored weights need one denomination`),w&&h&&w.name===h.name&&n(h.origin,`${d} uses ${w.name} for both pool and weight; the fields must differ`),g&&_&&w&&h&&w.currency===h.currency&&w.name!==h.name&&E&&P&&N&&L&&S&&H.push({amount:w,archetype:"weighted_distribution",correctionPolicy:"new_distribution",maxRecipients:E,name:i.name.name,origin:i.span,recipient:_,recordAtField:P,roundingPolicy:"largest_remainder",snapshot:N,source:g,weight:h,withholdingPolicy:"refuse"});break}case"credit_facility":{let g=O("lender","lender"),_=O("borrower","borrower"),w=O("draw_destination","draw destination"),h=K(m.get("limit"),d),E=ae(m.get("expires_at"),d),P=m.get("obligation"),N=P?gn(P,d):void 0,L=m.get("availability_policy"),S;L?.value.kind==="ident"&&(L.value.name==="revolving"||L.value.name==="non_revolving")?S=L.value.name:L&&n(L.value.span,`availability_policy on ${d} is revolving or non_revolving; the factpack does not justify an implicit choice`);let j=[ne(m.get("expiry_policy"),d,"freeze_draws","expiry stops new draws without closing linked debt"),ne(m.get("close_policy"),d,"no_open_draws","the facility closes only after every linked obligation resolves")].every(Boolean),V=[J(g,_,`uses ${g} as both lender and borrower; the roles must differ`),J(g,w,`draws back to its lender ${g}; draw_destination must differ`)].every(Boolean);g&&_&&w&&h&&E&&N&&S&&j&&V&&H.push({archetype:"credit_facility",availabilityPolicy:S,borrower:_,closePolicy:"no_open_draws",drawDestination:w,expiresAtField:E,expiryPolicy:"freeze_draws",lender:g,limit:h,name:i.name.name,obligation:N,origin:i.span});break}case"recurring_collection":{let g=m.get("obligation"),_=g?gn(g,d):void 0,w=re(m.get("mandate"),d,"mandate evidence"),h=[ne(m.get("attempt_policy"),d,"explicit","every attempt is a separate receipted call"),ne(m.get("period_idempotency"),d,"obligation_and_anchor","the parent obligation and stored anchor form the period identity"),ne(m.get("retry_policy"),d,"explicit_attempt","PRINCIPLES.md bans hidden retries; a retry needs a new explicit idempotency key"),ne(m.get("failure_policy"),d,"parent_delinquency","the scheduled obligation owns due state and delinquency")].every(Boolean);_&&w&&h&&H.push({archetype:"recurring_collection",attemptPolicy:"explicit",failurePolicy:"parent_delinquency",mandate:w,name:i.name.name,obligation:_,origin:i.span,periodIdempotency:"obligation_and_anchor",retryPolicy:"explicit_attempt"});break}case"conditional_disbursement":{let g=O("source","source"),_=O("destination","destination"),w=K(m.get("cap"),d),h=K(m.get("amount"),d),E=re(m.get("decision"),d,"capped disbursement decision"),P=[ne(m.get("reopen_policy"),d,"refuse","a closed decision cannot be reopened; create a new linked disbursement"),ne(m.get("recovery_policy"),d,"separate_transfer","recovery is a new money movement with its own receipt")].every(Boolean),N=J(g,_,`pays ${g} from itself; source and destination must differ`);w&&h&&w.currency!==h.currency&&n(h.origin,`${d} mixes ${w.currency} and ${h.currency}; cap and approved amount need one currency`),w&&h&&w.name===h.name&&n(h.origin,`${d} uses ${w.name} for both cap and approved amount; the fields must differ`),g&&_&&w&&h&&w.currency===h.currency&&w.name!==h.name&&E&&P&&N&&H.push({amount:h,archetype:"conditional_disbursement",cap:w,decision:E,destination:_,name:i.name.name,origin:i.span,recoveryPolicy:"separate_transfer",reopenPolicy:"refuse",source:g});break}case"rotating_pool":{let g=Xn(m.get("members"),d,"members",2,5),_=Xn(m.get("payout_order"),d,"payout_order",2,5),w=K(m.get("contribution"),d),h=Qn(m,d,i.span,12),E=m.has("guarantor")?O("guarantor","guarantor"):void 0,P=[ne(m.get("default_policy"),d,"due_condition","default follows an unmet stored contribution due condition"),ne(m.get("guarantee_policy"),d,"funded_only","a guarantee changes money only through an explicit funded contribution"),ne(m.get("exit_policy"),d,"before_activation_only","membership and order freeze before the first contribution")].every(Boolean),N=!0;if(g&&_){let L=new Set(g);(_.length!==g.length||_.some(S=>!L.has(S)))&&(n(m.get("payout_order")?.span??i.span,`${d} payout_order must contain every member exactly once`),N=!1)}g&&h&&h.count!==g.length&&(n(m.get("count")?.span??i.span,`${d} count ${h.count} must equal its ${g.length}-member roster`),N=!1),g&&E&&g.includes(E)&&(n(m.get("guarantor")?.span??i.span,`${d} guarantor must differ from every member`),N=!1),g&&E&&g.length>4&&(n(m.get("members")?.span??i.span,`${d} supports at most 4 members with a guarantor so every generated child binding stays within the 8-entry cap`),N=!1),g&&_&&w&&h&&P&&N&&H.push({archetype:"rotating_pool",contribution:w,defaultPolicy:"due_condition",exitPolicy:"before_activation_only",guaranteePolicy:"funded_only",...E?{guarantor:E}:{},members:g,name:i.name.name,origin:i.span,payoutOrder:_,schedule:h});break}case"swap":{let g=m.get("between"),_,w;g&&(C(g,d),g.value.kind!=="list"||g.value.items.length!==2?n(g.value.span,`${d} swaps between exactly two parties, like: between: [buyer, seller]`):(_=B(g.value.items[0],`${d} first side`),w=B(g.value.items[1],`${d} second side`),J(_,w,`names ${_} on both sides; the two swap parties must differ`)));let h=new Map,E=m.get("amounts");if(E)if(C(E,d),E.value.kind!=="block")n(E.value.span,`${d} amounts is a two-party block, like: amounts { buyer: buyerPays: money(SAR), seller: sellerPays: money(SAR) }`);else for(let V of E.value.entries){let G=V.key.name;if(G!==_&&G!==w){n(V.key.span,`${d} amount belongs to one of its two parties; ${G} is not in between`);continue}if(h.has(G)){n(V.key.span,`${d} declares more than one amount for ${G}`);continue}let oe=K(V,d);oe&&(h.set(G,oe),b.add(oe.name))}let P=_?h.get(_):void 0,N=w?h.get(w):void 0;_&&!P&&n(E?.span??i.span,`${d} needs exactly one funded amount for ${_}`),w&&!N&&n(E?.span??i.span,`${d} needs exactly one funded amount for ${w}`),P&&N&&P.currency!==N.currency&&n(E?.span??i.span,`${d} cannot link ${P.currency} and ${N.currency} in one atomic ledger batch; both amounts need one currency`);let L=re(m.get("release"),d,"whole-trade release"),S=ee(m.get("dispute"),d),j=F(m.get("fees"),d,[_,w].filter(V=>V!==void 0),h,b,()=>"on_top");if(_&&w&&P&&N&&P.currency===N.currency&&L){let V=j.find(oe=>oe.bearer===_),G=j.find(oe=>oe.bearer===w);H.push({archetype:"swap",...S?{dispute:S}:{},name:i.name.name,origin:i.span,release:L,sides:[{amount:P,...V?{fee:V}:{},party:_},{amount:N,...G?{fee:G}:{},party:w}]})}break}case"held_payment":{let g=O("payer","payer"),_=O("payee","payee"),w=J(g,_,`pays ${g} from ${g}; payer and payee must differ`),h=K(m.get("amount"),d),E=re(m.get("release"),d,"release",!0);h&&b.add(h.name),E?.deadlineField&&b.add(E.deadlineField);let P=F(m.get("fees"),d,[g,_].filter(S=>S!==void 0),new Map(h&&g&&_?[[g,h],[_,h]]:[]),b,S=>S===_?"carved":"on_top"),N=ce(m.get("on_cancel"),d,[g,_].filter(S=>S!==void 0),"this settlement's payer or payee"),L=P.find(S=>S.position==="carved"&&S.rule.kind!=="bps");if(L&&n(L.origin,`${d} supports exact and tiered carved fees on straight-through payments; held_payment currently requires a bps carved fee so cancellation and release share one fixed partition`),h&&E?.deadlineField===h.name){n(E.origin,`${d} uses ${h.name} as both the held amount and the release date field; they need distinct names`);break}g&&_&&h&&E&&w&&!L&&H.push({amount:h,archetype:"held_payment",fees:P,name:i.name.name,...N?{onCancel:N}:{},origin:i.span,payee:_,payer:g,release:{origin:E.origin,port:E.port},...E.deadlineField?{releaseDeadlineField:E.deadlineField}:{}});break}case"instant_transfer":{let g=O("payer","payer"),_=O("payee","payee"),w=J(g,_,`pays ${g} from ${g}; payer and payee must differ`),h=K(m.get("amount"),d);h&&b.add(h.name);let E=F(m.get("fees"),d,[g,_].filter(P=>P!==void 0),new Map(h&&g&&_?[[g,h],[_,h]]:[]),b,P=>P===_?"carved":"on_top");g&&_&&h&&w&&H.push({amount:h,archetype:"instant_transfer",fees:E,name:i.name.name,origin:i.span,payee:_,payer:g});break}case"premium_forward":{let g=O("payer","payer"),_=O("carrier","carrier"),w=J(g,_,`forwards the premium from ${g} to ${g}; payer and carrier must differ`),h=K(m.get("amount"),d),E=re(m.get("bind"),d,"binding"),P=U(m.get("commission"),d,"commission")??0,N=ce(m.get("on_cancel"),d,[g,_].filter(ie=>ie!==void 0),"this settlement's payer or carrier"),L=["policy_ref","renewal_due","renewal_policy","endorsement","endorsement_policy","lapse_policy"],S=L.some(ie=>m.has(ie));if(S)for(let ie of L)m.has(ie)||n(i.span,`${d} is missing ${ie}`);let j=S?ge(m.get("policy_ref"),d):void 0,V=S?ae(m.get("renewal_due"),d):void 0,G=S?re(m.get("endorsement"),d,"endorsement evidence"):void 0,oe=S?[ne(m.get("renewal_policy"),d,"explicit_new_forward","each renewal creates a new premium_forward instead of moving money from policy state"),ne(m.get("endorsement_policy"),d,"non_money_only","a money adjustment needs a separate corrected movement"),ne(m.get("lapse_policy"),d,"due_condition","lapse follows the stored renewal due condition")].every(Boolean):!0;if(g&&_&&h&&E&&w&&oe&&(!S||j&&V&&G)){let ie={amount:h,archetype:"premium_forward",bind:E,carrier:_,commissionBps:P,...G?{endorsement:G}:{},...S&&j&&V&&G?{endorsementPolicy:"non_money_only",lapsePolicy:"due_condition",policyReferenceField:j,renewalDueField:V,renewalPolicy:"explicit_new_forward"}:{},name:i.name.name,...N?{onCancel:N}:{},origin:i.span,payer:g};H.push(ie)}break}case"deposit":{let g=O("payer","payer"),_=O("holder","holder"),w=J(g,_,`holds ${g}'s deposit for ${g}; payer and holder must differ`),h=K(m.get("amount"),d),E=re(m.get("claim"),d,"claim"),P=re(m.get("return"),d,"return"),N=m.get("claim_amount"),L;if(N){C(N,d);let S=N.value;if(S.kind!=="decided_amount")n(S.span,`${d} claim_amount must be decided { field: <portMoneyField>, bound: ${h?.name??"<depositAmount>"}, remainder: return }`);else{let j=`${d} decided claim_amount`,V=R(S.body,["field","bound","remainder"],j);for(let pe of["field","bound","remainder"])V.has(pe)||n(S.span,`${j} is missing ${pe}`);let G=V.get("field")?.value,oe=V.get("bound")?.value,ie=V.get("remainder")?.value;G&&G.kind!=="ident"&&n(G.span,`${j} field must name a port field`),oe&&oe.kind!=="ident"&&n(oe.span,`${j} bound must name the stored deposit amount`),ie&&ie.kind!=="ident"&&n(ie.span,`${j} remainder must name the return exit`),G?.kind==="ident"&&oe?.kind==="ident"&&ie?.kind==="ident"&&(L={boundField:oe.name,boundOrigin:oe.span,field:G.name,fieldOrigin:G.span,origin:S.span,remainderExit:ie.name,remainderOrigin:ie.span})}}if(E&&P&&E.port===P.port){n(P.origin,`${d} claims and returns through the same port ${E.port}; the two exits need their own ports`);break}if(g&&_&&h&&E&&P&&w){let S={amount:h,archetype:"deposit",claim:E,holder:_,name:i.name.name,origin:i.span,payer:g,return:P};H.push(S),L&&ue.set(S,L)}break}case"scheduled":{let g=O("payer","payer"),_=O("payee","payee"),w=J(g,_,`pays ${g} from ${g}; payer and payee must differ`),h=K(m.get("amount"),d),E=m.get("mode")?.value,P=E?.kind==="ident"&&E.name==="obligation",N=Zn(m,d,i.span,P?7:12,!0);if(N?.kind==="open"&&!P&&n(N.origin,`${d} uses an open recurrence without mode: obligation; open periods need explicit liability and delinquency state`),h&&N&&h.name===N.firstDueField){n(N.origin,`${d} uses ${h.name} as both the amount and the first_due date field; they need distinct names`);break}let L=m.get("mode"),j=["advance_to","debtor","delinquency_policy","partial_payment","refund_policy","repayment_matching","reschedule_policy"].some(ke=>m.has(ke));if(!L&&j){n(i.span,`${d} uses obligation policies without mode: obligation`);break}if(!L){g&&_&&h&&N&&w&&H.push({amount:h,archetype:"scheduled",mode:"transfer",name:i.name.name,origin:i.span,payee:_,payer:g,schedule:N});break}if(!ne(L,d,"obligation","omit mode for a fixed transfer schedule"))break;let V=["debtor","partial_payment","repayment_matching","refund_policy","reschedule_policy","delinquency_policy"];for(let ke of V)m.has(ke)||n(i.span,`${d} is missing ${ke}`);let G=O("debtor","debtor"),oe=m.has("advance_to")?O("advance_to","advance recipient"):void 0,ie=[ne(m.get("partial_payment"),d,"anchor_bound","payments must bind to one stored installment anchor"),ne(m.get("repayment_matching"),d,"obligation_and_anchor","each payment must name both the obligation and its installment anchor; fuzzy or balance-wide matching is refused"),ne(m.get("refund_policy"),d,"full_payment_only","a refund reverses one stored payment whole so it cannot exceed that payment"),ne(m.get("reschedule_policy"),d,"refuse","forward-version carryover is not mechanically proven; create a new obligation after closing this one"),ne(m.get("delinquency_policy"),d,"due_condition","delinquency must come from an unmet stored due anchor")].every(Boolean),pe=[J(G,_,`${d} names ${G} as both debtor and settlement recipient; they must differ`),oe?J(oe,G,`${d} advances to its debtor ${G}; advance_to must name a distinct recipient`):!0].every(Boolean);g&&_&&h&&N&&w&&G&&ie&&pe&&H.push({...oe?{advanceTo:oe}:{},amount:h,archetype:"scheduled",debtor:G,mode:"obligation",name:i.name.name,origin:i.span,payee:_,payer:g,schedule:N});break}case"advance":{let g=O("funder","funder"),_=O("to","advanced party"),w=J(g,_,`advances ${g} their own money; funder and advanced party must differ`),h=K(m.get("amount"),d),E=U(m.get("fee"),d,"fee")??0,P=Zt(m,d,i.span);if(h&&P?.kind==="schedule"&&h.name===P.schedule.firstDueField){n(P.schedule.origin,`${d} uses ${h.name} as both the amount and the first_due date field; they need distinct names`);break}g&&_&&h&&P&&w&&H.push({advanced:_,amount:h,archetype:"advance",feeBps:E,funder:g,name:i.name.name,origin:i.span,source:P});break}case"metered":{let g=O("payer","payer"),_=O("payee","payee"),w=J(g,_,`meters ${g} against ${g}; payer and payee must differ`),h=ae(m.get("close_by"),d),E=[],P=m.get("rates"),N=!0;if(P)if(C(P,d),P.value.kind!=="block")n(P.value.span,"rates is a block of per-unit prices, like: rates { api_call: unitFee: money(SAR) }");else{let L=$e.metered.maxRates??$e.metered.eventCap;P.value.entries.length>L&&(n(P.value.span,`${d} prices ${P.value.entries.length} meters, but metered allows at most ${L} so one settlement stays within its ${$e.metered.eventCap}-event cap`),N=!1);for(let S of P.value.entries){if(!Ze.test(S.key.name)){n(S.key.span,`meter names are snake_case; "${S.key.name}" is not`);continue}if(E.some(G=>G.meter===S.key.name)){n(S.key.span,`${d} prices meter ${S.key.name} twice`);continue}let j=K(S,d);if(!j)continue;if(E.some(G=>G.field.name===j.name)){n(j.origin,`${d} reuses the field ${j.name} for two meters`);continue}let V=E[0]?.field.currency;if(V&&V!==j.currency){n(j.origin,`${d} mixes ${V} and ${j.currency}; one settlement meters in one currency`);continue}E.push({field:j,meter:S.key.name,origin:S.span})}P.value.entries.length===0&&n(P.value.span,`${d} prices no meters`)}if(h&&E.some(L=>L.field.name===h)){n(i.span,`${d} uses ${h} as both a rate field and the close_by date field; they need distinct names`);break}g&&_&&h&&E.length>0&&w&&N&&H.push({archetype:"metered",closeByField:h,name:i.name.name,origin:i.span,payee:_,payer:g,rates:E});break}case"pooled_split":{let g=O("payer","payer"),_=K(m.get("amount"),d),w=ae(m.get("payout_due"),d),h=m.get("split"),E=[...f.keys()].filter(S=>S!==g),P=h?M(h,d,E,"declared parties other than the funder",!0):void 0;if(P&&P.shares.length<2){n(h.value.span,`${d} splits to a single recipient; a pool distributes between at least two`);break}let N=$e.pooled_split.maxRecipients??Math.floor($e.pooled_split.eventCap/2),L=!P||P.shares.length<=N;if(L||n(h.value.span,`${d} splits to ${P.shares.length} recipients, but pooled_split allows at most ${N} so funding and payout stay within its ${$e.pooled_split.eventCap}-event cap`),P){let S=new Map;for(let j of P.shares){let[V="",...G]=j.to.split("_"),oe=`${V+G.map(pe=>pe.charAt(0).toUpperCase()+pe.slice(1)).join("")}ShareAmount`,ie=S.get(oe);ie&&n(j.origin,`${d} splits to ${ie} and ${j.to}, whose generated share fields both come out as ${oe}; rename one party`),S.set(oe,j.to)}}if(_&&w&&_.name===w){n(i.span,`${d} uses ${_.name} as both the amount and the payout_due date field; they need distinct names`);break}g&&_&&w&&P&&L&&H.push({amount:_,archetype:"pooled_split",distributeDueField:w,name:i.name.name,origin:i.span,payer:g,remainderTo:P.remainderTo??P.shares[0].to,shares:P.shares});break}}}let $n=[];for(let i of x){let p=`port ${i.name.name}`,d=R(i.body,["allowed","shape"],p);d.has("allowed")||n(i.span,`${p} is missing allowed`);let b=[],A=d.get("allowed");if(A){C(A,p);let J=A.value;if(J.kind!=="list"||J.items.length===0)n(J.span,"allowed lists who may ask this question, like: allowed: [buyer]");else for(let z of J.items){let g=B(z,`${p} allowed`);if(g){if(b.includes(g)){n(z.span,`${p} allows ${g} twice`);continue}b.push(g)}}}let m=[],O=d.get("shape");if(O)if(C(O,p),O.value.kind!=="block")n(O.value.span,"shape is a block of typed fields, like: shape { vehicleId: id(vehicle) }");else for(let J of O.value.entries){if(!_e.test(J.key.name)){n(J.key.span,`shape fields are camelCase names; "${J.key.name}" is not`);continue}if(m.some(g=>g.name===J.key.name)){n(J.key.span,`${p} declares ${J.key.name} twice`);continue}let z=er(J.value);if(!z){n(J.value.span,`${J.key.name} needs a type: id(<asset>), money(<CUR>), text, or date`);continue}if(z.kind==="asset_id"&&!v.has(z.asset)){n(J.value.span,`id(${z.asset}) points at an asset that is not declared`);continue}if(z.kind==="money"&&!rt.test(z.currency)){n(J.value.span,`"${z.currency}" is not a currency code; use three capital letters like SAR`);continue}m.push({name:J.key.name,origin:J.span,type:z})}b.length>0&&$n.push({allowed:b,fields:m,name:i.name.name,origin:i.span})}let be=new Map($n.map(i=>[i.name,i]));for(let[i,p]of ue){let b=be.get(i.claim.port)?.fields.find(J=>J.name===p.field),A=!0;if(b?b.type.kind!=="money"?(n(p.fieldOrigin,`settlement ${i.name} decided claim_amount field ${p.field} must be money`),A=!1):b.type.currency!==i.amount.currency&&(n(p.fieldOrigin,`settlement ${i.name} decided claim_amount mixes ${b.type.currency} and ${i.amount.currency}; decided value and bound need one currency`),A=!1):(n(p.fieldOrigin,`settlement ${i.name} decided claim_amount names ${p.field}, but claim port ${i.claim.port} has no such field`),A=!1),p.boundField!==i.amount.name&&(n(p.boundOrigin,`settlement ${i.name} decided claim_amount bound must name immutable stored amount ${i.amount.name}; ${p.boundField} is not that bound`),A=!1),p.remainderExit!=="return"&&(n(p.remainderOrigin,`settlement ${i.name} decided claim_amount remainder must name its return exit; ${p.remainderExit} would strand the unclaimed amount`),A=!1),!A)continue;let m={boundField:p.boundField,boundOrigin:p.boundOrigin,field:p.field,fieldOrigin:p.fieldOrigin,origin:p.origin,remainderExit:"return",remainderOrigin:p.remainderOrigin},O=H.indexOf(i);H[O]={...i,claimAmount:m}}for(let i of H){if(i.archetype==="captured_payment"){let b=be.get(i.correction.port);b&&(b.allowed.length!==1||b.allowed[0]!==i.payee)&&n(b.origin,`captured_payment ${i.name} correction port ${b.name} must allow only its payee ${i.payee}`);let A=be.get(i.externalReversal.port);A&&!A.fields.some(m=>m.name==="externalReference"&&m.type.kind==="text")&&n(A.origin,`captured_payment ${i.name} external reversal port ${A.name} needs shape { externalReference: text }`);continue}if(i.archetype==="settlement_batch"){let b=be.get(i.payoutAcknowledgement.port);b&&!b.fields.some(A=>A.name==="acknowledgementReference"&&A.type.kind==="text")&&n(b.origin,`settlement_batch ${i.name} payout acknowledgement port ${b.name} needs shape { acknowledgementReference: text }`);continue}if(i.archetype==="weighted_distribution"){let b=be.get(i.snapshot.port);b&&!b.fields.some(A=>A.name==="evidenceReference"&&A.type.kind==="text")&&n(b.origin,`weighted_distribution ${i.name} snapshot port ${b.name} needs shape { evidenceReference: text }`);continue}if(i.archetype==="recurring_collection"){let b=be.get(i.mandate.port);b&&!b.fields.some(A=>A.name==="evidenceReference"&&A.type.kind==="text")&&n(b.origin,`recurring_collection ${i.name} mandate port ${b.name} needs shape { evidenceReference: text }`);continue}if(i.archetype==="conditional_disbursement"){let b=be.get(i.decision.port);b&&(!b.fields.some(A=>A.name==="evidenceReference"&&A.type.kind==="text")||b.allowed.length!==1||b.allowed[0]!==i.source)&&n(b.origin,`conditional_disbursement ${i.name} decision port ${b.name} must allow only ${i.source} and needs shape { evidenceReference: text }`);continue}if(i.archetype==="premium_forward"&&i.endorsement){let b=be.get(i.endorsement.port);b&&!b.fields.some(A=>A.name==="evidenceReference"&&A.type.kind==="text")&&n(b.origin,`premium_forward ${i.name} endorsement port ${b.name} needs shape { evidenceReference: text }`);continue}if(i.archetype!=="swap")continue;let p=new Set(i.sides.map(b=>b.party)),d=[{label:"release",portRef:i.release},...i.dispute?[{label:"dispute",portRef:i.dispute}]:[]];for(let b of d){let A=be.get(b.portRef.port);if(A)for(let m of A.allowed)p.has(m)||n(A.origin,`swap ${i.name} ${b.label} port ${A.name} allows ${m}, but whole-trade decisions belong only to ${i.sides.map(O=>O.party).join(" or ")}`)}}let et=new Map(H.filter(i=>i.archetype==="scheduled"&&i.mode==="obligation").map(i=>[i.name,i])),bn=new Map;for(let i of H){if(i.archetype!=="credit_facility"&&i.archetype!=="recurring_collection")continue;let p=et.get(i.obligation.settlement),d=`settlement ${i.name}`;if(!p){n(i.obligation.origin,`${d} must compose with scheduled in mode: obligation; ${i.obligation.settlement} is not one`);continue}if(i.archetype==="credit_facility"){p.advanceTo&&n(i.obligation.origin,`${d} references ${p.name}, which already owns an advance; facility draws and obligation repayment must have one disbursement owner`),(p.payee!==i.lender||p.debtor!==i.borrower||p.amount.currency!==i.limit.currency)&&n(i.obligation.origin,`${d} must link an obligation whose payee is ${i.lender}, debtor is ${i.borrower}, and currency is ${i.limit.currency}`);continue}let b=be.get(i.mandate.port),A=bn.get(p.name);A?n(i.obligation.origin,`${d} and settlement ${A} both collect ${p.name}; one obligation may have one collection policy owner`):bn.set(p.name,i.name),b&&(b.allowed.length!==1||b.allowed[0]!==p.payer)&&n(b.origin,`${d} mandate port ${b.name} must allow only the obligation payer ${p.payer}`)}for(let i of et.values())i.schedule.kind==="open"&&!bn.has(i.name)&&n(i.schedule.origin,`settlement ${i.name} has an open recurrence without recurring_collection; open-period failures must reuse failure_policy: parent_delinquency`);let Qt=new Map(H.filter(i=>i.archetype==="held_payment").map(i=>[i.name,i])),nt=new Map;for(let i of H){if(i.archetype!=="advance"||i.source.kind!=="carve")continue;let p=`settlement ${i.name}`,d=i.source.settlement,b=i.source.origin;if(i.source.targetArchetype!=="held_payment"||i.source.exit!=="release"){n(b,`${p} can only carve held_payment.release; ${d}.${i.source.exit} is a ${i.source.targetArchetype} exit`);continue}let A=Qt.get(d);if(!A)continue;if(A.payee!==i.advanced){n(b,`${p} advances ${i.advanced}, but ${d} releases to ${A.payee}; an advance carves the release of the party it finances`);continue}if(A.amount.name!==i.amount.name){n(b,`${p} advances field ${i.amount.name}, but ${d}.release carries ${A.amount.name}; a carve must name the same money field`);continue}if(A.amount.currency!==i.amount.currency){n(b,`${p} advances ${i.amount.currency}, but ${d}.release carries ${A.amount.currency}; a carve must use one currency`);continue}if(i.feeBps>0){n(b,`${p} adds a fee to a carved advance, but ${d}.release can only prove repayment of the principal field; use a fee-free carve or a scheduled advance`);continue}if(A.fees.some(z=>z.bearer===A.payee&&(z.rule.kind!=="bps"||z.rule.bps>0))){n(b,`${p} carves ${d}.release after a payee fee reduces it; a carved hold must release the full principal field to the funder`);continue}if(A.payer===i.funder){n(b,`${i.funder} funds ${d} and finances it too; the party who pays the hold cannot be the funder its release repays`);continue}let m=nt.get(d);if(m){n(b,`${p} and settlement ${m} both draw against ${d}; one release repays one advance`);continue}if(nt.set(d,i.name),H.some(z=>z.archetype==="scheduled"&&z.mode==="transfer"&&z.payer===i.advanced&&z.payee===i.funder&&z.amount.name===i.amount.name&&z.amount.currency===i.amount.currency))continue;let J=`add a scheduled settlement collecting from the ${i.advanced.replaceAll("_"," ")} to the ${i.funder.replaceAll("_"," ")}`;if(A.onCancel){n(b,`${p} has no repayment path when ${d} is refunded instead of released; ${J}`);continue}r(b,`${p} has no repayment path if ${d} is abandoned before it funds; ${J}`)}for(let[i,p]of f)Q.has(i)||r(p.origin,`party ${i} is declared but no settlement or port involves them`);for(let i of x)T.has(i.name.name)&&!W.has(i.name.name)&&r(i.span,`port ${i.name.name} is declared but nothing releases through it`);for(let[i,p]of s)k.some(b=>b.archetype.name===i)||r(p,`${i} is imported but never instantiated`);return t.some(i=>i.severity==="error")||!c?{diagnostics:t}:{diagnostics:t,program:{assets:[...v.values()],derivedAmounts:o,name:c.name.name,origin:e.span,parties:[...f.values()],ports:$n,settlements:H,title:c.title?.value??nr(c.name.name)}}}function er(e){if(e.kind==="ident"&&e.name==="text")return{kind:"text"};if(e.kind==="ident"&&e.name==="date")return{kind:"date"};if(e.kind==="call"&&e.args.length===1&&e.args[0]?.kind==="ident"){let t=e.args[0].name;if(e.callee.name==="id")return{asset:t,kind:"asset_id"};if(e.callee.name==="money")return{currency:t,kind:"money"}}}function nr(e){let t=e.replaceAll("_"," ");return t.charAt(0).toUpperCase()+t.slice(1)}function at(e){let t=[0];for(let n=0;n<e.length;n+=1)e.charCodeAt(n)===10&&t.push(n+1);return{length:e.length,starts:t}}function kn(e,t){let n=Math.max(0,Math.min(t,e.length)),r=0,o=e.starts.length-1;for(;r<o;){let a=Math.floor((r+o+1)/2);e.starts[a]<=n?r=a:o=a-1}return{column:n-e.starts[r]+1,line:r+1}}var it=20,st=48,_n=10000n;function tr(e){if(!e)return{amountDependencies:[],amountMode:"fixed"};switch(e.kind){case"bounded_by_reference":return{amountDependencies:[Y(e.reference)],amountMode:"runtime_bounded"};case"net_of_offsets":{if(e.offsets.length===0)throw new Error("net_of_offsets requires at least one offset event");return{amountDependencies:ct(e.source,e.offsets),amountMode:"runtime_bounded"}}case"percent_of_reference":if(!Number.isInteger(e.bps)||e.bps<=0||e.bps>1e4)throw new Error("percent_of_reference bps must be an integer between 1 and 10000");return{amountDependencies:[Y(e.reference)],amountMode:"runtime_bounded"};case"remainder":{if(e.consumed.length===0)throw new Error("remainder requires at least one consumed event");return{amountDependencies:ct(e.source,e.consumed),amountMode:"remaining_balance"}}}}function ct(e,t){let n=[e,...t].map(Y);if(new Set(n).size!==n.length)throw new Error("amount dependency event keys must be distinct");return n}var dt=160,rr=new Set(["amount","design","detail","headline","label","summary","title","trigger","why"]);function An(e,t){return typeof e=="string"?t!==void 0&&rr.has(t)&&e.length>dt?`${e.slice(0,dt-3)}...`:e:Array.isArray(e)?e.map(n=>An(n,t)):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,An(r,n)])):e}function or(e){return An(e)}function Y(e){if(e.length<=40)return e;let t=2166136261;for(let n=0;n<e.length;n+=1)t=Math.imul(t^e.charCodeAt(n),16777619);return`${e.slice(0,33)}_${(t>>>0).toString(36).slice(0,6)}`}function ar(e){let t=e.amountDependency;if(!t)return e.amount;switch(t.kind){case"bounded_by_reference":return`Bounded by ${t.reference}: ${e.amount}`;case"net_of_offsets":return`Net of ${t.source} after ${t.offsets.join(", ")}: ${e.amount}`;case"percent_of_reference":return`${le(t.bps)} of ${t.reference}: ${e.amount}`;case"remainder":return`Remainder of ${t.source} after ${t.consumed.join(", ")}: ${e.amount}`}}function te(e){return{allocationTotalBps:0,amount:ar(e),...tr(e.amountDependency),amountSchedule:[],distribution:"single",fromActor:e.fromActor,key:Y(e.key),kind:e.kind,label:e.trigger,occurrence:e.occurrence??"once",timing:e.timing??"on_lifecycle",toActor:e.toActor,trigger:e.trigger}}function Ie(e,t,n,r){return e.map((o,a)=>({from:a===0?t:`${r}_${a}`,to:a===e.length-1?n:`${r}_${a+1}`}))}function Je(e,t,n,r){let o=new Set;for(let a of t){if(a==="create"||o.has(a))return r.push({message:`settlement ${e} generates two actions named "${a}"; rename the colliding port`,span:n}),!1;o.add(a)}return!0}function Ae(e,t){return t.length>=2?[{pieces:[...t],total:e}]:[]}function Pe(e){return e.length>0?{partitions:[...e]}:{}}function Z(e){return{desc:e,type:"money"}}function je(e,t){return e.fixedAmount===void 0?Z(t):{desc:t,type:`money:${e.currency}:${e.fixedAmount}`}}function rn(e){return e.kind==="exact"?[e.amount]:e.kind==="bps"?[]:e.tiers.flatMap(t=>rn(t.rule))}function ut(e){switch(e.kind){case"bps":return{bps:e.bps,kind:"bps"};case"exact":return{currencyField:"currency",field:e.amount.name,kind:"exact"};case"tiered":return{kind:"tiered",tiers:e.tiers.map(t=>({fromInclusive:t.fromInclusive,...t.toExclusive?{toExclusive:t.toExclusive}:{},rule:ut(t.rule)}))}}}function Qe(e,t){return e.rule.kind==="exact"?e.rule.amount.name:t}function en(e,t,n){return{amountField:n,baseField:t,bearer:e.bearer,position:e.position,rule:ut(e.rule)}}function he(e){switch(e.kind){case"bps":return le(e.bps);case"exact":return`Exact ${e.amount.name}`;case"tiered":return`${e.tiers.length}-tier fee`}}function me(e){return{desc:e,type:"date"}}function ir(e){return{desc:e,type:"date?"}}function pt(e){return Object.fromEntries(e.fields.map(t=>[t.name,t.type.kind==="asset_id"?{...t.type}:t.type.kind]))}function sr(e){if(typeof e.prefix=="string")return e.prefix;let t=e.id,n=t.split("_");return(n.length>1?n.map(o=>o[0]).join(""):t.slice(0,4)).slice(0,8).padEnd(2,"x")}function cr(e,t){let n=new Set(e.filter(a=>!t.has(a.id)).map(sr)),r=0,o=()=>{for(;;){let a=String.fromCharCode(97+Math.floor(r/26)),c=String.fromCharCode(97+r%26);r+=1;let s=`zz${a}${c}`;if(!n.has(s))return n.add(s),s}};return e.map(a=>t.has(a.id)?{...a,prefix:o()}:a)}function mt(e){let t=[],n=[],r=[],o=[],a=[],c=[],s=[],l=[],u=[],f=new Set,v=new Map,x=new Map(e.ports.map($=>[$.name,$])),k=($,D,K)=>{let re=x.get(D);return re||t.push({message:`settlement ${$.name} decides through an unknown port; the checker should have refused this program`,span:K}),re},T=new Map(e.settlements.flatMap($=>$.archetype==="advance"&&$.source.kind==="carve"?[[$.source.settlement,$.funder]]:[])),R=new Map(e.settlements.flatMap($=>{if($.archetype!=="advance"||$.source.kind!=="carve")return[];let D=e.settlements.filter(K=>K.archetype==="scheduled"&&K.mode==="transfer"&&K.payer===$.advanced&&K.payee===$.funder&&K.amount.name===$.amount.name&&K.amount.currency===$.amount.currency);return[[$.name,D]]})),C=new Map(e.settlements.flatMap($=>$.archetype==="recurring_collection"?[[$.obligation.settlement,$]]:[]));for(let $ of e.settlements){let D;switch($.archetype){case"held_payment":{let U=k($,$.release.port,$.release.origin);if(!U)continue;D=vr($,U,T.get($.name),t);break}case"captured_payment":{let U=k($,$.correction.port,$.correction.origin),F=k($,$.externalReversal.port,$.externalReversal.origin);if(!U||!F)continue;D=Ar($,U,F,t);break}case"settlement_batch":{let U=k($,$.payoutAcknowledgement.port,$.payoutAcknowledgement.origin);if(!U)continue;D=xr($,U,t);break}case"funding_round":D=Ir($);break;case"weighted_distribution":{let U=k($,$.snapshot.port,$.snapshot.origin);if(!U)continue;D=Pr($,U);break}case"credit_facility":D=Cr($);break;case"recurring_collection":continue;case"conditional_disbursement":{let U=k($,$.decision.port,$.decision.origin);if(!U)continue;D=Er($,U);break}case"rotating_pool":D=Tr($);break;case"premium_forward":{let U=k($,$.bind.port,$.bind.origin),F=$.endorsement?k($,$.endorsement.port,$.endorsement.origin):void 0;if(!U||$.endorsement&&!F)continue;D=kr($,U,F,t);break}case"deposit":{let U=k($,$.claim.port,$.claim.origin),F=k($,$.return.port,$.return.origin);if(!U||!F)continue;D=Sr($,U,F,t);break}case"instant_transfer":D=_r($);break;case"scheduled":if($.mode==="obligation"){let U=C.get($.name),F=U?k(U,U.mandate.port,U.mandate.origin):void 0;if($.schedule.kind==="open"){let M=$.schedule.termination.kind==="port"?k($,$.schedule.termination.port.port,$.schedule.termination.port.origin):void 0;if(!U||!F||$.schedule.termination.kind==="port"&&!M)continue;D=Rr({...$,schedule:$.schedule},U,F,t,M)}else D=Fr({...$,schedule:$.schedule},U,F)}else{if($.schedule.kind==="open")continue;D=Or({...$,schedule:$.schedule})}break;case"advance":D=Dr($,R.get($.name)??[]);break;case"metered":D=jr($);break;case"pooled_split":D=Br($);break;case"swap":{let U=k($,$.release.port,$.release.origin),F=$.dispute?k($,$.dispute.port,$.dispute.origin):void 0;if(!U||$.dispute&&!F)continue;D=wr($,U,F);break}}if(!D)continue;let K=(e.derivedAmounts??[]).filter(U=>U.settlement===$.name);if(K.length>0&&(D=fr(D,$,K,t),!D))continue;let re=$e[$.archetype].eventCap+K.length;if(D.moneyEvents.length>re){t.push({message:`settlement ${$.name} emits ${D.moneyEvents.length} money events, but ${$.archetype} carries a local cap of ${re}`,span:$.origin});continue}for(let U of[...D.moneyEvents,...D.rules]){let F=U.key,M=v.get(F);M&&t.push({message:`settlements ${M} and ${$.name} both generate the internal key ${F}; rename one settlement (or its port or meter) so the generated keys stay distinct`,span:$.origin}),v.set(F,$.name)}n.push(D.settlement);let ee=[D.instrument,...D.extraInstruments??[]];for(let U of ee){let F=U.actions;for(let[M,ce]of Object.entries(F)){if(Object.hasOwn(ce,"due")||Object.hasOwn(ce,"requiresSettlement"))continue;let ae=ft(U.id,M);ae.length<=st||t.push({message:`settlement ${$.name} generates public action "${ae}" with ${ae.length} characters; rename the settlement so each public action fits the ${st}-character camelName limit`,span:$.origin})}}r.push(...ee),o.push(...ee.map(()=>({lowered:D.settlement,settlement:$})));for(let U of D.generatedPrefixInstrumentIds??[])f.add(U);a.push(...D.moneyEvents),c.push(...D.rules),s.push(...D.design),l.push(...D.feeLines),D.repeatableCounterparty&&u.push(D.repeatableCounterparty)}a.length>it&&t.push({message:`this program needs ${a.length} money events but a Business Frame carries at most ${it}; simplify the fee or cancellation terms, or drop a settlement`,span:e.settlements[0]?.origin??{end:0,start:0}}),t.push(...hr(a,e.settlements[0]?.origin??{end:0,start:0}));let Q=yr(e,u);if(t.push(...Q.issues),t.length>0)return{issues:t,ok:!1};let B=mr(cr(r,f)),W=e.assets.map($=>({kind:$.name,title:q($.name),value:"optional"})),H={hsx:1,instruments:B,product:e.name,...W.length>0?{subjects:W}:{},title:e.title},ue=dr(H,e,o),X={actors:Q.actors,confidence:"high",conservationGroups:[],design:s,feePolicy:l.length>0?"defined":"none",fees:l,headline:e.title,mechanics:br(e.settlements),moneyEvents:a,offPlatform:e.assets.filter($=>$.titleTransfer==="off_platform").map($=>({label:`${q($.name)} title transfer`,why:`Ownership of the ${$.name.replaceAll("_"," ")} changes hands outside the platform`})),openQuestions:[],rules:c,subjects:e.assets.map($=>({kind:$.name,title:q($.name)})),summary:Jr(e)};return{ok:!0,value:{document:H,frame:or(X),originMap:ue,settlements:n}}}function dr(e,t,n){let r=[{path:"$",span:t.origin}];for(let[o,a]of e.instruments.entries()){let c=n[o];if(!c)continue;let s=lt(c,t),l=`$.instruments[${o}]`;r.push({path:l,span:c.settlement.origin});for(let[u,f]of Object.entries(a))tn(f,xn(l,u),c.settlement.origin,s,r);if(c.settlement.archetype==="deposit"){let u=c.settlement.claimAmount;if(u){let f=xn(`${l}.actions`,c.settlement.claim.port);Re(r,`${f}.decidedAmount`,u.origin),Re(r,`${f}.decidedAmount.field`,u.fieldOrigin),Re(r,`${f}.decidedAmount.boundField`,u.boundOrigin),Re(r,`${f}.decidedAmount.remainderAction`,u.remainderOrigin),Re(r,`${f}.moves[0].amount`,u.fieldOrigin),Re(r,`${f}.moves[1]`,u.remainderOrigin)}}}for(let[o,a]of(e.subjects??[]).entries()){let c=t.assets[o];tn(a,`$.subjects[${o}]`,c?.origin??t.origin,c?lt(c,t):[],r)}return r}function Re(e,t,n){let r=e.findIndex(o=>o.path===t);r>=0?e[r]={path:t,span:n}:e.push({path:t,span:n})}function lt(e,t){let n=[],r="settlement"in e?e.settlement:e;if(Fe(r,[],n),"lowered"in e)for(let o of e.lowered.pieces)n.push({labels:[],span:o.origin,tokens:[o.field]});for(let o of t.ports)Fe(o,["port"],n);for(let o of t.parties)Fe(o,["party"],n);for(let o of t.derivedAmounts)"settlement"in e&&o.settlement===e.settlement.name&&Fe(o,["derivedAmounts"],n);return n}function Fe(e,t,n){if(!e||typeof e!="object")return;if(Array.isArray(e)){for(let o of e)Fe(o,t,n);return}let r=e;pr(r.origin)&&n.push({labels:t,span:r.origin,tokens:nn(r)});for(let[o,a]of Object.entries(r))o!=="origin"&&Fe(a,[...t,o],n)}function nn(e){return typeof e=="string"||typeof e=="number"?[String(e)]:!e||typeof e!="object"?[]:Array.isArray(e)?e.flatMap(nn):Object.entries(e).flatMap(([t,n])=>t==="origin"?[]:nn(n))}function tn(e,t,n,r,o){let a=t.slice(t.lastIndexOf(".")+1),s=(/\.actions\.[^.[]+$/.test(t)?lr(a,r):ur([a,...nn(e)],r))??n;if(o.push({path:t,span:s}),!(!e||typeof e!="object")){if(Array.isArray(e)){for(let[l,u]of e.entries())tn(u,`${t}[${l}]`,s,r,o);return}for(let[l,u]of Object.entries(e))tn(u,xn(t,l),s,r,o)}}function lr(e,t){let n=Se(e),r=t.filter(a=>a.tokens.some(c=>Se(c)===n));if(r.length>0)return Le(r);if(n==="settle"){let a=t.filter(c=>c.labels.some(s=>Se(s)==="source"));if(a.length>0)return Le(a)}let o=t.filter(a=>a.labels.some(c=>{let s=Se(c);return s.length>=4&&(n.includes(s)||n!=="create"&&n.length>=5&&s.startsWith(n))}));if(o.length>0)return Le(o);if(/collect|installment|repayment|delinquent/.test(n)){let a=t.filter(c=>c.labels.some(s=>Se(s)==="schedule"));if(a.length>0)return Le(a)}if(/cancel|refund|unfund|abandon/.test(n)){let a=t.filter(c=>c.labels.some(s=>Se(s)==="oncancel"));if(a.length>0)return Le(a)}}function Le(e){return e.reduce((t,n)=>{let r=n.span.end-n.span.start,o=t.end-t.start;return r<o||r===o&&n.span.start<t.start?n.span:t},e[0].span)}function ur(e,t){let n=e.map(Se).filter(Boolean),r;for(let o of t){let a=[...o.tokens,...o.labels].map(Se),c=0;for(let u of n)for(let f of a)f.length<2||(u===f?c=Math.max(c,4):(u.includes(f)||f.includes(u))&&(c=Math.max(c,1)));if(c===0)continue;let s=o.span.end-o.span.start,l=r?r.span.end-r.span.start:1/0;(!r||c>r.score||c===r.score&&s<l||c===r.score&&s===l&&o.span.start<r.span.start)&&(r={score:c,span:o.span})}return r?.span}function Se(e){return e.replace(/[^A-Za-z0-9]/g,"").toLowerCase()}function xn(e,t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function pr(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.start=="number"&&typeof t.end=="number"}function mr(e){return e.map(t=>{let n=t.actions;return{...t,actions:Object.fromEntries(Object.entries(n).map(([r,o])=>[r,Object.hasOwn(o,"due")||Object.hasOwn(o,"requiresSettlement")?o:{...o,publicAction:ft(t.id,r)}]))}})}function ft(e,t){let n=de(e),r=n.charAt(0).toUpperCase()+n.slice(1);return`${de(t)}${r}`}function fr(e,t,n,r){let o=e.instrument,a={...o.fields??{}},c={...o.actions??{}},s={...c.create??{}},l=[...s.moves??[]],u={...o.actors??{}},f=[],v=[...e.moneyEvents],x=[...e.feeLines];for(let k of n){let T=a[k.baseField];if(T===void 0||T.type!=="money"){r.push({message:`settlement ${t.name} derives ${k.field} from ${T===void 0?"unknown ":"non-money "}field ${k.baseField}; from must name a stored money field on the settlement owner`,span:k.origin});return}if(a[k.field]!==void 0){r.push({message:`settlement ${t.name} derives into existing field ${k.field}; choose a new derived amount field`,span:k.origin});return}let R=Y(`${t.name}_derived_amount`);a[k.field]=Z(`Machine-computed ${le(k.bps)} of ${k.baseField}; callers never supply it`),u[k.bearer]===void 0&&(u[k.bearer]="payer"),u.platform="beneficiary",f.push({field:k.field,rounding:"floor",rule:{bps:k.bps,kind:"percentage_of"},sourceField:k.baseField}),l.push({amount:k.field,from:k.bearer,key:"derived_amount",moneyEvent:R,operation:"create",to:"platform"}),v.push(te({amount:`The machine-computed ${k.field}`,fromActor:k.bearer,key:R,kind:"charge",toActor:"platform",trigger:`Collect ${k.field} with settlement creation`})),x.push({label:q(k.field),on:`each ${t.name.replaceAll("_"," ")}`,structure:`${le(k.bps)} of stored ${k.baseField}, computed by the runtime`})}return s.moves=l,c.create=s,{...e,design:[...e.design,`${t.name}: derived amounts are machine-computed from stored source fields before create movements; fixed and tiered rules are refused`],feeLines:x,moneyEvents:v,instrument:{...o,actors:u,derivedAmounts:f,fields:a,actions:c}}}function yr(e,t=[]){let n=gr(e.settlements),r=new Set(e.parties.map(s=>s.name)),o=new Map,a=[];for(let s of t){if(!r.has(s.key)){a.push({message:`repeatable counterparty ${s.key} is not a declared party`,span:s.origin});continue}let l=n.get(s.key);if(!l){a.push({message:`repeatable counterparty ${s.key} is not used by any settlement`,span:s.origin});continue}if(l!==s.role){a.push({message:`repeatable counterparty ${s.key} declares role ${s.role}, but its settlement uses role ${l}`,span:s.origin});continue}if(s.label.trim().length===0||s.label.length>160){a.push({message:`repeatable counterparty ${s.key} label must contain 1 through 160 characters`,span:s.origin});continue}if(!Number.isInteger(s.minCount)||!Number.isInteger(s.maxCount)||s.minCount<1||s.maxCount>1e4){a.push({message:`repeatable counterparty ${s.key} counts must be integers from 1 through 10000`,span:s.origin});continue}if(s.minCount>s.maxCount){a.push({message:`repeatable counterparty ${s.key} has minCount ${s.minCount} above maxCount ${s.maxCount}`,span:s.origin});continue}if(o.has(s.key)){a.push({message:`repeatable counterparty ${s.key} is declared twice`,span:s.origin});continue}o.set(s.key,s)}return{actors:[...e.parties.filter(s=>n.has(s.name)).map(s=>{let l=o.get(s.name);return l?{key:l.key,label:l.label,maxCount:l.maxCount,minCount:l.minCount,role:l.role}:{key:s.name,label:q(s.name),maxCount:1,minCount:1,role:n.get(s.name)}}),{key:"platform",label:"Platform",maxCount:1,minCount:1,role:"platform"}],issues:a}}function hr(e,t){let n=[],r=new Map;for(let l of e){if(typeof l.key!="string")continue;let u=Array.isArray(l.amountDependencies)?l.amountDependencies.filter(f=>typeof f=="string"):[];r.set(l.key,u)}for(let[l,u]of r)for(let f of u){if(f===l){n.push({message:`money event ${l} cannot depend on itself`,span:t});continue}r.has(f)||n.push({message:`money event ${l} depends on missing money event ${f}`,span:t})}let o=new Set,a=new Set,c=new Set,s=l=>{if(!(a.has(l)||c.has(l))){if(o.has(l)){c.add(l);return}o.add(l);for(let u of r.get(l)??[])r.has(u)&&s(u),c.has(u)&&c.add(l);o.delete(l),a.add(l)}};for(let l of r.keys())s(l);return c.size>0&&n.push({message:`money event amount dependencies contain a cycle through ${[...c].sort().join(", ")}`,span:t}),n}function gr(e){let t=new Set,n=new Set,r=new Set,o=new Set;for(let s of e)switch(s.archetype){case"held_payment":case"captured_payment":case"instant_transfer":case"metered":t.add(s.payer),n.add(s.payee);break;case"scheduled":t.add(s.payer),n.add(s.payee),s.mode==="obligation"&&(t.add(s.debtor),s.advanceTo&&n.add(s.advanceTo));break;case"premium_forward":t.add(s.payer),r.add(s.carrier);break;case"deposit":t.add(s.payer),o.add(s.holder);break;case"advance":t.add(s.funder),n.add(s.advanced);break;case"pooled_split":t.add(s.payer);for(let l of s.shares)n.add(l.to);break;case"settlement_batch":t.add(s.settlementAccount),n.add(s.payoutDestination);break;case"funding_round":t.add(s.contributor),n.add(s.beneficiary);break;case"weighted_distribution":t.add(s.source),n.add(s.recipient);break;case"credit_facility":t.add(s.lender),n.add(s.borrower),n.add(s.drawDestination);break;case"recurring_collection":break;case"conditional_disbursement":t.add(s.source),n.add(s.destination);break;case"rotating_pool":for(let l of s.members)t.add(l),n.add(l);s.guarantor&&t.add(s.guarantor);break;case"swap":t.add(s.sides[0].party),n.add(s.sides[1].party);break}let a=new Map,c=(s,l)=>{for(let u of s)a.has(u)||a.set(u,l)};return c(t,"payer"),c(r,"provider"),c(o,"holder"),c(n,"beneficiary"),a}var $r={advance:"credit",captured_payment:"escrow",conditional_disbursement:"marketplace",credit_facility:"credit",deposit:"escrow",funding_round:"credit",held_payment:"escrow",instant_transfer:"marketplace",metered:"recurring_billing",pooled_split:"marketplace",premium_forward:"insurance",recurring_collection:"recurring_billing",rotating_pool:"recurring_billing",scheduled:"recurring_billing",settlement_batch:"marketplace",swap:"escrow",weighted_distribution:"marketplace"};function br(e){let t=new Set(e.map(n=>n.archetype==="scheduled"&&n.mode==="obligation"?"credit":$r[n.archetype]));return t.size>0?[...t]:["escrow"]}function wr(e,t,n){let r=e.name,[o,a]=e.sides,c=e.dispute?.window,s=c!==void 0&&c.days>0,l=Y(`${r}_clawback_maturity`),u=[],f=(re,ee,U,F,M,ce)=>{let ae=Y(`${r}_${re}`);return u.push(te({amount:U,fromActor:F,key:ae,kind:ee,toActor:M,trigger:ce})),ae},v=f("side_a_fund","charge",`The full ${o.amount.name}`,o.party,"escrow",`Fund ${o.amount.name} into the shared trade escrow`),x=f("side_b_fund","charge",`The full ${a.amount.name}`,a.party,"escrow",`Fund ${a.amount.name} into the shared trade escrow`),k=f("side_a_release","payout",`The full ${o.amount.name}`,"escrow",a.party,`Release ${o.amount.name} across to ${a.party.replaceAll("_"," ")}`),T=f("side_b_release","payout",`The full ${a.amount.name}`,"escrow",o.party,`Release ${a.amount.name} across to ${o.party.replaceAll("_"," ")}`),R=f("side_a_cancel","refund",`The full ${o.amount.name}`,"escrow",o.party,`Return ${o.amount.name} to its original funder on cancellation`),C=f("side_b_cancel","refund",`The full ${a.amount.name}`,"escrow",a.party,`Return ${a.amount.name} to its original funder on cancellation`),Q=s?f("side_a_clawback","refund",`The full ${o.amount.name}`,"escrow",o.party,`Return ${o.amount.name} after the whole trade is disputed`):void 0,B=s?f("side_b_clawback","refund",`The full ${a.amount.name}`,"escrow",a.party,`Return ${a.amount.name} after the whole trade is disputed`):void 0,W={[o.amount.name]:Z(`Side A amount in ${o.amount.currency} minor units, held against the whole trade`),[a.amount.name]:Z(`Side B amount in ${a.amount.currency} minor units, held against the whole trade`),...s?{clawbackAt:{type:"date?",desc:`Machine-owned end of the ${c?.raw??"fixed"} whole-trade dispute window`}}:{}},H=[{amount:o.amount.name,from:o.party,key:"side_a_principal",moneyEvent:v,operation:"create",to:"escrow"},{amount:a.amount.name,from:a.party,key:"side_b_principal",moneyEvent:x,operation:"create",to:"escrow"}],ue=[],X=[];for(let[re,ee]of e.sides.entries()){if(!ee.fee)continue;let U=Qe(ee.fee,re===0?"sideAServiceFeeAmount":"sideBServiceFeeAmount");for(let M of rn(ee.fee.rule))W[M.name]=Z(`Immutable exact ${ee.party.replaceAll("_"," ")} service fee in ${M.currency} minor units`);ee.fee.rule.kind!=="exact"&&(W[U]=Z(`Machine-owned ${ee.party.replaceAll("_"," ")} service fee computed from ${ee.amount.name}`)),X.push(en(ee.fee,ee.amount.name,U));let F=f(re===0?"side_a_service_fee":"side_b_service_fee","charge",`${he(ee.fee.rule)} of ${ee.amount.name}, on top`,ee.party,"platform",`Collect the ${ee.party.replaceAll("_"," ")} custody fee at funding`);H.push({amount:U,from:ee.party,key:re===0?"side_a_service_fee":"side_b_service_fee",moneyEvent:F,operation:"create",to:"platform"}),ue.push({label:`${q(ee.party)} custody fee`,on:`each funded ${r.replaceAll("_"," ")}`,structure:`${he(ee.fee.rule)}, on top`})}let $=[{amount:o.amount.name,from:"escrow",key:"side_a",moneyEvent:k,operation:s?"reserve":"create",to:a.party},{amount:a.amount.name,from:"escrow",key:"side_b",moneyEvent:T,operation:s?"reserve":"create",to:o.party}],D={abandon:{from:["created"],requiresDrainedAccount:{path:"refs.escrowAccountId"},summary:"Abandon the trade before its atomic funding batch",to:"abandoned"},cancel:{from:["funded"],moves:[{amount:o.amount.name,from:"escrow",key:"side_a_refund",moneyEvent:R,operation:"create",to:o.party},{amount:a.amount.name,from:"escrow",key:"side_b_refund",moneyEvent:C,operation:"create",to:a.party}],summary:"Cancel and return both trade principals atomically",to:"cancelled"},create:{summary:`Create a ${q(r).toLowerCase()} atomic trade`,to:"created"},fund:{from:["created"],moves:H,summary:"Fund both trade sides and collect on-top fees atomically",to:"funded"},release:{from:["funded"],moves:$,port:{allowed:[...t.allowed]},...s?{setsAt:{field:"clawbackAt",offset:c?.raw}}:{},summary:s?"Reserve both cross-payments for the whole-trade clawback window":"Post both cross-payments atomically",to:s?"released":"settled"}};s&&e.dispute&&n&&Q&&B&&(D.post={due:{field:"clawbackAt",rule:l},from:["released"],moves:[{key:"side_a",operation:"post",reservation:"release_side_a"},{key:"side_b",operation:"post",reservation:"release_side_b"}],summary:"Post both trade reservations when the clawback window matures",to:"settled"},D.dispute={deadline:{field:"clawbackAt"},from:["released"],moves:[{key:"side_a_void",operation:"void",reason:"Whole trade disputed inside the clawback window",reservation:"release_side_a"},{key:"side_b_void",operation:"void",reason:"Whole trade disputed inside the clawback window",reservation:"release_side_b"},{amount:o.amount.name,clawbackOf:"release_side_a",from:"escrow",key:"side_a_refund",moneyEvent:Q,operation:"create",to:o.party},{amount:a.amount.name,clawbackOf:"release_side_b",from:"escrow",key:"side_b_refund",moneyEvent:B,operation:"create",to:a.party}],port:{allowed:[...n.allowed]},summary:"Void both reservations, then refund both principals atomically",to:"clawed_back"});let K=[{allowedActors:[...t.allowed],detail:`${t.allowed.map(q).join(" or ")} confirms the whole exchange through ${t.name}`,dueDriven:!1,enforcement:"tenant_app",gatesEvent:k,key:Y(`${r}_${t.name}_gate`),kind:"release_condition",label:`Whole trade released through ${t.name}`,tenantTunable:!1}];return s&&e.dispute&&n&&K.push({allowedActors:[],detail:`Both pending trade payouts post together at the immutable ${e.dispute.window.raw} cutoff`,dueDriven:!0,enforcement:"platform",gatesEvent:null,key:l,kind:"deadline",label:"Whole trade posts when its clawback window matures",tenantTunable:!1},{allowedActors:[...n.allowed],detail:`${n.allowed.map(q).join(" or ")} may dispute only before the immutable cutoff`,dueDriven:!1,enforcement:"tenant_app",gatesEvent:Q??null,key:Y(`${r}_${n.name}_gate`),kind:"release_condition",label:`Whole trade disputed through ${n.name}`,tenantTunable:!1}),{design:[`${r}: exactly two parties, two same-currency principals, one escrow, and one linked batch per phase`,s?`${r}: ${c?.raw} whole-trade clawback; release reserves both legs, then exactly one grouped post or grouped void-and-refund wins`:`${r}: no clawback window; release posts both legs directly and exposes no pending or dispute surface`],feeLines:ue,moneyEvents:u,instrument:{actors:{[o.party]:"payer",[a.party]:"beneficiary",...ue.length>0?{platform:"party"}:{}},desc:`Atomic swap between ${o.party.replaceAll("_"," ")} and ${a.party.replaceAll("_"," ")}; half-funded and half-released states do not exist`,distinctParties:!0,escrow:!0,...X.length>0?{feeRules:X}:{},fields:W,id:r,summary:`Two-party atomic trade between ${o.party.replaceAll("_"," ")} and ${a.party.replaceAll("_"," ")}`,title:q(r),actions:D},rules:K,settlement:{name:r,pieces:[{bps:1e4,cancelTo:o.party,field:o.amount.name,origin:o.amount.origin,releaseTo:a.party},{bps:1e4,cancelTo:a.party,field:a.amount.name,origin:a.amount.origin,releaseTo:o.party}]}}}function vr(e,t,n,r){let o=e.fees.find(s=>s.bearer===e.payer),a=e.fees.find(s=>s.bearer===e.payee),c=yt({amount:e.amount,carveTo:n,deadlineField:e.releaseDeadlineField,fundEventKind:"charge",fundTrigger:(s,l)=>`Fund piece ${s+1} of ${l} into escrow`,name:e.name,onCancel:e.onCancel,payee:e.payee,payeeFeeBps:a?.rule.kind==="bps"?a.rule.bps:0,payeeFeeRule:a,payer:e.payer,payerFeeBps:o?.rule.kind==="bps"?o.rule.bps:void 0,payerFeeRule:o,port:t,releaseWord:"release"},r);if(c)return{...c,feeLines:[...o?[{label:`${q(e.payer)} service fee`,on:`each funded ${e.name.replaceAll("_"," ")}`,structure:`${he(o.rule)} of the ${e.amount.name}, on top`}]:[],...a?[{label:`${q(e.payee)} fee`,on:`each released ${e.name.replaceAll("_"," ")}`,structure:`${he(a.rule)} of the ${e.amount.name}, deducted from the payout`}]:[]],instrument:{...c.instrument,desc:`Held payment: the ${e.payer.replaceAll("_"," ")} funds ${e.amount.name} into this settlement's own escrow; ${t.allowed.map(s=>s.replaceAll("_"," ")).join(" or ")} confirms through ${t.name} to release${n?` to the ${n.replaceAll("_"," ")}, whose advance the ${e.payee.replaceAll("_"," ")} repays out of it`:""}`,summary:`Escrow-held payment from ${e.payer.replaceAll("_"," ")} to ${e.payee.replaceAll("_"," ")}`}}}function kr(e,t,n,r){let o=yt({amount:e.amount,carveTo:void 0,deadlineField:void 0,fundEventKind:"premium",fundTrigger:(u,f)=>f===1?"Collect the premium into escrow":`Collect premium piece ${u+1} of ${f} into escrow`,name:e.name,onCancel:e.onCancel,payee:e.carrier,payeeFeeBps:e.commissionBps,payeeFeeRule:void 0,payer:e.payer,payerFeeBps:void 0,payerFeeRule:void 0,port:t,releaseWord:"forward"},r);if(!o)return;let a=o.instrument,c={...a.fields??{}},s={...a.actions??{}},l=[...o.rules];if(e.policyReferenceField&&e.renewalDueField&&e.endorsement&&n){c[e.policyReferenceField]={desc:"Immutable external policy reference recorded with this forward",type:"text"},c[e.renewalDueField]=me("Stored renewal due condition for the forwarded policy"),s[e.endorsement.port]={captureInput:{endorsementEvidenceReference:"evidenceReference"},from:["released"],port:{allowed:n.allowed,fields:{evidenceReference:"text"}},summary:"Record one non-money endorsement from external evidence",to:"endorsed"};let u=Y(`${e.name}_renewal_due`);s.lapse={due:{field:e.renewalDueField,rule:u},from:["released","endorsed"],requiresDrainedAccount:{path:"refs.escrowAccountId"},summary:"Mark the forwarded policy lapsed at its stored renewal due condition",to:"lapsed"},l.push({allowedActors:[],detail:"The stored renewal due condition changes policy state without moving money",dueDriven:!0,enforcement:"platform",gatesEvent:null,key:u,kind:"deadline",label:"Policy lapses at its stored renewal due condition",tenantTunable:!1})}return{...o,design:[`${e.name}: premium forwards to the ${e.carrier.replaceAll("_"," ")} exactly once on ${t.name}; ${le(e.commissionBps)} commission retained by the platform`,...e.policyReferenceField?[`${e.name}: extends premium_forward with stored policy reference, non-money endorsement evidence, and a due-only lapse; renewal creates a new forward`]:[]],feeLines:e.commissionBps>0?[{label:"Platform commission",on:`each bound ${e.name.replaceAll("_"," ")}`,structure:`${le(e.commissionBps)} of the ${e.amount.name}, deducted at forwarding`}]:[],instrument:{...o.instrument,fields:c,actions:s,desc:`Premium forward: the ${e.payer.replaceAll("_"," ")} funds the ${e.amount.name} into this settlement's own escrow; binding through ${t.name} forwards it to the ${e.carrier.replaceAll("_"," ")} exactly once, minus the platform commission`,summary:`Premium held for the ${e.carrier.replaceAll("_"," ")} until the policy binds`},rules:l}}function yt(e,t){let n=e.amount.name,r=ht(e),o=r.length===1?r.map(F=>({...F,field:n})):r,a=e.name,c=e.carveTo??e.payee,s=c.replaceAll("_"," "),l=e.payerFeeRule?Qe(e.payerFeeRule,"serviceFeeAmount"):void 0,u={[n]:je(e.amount,o.length===1?`The held amount in ${e.amount.currency} minor units, funded and paid out whole`:`The gross held amount in ${e.amount.currency} minor units; the piece fields below partition it exactly`)};for(let[F,M]of o.entries())M.field!==n&&(u[M.field]=Z(gt(M,F,n,e.amount.currency)));if(e.deadlineField&&(u[e.deadlineField]=me(`The date an undecided hold releases to the ${s} on; ${e.port.name} and cancellation decide only before it`)),e.payerFeeRule&&l){for(let F of rn(e.payerFeeRule.rule))u[F.name]=Z(`Immutable exact ${e.payer.replaceAll("_"," ")}-side service fee in ${F.currency} minor units`);e.payerFeeRule.rule.kind!=="exact"&&(u[l]=Z(`Machine-owned ${he(e.payerFeeRule.rule)} service fee computed from ${n}; charged on top at funding`))}let f=o.filter(F=>F.releaseTo==="platform"),v=f.length===1?f[0].field:f.length>1?"carvedFeeAmount":void 0;v==="carvedFeeAmount"&&(u.carvedFeeAmount=Z(`Machine-owned total of the ${f.length} carved platform fee pieces`));let x=[...e.payerFeeRule&&l?[en(e.payerFeeRule,n,l)]:[],...e.payeeFeeRule&&v?[en(e.payeeFeeRule,n,v)]:[]],k=[...Ae(n,o.map(F=>F.field)),...v==="carvedFeeAmount"?Ae(v,f.map(F=>F.field)):[]],T=o.map((F,M)=>`fund_piece_${M+1}`);e.payerFeeRule&&T.push("collect_service_fee");let R=o.map((F,M)=>M===0?e.port.name:`${e.releaseWord}_piece_${M+1}`),C=e.onCancel?o.map((F,M)=>M===0?"cancel":`refund_piece_${M+1}`):[],Q=e.deadlineField?`${e.releaseWord}_on_deadline`:void 0,B=Y(`${a}_${e.releaseWord}_deadline`),W=T.length-1,H=Array.from({length:W},(F,M)=>`unfund_piece_${M+1}`);if(!Je(e.name,[...T,...R,...Q?[Q]:[],...C,"abandon",...H],e.port.origin,t))return;let ue=Ie(T,"created","funded","funding"),X=Ie(R,"funded","released","releasing"),$=Ie(C,"funded","cancelled","cancelling"),D=[],K={},re=`${a}_fund`;D.push(te({amount:o.length===1?`The full ${n}`:`The ${n}, funded piece by piece`,fromActor:e.payer,key:re,kind:e.fundEventKind,...o.length>1?{occurrence:"repeatable"}:{},toActor:"escrow",trigger:e.fundTrigger(0,o.length)}));for(let[F,M]of o.entries())K[T[F]]={from:[ue[F]?.from],moneyEvent:re,moves:[{key:"transfer",operation:"create",amount:M.field,from:e.payer,to:"escrow"}],summary:`Fund piece ${F+1} of the held amount into escrow`,to:ue[F]?.to};if(e.payerFeeRule&&l){let F=T.length-1,M=`${a}_service_fee`;D.push(te({amount:`${he(e.payerFeeRule.rule)} of the ${n}, on top`,fromActor:e.payer,key:M,kind:"charge",toActor:"platform",trigger:"Collect the service fee at funding"})),K.collect_service_fee={from:[ue[F]?.from],moneyEvent:M,moves:[{key:"transfer",operation:"create",amount:l,from:e.payer,to:"platform"}],summary:"Collect the payer-side service fee",to:ue[F]?.to}}let ee=new Map;for(let F of o)ee.set(F.releaseTo,(ee.get(F.releaseTo)??0)+1);for(let[F,M]of ee){let ce=o.filter(ae=>ae.releaseTo===F).reduce((ae,ge)=>ae+ge.bps,0);D.push(te({amount:`${le(ce)} of the ${n}`,fromActor:"escrow",key:`${a}_release_${F}`,kind:"payout",...M>1?{occurrence:"repeatable"}:{},toActor:F,trigger:`Release to the ${F.replaceAll("_"," ")}`}))}for(let[F,M]of o.entries())K[R[F]]={...F===0&&e.deadlineField?{deadline:{field:e.deadlineField}}:{},from:[X[F]?.from],moneyEvent:Y(`${a}_release_${M.releaseTo}`),moves:[{key:"transfer",operation:"create",amount:M.field,from:"escrow",to:M.releaseTo}],...F===0?{port:{allowed:[...e.port.allowed],fields:Object.fromEntries(e.port.fields.map(ce=>[ce.name,"text"]))}}:{},summary:F===0?`Confirm through ${e.port.name} and start the ${e.releaseWord} payout`:`${q(e.releaseWord)} piece ${F+1} of the held amount`,to:X[F]?.to};if(Q&&e.deadlineField){let F=o[0];K[Q]={due:{field:e.deadlineField,rule:B},from:[X[0]?.from],moneyEvent:Y(`${a}_release_${F.releaseTo}`),moves:[{key:"transfer",operation:"create",amount:F.field,from:"escrow",to:F.releaseTo}],summary:`Release to the ${F.releaseTo.replaceAll("_"," ")} when ${e.deadlineField} arrives undecided`,to:X[0]?.to}}if(e.onCancel){let F=new Map;for(let M of o){let ce=M.cancelTo;F.set(ce,(F.get(ce)??0)+1)}for(let[M,ce]of F){let ae=o.filter(ge=>ge.cancelTo===M).reduce((ge,ne)=>ge+ne.bps,0);D.push(te({amount:`${le(ae)} of the ${n}`,fromActor:"escrow",key:`${a}_cancel_${M}`,kind:M===e.payer?"refund":"penalty",...ce>1?{occurrence:"repeatable"}:{},toActor:M,trigger:`Return to the ${M.replaceAll("_"," ")} on cancellation`}))}for(let[M,ce]of o.entries())K[C[M]]={...M===0&&e.deadlineField?{deadline:{field:e.deadlineField}}:{},from:[$[M]?.from],moneyEvent:Y(`${a}_cancel_${ce.cancelTo}`),moves:[{key:"transfer",operation:"create",amount:ce.field,from:"escrow",to:ce.cancelTo}],summary:M===0?"Cancel the settlement and start the unwind":`Return piece ${M+1} on cancellation`,to:$[M]?.to}}if(H.length>0){let F=`${a}_abandon`;D.push(te({amount:`The funded pieces of the ${n}, returned exactly`,fromActor:"escrow",key:F,kind:"refund",...H.length>1?{occurrence:"repeatable"}:{},toActor:e.payer,trigger:`Return the held pieces to the ${e.payer.replaceAll("_"," ")} on abandonment`}));for(let[M,ce]of H.entries()){let ae=M+1;K[ce]={from:[`funding_${ae}`,...ae<W?[`abandoning_${ae}`]:[]],moneyEvent:Y(F),moves:[{key:"transfer",operation:"create",amount:o[M].field,from:"escrow",to:e.payer}],summary:`Return piece ${ae} to the ${e.payer.replaceAll("_"," ")} on abandonment`,to:ae===1?"abandoned":`abandoning_${ae-1}`}}}K.abandon={from:["created"],requiresDrainedAccount:{path:"refs.escrowAccountId"},summary:"Abandon the settlement before any money is held",to:"abandoned"},K.create={summary:`Create a ${q(e.name).toLowerCase()} settlement`,to:"created"};let U=[{allowedActors:[...e.port.allowed],detail:`${e.port.allowed.map(q).join(" or ")} confirms through the tenant backend before ${e.deadlineField?`${e.deadlineField}, to decide ahead of it`:"any payout"}`,dueDriven:!1,enforcement:"tenant_app",gatesEvent:Y(`${a}_release_${o[0].releaseTo}`),key:Y(`${a}_${e.port.name}_gate`),kind:"release_condition",label:`${q(e.releaseWord)} decided through ${e.port.name}`,tenantTunable:!1}];return e.deadlineField&&U.push({allowedActors:[],detail:`A hold nobody decided releases to the ${s} on its stored ${e.deadlineField}, exactly once`,dueDriven:!0,enforcement:"platform",gatesEvent:null,key:B,kind:"deadline",label:`Undecided holds release on ${e.deadlineField}`,tenantTunable:!1}),{design:[`${a}: own escrow; ${o.length}-piece partition of ${n} (${o.map(F=>le(F.bps)).join(" + ")}); every exit drains every piece; abandonable before funded (created closes directly, funding states unwind piece by piece to the ${e.payer})`,...e.deadlineField?[`${a}: undecided holds release to the ${c} on ${e.deadlineField}; the port and the cancel decide only before that anchor`]:[],...e.carveTo?[`${a}: the ${e.payee}'s whole release share is carved to the ${e.carveTo}, who financed it; the platform fee and the cancellation split are untouched`]:[],...e.payerFeeRule?[`${a}: ${he(e.payerFeeRule.rule)} ${e.payer} service fee on top, straight to platform at funding`]:[]],feeLines:[],moneyEvents:D,instrument:{actors:{[e.payer]:"payer",[e.payee]:"beneficiary",...e.carveTo?{[e.carveTo]:"party"}:{},platform:"party"},desc:`Held amount from ${e.payer.replaceAll("_"," ")} to ${e.payee.replaceAll("_"," ")}${e.carveTo?`, released to the ${s} against the advance it secures`:""}`,escrow:!0,...x.length>0?{feeRules:x}:{},fields:u,id:e.name,...Pe(k),summary:`Escrow-held amount from ${e.payer.replaceAll("_"," ")}`,title:q(e.name),actions:K},rules:U,settlement:{name:e.name,pieces:o,...e.payerFeeBps!==void 0?{serviceFee:{bps:e.payerFeeBps,field:"serviceFeeAmount"}}:{}}}}function _r(e){let t=e.fees.find(B=>B.bearer===e.payer),n=e.fees.find(B=>B.bearer===e.payee),r=e.amount.name,o=n?.rule.kind==="bps"?n.rule.bps:void 0,a=n&&n.rule.kind!=="bps"?n:void 0,c=a?Qe(a,"carvedFeeAmount"):void 0,s=ht({amount:e.amount,payee:e.payee,payeeFeeBps:o??0}),l=c?[{bps:1e4,field:"netOfCarvedFeeAmount",origin:a?.origin??e.origin,releaseTo:e.payee},{bps:0,field:c,origin:a?.origin??e.origin,releaseTo:"platform"}]:s.length===1?s.map(B=>({...B,field:r})):s,u=e.name,f=t?Qe(t,"serviceFeeAmount"):void 0,v={[r]:je(e.amount,l.length===1?`The amount in ${e.amount.currency} minor units, paid through whole`:`The gross amount in ${e.amount.currency} minor units; the piece fields below partition it exactly`)};for(let[B,W]of l.entries())W.field!==r&&(v[W.field]=Z(a&&W.releaseTo===e.payee?`The remainder of ${r} after the carved platform fee`:a&&W.releaseTo==="platform"?`The carved platform fee selected from ${r}`:gt(W,B,r,e.amount.currency)));for(let B of e.fees)for(let W of rn(B.rule))v[W.name]=je(W,`Immutable exact ${B.bearer.replaceAll("_"," ")} fee in ${W.currency} minor units`);t&&f&&t.rule.kind!=="exact"&&(v[f]=Z(`Machine-owned ${he(t.rule)} service fee computed from ${r}; charged on top`));let x=e.fees.flatMap(B=>{let W=B.position==="carved"?c??l.find(H=>H.releaseTo==="platform")?.field:f;return W?[en(B,r,W)]:[]}),k=l.map((B,W)=>`pay_piece_${W+1}`);t&&k.push("collect_service_fee");let T=Ie(k,"created","paid","paying"),R=[],C={create:{summary:`Create a ${q(u).toLowerCase()} payment`,to:"created"}};for(let[B,W]of l.entries()){let H=`${u}_pay_${B+1}`,ue=a?W.releaseTo===e.payee?`The remainder of ${r} after the carved fee`:`${he(a.rule)} selected from ${r}`:`${le(W.bps)} of the ${r}`;R.push(te({amount:ue,fromActor:e.payer,key:H,kind:"charge",toActor:W.releaseTo,trigger:`Pay piece ${B+1} straight to the ${W.releaseTo.replaceAll("_"," ")}`})),C[k[B]]={from:[T[B]?.from],moneyEvent:H,moves:[{key:"transfer",operation:"create",amount:W.field,from:e.payer,to:W.releaseTo}],summary:`Pay piece ${B+1} of the amount through`,to:T[B]?.to}}if(t&&f){let B=k.length-1,W=`${u}_service_fee`;R.push(te({amount:`${he(t.rule)} of the ${r}, on top`,fromActor:e.payer,key:W,kind:"charge",toActor:"platform",trigger:"Collect the service fee with the payment"})),C.collect_service_fee={from:[T[B]?.from],moneyEvent:W,moves:[{key:"transfer",operation:"create",amount:f,from:e.payer,to:"platform"}],summary:"Collect the payer-side service fee",to:T[B]?.to}}let Q=t!==void 0||l.some(B=>B.releaseTo==="platform");return{design:[a?`${u}: instant pass-through; ${r} partitions into the selected carved fee and its exact remainder; no custody`:`${u}: instant pass-through; ${l.length}-piece partition of ${r} (${l.map(B=>le(B.bps)).join(" + ")}); no custody`],feeLines:[...t?[{label:`${q(e.payer)} service fee`,on:`each ${u.replaceAll("_"," ")}`,structure:`${he(t.rule)} of the ${r}, on top`}]:[],...n?[{label:`${q(e.payee)} fee`,on:`each ${u.replaceAll("_"," ")}`,structure:`${he(n.rule)} of the ${r}, deducted from the payout`}]:[]],moneyEvents:R,instrument:{actors:{[e.payer]:"payer",[e.payee]:"beneficiary",...Q?{platform:"party"}:{}},desc:`Instant transfer: the ${e.payer.replaceAll("_"," ")} pays ${r} straight through to the ${e.payee.replaceAll("_"," ")}, no custody`,...x.length>0?{feeRules:x}:{},fields:v,id:u,...Pe(Ae(r,l.map(B=>B.field))),summary:`Instant payment from ${e.payer.replaceAll("_"," ")} to ${e.payee.replaceAll("_"," ")}`,title:q(u),actions:C},rules:[],settlement:{name:u,pieces:l,...t?.rule.kind==="bps"&&f?{serviceFee:{bps:t.rule.bps,field:f}}:{}}}}function Ar(e,t,n,r){let o=e.name,a=e.amount.name,c="authorize_reservation",s="capturedAmount",l="reversalUntil",f=["authorize",...["capture","capture_more"],"settle","void","expire","settle_on_expiry",e.correction.port,e.externalReversal.port];if(!Je(o,f,e.origin,r))return;let v=Y(`${o}_reserve`),x=Y(`${o}_capture`),k=Y(`${o}_correction`),T=Y(`${o}_external_reversal`),R=Y(`${o}_reservation_expiry`),C=H=>({amount:"captureAmount",capture:{[s]:"postedAmount"},key:"post",operation:"post",...H?{partialOnly:!0}:{},reservation:c}),Q=()=>({amount:`refs.${s}`,clawbackOf:c,from:e.payee,key:"transfer",operation:"create",to:e.payer}),B={create:{summary:`Create a ${q(o).toLowerCase()}`,to:"created"},authorize:{from:["created"],moneyEvent:v,moves:[{amount:a,from:e.payer,key:"reservation",operation:"reserve",to:e.payee}],summary:`Reserve the ${a} until ${e.reserveUntilField}`,to:"authorized"},capture:{deadline:{field:e.reserveUntilField},from:["authorized"],moneyEvent:x,moves:[C(!0)],summary:"Post one strict partial capture slice",to:"partially_captured"},capture_more:{deadline:{field:e.reserveUntilField},from:["partially_captured"],moneyEvent:x,moves:[C(!0)],summary:"Post another strict partial capture slice",to:"partially_captured"},settle:{deadline:{field:e.reserveUntilField},from:["authorized","partially_captured"],moneyEvent:x,moves:[{capture:{[s]:"postedAmount"},key:"post",operation:"post",reservation:c}],summary:"Post the full reserved remainder and settle",setsAt:{field:l,offset:e.externalReversal.window.raw},to:"settled"},void:{from:["authorized"],moves:[{key:"void",operation:"void",reason:"Reservation voided before any capture",reservation:c}],summary:"Release an entirely uncaptured reservation",to:"voided"},expire:{due:{field:e.reserveUntilField,rule:R},from:["authorized"],moves:[{key:"void",operation:"void",reason:"Uncaptured reservation expired",reservation:c}],summary:"Release an uncaptured reservation at expiry",to:"expired"},settle_on_expiry:{due:{field:e.reserveUntilField,rule:R},from:["partially_captured"],moves:[{key:"void",operation:"void",reason:"Uncaptured remainder released at expiry",reservation:c}],summary:"Release the uncaptured remainder and settle captured slices",setsAt:{field:l,offset:e.externalReversal.window.raw},to:"settled"},[e.correction.port]:{from:["settled"],moneyEvent:k,moves:[Q()],port:{allowed:t.allowed},summary:"Return the full captured amount on payee correction",to:"corrected"},[e.externalReversal.port]:{captureInput:{externalReference:"externalReference"},deadline:{field:l},from:["settled"],moneyEvent:T,moves:[Q()],port:{allowed:n.allowed,fields:{externalReference:"text"}},summary:"Return the full captured amount on an external reversal",to:"reversed"}},W=[te({amount:`The full ${a}`,fromActor:e.payer,key:v,kind:"hold",toActor:e.payee,trigger:`Reserve ${a} until ${e.reserveUntilField}`}),te({amount:`Each posted slice, never more than the remaining ${a}`,amountDependency:{kind:"bounded_by_reference",reference:v},fromActor:e.payer,key:x,kind:"payout",occurrence:"repeatable",toActor:e.payee,trigger:"Post a capture slice or the final remainder"}),te({amount:"100% of the cumulative captured amount",amountDependency:{bps:1e4,kind:"percent_of_reference",reference:x},fromActor:e.payee,key:k,kind:"refund",toActor:e.payer,trigger:"Apply one full payee correction"}),te({amount:"100% of the cumulative captured amount",amountDependency:{bps:1e4,kind:"percent_of_reference",reference:x},fromActor:e.payee,key:T,kind:"refund",toActor:e.payer,trigger:"Apply one full externally decided reversal"})];return{design:[`${o}: reserve ${a} until ${e.reserveUntilField}; capture in strict partial slices; post the remainder to settle; expiry releases only the uncaptured remainder`,`${o}: correction and external reversal each return the full captured amount once; insufficient payee funds reject the move instead of creating a negative position`],feeLines:[],moneyEvents:W,instrument:{actors:{[e.payer]:"payer",[e.payee]:"beneficiary"},desc:"Payer reservation captured by the payee in slices within a fixed window",fields:{[a]:Z(`Maximum captured amount in ${e.amount.currency} minor units`),[e.reserveUntilField]:me("Reservation expiry that releases any uncaptured remainder"),[l]:{desc:"Machine-owned external reversal cutoff anchored when settlement completes",type:"date?"}},id:o,summary:`Capture reservation from ${e.payer.replaceAll("_"," ")} to ${e.payee.replaceAll("_"," ")}`,title:q(o),actions:B},rules:[{allowedActors:[],detail:`At ${e.reserveUntilField}, the platform releases the uncaptured remainder and preserves any posted slices`,dueDriven:!0,enforcement:"platform",gatesEvent:null,key:R,kind:"deadline",label:`Uncaptured remainder releases on ${e.reserveUntilField}`,tenantTunable:!1},{allowedActors:[...t.allowed],detail:"The payee may return the full captured amount once",dueDriven:!1,enforcement:"tenant_app",gatesEvent:k,key:Y(`${o}_${e.correction.port}_gate`),kind:"release_condition",label:"Full correction confirmed through the tenant backend",tenantTunable:!1},{allowedActors:[...n.allowed],detail:`A confirmed external decision may reverse the full captured amount within ${e.externalReversal.window.raw}; timeout moves nothing`,dueDriven:!1,enforcement:"tenant_app",gatesEvent:T,key:Y(`${o}_${e.externalReversal.port}_gate`),kind:"release_condition",label:"External reversal confirmed through the tenant backend",tenantTunable:!1}],settlement:{name:o,pieces:[]}}}function xr(e,t,n){let r=e.name,o=`${r}_capture_entry`,a=`${r}_credit_adjustment`,c=`${r}_debit_adjustment`,s=`${r.replaceAll(/_([a-z])/g,(T,R)=>R.toUpperCase())}Id`,l=Y(`${r}_payout`),u=Y(`${r}_close`);if(!Je(r,["close","calculate","approve","instruct","reconcile",e.payoutAcknowledgement.port],e.origin,n))return;let f={[s]:{match:{"fields.currency":"fields.currency"},statuses:["open"]}},v={desc:"One gross capture entry linked to an open payout batch",fields:{amount:Z("Gross captured amount in minor units"),currency:{desc:"ISO 4217 currency shared with the payout batch",type:"currency"},[s]:{desc:"Open batch this capture entry accrues into",type:`ref:${r}`},[e.sourceCaptureReferenceField]:{desc:"Immutable source capture reference",type:"text"}},id:o,summary:"Gross capture lineage entry",title:`${q(r)} Capture Entry`,actions:{create:{requires:f,summary:"Create a capture lineage entry on an open batch",to:"created"},accrue:{from:["created"],requires:f,summary:"Accrue the capture entry into the open batch",to:"accrued"}}},x=(T,R)=>({desc:`One ${R} adjustment linked to an open payout batch; closed batches stay unchanged`,fields:{amount:Z(`${q(R)} adjustment amount in minor units`),currency:{desc:"ISO 4217 currency shared with the payout batch",type:"currency"},adjustmentReference:{desc:"Immutable explicit adjustment reference",type:"text"},[s]:{desc:"Open batch this adjustment applies to",type:`ref:${r}`},[e.externalReversalReferenceField]:{desc:"Optional externally decided reversal reference",type:"text?"},[e.feeReferenceField]:{desc:"Optional fee entry reference",type:"text?"},[e.sourceCaptureReferenceField]:{desc:"Original capture reference that this adjustment corrects",type:"text"}},id:T,summary:`${q(R)} adjustment with capture lineage`,title:`${q(r)} ${q(R)} Adjustment`,actions:{create:{requires:f,summary:`Create a ${R} adjustment on an open batch`,to:"created"},adjust:{from:["created"],requires:f,summary:`Apply the ${R} adjustment to the open batch`,to:"applied"},correct:{from:["created"],requires:f,summary:"Record a later correction on this open batch instead of changing the closed source batch",to:"applied"}}}),k={create:{...e.cadence?{setsAt:{field:e.closeTriggerField,offset:e.cadence.raw}}:{},summary:`Open a ${q(r).toLowerCase()}`,to:"open"},close:{due:{field:e.closeTriggerField,rule:u},from:["open"],summary:"Freeze the batch and stop all new entries",to:"closed"},calculate:{from:["closed"],signedSum:{amountRef:"netPayable",onNegative:"refuse",onZero:"refuse",sources:[{amountField:"amount",instrumentId:o,refField:s,sign:"add",statuses:["accrued"],subtotalRef:"grossCaptureAmount"},{amountField:"amount",instrumentId:a,refField:s,sign:"add",statuses:["applied"],subtotalRef:"creditAdjustmentAmount"},{amountField:"amount",instrumentId:c,refField:s,sign:"subtract",statuses:["applied"],subtotalRef:"debitAdjustmentAmount"}]},summary:"Prove and freeze the one signed net payable amount",to:"calculated"},approve:{from:["calculated"],summary:"Approve the frozen payable without recomputing it",to:"approved"},instruct:{from:["approved"],moneyEvent:l,payout:{amount:"refs.netPayable",beneficiaryField:e.payoutBeneficiaryReferenceField,beneficiaryPartyField:`${de(e.payoutDestination)}AccountId`,capture:"payoutId",currencyField:"currency",sourceAccountField:`${de(e.settlementAccount)}AccountId`,speed:"standard"},summary:"Create one idempotent payout from the frozen net payable",to:"instructed"},[e.payoutAcknowledgement.port]:{captureInput:{acknowledgementReference:"acknowledgementReference"},from:["instructed"],port:{allowed:t.allowed,fields:{acknowledgementReference:"text"}},summary:"Record the tenant's payout acknowledgement in the receipt",to:"acknowledged"},reconcile:{from:["instructed","acknowledged"],requiresSettlement:{capture:"settlementEvidenceId",payoutRef:"payoutId"},summary:"Record durable evidence that the payout settled",to:"reconciled"}};return{design:[`${r}: capture entries plus signed adjustments freeze at ${e.closeTriggerField}; calculate persists gross, credit, debit, and net refs; negative or zero net refuses`,`${r}: instruct creates one payout intent for the frozen refs.netPayable; only matched settlement evidence can reconcile it`],extraInstruments:[v,x(a,"credit"),x(c,"debit")],feeLines:[],moneyEvents:[te({amount:"The frozen signed sum of gross capture entries plus credit adjustments minus debit adjustments",fromActor:e.settlementAccount,key:l,kind:"payout",toActor:e.payoutDestination,trigger:"Instruct the approved batch payout exactly once"})],instrument:{actors:{[e.payoutDestination]:"beneficiary",[e.settlementAccount]:"payer"},desc:"Immutable batch of capture lineage and signed adjustments that creates one payout",fields:{[e.closeTriggerField]:me("Date the open batch freezes against later entries"),currency:{desc:"ISO 4217 currency shared by the batch and payout instruction",type:"currency"},[e.payoutBeneficiaryReferenceField]:{desc:"Beneficiary ID for the payout instruction",type:"beneficiary"}},id:r,summary:`Payout batch from ${e.settlementAccount.replaceAll("_"," ")} to ${e.payoutDestination.replaceAll("_"," ")}`,title:q(r),actions:k},rules:[{allowedActors:[],detail:`At ${e.closeTriggerField}, the platform closes the batch and every child reference gate refuses later entries`,dueDriven:!0,enforcement:"platform",gatesEvent:null,key:u,kind:"deadline",label:`Batch freezes on ${e.closeTriggerField}`,tenantTunable:!1}],settlement:{name:r,pieces:[]}}}function Sr(e,t,n,r){let o=e.name,a=e.amount.name;if(!Je(o,["place_deposit",t.name,n.name],e.origin,r))return;let c=`${o}_hold_1`,s=e.claimAmount,l=[te({amount:`The full ${a}`,fromActor:e.payer,key:c,kind:"hold",toActor:e.holder,trigger:`Reserve the ${a} in the ${e.holder.replaceAll("_"," ")}'s favor`})],u={create:{summary:`Create a ${q(o).toLowerCase()}`,to:"created"},place_deposit:{from:["created"],moves:[{key:"reservation",operation:"reserve",amount:a,from:e.payer,to:e.holder}],moneyEvent:c,summary:`Reserve the ${a} against the ${e.payer.replaceAll("_"," ")}'s account`,to:"held"},[t.name]:{...s?{decidedAmount:{boundField:s.boundField,field:s.field,remainderAction:n.name},port:{allowed:[...t.allowed],fields:pt(t)}}:{},from:["held"],moves:[{...s?{amount:s.field}:{},key:"post",operation:"post",...s?{partialOnly:!0}:{},reservation:"place_deposit_reservation"},...s?[{key:"remainder",operation:"void",reason:"Return the unclaimed deposit remainder",reservation:"place_deposit_reservation"}]:[]],summary:`Claim the deposit for the ${e.holder.replaceAll("_"," ")} through ${t.name}`,to:"claimed"},[n.name]:{from:["held"],summary:`Return the deposit to the ${e.payer.replaceAll("_"," ")} through ${n.name}`,to:"returned",moves:[{key:"void",operation:"void",reason:"Deposit returned in full",reservation:"place_deposit_reservation"}]}},f=(v,x)=>({allowedActors:[...v.allowed],detail:`${v.allowed.map(q).join(" or ")} decides through the tenant backend`,dueDriven:!1,enforcement:"tenant_app",gatesEvent:null,key:Y(`${o}_${v.name}_gate`),kind:"release_condition",label:`${x} decided through ${v.name}`,tenantTunable:!1});return{design:[s?`${o}: ${a} held as a reservation on the ${e.payer.replaceAll("_"," ")}'s account; ${s.field} claimed through ${t.name} and its exact remainder returned, or the full amount returned through ${n.name}`:`${o}: ${a} held as a reservation on the ${e.payer.replaceAll("_"," ")}'s account; claimed whole through ${t.name} or returned whole through ${n.name}`],feeLines:[],moneyEvents:l,instrument:{actors:{[e.payer]:"payer",[e.holder]:"beneficiary"},desc:s?`Deposit: the ${a} is reserved against the ${e.payer.replaceAll("_"," ")}'s account in the ${e.holder.replaceAll("_"," ")}'s favor, then ${s.field} is claimed and the exact remainder returned, or the deposit is returned in full`:`Deposit: the ${a} is reserved against the ${e.payer.replaceAll("_"," ")}'s account in the ${e.holder.replaceAll("_"," ")}'s favor, then claimed or returned in full`,fields:{[a]:je(e.amount,`The deposit amount in ${e.amount.currency} minor units, reserved in full and fully accounted on claim or return`)},id:o,summary:`Refundable deposit from ${e.payer.replaceAll("_"," ")} held for ${e.holder.replaceAll("_"," ")}`,title:q(o),actions:u},rules:[f(t,"Claim"),f(n,"Return")],settlement:{name:o,pieces:[]}}}function Sn(e){let t=Math.floor(Number(_n)/e),n=Array.from({length:e},()=>t);return n[0]=Number(_n)-t*(e-1),n}function Ir(e){let t=e.name,n=`${t}_commitment`,r=`${de(t)}Id`,o=Y(`${t}_commit`),a=Y(`${t}_cancel`),c=Y(`${t}_collect`),s=Y(`${t}_refund`),l=Y(`${t}_close`),u=x=>[{check:{amountField:"amount",kind:x,targetField:e.target.name},instrumentId:n,over:"children",refField:r,statuses:["committed"]}],f=x=>({[r]:{bind:{currency:"fields.currency",[`${de(e.beneficiary)}AccountId`]:`fields.${de(e.beneficiary)}AccountId`},statuses:x}}),v=x=>({[r]:{match:{"fields.currency":"fields.currency",[`fields.${de(e.beneficiary)}AccountId`]:`fields.${de(e.beneficiary)}AccountId`},statuses:x}});return{design:[`${t}: reuses the catalog funding round and commitment mechanism; the parent lock caps committed rows by target and contributor count`,`${t}: the stored close anchor chooses threshold activation or failure; each commitment then moves whole from its own custody`],extraInstruments:[{actors:{[e.beneficiary]:"beneficiary",[e.contributor]:"payer"},desc:`One whole commitment linked to ${t}`,escrow:!0,fields:{amount:Z("One whole commitment amount"),currency:{desc:"Currency derived from the funding round",type:"currency"},[r]:{desc:`The exact ${t}`,type:`ref:${t}`}},id:n,summary:`Whole commitment to ${t}`,title:`${q(t)} Commitment`,actions:{create:{moneyEvent:o,moves:[{amount:"amount",from:e.contributor,key:"commit",operation:"create",to:"escrow"}],requires:f(["open"]),requiresExposure:[{amountField:"amount",anchorField:r,capField:e.target.name,capOnAnchor:!0,childInstrumentId:n,statuses:["committed"]}],summary:"Store one whole commitment without exceeding the round target",to:"committed"},cancel:{from:["committed"],moneyEvent:a,moves:[{amount:"amount",from:"escrow",key:"cancel",operation:"create",to:e.contributor}],requires:v(["open"]),summary:"Cancel one commitment while the round is open",to:"cancelled"},collect:{from:["committed"],moneyEvent:c,moves:[{amount:"amount",from:"escrow",key:"collect",operation:"create",to:e.beneficiary}],requires:v(["active"]),summary:"Collect one successful commitment whole",to:"collected"},refund:{from:["committed"],moneyEvent:s,moves:[{amount:"amount",from:"escrow",key:"refund",operation:"create",to:e.contributor}],requires:v(["failed"]),summary:"Refund one failed-round commitment whole",to:"refunded"}}}],generatedPrefixInstrumentIds:[n],feeLines:[],moneyEvents:[te({amount:"One stored commitment",fromActor:e.contributor,key:o,kind:"charge",occurrence:"repeatable",toActor:"escrow",trigger:"Create one target-capped commitment"}),te({amount:"One stored commitment whole",fromActor:"escrow",key:a,kind:"refund",occurrence:"repeatable",toActor:e.contributor,trigger:"Cancel before close"}),te({amount:"One stored commitment whole",fromActor:"escrow",key:c,kind:"payout",occurrence:"repeatable",toActor:e.beneficiary,trigger:"Collect after threshold close"}),te({amount:"One stored commitment whole",fromActor:"escrow",key:s,kind:"refund",occurrence:"repeatable",toActor:e.contributor,trigger:"Refund after failed close"})],instrument:{actors:{[e.beneficiary]:"beneficiary"},aggregateInvariants:[{childField:"amount",childInstrumentId:n,childRefField:r,childStatuses:["committed"],parentField:e.target.name},{count:!0,childInstrumentId:n,childRefField:r,childStatuses:["committed"],parentField:"maxContributors"}],desc:"All-or-nothing aggregate funding threshold",fields:{currency:{desc:`Currency fixed to ${e.target.currency}`,type:"currency"},[e.target.name]:Z(`Funding target in ${e.target.currency} minor units`),[e.closeByField]:me("Stored close anchor"),maxContributors:{desc:`Exactly ${e.maxContributors} admitted contributors`,type:`const:${e.maxContributors}`}},id:t,summary:`Threshold funding round for ${e.beneficiary.replaceAll("_"," ")}`,title:q(t),actions:{create:{summary:"Open the funding round",to:"open"},activate:{due:{field:e.closeByField,rule:l},from:["open"],requiresAggregate:u("sum_at_least"),summary:"Activate when commitments meet the target",to:"active"},fail:{due:{field:e.closeByField,rule:l},from:["open"],requiresAggregate:u("sum_below"),summary:"Fail when commitments remain below target",to:"failed"},close:{from:["active"],requiresAggregate:[{check:{kind:"all_in"},instrumentId:n,over:"children",refField:r,statuses:["cancelled","collected"]}],summary:"Settle after every admitted row is collected or was cancelled before activation",to:"settled"}}},rules:[{allowedActors:[],detail:"The stored close anchor compares committed rows with the target",dueDriven:!0,enforcement:"platform",gatesEvent:null,key:l,kind:"deadline",label:"Round closes against its stored threshold",tenantTunable:!1}],settlement:{name:t,pieces:[]}}}function Pr(e,t){let n=e.name,r=`${n}_entitlement`,o=`${de(n)}Id`,a=Y(`${n}_payout`),c=s=>({[o]:{bind:{currency:"fields.currency",[`${de(e.source)}AccountId`]:`fields.${de(e.source)}AccountId`},statuses:s}});return{design:[`${n}: reuses the catalog largest-remainder distribution; the evidence port freezes the claimant set before any payout`],extraInstruments:[{actors:{[e.recipient]:"beneficiary",[e.source]:"payer"},desc:`One frozen weighted entitlement in ${n}`,fields:{currency:{desc:"Currency derived from the distribution",type:"currency"},[o]:{desc:`The exact ${n}`,type:`ref:${n}`},[e.weight.name]:Z("Stored non-negative entitlement weight")},id:r,summary:`Frozen entitlement in ${n}`,title:`${q(n)} Entitlement`,actions:{create:{requires:c(["open"]),summary:"Record one entitlement before snapshot",to:"recorded"},payout:{distribute:{amountRef:"payoutShare",onZero:"skip_steps",pool:{from:"parent",path:`fields.${e.amount.name}`},refField:o,statuses:["recorded","paid"],weightField:e.weight.name},from:["recorded"],moneyEvent:a,moves:[{amount:"refs.payoutShare",from:e.source,key:"payout",operation:"create",to:e.recipient}],requires:{[o]:{match:{"fields.currency":"fields.currency",[`fields.${de(e.source)}AccountId`]:`fields.${de(e.source)}AccountId`},statuses:["snapshotted"]}},summary:"Pay the deterministic largest-remainder share once",to:"paid"}}}],generatedPrefixInstrumentIds:[r],feeLines:[],moneyEvents:[te({amount:"A deterministic largest-remainder share of the stored pool",fromActor:e.source,key:a,kind:"payout",occurrence:"repeatable",toActor:e.recipient,trigger:"Pay one frozen entitlement"})],instrument:{actors:{[e.source]:"payer"},aggregateInvariants:[{count:!0,childInstrumentId:r,childRefField:o,childStatuses:["recorded","paid"],parentField:"maxRecipients"}],desc:"Evidence-frozen weighted distribution",fields:{currency:{desc:`Currency fixed to ${e.amount.currency}`,type:"currency"},[e.amount.name]:Z(`Distribution pool in ${e.amount.currency} minor units`),[e.recordAtField]:me("Stored record date"),maxRecipients:{desc:`Exactly ${e.maxRecipients} frozen entitlement rows`,type:`const:${e.maxRecipients}`}},id:n,summary:"Frozen largest-remainder distribution",title:q(n),actions:{create:{summary:"Open entitlement recording",to:"open"},[e.snapshot.port]:{captureInput:{snapshotEvidenceReference:"evidenceReference"},from:["open"],port:{allowed:t.allowed,fields:{evidenceReference:"text"}},summary:"Freeze the entitlement set from stored evidence",to:"snapshotted"}}},rules:[],settlement:{name:n,pieces:[]}}}function Cr(e){let t=e.name,n=`${t}_draw`,r=`${de(t)}Id`,o=`${de(e.obligation.settlement)}Id`,a=Y(`${t}_draw`),c=Y(`${t}_expiry`),s=e.availabilityPolicy==="revolving"?["drawn"]:["drawn","resolved"];return{design:[`${t}: owns reusable draw capacity only; ${e.obligation.settlement} remains the sole repayment and delinquency owner`],extraInstruments:[{actors:{[e.drawDestination]:"beneficiary",[e.lender]:"payer"},desc:`One capacity-capped draw linked to ${e.obligation.settlement}`,fields:{amount:Z("One draw amount"),currency:{desc:"Currency derived from the facility",type:"currency"},[r]:{desc:`The exact ${t}`,type:`ref:${t}`},[o]:{desc:"The sole repayment obligation",type:`ref:${e.obligation.settlement}`}},id:n,summary:`Draw from ${t}`,title:`${q(t)} Draw`,actions:{create:{moneyEvent:a,moves:[{amount:"amount",from:e.lender,key:"draw",operation:"create",to:e.drawDestination}],requires:{[r]:{bind:{currency:"fields.currency",[`${de(e.drawDestination)}AccountId`]:`fields.${de(e.drawDestination)}AccountId`,[`${de(e.lender)}AccountId`]:`fields.${de(e.lender)}AccountId`},statuses:["active"]},[o]:{statuses:["active"],unique:!0}},requiresExposure:[{amountField:"amount",anchorField:r,capField:e.limit.name,capOnAnchor:!0,childInstrumentId:n,statuses:s}],summary:"Create one draw under the locked facility capacity",to:"drawn"},resolve:{from:["drawn"],requires:{[o]:["repaid","written_off"]},summary:"Release revolving capacity only after the linked obligation resolves",to:"resolved"}}}],generatedPrefixInstrumentIds:[n],feeLines:[],moneyEvents:[te({amount:"One draw under the stored facility limit",fromActor:e.lender,key:a,kind:"payout",occurrence:"repeatable",toActor:e.drawDestination,trigger:"Admit one linked draw"})],instrument:{actors:{[e.borrower]:"party",[e.drawDestination]:"beneficiary",[e.lender]:"payer"},desc:"Reusable capacity with repayment delegated to one scheduled obligation",fields:{currency:{desc:`Currency fixed to ${e.limit.currency}`,type:"currency"},[e.limit.name]:Z(`Facility limit in ${e.limit.currency} minor units`),[e.expiresAtField]:me("Stored draw expiry")},id:t,summary:`Draw capacity for ${e.borrower.replaceAll("_"," ")}`,title:q(t),actions:{create:{summary:"Open the facility",to:"active"},freeze:{due:{field:e.expiresAtField,rule:c},from:["active"],summary:"Freeze new draws at expiry",to:"frozen"},close:{from:["active","frozen"],requiresAggregate:[{check:{kind:"all_in"},instrumentId:n,over:"children",refField:r,statuses:["resolved"]}],summary:"Close only when every admitted draw resolved",to:"closed"}}},rules:[{allowedActors:[],detail:"The stored expiry freezes new draws without changing repayment state",dueDriven:!0,enforcement:"platform",gatesEvent:null,key:c,kind:"deadline",label:"Facility freezes at expiry",tenantTunable:!1}],settlement:{name:t,pieces:[]}}}function Er(e,t){let n=e.name,r=`${n}_approved_amount`,o=`${de(n)}Id`,a=Y(`${n}_payout`),c=`${de(e.source)}AccountId`,s=`${de(e.destination)}AccountId`,l={[o]:{match:{"fields.currency":"fields.currency",[`fields.${s}`]:`fields.${s}`,[`fields.${c}`]:`fields.${c}`},statuses:["submitted"]}};return{design:[`${n}: a stored external decision may approve one amount under the cap; recovery requires a separate transfer`],extraInstruments:[{actors:{[e.destination]:"beneficiary",[e.source]:"payer"},desc:`One evidence-gated amount under ${n}`,fields:{amount:Z("Approved amount under the parent cap"),currency:{desc:"Currency derived from the parent cap",type:"currency"},[o]:{desc:`The exact ${n}`,type:`ref:${n}`}},id:r,summary:`Approved amount under ${n}`,title:`${q(n)} Approved Amount`,actions:{create:{requires:{[o]:{bind:{currency:"fields.currency",[s]:`fields.${s}`,[c]:`fields.${c}`},statuses:["submitted"],unique:!0}},summary:"Create one candidate amount under the parent",to:"created"},approve:{captureInput:{decisionEvidenceReference:"evidenceReference"},from:["created"],port:{allowed:t.allowed,fields:{evidenceReference:"text"}},requires:l,requiresExposure:[{amountField:"amount",anchorField:o,capField:e.cap.name,capOnAnchor:!0,childInstrumentId:r,statuses:["approved","paid"]}],summary:"Store one externally approved amount under the cap",to:"approved"},pay:{from:["approved"],moneyEvent:a,moves:[{amount:"amount",from:e.source,key:"payout",operation:"create",to:e.destination}],requires:l,summary:"Pay the stored approved amount once",to:"paid"}}}],generatedPrefixInstrumentIds:[r],feeLines:[],moneyEvents:[te({amount:"The stored approved amount under the cap",fromActor:e.source,key:a,kind:"payout",occurrence:"repeatable",toActor:e.destination,trigger:"Pay one approved amount"})],instrument:{actors:{[e.destination]:"beneficiary",[e.source]:"payer"},desc:"Capped disbursement controlled by stored external evidence",fields:{currency:{desc:`Currency fixed to ${e.cap.currency}`,type:"currency"},[e.cap.name]:Z(`Disbursement cap in ${e.cap.currency} minor units`)},id:n,summary:`Capped disbursement to ${e.destination.replaceAll("_"," ")}`,title:q(n),actions:{create:{summary:"Submit the capped disbursement",to:"submitted"},deny:{captureInput:{decisionEvidenceReference:"evidenceReference"},from:["submitted"],port:{allowed:t.allowed,fields:{evidenceReference:"text"}},requiresAggregate:[{check:{kind:"all_in"},instrumentId:r,over:"children",refField:o,statuses:["created"]}],summary:"Record a denial without moving money",to:"denied"}}},rules:[],settlement:{name:n,pieces:[]}}}function Tr(e){let t=e.name,n=`${de(t)}Id`,r=Y(`${t}_contribution`),o=Y(`${t}_guarantee_contribution`),a=Y(`${t}_payout`),c=[...new Set([...e.members,...e.payoutOrder,...e.guarantor?[e.guarantor]:[]])],s=Object.fromEntries(c.map(v=>{let x=`${de(v)}AccountId`;return[x,`fields.${x}`]})),l=e.members.map(v=>`${t}_${v}_contribution`),u=e.members.map((v,x)=>{let k=l[x],T={create:{requires:{[n]:{bind:{currency:"fields.currency",...s,[e.schedule.firstDueField]:`fields.${e.schedule.firstDueField}`,[e.contribution.name]:`fields.${e.contribution.name}`},statuses:["forming"],unique:!0}},summary:`Create the fixed contribution row for ${v.replaceAll("_"," ")}`,to:"cycle_1_due"}};for(let R=0;R<e.schedule.count;R+=1){let C=R+1,Q=`cycle_${C}_due`,B=`cycle_${C}_defaulted`,W=`cycle_${C}_funded`,H=`cycle_${C}_guaranteed`,ue=C===e.schedule.count?"final_paid":`cycle_${C+1}_due`,X=Y(`${t}_cycle_${C}_due`),$=e.contribution.name,D=e.contribution.name,K={field:e.schedule.firstDueField,rule:X,...Be(e.schedule,R)};T[`contribute_cycle_${C}`]={due:K,from:[Q],moneyEvent:r,moves:[{amount:$,from:v,key:"contribution",operation:"create",to:"escrow"}],requires:{[n]:[`active_cycle_${C}`]},summary:`Fund ${v.replaceAll("_"," ")}'s cycle ${C} contribution`,to:W},T[`mark_default_cycle_${C}`]={due:K,from:[Q],requires:{[n]:[`active_cycle_${C}`]},summary:`Mark the stored cycle ${C} due condition`,to:B},e.guarantor&&(T[`guarantee_cycle_${C}`]={from:[B],moneyEvent:o,moves:[{amount:D,from:e.guarantor,key:"guarantee",operation:"create",to:"escrow"}],requires:{[n]:[`active_cycle_${C}`]},summary:`Fund the defaulted cycle ${C} amount before payout`,to:H}),T[`pay_cycle_${C}`]={from:[W],moneyEvent:a,moves:[{amount:$,from:"escrow",key:"payout",operation:"create",to:e.payoutOrder[R]}],requires:{[n]:[`cycle_${C}_ready`]},summary:`Pay this member's stored contribution into cycle ${C}'s shared pot recipient`,to:ue},e.guarantor&&(T[`pay_guaranteed_cycle_${C}`]={from:[H],moneyEvent:a,moves:[{amount:D,from:"escrow",key:"payout",operation:"create",to:e.payoutOrder[R]}],requires:{[n]:[`cycle_${C}_ready`]},summary:`Pay the funded default into cycle ${C}'s stored recipient`,to:ue})}return T.close={from:["final_paid"],requiresDrainedAccount:{path:"refs.escrowAccountId"},summary:"Complete after the final payout drains this member custody",to:"completed"},{actors:Object.fromEntries([[v,"payer"],...e.guarantor?[[e.guarantor,"payer"]]:[],...e.payoutOrder.map(R=>[R,"beneficiary"])]),desc:`Fixed contribution row for ${v.replaceAll("_"," ")}`,escrow:!0,fields:{[e.contribution.name]:Z("Exact contribution amount shared by every cycle"),currency:{desc:"Currency derived from the pool",type:"currency"},[e.schedule.firstDueField]:me("First due anchor derived from the pool"),[n]:{desc:`The exact ${t}`,type:`ref:${t}`}},id:k,summary:`${v.replaceAll("_"," ")} contribution row`,title:`${q(t)} ${q(v)} Contribution`,actions:T}}),f={create:{summary:"Create the fixed roster before activation",to:"forming"},cancel:{from:["forming"],summary:"Cancel before activation without moving money",to:"cancelled"},activate:{from:["forming"],requiresAggregate:l.map(v=>({check:{kind:"count_equals_field",field:"one"},instrumentId:v,over:"children",refField:n,statuses:["cycle_1_due"]})),summary:"Activate only after every fixed member row exists once",to:"active_cycle_1"}};for(let v=0;v<e.schedule.count;v+=1){let x=v+1;f[`ready_cycle_${x}`]={from:[`active_cycle_${x}`],requiresAggregate:l.map(k=>({check:{kind:"all_in"},instrumentId:k,over:"children",refField:n,statuses:[`cycle_${x}_funded`,...e.guarantor?[`cycle_${x}_guaranteed`]:[]]})),summary:`Lock cycle ${x} only after every member row is funded or guaranteed`,to:`cycle_${x}_ready`},f[`advance_cycle_${x}`]={from:[`cycle_${x}_ready`],requiresAggregate:l.map(k=>({check:{kind:"all_in"},instrumentId:k,over:"children",refField:n,statuses:[x===e.schedule.count?"completed":`cycle_${x+1}_due`]})),summary:x===e.schedule.count?"Complete after the final shared pot pays":`Advance after every cycle ${x} contribution pays`,to:x===e.schedule.count?"completed":`active_cycle_${x+1}`}}return{design:[`${t}: fixed roster and stored payout order; one member-specific row per member avoids tuple identity and keeps each cycle idempotent`],extraInstruments:u,generatedPrefixInstrumentIds:l,feeLines:[],moneyEvents:[te({amount:"One exact member contribution",fromActor:e.members[0],key:r,kind:"charge",occurrence:"repeatable",toActor:"escrow",trigger:"Fund one member and cycle"}),...e.guarantor?[te({amount:"One exact defaulted contribution",fromActor:e.guarantor,key:o,kind:"charge",occurrence:"repeatable",toActor:"escrow",trigger:"Fund one defaulted member and cycle"})]:[],te({amount:"One exact member contribution from the cycle pot",fromActor:"escrow",key:a,kind:"payout",occurrence:"repeatable",toActor:e.payoutOrder[0],trigger:"Pay the stored cycle recipient"})],instrument:{actors:Object.fromEntries([...e.members.map(v=>[v,"party"]),...e.guarantor?[[e.guarantor,"payer"]]:[]]),desc:"Fixed rotating contribution and payout order",fields:{currency:{desc:`Currency fixed to ${e.contribution.currency}`,type:"currency"},[e.contribution.name]:Z(`Exact contribution in ${e.contribution.currency} minor units`),[e.schedule.firstDueField]:me("Stored first contribution due date"),one:{desc:"Exact fixed member-row count",type:"const:1"}},id:t,summary:`${e.members.length}-member rotating pool`,title:q(t),actions:f},rules:Array.from({length:e.schedule.count},(v,x)=>({allowedActors:[],detail:`Cycle ${x+1} default follows its stored due condition`,dueDriven:!0,enforcement:"platform",gatesEvent:null,key:Y(`${t}_cycle_${x+1}_due`),kind:"deadline",label:`Cycle ${x+1} due condition`,tenantTunable:!1})),settlement:{name:t,pieces:[]}}}function Be(e,t){return t===0?{}:{offset:`P${e.every.days*t}D`}}function Rr(e,t,n,r,o){let a=e.name,c=e.schedule,s=e.amount.name,l=Y(`${a}_period_collection`),u=Y(`${a}_period_open`),f=c.terminationDrain;if(!Je(a,["open_period","collect_period",f],e.origin,r))return;let v={drainAction:f,delinquency:"parent_policy",liability:"one_open",period:{calendar:"gregorian",monthEnd:"clamp_to_last_day",months:c.every.months},...c.termination.kind==="stored_date"?{untilField:c.termination.field}:{untilAction:f}},x=c.termination.kind==="stored_date"?{due:{field:c.termination.field,rule:Y(`${a}_termination`)}}:{},k=c.termination.kind==="port"&&o?{captureInput:Object.fromEntries(o.fields.map(T=>[T.name,T.name])),port:{allowed:o.allowed,fields:pt(o)}}:{};return{design:[`${a}: one ${c.every.raw} calendar period may be open; the due action opens liability without moving money`,`${a}: recurring_collection ${t.name} owns explicit collection attempts and parent delinquency; only collect_period moves ${s}`,`${a}: ${f} cancels active or open liability and prevents later recurrence dispatch`],feeLines:[],moneyEvents:[te({amount:`One ${s} period charge`,fromActor:e.payer,key:l,kind:"installment",occurrence:"repeatable",toActor:e.payee,trigger:"Collect one explicitly opened period liability"})],instrument:{actors:{[e.debtor]:"party",[e.payee]:"beneficiary",[e.payer]:"payer"},desc:`Open monthly obligation for ${e.debtor.replaceAll("_"," ")}; one period liability at a time`,fields:{[s]:je(e.amount,`Exact charge for one ${c.every.raw} period in ${e.amount.currency} minor units`),currency:{desc:`Currency fixed to ${e.amount.currency}`,type:`currency:${e.amount.currency}`},[c.firstDueField]:me("First period anchor; missing Gregorian month days clamp to the target month's final day"),...c.termination.kind==="stored_date"&&c.termination.field!==c.firstDueField?{[c.termination.field]:me("Stored termination date that bars later period anchors")}:{}},id:a,summary:`Open ${c.every.raw} obligation for ${e.debtor.replaceAll("_"," ")}`,title:q(a),actions:{create:{summary:"Create the open obligation before its first anchor",to:"active"},open_period:{due:{every:v,field:c.firstDueField,rule:u},from:["active"],summary:"Open exactly one period liability without moving money",to:"period_open"},collect_period:{captureInput:{mandateEvidenceReference:"evidenceReference"},from:["period_open"],moneyEvent:l,moves:[{amount:s,from:e.payer,key:"period_collection",operation:"create",to:e.payee}],port:{allowed:n.allowed,fields:{evidenceReference:"text"}},summary:"Collect one authored period charge with mandate evidence",to:"active"},[f]:{...x,...k,from:["active","period_open"],summary:"Cancel the open schedule and drain any period liability",to:"canceled"}}},rules:[{allowedActors:[],detail:"The recurrence action opens one liability only from active; it never moves money",dueDriven:!0,enforcement:"platform",gatesEvent:null,key:u,kind:"deadline",label:"One deterministic period occurrence opens liability",tenantTunable:!1},...c.termination.kind==="stored_date"?[{allowedActors:[],detail:"The stored termination date invokes the declared cancel path without moving money",dueDriven:!0,enforcement:"platform",gatesEvent:null,key:Y(`${a}_termination`),kind:"deadline",label:"Stored termination drains the open schedule",tenantTunable:!1}]:[]],settlement:{name:a,pieces:[]}}}function Fr(e,t,n){let r=e.name,o=e.amount.name,a=`${r.replaceAll(/_([a-z])/g,(X,$)=>$.toUpperCase())}Id`,c=Sn(e.schedule.count),s=c.map((X,$)=>`installment${$+1}Amount`),l=c.map((X,$)=>`${r}_installment_${$+1}_payment`),u="active",f=X=>`installment_${X+1}_delinquent`,v=c.map((X,$)=>f($)),x=[u,...v],k=Y(`${r}_repayment`),T=Y(`${r}_refund`),R=Y(`${r}_advance`),C={currency:{desc:`Currency fixed to ${e.amount.currency}`,type:"currency"},[o]:Z(`The principal in ${e.amount.currency} minor units; the stored installment anchors partition it exactly`),[e.schedule.firstDueField]:me(`Due date of the first installment; later anchors use fixed offsets of ${e.schedule.every.raw}`)};for(let[X,$]of s.entries())C[$]=Z(`Stored amount for installment ${X+1} of ${e.schedule.count}${X===0?" (carries the integer-division remainder)":""}`),C[`installment${X+1}DelinquentAfter`]=ir(`Machine-set marker proving installment ${X+1} reached its stored due date while unpaid`);let Q=l.map((X,$)=>({childField:"amount",childInstrumentId:X,childRefField:a,childStatuses:["paid"],parentField:s[$]})),B={create:{summary:`Create a ${q(r).toLowerCase()} obligation`,to:"draft"},approve:{from:["draft"],summary:"Approve the immutable principal partition and stored anchors",to:e.advanceTo?"approved":u},...e.advanceTo?{advance:{from:["approved"],moneyEvent:R,moves:[{amount:o,from:e.payee,key:"advance",operation:"create",to:e.advanceTo}],summary:`Advance the principal to the ${e.advanceTo.replaceAll("_"," ")}; the internal ledger receipt is the confirmation`,to:u}}:{},write_off:{from:["draft",...e.advanceTo?["approved"]:[],...x],summary:"Write off the remaining exposure without moving money",to:"written_off"}},W=[];for(let[X,$]of l.entries()){let D=X+1,K=Y(`${r}_installment_${D}_due`),re={field:e.schedule.firstDueField,rule:K,...Be(e.schedule,X)},ee=U=>[{check:{amountField:"amount",kind:U,targetField:s[X]},instrumentId:$,over:"children",refField:a,statuses:["paid"]}];B[`mark_installment_${D}_delinquent`]={due:re,from:x.filter(U=>U!==f(X)),requiresAggregate:ee("sum_below"),setsAt:{field:`installment${D}DelinquentAfter`,marker:!0,offset:"PT1S"},summary:`Mark installment ${D} delinquent only when its due anchor is unmet`,to:f(X)},B[`collect_installment_${D}`]={due:re,from:v,requiresAggregate:ee("sum_exactly"),summary:`Close delinquent installment ${D} after linked payments reach its stored amount`,to:u},W.push({allowedActors:[],detail:`At stored anchor ${D}, the platform compares paid child rows with ${s[X]} and chooses paid or delinquent`,dueDriven:!0,enforcement:"platform",gatesEvent:null,key:K,kind:"deadline",label:`Installment ${D} resolves from its stored due condition`,tenantTunable:!1})}let H=Y(`${r}_completion_due`);B.complete={due:{field:e.schedule.firstDueField,rule:H,...Be(e.schedule,c.length-1)},from:x,requiresAggregate:l.map((X,$)=>({check:{amountField:"amount",kind:"sum_exactly",targetField:s[$]},instrumentId:X,over:"children",refField:a,statuses:["paid"]})),summary:"Close the obligation only after every stored anchor is paid exactly",to:"repaid"},W.push({allowedActors:[],detail:"After the final stored anchor, the platform closes only when every anchor is paid exactly",dueDriven:!0,enforcement:"platform",gatesEvent:null,key:H,kind:"deadline",label:"Obligation completion follows exact aggregate repayment",tenantTunable:!1});let ue=X=>{let $=X+1,D=l[X],K=x,re=`${e.payer.replaceAll(/_([a-z])/g,(M,ce)=>ce.toUpperCase())}AccountId`,ee=`${e.payee.replaceAll(/_([a-z])/g,(M,ce)=>ce.toUpperCase())}AccountId`,U={[a]:{bind:{currency:"fields.currency",[re]:`fields.${re}`,[ee]:`fields.${ee}`},statuses:K}},F={[a]:{match:{"fields.currency":"fields.currency",[`fields.${re}`]:`fields.${re}`,[`fields.${ee}`]:`fields.${ee}`},statuses:K}};return{actors:{[e.payee]:"beneficiary",[e.payer]:"payer"},desc:`One partial or full payment bound to installment ${$} of ${r}; the operation name fixes the anchor and ${a} fixes the obligation`,fields:{amount:Z(`Positive payment amount capped with its paid siblings at ${s[X]}`),currency:{desc:"ISO 4217 currency derived from the obligation",type:"currency"},[a]:{desc:`The exact ${r.replaceAll("_"," ")} this payment belongs to`,type:`ref:${r}`}},id:D,summary:`Anchor-bound payment for installment ${$}`,title:`${q(r)} Installment ${$} Payment`,actions:{create:{requires:U,summary:`Create a payment record for installment ${$}`,to:"created"},repay:{...t&&n?{captureInput:{mandateEvidenceReference:"evidenceReference"},port:{allowed:n.allowed,fields:{evidenceReference:"text"}}}:{},from:["created"],moneyEvent:k,moves:[{amount:"amount",from:e.payer,key:"repayment",operation:"create",to:e.payee}],requires:F,requiresExposure:[{amountField:"amount",anchorField:a,capField:s[X],capOnAnchor:!0,childInstrumentId:D,statuses:["paid"]}],summary:`Pay a partial or full amount against installment ${$}`,to:"paid"},refund:{from:["paid"],moneyEvent:T,moves:[{amount:"amount",from:e.payee,key:"refund",operation:"create",to:e.payer}],requires:F,summary:`Refund this one stored installment ${$} payment whole`,to:"refunded"}}}};return{design:[`${r}: existing scheduled mechanism in obligation mode; principal partitions into ${e.schedule.count} stored anchors; each payment operation names one anchor and one obligation`,`${r}: partial and early payments serialize under per-anchor aggregate caps; each refund reverses one paid row whole; rescheduling is refused by the checker`,`${r}: due-only delinquency and write-off change state without money; ${e.advanceTo?"advance is an internal ledger movement with no provider claim":"no advance is emitted"}`,...t?[`${t.name}: explicit collection attempts reuse ${r}'s anchor-bound repayment actions; mandate evidence is captured per attempt; failures remain receipted failures and delinquency stays on ${r}`]:[]],extraInstruments:l.map((X,$)=>ue($)),generatedPrefixInstrumentIds:l,feeLines:[],moneyEvents:[...e.advanceTo?[te({amount:`The full ${o}`,fromActor:e.payee,key:R,kind:"payout",toActor:e.advanceTo,trigger:"Advance the approved principal once"})]:[],te({amount:"A positive amount capped by its stored installment anchor",fromActor:e.payer,key:k,kind:"installment",occurrence:"repeatable",toActor:e.payee,trigger:"Pay one anchor-bound partial or full installment amount"}),te({amount:"Exactly one stored paid installment payment",fromActor:e.payee,key:T,kind:"refund",occurrence:"repeatable",toActor:e.payer,trigger:"Refund one linked paid installment payment whole"})],instrument:{actors:{...e.advanceTo?{[e.advanceTo]:"beneficiary"}:{},[e.payee]:"beneficiary",[e.payer]:"payer",[e.debtor]:"party"},aggregateInvariants:Q,desc:`Installment obligation for ${e.debtor.replaceAll("_"," ")}; ${e.payer.replaceAll("_"," ")} pays ${e.payee.replaceAll("_"," ")} against exact stored anchors`,fields:C,id:r,...Pe(Ae(o,s)),summary:`${e.schedule.count}-anchor obligation for ${e.debtor.replaceAll("_"," ")}`,title:q(r),actions:B},rules:W,settlement:{name:r,pieces:[]}}}function Or(e){let t=e.name,n=e.amount.name,{schedule:r}=e,o=`${t}_schedule`,a=Sn(r.count),c={[n]:Z(`The total scheduled amount in ${e.amount.currency} minor units; the installment fields below partition it exactly`),[r.firstDueField]:me(`Due date of the first installment; installment k falls ${r.every.raw} after its predecessor`)},s=a.map((k,T)=>{let R=`installment${T+1}Amount`;return c[R]=Z(`Installment ${T+1} of ${r.count}${T===0?" (carries the integer-division remainder)":""}: about ${le(a[T])} of ${n}, collected on its own stored-date anchor`),R}),l=a.map((k,T)=>`pay_installment_${T+1}`),u=Ie(l,"active","settled","collecting"),f=`${t}_installments`,v=[te({amount:`The ${n}, partitioned into ${r.count} installments`,fromActor:e.payer,key:f,kind:"installment",occurrence:"repeatable",toActor:e.payee,trigger:`Collect each of the ${r.count} installments on its stored due date`})],x={create:{summary:`Create a ${q(t).toLowerCase()} plan`,to:"active"}};for(let[k,T]of s.entries())x[l[k]]={due:{field:r.firstDueField,rule:o,...Be(r,k)},from:[u[k]?.from],moneyEvent:f,moves:[{key:"transfer",operation:"create",amount:T,from:e.payer,to:e.payee}],summary:`Collect installment ${k+1} of ${r.count}`,to:u[k]?.to};return{design:[`${t}: ${r.count} installments every ${r.every.raw} from ${r.firstDueField}; finite by construction, one idempotent anchor per installment`],feeLines:[],moneyEvents:v,instrument:{actors:{[e.payer]:"payer",[e.payee]:"beneficiary"},desc:`Scheduled payment: the ${e.payer.replaceAll("_"," ")} pays ${n} to the ${e.payee.replaceAll("_"," ")} in ${r.count} installments, one every ${r.every.raw}`,fields:c,id:t,...Pe(Ae(n,s)),summary:`${r.count}-installment schedule from ${e.payer.replaceAll("_"," ")} to ${e.payee.replaceAll("_"," ")}`,title:q(t),actions:x},rules:[{allowedActors:[],detail:`Each of the ${r.count} installments is collected once from its stored due date`,dueDriven:!0,enforcement:"platform",gatesEvent:null,key:o,kind:"deadline",label:"Installments collected on their stored due dates",tenantTunable:!1}],settlement:{name:t,pieces:[]}}}function Dr(e,t){return e.source.kind==="carve"?Nr(e,e.source.settlement,t):Lr(e,e.source.schedule)}function Nr(e,t,n){let r=e.name,o=e.amount.name,a=e.feeBps>0,c=e.advanced.replaceAll("_"," "),s=e.funder.replaceAll("_"," "),l=t.replaceAll("_"," "),f=[{field:"carveHoldId",statuses:["funded"],target:t},...n.map((x,k)=>({field:`carveRecourse${k+1}Id`,statuses:["active"],target:x.name}))],v={[o]:Z(`The advanced amount in ${e.amount.currency} minor units, disbursed to the ${c} up front`),...Object.fromEntries(f.map(x=>[x.field,{desc:`The ${x.target.replaceAll("_"," ")} bound to this advance`,type:`ref:${x.target}`}])),...a?{feeAmount:Z(`${le(e.feeBps)} of ${o}, the funder's discount owed on top of the advance`),repayableAmount:Z(`${o} + feeAmount: what the ${l} release owes the ${s}`)}:{}};return{design:[`${r}: ${o} advanced to the ${e.advanced} up front and repaid by carving the ${t} release${a?`; repayableAmount = ${o} + ${le(e.feeBps)} fee`:""}`],feeLines:a?[{label:`${q(e.funder)} discount`,on:`each ${r.replaceAll("_"," ")}`,structure:`${le(e.feeBps)} of the ${o}, owed on top out of the ${l} release`}]:[],moneyEvents:[te({amount:`The full ${o}`,fromActor:e.funder,key:`${r}_disburse`,kind:"payout",toActor:e.advanced,trigger:`Disburse the advance to the ${c}`})],instrument:{actors:{[e.advanced]:"beneficiary",[e.funder]:"payer"},desc:`Advance: the ${s} disburses ${o} to the ${c} and is repaid out of the ${l} release, which pays the ${s} in the ${c}'s place${a?", plus the funder's discount":""}`,fields:v,id:r,...Pe(a?Ae("repayableAmount",[o,"feeAmount"]):[]),summary:`Advance to the ${c} repaid by carving the ${l} release`,title:q(r),actions:{create:{summary:`Create a ${q(r).toLowerCase()}`,to:"created"},disburse:{from:["created"],moneyEvent:`${r}_disburse`,moves:[{key:"transfer",operation:"create",amount:o,from:e.funder,to:e.advanced}],requires:Object.fromEntries(f.map(x=>[x.field,{match:{[`fields.${o}`]:`fields.${o}`,"fields.currency":"fields.currency"},statuses:x.statuses}])),summary:`Disburse the ${o} to the ${c}`,to:"advanced"},settle:{from:["advanced"],summary:`Close the advance once the ${l} has released to the ${s}`,to:"repaid"}}},rules:[{allowedActors:[],detail:`The ${l} releases the ${c}'s whole share to the ${s} instead of to the ${c}; the advance is repaid out of that release and never out of new money`,dueDriven:!1,enforcement:"platform",gatesEvent:null,key:`${r}_carve`,kind:"release_condition",label:`Repaid by carving the ${l} release`,tenantTunable:!1}],settlement:{name:r,pieces:[]}}}function Lr(e,t){let n=e.name,r=e.amount.name,o=`${n}_schedule`,a=Sn(t.count),c=e.feeBps>0,s=c?"repayableAmount":r,l={[r]:Z(`The advanced amount in ${e.amount.currency} minor units, disbursed to the ${e.advanced.replaceAll("_"," ")} up front`),...c?{feeAmount:Z(`${le(e.feeBps)} of ${r}, the funder's discount repaid on top of the advance`),repayableAmount:Z(`${r} + feeAmount: the total the repayment fields below partition exactly`)}:{},[t.firstDueField]:me(`Due date of the first repayment; repayment k falls ${t.every.raw} after its predecessor`)},u=a.map((R,C)=>{let Q=`repayment${C+1}Amount`;return l[Q]=Z(`Repayment ${C+1} of ${t.count}${C===0?" (carries the integer-division remainder)":""}: about ${le(a[C])} of ${s}, collected on its own stored-date anchor`),Q}),f=a.map((R,C)=>`collect_repayment_${C+1}`),v=Ie(f,"advanced","repaid","repaying"),x=[te({amount:`The full ${r}`,fromActor:e.funder,key:`${n}_disburse`,kind:"payout",toActor:e.advanced,trigger:`Disburse the advance to the ${e.advanced.replaceAll("_"," ")}`})],k={create:{summary:`Create a ${q(n).toLowerCase()}`,to:"created"},disburse:{from:["created"],moneyEvent:`${n}_disburse`,moves:[{key:"transfer",operation:"create",amount:r,from:e.funder,to:e.advanced}],summary:`Disburse the ${r} to the ${e.advanced.replaceAll("_"," ")}`,to:"advanced"}},T=`${n}_repayments`;x.push(te({amount:`The ${s}, partitioned into ${t.count} repayments`,fromActor:e.advanced,key:T,kind:"installment",occurrence:"repeatable",toActor:e.funder,trigger:`Collect each of the ${t.count} repayments on its stored due date`}));for(let[R,C]of u.entries()){let Q=T;k[f[R]]={due:{field:t.firstDueField,rule:o,...Be(t,R)},from:[v[R]?.from],moneyEvent:Q,moves:[{key:"transfer",operation:"create",amount:C,from:e.advanced,to:e.funder}],summary:`Collect repayment ${R+1} of ${t.count}`,to:v[R]?.to}}return{design:[`${n}: ${r} advanced up front; ${t.count} repayments every ${t.every.raw} conserve against ${s}${c?` (advance + ${le(e.feeBps)} fee)`:""}`],feeLines:c?[{label:`${q(e.funder)} discount`,on:`each ${n.replaceAll("_"," ")}`,structure:`${le(e.feeBps)} of the ${r}, repaid on top of the advance`}]:[],moneyEvents:x,instrument:{actors:{[e.funder]:"payer",[e.advanced]:"beneficiary"},desc:`Advance: the ${e.funder.replaceAll("_"," ")} disburses ${r} to the ${e.advanced.replaceAll("_"," ")}, repaid over ${t.count} scheduled repayments${c?" plus the funder's discount":""}`,fields:l,id:n,...Pe([...Ae(s,u),...c?Ae("repayableAmount",[r,"feeAmount"]):[]]),summary:`Advance to ${e.advanced.replaceAll("_"," ")} repaid over ${t.count} anchors`,title:q(n),actions:k},rules:[{allowedActors:[],detail:`Each of the ${t.count} repayments is collected once from its stored due date`,dueDriven:!0,enforcement:"platform",gatesEvent:null,key:o,kind:"deadline",label:"Repayments collected on their stored due dates",tenantTunable:!1}],settlement:{name:n,pieces:[]}}}function jr(e){let t=e.name,n=`${t}_period`,r=e.rates[0]?.field.currency??"SAR",o={[e.closeByField]:me("End of this metering period; the close makes further charges unreachable")};for(let s of e.rates)o[s.field.name]=Z(`Per-unit price of ${s.meter.replaceAll("_"," ")} in ${r} minor units, committed at period open`);let a=[],c={close_period:{due:{field:e.closeByField,rule:n},from:["open"],summary:"Close the metering period; no further usage can be charged",to:"closed"},create:{summary:`Open a ${q(t).toLowerCase()} period with its committed rate card`,to:"open"}};for(let s of e.rates){let l=Y(`${t}_${s.meter}`);a.push(te({amount:`The committed ${s.field.name} per unit`,fromActor:e.payer,key:l,kind:"charge",occurrence:"repeatable",timing:"external_schedule",toActor:e.payee,trigger:`Charge one ${s.meter.replaceAll("_"," ")} at the committed rate`})),c[`charge_${s.meter}`]={from:["open"],moneyEvent:l,moves:[{key:"transfer",operation:"create",amount:s.field.name,from:e.payer,to:e.payee}],summary:`Charge one metered ${s.meter.replaceAll("_"," ")}; the emission is the transfer itself`,to:"open"}}return{design:[`${t}: committed rate card (${e.rates.map(s=>s.meter).join(", ")}); each usage charge IS the ledger transfer; period closes on ${e.closeByField}`],feeLines:[],moneyEvents:a,instrument:{actors:{[e.payer]:"payer",[e.payee]:"beneficiary"},desc:`Metered usage: the ${e.payer.replaceAll("_"," ")} is charged per unit at the committed rate card until the period closes on its stored end date`,fields:o,id:t,summary:`Metered charges from ${e.payer.replaceAll("_"," ")} on a committed rate card`,title:q(t),actions:c},rules:[{allowedActors:[],detail:"The period closes once from its stored end date",dueDriven:!0,enforcement:"platform",gatesEvent:null,key:n,kind:"deadline",label:"Period closed on its stored end date",tenantTunable:!1}],settlement:{name:t,pieces:[]}}}function Br(e){let t=e.name,n=e.amount.name,r=`${t}_payout`,o=e.shares.findIndex(k=>k.to===e.remainderTo),a=e.shares.map(k=>({bps:k.bps,field:`${de(k.to)}ShareAmount`,origin:k.origin,releaseTo:k.to})),c={[n]:Z(`The pooled period total in ${e.amount.currency} minor units; the share fields below partition it exactly`),[e.distributeDueField]:me("The period's payout date; the pool distributes from it")};for(let[k,T]of a.entries()){let R=k===Math.max(o,0)?" (carries the integer-division remainder)":"";c[T.field]=Z(`${le(T.bps)} of ${n}${R}: the ${T.releaseTo.replaceAll("_"," ")}'s share. Computed as floor(${n} * ${T.bps} / 10000) in ${e.amount.currency} minor units`)}let s=a.map((k,T)=>`fund_share_${T+1}`),l=a.map((k,T)=>`distribute_share_${T+1}`),u=Ie(s,"created","pooled","pooling"),f=Ie(l,"pooled","distributed","distributing"),v=[],x={create:{summary:`Open a ${q(t).toLowerCase()} period`,to:"created"}};for(let[k,T]of a.entries()){let R=`${t}_pool_${k+1}`;v.push(te({amount:`${le(T.bps)} of the ${n}`,fromActor:e.payer,key:R,kind:"charge",toActor:"escrow",trigger:`Pool the ${T.releaseTo.replaceAll("_"," ")}'s share for the period`})),x[s[k]]={from:[u[k]?.from],moneyEvent:R,moves:[{key:"transfer",operation:"create",amount:T.field,from:e.payer,to:"escrow"}],summary:`Pool share ${k+1} of the period total`,to:u[k]?.to}}for(let[k,T]of a.entries()){let R=`${t}_payout_${k+1}`;v.push(te({amount:`${le(T.bps)} of the ${n}`,fromActor:"escrow",key:R,kind:"payout",toActor:T.releaseTo,trigger:`Distribute the ${T.releaseTo.replaceAll("_"," ")}'s share on the payout date`})),x[l[k]]={due:{field:e.distributeDueField,rule:r},from:[f[k]?.from],moneyEvent:R,moves:[{key:"transfer",operation:"create",amount:T.field,from:"escrow",to:T.releaseTo}],summary:`Distribute the ${T.releaseTo.replaceAll("_"," ")}'s share of the pool`,to:f[k]?.to}}return{design:[`${t}: pool of ${n} partitioned ${a.map(k=>`${le(k.bps)} ${k.releaseTo}`).join(" + ")}; distributes in full on ${e.distributeDueField}; remainder to ${e.remainderTo}`],feeLines:[],moneyEvents:v,instrument:{actors:{[e.payer]:"payer",...Object.fromEntries(e.shares.map(k=>[k.to,"beneficiary"]))},desc:`Pooled split: the ${e.payer.replaceAll("_"," ")} pools the period's ${n} share by share; the pool distributes to every recipient in full on the stored payout date`,escrow:!0,fields:c,id:t,...Pe(Ae(n,a.map(k=>k.field))),summary:`Period pool from ${e.payer.replaceAll("_"," ")} split ${e.shares.length} ways`,title:q(t),actions:x},rules:[{allowedActors:[],detail:"Every share of the pool distributes once from the stored payout date",dueDriven:!0,enforcement:"platform",gatesEvent:null,key:r,kind:"deadline",label:"Pool distributed on its stored payout date",tenantTunable:!1}],settlement:{name:t,pieces:a}}}function ht(e){let t=Number(_n),n=e.carveTo??e.payee,r=[];e.payeeFeeBps<t&&r.push({end:t-e.payeeFeeBps,to:n}),e.payeeFeeBps>0&&r.push({end:t,to:"platform"});let o=[],a=0;for(let f of e.onCancel?.shares??[])a+=f.bps,o.push({end:a,origin:f.origin,to:f.to});let c=[...new Set([...r.map(f=>f.end),...o.map(f=>f.end),t])].sort((f,v)=>f-v),s=(f,v)=>f.find(x=>v<x.end),l=[],u=0;for(let f of c){if(f<=u)continue;let v=s(r,u),x=s(o,u);l.push({bps:f-u,...x?{cancelTo:x.to}:{},field:`piece${l.length+1}Amount`,origin:x?.origin??e.amount.origin,releaseTo:v?.to??n}),u=f}return l}function gt(e,t,n,r){let o=e.cancelTo?`; on cancellation to the ${e.cancelTo.replaceAll("_"," ")}`:"",a=t===0?" (carries the integer-division remainder)":"";return`${le(e.bps)} of ${n}${a}: released to the ${e.releaseTo.replaceAll("_"," ")}${o}. Computed as floor(${n} * ${e.bps} / 10000) in ${r} minor units`}function le(e){let t=e/100;return`${Number.isInteger(t)?t:t.toFixed(2).replace(/0$/,"")}%`}function Jr(e){let t=new Map(e.settlements.flatMap(r=>r.archetype==="advance"&&r.source.kind==="carve"?[[r.source.settlement,r.funder]]:[]));return`${e.settlements.map(r=>{switch(r.archetype){case"held_payment":{let o=r.onCancel?`; cancellation splits the held amount ${r.onCancel.shares.map(s=>`${le(s.bps)} to the ${s.to.replaceAll("_"," ")}`).join(" and ")}`:"",a=t.get(r.name),c=a?`the ${a.replaceAll("_"," ")} is paid on confirmed release, in the ${r.payee.replaceAll("_"," ")}'s place`:`the ${r.payee.replaceAll("_"," ")} is paid on confirmed release`;return`The ${r.payer.replaceAll("_"," ")} funds ${r.amount.name} into escrow and ${c}${o}`}case"captured_payment":return`The ${r.payer.replaceAll("_"," ")}'s ${r.amount.name} is reserved until ${r.reserveUntilField}, captured by the ${r.payee.replaceAll("_"," ")} in strict partial slices, then settled or released`;case"instant_transfer":return`The ${r.payer.replaceAll("_"," ")} pays ${r.amount.name} straight through to the ${r.payee.replaceAll("_"," ")}`;case"premium_forward":return`The ${r.payer.replaceAll("_"," ")}'s ${r.amount.name} forwards to the ${r.carrier.replaceAll("_"," ")} exactly once on binding`;case"deposit":return`The ${r.payer.replaceAll("_"," ")}'s ${r.amount.name} is reserved for the ${r.holder.replaceAll("_"," ")} until claimed or returned`;case"scheduled":return r.schedule.kind==="open"?r.mode==="obligation"?`The ${r.debtor.replaceAll("_"," ")} owes one ${r.amount.name} charge every ${r.schedule.every.raw} until the declared cancellation path closes the obligation`:"The open schedule is invalid without obligation mode":r.mode==="obligation"?`The ${r.debtor.replaceAll("_"," ")} owes ${r.amount.name}; ${r.advanceTo?`the ${r.payee.replaceAll("_"," ")} advances it to the ${r.advanceTo.replaceAll("_"," ")}, then `:""}the ${r.payer.replaceAll("_"," ")} repays the ${r.payee.replaceAll("_"," ")} over ${r.schedule.count} anchor-bound installments`:`The ${r.payer.replaceAll("_"," ")} pays ${r.amount.name} to the ${r.payee.replaceAll("_"," ")} over ${r.schedule.count} scheduled installments`;case"advance":return r.source.kind==="carve"?`The ${r.funder.replaceAll("_"," ")} advances ${r.amount.name} to the ${r.advanced.replaceAll("_"," ")}, repaid out of the ${r.source.settlement.replaceAll("_"," ")} release`:`The ${r.funder.replaceAll("_"," ")} advances ${r.amount.name} to the ${r.advanced.replaceAll("_"," ")}, repaid over ${r.source.schedule.count} anchors`;case"metered":return`The ${r.payer.replaceAll("_"," ")} is charged per metered unit at a committed rate card until the period closes`;case"pooled_split":return`The ${r.payer.replaceAll("_"," ")} pools ${r.amount.name} and it distributes ${r.shares.length} ways on the payout date`;case"settlement_batch":return`The ${r.settlementAccount.replaceAll("_"," ")} freezes capture lineage and pays one signed net amount to the ${r.payoutDestination.replaceAll("_"," ")}`;case"funding_round":return`The ${r.contributor.replaceAll("_"," ")} commits under ${r.target.name} until the stored close anchor activates or fails the round`;case"weighted_distribution":return`The ${r.source.replaceAll("_"," ")} pays a frozen claimant set by deterministic largest remainder`;case"credit_facility":return`The ${r.lender.replaceAll("_"," ")} admits draws under ${r.limit.name}; ${r.obligation.settlement.replaceAll("_"," ")} owns repayment`;case"recurring_collection":return`${r.name.replaceAll("_"," ")} adds explicit mandate evidence to ${r.obligation.settlement.replaceAll("_"," ")} repayment attempts`;case"conditional_disbursement":return`The ${r.source.replaceAll("_"," ")} pays one evidence-approved amount under ${r.cap.name} to the ${r.destination.replaceAll("_"," ")}`;case"rotating_pool":return`${r.members.length} fixed members contribute one exact amount per cycle in a stored payout order`;case"swap":return`The ${r.sides[0].party.replaceAll("_"," ")} and ${r.sides[1].party.replaceAll("_"," ")} fund one shared escrow and the entire two-sided trade releases or reverses together`}}).join(". ")}.`.slice(0,400)}function de(e){let[t,...n]=e.split("_");return(t??"")+n.map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join("")}function q(e){let t=e.replaceAll("_"," ");return t.charAt(0).toUpperCase()+t.slice(1)}var Mr=["asset","from","import","party","port","program","settlement"],$t=new Set(["{","}","(",")","[","]",":",",","=","|","."]),qr=new Set(Mr),Ur=e=>/[A-Za-z]/.test(e),Kr=e=>/[A-Za-z0-9_]/.test(e),on=e=>e>="0"&&e<="9";function bt(e){let t=[],n=[],r=0,o=(a,c,s,l=s)=>{t.push({kind:a,span:{end:r,start:c},text:s,value:l})};for(;r<e.length;){let a=e[r];if(a===" "||a===" "||a==="\r"||a===`
3
3
  `){r+=1;continue}if(a==="/"&&e[r+1]==="/"){for(;r<e.length&&e[r]!==`
4
4
  `;)r+=1;continue}if($t.has(a)){let s=r;r+=1,o("punct",s,a);continue}if(a==='"'){let s=r;r+=1;let l="",u=!1;for(;r<e.length;){let f=e[r];if(f==='"'){r+=1,u=!0;break}if(f===`
5
5
  `)break;l+=f,r+=1}u||n.push({message:"this string never closes; add the ending double quote",span:{end:r,start:s}}),o("string",s,e.slice(s,r),l);continue}if(on(a)){let s=r;for(;r<e.length&&on(e[r]);)r+=1;if(e[r]==="."&&on(e[r+1]??""))for(r+=1;r<e.length&&on(e[r]);)r+=1;let l=e.slice(s,r);e[r]==="%"?(r+=1,o("percent",s,e.slice(s,r),l)):o("number",s,l,l);continue}if(Ur(a)){let s=r;for(;r<e.length&&Kr(e[r]);)r+=1;let l=e.slice(s,r);o(qr.has(l)?"keyword":"ident",s,l);continue}let c=r;for(;r<e.length&&!/[\sA-Za-z0-9_"]/.test(e[r])&&!$t.has(e[r])&&!(e[r]==="/"&&e[r+1]==="/");)r+=1;r===c&&(r+=1),n.push({message:`"${e.slice(c,r)}" is not part of the HSX language`,span:{end:r,start:c}})}return t.push({kind:"eof",span:{end:e.length,start:e.length},text:"",value:""}),{diagnostics:n,tokens:t}}var Me=Object.freeze({maxNestingDepth:64,maxSourceBytes:262144});function wt(e){let t=new TextEncoder().encode(e).byteLength;if(t>Me.maxSourceBytes)return{diagnostics:[{message:`this file is ${t} bytes; HSX reads at most ${Me.maxSourceBytes}`,span:{end:0,start:0}}],program:{decls:[],span:{end:0,start:0}}};let n=bt(e),r=new In(n.tokens,[...n.diagnostics]),o=r.parseProgram(e.length);return{diagnostics:r.diagnostics,program:o}}var In=class{diagnostics;tokens;index=0;depth=0;constructor(t,n){this.tokens=t,this.diagnostics=n}parseProgram(t){let n=[];for(;!this.at("eof");){let r=this.parseDecl();if(r){n.push(r);continue}this.recoverToDecl()}return{decls:n,span:{end:t,start:0}}}parseDecl(){let t=this.peek();if(t.kind!=="keyword"||t.text==="from"){this.error(t.span,t.kind==="eof"?"the program ends unexpectedly":`expected a declaration (program, import, party, asset, settlement, or port), found "${t.text}"`);return}switch(t.text){case"program":return this.parseProgramDecl();case"import":return this.parseImportDecl();case"party":return this.parsePartyDecl();case"asset":return this.parseAssetDecl();case"settlement":return this.parseSettlementDecl();case"port":return this.parsePortDecl();default:this.error(t.span,`"${t.text}" cannot start a declaration`),this.advance();return}}parseProgramDecl(){let t=this.advance(),n=this.expectIdent("the program needs a snake_case name");if(!n)return;let r;if(this.at("string")){let o=this.advance();r={kind:"string",span:o.span,value:o.value}}return{kind:"program",name:n,span:this.spanFrom(t.span),...r?{title:r}:{}}}parseImportDecl(){let t=this.advance();if(!this.expectPunct("{",'import lists its names in braces: import { held_payment } from "settlement"'))return;let n=[];for(;!this.atPunct("}")&&!this.at("eof");){let o=this.expectIdent("expected an imported name");if(!o)return;n.push(o),this.atPunct(",")&&this.advance()}if(!this.expectPunct("}","the import name list never closes"))return;if(!this.at("keyword")||this.peek().text!=="from"){this.error(this.peek().span,'import needs from: import { held_payment } from "settlement"');return}if(this.advance(),!this.at("string")){this.error(this.peek().span,'the import source must be a quoted module name like "settlement"');return}let r=this.advance();return n.length===0&&this.error(t.span,"import brings in at least one name"),{from:{kind:"string",span:r.span,value:r.value},kind:"import",names:n,span:this.spanFrom(t.span)}}parsePartyDecl(){let t=this.advance(),n=this.expectIdent("the party needs a name, like: party buyer: person");if(!n||!this.expectPunct(":",`party ${n.name} needs a kind, like: party ${n.name}: person`))return;let r=this.expectIdent(`expected a kind for party ${n.name}`);if(!r)return;let o=this.atPunct("{")?this.parseBlock():void 0;return{...o?{attrs:o}:{},kind:"party",name:n,partyKind:r,span:this.spanFrom(t.span)}}parseAssetDecl(){let t=this.advance(),n=this.expectIdent("the asset needs a name, like: asset vehicle: good");if(!n||!this.expectPunct(":",`asset ${n.name} needs a kind, like: asset ${n.name}: good`))return;let r=this.expectIdent(`expected a kind for asset ${n.name}`);if(!r)return;let o=this.atPunct("{")?this.parseBlock():void 0;return{assetKind:r,...o?{attrs:o}:{},kind:"asset",name:n,span:this.spanFrom(t.span)}}parseSettlementDecl(){let t=this.advance(),n=this.expectIdent("the settlement needs a name, like: settlement sale = held_payment { ... }");if(!n||!this.expectPunct("=",`settlement ${n.name} instantiates an archetype: settlement ${n.name} = held_payment { ... }`))return;let r=this.expectIdent(`expected an archetype name for settlement ${n.name}`);if(!r)return;if(!this.atPunct("{")){this.error(this.peek().span,`settlement ${n.name} needs a body in braces`);return}let o=this.parseBlock();if(o)return{archetype:r,body:o,kind:"settlement",name:n,span:this.spanFrom(t.span)}}parsePortDecl(){let t=this.advance(),n=this.expectIdent("the port needs a name, like: port confirm_handover { ... }");if(!n)return;if(!this.atPunct("{")){this.error(this.peek().span,`port ${n.name} needs a body in braces`);return}let r=this.parseBlock();if(r)return{body:r,kind:"port",name:n,span:this.spanFrom(t.span)}}enterNesting(t){return this.depth>=Me.maxNestingDepth?(this.error(t,`this nests past the parser's depth budget of ${Me.maxNestingDepth}; flatten it`),!1):(this.depth+=1,!0)}parseBlock(){if(!this.enterNesting(this.peek().span))return;let t=this.parseBlockUnguarded();return this.depth-=1,t}parseBlockUnguarded(){let t=this.advance(),n=[];for(;!this.atPunct("}")&&!this.at("eof");){let r=this.index,o=this.parseEntry();if(!o){this.recoverInBlock(),this.index===r&&this.advance();continue}n.push(o),this.atPunct(",")&&this.advance()}return this.expectPunct("}","this block never closes; add the matching }")?{entries:n,kind:"block",span:this.spanFrom(t.span)}:{entries:n,kind:"block",span:this.spanFrom(t.span)}}parseEntry(){let t=this.peek().kind==="keyword"&&this.peek().text==="from"?this.parseIdent():this.expectIdent("expected an entry name here");if(!t)return;let n=[];if(this.atPunct("(")){for(this.advance();!this.atPunct(")")&&!this.at("eof");){let o=this.expectIdent(`expected a qualifier inside ${t.name}( ... )`);if(!o)return;n.push(o),this.atPunct(",")&&this.advance()}if(!this.expectPunct(")",`${t.name}( ... ) never closes`))return}let r;if(this.atPunct("{"))r=this.parseBlock();else if(this.atPunct(":"))this.advance(),r=this.parseExpr();else{this.error(this.peek().span,`entry ${t.name} needs a value: either "${t.name}: <value>" or "${t.name} { ... }"`);return}if(r)return{key:t,qualifiers:n,span:{end:r.span.end,start:t.span.start},value:r}}parseExpr(){if(!this.enterNesting(this.peek().span))return;let t=this.parseExprUnguarded();return this.depth-=1,t}parseExprUnguarded(){let t=this.peek();if(t.kind==="string")return this.advance(),{kind:"string",span:t.span,value:t.value};if(t.kind==="number")return this.advance(),{kind:"number",raw:t.value,span:t.span};if(t.kind==="percent"){this.advance();let n=Hr(t.value);return n===void 0?(this.error(t.span,`${t.text} is finer than the money system can settle; percents go down to a hundredth (basis point), like 99.75%`),{bps:0,kind:"percent",raw:t.value,span:t.span}):{bps:n,kind:"percent",raw:t.value,span:t.span}}if(this.atPunct("[")){let n=this.advance(),r=[];for(;!this.atPunct("]")&&!this.at("eof");){let o=this.parseExpr();if(!o)return;r.push(o),this.atPunct(",")&&this.advance()}return this.expectPunct("]","this list never closes; add the matching ]")?{items:r,kind:"list",span:this.spanFrom(n.span)}:void 0}if(this.atPunct("{"))return this.parseBlock();if(t.kind==="keyword"&&t.text==="port"){let n=this.advance(),r=this.expectIdent("expected a port name after the port keyword");if(!r)return;let o;if(this.at("ident")&&this.peek().text==="within"&&(this.advance(),o=this.expectIdent("expected a fixed duration after within, like P14D"),!o))return;let a;if(this.atPunct("|")){if(this.advance(),!this.at("ident")||this.peek().text!=="at"){this.error(this.peek().span,"after | comes the date the platform decides on, like: | at(releaseDueAt)");return}if(this.advance(),!this.expectPunct("(","at names its date field in parentheses: at(releaseDueAt)")||(a=this.expectIdent("expected a stored date field inside at( ... ), like at(releaseDueAt)"),!a)||!this.expectPunct(")","at( ... ) never closes"))return}return{...a?{deadline:a}:{},kind:"port_ref",name:r,span:this.spanFrom(n.span),...o?{within:o}:{}}}if(t.kind==="ident"){let n=this.parseIdent();if(n.name==="decided"&&this.atPunct("{")){let r=this.parseBlock();return r?{body:r,kind:"decided_amount",span:{end:r.span.end,start:n.span.start}}:void 0}if(this.atPunct(".")){this.advance();let r=this.expectIdent(`expected the exit after ${n.name}., like ${n.name}.release`);return r?{kind:"settlement_ref",member:r,owner:n,span:{end:r.span.end,start:n.span.start}}:void 0}if(this.atPunct("(")){this.advance();let r=[];for(;!this.atPunct(")")&&!this.at("eof");){let o=this.parseExpr();if(!o)return;r.push(o),this.atPunct(",")&&this.advance()}return this.expectPunct(")",`${n.name}( ... ) never closes`)?{args:r,callee:n,kind:"call",span:this.spanFrom(n.span)}:void 0}if(this.atPunct(":")){this.advance();let r=this.parseExpr();return r?{kind:"binding",name:n,span:{end:r.span.end,start:n.span.start},type:r}:void 0}return n}this.error(t.span,t.kind==="eof"?"the program ends where a value was expected":`"${t.text}" is not a value HSX understands here`)}recoverToDecl(){for(;!this.at("eof");){let t=this.peek();if(t.kind==="keyword"&&t.text!=="from")return;this.advance()}}recoverInBlock(){let t=0;for(;!this.at("eof");){let n=this.peek();if(n.kind==="punct"){if((n.text==="{"||n.text==="["||n.text==="(")&&(t+=1),n.text==="}"||n.text==="]"||n.text===")"){if(t===0)return;t-=1}if(n.text===","&&t===0){this.advance();return}}if(n.kind==="keyword"&&t===0)return;this.advance()}}peek(){return this.tokens[this.index]}previous(){return this.tokens[Math.max(0,this.index-1)]}advance(){let t=this.peek();return t.kind!=="eof"&&(this.index+=1),t}at(t){return this.peek().kind===t}atPunct(t){let n=this.peek();return n.kind==="punct"&&n.text===t}parseIdent(){let t=this.advance();return{kind:"ident",name:t.text,span:t.span}}expectIdent(t){if(this.at("ident"))return this.parseIdent();this.error(this.peek().span,t)}expectPunct(t,n){return this.atPunct(t)?(this.advance(),!0):(this.error(this.peek().span,n),!1)}spanFrom(t){return{end:this.previous().span.end,start:t.start}}error(t,n){this.diagnostics.push({message:n,span:t})}};function Hr(e){let[t="0",n=""]=e.split(".");if(n.length>2)return;let r=n.padEnd(2,"0");return Number(t)*100+Number(r===""?"0":r)}function an(e){let t=[],n=at(e),r=zr(e),o=(u,f,v,x)=>{let k=kn(n,x);t.push({column:k.column,line:k.line,message:v,severity:f,stage:u})},a=wt(e);for(let u of a.diagnostics)o("parse","error",u.message,u.span.start);if(a.diagnostics.length>0)return{diagnostics:t,verdict:"invalid"};let c=ot(a.program);for(let u of c.diagnostics)o("check",u.severity,u.message,u.span.start);if(!c.program)return{diagnostics:t,verdict:"invalid"};let s=mt(c.program);if(!s.ok){for(let u of s.issues)o("lower","error",u.message,u.span.start);return{diagnostics:t,verdict:"invalid"}}let l=u=>{let f=kn(n,u.span.start);return{path:u.path,span:{column:f.column,end:r[u.span.end]??r[r.length-1],line:f.line,start:r[u.span.start]??0}}};return{artifacts:{document:s.value.document,frame:s.value.frame,originMap:s.value.originMap.map(l)},diagnostics:t,verdict:t.length>0?"warning":"valid"}}function zr(e){let t=new Uint32Array(e.length+1),n=0;for(let r=0;r<e.length;r+=1){t[r]=n;let o=e.codePointAt(r);o>65535?(t[r+1]=n,n+=4,r+=1):o>2047?n+=3:o>127?n+=2:n+=1}return t[e.length]=n,t}import{spawn as Ct}from"node:child_process";import{createHash as Yr}from"node:crypto";import{createServer as Wr}from"node:http";import{createInterface as Vr}from"node:readline/promises";import{chmod as Pn,mkdir as Gr,readdir as Xr,readFile as ln,rename as Zr,unlink as Qr,writeFile as eo}from"node:fs/promises";import{homedir as no}from"node:os";import{basename as to,dirname as Rn,join as un}from"node:path";var Jn="https://hyperscale0.ai",Mn="sandbox",qn="hyperscale-cli-session",ro="/v1/personal-access-tokens/current",Fn=process.platform==="darwin"?"/usr/bin/security":null,oo="config.json",On="https://hyperscale0.ai/desk/security/tokens",Ue="https://hyperscale0.ai/request-access",Ke=`Mint a founder PAT in the portal at ${On}. Open Security, then Personal access tokens.`,ao=`Not logged in. Run "hyperscale auth login" to open portal sign-in. In a headless environment, ${Ke} Then set HYPERSCALE_TOKEN or pass --token. Unapproved founders can request access at ${Ue}.`,io=`Run "hyperscale auth login". For headless use, ${Ke} Unapproved founders can request access at ${Ue}.`,Dn=3e4,so=2e3,co=120*1e3,lo=/^prd_(sandbox|live)_[a-z0-9]{8,64}$/,uo=`hyperscale <command> [options]
@@ -93,37 +93,37 @@ Examples:
93
93
  hyperscale call account.list --input-file input.json
94
94
  printf '{"limit":5}' | hyperscale call account.list
95
95
  hyperscale call account.retrieve --input '{"accountId":"acct_sandbox_..."}'
96
- `,vt={start:{usage:"start [--blueprint <slug>] [--name <name>] [--json]",summary:"Choose a catalog company, create its Product, and run its first published runnable journey step.",options:["--blueprint <slug> Skip the prompt and choose this catalog Blueprint.","--name <name> Product name. Defaults to the selected Blueprint name.","--json Print one machine document, including the one-time API key under shown_once."],notes:["The command requires an active founder login.","Without --blueprint, start requires an interactive terminal and asks which company to build.","Scripts and agents must pass --blueprint <slug>.","Machine output returns the Product API key only under shown_once.","A Blueprint without a published runnable journey stops after composition and names the next command."],example:"hyperscale start --blueprint vehicle-escrow-marketplace --json"},"auth login":{usage:"auth login [--no-browser] [--token <pat>]",summary:"Sign in through the portal callback or save a founder PAT.",options:["--no-browser Skip the portal callback. Print where to mint a PAT when no token is set.","--token <pat> Founder PAT. Defaults to HYPERSCALE_TOKEN.","--json Print the saved session summary as one JSON document."],notes:["Without a PAT, the CLI opens portal sign-in and accepts one localhost callback.","Headless environments should pass --no-browser and set HYPERSCALE_TOKEN or --token to a portal-minted founder PAT.","Set HYPERSCALE_CREDENTIAL_STORE=file to use the 0600 profile file instead of macOS Keychain."],example:"hyperscale auth login --no-browser"},"auth status":{usage:"auth status [--json]",summary:"Verify and show the active founder PAT and selected Product.",options:["--json Print machine-readable JSON."],example:"hyperscale auth status --json"},"auth logout":{usage:"auth logout [--revoke] [--json]",summary:"Forget the local founder PAT. Optionally revoke it first.",options:["--revoke Revoke the PAT before deleting local state.","--json Print machine-readable JSON."],example:"hyperscale auth logout --revoke"},"blueprint list":{usage:"blueprint list [--json]",summary:"List public Blueprints without authentication.",options:["--json Print the complete collection as JSON."],example:"hyperscale blueprint list"},"blueprint show":{usage:"blueprint show <id> [--json]",summary:"Show one public Blueprint.",options:["--json Print the complete Blueprint as JSON."],example:"hyperscale blueprint show luxury-goods-consignment-escrow"},"product create":{usage:"product create --blueprint <id> --name <name> [--json]",summary:"Create and select a Product. The command refuses a duplicate name.",options:["--blueprint <id> Required Blueprint id.","--name <name> Required Product name.","--json Print the creation summary as JSON."],example:'hyperscale product create --blueprint luxury-goods-consignment-escrow --name "Luxury Consignment"'},"product list":{usage:"product list [--json]",summary:"List Products in the signed-in company.",options:["--json Print the complete collection as JSON."],example:"hyperscale product list"},"product show":{usage:"product show [id] [--json]",summary:"Show a Product summary, or the complete Product document as JSON.",options:["--json Print the complete Product document."],example:"hyperscale product show prd_sandbox_..."},"product select":{usage:"product select <id> [--json]",summary:"Verify a Product and save it as the default for later commands.",options:["--token <pat> Founder PAT. Defaults to HYPERSCALE_TOKEN or the stored login.","--base-url <url> API origin. Defaults to the active founder profile.","--environment <name> sandbox or live. Defaults to the active founder profile.","--json Print the selected Product id as JSON."],notes:["The CLI stores the selection in the active founder profile.","Product show, compose plan/apply, and key commands use it when --product is absent.","Product create and start select the Product they create."],example:"hyperscale product select prd_sandbox_..."},"product actions":{usage:"product actions [operation-id] [--product <id>] [--json]",summary:"List frozen public actions or show one action's full schemas.",options:["--product <id> Product to inspect. Defaults to the selected Product.","--api-key <key> Product API key. Defaults to HYPERSCALE_API_KEY.","--json Print machine-readable JSON."],notes:["Setup operation details include the public input schema used by hyperscale call.","When that schema has no required fields, omit --input or pass {}."],example:"hyperscale product actions escrow_order.placeBuyerHold --json"},"product run":{usage:"product run <operation-id> [--input <json> | --input-file <path>] [--idempotency-key <key>] [--json]",summary:"Run one frozen public action with a Product API key.",options:["--input <json> JSON input object. Stdin is used when piped.","--input-file <path> Read the JSON input object from a file.","--product <id> Product to call. Defaults to the selected Product.","--api-key <key> Product API key. Defaults to HYPERSCALE_API_KEY.","--idempotency-key <key> Send this exact Idempotency-Key header. The default is a generated UUID.","--json Print the key, receipt ids, and output as JSON."],notes:["Reuse an Idempotency-Key only with the same operation and input.",'If a bounded validation value appears as "[Truncated]", run "hyperscale product actions <operation-id>" for the full input schema.'],example:`hyperscale product run escrow_order.placeBuyerHold --input '{"escrowOrderId":"eord_sandbox_..."}' --idempotency-key hold-001`},"compose check":{usage:"compose check <file.hsx> [--json]",summary:"Compile and check an HSX program.",options:["--json Print diagnostics and the verdict as JSON."],example:"hyperscale compose check product.hsx"},"compose plan":{usage:"compose plan <file.hsx> [--product <id>] [--json]",summary:"Diff an HSX program against a Product.",options:["--product <id> Product to compare. Defaults to the selected Product.","--json Print the plan as JSON."],example:"hyperscale compose plan product.hsx --json"},"compose apply":{usage:"compose apply <file.hsx> (--confirm | --yes) [--product <id>] [--json]",summary:"Recompose a Product from checked HSX.",options:["--confirm Confirm the mutation for a person.","--yes Confirm the mutation without a prompt for an agent.","--product <id> Product to recompose. Defaults to the selected Product.","--json Print the result as JSON."],example:"hyperscale compose apply product.hsx --yes"},"key create":{usage:"key create [--name <name>] [--product <id>] [--json]",summary:"Create a sandbox Product API key.",options:["--name <name> Key name. Defaults to Founder CLI.","--product <id> Product for the key. Defaults to the selected Product.","--json Print the one-time secret and key metadata as JSON."],example:'hyperscale key create --name "Founder laptop"'},"key list":{usage:"key list [--product <id>] [--json]",summary:"List keys for one Product.",options:["--product <id> Product to inspect. Defaults to the selected Product.","--json Print the collection as JSON."],example:"hyperscale key list --json"},"key revoke":{usage:"key revoke <id> [--product <id>] [--json]",summary:"Revoke one Product API key.",options:["--product <id> Product that owns the key. Defaults to the selected Product.","--json Print the result as JSON."],example:"hyperscale key revoke key_sandbox_..."},"team list":{usage:"team list [--json]",summary:"List company members and pending invitations.",options:["--json Print machine-readable JSON."],example:"hyperscale team list"},"team invite":{usage:"team invite --email <email> --role <role> [--json]",summary:"Invite a company member.",options:["--email <email> Required invitee email.","--role <role> Required seeded role or custom role id.","--json Print the invitation and one-time token as JSON."],example:"hyperscale team invite --email developer@example.com --role developer"},"activity list":{usage:"activity list [--json]",summary:"List company activity with timestamps and resource targets.",options:["--json Print the complete collection as JSON."],example:"hyperscale activity list"},whoami:{usage:"whoami [--json]",summary:"Show the user and company the founder PAT resolves to.",options:["--json Print machine-readable JSON."],example:"hyperscale whoami --json"},"ops list":{usage:"ops list [filter] [--product <id>] [--json]",summary:"List callable operations from the Product machine document.",options:["--product <id> Product to inspect. The Product API key must belong to it.","--api-key <key> Product API key. Defaults to HYPERSCALE_API_KEY.","--json Print matching operations as JSON."],example:"hyperscale ops list account"},call:{usage:"call <operation> [--input <json> | --input-file <path>] [--idempotency-key <key>] [--product <id>]",summary:"Call one operation from the Product machine document.",options:["--input <json> JSON input object. Stdin is used when piped.","--input-file <path> Read the JSON input object from a file.","--product <id> Product to call. The Product API key must belong to it.","--api-key <key> Product API key. Defaults to HYPERSCALE_API_KEY.","--idempotency-key <key> Send this exact Idempotency-Key header for a mutation. The default is a generated UUID."],notes:["Reuse an Idempotency-Key only with the same operation and input."],example:`hyperscale call account.create --input '{"currency":"SAR"}'`}};function po(e){let n=Object.keys(vt).sort((o,a)=>a.split(" ").length-o.split(" ").length).find(o=>o.split(" ").every((c,s)=>e[s]===c));if(!n)throw new S(`No help for ${e.join(" ")}. Run "hyperscale --help" to list commands.`);let r=vt[n];return[`Usage: hyperscale ${r.usage}`,"",r.summary,"","Options:",...r.options.map(o=>` ${o}`),...r.notes?["","Notes:",...r.notes.map(o=>` ${o}`)]:[],"","Example:",` ${r.example}`,""].join(`
97
- `)}var S=class extends Error{constructor(t,n={}){super(t),typeof n.code=="string"&&(this.code=n.code),n.details!==void 0&&(this.details=n.details),Number.isInteger(n.exitCode)&&(this.exitCode=n.exitCode),typeof n.fix=="string"&&(this.fix=n.fix)}},He=class extends S{constructor(t,{requestId:n,status:r}){super(t),this.requestId=n,this.status=r}};function Cn(){return new S(ao,{fix:io})}function Et(e){let t=e??"<id>";return new S(`This command needs a Product API key. Create one with "hyperscale key create --name 'Founder CLI' --product ${t}", then set HYPERSCALE_API_KEY or pass --api-key.`)}var ze=class extends S{constructor(t,n){super(t),this.code="check_failed",this.details=n,this.exitCode=2}},mo=new Set(["--api-key","--base-url","--blueprint","--environment","--email","--idempotency-key","--input","--input-file","--name","--product","--role","--token"]);function fo(e){let t=[],n={};for(let r=0;r<e.length;r+=1){let o=e[r];if(!o.startsWith("--")){t.push(o);continue}if(mo.has(o)){let a=e[r+1];if(a===void 0)throw new S(`${o} needs a value`);n[o]=a,r+=1;continue}if(o==="--help"||o==="--version"||o==="--json"||o==="--confirm"||o==="--yes"||o==="--no-browser"||o==="--passkey"||o==="--revoke"){n[o]=!0;continue}throw new S(`Unknown option: ${o}`)}return{flags:n,positional:t}}function kt(e,t){let n=e["--api-key"]??t.HYPERSCALE_API_KEY;if(!n)throw Et();let r=e["--environment"]??t.HYPERSCALE_ENVIRONMENT??Mn;if(r!=="sandbox"&&r!=="live")throw new S(`Unknown environment: ${r}. Use sandbox or live.`);let o=(e["--base-url"]??t.HYPERSCALE_BASE_URL??Jn).replace(/\/+$/,"");return{apiKey:n,baseUrl:o,environment:r}}function Ye(e,t,n={}){let r=e["--environment"]??t.HYPERSCALE_ENVIRONMENT??n.environment??Mn;if(r!=="sandbox"&&r!=="live")throw new S(`Unknown environment: ${r}. Use sandbox or live.`);let o=(e["--base-url"]??t.HYPERSCALE_BASE_URL??n.baseUrl??Jn).replace(/\/+$/,""),a;try{a=new URL(o)}catch{a=null}let c=a?.origin??null;if(!c||c!==o)throw new S(`Invalid API origin: ${o}. Use an origin such as https://hyperscale0.ai.`);let s=["localhost","127.0.0.1","[::1]","::1"].includes(a.hostname);if(a.protocol!=="https:"&&!(a.protocol==="http:"&&s))throw new S(`Refusing cleartext API origin ${o}. Use HTTPS unless the API runs on loopback.`);return{baseUrl:o,environment:r}}function Tt(e){return e.HYPERSCALE_CONFIG_DIR??un(no(),".config","hyperscale")}function Rt(e){return un(Tt(e),oo)}function we(e,t){return un(Tt(t),`session-${Ve(e)}.json`)}function pn(e){let t=e.HYPERSCALE_CREDENTIAL_STORE??"auto";if(t==="auto"||t==="file")return t;throw new S(`Unknown HYPERSCALE_CREDENTIAL_STORE value: ${t}. Use auto or file.`)}async function Un(e,t){let n=we(e,t),r=`${to(n)}.`,o;try{o=await Xr(Rn(n),{withFileTypes:!0})}catch(a){if(a&&a.code==="ENOENT")return;throw a}for(let a of o){if(!a.isFile()||!a.name.startsWith(r))continue;let c=a.name.slice(r.length);/^\d+\.[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.tmp$/.test(c)&&await We(un(Rn(n),a.name))}}async function yo(e){try{return JSON.parse(await ln(e,"utf8"))}catch(t){if(t&&t.code==="ENOENT")return null;throw t instanceof SyntaxError?new S(`${e} is not valid JSON`):t}}async function qe(e,t){let n=ho(e);await Gr(n,{mode:448,recursive:!0}),await Pn(n,448);let r=`${e}.${process.pid}.${globalThis.crypto.randomUUID()}.tmp`;await eo(r,t,{flag:"wx",mode:384}),await Pn(r,384);try{await Zr(r,e),await Pn(e,384)}catch(o){throw await We(r),o}}function ho(e){return Rn(e)}async function We(e){try{await Qr(e)}catch(t){if(!t||t.code!=="ENOENT")throw t}}function go(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new S(`${t} does not contain a CLI profile`);let{baseUrl:n,email:r,environment:o,selectedProduct:a}=e;if(typeof n!="string"||typeof r!="string"||o!=="sandbox"&&o!=="live"||!(a===null||typeof a=="string"))throw new S(`${t} does not contain a valid CLI profile`);return{baseUrl:n,email:r,environment:o,selectedProduct:a}}async function mn(e){let t=Rt(e),n=await yo(t);return n===null?null:go(n,t)}async function fn(e,t){let n={email:t.email,baseUrl:t.baseUrl,environment:t.environment,selectedProduct:t.selectedProduct??null};await qe(Rt(e),`${JSON.stringify(n,null,2)}
96
+ `,vt={start:{usage:"start [--blueprint <slug>] [--name <name>] [--json]",summary:"Choose a catalog company, create its Product, and run its first published runnable journey step.",options:["--blueprint <slug> Skip the prompt and choose this catalog Blueprint.","--name <name> Product name. Defaults to the selected Blueprint name.","--json Print one machine document, including the one-time API key under shown_once."],notes:["The command requires an active founder login.","Without --blueprint, start requires an interactive terminal and asks which company to build.","Scripts and agents must pass --blueprint <slug>.","Machine output returns the Product API key only under shown_once.","A Blueprint without a published runnable journey stops after composition and names the next command."],example:"hyperscale start --blueprint vehicle-escrow-marketplace --json"},"auth login":{usage:"auth login [--no-browser] [--token <pat>]",summary:"Sign in through the portal callback or save a founder PAT.",options:["--no-browser Skip the portal callback. Print where to mint a PAT when no token is set.","--token <pat> Founder PAT. Defaults to HYPERSCALE_TOKEN.","--json Print the saved session summary as one JSON document."],notes:["Without a PAT, the CLI opens portal sign-in and accepts one localhost callback.","Headless environments should pass --no-browser and set HYPERSCALE_TOKEN or --token to a portal-minted founder PAT.","Set HYPERSCALE_CREDENTIAL_STORE=file to use the 0600 profile file instead of macOS Keychain."],example:"hyperscale auth login --no-browser"},"auth status":{usage:"auth status [--json]",summary:"Verify and show the active founder PAT and selected Product.",options:["--json Print machine-readable JSON."],example:"hyperscale auth status --json"},"auth logout":{usage:"auth logout [--revoke] [--json]",summary:"Forget the local founder PAT. Optionally revoke it first.",options:["--revoke Revoke the PAT before deleting local state.","--json Print machine-readable JSON."],example:"hyperscale auth logout --revoke"},"blueprint list":{usage:"blueprint list [--json]",summary:"List public Blueprints without authentication.",options:["--json Print the complete collection as JSON."],example:"hyperscale blueprint list"},"blueprint show":{usage:"blueprint show <id> [--json]",summary:"Show one public Blueprint.",options:["--json Print the complete Blueprint as JSON."],example:"hyperscale blueprint show luxury-goods-consignment-escrow"},"product create":{usage:"product create --blueprint <id> --name <name> [--json]",summary:"Create and select a Product. The command refuses a duplicate name.",options:["--blueprint <id> Required Blueprint id.","--name <name> Required Product name.","--json Print the creation summary as JSON."],example:'hyperscale product create --blueprint luxury-goods-consignment-escrow --name "Luxury Consignment"'},"product list":{usage:"product list [--json]",summary:"List Products in the signed-in company.",options:["--json Print the complete collection as JSON."],example:"hyperscale product list"},"product show":{usage:"product show [id] [--json]",summary:"Show a Product summary, or the complete Product document as JSON.",options:["--json Print the complete Product document."],example:"hyperscale product show prd_sandbox_..."},"product select":{usage:"product select <id> [--json]",summary:"Verify a Product and save it as the default for later commands.",options:["--token <pat> Founder PAT. Defaults to HYPERSCALE_TOKEN or the stored login.","--base-url <url> API origin. Defaults to the active founder profile.","--environment <name> sandbox or live. Defaults to the active founder profile.","--json Print the selected Product id as JSON."],notes:["The CLI stores the selection in the active founder profile.","Product show, compose plan/apply, and key commands use it when --product is absent.","Product create and start select the Product they create."],example:"hyperscale product select prd_sandbox_..."},"product actions":{usage:"product actions [operation-id] [--product <id>] [--json]",summary:"List frozen public actions or show one action's full schemas.",options:["--product <id> Product to inspect. Defaults to the selected Product.","--api-key <key> Product API key. Defaults to HYPERSCALE_API_KEY.","--json Print machine-readable JSON."],notes:["Setup operation details include the public input schema used by hyperscale call.","When that schema has no required fields, omit --input or pass {}."],example:"hyperscale product actions escrow_order.placeBuyerHold --json"},"product run":{usage:"product run <operation-id> [--input <json> | --input-file <path>] [--idempotency-key <key>] [--json]",summary:"Run one frozen public action with a Product API key.",options:["--input <json> JSON input object. Stdin is used when piped.","--input-file <path> Read the JSON input object from a file.","--product <id> Product to call. Defaults to the selected Product.","--api-key <key> Product API key. Defaults to HYPERSCALE_API_KEY.","--idempotency-key <key> Send this exact Idempotency-Key header. The default is a generated UUID.","--json Print the key, receipt ids, and output as JSON."],notes:["Reuse an Idempotency-Key only with the same operation and input.",'If a bounded validation value appears as "[Truncated]", run "hyperscale product actions <operation-id>" for the full input schema.'],example:`hyperscale product run escrow_order.placeBuyerHold --input '{"escrowOrderId":"eord_sandbox_..."}' --idempotency-key hold-001`},"compose check":{usage:"compose check <file.hsx> [--json]",summary:"Compile and check an HSX program.",options:["--json Print diagnostics and the verdict as JSON."],example:"hyperscale compose check product.hsx"},"compose plan":{usage:"compose plan <file.hsx> [--product <id>] [--json]",summary:"Diff an HSX program against a Product.",options:["--product <id> Product to compare. Defaults to the selected Product.","--json Print the plan as JSON."],example:"hyperscale compose plan product.hsx --json"},"compose apply":{usage:"compose apply <file.hsx> (--confirm | --yes) [--product <id>] [--json]",summary:"Recompose a Product from checked HSX.",options:["--confirm Confirm the mutation for a person.","--yes Confirm the mutation without a prompt for an agent.","--product <id> Product to recompose. Defaults to the selected Product.","--json Print the result as JSON."],example:"hyperscale compose apply product.hsx --yes"},"key create":{usage:"key create [--name <name>] [--product <id>] [--json]",summary:"Create a sandbox Product API key.",options:["--name <name> Key name. Defaults to Founder CLI.","--product <id> Product for the key. Defaults to the selected Product.","--json Print the one-time secret and key metadata as JSON."],example:'hyperscale key create --name "Founder laptop"'},"key list":{usage:"key list [--product <id>] [--json]",summary:"List keys for one Product.",options:["--product <id> Product to inspect. Defaults to the selected Product.","--json Print the collection as JSON."],example:"hyperscale key list --json"},"key revoke":{usage:"key revoke <id> [--product <id>] [--json]",summary:"Revoke one Product API key.",options:["--product <id> Product that owns the key. Defaults to the selected Product.","--json Print the result as JSON."],example:"hyperscale key revoke key_sandbox_..."},"team list":{usage:"team list [--json]",summary:"List company members and pending invitations.",options:["--json Print machine-readable JSON."],example:"hyperscale team list"},"team invite":{usage:"team invite --email <email> --role <role> [--json]",summary:"Invite a company member.",options:["--email <email> Required invitee email.","--role <role> Required seeded role or custom role id.","--json Print the invitation and one-time token as JSON."],example:"hyperscale team invite --email developer@example.com --role developer"},"activity list":{usage:"activity list [--json]",summary:"List company activity with timestamps and resource targets.",options:["--json Print the complete collection as JSON."],example:"hyperscale activity list"},whoami:{usage:"whoami [--json]",summary:"Show the user and company the founder PAT resolves to.",options:["--json Print machine-readable JSON."],example:"hyperscale whoami --json"},"ops list":{usage:"ops list [filter] [--product <id>] [--json]",summary:"List callable operations from the Product machine document.",options:["--product <id> Product to inspect. The Product API key must belong to it.","--api-key <key> Product API key. Defaults to HYPERSCALE_API_KEY.","--json Print matching operations as JSON."],example:"hyperscale ops list account"},call:{usage:"call <operation> [--input <json> | --input-file <path>] [--idempotency-key <key>] [--product <id>]",summary:"Call one operation from the Product machine document.",options:["--input <json> JSON input object. Stdin is used when piped.","--input-file <path> Read the JSON input object from a file.","--product <id> Product to call. The Product API key must belong to it.","--api-key <key> Product API key. Defaults to HYPERSCALE_API_KEY.","--idempotency-key <key> Send this exact Idempotency-Key header for a mutation. The default is a generated UUID."],notes:["Reuse an Idempotency-Key only with the same operation and input."],example:`hyperscale call account.create --input '{"currency":"SAR"}'`}};function po(e){let n=Object.keys(vt).sort((o,a)=>a.split(" ").length-o.split(" ").length).find(o=>o.split(" ").every((c,s)=>e[s]===c));if(!n)throw new I(`No help for ${e.join(" ")}. Run "hyperscale --help" to list commands.`);let r=vt[n];return[`Usage: hyperscale ${r.usage}`,"",r.summary,"","Options:",...r.options.map(o=>` ${o}`),...r.notes?["","Notes:",...r.notes.map(o=>` ${o}`)]:[],"","Example:",` ${r.example}`,""].join(`
97
+ `)}var I=class extends Error{constructor(t,n={}){super(t),typeof n.code=="string"&&(this.code=n.code),n.details!==void 0&&(this.details=n.details),Number.isInteger(n.exitCode)&&(this.exitCode=n.exitCode),typeof n.fix=="string"&&(this.fix=n.fix)}},He=class extends I{constructor(t,{requestId:n,status:r}){super(t),this.requestId=n,this.status=r}};function Cn(){return new I(ao,{fix:io})}function Et(e){let t=e??"<id>";return new I(`This command needs a Product API key. Create one with "hyperscale key create --name 'Founder CLI' --product ${t}", then set HYPERSCALE_API_KEY or pass --api-key.`)}var ze=class extends I{constructor(t,n){super(t),this.code="check_failed",this.details=n,this.exitCode=2}},mo=new Set(["--api-key","--base-url","--blueprint","--environment","--email","--idempotency-key","--input","--input-file","--name","--product","--role","--token"]);function fo(e){let t=[],n={};for(let r=0;r<e.length;r+=1){let o=e[r];if(!o.startsWith("--")){t.push(o);continue}if(mo.has(o)){let a=e[r+1];if(a===void 0)throw new I(`${o} needs a value`);n[o]=a,r+=1;continue}if(o==="--help"||o==="--version"||o==="--json"||o==="--confirm"||o==="--yes"||o==="--no-browser"||o==="--passkey"||o==="--revoke"){n[o]=!0;continue}throw new I(`Unknown option: ${o}`)}return{flags:n,positional:t}}function kt(e,t){let n=e["--api-key"]??t.HYPERSCALE_API_KEY;if(!n)throw Et();let r=e["--environment"]??t.HYPERSCALE_ENVIRONMENT??Mn;if(r!=="sandbox"&&r!=="live")throw new I(`Unknown environment: ${r}. Use sandbox or live.`);let o=(e["--base-url"]??t.HYPERSCALE_BASE_URL??Jn).replace(/\/+$/,"");return{apiKey:n,baseUrl:o,environment:r}}function Ye(e,t,n={}){let r=e["--environment"]??t.HYPERSCALE_ENVIRONMENT??n.environment??Mn;if(r!=="sandbox"&&r!=="live")throw new I(`Unknown environment: ${r}. Use sandbox or live.`);let o=(e["--base-url"]??t.HYPERSCALE_BASE_URL??n.baseUrl??Jn).replace(/\/+$/,""),a;try{a=new URL(o)}catch{a=null}let c=a?.origin??null;if(!c||c!==o)throw new I(`Invalid API origin: ${o}. Use an origin such as https://hyperscale0.ai.`);let s=["localhost","127.0.0.1","[::1]","::1"].includes(a.hostname);if(a.protocol!=="https:"&&!(a.protocol==="http:"&&s))throw new I(`Refusing cleartext API origin ${o}. Use HTTPS unless the API runs on loopback.`);return{baseUrl:o,environment:r}}function Tt(e){return e.HYPERSCALE_CONFIG_DIR??un(no(),".config","hyperscale")}function Rt(e){return un(Tt(e),oo)}function we(e,t){return un(Tt(t),`session-${Ve(e)}.json`)}function pn(e){let t=e.HYPERSCALE_CREDENTIAL_STORE??"auto";if(t==="auto"||t==="file")return t;throw new I(`Unknown HYPERSCALE_CREDENTIAL_STORE value: ${t}. Use auto or file.`)}async function Un(e,t){let n=we(e,t),r=`${to(n)}.`,o;try{o=await Xr(Rn(n),{withFileTypes:!0})}catch(a){if(a&&a.code==="ENOENT")return;throw a}for(let a of o){if(!a.isFile()||!a.name.startsWith(r))continue;let c=a.name.slice(r.length);/^\d+\.[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.tmp$/.test(c)&&await We(un(Rn(n),a.name))}}async function yo(e){try{return JSON.parse(await ln(e,"utf8"))}catch(t){if(t&&t.code==="ENOENT")return null;throw t instanceof SyntaxError?new I(`${e} is not valid JSON`):t}}async function qe(e,t){let n=ho(e);await Gr(n,{mode:448,recursive:!0}),await Pn(n,448);let r=`${e}.${process.pid}.${globalThis.crypto.randomUUID()}.tmp`;await eo(r,t,{flag:"wx",mode:384}),await Pn(r,384);try{await Zr(r,e),await Pn(e,384)}catch(o){throw await We(r),o}}function ho(e){return Rn(e)}async function We(e){try{await Qr(e)}catch(t){if(!t||t.code!=="ENOENT")throw t}}function go(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new I(`${t} does not contain a CLI profile`);let{baseUrl:n,email:r,environment:o,selectedProduct:a}=e;if(typeof n!="string"||typeof r!="string"||o!=="sandbox"&&o!=="live"||!(a===null||typeof a=="string"))throw new I(`${t} does not contain a valid CLI profile`);return{baseUrl:n,email:r,environment:o,selectedProduct:a}}async function mn(e){let t=Rt(e),n=await yo(t);return n===null?null:go(n,t)}async function fn(e,t){let n={email:t.email,baseUrl:t.baseUrl,environment:t.environment,selectedProduct:t.selectedProduct??null};await qe(Rt(e),`${JSON.stringify(n,null,2)}
98
98
  `)}function Ve(e){return Yr("sha256").update(`${e.baseUrl}\0${e.environment}\0${e.email}`).digest("hex")}async function yn(e,t){return Fn===null?{error:null,status:null,stdout:"",unavailable:!0}:await new Promise(n=>{let r={...process.env};delete r.HYPERSCALE_API_KEY,delete r.HYPERSCALE_TOKEN;let o=Ct(Fn,e,{env:r,stdio:["pipe","pipe","pipe"]}),a=[],c=!1,s=u=>{c||(c=!0,clearTimeout(l),n(u))},l=setTimeout(()=>{o.kill("SIGKILL"),s({error:null,status:null,stdout:"",unavailable:!0})},so);o.stdout.on("data",u=>a.push(u)),o.stderr.on("data",()=>{}),o.stdin.on("error",()=>{}),o.once("error",u=>s({error:u,status:null,stdout:"",unavailable:!0})),o.once("close",u=>s({error:null,status:u,stdout:Buffer.concat(a).toString("utf8"),unavailable:!1})),t===void 0?o.stdin.end():o.stdin.end(`${t}
99
99
  `)})}async function Kn(){return(await yn(["show-keychain-info"])).status===0}function Ft(e){try{let t=typeof e=="string"?JSON.parse(e):e;if(t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.token=="string"&&typeof t.tenantId=="string"&&(t.personalAccessTokenId===void 0||typeof t.personalAccessTokenId=="string")&&(t.tokenName===void 0||typeof t.tokenName=="string"))return{token:t.token,tenantId:t.tenantId,...t.personalAccessTokenId?{personalAccessTokenId:t.personalAccessTokenId}:{},...t.tokenName?{tokenName:t.tokenName}:{}}}catch{}return null}async function $o(e,t,n){await Un(e,n);let r=Ve(e);if(pn(n)==="auto"&&await Kn()){let o=JSON.stringify(t),a=["add-generic-password","-a",r,"-s",qn,"-U","-X",Buffer.from(o,"utf8").toString("hex")].join(" ");if((await yn(["-i"],a)).status===0)return await We(we(e,n)),"keychain"}return await qe(we(e,n),`${JSON.stringify({account:r,activeStore:"file",credential:t})}
100
100
  `),"file"}async function bo(e,t){let n=Ve(e);try{let r=JSON.parse(await ln(we(e,t),"utf8"));if(!r||typeof r!="object"||Array.isArray(r)||r.account!==n)return{state:"invalid"};if(r.revoked===!0)return{state:"revoked"};let o=Ft(r.credential);return o?{activeStore:r.activeStore==="file"?"file":null,credential:o,state:"valid"}:{state:"invalid"}}catch(r){return r&&r.code==="ENOENT"?{state:"missing"}:{state:"invalid"}}}async function Ot(e,t){await Un(e,t);let n=pn(t),r=await bo(e,t);if(r.state==="revoked")return null;if(r.state==="valid"&&(r.activeStore==="file"||n==="file"))return r.credential;if(n==="file")return null;let o=null;if(await Kn()){let a=await yn(["find-generic-password","-a",Ve(e),"-s",qn,"-w"]);a.status===0&&(o=Ft(a.stdout.trim()))}return o||(r.state==="valid"?r.credential:null)}async function Dt(e,t){await Un(e,t);let n=Ve(e);if(pn(t)==="file")return await qe(we(e,t),`${JSON.stringify({account:n,revoked:!0})}
101
101
  `),{keychainDeleted:!0};if(Fn===null)return await We(we(e,t)),{keychainDeleted:!0};if(!await Kn())return await qe(we(e,t),`${JSON.stringify({account:n,revoked:!0})}
102
102
  `),{keychainDeleted:!1};let r=await yn(["delete-generic-password","-a",n,"-s",qn]);return r.status!==0&&r.status!==44?(await qe(we(e,t),`${JSON.stringify({account:n,revoked:!0})}
103
- `),{keychainDeleted:!1}):(await We(we(e,t)),{keychainDeleted:!0})}function Nt(e,t){return e["--token"]!==void 0?e["--token"]:t.HYPERSCALE_TOKEN||void 0}async function ye(e,t,n=!1){let r=await mn(t),o=Nt(e,t);if(o!==void 0){if(!o)throw Cn();let s=Ye(e,t,r??{}),l=await Ee(s,o),u=r?.baseUrl===s.baseUrl&&r.environment===s.environment&&r.email===l.email;return{...s,email:l.email,identity:l,personalAccessTokenId:l.personalAccessTokenId,selectedProduct:u?r.selectedProduct:null,tenantId:l.tenantId,token:o,tokenName:l.name}}if(!r){if(n)return null;throw Cn()}let a=Ye(e,t,r);if(a.baseUrl!==r.baseUrl||a.environment!==r.environment)throw new S(`The active founder login belongs to ${r.baseUrl} (${r.environment}). Log in again to change it.`);let c=await Ot(r,t);if(!c){if(n)return null;throw Cn()}return{...r,...c}}function Lt(e){return e.replace(new RegExp("\\p{Cc}","gu"),t=>`
104
- \r`.includes(t)?t:"")}function sn(e){try{return new URL(e).origin}catch{return null}}function xe(e,t){let n=e;for(let r of t)typeof r=="string"&&r.length>0&&(n=n.replaceAll(r,"[redacted]"));return n}async function jt(e,t,n={},r){let o=`${e.baseUrl}${t}`,a=sn(e.baseUrl);if(sn(o)!==a)throw new S(`The requested path ${t} leaves the ${a} origin; refusing the request.`);try{let c=await fetch(o,{...n,headers:{accept:"application/json",...r?{authorization:`Bearer ${r}`}:{},"x-hyperscale-environment":e.environment,...n.headers},signal:AbortSignal.timeout(Dn),redirect:"manual"});if(c.status>=300&&c.status<400)throw new S(`${o} redirected, so no credential was sent on. Point --base-url at the origin the API answers on.`);return{response:c,text:Lt(await c.text())}}catch(c){throw c instanceof S?c:new S(`Could not reach ${o}: ${c.message}`)}}async function fe(e,t,n={},r,o=[]){let{response:a,text:c}=await jt(e,t,n,r);if(!a.ok)throw Ge(a,c,o);try{return JSON.parse(c)}catch{throw new S(`HTTP ${a.status} returned invalid JSON`)}}function ve(e,t=globalThis.crypto.randomUUID()){return{body:JSON.stringify(e),headers:{"content-type":"application/json","idempotency-key":t},method:"POST"}}async function wo(){let e=[];for await(let t of process.stdin)e.push(Buffer.from(t));return Buffer.concat(e).toString("utf8")}async function Te(e,t,n={},r){let o=`${e.baseUrl}${t}`,a=sn(e.baseUrl);if(sn(o)!==a)throw new S(`The product document puts ${t} on another origin than the ${a} you configured; refusing to send the key there.`);try{let c=await fetch(o,{...n,headers:{accept:"application/json",authorization:`Bearer ${e.apiKey}`,"x-hyperscale-environment":e.environment,...n.headers},signal:AbortSignal.timeout(Dn),redirect:"manual"});if(c.status>=300&&c.status<400)throw new S(`${o} redirected, so the key was not sent on. Point --base-url at the origin the API answers on; the usual cause is http:// where it serves https://.`);return{response:c,text:Lt(await c.text())}}catch(c){throw c instanceof S?c:r&&(c?.name==="TimeoutError"||c?.name==="AbortError")?new S(`product run ${r} timed out after ${Dn/1e3} seconds.`):new S(`Could not reach ${o}: ${c.message}`)}}async function Hn(e){let{response:t,text:n}=await Te(e,"/v1/llms.txt");if(!t.ok)throw Ge(t,n,[e.apiKey]);let r=/^# (.+)$/m.exec(n),o=/^> Generated for composition (\S+) /m.exec(n),a=/^## Operations \((\d+)\)$/m.exec(n);if(!r||!a)throw new Error("The product document is not in the expected format; upgrade the CLI.");let c=[],s=/^- ([A-Z]+) (\S+) · (\S+) \((\S+); idempotency (\S+)\)\n {2}Summary: (".*")\n {2}Description: (".*")$/gm;for(let f of n.matchAll(s))c.push({description:JSON.parse(f[7]),idempotency:f[5],method:f[1],name:f[3],operationId:f[4],path:f[2],summary:JSON.parse(f[6])});let l=Number(a[1]);if(c.length!==l)throw new S(`The product document declares ${l} operations but ${c.length} parsed. The server descriptor predates operation prose. Redeploy the platform, then recompose the Product.`);let u=/^- Package: (.+)$/m.exec(n);return{compositionId:o?o[1]:null,operations:c,packageName:u?u[1].trim():null,title:r[1].trim()}}function Ge(e,t,n=[]){let r=xe(t.trim(),n),o=e.headers.get("x-request-id")??void 0;try{let a=JSON.parse(t);a&&a.error&&typeof a.error.message=="string"&&(r=xe(`${a.error.code}: ${a.error.message}`,n)),!o&&typeof a?.requestId=="string"&&(o=a.requestId)}catch{}return new He(`HTTP ${e.status}${r?` \xB7 ${r}`:""}${o?`
105
- Request id: ${o}`:""}`,{requestId:o,status:e.status})}function zn(e,t){return{authenticated:!0,baseUrl:e.baseUrl,email:t.email,environment:e.environment,expiresAt:t.expiresAt,personalAccessTokenId:t.personalAccessTokenId,role:t.role,scopes:t.scopes,selectedProduct:e.selectedProduct,teamId:t.teamId,tenantId:t.tenantId,tokenName:t.name,userId:t.userId}}function vo(e){if(!e||typeof e!="object"||typeof e.userId!="string"||typeof e.email!="string"||typeof e.tenantId!="string"||typeof e.teamId!="string"||typeof e.role!="string"||typeof e.personalAccessTokenId!="string"||typeof e.name!="string"||!Array.isArray(e.scopes)||e.scopes.some(t=>typeof t!="string")||typeof e.expiresAt!="string"||e.status!=="active")throw new S("personal_access_token.current returned invalid data");return e}async function Ee(e,t){try{return vo(await fe(e,ro,{},t,[t]))}catch(n){throw!(n instanceof He)||n.status!==401?n:new S(`That founder PAT was not accepted (HTTP 401). ${Ke}${n.requestId?` Request id: ${n.requestId}.`:""}`,{code:"founder_pat_rejected",fix:Ke})}}function ko(e,t){return e.HYPERSCALE_CLI_BROWSER?{command:e.HYPERSCALE_CLI_BROWSER,args:[t]}:e.HYPERSCALE_NO_BROWSER==="1"||e.CI==="1"||e.CI==="true"||process.platform==="linux"&&!e.DISPLAY&&!e.WAYLAND_DISPLAY?null:process.platform==="darwin"?{command:"/usr/bin/open",args:[t]}:process.platform==="win32"?{command:"rundll32.exe",args:["url.dll,FileProtocolHandler",t]}:{command:"xdg-open",args:[t]}}async function _o(e,t){let n=ko(e,t);return n?new Promise(r=>{let o=Ct(n.command,n.args,{detached:!0,stdio:"ignore"});o.once("error",()=>r(!1)),o.once("spawn",()=>{o.unref(),r(!0)})}):!1}function En(e){return new Promise(t=>{if(!e.listening){t();return}e.close(()=>t())})}async function Ao(e,t){let n=globalThis.crypto.randomUUID(),r=!1,o,a=new Promise((T,R)=>{o={reject:R,resolve:T}}),c=Wr((T,R)=>{let C=new URL(T.url??"/","http://127.0.0.1");if(T.method!=="GET"||C.pathname!=="/callback"){R.writeHead(404,{"content-type":"text/plain; charset=utf-8"}),R.end(`Not found.
103
+ `),{keychainDeleted:!1}):(await We(we(e,t)),{keychainDeleted:!0})}function Nt(e,t){return e["--token"]!==void 0?e["--token"]:t.HYPERSCALE_TOKEN||void 0}async function ye(e,t,n=!1){let r=await mn(t),o=Nt(e,t);if(o!==void 0){if(!o)throw Cn();let s=Ye(e,t,r??{}),l=await Ce(s,o),u=r?.baseUrl===s.baseUrl&&r.environment===s.environment&&r.email===l.email;return{...s,email:l.email,identity:l,personalAccessTokenId:l.personalAccessTokenId,selectedProduct:u?r.selectedProduct:null,tenantId:l.tenantId,token:o,tokenName:l.name}}if(!r){if(n)return null;throw Cn()}let a=Ye(e,t,r);if(a.baseUrl!==r.baseUrl||a.environment!==r.environment)throw new I(`The active founder login belongs to ${r.baseUrl} (${r.environment}). Log in again to change it.`);let c=await Ot(r,t);if(!c){if(n)return null;throw Cn()}return{...r,...c}}function Lt(e){return e.replace(new RegExp("\\p{Cc}","gu"),t=>`
104
+ \r`.includes(t)?t:"")}function sn(e){try{return new URL(e).origin}catch{return null}}function xe(e,t){let n=e;for(let r of t)typeof r=="string"&&r.length>0&&(n=n.replaceAll(r,"[redacted]"));return n}async function jt(e,t,n={},r){let o=`${e.baseUrl}${t}`,a=sn(e.baseUrl);if(sn(o)!==a)throw new I(`The requested path ${t} leaves the ${a} origin; refusing the request.`);try{let c=await fetch(o,{...n,headers:{accept:"application/json",...r?{authorization:`Bearer ${r}`}:{},"x-hyperscale-environment":e.environment,...n.headers},signal:AbortSignal.timeout(Dn),redirect:"manual"});if(c.status>=300&&c.status<400)throw new I(`${o} redirected, so no credential was sent on. Point --base-url at the origin the API answers on.`);return{response:c,text:Lt(await c.text())}}catch(c){throw c instanceof I?c:new I(`Could not reach ${o}: ${c.message}`)}}async function fe(e,t,n={},r,o=[]){let{response:a,text:c}=await jt(e,t,n,r);if(!a.ok)throw Ge(a,c,o);try{return JSON.parse(c)}catch{throw new I(`HTTP ${a.status} returned invalid JSON`)}}function ve(e,t=globalThis.crypto.randomUUID()){return{body:JSON.stringify(e),headers:{"content-type":"application/json","idempotency-key":t},method:"POST"}}async function wo(){let e=[];for await(let t of process.stdin)e.push(Buffer.from(t));return Buffer.concat(e).toString("utf8")}async function Ee(e,t,n={},r){let o=`${e.baseUrl}${t}`,a=sn(e.baseUrl);if(sn(o)!==a)throw new I(`The product document puts ${t} on another origin than the ${a} you configured; refusing to send the key there.`);try{let c=await fetch(o,{...n,headers:{accept:"application/json",authorization:`Bearer ${e.apiKey}`,"x-hyperscale-environment":e.environment,...n.headers},signal:AbortSignal.timeout(Dn),redirect:"manual"});if(c.status>=300&&c.status<400)throw new I(`${o} redirected, so the key was not sent on. Point --base-url at the origin the API answers on; the usual cause is http:// where it serves https://.`);return{response:c,text:Lt(await c.text())}}catch(c){throw c instanceof I?c:r&&(c?.name==="TimeoutError"||c?.name==="AbortError")?new I(`product run ${r} timed out after ${Dn/1e3} seconds.`):new I(`Could not reach ${o}: ${c.message}`)}}async function Hn(e){let{response:t,text:n}=await Ee(e,"/v1/llms.txt");if(!t.ok)throw Ge(t,n,[e.apiKey]);let r=/^# (.+)$/m.exec(n),o=/^> Generated for composition (\S+) /m.exec(n),a=/^## Operations \((\d+)\)$/m.exec(n);if(!r||!a)throw new Error("The product document is not in the expected format; upgrade the CLI.");let c=[],s=/^- ([A-Z]+) (\S+) · (\S+) \((\S+); idempotency (\S+)\)\n {2}Summary: (".*")\n {2}Description: (".*")$/gm;for(let f of n.matchAll(s))c.push({description:JSON.parse(f[7]),idempotency:f[5],method:f[1],name:f[3],operationId:f[4],path:f[2],summary:JSON.parse(f[6])});let l=Number(a[1]);if(c.length!==l)throw new I(`The product document declares ${l} operations but ${c.length} parsed. The server descriptor predates operation prose. Redeploy the platform, then recompose the Product.`);let u=/^- Package: (.+)$/m.exec(n);return{compositionId:o?o[1]:null,operations:c,packageName:u?u[1].trim():null,title:r[1].trim()}}function Ge(e,t,n=[]){let r=xe(t.trim(),n),o=e.headers.get("x-request-id")??void 0;try{let a=JSON.parse(t);a&&a.error&&typeof a.error.message=="string"&&(r=xe(`${a.error.code}: ${a.error.message}`,n)),!o&&typeof a?.requestId=="string"&&(o=a.requestId)}catch{}return new He(`HTTP ${e.status}${r?` \xB7 ${r}`:""}${o?`
105
+ Request id: ${o}`:""}`,{requestId:o,status:e.status})}function zn(e,t){return{authenticated:!0,baseUrl:e.baseUrl,email:t.email,environment:e.environment,expiresAt:t.expiresAt,personalAccessTokenId:t.personalAccessTokenId,role:t.role,scopes:t.scopes,selectedProduct:e.selectedProduct,teamId:t.teamId,tenantId:t.tenantId,tokenName:t.name,userId:t.userId}}function vo(e){if(!e||typeof e!="object"||typeof e.userId!="string"||typeof e.email!="string"||typeof e.tenantId!="string"||typeof e.teamId!="string"||typeof e.role!="string"||typeof e.personalAccessTokenId!="string"||typeof e.name!="string"||!Array.isArray(e.scopes)||e.scopes.some(t=>typeof t!="string")||typeof e.expiresAt!="string"||e.status!=="active")throw new I("personal_access_token.current returned invalid data");return e}async function Ce(e,t){try{return vo(await fe(e,ro,{},t,[t]))}catch(n){throw!(n instanceof He)||n.status!==401?n:new I(`That founder PAT was not accepted (HTTP 401). ${Ke}${n.requestId?` Request id: ${n.requestId}.`:""}`,{code:"founder_pat_rejected",fix:Ke})}}function ko(e,t){return e.HYPERSCALE_CLI_BROWSER?{command:e.HYPERSCALE_CLI_BROWSER,args:[t]}:e.HYPERSCALE_NO_BROWSER==="1"||e.CI==="1"||e.CI==="true"||process.platform==="linux"&&!e.DISPLAY&&!e.WAYLAND_DISPLAY?null:process.platform==="darwin"?{command:"/usr/bin/open",args:[t]}:process.platform==="win32"?{command:"rundll32.exe",args:["url.dll,FileProtocolHandler",t]}:{command:"xdg-open",args:[t]}}async function _o(e,t){let n=ko(e,t);return n?new Promise(r=>{let o=Ct(n.command,n.args,{detached:!0,stdio:"ignore"});o.once("error",()=>r(!1)),o.once("spawn",()=>{o.unref(),r(!0)})}):!1}function En(e){return new Promise(t=>{if(!e.listening){t();return}e.close(()=>t())})}async function Ao(e,t){let n=globalThis.crypto.randomUUID(),r=!1,o,a=new Promise((T,R)=>{o={reject:R,resolve:T}}),c=Wr((T,R)=>{let C=new URL(T.url??"/","http://127.0.0.1");if(T.method!=="GET"||C.pathname!=="/callback"){R.writeHead(404,{"content-type":"text/plain; charset=utf-8"}),R.end(`Not found.
106
106
  `);return}if(r){R.writeHead(409,{"content-type":"text/plain; charset=utf-8"}),R.end(`Login callback was already received.
107
107
  `);return}if(C.searchParams.get("state")!==n){R.writeHead(400,{"content-type":"text/plain; charset=utf-8"}),R.end(`Login state did not match. Return to the terminal.
108
108
  `);return}let Q=C.searchParams.get("grant"),B=C.searchParams.get("tenantId");if(!Q||!B){R.writeHead(400,{"content-type":"text/plain; charset=utf-8"}),R.end(`Login callback is missing its grant or tenant.
109
109
  `);return}r=!0,R.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),R.end(`Login received. Return to the terminal.
110
- `),o.resolve({grant:Q,tenantId:B})});await new Promise((T,R)=>{let C=Q=>R(Q);c.once("error",C),c.listen(0,"127.0.0.1",()=>{c.off("error",C),T()})}),c.once("error",T=>o.reject(T));let s=c.address();if(!s||typeof s=="string")throw await En(c),new S("Could not bind the localhost login callback");let l=`http://127.0.0.1:${s.port}/callback`,u=new URL("/auth/cli",e.baseUrl);u.searchParams.set("callback",l),u.searchParams.set("state",n);let f=new URL("/signin",e.baseUrl);f.searchParams.set("returnTo",`${u.pathname}${u.search}`);let v=f.toString();if(!await _o(t,v))return await En(c),null;process.stderr.write(`Opening portal sign-in: ${v}
111
- `);let k=setTimeout(()=>{o.reject(new S("Portal login timed out. Run hyperscale auth login to start a new callback.",{code:"auth_callback_timeout"}))},co);try{return await a}finally{clearTimeout(k),await En(c)}}function _t(e){let t={authenticated:!1,browserOpened:!1,next:["export HYPERSCALE_TOKEN=hyperscale_pat_...","hyperscale auth login --no-browser"],patMintUrl:On,requestAccessUrl:Ue};if(e["--json"]){se(t);return}y("No browser detected. Mint a founder PAT in the portal, then run:");for(let n of t.next)y(` ${n}`);y(`PAT desk: ${On}`),y(`No access yet: ${Ue}`)}async function At(e,t,n,r,o){let a=await mn(o),c={email:t.email,...e,selectedProduct:a&&a.email===t.email&&a.baseUrl===e.baseUrl&&a.environment===e.environment?a.selectedProduct:null},s=await $o(c,{personalAccessTokenId:t.personalAccessTokenId,token:n,tokenName:t.name,tenantId:t.tenantId},o);try{await fn(o,c)}catch(u){throw await Dt(c,o),u}if(s==="file"){let u=pn(o)==="file"?"Founder PAT file storage is active.":"macOS Keychain is unavailable.";process.stderr.write(`${u} The founder PAT is in ${we(c,o)} with mode 0600.
112
- `)}let l=zn(c,t);r["--json"]?se(l):y(`Logged in as ${t.email} with PAT ${t.name}.`)}async function xo(e,t){let n=Ye(e,t),r=Nt(e,t);if(r){if(!r.startsWith("hyperscale_pat_"))throw new S("Founder PATs start with hyperscale_pat_. Product API keys belong in HYPERSCALE_API_KEY.");let l=await Ee(n,r);await At(n,l,r,e,t);return}if(e["--no-browser"]){_t(e);return}let o=await Ao(n,t);if(!o){_t(e);return}let a=await fe(n,"/v1/personal-access-token-login-grants/exchange",ve({tenantId:o.tenantId,grant:o.grant}),void 0,[o.grant]),c=a?.secret;if(typeof c!="string"||!c.startsWith("hyperscale_pat_")||a?.tenantId!==o.tenantId)throw new S("CLI login grant exchange returned an invalid PAT");let s=await Ee(n,c);await At(n,s,c,e,t)}async function So(e,t){let n=await ye(e,t),r=n.identity??await Ee(n,n.token),o=zn(n,r);if(e["--json"]){se(o);return}y(`User: ${r.email}`),y(`Tenant: ${r.tenantId}`),y(`Role: ${r.role}`),y(`Token: ${r.name}`),y(`Scopes: ${r.scopes.join(", ")}`),y(`Expires: ${r.expiresAt}`),y(`API: ${n.baseUrl}`),y(`Environment: ${n.environment}`),y(`Product: ${n.selectedProduct??"not selected"}`)}async function Io(e,t){let n=await mn(t);if(!n){e["--json"]?se({status:"signed_out"}):y("Already logged out.");return}let r=await Ot(n,t);if(e["--revoke"]&&!r)throw new S("The local founder PAT is missing, so the CLI cannot revoke it.");let o=r?.personalAccessTokenId,a=r?.tokenName;if(e["--revoke"]&&r){if(!o||!a){let l=await Ee(n,r.token);o=l.personalAccessTokenId,a=l.name}await fe(n,`/v1/personal-access-tokens/${encodeURIComponent(o)}/revoke`,ve({tenantId:r.tenantId,personalAccessTokenId:o}),r.token,[r.token])}let c=await Dt(n,t),s=e["--revoke"]===!0;Po(e,{cleanup:c,personalAccessTokenId:o,revoked:s,status:"signed_out",tokenName:a})}function Po(e,t){let n=t.cleanup.keychainDeleted?"complete":"tombstoned";if(e["--json"])se({credentialCleanup:n,...t.personalAccessTokenId?{personalAccessTokenId:t.personalAccessTokenId}:{},...t.revoked===void 0?{}:{revoked:t.revoked},status:t.status,...t.tokenName?{tokenName:t.tokenName}:{},...t.revoked===!1?{tokenStillValid:!0}:{}});else{let r=t.tokenName&&t.personalAccessTokenId?`${t.tokenName} (${t.personalAccessTokenId})`:"with unavailable local metadata";t.revoked?y(`Revoked founder PAT ${r} and forgot local state.`):(y(`Forgot local founder PAT ${r}.`),y("The PAT stays valid until expiry; revoke at /desk/security/tokens."))}t.cleanup.keychainDeleted||process.stderr.write(`Keychain cleanup failed. A 0600 profile tombstone blocks the stale founder PAT.
113
- `)}function Pe(e,t){if(!e||typeof e!="object"||!Array.isArray(e.items))throw new S(`${t} returned an invalid collection`);return e.items}async function Oe(e,t,n,r,o,a=[]){let c=[],s=new Set,l,u;for(;;){let k=new URLSearchParams(n);l&&k.set("cursor",l);let T=k.size>0?`?${k}`:"",R=await fe(e,`${t}${T}`,{},o,a);u===void 0&&(u=R),c.push(...Pe(R,r));let C=R.nextCursor;if(typeof C!="string"||C.length===0)break;if(s.has(C))throw new S(`${r} repeated cursor ${C}`);s.add(C),l=C}let{items:f,nextCursor:v,...x}=u;return{...x,items:c}}async function Co(e,t){let n=await Oe(e,"/v1/blueprints",{},"blueprint.list"),r=Pe(n,"blueprint.list");if(t["--json"]){se(n);return}y("ID Name Summary");for(let o of r)y(`${o.id} ${o.name}${o.summary?` ${o.summary}`:""}`);y("Next:"),y(" hyperscale blueprint show <id>"),y(" hyperscale product create --blueprint <id> --name <name>")}async function Eo(e,t,n){if(!n)throw new S("blueprint show needs a Blueprint id");let r=await fe(e,`/v1/blueprints/${encodeURIComponent(n)}`),o=To(r,e.baseUrl);if(t["--json"]){se(o);return}y(`${o.name} (${o.id})`),y(o.summary),y(o.description),y("Nouns:");for(let a of o.customInstruments??[])y(` ${a.name} (${a.id}): ${a.summary}`);for(let a of o.instruments??[])y(` ${a.title} (${a.id}): ${a.summary}`);y("Verbs:");for(let a of o.verbs??[])y(` ${a.alias} -> ${a.operation}: ${a.summary}`);y("Parties:");for(let a of o.parties??[])y(` ${a.instrumentId}.${a.role} -> ${a.accountField}`);y("Money flows:");for(let a of o.moneyFlows??[]){let c=a.sourceAccount??"action input",s=a.destinationAccount??"action input",l=a.amountPath??"action input";y(` ${a.action} [${a.kind}]: ${c} -> ${s}; amount ${l}`)}y("Fee forms:");for(let a of o.feeForms??[]){let c=a.bps?`${a.bps} bps`:a.amountSar?`SAR ${a.amountSar}`:a.includedQuantity?`${a.includedQuantity} included`:a.kind;y(` ${a.id}: ${c} per ${a.unit}. ${a.summary}`)}o.priceEstimate&&(y("Price estimate:"),y(` monthlySar: SAR ${Number(o.priceEstimate.monthlySar).toLocaleString("en-US")}`),y(` setupSar: SAR ${Number(o.priceEstimate.setupSar).toLocaleString("en-US")}`),y(` complexityScore: ${o.priceEstimate.complexityScore}`)),y("Dials:");for(let a of o.dials??[])y(` ${a.instrumentId}.${a.key} (${a.kind}): ${a.summary}`);y("Journeys:");for(let a of o.journeys??[])y(` ${a.title} (${a.id}): ${a.summary}`),y(` ${a.steps.join(" -> ")}`);o.hsxStructured&&(y("HSX:"),y(` Source:
110
+ `),o.resolve({grant:Q,tenantId:B})});await new Promise((T,R)=>{let C=Q=>R(Q);c.once("error",C),c.listen(0,"127.0.0.1",()=>{c.off("error",C),T()})}),c.once("error",T=>o.reject(T));let s=c.address();if(!s||typeof s=="string")throw await En(c),new I("Could not bind the localhost login callback");let l=`http://127.0.0.1:${s.port}/callback`,u=new URL("/auth/cli",e.baseUrl);u.searchParams.set("callback",l),u.searchParams.set("state",n);let f=new URL("/signin",e.baseUrl);f.searchParams.set("returnTo",`${u.pathname}${u.search}`);let v=f.toString();if(!await _o(t,v))return await En(c),null;process.stderr.write(`Opening portal sign-in: ${v}
111
+ `);let k=setTimeout(()=>{o.reject(new I("Portal login timed out. Run hyperscale auth login to start a new callback.",{code:"auth_callback_timeout"}))},co);try{return await a}finally{clearTimeout(k),await En(c)}}function _t(e){let t={authenticated:!1,browserOpened:!1,next:["export HYPERSCALE_TOKEN=hyperscale_pat_...","hyperscale auth login --no-browser"],patMintUrl:On,requestAccessUrl:Ue};if(e["--json"]){se(t);return}y("No browser detected. Mint a founder PAT in the portal, then run:");for(let n of t.next)y(` ${n}`);y(`PAT desk: ${On}`),y(`No access yet: ${Ue}`)}async function At(e,t,n,r,o){let a=await mn(o),c={email:t.email,...e,selectedProduct:a&&a.email===t.email&&a.baseUrl===e.baseUrl&&a.environment===e.environment?a.selectedProduct:null},s=await $o(c,{personalAccessTokenId:t.personalAccessTokenId,token:n,tokenName:t.name,tenantId:t.tenantId},o);try{await fn(o,c)}catch(u){throw await Dt(c,o),u}if(s==="file"){let u=pn(o)==="file"?"Founder PAT file storage is active.":"macOS Keychain is unavailable.";process.stderr.write(`${u} The founder PAT is in ${we(c,o)} with mode 0600.
112
+ `)}let l=zn(c,t);r["--json"]?se(l):y(`Logged in as ${t.email} with PAT ${t.name}.`)}async function xo(e,t){let n=Ye(e,t),r=Nt(e,t);if(r){if(!r.startsWith("hyperscale_pat_"))throw new I("Founder PATs start with hyperscale_pat_. Product API keys belong in HYPERSCALE_API_KEY.");let l=await Ce(n,r);await At(n,l,r,e,t);return}if(e["--no-browser"]){_t(e);return}let o=await Ao(n,t);if(!o){_t(e);return}let a=await fe(n,"/v1/personal-access-token-login-grants/exchange",ve({tenantId:o.tenantId,grant:o.grant}),void 0,[o.grant]),c=a?.secret;if(typeof c!="string"||!c.startsWith("hyperscale_pat_")||a?.tenantId!==o.tenantId)throw new I("CLI login grant exchange returned an invalid PAT");let s=await Ce(n,c);await At(n,s,c,e,t)}async function So(e,t){let n=await ye(e,t),r=n.identity??await Ce(n,n.token),o=zn(n,r);if(e["--json"]){se(o);return}y(`User: ${r.email}`),y(`Tenant: ${r.tenantId}`),y(`Role: ${r.role}`),y(`Token: ${r.name}`),y(`Scopes: ${r.scopes.join(", ")}`),y(`Expires: ${r.expiresAt}`),y(`API: ${n.baseUrl}`),y(`Environment: ${n.environment}`),y(`Product: ${n.selectedProduct??"not selected"}`)}async function Io(e,t){let n=await mn(t);if(!n){e["--json"]?se({status:"signed_out"}):y("Already logged out.");return}let r=await Ot(n,t);if(e["--revoke"]&&!r)throw new I("The local founder PAT is missing, so the CLI cannot revoke it.");let o=r?.personalAccessTokenId,a=r?.tokenName;if(e["--revoke"]&&r){if(!o||!a){let l=await Ce(n,r.token);o=l.personalAccessTokenId,a=l.name}await fe(n,`/v1/personal-access-tokens/${encodeURIComponent(o)}/revoke`,ve({tenantId:r.tenantId,personalAccessTokenId:o}),r.token,[r.token])}let c=await Dt(n,t),s=e["--revoke"]===!0;Po(e,{cleanup:c,personalAccessTokenId:o,revoked:s,status:"signed_out",tokenName:a})}function Po(e,t){let n=t.cleanup.keychainDeleted?"complete":"tombstoned";if(e["--json"])se({credentialCleanup:n,...t.personalAccessTokenId?{personalAccessTokenId:t.personalAccessTokenId}:{},...t.revoked===void 0?{}:{revoked:t.revoked},status:t.status,...t.tokenName?{tokenName:t.tokenName}:{},...t.revoked===!1?{tokenStillValid:!0}:{}});else{let r=t.tokenName&&t.personalAccessTokenId?`${t.tokenName} (${t.personalAccessTokenId})`:"with unavailable local metadata";t.revoked?y(`Revoked founder PAT ${r} and forgot local state.`):(y(`Forgot local founder PAT ${r}.`),y("The PAT stays valid until expiry; revoke at /desk/security/tokens."))}t.cleanup.keychainDeleted||process.stderr.write(`Keychain cleanup failed. A 0600 profile tombstone blocks the stale founder PAT.
113
+ `)}function Te(e,t){if(!e||typeof e!="object"||!Array.isArray(e.items))throw new I(`${t} returned an invalid collection`);return e.items}async function Oe(e,t,n,r,o,a=[]){let c=[],s=new Set,l,u;for(;;){let k=new URLSearchParams(n);l&&k.set("cursor",l);let T=k.size>0?`?${k}`:"",R=await fe(e,`${t}${T}`,{},o,a);u===void 0&&(u=R),c.push(...Te(R,r));let C=R.nextCursor;if(typeof C!="string"||C.length===0)break;if(s.has(C))throw new I(`${r} repeated cursor ${C}`);s.add(C),l=C}let{items:f,nextCursor:v,...x}=u;return{...x,items:c}}async function Co(e,t){let n=await Oe(e,"/v1/blueprints",{},"blueprint.list"),r=Te(n,"blueprint.list");if(t["--json"]){se(n);return}y("ID Name Summary");for(let o of r)y(`${o.id} ${o.name}${o.summary?` ${o.summary}`:""}`);y("Next:"),y(" hyperscale blueprint show <id>"),y(" hyperscale product create --blueprint <id> --name <name>")}async function Eo(e,t,n){if(!n)throw new I("blueprint show needs a Blueprint id");let r=await fe(e,`/v1/blueprints/${encodeURIComponent(n)}`),o=To(r,e.baseUrl);if(t["--json"]){se(o);return}y(`${o.name} (${o.id})`),y(o.summary),y(o.description),y("Nouns:");for(let a of o.customInstruments??[])y(` ${a.name} (${a.id}): ${a.summary}`);for(let a of o.instruments??[])y(` ${a.title} (${a.id}): ${a.summary}`);y("Verbs:");for(let a of o.verbs??[])y(` ${a.alias} -> ${a.operation}: ${a.summary}`);y("Parties:");for(let a of o.parties??[])y(` ${a.instrumentId}.${a.role} -> ${a.accountField}`);y("Money flows:");for(let a of o.moneyFlows??[]){let c=a.sourceAccount??"action input",s=a.destinationAccount??"action input",l=a.amountPath??"action input";y(` ${a.action} [${a.kind}]: ${c} -> ${s}; amount ${l}`)}y("Fee forms:");for(let a of o.feeForms??[]){let c=a.bps?`${a.bps} bps`:a.amountSar?`SAR ${a.amountSar}`:a.includedQuantity?`${a.includedQuantity} included`:a.kind;y(` ${a.id}: ${c} per ${a.unit}. ${a.summary}`)}o.priceEstimate&&(y("Price estimate:"),y(` monthlySar: SAR ${Number(o.priceEstimate.monthlySar).toLocaleString("en-US")}`),y(` setupSar: SAR ${Number(o.priceEstimate.setupSar).toLocaleString("en-US")}`),y(` complexityScore: ${o.priceEstimate.complexityScore}`)),y("Dials:");for(let a of o.dials??[])y(` ${a.instrumentId}.${a.key} (${a.kind}): ${a.summary}`);y("Journeys:");for(let a of o.journeys??[])y(` ${a.title} (${a.id}): ${a.summary}`),y(` ${a.steps.join(" -> ")}`);o.hsxStructured&&(y("HSX:"),y(` Source:
114
114
  ${xt(o.hsxStructured.source," ")}`),o.hsxStructured.document&&y(` Structured document:
115
115
  ${xt(JSON.stringify(o.hsxStructured.document,null,2)," ")}`)),y("Terms:");for(let[a,c]of Object.entries(o.terminology))y(` ${a}: ${c.definition}`),y(` ${c.href}`);y("Next:"),y(` hyperscale product create --blueprint ${o.id} --name <name>`)}function To(e,t){let n=Ro(e?.hsx);return{...e,...n?{hsxStructured:n}:{},terminology:{firedBy:{definition:"Who invokes an action: tenant through the Product surface, operator through a console session, or machine when a due condition arrives.",href:`${t}/glossary#action-caller`},publicIntents:{definition:"The retired name for publicActions. publicActions contains the canonical action IDs frozen into a composed Product.",href:`${t}/glossary#public-actions`},trustFile:{definition:"The evidence attached to a business record for later review, such as inspection, authentication, delivery, or proof-of-work records.",href:`${t}/glossary#trust-file`}}}}function Ro(e){if(typeof e!="string"||e.length===0)return;try{let n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return{document:n,language:"hsx-json",source:e,verdict:"valid"}}catch{}let t=an(e);return{diagnostics:t.diagnostics,...t.artifacts?{document:t.artifacts.document,frame:t.artifacts.frame}:{},language:"hsx-text",source:e,verdict:t.verdict}}function xt(e,t){return e.split(`
116
116
  `).map(n=>`${t}${n}`).join(`
117
- `)}function Bt(e){return{operationId:e.headers.get("hyperscale-operation-id")??"not returned",receiptId:e.headers.get("hyperscale-receipt-id")??"not returned"}}function Fo(e,t,n=[]){if(!e.ok)throw Ge(e,t,n);try{return JSON.parse(t)}catch{throw new S(`HTTP ${e.status} returned invalid JSON`)}}function St(e,t){y(`${e} operation: ${t.operationId}`),y(`${e} receipt: ${t.receiptId}`)}function Oo(e,t){let n=e instanceof S?e:new S("hyperscale start failed after the Product was created",{code:"start_failed_after_compose"});return n.shownOnce=t,n}function Do(e){if(!e["--blueprint"]&&!(process.stdin.isTTY&&process.stderr.isTTY))throw new S("hyperscale start needs an interactive terminal to choose a company. Pass --blueprint <slug> in scripts and non-interactive environments.",{code:"start_blueprint_required",fix:'Run "hyperscale blueprint list", then pass --blueprint <slug>.'})}function No(e){return Pe(e,"blueprint.list").map(t=>{if(typeof t?.id!="string"||t.id.length===0||typeof t?.name!="string"||t.name.length===0)throw new S("blueprint.list returned an invalid start choice");return{id:t.id,name:t.name,summary:typeof t.summary=="string"?t.summary:""}})}async function Lo(e,t){let n=await Oe(t,"/v1/blueprints",{},"blueprint.list"),r=No(n);if(r.length===0)throw new S("The Blueprint catalog has no companies to build.");let o=e["--blueprint"];if(o){let v=r.find(({id:x})=>x===o);if(v)return v;throw new S(`Unknown Blueprint: ${o}`,{fix:'Run "hyperscale blueprint list" and pass one listed slug to --blueprint.'})}process.stderr.write(`Which company do you want to build?
117
+ `)}function Bt(e){return{operationId:e.headers.get("hyperscale-operation-id")??"not returned",receiptId:e.headers.get("hyperscale-receipt-id")??"not returned"}}function Fo(e,t,n=[]){if(!e.ok)throw Ge(e,t,n);try{return JSON.parse(t)}catch{throw new I(`HTTP ${e.status} returned invalid JSON`)}}function St(e,t){y(`${e} operation: ${t.operationId}`),y(`${e} receipt: ${t.receiptId}`)}function Oo(e,t){let n=e instanceof I?e:new I("hyperscale start failed after the Product was created",{code:"start_failed_after_compose"});return n.shownOnce=t,n}function Do(e){if(!e["--blueprint"]&&!(process.stdin.isTTY&&process.stderr.isTTY))throw new I("hyperscale start needs an interactive terminal to choose a company. Pass --blueprint <slug> in scripts and non-interactive environments.",{code:"start_blueprint_required",fix:'Run "hyperscale blueprint list", then pass --blueprint <slug>.'})}function No(e){return Te(e,"blueprint.list").map(t=>{if(typeof t?.id!="string"||t.id.length===0||typeof t?.name!="string"||t.name.length===0)throw new I("blueprint.list returned an invalid start choice");return{id:t.id,name:t.name,summary:typeof t.summary=="string"?t.summary:""}})}async function Lo(e,t){let n=await Oe(t,"/v1/blueprints",{},"blueprint.list"),r=No(n);if(r.length===0)throw new I("The Blueprint catalog has no companies to build.");let o=e["--blueprint"];if(o){let v=r.find(({id:x})=>x===o);if(v)return v;throw new I(`Unknown Blueprint: ${o}`,{fix:'Run "hyperscale blueprint list" and pass one listed slug to --blueprint.'})}process.stderr.write(`Which company do you want to build?
118
118
  `);for(let[v,x]of r.entries()){let k=x.summary.replace(/\s+/g," ").trim();process.stderr.write(` ${v+1}. ${x.name} (${x.id})${k?`: ${k}`:""}
119
- `)}let a=Vr({input:process.stdin,output:process.stderr,terminal:!0}),c=new AbortController,s=()=>c.abort();process.stdin.once("end",s),process.stdin.readableEnded&&c.abort();let l;try{try{l=(await a.question("Choose a number or Blueprint slug: ",{signal:c.signal})).trim()}catch(v){throw v?.name!=="AbortError"&&v?.code!=="ABORT_ERR"?v:new S("Start cancelled before a Blueprint was chosen.",{code:"start_cancelled"})}}finally{process.stdin.off("end",s),a.close()}let u=Number(l),f=Number.isInteger(u)?r[u-1]:r.find(({id:v})=>v===l);if(f)return f;throw new S(`No Blueprint matches ${JSON.stringify(l)}.`,{fix:"Run hyperscale start again and choose a listed number or slug."})}function jo(e){if(!(!e||typeof e!="object")&&Array.isArray(e.journeys))for(let t of e.journeys){if(!t||typeof t!="object"||!Array.isArray(t.steps))continue;let n=t.steps[0];if(n?.status==="runnable"&&typeof n.operationId=="string"&&n.request&&typeof n.request=="object"&&Array.isArray(n.request.body)&&Array.isArray(n.request.path)&&Array.isArray(n.request.query)&&n.request.literals&&typeof n.request.literals=="object"&&!Array.isArray(n.request.literals)&&typeof t.id=="string")return{id:t.id,step:n}}}function Bo(e,t,n){if(e==="tenantId")return t.tenantId;if(e==="productId")return t.productId;if(e==="customerId")return t.fixtureProfileId;if(e==="currency")return t.fixtureCurrency;if(e==="subject"||e==="subjectId")return t.fixtureSubjects?.[0]?.subjectId;if(e.endsWith("AccountId")){let r=n.distinctPartyAccountFields?.indexOf(e);return r>=0&&(e==="buyerAccountId"||e==="claimantAccountId"||e==="policyholderAccountId")?t.fixtureCounterpartyAccountId:r>=0&&(e==="insurerAccountId"||e==="sellerAccountId")?t.fixtureAccountId:r>0?t.fixtureCounterpartyAccountId:t.fixtureAccountId}}var Jo=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/,Mo=6e4;function Jt(e){if(typeof e!="string"||!Jo.test(e))return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function Nn(e,t){let n=Jt(e);if(n!==void 0){t.push(n);return}if(Array.isArray(e)){for(let r of e)Nn(r,t);return}if(!(!e||typeof e!="object"))for(let r of Object.values(e))Nn(r,t)}function Ln(e,t){let n=Jt(e);return n!==void 0?new Date(n+t).toISOString():Array.isArray(e)?e.map(r=>Ln(r,t)):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).map(([r,o])=>[r,Ln(o,t)]))}function qo(e,t=Date.now()){let n=[];Nn(e,n);let r=Math.min(...n);return!Number.isFinite(r)||r>t?e:Ln(e,t+Mo-r)}function Uo(e,t){let n={...qo(e.request.literals)},r=[...e.request.path,...e.request.query,...e.request.body];for(let o of r){if(typeof o!="string"||Object.hasOwn(n,o))continue;let a=Bo(o,t,e);if(a===void 0)throw new S(`The frozen journey needs ${o}, but composition did not return a matching sandbox fixture.`,{code:"start_fixture_unavailable"});n[o]=a}return n}async function Ko(e,t,n){let r=await Hn(e),o=Vt(r.operations,t.operationId),a=Uo(t,n),{path:c,remaining:s}=Yt(o,a),l={method:o.method},u=c,f;o.method==="GET"?u+=Wt(s):(f=globalThis.crypto.randomUUID(),l.body=JSON.stringify(s),l.headers={"content-type":"application/json",...o.idempotency==="not_required"?{}:{"idempotency-key":f}});let v=await Te(e,u,l);if(!v.response.ok)throw hn(v.response,v.text,[e.apiKey],{action:t.operationId});return{...f?{idempotencyKey:f}:{},input:a,operationId:t.operationId,output:dn(zt(v.text),[e.apiKey]),receipt:Bt(v.response)}}async function It(e,t){Do(e);let n={};try{await Ho(e,t,n)}catch(r){throw typeof n.apiKey!="string"?r:Oo(r,n.apiKey)}}async function Ho(e,t,n){let r=await ye(e,t),o=await Ee(r,r.token),a=await Lo(e,r),c=e["--name"]??a.name;e["--json"]||y(`Authenticated: ${o.email}`);let s=await jt(r,"/v1/products/blueprint-compose",ve({blueprintId:a.id,name:c,tenantId:r.tenantId}),r.token),l=Fo(s.response,s.text,[r.token]);if(typeof l?.productId!="string"||!lo.test(l.productId)||typeof l?.productBuildId!="string"||l?.blueprintId!==a.id)throw new S("product.blueprint.compose returned an invalid start Product");let u=l?.shown_once;if(typeof u!="string"||u.length===0)throw new S("The composed Product did not return its one-time API key. Choose a new Product name and run hyperscale start again.",{code:"start_api_key_unavailable"});n.apiKey=u;let f=Bt(s.response);await fn(t,{...r,selectedProduct:l.productId}),e["--json"]||(y(`Product: ${l.productId}`),y(`Blueprint: ${l.blueprintId}`),St("Compose",f));let v={baseUrl:r.baseUrl,environment:r.environment,apiKey:u,productId:l.productId},x=await Te(v,`/v1/products/${encodeURIComponent(l.productId)}/operation-set`);if(!x.response.ok)throw hn(x.response,x.text,[u]);let k=Kt(x.text,x.response.status);if(k.status!=="frozen"||k.productBuildId!==l.productBuildId)throw new S("The composed Product did not return its frozen build operation set.",{code:"start_build_unavailable"});let T=[`hyperscale compose plan product.hsx --product ${l.productId}`],R=jo(k.goldenPath);if(!R){let B=`Blueprint ${a.id} has no published runnable journeys. Composition completed only.`,W={blueprintId:l.blueprintId,composeOnly:!0,nextCommands:T,notice:B,productBuildId:l.productBuildId,productId:l.productId,receipts:[{stage:"product.blueprint.compose",...f}],...typeof l.startKeyId=="string"?{startKeyId:l.startKeyId}:{},shown_once:u};if(e["--json"]){se(W);return}y(B),y(`Shown once Product API key: ${u}`),y("Next:");for(let H of T)y(` ${H}`);return}let C=await Ko(v,R.step,l);e["--json"]||St("First journey step",C.receipt);let Q={blueprintId:l.blueprintId,journey:{id:R.id,firstStep:C},nextCommands:T,productBuildId:l.productBuildId,productId:l.productId,receipts:[{stage:"product.blueprint.compose",...f},{stage:R.step.operationId,...C.receipt}],...typeof l.startKeyId=="string"?{startKeyId:l.startKeyId}:{},shown_once:u};if(e["--json"]){se(Q);return}C.output!==null&&y(JSON.stringify(C.output,null,2)),y(`Shown once Product API key: ${u}`),y("Next:");for(let B of T)y(` ${B}`)}async function zo(e,t){let n=e["--blueprint"],r=e["--name"];if(!n)throw new S("product create needs --blueprint <id>");if(!r)throw new S("product create needs --name <name>");let o=await ye(e,t),a;try{a=await Oe(o,"/v1/products",{tenantId:o.tenantId},"product.list",o.token,[o.token])}catch(v){if(!(v instanceof He)||v.status!==403)throw v}let c=r.trim().toLocaleLowerCase("en-US"),s=(a?Pe(a,"product.list"):[]).find(v=>{let x=v?.displayName??v?.name;return typeof x=="string"&&x.trim().toLocaleLowerCase("en-US")===c});if(s){let v=s.productId??s.id??"<id>";throw new S(`A Product named ${JSON.stringify(r.trim())} already exists as ${v}.`,{code:"duplicate_product_name",fix:`Use "hyperscale product select ${v}" or choose another --name.`})}let l=await fe(o,"/v1/products/blueprint-compose",ve({blueprintId:n,name:r,tenantId:o.tenantId}),o.token,[o.token]);if(typeof l?.productId!="string"||typeof l?.blueprintId!="string"||typeof l?.productBuildId!="string")throw new S("product.blueprint.compose returned an invalid Product");await fn(t,{...o,selectedProduct:l.productId});let u=typeof l?.shown_once=="string"&&l.shown_once.length>0?l.shown_once:void 0,f={blueprintId:l.blueprintId,nextSteps:[`hyperscale product show ${l.productId}`,...u?[]:['hyperscale key create --name "Founder CLI"']],productBuildId:l.productBuildId,productId:l.productId,selectedProduct:l.productId,...typeof l.startKeyId=="string"?{startKeyId:l.startKeyId}:{},...u?{shown_once:u}:{}};if(e["--json"]){se(f);return}y(`Product: ${f.productId}`),y(`Blueprint: ${f.blueprintId}`),y(`Build: ${f.productBuildId}`),y(`Selected: ${f.selectedProduct}`),f.shown_once&&y(`Shown once Product API key: ${f.shown_once}`),y("Next:");for(let v of f.nextSteps)y(` ${v}`)}function Yn(e){return new URLSearchParams({tenantId:e}).toString()}async function Yo(e,t){let n=await ye(e,t),r=await Oe(n,"/v1/products",{tenantId:n.tenantId},"product.list",n.token,[n.token]),o=Pe(r,"product.list");if(e["--json"]){se(r);return}if(o.length===0){y('No Products yet. Run "hyperscale blueprint list", then "hyperscale product create --blueprint <id> --name <name>".');return}y("ID Name Status");for(let a of o){let c=a.productId??a.id??"unknown",s=a.displayName??a.name??"unnamed";y(`${c} ${s}${a.status?` ${a.status}`:""}`)}}async function Wo(e,t,n){let r=await ye(e,t),o=n??r.selectedProduct;if(!o)throw new S("product show needs an id because no Product is selected. Create a Product first.");let a=await fe(r,`/v1/products/${encodeURIComponent(o)}?${Yn(r.tenantId)}`,{},r.token,[r.token]);if(e["--json"]){se(a);return}Vo(a,o)}function Vo(e,t){let n=e?.displayName??e?.name??"unnamed",r=e?.status??"unknown",o=e?.blueprint,a=o?.id?`${o.name??o.id}${o.name?` (${o.id})`:""}`:"custom composition",c=e?.cost?.currency??"SAR",s=e?.plan?.monthlySar??e?.cost?.platformMonthlySar,l=e?.plan?.setupSar??e?.cost?.platformSetupSar,u=[...Array.isArray(e?.readiness?.outstandingLiveRequirements)?e.readiness.outstandingLiveRequirements:[],...Array.isArray(e?.readiness?.liveUnavailableCapabilities)?e.readiness.liveUnavailableCapabilities.map(f=>`unavailable:${f}`):[],...Array.isArray(e?.cost?.blockers)?e.cost.blockers.map(f=>f?.code??"pricing"):[]];y(`Name: ${n}`),y(`Product: ${e?.productId??t}`),y(`Status: ${r}`),y(`Blueprint: ${a}`),y(`Monthly: ${s==null?"not returned":`${c} ${s}`}`),y(`Setup: ${l==null?"not returned":`${c} ${l}`}`),y(`Live: ${e?.readiness?.live===!0?"active":"not active"}`),y(`Live blockers: ${u.length>0?u.join(", "):"none"}`);for(let[f,v]of[["openapi","OpenAPI"],["mcp","MCP"],["sdk","SDK"],["graphql","GraphQL"]]){let x=e?.surfaces?.[f];x?.url&&y(`${v}: ${x.url}`)}y("Next:"),y(` hyperscale key create --name "Founder CLI" --product ${e?.productId??t}`)}async function Go(e,t,n){if(!n)throw new S("product select needs a Product id");let r=await ye(e,t),o=await fe(r,`/v1/products/${encodeURIComponent(n)}?${Yn(r.tenantId)}`,{},r.token,[r.token]);if(o?.productId!==n)throw new S("product.retrieve returned the wrong Product");await fn(t,{...r,selectedProduct:n});let a={productId:n,selected:!0};e["--json"]?se(a):y(`Selected Product: ${o.displayName??n} (${n})`)}function Mt(e,t){return t.map(n=>`${e}:${n.line}:${n.column}: ${n.severity} [${n.stage}] ${n.message}`)}function Xo(e){return e.map(t=>`${t.path}: error [composer] ${t.code}: ${t.message}`)}async function Zo(e){if(!e)throw new S("compose needs a .hsx file");if(!e.endsWith(".hsx"))throw new S(`compose reads a .hsx file, got ${e}`);let t;try{t=await ln(e,"utf8")}catch(r){throw new S(`Could not read ${e}: ${r.message}`)}let n=an(t);if(n.verdict==="invalid"||!n.artifacts){let r=[...n.diagnostics];throw new ze(["HSX compilation failed.",...Mt(e,r)].join(`
120
- `),{diagnostics:r,file:e,issues:[],verdict:n.verdict})}return{file:e,result:n,source:t}}function Qo(e){if(!e||typeof e!="object"||typeof e.ok!="boolean"||!Array.isArray(e.issues))throw new S("composer.check returned an invalid result");return{issues:e.issues.map(n=>{if(!n||typeof n!="object"||typeof n.code!="string"||typeof n.message!="string"||typeof n.path!="string")throw new S("composer.check returned an invalid issue");return{code:n.code,message:n.message,path:n.path}}),ok:e.ok}}async function Wn(e,t,n,r){let o=await Zo(n),a=await ye(e,t,!r);if(!a)return{check:{issues:[],ok:!0},compiled:o,context:null,productId:void 0};let c=r?Xe(a,e):void 0,s=Qo(await fe(a,"/v1/composer/check",ve({tenantId:a.tenantId,document:o.result.artifacts.document}),a.token,[a.token]));if(!s.ok){let l=[...o.result.diagnostics];throw new ze(["composer.check refused the program.",...Xo(s.issues)].join(`
119
+ `)}let a=Vr({input:process.stdin,output:process.stderr,terminal:!0}),c=new AbortController,s=()=>c.abort();process.stdin.once("end",s),process.stdin.readableEnded&&c.abort();let l;try{try{l=(await a.question("Choose a number or Blueprint slug: ",{signal:c.signal})).trim()}catch(v){throw v?.name!=="AbortError"&&v?.code!=="ABORT_ERR"?v:new I("Start cancelled before a Blueprint was chosen.",{code:"start_cancelled"})}}finally{process.stdin.off("end",s),a.close()}let u=Number(l),f=Number.isInteger(u)?r[u-1]:r.find(({id:v})=>v===l);if(f)return f;throw new I(`No Blueprint matches ${JSON.stringify(l)}.`,{fix:"Run hyperscale start again and choose a listed number or slug."})}function jo(e){if(!(!e||typeof e!="object")&&Array.isArray(e.journeys))for(let t of e.journeys){if(!t||typeof t!="object"||!Array.isArray(t.steps))continue;let n=t.steps[0];if(n?.status==="runnable"&&typeof n.operationId=="string"&&n.request&&typeof n.request=="object"&&Array.isArray(n.request.body)&&Array.isArray(n.request.path)&&Array.isArray(n.request.query)&&n.request.literals&&typeof n.request.literals=="object"&&!Array.isArray(n.request.literals)&&typeof t.id=="string")return{id:t.id,step:n}}}function Bo(e,t,n){if(e==="tenantId")return t.tenantId;if(e==="productId")return t.productId;if(e==="customerId")return t.fixtureProfileId;if(e==="currency")return t.fixtureCurrency;if(e==="subject"||e==="subjectId")return t.fixtureSubjects?.[0]?.subjectId;if(e.endsWith("AccountId")){let r=n.distinctPartyAccountFields?.indexOf(e);return r>=0&&(e==="buyerAccountId"||e==="claimantAccountId"||e==="policyholderAccountId")?t.fixtureCounterpartyAccountId:r>=0&&(e==="insurerAccountId"||e==="sellerAccountId")?t.fixtureAccountId:r>0?t.fixtureCounterpartyAccountId:t.fixtureAccountId}}var Jo=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/,Mo=6e4;function Jt(e){if(typeof e!="string"||!Jo.test(e))return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function Nn(e,t){let n=Jt(e);if(n!==void 0){t.push(n);return}if(Array.isArray(e)){for(let r of e)Nn(r,t);return}if(!(!e||typeof e!="object"))for(let r of Object.values(e))Nn(r,t)}function Ln(e,t){let n=Jt(e);return n!==void 0?new Date(n+t).toISOString():Array.isArray(e)?e.map(r=>Ln(r,t)):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).map(([r,o])=>[r,Ln(o,t)]))}function qo(e,t=Date.now()){let n=[];Nn(e,n);let r=Math.min(...n);return!Number.isFinite(r)||r>t?e:Ln(e,t+Mo-r)}function Uo(e,t){let n={...qo(e.request.literals)},r=[...e.request.path,...e.request.query,...e.request.body];for(let o of r){if(typeof o!="string"||Object.hasOwn(n,o))continue;let a=Bo(o,t,e);if(a===void 0)throw new I(`The frozen journey needs ${o}, but composition did not return a matching sandbox fixture.`,{code:"start_fixture_unavailable"});n[o]=a}return n}async function Ko(e,t,n){let r=await Hn(e),o=Vt(r.operations,t.operationId),a=Uo(t,n),{path:c,remaining:s}=Yt(o,a),l={method:o.method},u=c,f;o.method==="GET"?u+=Wt(s):(f=globalThis.crypto.randomUUID(),l.body=JSON.stringify(s),l.headers={"content-type":"application/json",...o.idempotency==="not_required"?{}:{"idempotency-key":f}});let v=await Ee(e,u,l);if(!v.response.ok)throw hn(v.response,v.text,[e.apiKey],{action:t.operationId});return{...f?{idempotencyKey:f}:{},input:a,operationId:t.operationId,output:dn(zt(v.text),[e.apiKey]),receipt:Bt(v.response)}}async function It(e,t){Do(e);let n={};try{await Ho(e,t,n)}catch(r){throw typeof n.apiKey!="string"?r:Oo(r,n.apiKey)}}async function Ho(e,t,n){let r=await ye(e,t),o=await Ce(r,r.token),a=await Lo(e,r),c=e["--name"]??a.name;e["--json"]||y(`Authenticated: ${o.email}`);let s=await jt(r,"/v1/products/blueprint-compose",ve({blueprintId:a.id,name:c,tenantId:r.tenantId}),r.token),l=Fo(s.response,s.text,[r.token]);if(typeof l?.productId!="string"||!lo.test(l.productId)||typeof l?.productBuildId!="string"||l?.blueprintId!==a.id)throw new I("product.blueprint.compose returned an invalid start Product");let u=l?.shown_once;if(typeof u!="string"||u.length===0)throw new I("The composed Product did not return its one-time API key. Choose a new Product name and run hyperscale start again.",{code:"start_api_key_unavailable"});n.apiKey=u;let f=Bt(s.response);await fn(t,{...r,selectedProduct:l.productId}),e["--json"]||(y(`Product: ${l.productId}`),y(`Blueprint: ${l.blueprintId}`),St("Compose",f));let v={baseUrl:r.baseUrl,environment:r.environment,apiKey:u,productId:l.productId},x=await Ee(v,`/v1/products/${encodeURIComponent(l.productId)}/operation-set`);if(!x.response.ok)throw hn(x.response,x.text,[u]);let k=Kt(x.text,x.response.status);if(k.status!=="frozen"||k.productBuildId!==l.productBuildId)throw new I("The composed Product did not return its frozen build operation set.",{code:"start_build_unavailable"});let T=[`hyperscale compose plan product.hsx --product ${l.productId}`],R=jo(k.goldenPath);if(!R){let B=`Blueprint ${a.id} has no published runnable journeys. Composition completed only.`,W={blueprintId:l.blueprintId,composeOnly:!0,nextCommands:T,notice:B,productBuildId:l.productBuildId,productId:l.productId,receipts:[{stage:"product.blueprint.compose",...f}],...typeof l.startKeyId=="string"?{startKeyId:l.startKeyId}:{},shown_once:u};if(e["--json"]){se(W);return}y(B),y(`Shown once Product API key: ${u}`),y("Next:");for(let H of T)y(` ${H}`);return}let C=await Ko(v,R.step,l);e["--json"]||St("First journey step",C.receipt);let Q={blueprintId:l.blueprintId,journey:{id:R.id,firstStep:C},nextCommands:T,productBuildId:l.productBuildId,productId:l.productId,receipts:[{stage:"product.blueprint.compose",...f},{stage:R.step.operationId,...C.receipt}],...typeof l.startKeyId=="string"?{startKeyId:l.startKeyId}:{},shown_once:u};if(e["--json"]){se(Q);return}C.output!==null&&y(JSON.stringify(C.output,null,2)),y(`Shown once Product API key: ${u}`),y("Next:");for(let B of T)y(` ${B}`)}async function zo(e,t){let n=e["--blueprint"],r=e["--name"];if(!n)throw new I("product create needs --blueprint <id>");if(!r)throw new I("product create needs --name <name>");let o=await ye(e,t),a;try{a=await Oe(o,"/v1/products",{tenantId:o.tenantId},"product.list",o.token,[o.token])}catch(v){if(!(v instanceof He)||v.status!==403)throw v}let c=r.trim().toLocaleLowerCase("en-US"),s=(a?Te(a,"product.list"):[]).find(v=>{let x=v?.displayName??v?.name;return typeof x=="string"&&x.trim().toLocaleLowerCase("en-US")===c});if(s){let v=s.productId??s.id??"<id>";throw new I(`A Product named ${JSON.stringify(r.trim())} already exists as ${v}.`,{code:"duplicate_product_name",fix:`Use "hyperscale product select ${v}" or choose another --name.`})}let l=await fe(o,"/v1/products/blueprint-compose",ve({blueprintId:n,name:r,tenantId:o.tenantId}),o.token,[o.token]);if(typeof l?.productId!="string"||typeof l?.blueprintId!="string"||typeof l?.productBuildId!="string")throw new I("product.blueprint.compose returned an invalid Product");await fn(t,{...o,selectedProduct:l.productId});let u=typeof l?.shown_once=="string"&&l.shown_once.length>0?l.shown_once:void 0,f={blueprintId:l.blueprintId,nextSteps:[`hyperscale product show ${l.productId}`,...u?[]:['hyperscale key create --name "Founder CLI"']],productBuildId:l.productBuildId,productId:l.productId,selectedProduct:l.productId,...typeof l.startKeyId=="string"?{startKeyId:l.startKeyId}:{},...u?{shown_once:u}:{}};if(e["--json"]){se(f);return}y(`Product: ${f.productId}`),y(`Blueprint: ${f.blueprintId}`),y(`Build: ${f.productBuildId}`),y(`Selected: ${f.selectedProduct}`),f.shown_once&&y(`Shown once Product API key: ${f.shown_once}`),y("Next:");for(let v of f.nextSteps)y(` ${v}`)}function Yn(e){return new URLSearchParams({tenantId:e}).toString()}async function Yo(e,t){let n=await ye(e,t),r=await Oe(n,"/v1/products",{tenantId:n.tenantId},"product.list",n.token,[n.token]),o=Te(r,"product.list");if(e["--json"]){se(r);return}if(o.length===0){y('No Products yet. Run "hyperscale blueprint list", then "hyperscale product create --blueprint <id> --name <name>".');return}y("ID Name Status");for(let a of o){let c=a.productId??a.id??"unknown",s=a.displayName??a.name??"unnamed";y(`${c} ${s}${a.status?` ${a.status}`:""}`)}}async function Wo(e,t,n){let r=await ye(e,t),o=n??r.selectedProduct;if(!o)throw new I("product show needs an id because no Product is selected. Create a Product first.");let a=await fe(r,`/v1/products/${encodeURIComponent(o)}?${Yn(r.tenantId)}`,{},r.token,[r.token]);if(e["--json"]){se(a);return}Vo(a,o)}function Vo(e,t){let n=e?.displayName??e?.name??"unnamed",r=e?.status??"unknown",o=e?.blueprint,a=o?.id?`${o.name??o.id}${o.name?` (${o.id})`:""}`:"custom composition",c=e?.cost?.currency??"SAR",s=e?.plan?.monthlySar??e?.cost?.platformMonthlySar,l=e?.plan?.setupSar??e?.cost?.platformSetupSar,u=[...Array.isArray(e?.readiness?.outstandingLiveRequirements)?e.readiness.outstandingLiveRequirements:[],...Array.isArray(e?.readiness?.liveUnavailableCapabilities)?e.readiness.liveUnavailableCapabilities.map(f=>`unavailable:${f}`):[],...Array.isArray(e?.cost?.blockers)?e.cost.blockers.map(f=>f?.code??"pricing"):[]];y(`Name: ${n}`),y(`Product: ${e?.productId??t}`),y(`Status: ${r}`),y(`Blueprint: ${a}`),y(`Monthly: ${s==null?"not returned":`${c} ${s}`}`),y(`Setup: ${l==null?"not returned":`${c} ${l}`}`),y(`Live: ${e?.readiness?.live===!0?"active":"not active"}`),y(`Live blockers: ${u.length>0?u.join(", "):"none"}`);for(let[f,v]of[["openapi","OpenAPI"],["mcp","MCP"],["sdk","SDK"],["graphql","GraphQL"]]){let x=e?.surfaces?.[f];x?.url&&y(`${v}: ${x.url}`)}y("Next:"),y(` hyperscale key create --name "Founder CLI" --product ${e?.productId??t}`)}async function Go(e,t,n){if(!n)throw new I("product select needs a Product id");let r=await ye(e,t),o=await fe(r,`/v1/products/${encodeURIComponent(n)}?${Yn(r.tenantId)}`,{},r.token,[r.token]);if(o?.productId!==n)throw new I("product.retrieve returned the wrong Product");await fn(t,{...r,selectedProduct:n});let a={productId:n,selected:!0};e["--json"]?se(a):y(`Selected Product: ${o.displayName??n} (${n})`)}function Mt(e,t){return t.map(n=>`${e}:${n.line}:${n.column}: ${n.severity} [${n.stage}] ${n.message}`)}function Xo(e){return e.map(t=>`${t.path}: error [composer] ${t.code}: ${t.message}`)}async function Zo(e){if(!e)throw new I("compose needs a .hsx file");if(!e.endsWith(".hsx"))throw new I(`compose reads a .hsx file, got ${e}`);let t;try{t=await ln(e,"utf8")}catch(r){throw new I(`Could not read ${e}: ${r.message}`)}let n=an(t);if(n.verdict==="invalid"||!n.artifacts){let r=[...n.diagnostics];throw new ze(["HSX compilation failed.",...Mt(e,r)].join(`
120
+ `),{diagnostics:r,file:e,issues:[],verdict:n.verdict})}return{file:e,result:n,source:t}}function Qo(e){if(!e||typeof e!="object"||typeof e.ok!="boolean"||!Array.isArray(e.issues))throw new I("composer.check returned an invalid result");return{issues:e.issues.map(n=>{if(!n||typeof n!="object"||typeof n.code!="string"||typeof n.message!="string"||typeof n.path!="string")throw new I("composer.check returned an invalid issue");return{code:n.code,message:n.message,path:n.path}}),ok:e.ok}}async function Wn(e,t,n,r){let o=await Zo(n),a=await ye(e,t,!r);if(!a)return{check:{issues:[],ok:!0},compiled:o,context:null,productId:void 0};let c=r?Xe(a,e):void 0,s=Qo(await fe(a,"/v1/composer/check",ve({tenantId:a.tenantId,document:o.result.artifacts.document}),a.token,[a.token]));if(!s.ok){let l=[...o.result.diagnostics];throw new ze(["composer.check refused the program.",...Xo(s.issues)].join(`
121
121
  `),{diagnostics:l,file:n,issues:s.issues,verdict:o.result.verdict})}return{check:s,compiled:o,context:a,productId:c}}function Vn(e,t){for(let n of Mt(e,t.diagnostics))process.stderr.write(`${n}
122
- `)}async function ea(e,t,n){let r=await Wn(e,t,n,!1);if(e["--json"]){se({command:"composer.check",diagnostics:r.compiled.result.diagnostics,file:n,issues:r.check.issues,ok:!0,verdict:r.compiled.result.verdict});return}Vn(n,r.compiled.result),y(`Check passed: ${n}`)}async function qt(e,t){let n=await fe(e.context,"/v1/composer/plan",ve({document:e.compiled.result.artifacts.document,tenantId:e.context.tenantId,productId:e.productId}),e.context.token,[e.context.token]);if(!n||typeof n!="object"||typeof n.summary!="string"||!Array.isArray(n.actions)||!n.pricing||typeof n.pricing!="object")throw new S("composer.plan returned an invalid result");let r=n.actions.filter(o=>!o||typeof o!="object"||o.kind!=="configure_product");if(r.length>0)throw new ze([n.summary,...r.map(o=>o&&typeof o=="object"?`${o.kind??"unknown"} ${o.target??"unknown"} ${o.detail??"Composer refused this action."}`:"unknown unknown Composer returned an invalid refusal action.")].join(`
123
- `),{actions:r,file:t,productId:e.productId});return n}async function na(e,t,n){let r=await Wn(e,t,n,!0),o=await qt(r,n);if(e["--json"]){se({command:"composer.plan",diagnostics:r.compiled.result.diagnostics,file:n,plan:o,productId:r.productId});return}Vn(n,r.compiled.result),y(o.summary);for(let a of o.actions)y(`${a.kind} ${a.target} ${a.detail}`);y(`Monthly: SAR ${o.pricing.monthlySar}`),y(`Activation: SAR ${o.pricing.activationSar}`)}function ta(e){if(!Array.isArray(e.instruments))throw new S("The HSX compiler returned no instrument list");let t=e.instruments.map(n=>n&&typeof n=="object"?n.id:void 0);if(t.length===0||t.some(n=>typeof n!="string"||n.length===0)||new Set(t).size!==t.length)throw new S("The HSX compiler returned invalid instrument identities");return t}async function ra(e,t,n){if(!e["--confirm"]&&!e["--yes"])throw new S("compose apply changes the selected Product. Pass --confirm, or --yes for an agent.");let r=await Wn(e,t,n,!0);await qt(r,n);let o=r.compiled.result.artifacts.document,a=await fe(r.context,"/v1/products/recompose",ve({instrumentIds:ta(o),program:{frame:r.compiled.result.artifacts.frame,source:JSON.stringify(o)},tenantId:r.context.tenantId,productId:r.productId},e["--idempotency-key"]),r.context.token,[r.context.token]);if(!a||typeof a.productBuildId!="string")throw new S("product.recompose returned no new build identity");if(e["--json"]){se({command:"product.recompose",diagnostics:r.compiled.result.diagnostics,file:n,output:a});return}Vn(n,r.compiled.result),y(`Product: ${a.productId??r.productId}`),y(`Build: ${a.productBuildId}`),a.buildDigest&&y(`Digest: ${a.buildDigest}`)}function Xe(e,t){let n=t["--product"]??e.selectedProduct;if(!n)throw new S("No Product selected. Pass --product <id> or create a Product first.");return n}async function cn(e,t,n){let r=await mn(t),o=Xe(r??{},e),a=Ye(e,t,r??{});if(r&&(a.baseUrl!==r.baseUrl||a.environment!==r.environment))throw new S(`The selected Product belongs to ${r.baseUrl} (${r.environment}). Select a Product at the configured API origin first.`);let c=e["--api-key"]??t.HYPERSCALE_API_KEY;if(!c)throw Et(o);let s={...a,apiKey:c,productId:o};return await oa(s,o,n),s}async function oa(e,t,n){let{response:r,text:o}=await Te(e,"/v1/products?limit=2",{},n);if(!r.ok)throw Ge(r,o,[e.apiKey]);let a;try{a=JSON.parse(o)}catch{throw new S(`HTTP ${r.status} returned invalid JSON`)}let c=Pe(a,"product.list"),s=c[0]?.productId;if(c.length!==1||typeof s!="string")throw new S("product.list did not identify exactly one Product for this Product API key.");if(s!==t)throw new S(`This Product API key belongs to ${s}, but this command targets ${t}. Set HYPERSCALE_API_KEY to a key for ${t}, or pass that key with --api-key.`)}async function Ut(e,t){let n=`/v1/products/${encodeURIComponent(e.productId)}/operation-set`,{response:r,text:o}=await Te(e,n,{},t);if(!r.ok)throw hn(r,o,[e.apiKey]);return Kt(o,r.status)}async function aa(e,t,n){let r=await cn(e,t),o=await Ut(r);if(n){ia(o,n,e);return}if(e["--json"]){se(o);return}if(o.status==="legacy"){y("This Product uses a legacy surface. It has no frozen public actions yet."),y(`Build: ${o.productBuildId}`);return}if(o.publicActions.length===0)y("No public actions");else{y("Operation ID Input Kind");for(let a of o.publicActions){let c=a.idempotencyPolicy?.mode==="not_required"?"read-only":"mutation";y(`${a.instrument}.${a.name} ${da(a.inputSchema)} ${c}`)}}if(o.setupOperations.length>0){y("Setup operations (run with hyperscale call)");for(let a of o.setupOperations)y(a.operationName)}if(o.readOperationIds.length>0){y("Reads (run with hyperscale call)");for(let a of o.readOperationIds)y(ca(a))}y(`Digest: ${o.tenantOperationSetDigest}`),y(`Setup digest: ${o.tenantSetupOperationSetDigest}`),y(`Read digest: ${o.tenantReadOperationSetDigest}`),y(`Build: ${o.productBuildId}`),y(`Surface version: ${o.tenantSurfaceVersion}`)}function ia(e,t,n){if(e.status==="legacy")throw new S(`This Product uses a legacy surface and has no frozen public action named ${t}. Run "hyperscale product actions" after rebuilding the Product.`);let r=e.publicActions.find(s=>s&&`${s.instrument}.${s.name}`===t),o=sa(t),a=e.setupOperations.find(s=>s&&(s.operationId===t||s.operationId===o||s.operationName===t));if(a){let{inputSchema:s,operationId:l,operationName:u}=a,f={status:e.status,productBuildId:e.productBuildId,tenantSurfaceVersion:e.tenantSurfaceVersion,tenantSetupOperationSetDigest:e.tenantSetupOperationSetDigest,setupOperationId:l,operationName:u,command:`hyperscale call ${u}`,inputSchema:s};if(n["--json"]){se(f);return}y(`Operation ID: ${l}`),y(`Operation name: ${u}`),y(`Run: hyperscale call ${u}`),y(`Input schema: ${JSON.stringify(s,null,2)}`),(!Array.isArray(s.required)||s.required.length===0)&&y("Input: omit --input or pass {}."),y(`Setup digest: ${e.tenantSetupOperationSetDigest}`),y(`Build: ${e.productBuildId}`),y(`Surface version: ${e.tenantSurfaceVersion}`);return}if(!r)throw new S(`Unknown frozen public action: ${t}. Run "hyperscale product actions" to list exact names.`);let c={status:e.status,productBuildId:e.productBuildId,tenantSurfaceVersion:e.tenantSurfaceVersion,tenantOperationSetDigest:e.tenantOperationSetDigest,publicAction:r};if(n["--json"]){se(c);return}y(`Operation ID: ${r.instrument}.${r.name}`),y(`Instrument: ${r.instrument}`),y(`Input schema: ${JSON.stringify(r.inputSchema,null,2)}`),y(`Output schema: ${JSON.stringify(r.outputSchema,null,2)}`),y(`Actor policy: ${JSON.stringify(r.actorPolicy,null,2)}`),y(`Port policy: ${JSON.stringify(r.portPolicy,null,2)}`),y(`Idempotency policy: ${JSON.stringify(r.idempotencyPolicy,null,2)}`),y(`Receipt policy: ${JSON.stringify(r.receiptPolicy,null,2)}`),y(`Receipt evidence: ${JSON.stringify(r.receiptEvidence,null,2)}`),y(`Digest: ${e.tenantOperationSetDigest}`),y(`Build: ${e.productBuildId}`),y(`Surface version: ${e.tenantSurfaceVersion}`)}function Kt(e,t){let n;try{n=JSON.parse(e)}catch{throw new S(`HTTP ${t} returned invalid JSON`)}if(!n||typeof n!="object"||n.status!=="legacy"&&n.status!=="frozen"||typeof n.productBuildId!="string")throw new S("The Product operation set is not in the expected format. Upgrade the CLI.");if(n.status==="legacy")return n;if(typeof n.tenantSurfaceVersion!="number"||typeof n.tenantOperationSetDigest!="string"||typeof n.tenantReadOperationSetDigest!="string"||typeof n.tenantSetupOperationSetDigest!="string"||!Array.isArray(n.publicActions)||!Array.isArray(n.readOperationIds)||!Array.isArray(n.setupOperationIds)||!Array.isArray(n.setupOperations))throw new S("The Product operation set is not in the expected format. Upgrade the CLI.");return n}function sa(e){return e.replaceAll(".","_")}function ca(e){for(let t of["create","list","retrieve"]){let n=`_${t}`;if(e.endsWith(n))return`${e.slice(0,-n.length)}.${t}`}return e}function da(e){if(!e||typeof e!="object")return"input schema unavailable";let t=e.properties&&typeof e.properties=="object"&&!Array.isArray(e.properties)?e.properties:{},n=new Set(Array.isArray(e.required)?e.required.filter(o=>typeof o=="string"):[]),r=Object.entries(t).map(([o,a])=>`${o}${n.has(o)?"":"?"}: ${Ht(a)}`);return r.length===0?"no input":r.join(", ")}function Ht(e){return!e||typeof e!="object"?"value":Array.isArray(e.enum)&&e.enum.length>0?e.enum.map(t=>String(t)).join(" | "):e.type==="array"?`${Ht(e.items)}[]`:typeof e.type=="string"?typeof e.format=="string"?`${e.type} (${e.format})`:e.type:"value"}async function la(e,t,n){if(!n)throw new S("product run needs a public action");let r=await cn(e,t,n),o=await Ut(r,n);ua(o,n);let a=await Gt(e),c=e["--idempotency-key"]??globalThis.crypto.randomUUID(),{response:s,text:l}=await Te(r,`/v1/operations/${encodeURIComponent(n)}`,{body:JSON.stringify(a),headers:{"content-type":"application/json","idempotency-key":c},method:"POST"},n);if(!s.ok)throw hn(s,l,[r.apiKey],{action:n});let u=s.headers.get("hyperscale-operation-id"),f=s.headers.get("hyperscale-receipt-id");if(e["--json"]){se({idempotencyKey:c,operationId:u,receiptId:f,output:zt(l)});return}y(`Operation: ${u??"not returned"}`),y(`Receipt: ${f??"not returned"}`),y(`Idempotency key: ${c}`);let v=Xt(l);v&&y(v)}function ua(e,t){if(e.status==="legacy")throw new S(`This Product uses a legacy surface and has no frozen public action named ${t}. Run "hyperscale product actions" after rebuilding the Product.`);let n=e.publicActions.find(o=>o&&`${o.instrument}.${o.name}`===t);if(n)return n;let r=e.publicActions.map(o=>`${o.instrument}.${o.name}`).map(o=>({candidate:o,distance:Bn(t,o)})).sort((o,a)=>o.distance-a.distance||o.candidate.localeCompare(a.candidate)).slice(0,3).map(({candidate:o})=>o);throw new S(`Unknown frozen public action: ${t}. Closest valid names: ${r.join(", ")}. Run "hyperscale product actions" to list exact names.`)}function zt(e){if(e.trim()==="")return null;try{return JSON.parse(e)}catch{return e}}function hn(e,t,n=[],r={}){let o=xe(t.trim(),n),a;try{a=JSON.parse(t)}catch{return new S(`HTTP ${e.status}${o?` \xB7 ${o}`:""}`)}if(!a?.error||typeof a.error.message!="string")return new S(`HTTP ${e.status}`);let c=typeof a.error.code=="string"?a.error.code:"user_error",s=c==="user_error"?"":`${c}: `,l=xe(`HTTP ${e.status} \xB7 ${s}${a.error.message}`,n),u=pa(a.error.details,n),f;return c==="idempotency_conflict"?f="Reuse the same key only with the same operation and input. Use a new unique key for a different request.":[a.error.message,...u].some(v=>typeof v=="string"&&v.includes("[Truncated]"))&&r.action&&(f=`Run "hyperscale product actions ${r.action}" to read the full input schema and allowed values.`),new S([l,...u].join(`
124
- `),{code:c,...a.error.details?{details:dn(a.error.details,n)}:{},...f?{fix:f}:{}})}function dn(e,t){return typeof e=="string"?xe(e,t):Array.isArray(e)?e.map(n=>dn(n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,r])=>[xe(n,t),dn(r,t)])):e}function pa(e,t){if(!e||typeof e!="object")return[];if(Array.isArray(e.issues))return e.issues.flatMap(r=>{if(!r||typeof r!="object")return[];let a=(Array.isArray(r.path)?r.path.join("."):"input")||"input";return typeof r.message=="string"?[`${a}: ${xe(r.message,t)}`]:[]});let n=[];return jn(e,"",n,t),n}function jn(e,t,n,r){if(Array.isArray(e)){if(e.every(o=>o===null||typeof o!="object")){n.push(`${Pt(t)}: ${xe(e.join(", "),r)}`);return}e.forEach((o,a)=>jn(o,`${t}[${a}]`,n,r));return}if(e&&typeof e=="object"){for(let[o,a]of Object.entries(e))jn(a,t?`${t}.${o}`:o,n,r);return}t&&n.push(`${Pt(t)}: ${xe(String(e),r)}`)}function Pt(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replaceAll("."," ");return t.charAt(0).toUpperCase()+t.slice(1)}async function ma(e,t){let n=await ye(e,t),r=Xe(n,e),o=await fe(n,"/v1/sandbox-api-keys",ve({name:e["--name"]??"Founder CLI",tenantId:n.tenantId,productId:r}),n.token,[n.token]);if(e["--json"]){se(o);return}y(`Key: ${o.apiKeyId??"unknown"}`),y(`Product: ${o.productId??r}`),y(`Status: ${o.status??"unknown"}`),o.secret?(y(`Secret: ${o.secret}`),y("Store it now. Hyperscale will not return it again."),y("Next:"),y(` export HYPERSCALE_API_KEY=${fa(o.secret)}`),y(` hyperscale product actions --product ${r}`)):y("The key already existed, so the one-time secret is unavailable.")}function fa(e){return`'${String(e).replaceAll("'",`'"'"'`)}'`}async function ya(e,t){let n=await ye(e,t),r=Xe(n,e),o=await Oe(n,"/v1/api-keys",{tenantId:n.tenantId},"api_key.list",n.token,[n.token]),a=Pe(o,"api_key.list").filter(s=>s.productId===r),c={...o,items:a};if(e["--json"]){se(c);return}for(let s of a)y(`${s.apiKeyId} ${s.name??"unnamed"} ${s.status??"unknown"}`)}async function ha(e,t,n){if(!n)throw new S("key revoke needs an API key id");let r=await ye(e,t),o=Xe(r,e),a=await fe(r,`/v1/api-keys/${encodeURIComponent(n)}/revoke`,ve({tenantId:r.tenantId,productId:o}),r.token,[r.token]);e["--json"]?se(a):y(`Key ${a.apiKeyId??n}: ${a.status??"revoked"}`)}async function ga(e,t){let n=await ye(e,t),r=n.identity??await Ee(n,n.token),o=zn(n,r);if(e["--json"]){se(o);return}y(`User: ${r.email}`),y(`Tenant: ${r.tenantId}`),y(`Role: ${r.role}`),y(`Token: ${r.name}`),y(`Expires: ${r.expiresAt}`)}async function $a(e,t,n){let r=await Hn(e),o=n?n.toLowerCase():null,a=o?r.operations.filter(s=>s.name.toLowerCase().includes(o)||s.path.toLowerCase().includes(o)):r.operations;if(t["--json"]){y(JSON.stringify(a,null,2));return}if(a.length===0){y(n?`No operation matches ${n}`:"No operations");return}let c=Math.max(...a.map(s=>s.name.length));for(let s of a)y(`${s.name.padEnd(c)} ${s.method.padEnd(6)}${s.path}`)}async function ba(e,t){let n=await ye(e,t),r=await fe(n,`/v1/team/members?${Yn(n.tenantId)}`,{},n.token,[n.token]);if(!r||typeof r!="object"||!Array.isArray(r.members)||!Array.isArray(r.invitations))throw new S("team.member.list returned invalid data");if(e["--json"]){se(r);return}for(let o of r.members)y(`${o.email??"unknown"} ${o.role??"unknown"} ${o.status??"unknown"}`);for(let o of r.invitations)y(`${o.email??"unknown"} ${o.role??"unknown"} pending invitation`)}async function wa(e,t){let n=e["--email"],r=e["--role"];if(!n)throw new S("team invite needs --email <email>");if(!r)throw new S("team invite needs --role <role>");let o=await ye(e,t),a=await fe(o,"/v1/team/members/invite",ve({email:n,role:r,tenantId:o.tenantId}),o.token,[o.token]);if(e["--json"]){se(a);return}y(`Invitation: ${a.invitationId??"unknown"}`),y(`Email: ${a.email??n}`),y(`Role: ${a.role??r}`),y(`Expires: ${a.expiresAt??"unknown"}`),a.inviteToken&&(y(`Invite token: ${a.inviteToken}`),y("Share it now. Hyperscale will not return it again."))}async function va(e,t){let n=await ye(e,t),r=await Oe(n,"/v1/activity",{tenantId:n.tenantId},"activity.list",n.token,[n.token]),o=Pe(r,"activity.list");if(e["--json"]){se(r);return}y("Time Activity Target Status");for(let a of o){let c=a.operation??a.auditEvent??"activity",s=a.resourceKind&&a.resourceId?`${a.resourceKind}:${a.resourceId}`:a.resourceKind??a.resourceId??"-";y(`${a.occurredAt??"unknown"} ${c} ${s} ${a.status??"recorded"}`)}}function Yt(e,t){let n={...t},r=[],o=e.path.replace(/\{([^}]+)\}/g,(a,c)=>{let s=n[c];return s==null?(r.push(c),""):(delete n[c],encodeURIComponent(String(s)))});if(r.length>0)throw new S(`${e.name} needs ${r.join(", ")} in --input`);return{path:o,remaining:n}}function Wt(e){let t=new URLSearchParams;for(let[r,o]of Object.entries(e))o!=null&&t.set(r,typeof o=="string"?o:JSON.stringify(o));let n=t.toString();return n?`?${n}`:""}function Bn(e,t){let n=Array.from({length:t.length+1},(r,o)=>o);for(let r=1;r<=e.length;r+=1){let o=[r];for(let a=1;a<=t.length;a+=1)o[a]=Math.min(o[a-1]+1,n[a]+1,n[a-1]+(e[r-1]===t[a-1]?0:1));n.splice(0,n.length,...o)}return n[t.length]}function Vt(e,t){let n=e.find(a=>a.name===t);if(n)return n;let r=e.filter(a=>a.operationId===t);if(r.length===1)return r[0];if(r.length>1)throw new S(`${t} matches more than one operation. Use one of: ${r.map(a=>a.name).join(", ")}.`);let o=e.map(a=>({candidate:a,distance:Math.min(Bn(t,a.name),Bn(t,a.operationId))})).sort((a,c)=>a.distance-c.distance||a.candidate.name.localeCompare(c.candidate.name)).slice(0,3).flatMap(({candidate:a})=>[a.name,a.operationId]);throw new S(`${t} is not an operation in the selected Product's machine document. Closest valid names: ${o.join(", ")}.`)}async function ka(e,t,n){if(!n)throw new S("call needs an operation name");let r=await Hn(e),o=Vt(r.operations,n),a=await Gt(t),{path:c,remaining:s}=Yt(o,a),l={method:o.method},u=c;o.method==="GET"?u+=Wt(s):(l.body=JSON.stringify(s),l.headers={"content-type":"application/json",...o.idempotency==="not_required"?{}:{"idempotency-key":t["--idempotency-key"]??globalThis.crypto.randomUUID()}});let{response:f,text:v}=await Te(e,u,l);if(!f.ok)throw Ge(f,v,[e.apiKey]);y(Xt(v))}async function Gt(e){if(e["--input"]!==void 0&&e["--input-file"]!==void 0)throw new S("Use only one of --input and --input-file");if(e["--input"]!==void 0)return Tn(e["--input"],"--input");if(e["--input-file"]!==void 0){let t;try{t=await ln(e["--input-file"],"utf8")}catch(n){throw new S(`Could not read ${e["--input-file"]}: ${n.message}`)}return Tn(t,"--input-file")}if(!process.stdin.isTTY){let t=await wo();if(t.trim()!=="")return Tn(t,"stdin")}return{}}function Tn(e,t="--input"){if(e===void 0)return{};let n;try{n=JSON.parse(e)}catch(r){throw new S(`${t} is not valid JSON: ${r.message}`)}if(n===null||typeof n!="object"||Array.isArray(n))throw new S(`${t} must be a JSON object`);return n}function Xt(e){if(e.trim()==="")return"";try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function y(e){process.stdout.write(`${e}
125
- `)}function se(e){y(JSON.stringify(e,null,2))}function _a(e,t){let n=e instanceof S&&typeof e.shownOnce=="string"?e.shownOnce:void 0;if(!t.includes("--json")){let a=e instanceof S?e.message:e.stack??String(e),c=e instanceof S&&typeof e.fix=="string"?`
122
+ `)}async function ea(e,t,n){let r=await Wn(e,t,n,!1);if(e["--json"]){se({command:"composer.check",diagnostics:r.compiled.result.diagnostics,file:n,issues:r.check.issues,ok:!0,verdict:r.compiled.result.verdict});return}Vn(n,r.compiled.result),y(`Check passed: ${n}`)}async function qt(e,t){let n=await fe(e.context,"/v1/composer/plan",ve({document:e.compiled.result.artifacts.document,tenantId:e.context.tenantId,productId:e.productId}),e.context.token,[e.context.token]);if(!n||typeof n!="object"||typeof n.summary!="string"||!Array.isArray(n.actions)||!n.pricing||typeof n.pricing!="object")throw new I("composer.plan returned an invalid result");let r=n.actions.filter(o=>!o||typeof o!="object"||o.kind!=="configure_product");if(r.length>0)throw new ze([n.summary,...r.map(o=>o&&typeof o=="object"?`${o.kind??"unknown"} ${o.target??"unknown"} ${o.detail??"Composer refused this action."}`:"unknown unknown Composer returned an invalid refusal action.")].join(`
123
+ `),{actions:r,file:t,productId:e.productId});return n}async function na(e,t,n){let r=await Wn(e,t,n,!0),o=await qt(r,n);if(e["--json"]){se({command:"composer.plan",diagnostics:r.compiled.result.diagnostics,file:n,plan:o,productId:r.productId});return}Vn(n,r.compiled.result),y(o.summary);for(let a of o.actions)y(`${a.kind} ${a.target} ${a.detail}`);y(`Monthly: SAR ${o.pricing.monthlySar}`),y(`Activation: SAR ${o.pricing.activationSar}`)}function ta(e){if(!Array.isArray(e.instruments))throw new I("The HSX compiler returned no instrument list");let t=e.instruments.map(n=>n&&typeof n=="object"?n.id:void 0);if(t.length===0||t.some(n=>typeof n!="string"||n.length===0)||new Set(t).size!==t.length)throw new I("The HSX compiler returned invalid instrument identities");return t}async function ra(e,t,n){if(!e["--confirm"]&&!e["--yes"])throw new I("compose apply changes the selected Product. Pass --confirm, or --yes for an agent.");let r=await Wn(e,t,n,!0);await qt(r,n);let o=r.compiled.result.artifacts.document,a=await fe(r.context,"/v1/products/recompose",ve({instrumentIds:ta(o),program:{frame:r.compiled.result.artifacts.frame,source:JSON.stringify(o)},tenantId:r.context.tenantId,productId:r.productId},e["--idempotency-key"]),r.context.token,[r.context.token]);if(!a||typeof a.productBuildId!="string")throw new I("product.recompose returned no new build identity");if(e["--json"]){se({command:"product.recompose",diagnostics:r.compiled.result.diagnostics,file:n,output:a});return}Vn(n,r.compiled.result),y(`Product: ${a.productId??r.productId}`),y(`Build: ${a.productBuildId}`),a.buildDigest&&y(`Digest: ${a.buildDigest}`)}function Xe(e,t){let n=t["--product"]??e.selectedProduct;if(!n)throw new I("No Product selected. Pass --product <id> or create a Product first.");return n}async function cn(e,t,n){let r=await mn(t),o=Xe(r??{},e),a=Ye(e,t,r??{});if(r&&(a.baseUrl!==r.baseUrl||a.environment!==r.environment))throw new I(`The selected Product belongs to ${r.baseUrl} (${r.environment}). Select a Product at the configured API origin first.`);let c=e["--api-key"]??t.HYPERSCALE_API_KEY;if(!c)throw Et(o);let s={...a,apiKey:c,productId:o};return await oa(s,o,n),s}async function oa(e,t,n){let r=`/v1/products/${encodeURIComponent(t)}/operation-set`,{response:o,text:a}=await Ee(e,r,{},n);if(o.ok)return;let c;try{c=JSON.parse(a)?.error?.message}catch{c=void 0}throw typeof c=="string"&&c.includes("does not match API key Product")?new I(`${c} Or set HYPERSCALE_API_KEY to a key for ${t}, or pass that key with --api-key.`):Ge(o,a,[e.apiKey])}async function Ut(e,t){let n=`/v1/products/${encodeURIComponent(e.productId)}/operation-set`,{response:r,text:o}=await Ee(e,n,{},t);if(!r.ok)throw hn(r,o,[e.apiKey]);return Kt(o,r.status)}async function aa(e,t,n){let r=await cn(e,t),o=await Ut(r);if(n){ia(o,n,e);return}if(e["--json"]){se(o);return}if(o.status==="legacy"){y("This Product uses a legacy surface. It has no frozen public actions yet."),y(`Build: ${o.productBuildId}`);return}if(o.publicActions.length===0)y("No public actions");else{y("Operation ID Input Kind");for(let a of o.publicActions){let c=a.idempotencyPolicy?.mode==="not_required"?"read-only":"mutation";y(`${a.instrument}.${a.name} ${da(a.inputSchema)} ${c}`)}}if(o.setupOperations.length>0){y("Setup operations (run with hyperscale call)");for(let a of o.setupOperations)y(a.operationName)}if(o.readOperationIds.length>0){y("Reads (run with hyperscale call)");for(let a of o.readOperationIds)y(ca(a))}y(`Digest: ${o.tenantOperationSetDigest}`),y(`Setup digest: ${o.tenantSetupOperationSetDigest}`),y(`Read digest: ${o.tenantReadOperationSetDigest}`),y(`Build: ${o.productBuildId}`),y(`Surface version: ${o.tenantSurfaceVersion}`)}function ia(e,t,n){if(e.status==="legacy")throw new I(`This Product uses a legacy surface and has no frozen public action named ${t}. Run "hyperscale product actions" after rebuilding the Product.`);let r=e.publicActions.find(s=>s&&`${s.instrument}.${s.name}`===t),o=sa(t),a=e.setupOperations.find(s=>s&&(s.operationId===t||s.operationId===o||s.operationName===t));if(a){let{inputSchema:s,operationId:l,operationName:u}=a,f={status:e.status,productBuildId:e.productBuildId,tenantSurfaceVersion:e.tenantSurfaceVersion,tenantSetupOperationSetDigest:e.tenantSetupOperationSetDigest,setupOperationId:l,operationName:u,command:`hyperscale call ${u}`,inputSchema:s};if(n["--json"]){se(f);return}y(`Operation ID: ${l}`),y(`Operation name: ${u}`),y(`Run: hyperscale call ${u}`),y(`Input schema: ${JSON.stringify(s,null,2)}`),(!Array.isArray(s.required)||s.required.length===0)&&y("Input: omit --input or pass {}."),y(`Setup digest: ${e.tenantSetupOperationSetDigest}`),y(`Build: ${e.productBuildId}`),y(`Surface version: ${e.tenantSurfaceVersion}`);return}if(!r)throw new I(`Unknown frozen public action: ${t}. Run "hyperscale product actions" to list exact names.`);let c={status:e.status,productBuildId:e.productBuildId,tenantSurfaceVersion:e.tenantSurfaceVersion,tenantOperationSetDigest:e.tenantOperationSetDigest,publicAction:r};if(n["--json"]){se(c);return}y(`Operation ID: ${r.instrument}.${r.name}`),y(`Instrument: ${r.instrument}`),y(`Input schema: ${JSON.stringify(r.inputSchema,null,2)}`),y(`Output schema: ${JSON.stringify(r.outputSchema,null,2)}`),y(`Actor policy: ${JSON.stringify(r.actorPolicy,null,2)}`),y(`Port policy: ${JSON.stringify(r.portPolicy,null,2)}`),y(`Idempotency policy: ${JSON.stringify(r.idempotencyPolicy,null,2)}`),y(`Receipt policy: ${JSON.stringify(r.receiptPolicy,null,2)}`),y(`Receipt evidence: ${JSON.stringify(r.receiptEvidence,null,2)}`),y(`Digest: ${e.tenantOperationSetDigest}`),y(`Build: ${e.productBuildId}`),y(`Surface version: ${e.tenantSurfaceVersion}`)}function Kt(e,t){let n;try{n=JSON.parse(e)}catch{throw new I(`HTTP ${t} returned invalid JSON`)}if(!n||typeof n!="object"||n.status!=="legacy"&&n.status!=="frozen"||typeof n.productBuildId!="string")throw new I("The Product operation set is not in the expected format. Upgrade the CLI.");if(n.status==="legacy")return n;if(typeof n.tenantSurfaceVersion!="number"||typeof n.tenantOperationSetDigest!="string"||typeof n.tenantReadOperationSetDigest!="string"||typeof n.tenantSetupOperationSetDigest!="string"||!Array.isArray(n.publicActions)||!Array.isArray(n.readOperationIds)||!Array.isArray(n.setupOperationIds)||!Array.isArray(n.setupOperations))throw new I("The Product operation set is not in the expected format. Upgrade the CLI.");return n}function sa(e){return e.replaceAll(".","_")}function ca(e){for(let t of["create","list","retrieve"]){let n=`_${t}`;if(e.endsWith(n))return`${e.slice(0,-n.length)}.${t}`}return e}function da(e){if(!e||typeof e!="object")return"input schema unavailable";let t=e.properties&&typeof e.properties=="object"&&!Array.isArray(e.properties)?e.properties:{},n=new Set(Array.isArray(e.required)?e.required.filter(o=>typeof o=="string"):[]),r=Object.entries(t).map(([o,a])=>`${o}${n.has(o)?"":"?"}: ${Ht(a)}`);return r.length===0?"no input":r.join(", ")}function Ht(e){return!e||typeof e!="object"?"value":Array.isArray(e.enum)&&e.enum.length>0?e.enum.map(t=>String(t)).join(" | "):e.type==="array"?`${Ht(e.items)}[]`:typeof e.type=="string"?typeof e.format=="string"?`${e.type} (${e.format})`:e.type:"value"}async function la(e,t,n){if(!n)throw new I("product run needs a public action");let r=await cn(e,t,n),o=await Ut(r,n);ua(o,n);let a=await Gt(e),c=e["--idempotency-key"]??globalThis.crypto.randomUUID(),{response:s,text:l}=await Ee(r,`/v1/operations/${encodeURIComponent(n)}`,{body:JSON.stringify(a),headers:{"content-type":"application/json","idempotency-key":c},method:"POST"},n);if(!s.ok)throw hn(s,l,[r.apiKey],{action:n});let u=s.headers.get("hyperscale-operation-id"),f=s.headers.get("hyperscale-receipt-id");if(e["--json"]){se({idempotencyKey:c,operationId:u,receiptId:f,output:zt(l)});return}y(`Operation: ${u??"not returned"}`),y(`Receipt: ${f??"not returned"}`),y(`Idempotency key: ${c}`);let v=Xt(l);v&&y(v)}function ua(e,t){if(e.status==="legacy")throw new I(`This Product uses a legacy surface and has no frozen public action named ${t}. Run "hyperscale product actions" after rebuilding the Product.`);let n=e.publicActions.find(o=>o&&`${o.instrument}.${o.name}`===t);if(n)return n;let r=e.publicActions.map(o=>`${o.instrument}.${o.name}`).map(o=>({candidate:o,distance:Bn(t,o)})).sort((o,a)=>o.distance-a.distance||o.candidate.localeCompare(a.candidate)).slice(0,3).map(({candidate:o})=>o);throw new I(`Unknown frozen public action: ${t}. Closest valid names: ${r.join(", ")}. Run "hyperscale product actions" to list exact names.`)}function zt(e){if(e.trim()==="")return null;try{return JSON.parse(e)}catch{return e}}function hn(e,t,n=[],r={}){let o=xe(t.trim(),n),a;try{a=JSON.parse(t)}catch{return new I(`HTTP ${e.status}${o?` \xB7 ${o}`:""}`)}if(!a?.error||typeof a.error.message!="string")return new I(`HTTP ${e.status}`);let c=typeof a.error.code=="string"?a.error.code:"user_error",s=c==="user_error"?"":`${c}: `,l=xe(`HTTP ${e.status} \xB7 ${s}${a.error.message}`,n),u=pa(a.error.details,n),f;return c==="idempotency_conflict"?f="Reuse the same key only with the same operation and input. Use a new unique key for a different request.":[a.error.message,...u].some(v=>typeof v=="string"&&v.includes("[Truncated]"))&&r.action&&(f=`Run "hyperscale product actions ${r.action}" to read the full input schema and allowed values.`),new I([l,...u].join(`
124
+ `),{code:c,...a.error.details?{details:dn(a.error.details,n)}:{},...f?{fix:f}:{}})}function dn(e,t){return typeof e=="string"?xe(e,t):Array.isArray(e)?e.map(n=>dn(n,t)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,r])=>[xe(n,t),dn(r,t)])):e}function pa(e,t){if(!e||typeof e!="object")return[];if(Array.isArray(e.issues))return e.issues.flatMap(r=>{if(!r||typeof r!="object")return[];let a=(Array.isArray(r.path)?r.path.join("."):"input")||"input";return typeof r.message=="string"?[`${a}: ${xe(r.message,t)}`]:[]});let n=[];return jn(e,"",n,t),n}function jn(e,t,n,r){if(Array.isArray(e)){if(e.every(o=>o===null||typeof o!="object")){n.push(`${Pt(t)}: ${xe(e.join(", "),r)}`);return}e.forEach((o,a)=>jn(o,`${t}[${a}]`,n,r));return}if(e&&typeof e=="object"){for(let[o,a]of Object.entries(e))jn(a,t?`${t}.${o}`:o,n,r);return}t&&n.push(`${Pt(t)}: ${xe(String(e),r)}`)}function Pt(e){let t=e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replaceAll("."," ");return t.charAt(0).toUpperCase()+t.slice(1)}async function ma(e,t){let n=await ye(e,t),r=Xe(n,e),o=await fe(n,"/v1/sandbox-api-keys",ve({name:e["--name"]??"Founder CLI",tenantId:n.tenantId,productId:r}),n.token,[n.token]);if(e["--json"]){se(o);return}y(`Key: ${o.apiKeyId??"unknown"}`),y(`Product: ${o.productId??r}`),y(`Status: ${o.status??"unknown"}`),o.secret?(y(`Secret: ${o.secret}`),y("Store it now. Hyperscale will not return it again."),y("Next:"),y(` export HYPERSCALE_API_KEY=${fa(o.secret)}`),y(` hyperscale product actions --product ${r}`)):y("The key already existed, so the one-time secret is unavailable.")}function fa(e){return`'${String(e).replaceAll("'",`'"'"'`)}'`}async function ya(e,t){let n=await ye(e,t),r=Xe(n,e),o=await Oe(n,"/v1/api-keys",{tenantId:n.tenantId},"api_key.list",n.token,[n.token]),a=Te(o,"api_key.list").filter(s=>s.productId===r),c={...o,items:a};if(e["--json"]){se(c);return}for(let s of a)y(`${s.apiKeyId} ${s.name??"unnamed"} ${s.status??"unknown"}`)}async function ha(e,t,n){if(!n)throw new I("key revoke needs an API key id");let r=await ye(e,t),o=Xe(r,e),a=await fe(r,`/v1/api-keys/${encodeURIComponent(n)}/revoke`,ve({tenantId:r.tenantId,productId:o}),r.token,[r.token]);e["--json"]?se(a):y(`Key ${a.apiKeyId??n}: ${a.status??"revoked"}`)}async function ga(e,t){let n=await ye(e,t),r=n.identity??await Ce(n,n.token),o=zn(n,r);if(e["--json"]){se(o);return}y(`User: ${r.email}`),y(`Tenant: ${r.tenantId}`),y(`Role: ${r.role}`),y(`Token: ${r.name}`),y(`Expires: ${r.expiresAt}`)}async function $a(e,t,n){let r=await Hn(e),o=n?n.toLowerCase():null,a=o?r.operations.filter(s=>s.name.toLowerCase().includes(o)||s.path.toLowerCase().includes(o)):r.operations;if(t["--json"]){y(JSON.stringify(a,null,2));return}if(a.length===0){y(n?`No operation matches ${n}`:"No operations");return}let c=Math.max(...a.map(s=>s.name.length));for(let s of a)y(`${s.name.padEnd(c)} ${s.method.padEnd(6)}${s.path}`)}async function ba(e,t){let n=await ye(e,t),r=await fe(n,`/v1/team/members?${Yn(n.tenantId)}`,{},n.token,[n.token]);if(!r||typeof r!="object"||!Array.isArray(r.members)||!Array.isArray(r.invitations))throw new I("team.member.list returned invalid data");if(e["--json"]){se(r);return}for(let o of r.members)y(`${o.email??"unknown"} ${o.role??"unknown"} ${o.status??"unknown"}`);for(let o of r.invitations)y(`${o.email??"unknown"} ${o.role??"unknown"} pending invitation`)}async function wa(e,t){let n=e["--email"],r=e["--role"];if(!n)throw new I("team invite needs --email <email>");if(!r)throw new I("team invite needs --role <role>");let o=await ye(e,t),a=await fe(o,"/v1/team/members/invite",ve({email:n,role:r,tenantId:o.tenantId}),o.token,[o.token]);if(e["--json"]){se(a);return}y(`Invitation: ${a.invitationId??"unknown"}`),y(`Email: ${a.email??n}`),y(`Role: ${a.role??r}`),y(`Expires: ${a.expiresAt??"unknown"}`),a.inviteToken&&(y(`Invite token: ${a.inviteToken}`),y("Share it now. Hyperscale will not return it again."))}async function va(e,t){let n=await ye(e,t),r=await Oe(n,"/v1/activity",{tenantId:n.tenantId},"activity.list",n.token,[n.token]),o=Te(r,"activity.list");if(e["--json"]){se(r);return}y("Time Activity Target Status");for(let a of o){let c=a.operation??a.auditEvent??"activity",s=a.resourceKind&&a.resourceId?`${a.resourceKind}:${a.resourceId}`:a.resourceKind??a.resourceId??"-";y(`${a.occurredAt??"unknown"} ${c} ${s} ${a.status??"recorded"}`)}}function Yt(e,t){let n={...t},r=[],o=e.path.replace(/\{([^}]+)\}/g,(a,c)=>{let s=n[c];return s==null?(r.push(c),""):(delete n[c],encodeURIComponent(String(s)))});if(r.length>0)throw new I(`${e.name} needs ${r.join(", ")} in --input`);return{path:o,remaining:n}}function Wt(e){let t=new URLSearchParams;for(let[r,o]of Object.entries(e))o!=null&&t.set(r,typeof o=="string"?o:JSON.stringify(o));let n=t.toString();return n?`?${n}`:""}function Bn(e,t){let n=Array.from({length:t.length+1},(r,o)=>o);for(let r=1;r<=e.length;r+=1){let o=[r];for(let a=1;a<=t.length;a+=1)o[a]=Math.min(o[a-1]+1,n[a]+1,n[a-1]+(e[r-1]===t[a-1]?0:1));n.splice(0,n.length,...o)}return n[t.length]}function Vt(e,t){let n=e.find(a=>a.name===t);if(n)return n;let r=e.filter(a=>a.operationId===t);if(r.length===1)return r[0];if(r.length>1)throw new I(`${t} matches more than one operation. Use one of: ${r.map(a=>a.name).join(", ")}.`);let o=e.map(a=>({candidate:a,distance:Math.min(Bn(t,a.name),Bn(t,a.operationId))})).sort((a,c)=>a.distance-c.distance||a.candidate.name.localeCompare(c.candidate.name)).slice(0,3).flatMap(({candidate:a})=>[a.name,a.operationId]);throw new I(`${t} is not an operation in the selected Product's machine document. Closest valid names: ${o.join(", ")}.`)}async function ka(e,t,n){if(!n)throw new I("call needs an operation name");let r=await Hn(e),o=Vt(r.operations,n),a=await Gt(t),{path:c,remaining:s}=Yt(o,a),l={method:o.method},u=c;o.method==="GET"?u+=Wt(s):(l.body=JSON.stringify(s),l.headers={"content-type":"application/json",...o.idempotency==="not_required"?{}:{"idempotency-key":t["--idempotency-key"]??globalThis.crypto.randomUUID()}});let{response:f,text:v}=await Ee(e,u,l);if(!f.ok)throw Ge(f,v,[e.apiKey]);y(Xt(v))}async function Gt(e){if(e["--input"]!==void 0&&e["--input-file"]!==void 0)throw new I("Use only one of --input and --input-file");if(e["--input"]!==void 0)return Tn(e["--input"],"--input");if(e["--input-file"]!==void 0){let t;try{t=await ln(e["--input-file"],"utf8")}catch(n){throw new I(`Could not read ${e["--input-file"]}: ${n.message}`)}return Tn(t,"--input-file")}if(!process.stdin.isTTY){let t=await wo();if(t.trim()!=="")return Tn(t,"stdin")}return{}}function Tn(e,t="--input"){if(e===void 0)return{};let n;try{n=JSON.parse(e)}catch(r){throw new I(`${t} is not valid JSON: ${r.message}`)}if(n===null||typeof n!="object"||Array.isArray(n))throw new I(`${t} must be a JSON object`);return n}function Xt(e){if(e.trim()==="")return"";try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function y(e){process.stdout.write(`${e}
125
+ `)}function se(e){y(JSON.stringify(e,null,2))}function _a(e,t){let n=e instanceof I&&typeof e.shownOnce=="string"?e.shownOnce:void 0;if(!t.includes("--json")){let a=e instanceof I?e.message:e.stack??String(e),c=e instanceof I&&typeof e.fix=="string"?`
126
126
  Fix: ${e.fix}`:"",s=n?`
127
127
  Shown once Product API key: ${n}`:"";process.stderr.write(`${a}${c}${s}
128
- `);return}let r=e instanceof S,o=r&&typeof e.code=="string"?e.code:r?"user_error":"internal_error";process.stderr.write(`${JSON.stringify({error:{code:o,message:r?e.message:"The command failed unexpectedly.",...r&&e.details?{details:e.details}:{},fix:r?e.fix??'Follow the message, or run "hyperscale --help" for command usage.':"Report the failure without including credentials."},...n?{shown_once:n}:{}})}
129
- `)}async function Aa(){let{readFileSync:e}=await import("node:fs");return JSON.parse(e(new URL("./package.json",import.meta.url),"utf8")).version}async function xa(e,t){let{flags:n,positional:r}=fo(e);if(n["--version"])return y(await Aa()),0;if(n["--help"]&&r.length>0)return process.stdout.write(po(r)),0;if(r.length===0&&!n["--help"]){if(n["--json"])throw new S('No command. Run "hyperscale --help" to list commands.');return process.stdin.isTTY&&process.stderr.isTTY?(await It(n,t),0):(y('Build your first Product with "hyperscale start".'),y('Run "hyperscale --help" for every command.'),0)}if(n["--help"])return process.stdout.write(uo),0;let[o,...a]=r;if(o==="start")return await It(n,t),0;if(o==="auth"){if(a[0]==="login")await xo(n,t);else if(a[0]==="status")await So(n,t);else if(a[0]==="logout")await Io(n,t);else throw new S('Auth subcommands are "login", "status", and "logout"');return 0}if(o==="blueprint"){let c=Ye(n,t);if(a[0]==="list")await Co(c,n);else if(a[0]==="show")await Eo(c,n,a[1]);else throw new S('Blueprint subcommands are "list" and "show"');return 0}if(o==="product"){if(a[0]==="create")await zo(n,t);else if(a[0]==="list")await Yo(n,t);else if(a[0]==="show")await Wo(n,t,a[1]);else if(a[0]==="select")await Go(n,t,a[1]);else if(a[0]==="actions")await aa(n,t,a[1]);else if(a[0]==="run")await la(n,t,a[1]);else throw new S('Product subcommands are "create", "list", "show", "select", "actions", and "run"');return 0}if(o==="compose"){if(a[0]==="check")await ea(n,t,a[1]);else if(a[0]==="plan")await na(n,t,a[1]);else if(a[0]==="apply")await ra(n,t,a[1]);else throw new S('Compose subcommands are "check", "plan", and "apply"');return 0}if(o==="key"){if(a[0]==="create")await ma(n,t);else if(a[0]==="list")await ya(n,t);else if(a[0]==="revoke")await ha(n,t,a[1]);else throw new S('Key subcommands are "create", "list", and "revoke"');return 0}if(o==="whoami")return await ga(n,t),0;if(o==="team"){if(a[0]==="list")await ba(n,t);else if(a[0]==="invite")await wa(n,t);else throw new S('Team subcommands are "list" and "invite"');return 0}if(o==="activity"){if(a[0]!=="list")throw new S('The only activity subcommand is "list"');return await va(n,t),0}if(o==="ops"){if(a[0]!=="list")throw new S('The only ops subcommand is "list"');let c=n["--product"]?await cn(n,t):kt(n,t);return await $a(c,n,a[1]),0}if(o==="call"){let c=n["--product"]?await cn(n,t):kt(n,t);return await ka(c,n,a[0]),0}throw new S(`Unknown command: ${o}`)}xa(process.argv.slice(2),process.env).then(e=>{process.exitCode=e},e=>{_a(e,process.argv.slice(2)),process.exitCode=e instanceof S&&Number.isInteger(e.exitCode)?e.exitCode:1});
128
+ `);return}let r=e instanceof I,o=r&&typeof e.code=="string"?e.code:r?"user_error":"internal_error";process.stderr.write(`${JSON.stringify({error:{code:o,message:r?e.message:"The command failed unexpectedly.",...r&&e.details?{details:e.details}:{},fix:r?e.fix??'Follow the message, or run "hyperscale --help" for command usage.':"Report the failure without including credentials."},...n?{shown_once:n}:{}})}
129
+ `)}async function Aa(){let{readFileSync:e}=await import("node:fs");return JSON.parse(e(new URL("./package.json",import.meta.url),"utf8")).version}async function xa(e,t){let{flags:n,positional:r}=fo(e);if(n["--version"])return y(await Aa()),0;if(n["--help"]&&r.length>0)return process.stdout.write(po(r)),0;if(r.length===0&&!n["--help"]){if(n["--json"])throw new I('No command. Run "hyperscale --help" to list commands.');return process.stdin.isTTY&&process.stderr.isTTY?(await It(n,t),0):(y('Build your first Product with "hyperscale start".'),y('Run "hyperscale --help" for every command.'),0)}if(n["--help"])return process.stdout.write(uo),0;let[o,...a]=r;if(o==="start")return await It(n,t),0;if(o==="auth"){if(a[0]==="login")await xo(n,t);else if(a[0]==="status")await So(n,t);else if(a[0]==="logout")await Io(n,t);else throw new I('Auth subcommands are "login", "status", and "logout"');return 0}if(o==="blueprint"){let c=Ye(n,t);if(a[0]==="list")await Co(c,n);else if(a[0]==="show")await Eo(c,n,a[1]);else throw new I('Blueprint subcommands are "list" and "show"');return 0}if(o==="product"){if(a[0]==="create")await zo(n,t);else if(a[0]==="list")await Yo(n,t);else if(a[0]==="show")await Wo(n,t,a[1]);else if(a[0]==="select")await Go(n,t,a[1]);else if(a[0]==="actions")await aa(n,t,a[1]);else if(a[0]==="run")await la(n,t,a[1]);else throw new I('Product subcommands are "create", "list", "show", "select", "actions", and "run"');return 0}if(o==="compose"){if(a[0]==="check")await ea(n,t,a[1]);else if(a[0]==="plan")await na(n,t,a[1]);else if(a[0]==="apply")await ra(n,t,a[1]);else throw new I('Compose subcommands are "check", "plan", and "apply"');return 0}if(o==="key"){if(a[0]==="create")await ma(n,t);else if(a[0]==="list")await ya(n,t);else if(a[0]==="revoke")await ha(n,t,a[1]);else throw new I('Key subcommands are "create", "list", and "revoke"');return 0}if(o==="whoami")return await ga(n,t),0;if(o==="team"){if(a[0]==="list")await ba(n,t);else if(a[0]==="invite")await wa(n,t);else throw new I('Team subcommands are "list" and "invite"');return 0}if(o==="activity"){if(a[0]!=="list")throw new I('The only activity subcommand is "list"');return await va(n,t),0}if(o==="ops"){if(a[0]!=="list")throw new I('The only ops subcommand is "list"');let c=n["--product"]?await cn(n,t):kt(n,t);return await $a(c,n,a[1]),0}if(o==="call"){let c=n["--product"]?await cn(n,t):kt(n,t);return await ka(c,n,a[0]),0}throw new I(`Unknown command: ${o}`)}xa(process.argv.slice(2),process.env).then(e=>{process.exitCode=e},e=>{_a(e,process.argv.slice(2)),process.exitCode=e instanceof I&&Number.isInteger(e.exitCode)?e.exitCode:1});