@aipt/cli 0.1.38 → 0.1.40
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/application-runner.js +183 -168
- package/dist/application.js +78 -74
- package/dist/chunk.js +5 -2
- package/dist/package-releases/aipt--cli/0.1.39/release.json +29 -0
- package/dist/package-releases/aipt--idp-setup/0.1.12/release.json +31 -0
- package/dist/package-releases/aipt--platform-kernel/0.1.13/release.json +33 -0
- package/docs/bootstrap.md +1 -1
- package/docs/vibe-coding-guide.md +1 -1
- package/documentation-manifest.json +3 -3
- package/package.json +1 -1
package/dist/application.js
CHANGED
|
@@ -1,48 +1,48 @@
|
|
|
1
|
-
var ng=Object.create;var ul=Object.defineProperty;var ig=Object.getOwnPropertyDescriptor;var ag=Object.getOwnPropertyNames;var og=Object.getPrototypeOf,sg=Object.prototype.hasOwnProperty;var R=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var cg=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of ag(t))!sg.call(e,i)&&i!==r&&ul(e,i,{get:()=>t[i],enumerable:!(n=ig(t,i))||n.enumerable});return e};var br=(e,t,r)=>(r=e!=null?ng(og(e)):{},cg(t||!e||!e.__esModule?ul(r,"default",{value:e,enumerable:!0}):r,e));var rn=R(W=>{"use strict";Object.defineProperty(W,"__esModule",{value:!0});W.regexpCode=W.getEsmExportName=W.getProperty=W.safeStringify=W.stringify=W.strConcat=W.addCodeArg=W.str=W._=W.nil=W._Code=W.Name=W.IDENTIFIER=W._CodeOrName=void 0;var en=class{};W._CodeOrName=en;W.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Jt=class extends en{constructor(t){if(super(),!W.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};W.Name=Jt;var Je=class extends en{constructor(t){super(),this._items=typeof t=="string"?[t]:t}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let t=this._items[0];return t===""||t==='""'}get str(){var t;return(t=this._str)!==null&&t!==void 0?t:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var t;return(t=this._names)!==null&&t!==void 0?t:this._names=this._items.reduce((r,n)=>(n instanceof Jt&&(r[n.str]=(r[n.str]||0)+1),r),{})}};W._Code=Je;W.nil=new Je("");function fl(e,...t){let r=[e[0]],n=0;for(;n<t.length;)no(r,t[n]),r.push(e[++n]);return new Je(r)}W._=fl;var ro=new Je("+");function ml(e,...t){let r=[tn(e[0])],n=0;for(;n<t.length;)r.push(ro),no(r,t[n]),r.push(ro,tn(e[++n]));return lg(r),new Je(r)}W.str=ml;function no(e,t){t instanceof Je?e.push(...t._items):t instanceof Jt?e.push(t):e.push(ug(t))}W.addCodeArg=no;function lg(e){let t=1;for(;t<e.length-1;){if(e[t]===ro){let r=dg(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function dg(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof Jt||e[e.length-1]!=='"'?void 0:typeof t!="string"?`${e.slice(0,-1)}${t}"`:t[0]==='"'?e.slice(0,-1)+t.slice(1):void 0;if(typeof t=="string"&&t[0]==='"'&&!(e instanceof Jt))return`"${e}${t.slice(1)}`}function pg(e,t){return t.emptyStr()?e:e.emptyStr()?t:ml`${e}${t}`}W.strConcat=pg;function ug(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:tn(Array.isArray(e)?e.join(","):e)}function fg(e){return new Je(tn(e))}W.stringify=fg;function tn(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}W.safeStringify=tn;function mg(e){return typeof e=="string"&&W.IDENTIFIER.test(e)?new Je(`.${e}`):fl`[${e}]`}W.getProperty=mg;function gg(e){if(typeof e=="string"&&W.IDENTIFIER.test(e))return new Je(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}W.getEsmExportName=gg;function hg(e){return new Je(e.toString())}W.regexpCode=hg});var oo=R(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.ValueScope=Ve.ValueScopeName=Ve.Scope=Ve.varKinds=Ve.UsedValueState=void 0;var Le=rn(),io=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},gi;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(gi||(Ve.UsedValueState=gi={}));Ve.varKinds={const:new Le.Name("const"),let:new Le.Name("let"),var:new Le.Name("var")};var hi=class{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof Le.Name?t:this.name(t)}name(t){return new Le.Name(this._newName(t))}_newName(t){let r=this._names[t]||this._nameGroup(t);return`${t}${r.index++}`}_nameGroup(t){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(t)||this._prefixes&&!this._prefixes.has(t))throw new Error(`CodeGen: prefix "${t}" is not allowed in this scope`);return this._names[t]={prefix:t,index:0}}};Ve.Scope=hi;var yi=class extends Le.Name{constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,Le._)`.${new Le.Name(r)}[${n}]`}};Ve.ValueScopeName=yi;var yg=(0,Le._)`\n`,ao=class extends hi{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?yg:Le.nil}}get(){return this._scope}name(t){return new yi(t,this._newName(t))}value(t,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let i=this.toName(t),{prefix:a}=i,o=(n=r.key)!==null&&n!==void 0?n:r.ref,s=this._values[a];if(s){let l=s.get(o);if(l)return l}else s=this._values[a]=new Map;s.set(o,i);let c=this._scope[a]||(this._scope[a]=[]),d=c.length;return c[d]=r.ref,i.setValue(r,{property:a,itemIndex:d}),i}getValue(t,r){let n=this._values[t];if(n)return n.get(r)}scopeRefs(t,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Le._)`${t}${n.scopePath}`})}scopeCode(t=this._values,r,n){return this._reduceValues(t,i=>{if(i.value===void 0)throw new Error(`CodeGen: name "${i}" has no value`);return i.value.code},r,n)}_reduceValues(t,r,n={},i){let a=Le.nil;for(let o in t){let s=t[o];if(!s)continue;let c=n[o]=n[o]||new Map;s.forEach(d=>{if(c.has(d))return;c.set(d,gi.Started);let l=r(d);if(l){let p=this.opts.es5?Ve.varKinds.var:Ve.varKinds.const;a=(0,Le._)`${a}${p} ${d} = ${l};${this.opts._n}`}else if(l=i?.(d))a=(0,Le._)`${a}${l}${this.opts._n}`;else throw new io(d);c.set(d,gi.Completed)})}return a}};Ve.ValueScope=ao});var x=R(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.or=V.and=V.not=V.CodeGen=V.operators=V.varKinds=V.ValueScopeName=V.ValueScope=V.Scope=V.Name=V.regexpCode=V.stringify=V.getProperty=V.nil=V.strConcat=V.str=V._=void 0;var z=rn(),rt=oo(),Nt=rn();Object.defineProperty(V,"_",{enumerable:!0,get:function(){return Nt._}});Object.defineProperty(V,"str",{enumerable:!0,get:function(){return Nt.str}});Object.defineProperty(V,"strConcat",{enumerable:!0,get:function(){return Nt.strConcat}});Object.defineProperty(V,"nil",{enumerable:!0,get:function(){return Nt.nil}});Object.defineProperty(V,"getProperty",{enumerable:!0,get:function(){return Nt.getProperty}});Object.defineProperty(V,"stringify",{enumerable:!0,get:function(){return Nt.stringify}});Object.defineProperty(V,"regexpCode",{enumerable:!0,get:function(){return Nt.regexpCode}});Object.defineProperty(V,"Name",{enumerable:!0,get:function(){return Nt.Name}});var bi=oo();Object.defineProperty(V,"Scope",{enumerable:!0,get:function(){return bi.Scope}});Object.defineProperty(V,"ValueScope",{enumerable:!0,get:function(){return bi.ValueScope}});Object.defineProperty(V,"ValueScopeName",{enumerable:!0,get:function(){return bi.ValueScopeName}});Object.defineProperty(V,"varKinds",{enumerable:!0,get:function(){return bi.varKinds}});V.operators={GT:new z._Code(">"),GTE:new z._Code(">="),LT:new z._Code("<"),LTE:new z._Code("<="),EQ:new z._Code("==="),NEQ:new z._Code("!=="),NOT:new z._Code("!"),OR:new z._Code("||"),AND:new z._Code("&&"),ADD:new z._Code("+")};var vt=class{optimizeNodes(){return this}optimizeNames(t,r){return this}},so=class extends vt{constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?rt.varKinds.var:this.varKind,i=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${i};`+r}optimizeNames(t,r){if(t[this.name.str])return this.rhs&&(this.rhs=_r(this.rhs,t,r)),this}get names(){return this.rhs instanceof z._CodeOrName?this.rhs.names:{}}},wi=class extends vt{constructor(t,r,n){super(),this.lhs=t,this.rhs=r,this.sideEffects=n}render({_n:t}){return`${this.lhs} = ${this.rhs};`+t}optimizeNames(t,r){if(!(this.lhs instanceof z.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=_r(this.rhs,t,r),this}get names(){let t=this.lhs instanceof z.Name?{}:{...this.lhs.names};return Ii(t,this.rhs)}},co=class extends wi{constructor(t,r,n,i){super(t,n,i),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},lo=class extends vt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},po=class extends vt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},uo=class extends vt{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},fo=class extends vt{constructor(t){super(),this.code=t}render({_n:t}){return`${this.code};`+t}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(t,r){return this.code=_r(this.code,t,r),this}get names(){return this.code instanceof z._CodeOrName?this.code.names:{}}},nn=class extends vt{constructor(t=[]){super(),this.nodes=t}render(t){return this.nodes.reduce((r,n)=>r+n.render(t),"")}optimizeNodes(){let{nodes:t}=this,r=t.length;for(;r--;){let n=t[r].optimizeNodes();Array.isArray(n)?t.splice(r,1,...n):n?t[r]=n:t.splice(r,1)}return t.length>0?this:void 0}optimizeNames(t,r){let{nodes:n}=this,i=n.length;for(;i--;){let a=n[i];a.optimizeNames(t,r)||(wg(t,a.names),n.splice(i,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>Kt(t,r.names),{})}},It=class extends nn{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},mo=class extends nn{},kr=class extends It{};kr.kind="else";var Gt=class e extends It{constructor(t,r){super(r),this.condition=t}render(t){let r=`if(${this.condition})`+super.render(t);return this.else&&(r+="else "+this.else.render(t)),r}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new kr(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(gl(t),r instanceof e?[r]:r.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(t,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(t,r),!!(super.optimizeNames(t,r)||this.else))return this.condition=_r(this.condition,t,r),this}get names(){let t=super.names;return Ii(t,this.condition),this.else&&Kt(t,this.else.names),t}};Gt.kind="if";var Wt=class extends It{};Wt.kind="for";var go=class extends Wt{constructor(t){super(),this.iteration=t}render(t){return`for(${this.iteration})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iteration=_r(this.iteration,t,r),this}get names(){return Kt(super.names,this.iteration.names)}},ho=class extends Wt{constructor(t,r,n,i){super(),this.varKind=t,this.name=r,this.from=n,this.to=i}render(t){let r=t.es5?rt.varKinds.var:this.varKind,{name:n,from:i,to:a}=this;return`for(${r} ${n}=${i}; ${n}<${a}; ${n}++)`+super.render(t)}get names(){let t=Ii(super.names,this.from);return Ii(t,this.to)}},vi=class extends Wt{constructor(t,r,n,i){super(),this.loop=t,this.varKind=r,this.name=n,this.iterable=i}render(t){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iterable=_r(this.iterable,t,r),this}get names(){return Kt(super.names,this.iterable.names)}},an=class extends It{constructor(t,r,n){super(),this.name=t,this.args=r,this.async=n}render(t){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(t)}};an.kind="func";var on=class extends nn{render(t){return"return "+super.render(t)}};on.kind="return";var yo=class extends It{render(t){let r="try"+super.render(t);return this.catch&&(r+=this.catch.render(t)),this.finally&&(r+=this.finally.render(t)),r}optimizeNodes(){var t,r;return super.optimizeNodes(),(t=this.catch)===null||t===void 0||t.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(t,r){var n,i;return super.optimizeNames(t,r),(n=this.catch)===null||n===void 0||n.optimizeNames(t,r),(i=this.finally)===null||i===void 0||i.optimizeNames(t,r),this}get names(){let t=super.names;return this.catch&&Kt(t,this.catch.names),this.finally&&Kt(t,this.finally.names),t}},sn=class extends It{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};sn.kind="catch";var cn=class extends It{render(t){return"finally"+super.render(t)}};cn.kind="finally";var wo=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
2
|
-
`:""},this._extScope=t,this._scope=new rt.Scope({parent:t}),this._nodes=[new mo]}toString(){return this._root.render(this.opts)}name(t){return this._scope.name(t)}scopeName(t){return this._extScope.name(t)}scopeValue(t,r){let n=this._extScope.value(t,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(t,r){return this._extScope.getValue(t,r)}scopeRefs(t){return this._extScope.scopeRefs(t,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(t,r,n,i){let a=this._scope.toName(r);return n!==void 0&&i&&(this._constants[a.str]=n),this._leafNode(new so(t,a,n)),a}const(t,r,n){return this._def(rt.varKinds.const,t,r,n)}let(t,r,n){return this._def(rt.varKinds.let,t,r,n)}var(t,r,n){return this._def(rt.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new wi(t,r,n))}add(t,r){return this._leafNode(new co(t,V.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==z.nil&&this._leafNode(new fo(t)),this}object(...t){let r=["{"];for(let[n,i]of t)r.length>1&&r.push(","),r.push(n),(n!==i||this.opts.es5)&&(r.push(":"),(0,z.addCodeArg)(r,i));return r.push("}"),new z._Code(r)}if(t,r,n){if(this._blockNode(new Gt(t)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(t){return this._elseNode(new Gt(t))}else(){return this._elseNode(new kr)}endIf(){return this._endBlockNode(Gt,kr)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new go(t),r)}forRange(t,r,n,i,a=this.opts.es5?rt.varKinds.var:rt.varKinds.let){let o=this._scope.toName(t);return this._for(new ho(a,o,r,n),()=>i(o))}forOf(t,r,n,i=rt.varKinds.const){let a=this._scope.toName(t);if(this.opts.es5){let o=r instanceof z.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,z._)`${o}.length`,s=>{this.var(a,(0,z._)`${o}[${s}]`),n(a)})}return this._for(new vi("of",i,a,r),()=>n(a))}forIn(t,r,n,i=this.opts.es5?rt.varKinds.var:rt.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,z._)`Object.keys(${r})`,n);let a=this._scope.toName(t);return this._for(new vi("in",i,a,r),()=>n(a))}endFor(){return this._endBlockNode(Wt)}label(t){return this._leafNode(new lo(t))}break(t){return this._leafNode(new po(t))}return(t){let r=new on;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(on)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new yo;if(this._blockNode(i),this.code(t),r){let a=this.name("e");this._currNode=i.catch=new sn(a),r(a)}return n&&(this._currNode=i.finally=new cn,this.code(n)),this._endBlockNode(sn,cn)}throw(t){return this._leafNode(new uo(t))}block(t,r){return this._blockStarts.push(this._nodes.length),t&&this.code(t).endBlock(r),this}endBlock(t){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||t!==void 0&&n!==t)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${t} expected`);return this._nodes.length=r,this}func(t,r=z.nil,n,i){return this._blockNode(new an(t,r,n)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(an)}optimize(t=1){for(;t-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(t){return this._currNode.nodes.push(t),this}_blockNode(t){this._currNode.nodes.push(t),this._nodes.push(t)}_endBlockNode(t,r){let n=this._currNode;if(n instanceof t||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${t.kind}/${r.kind}`:t.kind}"`)}_elseNode(t){let r=this._currNode;if(!(r instanceof Gt))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=t,this}get _root(){return this._nodes[0]}get _currNode(){let t=this._nodes;return t[t.length-1]}set _currNode(t){let r=this._nodes;r[r.length-1]=t}};V.CodeGen=wo;function Kt(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function Ii(e,t){return t instanceof z._CodeOrName?Kt(e,t.names):e}function _r(e,t,r){if(e instanceof z.Name)return n(e);if(!i(e))return e;return new z._Code(e._items.reduce((a,o)=>(o instanceof z.Name&&(o=n(o)),o instanceof z._Code?a.push(...o._items):a.push(o),a),[]));function n(a){let o=r[a.str];return o===void 0||t[a.str]!==1?a:(delete t[a.str],o)}function i(a){return a instanceof z._Code&&a._items.some(o=>o instanceof z.Name&&t[o.str]===1&&r[o.str]!==void 0)}}function wg(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function gl(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,z._)`!${vo(e)}`}V.not=gl;var vg=hl(V.operators.AND);function Ig(...e){return e.reduce(vg)}V.and=Ig;var bg=hl(V.operators.OR);function kg(...e){return e.reduce(bg)}V.or=kg;function hl(e){return(t,r)=>t===z.nil?r:r===z.nil?t:(0,z._)`${vo(t)} ${e} ${vo(r)}`}function vo(e){return e instanceof z.Name?e:(0,z._)`(${e})`}});var U=R(q=>{"use strict";Object.defineProperty(q,"__esModule",{value:!0});q.checkStrictMode=q.getErrorPath=q.Type=q.useFunc=q.setEvaluated=q.evaluatedPropsToName=q.mergeEvaluated=q.eachItem=q.unescapeJsonPointer=q.escapeJsonPointer=q.escapeFragment=q.unescapeFragment=q.schemaRefOrVal=q.schemaHasRulesButRef=q.schemaHasRules=q.checkUnknownRules=q.alwaysValidSchema=q.toHash=void 0;var re=x(),_g=rn();function Eg(e){let t={};for(let r of e)t[r]=!0;return t}q.toHash=Eg;function Ag(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(vl(e,t),!Il(t,e.self.RULES.all))}q.alwaysValidSchema=Ag;function vl(e,t=e.schema){let{opts:r,self:n}=e;if(!r.strictSchema||typeof t=="boolean")return;let i=n.RULES.keywords;for(let a in t)i[a]||_l(e,`unknown keyword: "${a}"`)}q.checkUnknownRules=vl;function Il(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}q.schemaHasRules=Il;function Rg(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}q.schemaHasRulesButRef=Rg;function Pg({topSchemaRef:e,schemaPath:t},r,n,i){if(!i){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,re._)`${r}`}return(0,re._)`${e}${t}${(0,re.getProperty)(n)}`}q.schemaRefOrVal=Pg;function Ng(e){return bl(decodeURIComponent(e))}q.unescapeFragment=Ng;function Dg(e){return encodeURIComponent(bo(e))}q.escapeFragment=Dg;function bo(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}q.escapeJsonPointer=bo;function bl(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}q.unescapeJsonPointer=bl;function Sg(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}q.eachItem=Sg;function yl({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(i,a,o,s)=>{let c=o===void 0?a:o instanceof re.Name?(a instanceof re.Name?e(i,a,o):t(i,a,o),o):a instanceof re.Name?(t(i,o,a),a):r(a,o);return s===re.Name&&!(c instanceof re.Name)?n(i,c):c}}q.mergeEvaluated={props:yl({mergeNames:(e,t,r)=>e.if((0,re._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,re._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,re._)`${r} || {}`).code((0,re._)`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if((0,re._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,re._)`${r} || {}`),ko(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:kl}),items:yl({mergeNames:(e,t,r)=>e.if((0,re._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,re._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0,re._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,re._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function kl(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,re._)`{}`);return t!==void 0&&ko(e,r,t),r}q.evaluatedPropsToName=kl;function ko(e,t,r){Object.keys(r).forEach(n=>e.assign((0,re._)`${t}${(0,re.getProperty)(n)}`,!0))}q.setEvaluated=ko;var wl={};function jg(e,t){return e.scopeValue("func",{ref:t,code:wl[t.code]||(wl[t.code]=new _g._Code(t.code))})}q.useFunc=jg;var Io;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(Io||(q.Type=Io={}));function $g(e,t,r){if(e instanceof re.Name){let n=t===Io.Num;return r?n?(0,re._)`"[" + ${e} + "]"`:(0,re._)`"['" + ${e} + "']"`:n?(0,re._)`"/" + ${e}`:(0,re._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,re.getProperty)(e).toString():"/"+bo(e)}q.getErrorPath=$g;function _l(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===!0)throw new Error(t);e.self.logger.warn(t)}}q.checkStrictMode=_l});var Ge=R(_o=>{"use strict";Object.defineProperty(_o,"__esModule",{value:!0});var Re=x(),Og={data:new Re.Name("data"),valCxt:new Re.Name("valCxt"),instancePath:new Re.Name("instancePath"),parentData:new Re.Name("parentData"),parentDataProperty:new Re.Name("parentDataProperty"),rootData:new Re.Name("rootData"),dynamicAnchors:new Re.Name("dynamicAnchors"),vErrors:new Re.Name("vErrors"),errors:new Re.Name("errors"),this:new Re.Name("this"),self:new Re.Name("self"),scope:new Re.Name("scope"),json:new Re.Name("json"),jsonPos:new Re.Name("jsonPos"),jsonLen:new Re.Name("jsonLen"),jsonPart:new Re.Name("jsonPart")};_o.default=Og});var ln=R(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.extendErrors=Pe.resetErrorsCount=Pe.reportExtraError=Pe.reportError=Pe.keyword$DataError=Pe.keywordError=void 0;var B=x(),ki=U(),Oe=Ge();Pe.keywordError={message:({keyword:e})=>(0,B.str)`must pass "${e}" keyword validation`};Pe.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,B.str)`"${e}" keyword must be ${t} ($data)`:(0,B.str)`"${e}" keyword is invalid ($data)`};function Cg(e,t=Pe.keywordError,r,n){let{it:i}=e,{gen:a,compositeRule:o,allErrors:s}=i,c=Rl(e,t,r);n??(o||s)?El(a,c):Al(i,(0,B._)`[${c}]`)}Pe.reportError=Cg;function Tg(e,t=Pe.keywordError,r){let{it:n}=e,{gen:i,compositeRule:a,allErrors:o}=n,s=Rl(e,t,r);El(i,s),a||o||Al(n,Oe.default.vErrors)}Pe.reportExtraError=Tg;function xg(e,t){e.assign(Oe.default.errors,t),e.if((0,B._)`${Oe.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,B._)`${Oe.default.vErrors}.length`,t),()=>e.assign(Oe.default.vErrors,null)))}Pe.resetErrorsCount=xg;function Lg({gen:e,keyword:t,schemaValue:r,data:n,errsCount:i,it:a}){if(i===void 0)throw new Error("ajv implementation error");let o=e.name("err");e.forRange("i",i,Oe.default.errors,s=>{e.const(o,(0,B._)`${Oe.default.vErrors}[${s}]`),e.if((0,B._)`${o}.instancePath === undefined`,()=>e.assign((0,B._)`${o}.instancePath`,(0,B.strConcat)(Oe.default.instancePath,a.errorPath))),e.assign((0,B._)`${o}.schemaPath`,(0,B.str)`${a.errSchemaPath}/${t}`),a.opts.verbose&&(e.assign((0,B._)`${o}.schema`,r),e.assign((0,B._)`${o}.data`,n))})}Pe.extendErrors=Lg;function El(e,t){let r=e.const("err",t);e.if((0,B._)`${Oe.default.vErrors} === null`,()=>e.assign(Oe.default.vErrors,(0,B._)`[${r}]`),(0,B._)`${Oe.default.vErrors}.push(${r})`),e.code((0,B._)`${Oe.default.errors}++`)}function Al(e,t){let{gen:r,validateName:n,schemaEnv:i}=e;i.$async?r.throw((0,B._)`new ${e.ValidationError}(${t})`):(r.assign((0,B._)`${n}.errors`,t),r.return(!1))}var Yt={keyword:new B.Name("keyword"),schemaPath:new B.Name("schemaPath"),params:new B.Name("params"),propertyName:new B.Name("propertyName"),message:new B.Name("message"),schema:new B.Name("schema"),parentSchema:new B.Name("parentSchema")};function Rl(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,B._)`{}`:Vg(e,t,r)}function Vg(e,t,r={}){let{gen:n,it:i}=e,a=[Mg(i,r),qg(e,r)];return Ug(e,t,a),n.object(...a)}function Mg({errorPath:e},{instancePath:t}){let r=t?(0,B.str)`${e}${(0,ki.getErrorPath)(t,ki.Type.Str)}`:e;return[Oe.default.instancePath,(0,B.strConcat)(Oe.default.instancePath,r)]}function qg({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let i=n?t:(0,B.str)`${t}/${e}`;return r&&(i=(0,B.str)`${i}${(0,ki.getErrorPath)(r,ki.Type.Str)}`),[Yt.schemaPath,i]}function Ug(e,{params:t,message:r},n){let{keyword:i,data:a,schemaValue:o,it:s}=e,{opts:c,propertyName:d,topSchemaRef:l,schemaPath:p}=s;n.push([Yt.keyword,i],[Yt.params,typeof t=="function"?t(e):t||(0,B._)`{}`]),c.messages&&n.push([Yt.message,typeof r=="function"?r(e):r]),c.verbose&&n.push([Yt.schema,o],[Yt.parentSchema,(0,B._)`${l}${p}`],[Oe.default.data,a]),d&&n.push([Yt.propertyName,d])}});var Nl=R(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});Er.boolOrEmptySchema=Er.topBoolOrEmptySchema=void 0;var Fg=ln(),zg=x(),Bg=Ge(),Jg={message:"boolean schema is false"};function Gg(e){let{gen:t,schema:r,validateName:n}=e;r===!1?Pl(e,!1):typeof r=="object"&&r.$async===!0?t.return(Bg.default.data):(t.assign((0,zg._)`${n}.errors`,null),t.return(!0))}Er.topBoolOrEmptySchema=Gg;function Wg(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),Pl(e)):r.var(t,!0)}Er.boolOrEmptySchema=Wg;function Pl(e,t){let{gen:r,data:n}=e,i={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,Fg.reportError)(i,Jg,void 0,t)}});var Eo=R(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});Ar.getRules=Ar.isJSONType=void 0;var Kg=["string","number","integer","boolean","null","object","array"],Yg=new Set(Kg);function Hg(e){return typeof e=="string"&&Yg.has(e)}Ar.isJSONType=Hg;function Zg(){let e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}Ar.getRules=Zg});var Ao=R(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.shouldUseRule=Dt.shouldUseGroup=Dt.schemaHasRulesForType=void 0;function Xg({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&Dl(e,n)}Dt.schemaHasRulesForType=Xg;function Dl(e,t){return t.rules.some(r=>Sl(e,r))}Dt.shouldUseGroup=Dl;function Sl(e,t){var r;return e[t.keyword]!==void 0||((r=t.definition.implements)===null||r===void 0?void 0:r.some(n=>e[n]!==void 0))}Dt.shouldUseRule=Sl});var dn=R(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.reportTypeError=Ne.checkDataTypes=Ne.checkDataType=Ne.coerceAndCheckDataType=Ne.getJSONTypes=Ne.getSchemaTypes=Ne.DataType=void 0;var Qg=Eo(),eh=Ao(),th=ln(),L=x(),jl=U(),Rr;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(Rr||(Ne.DataType=Rr={}));function rh(e){let t=$l(e.type);if(t.includes("null")){if(e.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');e.nullable===!0&&t.push("null")}return t}Ne.getSchemaTypes=rh;function $l(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(Qg.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}Ne.getJSONTypes=$l;function nh(e,t){let{gen:r,data:n,opts:i}=e,a=ih(t,i.coerceTypes),o=t.length>0&&!(a.length===0&&t.length===1&&(0,eh.schemaHasRulesForType)(e,t[0]));if(o){let s=Po(t,n,i.strictNumbers,Rr.Wrong);r.if(s,()=>{a.length?ah(e,t,a):No(e)})}return o}Ne.coerceAndCheckDataType=nh;var Ol=new Set(["string","number","integer","boolean","null"]);function ih(e,t){return t?e.filter(r=>Ol.has(r)||t==="array"&&r==="array"):[]}function ah(e,t,r){let{gen:n,data:i,opts:a}=e,o=n.let("dataType",(0,L._)`typeof ${i}`),s=n.let("coerced",(0,L._)`undefined`);a.coerceTypes==="array"&&n.if((0,L._)`${o} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>n.assign(i,(0,L._)`${i}[0]`).assign(o,(0,L._)`typeof ${i}`).if(Po(t,i,a.strictNumbers),()=>n.assign(s,i))),n.if((0,L._)`${s} !== undefined`);for(let d of r)(Ol.has(d)||d==="array"&&a.coerceTypes==="array")&&c(d);n.else(),No(e),n.endIf(),n.if((0,L._)`${s} !== undefined`,()=>{n.assign(i,s),oh(e,s)});function c(d){switch(d){case"string":n.elseIf((0,L._)`${o} == "number" || ${o} == "boolean"`).assign(s,(0,L._)`"" + ${i}`).elseIf((0,L._)`${i} === null`).assign(s,(0,L._)`""`);return;case"number":n.elseIf((0,L._)`${o} == "boolean" || ${i} === null
|
|
1
|
+
var ng=Object.create;var fl=Object.defineProperty;var ig=Object.getOwnPropertyDescriptor;var ag=Object.getOwnPropertyNames;var og=Object.getPrototypeOf,sg=Object.prototype.hasOwnProperty;var R=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var cg=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of ag(t))!sg.call(e,i)&&i!==r&&fl(e,i,{get:()=>t[i],enumerable:!(n=ig(t,i))||n.enumerable});return e};var br=(e,t,r)=>(r=e!=null?ng(og(e)):{},cg(t||!e||!e.__esModule?fl(r,"default",{value:e,enumerable:!0}):r,e));var rn=R(W=>{"use strict";Object.defineProperty(W,"__esModule",{value:!0});W.regexpCode=W.getEsmExportName=W.getProperty=W.safeStringify=W.stringify=W.strConcat=W.addCodeArg=W.str=W._=W.nil=W._Code=W.Name=W.IDENTIFIER=W._CodeOrName=void 0;var en=class{};W._CodeOrName=en;W.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Gt=class extends en{constructor(t){if(super(),!W.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};W.Name=Gt;var Ge=class extends en{constructor(t){super(),this._items=typeof t=="string"?[t]:t}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let t=this._items[0];return t===""||t==='""'}get str(){var t;return(t=this._str)!==null&&t!==void 0?t:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var t;return(t=this._names)!==null&&t!==void 0?t:this._names=this._items.reduce((r,n)=>(n instanceof Gt&&(r[n.str]=(r[n.str]||0)+1),r),{})}};W._Code=Ge;W.nil=new Ge("");function ml(e,...t){let r=[e[0]],n=0;for(;n<t.length;)no(r,t[n]),r.push(e[++n]);return new Ge(r)}W._=ml;var ro=new Ge("+");function gl(e,...t){let r=[tn(e[0])],n=0;for(;n<t.length;)r.push(ro),no(r,t[n]),r.push(ro,tn(e[++n]));return lg(r),new Ge(r)}W.str=gl;function no(e,t){t instanceof Ge?e.push(...t._items):t instanceof Gt?e.push(t):e.push(ug(t))}W.addCodeArg=no;function lg(e){let t=1;for(;t<e.length-1;){if(e[t]===ro){let r=dg(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function dg(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof Gt||e[e.length-1]!=='"'?void 0:typeof t!="string"?`${e.slice(0,-1)}${t}"`:t[0]==='"'?e.slice(0,-1)+t.slice(1):void 0;if(typeof t=="string"&&t[0]==='"'&&!(e instanceof Gt))return`"${e}${t.slice(1)}`}function pg(e,t){return t.emptyStr()?e:e.emptyStr()?t:gl`${e}${t}`}W.strConcat=pg;function ug(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:tn(Array.isArray(e)?e.join(","):e)}function fg(e){return new Ge(tn(e))}W.stringify=fg;function tn(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}W.safeStringify=tn;function mg(e){return typeof e=="string"&&W.IDENTIFIER.test(e)?new Ge(`.${e}`):ml`[${e}]`}W.getProperty=mg;function gg(e){if(typeof e=="string"&&W.IDENTIFIER.test(e))return new Ge(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}W.getEsmExportName=gg;function hg(e){return new Ge(e.toString())}W.regexpCode=hg});var oo=R(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.ValueScope=Ve.ValueScopeName=Ve.Scope=Ve.varKinds=Ve.UsedValueState=void 0;var Le=rn(),io=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},gi;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(gi||(Ve.UsedValueState=gi={}));Ve.varKinds={const:new Le.Name("const"),let:new Le.Name("let"),var:new Le.Name("var")};var hi=class{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof Le.Name?t:this.name(t)}name(t){return new Le.Name(this._newName(t))}_newName(t){let r=this._names[t]||this._nameGroup(t);return`${t}${r.index++}`}_nameGroup(t){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(t)||this._prefixes&&!this._prefixes.has(t))throw new Error(`CodeGen: prefix "${t}" is not allowed in this scope`);return this._names[t]={prefix:t,index:0}}};Ve.Scope=hi;var yi=class extends Le.Name{constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,Le._)`.${new Le.Name(r)}[${n}]`}};Ve.ValueScopeName=yi;var yg=(0,Le._)`\n`,ao=class extends hi{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?yg:Le.nil}}get(){return this._scope}name(t){return new yi(t,this._newName(t))}value(t,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let i=this.toName(t),{prefix:a}=i,o=(n=r.key)!==null&&n!==void 0?n:r.ref,s=this._values[a];if(s){let l=s.get(o);if(l)return l}else s=this._values[a]=new Map;s.set(o,i);let c=this._scope[a]||(this._scope[a]=[]),d=c.length;return c[d]=r.ref,i.setValue(r,{property:a,itemIndex:d}),i}getValue(t,r){let n=this._values[t];if(n)return n.get(r)}scopeRefs(t,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Le._)`${t}${n.scopePath}`})}scopeCode(t=this._values,r,n){return this._reduceValues(t,i=>{if(i.value===void 0)throw new Error(`CodeGen: name "${i}" has no value`);return i.value.code},r,n)}_reduceValues(t,r,n={},i){let a=Le.nil;for(let o in t){let s=t[o];if(!s)continue;let c=n[o]=n[o]||new Map;s.forEach(d=>{if(c.has(d))return;c.set(d,gi.Started);let l=r(d);if(l){let p=this.opts.es5?Ve.varKinds.var:Ve.varKinds.const;a=(0,Le._)`${a}${p} ${d} = ${l};${this.opts._n}`}else if(l=i?.(d))a=(0,Le._)`${a}${l}${this.opts._n}`;else throw new io(d);c.set(d,gi.Completed)})}return a}};Ve.ValueScope=ao});var x=R(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.or=V.and=V.not=V.CodeGen=V.operators=V.varKinds=V.ValueScopeName=V.ValueScope=V.Scope=V.Name=V.regexpCode=V.stringify=V.getProperty=V.nil=V.strConcat=V.str=V._=void 0;var z=rn(),rt=oo(),Nt=rn();Object.defineProperty(V,"_",{enumerable:!0,get:function(){return Nt._}});Object.defineProperty(V,"str",{enumerable:!0,get:function(){return Nt.str}});Object.defineProperty(V,"strConcat",{enumerable:!0,get:function(){return Nt.strConcat}});Object.defineProperty(V,"nil",{enumerable:!0,get:function(){return Nt.nil}});Object.defineProperty(V,"getProperty",{enumerable:!0,get:function(){return Nt.getProperty}});Object.defineProperty(V,"stringify",{enumerable:!0,get:function(){return Nt.stringify}});Object.defineProperty(V,"regexpCode",{enumerable:!0,get:function(){return Nt.regexpCode}});Object.defineProperty(V,"Name",{enumerable:!0,get:function(){return Nt.Name}});var bi=oo();Object.defineProperty(V,"Scope",{enumerable:!0,get:function(){return bi.Scope}});Object.defineProperty(V,"ValueScope",{enumerable:!0,get:function(){return bi.ValueScope}});Object.defineProperty(V,"ValueScopeName",{enumerable:!0,get:function(){return bi.ValueScopeName}});Object.defineProperty(V,"varKinds",{enumerable:!0,get:function(){return bi.varKinds}});V.operators={GT:new z._Code(">"),GTE:new z._Code(">="),LT:new z._Code("<"),LTE:new z._Code("<="),EQ:new z._Code("==="),NEQ:new z._Code("!=="),NOT:new z._Code("!"),OR:new z._Code("||"),AND:new z._Code("&&"),ADD:new z._Code("+")};var vt=class{optimizeNodes(){return this}optimizeNames(t,r){return this}},so=class extends vt{constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?rt.varKinds.var:this.varKind,i=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${i};`+r}optimizeNames(t,r){if(t[this.name.str])return this.rhs&&(this.rhs=_r(this.rhs,t,r)),this}get names(){return this.rhs instanceof z._CodeOrName?this.rhs.names:{}}},wi=class extends vt{constructor(t,r,n){super(),this.lhs=t,this.rhs=r,this.sideEffects=n}render({_n:t}){return`${this.lhs} = ${this.rhs};`+t}optimizeNames(t,r){if(!(this.lhs instanceof z.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=_r(this.rhs,t,r),this}get names(){let t=this.lhs instanceof z.Name?{}:{...this.lhs.names};return Ii(t,this.rhs)}},co=class extends wi{constructor(t,r,n,i){super(t,n,i),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},lo=class extends vt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},po=class extends vt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},uo=class extends vt{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},fo=class extends vt{constructor(t){super(),this.code=t}render({_n:t}){return`${this.code};`+t}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(t,r){return this.code=_r(this.code,t,r),this}get names(){return this.code instanceof z._CodeOrName?this.code.names:{}}},nn=class extends vt{constructor(t=[]){super(),this.nodes=t}render(t){return this.nodes.reduce((r,n)=>r+n.render(t),"")}optimizeNodes(){let{nodes:t}=this,r=t.length;for(;r--;){let n=t[r].optimizeNodes();Array.isArray(n)?t.splice(r,1,...n):n?t[r]=n:t.splice(r,1)}return t.length>0?this:void 0}optimizeNames(t,r){let{nodes:n}=this,i=n.length;for(;i--;){let a=n[i];a.optimizeNames(t,r)||(wg(t,a.names),n.splice(i,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>Kt(t,r.names),{})}},It=class extends nn{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},mo=class extends nn{},kr=class extends It{};kr.kind="else";var Jt=class e extends It{constructor(t,r){super(r),this.condition=t}render(t){let r=`if(${this.condition})`+super.render(t);return this.else&&(r+="else "+this.else.render(t)),r}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new kr(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(hl(t),r instanceof e?[r]:r.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(t,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(t,r),!!(super.optimizeNames(t,r)||this.else))return this.condition=_r(this.condition,t,r),this}get names(){let t=super.names;return Ii(t,this.condition),this.else&&Kt(t,this.else.names),t}};Jt.kind="if";var Wt=class extends It{};Wt.kind="for";var go=class extends Wt{constructor(t){super(),this.iteration=t}render(t){return`for(${this.iteration})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iteration=_r(this.iteration,t,r),this}get names(){return Kt(super.names,this.iteration.names)}},ho=class extends Wt{constructor(t,r,n,i){super(),this.varKind=t,this.name=r,this.from=n,this.to=i}render(t){let r=t.es5?rt.varKinds.var:this.varKind,{name:n,from:i,to:a}=this;return`for(${r} ${n}=${i}; ${n}<${a}; ${n}++)`+super.render(t)}get names(){let t=Ii(super.names,this.from);return Ii(t,this.to)}},vi=class extends Wt{constructor(t,r,n,i){super(),this.loop=t,this.varKind=r,this.name=n,this.iterable=i}render(t){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iterable=_r(this.iterable,t,r),this}get names(){return Kt(super.names,this.iterable.names)}},an=class extends It{constructor(t,r,n){super(),this.name=t,this.args=r,this.async=n}render(t){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(t)}};an.kind="func";var on=class extends nn{render(t){return"return "+super.render(t)}};on.kind="return";var yo=class extends It{render(t){let r="try"+super.render(t);return this.catch&&(r+=this.catch.render(t)),this.finally&&(r+=this.finally.render(t)),r}optimizeNodes(){var t,r;return super.optimizeNodes(),(t=this.catch)===null||t===void 0||t.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(t,r){var n,i;return super.optimizeNames(t,r),(n=this.catch)===null||n===void 0||n.optimizeNames(t,r),(i=this.finally)===null||i===void 0||i.optimizeNames(t,r),this}get names(){let t=super.names;return this.catch&&Kt(t,this.catch.names),this.finally&&Kt(t,this.finally.names),t}},sn=class extends It{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};sn.kind="catch";var cn=class extends It{render(t){return"finally"+super.render(t)}};cn.kind="finally";var wo=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
2
|
+
`:""},this._extScope=t,this._scope=new rt.Scope({parent:t}),this._nodes=[new mo]}toString(){return this._root.render(this.opts)}name(t){return this._scope.name(t)}scopeName(t){return this._extScope.name(t)}scopeValue(t,r){let n=this._extScope.value(t,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(t,r){return this._extScope.getValue(t,r)}scopeRefs(t){return this._extScope.scopeRefs(t,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(t,r,n,i){let a=this._scope.toName(r);return n!==void 0&&i&&(this._constants[a.str]=n),this._leafNode(new so(t,a,n)),a}const(t,r,n){return this._def(rt.varKinds.const,t,r,n)}let(t,r,n){return this._def(rt.varKinds.let,t,r,n)}var(t,r,n){return this._def(rt.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new wi(t,r,n))}add(t,r){return this._leafNode(new co(t,V.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==z.nil&&this._leafNode(new fo(t)),this}object(...t){let r=["{"];for(let[n,i]of t)r.length>1&&r.push(","),r.push(n),(n!==i||this.opts.es5)&&(r.push(":"),(0,z.addCodeArg)(r,i));return r.push("}"),new z._Code(r)}if(t,r,n){if(this._blockNode(new Jt(t)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(t){return this._elseNode(new Jt(t))}else(){return this._elseNode(new kr)}endIf(){return this._endBlockNode(Jt,kr)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new go(t),r)}forRange(t,r,n,i,a=this.opts.es5?rt.varKinds.var:rt.varKinds.let){let o=this._scope.toName(t);return this._for(new ho(a,o,r,n),()=>i(o))}forOf(t,r,n,i=rt.varKinds.const){let a=this._scope.toName(t);if(this.opts.es5){let o=r instanceof z.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,z._)`${o}.length`,s=>{this.var(a,(0,z._)`${o}[${s}]`),n(a)})}return this._for(new vi("of",i,a,r),()=>n(a))}forIn(t,r,n,i=this.opts.es5?rt.varKinds.var:rt.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,z._)`Object.keys(${r})`,n);let a=this._scope.toName(t);return this._for(new vi("in",i,a,r),()=>n(a))}endFor(){return this._endBlockNode(Wt)}label(t){return this._leafNode(new lo(t))}break(t){return this._leafNode(new po(t))}return(t){let r=new on;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(on)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new yo;if(this._blockNode(i),this.code(t),r){let a=this.name("e");this._currNode=i.catch=new sn(a),r(a)}return n&&(this._currNode=i.finally=new cn,this.code(n)),this._endBlockNode(sn,cn)}throw(t){return this._leafNode(new uo(t))}block(t,r){return this._blockStarts.push(this._nodes.length),t&&this.code(t).endBlock(r),this}endBlock(t){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||t!==void 0&&n!==t)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${t} expected`);return this._nodes.length=r,this}func(t,r=z.nil,n,i){return this._blockNode(new an(t,r,n)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(an)}optimize(t=1){for(;t-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(t){return this._currNode.nodes.push(t),this}_blockNode(t){this._currNode.nodes.push(t),this._nodes.push(t)}_endBlockNode(t,r){let n=this._currNode;if(n instanceof t||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${t.kind}/${r.kind}`:t.kind}"`)}_elseNode(t){let r=this._currNode;if(!(r instanceof Jt))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=t,this}get _root(){return this._nodes[0]}get _currNode(){let t=this._nodes;return t[t.length-1]}set _currNode(t){let r=this._nodes;r[r.length-1]=t}};V.CodeGen=wo;function Kt(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function Ii(e,t){return t instanceof z._CodeOrName?Kt(e,t.names):e}function _r(e,t,r){if(e instanceof z.Name)return n(e);if(!i(e))return e;return new z._Code(e._items.reduce((a,o)=>(o instanceof z.Name&&(o=n(o)),o instanceof z._Code?a.push(...o._items):a.push(o),a),[]));function n(a){let o=r[a.str];return o===void 0||t[a.str]!==1?a:(delete t[a.str],o)}function i(a){return a instanceof z._Code&&a._items.some(o=>o instanceof z.Name&&t[o.str]===1&&r[o.str]!==void 0)}}function wg(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function hl(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,z._)`!${vo(e)}`}V.not=hl;var vg=yl(V.operators.AND);function Ig(...e){return e.reduce(vg)}V.and=Ig;var bg=yl(V.operators.OR);function kg(...e){return e.reduce(bg)}V.or=kg;function yl(e){return(t,r)=>t===z.nil?r:r===z.nil?t:(0,z._)`${vo(t)} ${e} ${vo(r)}`}function vo(e){return e instanceof z.Name?e:(0,z._)`(${e})`}});var U=R(q=>{"use strict";Object.defineProperty(q,"__esModule",{value:!0});q.checkStrictMode=q.getErrorPath=q.Type=q.useFunc=q.setEvaluated=q.evaluatedPropsToName=q.mergeEvaluated=q.eachItem=q.unescapeJsonPointer=q.escapeJsonPointer=q.escapeFragment=q.unescapeFragment=q.schemaRefOrVal=q.schemaHasRulesButRef=q.schemaHasRules=q.checkUnknownRules=q.alwaysValidSchema=q.toHash=void 0;var re=x(),_g=rn();function Eg(e){let t={};for(let r of e)t[r]=!0;return t}q.toHash=Eg;function Ag(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(Il(e,t),!bl(t,e.self.RULES.all))}q.alwaysValidSchema=Ag;function Il(e,t=e.schema){let{opts:r,self:n}=e;if(!r.strictSchema||typeof t=="boolean")return;let i=n.RULES.keywords;for(let a in t)i[a]||El(e,`unknown keyword: "${a}"`)}q.checkUnknownRules=Il;function bl(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}q.schemaHasRules=bl;function Rg(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}q.schemaHasRulesButRef=Rg;function Pg({topSchemaRef:e,schemaPath:t},r,n,i){if(!i){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,re._)`${r}`}return(0,re._)`${e}${t}${(0,re.getProperty)(n)}`}q.schemaRefOrVal=Pg;function Ng(e){return kl(decodeURIComponent(e))}q.unescapeFragment=Ng;function Dg(e){return encodeURIComponent(bo(e))}q.escapeFragment=Dg;function bo(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}q.escapeJsonPointer=bo;function kl(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}q.unescapeJsonPointer=kl;function Sg(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}q.eachItem=Sg;function wl({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(i,a,o,s)=>{let c=o===void 0?a:o instanceof re.Name?(a instanceof re.Name?e(i,a,o):t(i,a,o),o):a instanceof re.Name?(t(i,o,a),a):r(a,o);return s===re.Name&&!(c instanceof re.Name)?n(i,c):c}}q.mergeEvaluated={props:wl({mergeNames:(e,t,r)=>e.if((0,re._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,re._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,re._)`${r} || {}`).code((0,re._)`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if((0,re._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,re._)`${r} || {}`),ko(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:_l}),items:wl({mergeNames:(e,t,r)=>e.if((0,re._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,re._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0,re._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,re._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function _l(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,re._)`{}`);return t!==void 0&&ko(e,r,t),r}q.evaluatedPropsToName=_l;function ko(e,t,r){Object.keys(r).forEach(n=>e.assign((0,re._)`${t}${(0,re.getProperty)(n)}`,!0))}q.setEvaluated=ko;var vl={};function jg(e,t){return e.scopeValue("func",{ref:t,code:vl[t.code]||(vl[t.code]=new _g._Code(t.code))})}q.useFunc=jg;var Io;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(Io||(q.Type=Io={}));function $g(e,t,r){if(e instanceof re.Name){let n=t===Io.Num;return r?n?(0,re._)`"[" + ${e} + "]"`:(0,re._)`"['" + ${e} + "']"`:n?(0,re._)`"/" + ${e}`:(0,re._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,re.getProperty)(e).toString():"/"+bo(e)}q.getErrorPath=$g;function El(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===!0)throw new Error(t);e.self.logger.warn(t)}}q.checkStrictMode=El});var Je=R(_o=>{"use strict";Object.defineProperty(_o,"__esModule",{value:!0});var Re=x(),Og={data:new Re.Name("data"),valCxt:new Re.Name("valCxt"),instancePath:new Re.Name("instancePath"),parentData:new Re.Name("parentData"),parentDataProperty:new Re.Name("parentDataProperty"),rootData:new Re.Name("rootData"),dynamicAnchors:new Re.Name("dynamicAnchors"),vErrors:new Re.Name("vErrors"),errors:new Re.Name("errors"),this:new Re.Name("this"),self:new Re.Name("self"),scope:new Re.Name("scope"),json:new Re.Name("json"),jsonPos:new Re.Name("jsonPos"),jsonLen:new Re.Name("jsonLen"),jsonPart:new Re.Name("jsonPart")};_o.default=Og});var ln=R(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.extendErrors=Pe.resetErrorsCount=Pe.reportExtraError=Pe.reportError=Pe.keyword$DataError=Pe.keywordError=void 0;var B=x(),ki=U(),Oe=Je();Pe.keywordError={message:({keyword:e})=>(0,B.str)`must pass "${e}" keyword validation`};Pe.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,B.str)`"${e}" keyword must be ${t} ($data)`:(0,B.str)`"${e}" keyword is invalid ($data)`};function Cg(e,t=Pe.keywordError,r,n){let{it:i}=e,{gen:a,compositeRule:o,allErrors:s}=i,c=Pl(e,t,r);n??(o||s)?Al(a,c):Rl(i,(0,B._)`[${c}]`)}Pe.reportError=Cg;function Tg(e,t=Pe.keywordError,r){let{it:n}=e,{gen:i,compositeRule:a,allErrors:o}=n,s=Pl(e,t,r);Al(i,s),a||o||Rl(n,Oe.default.vErrors)}Pe.reportExtraError=Tg;function xg(e,t){e.assign(Oe.default.errors,t),e.if((0,B._)`${Oe.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,B._)`${Oe.default.vErrors}.length`,t),()=>e.assign(Oe.default.vErrors,null)))}Pe.resetErrorsCount=xg;function Lg({gen:e,keyword:t,schemaValue:r,data:n,errsCount:i,it:a}){if(i===void 0)throw new Error("ajv implementation error");let o=e.name("err");e.forRange("i",i,Oe.default.errors,s=>{e.const(o,(0,B._)`${Oe.default.vErrors}[${s}]`),e.if((0,B._)`${o}.instancePath === undefined`,()=>e.assign((0,B._)`${o}.instancePath`,(0,B.strConcat)(Oe.default.instancePath,a.errorPath))),e.assign((0,B._)`${o}.schemaPath`,(0,B.str)`${a.errSchemaPath}/${t}`),a.opts.verbose&&(e.assign((0,B._)`${o}.schema`,r),e.assign((0,B._)`${o}.data`,n))})}Pe.extendErrors=Lg;function Al(e,t){let r=e.const("err",t);e.if((0,B._)`${Oe.default.vErrors} === null`,()=>e.assign(Oe.default.vErrors,(0,B._)`[${r}]`),(0,B._)`${Oe.default.vErrors}.push(${r})`),e.code((0,B._)`${Oe.default.errors}++`)}function Rl(e,t){let{gen:r,validateName:n,schemaEnv:i}=e;i.$async?r.throw((0,B._)`new ${e.ValidationError}(${t})`):(r.assign((0,B._)`${n}.errors`,t),r.return(!1))}var Yt={keyword:new B.Name("keyword"),schemaPath:new B.Name("schemaPath"),params:new B.Name("params"),propertyName:new B.Name("propertyName"),message:new B.Name("message"),schema:new B.Name("schema"),parentSchema:new B.Name("parentSchema")};function Pl(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,B._)`{}`:Vg(e,t,r)}function Vg(e,t,r={}){let{gen:n,it:i}=e,a=[Mg(i,r),qg(e,r)];return Ug(e,t,a),n.object(...a)}function Mg({errorPath:e},{instancePath:t}){let r=t?(0,B.str)`${e}${(0,ki.getErrorPath)(t,ki.Type.Str)}`:e;return[Oe.default.instancePath,(0,B.strConcat)(Oe.default.instancePath,r)]}function qg({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let i=n?t:(0,B.str)`${t}/${e}`;return r&&(i=(0,B.str)`${i}${(0,ki.getErrorPath)(r,ki.Type.Str)}`),[Yt.schemaPath,i]}function Ug(e,{params:t,message:r},n){let{keyword:i,data:a,schemaValue:o,it:s}=e,{opts:c,propertyName:d,topSchemaRef:l,schemaPath:p}=s;n.push([Yt.keyword,i],[Yt.params,typeof t=="function"?t(e):t||(0,B._)`{}`]),c.messages&&n.push([Yt.message,typeof r=="function"?r(e):r]),c.verbose&&n.push([Yt.schema,o],[Yt.parentSchema,(0,B._)`${l}${p}`],[Oe.default.data,a]),d&&n.push([Yt.propertyName,d])}});var Dl=R(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});Er.boolOrEmptySchema=Er.topBoolOrEmptySchema=void 0;var Fg=ln(),zg=x(),Bg=Je(),Gg={message:"boolean schema is false"};function Jg(e){let{gen:t,schema:r,validateName:n}=e;r===!1?Nl(e,!1):typeof r=="object"&&r.$async===!0?t.return(Bg.default.data):(t.assign((0,zg._)`${n}.errors`,null),t.return(!0))}Er.topBoolOrEmptySchema=Jg;function Wg(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),Nl(e)):r.var(t,!0)}Er.boolOrEmptySchema=Wg;function Nl(e,t){let{gen:r,data:n}=e,i={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,Fg.reportError)(i,Gg,void 0,t)}});var Eo=R(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});Ar.getRules=Ar.isJSONType=void 0;var Kg=["string","number","integer","boolean","null","object","array"],Yg=new Set(Kg);function Hg(e){return typeof e=="string"&&Yg.has(e)}Ar.isJSONType=Hg;function Zg(){let e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}Ar.getRules=Zg});var Ao=R(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.shouldUseRule=Dt.shouldUseGroup=Dt.schemaHasRulesForType=void 0;function Xg({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&Sl(e,n)}Dt.schemaHasRulesForType=Xg;function Sl(e,t){return t.rules.some(r=>jl(e,r))}Dt.shouldUseGroup=Sl;function jl(e,t){var r;return e[t.keyword]!==void 0||((r=t.definition.implements)===null||r===void 0?void 0:r.some(n=>e[n]!==void 0))}Dt.shouldUseRule=jl});var dn=R(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.reportTypeError=Ne.checkDataTypes=Ne.checkDataType=Ne.coerceAndCheckDataType=Ne.getJSONTypes=Ne.getSchemaTypes=Ne.DataType=void 0;var Qg=Eo(),eh=Ao(),th=ln(),L=x(),$l=U(),Rr;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(Rr||(Ne.DataType=Rr={}));function rh(e){let t=Ol(e.type);if(t.includes("null")){if(e.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');e.nullable===!0&&t.push("null")}return t}Ne.getSchemaTypes=rh;function Ol(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(Qg.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}Ne.getJSONTypes=Ol;function nh(e,t){let{gen:r,data:n,opts:i}=e,a=ih(t,i.coerceTypes),o=t.length>0&&!(a.length===0&&t.length===1&&(0,eh.schemaHasRulesForType)(e,t[0]));if(o){let s=Po(t,n,i.strictNumbers,Rr.Wrong);r.if(s,()=>{a.length?ah(e,t,a):No(e)})}return o}Ne.coerceAndCheckDataType=nh;var Cl=new Set(["string","number","integer","boolean","null"]);function ih(e,t){return t?e.filter(r=>Cl.has(r)||t==="array"&&r==="array"):[]}function ah(e,t,r){let{gen:n,data:i,opts:a}=e,o=n.let("dataType",(0,L._)`typeof ${i}`),s=n.let("coerced",(0,L._)`undefined`);a.coerceTypes==="array"&&n.if((0,L._)`${o} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>n.assign(i,(0,L._)`${i}[0]`).assign(o,(0,L._)`typeof ${i}`).if(Po(t,i,a.strictNumbers),()=>n.assign(s,i))),n.if((0,L._)`${s} !== undefined`);for(let d of r)(Cl.has(d)||d==="array"&&a.coerceTypes==="array")&&c(d);n.else(),No(e),n.endIf(),n.if((0,L._)`${s} !== undefined`,()=>{n.assign(i,s),oh(e,s)});function c(d){switch(d){case"string":n.elseIf((0,L._)`${o} == "number" || ${o} == "boolean"`).assign(s,(0,L._)`"" + ${i}`).elseIf((0,L._)`${i} === null`).assign(s,(0,L._)`""`);return;case"number":n.elseIf((0,L._)`${o} == "boolean" || ${i} === null
|
|
3
3
|
|| (${o} == "string" && ${i} && ${i} == +${i})`).assign(s,(0,L._)`+${i}`);return;case"integer":n.elseIf((0,L._)`${o} === "boolean" || ${i} === null
|
|
4
4
|
|| (${o} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(s,(0,L._)`+${i}`);return;case"boolean":n.elseIf((0,L._)`${i} === "false" || ${i} === 0 || ${i} === null`).assign(s,!1).elseIf((0,L._)`${i} === "true" || ${i} === 1`).assign(s,!0);return;case"null":n.elseIf((0,L._)`${i} === "" || ${i} === 0 || ${i} === false`),n.assign(s,null);return;case"array":n.elseIf((0,L._)`${o} === "string" || ${o} === "number"
|
|
5
|
-
|| ${o} === "boolean" || ${i} === null`).assign(s,(0,L._)`[${i}]`)}}}function oh({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,L._)`${t} !== undefined`,()=>e.assign((0,L._)`${t}[${r}]`,n))}function Ro(e,t,r,n=Rr.Correct){let i=n===Rr.Correct?L.operators.EQ:L.operators.NEQ,a;switch(e){case"null":return(0,L._)`${t} ${i} null`;case"array":a=(0,L._)`Array.isArray(${t})`;break;case"object":a=(0,L._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":a=o((0,L._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":a=o();break;default:return(0,L._)`typeof ${t} ${i} ${e}`}return n===Rr.Correct?a:(0,L.not)(a);function o(s=L.nil){return(0,L.and)((0,L._)`typeof ${t} == "number"`,s,r?(0,L._)`isFinite(${t})`:L.nil)}}Ne.checkDataType=Ro;function Po(e,t,r,n){if(e.length===1)return Ro(e[0],t,r,n);let i,a=(0,jl.toHash)(e);if(a.array&&a.object){let o=(0,L._)`typeof ${t} != "object"`;i=a.null?o:(0,L._)`!${t} || ${o}`,delete a.null,delete a.array,delete a.object}else i=L.nil;a.number&&delete a.integer;for(let o in a)i=(0,L.and)(i,Ro(o,t,r,n));return i}Ne.checkDataTypes=Po;var sh={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,L._)`{type: ${e}}`:(0,L._)`{type: ${t}}`};function No(e){let t=ch(e);(0,th.reportError)(t,sh)}Ne.reportTypeError=No;function ch(e){let{gen:t,data:r,schema:n}=e,i=(0,jl.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:e}}});var Tl=R(_i=>{"use strict";Object.defineProperty(_i,"__esModule",{value:!0});_i.assignDefaults=void 0;var Pr=x(),lh=U();function dh(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let i in r)Cl(e,i,r[i].default);else t==="array"&&Array.isArray(n)&&n.forEach((i,a)=>Cl(e,a,i.default))}_i.assignDefaults=dh;function Cl(e,t,r){let{gen:n,compositeRule:i,data:a,opts:o}=e;if(r===void 0)return;let s=(0,Pr._)`${a}${(0,Pr.getProperty)(t)}`;if(i){(0,lh.checkStrictMode)(e,`default is ignored for: ${s}`);return}let c=(0,Pr._)`${s} === undefined`;o.useDefaults==="empty"&&(c=(0,Pr._)`${c} || ${s} === null || ${s} === ""`),n.if(c,(0,Pr._)`${s} = ${(0,Pr.stringify)(r)}`)}});var We=R(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.validateUnion=ee.validateArray=ee.usePattern=ee.callValidateCode=ee.schemaProperties=ee.allSchemaProperties=ee.noPropertyInData=ee.propertyInData=ee.isOwnProperty=ee.hasPropFunc=ee.reportMissingProp=ee.checkMissingProp=ee.checkReportMissingProp=void 0;var ce=x(),Do=U(),St=Ge(),ph=U();function uh(e,t){let{gen:r,data:n,it:i}=e;r.if(jo(r,n,t,i.opts.ownProperties),()=>{e.setParams({missingProperty:(0,ce._)`${t}`},!0),e.error()})}ee.checkReportMissingProp=uh;function fh({gen:e,data:t,it:{opts:r}},n,i){return(0,ce.or)(...n.map(a=>(0,ce.and)(jo(e,t,a,r.ownProperties),(0,ce._)`${i} = ${a}`)))}ee.checkMissingProp=fh;function mh(e,t){e.setParams({missingProperty:t},!0),e.error()}ee.reportMissingProp=mh;function xl(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ce._)`Object.prototype.hasOwnProperty`})}ee.hasPropFunc=xl;function So(e,t,r){return(0,ce._)`${xl(e)}.call(${t}, ${r})`}ee.isOwnProperty=So;function gh(e,t,r,n){let i=(0,ce._)`${t}${(0,ce.getProperty)(r)} !== undefined`;return n?(0,ce._)`${i} && ${So(e,t,r)}`:i}ee.propertyInData=gh;function jo(e,t,r,n){let i=(0,ce._)`${t}${(0,ce.getProperty)(r)} === undefined`;return n?(0,ce.or)(i,(0,ce.not)(So(e,t,r))):i}ee.noPropertyInData=jo;function Ll(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}ee.allSchemaProperties=Ll;function hh(e,t){return Ll(t).filter(r=>!(0,Do.alwaysValidSchema)(e,t[r]))}ee.schemaProperties=hh;function yh({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:i,errorPath:a},it:o},s,c,d){let l=d?(0,ce._)`${e}, ${t}, ${n}${i}`:t,p=[[St.default.instancePath,(0,ce.strConcat)(St.default.instancePath,a)],[St.default.parentData,o.parentData],[St.default.parentDataProperty,o.parentDataProperty],[St.default.rootData,St.default.rootData]];o.opts.dynamicRef&&p.push([St.default.dynamicAnchors,St.default.dynamicAnchors]);let m=(0,ce._)`${l}, ${r.object(...p)}`;return c!==ce.nil?(0,ce._)`${s}.call(${c}, ${m})`:(0,ce._)`${s}(${m})`}ee.callValidateCode=yh;var wh=(0,ce._)`new RegExp`;function vh({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:i}=t.code,a=i(r,n);return e.scopeValue("pattern",{key:a.toString(),ref:a,code:(0,ce._)`${i.code==="new RegExp"?wh:(0,ph.useFunc)(e,i)}(${r}, ${n})`})}ee.usePattern=vh;function Ih(e){let{gen:t,data:r,keyword:n,it:i}=e,a=t.name("valid");if(i.allErrors){let s=t.let("valid",!0);return o(()=>t.assign(s,!1)),s}return t.var(a,!0),o(()=>t.break()),a;function o(s){let c=t.const("len",(0,ce._)`${r}.length`);t.forRange("i",0,c,d=>{e.subschema({keyword:n,dataProp:d,dataPropType:Do.Type.Num},a),t.if((0,ce.not)(a),s)})}}ee.validateArray=Ih;function bh(e){let{gen:t,schema:r,keyword:n,it:i}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,Do.alwaysValidSchema)(i,c))&&!i.opts.unevaluated)return;let o=t.let("valid",!1),s=t.name("_valid");t.block(()=>r.forEach((c,d)=>{let l=e.subschema({keyword:n,schemaProp:d,compositeRule:!0},s);t.assign(o,(0,ce._)`${o} || ${s}`),e.mergeValidEvaluated(l,s)||t.if((0,ce.not)(o))})),e.result(o,()=>e.reset(),()=>e.error(!0))}ee.validateUnion=bh});var ql=R(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.validateKeywordUsage=ft.validSchemaType=ft.funcKeywordCode=ft.macroKeywordCode=void 0;var Ce=x(),Ht=Ge(),kh=We(),_h=ln();function Eh(e,t){let{gen:r,keyword:n,schema:i,parentSchema:a,it:o}=e,s=t.macro.call(o.self,i,a,o),c=Ml(r,n,s);o.opts.validateSchema!==!1&&o.self.validateSchema(s,!0);let d=r.name("valid");e.subschema({schema:s,schemaPath:Ce.nil,errSchemaPath:`${o.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},d),e.pass(d,()=>e.error(!0))}ft.macroKeywordCode=Eh;function Ah(e,t){var r;let{gen:n,keyword:i,schema:a,parentSchema:o,$data:s,it:c}=e;Ph(c,t);let d=!s&&t.compile?t.compile.call(c.self,a,o,c):t.validate,l=Ml(n,i,d),p=n.let("valid");e.block$data(p,m),e.ok((r=t.valid)!==null&&r!==void 0?r:p);function m(){if(t.errors===!1)g(),t.modifying&&Vl(e),h(()=>e.error());else{let w=t.async?u():f();t.modifying&&Vl(e),h(()=>Rh(e,w))}}function u(){let w=n.let("ruleErrs",null);return n.try(()=>g((0,Ce._)`await `),_=>n.assign(p,!1).if((0,Ce._)`${_} instanceof ${c.ValidationError}`,()=>n.assign(w,(0,Ce._)`${_}.errors`),()=>n.throw(_))),w}function f(){let w=(0,Ce._)`${l}.errors`;return n.assign(w,null),g(Ce.nil),w}function g(w=t.async?(0,Ce._)`await `:Ce.nil){let _=c.opts.passContext?Ht.default.this:Ht.default.self,b=!("compile"in t&&!s||t.schema===!1);n.assign(p,(0,Ce._)`${w}${(0,kh.callValidateCode)(e,l,_,b)}`,t.modifying)}function h(w){var _;n.if((0,Ce.not)((_=t.valid)!==null&&_!==void 0?_:p),w)}}ft.funcKeywordCode=Ah;function Vl(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,Ce._)`${n.parentData}[${n.parentDataProperty}]`))}function Rh(e,t){let{gen:r}=e;r.if((0,Ce._)`Array.isArray(${t})`,()=>{r.assign(Ht.default.vErrors,(0,Ce._)`${Ht.default.vErrors} === null ? ${t} : ${Ht.default.vErrors}.concat(${t})`).assign(Ht.default.errors,(0,Ce._)`${Ht.default.vErrors}.length`),(0,_h.extendErrors)(e)},()=>e.error())}function Ph({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function Ml(e,t,r){if(r===void 0)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Ce.stringify)(r)})}function Nh(e,t,r=!1){return!t.length||t.some(n=>n==="array"?Array.isArray(e):n==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==n||r&&typeof e>"u")}ft.validSchemaType=Nh;function Dh({schema:e,opts:t,self:r,errSchemaPath:n},i,a){if(Array.isArray(i.keyword)?!i.keyword.includes(a):i.keyword!==a)throw new Error("ajv implementation error");let o=i.dependencies;if(o?.some(s=>!Object.prototype.hasOwnProperty.call(e,s)))throw new Error(`parent schema must have dependencies of ${a}: ${o.join(",")}`);if(i.validateSchema&&!i.validateSchema(e[a])){let c=`keyword "${a}" value is invalid at path "${n}": `+r.errorsText(i.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}ft.validateKeywordUsage=Dh});var Fl=R(jt=>{"use strict";Object.defineProperty(jt,"__esModule",{value:!0});jt.extendSubschemaMode=jt.extendSubschemaData=jt.getSubschema=void 0;var mt=x(),Ul=U();function Sh(e,{keyword:t,schemaProp:r,schema:n,schemaPath:i,errSchemaPath:a,topSchemaRef:o}){if(t!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let s=e.schema[t];return r===void 0?{schema:s,schemaPath:(0,mt._)`${e.schemaPath}${(0,mt.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:s[r],schemaPath:(0,mt._)`${e.schemaPath}${(0,mt.getProperty)(t)}${(0,mt.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,Ul.escapeFragment)(r)}`}}if(n!==void 0){if(i===void 0||a===void 0||o===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:i,topSchemaRef:o,errSchemaPath:a}}throw new Error('either "keyword" or "schema" must be passed')}jt.getSubschema=Sh;function jh(e,t,{dataProp:r,dataPropType:n,data:i,dataTypes:a,propertyName:o}){if(i!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:s}=t;if(r!==void 0){let{errorPath:d,dataPathArr:l,opts:p}=t,m=s.let("data",(0,mt._)`${t.data}${(0,mt.getProperty)(r)}`,!0);c(m),e.errorPath=(0,mt.str)`${d}${(0,Ul.getErrorPath)(r,n,p.jsPropertySyntax)}`,e.parentDataProperty=(0,mt._)`${r}`,e.dataPathArr=[...l,e.parentDataProperty]}if(i!==void 0){let d=i instanceof mt.Name?i:s.let("data",i,!0);c(d),o!==void 0&&(e.propertyName=o)}a&&(e.dataTypes=a);function c(d){e.data=d,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,d]}}jt.extendSubschemaData=jh;function $h(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:i,allErrors:a}){n!==void 0&&(e.compositeRule=n),i!==void 0&&(e.createErrors=i),a!==void 0&&(e.allErrors=a),e.jtdDiscriminator=t,e.jtdMetadata=r}jt.extendSubschemaMode=$h});var $o=R((nR,zl)=>{"use strict";zl.exports=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,i,a;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(i=n;i--!==0;)if(!e(t[i],r[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(a=Object.keys(t),n=a.length,n!==Object.keys(r).length)return!1;for(i=n;i--!==0;)if(!Object.prototype.hasOwnProperty.call(r,a[i]))return!1;for(i=n;i--!==0;){var o=a[i];if(!e(t[o],r[o]))return!1}return!0}return t!==t&&r!==r}});var Jl=R((iR,Bl)=>{"use strict";var $t=Bl.exports=function(e,t,r){typeof t=="function"&&(r=t,t={}),r=t.cb||r;var n=typeof r=="function"?r:r.pre||function(){},i=r.post||function(){};Ei(t,n,i,e,"",e)};$t.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};$t.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};$t.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};$t.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function Ei(e,t,r,n,i,a,o,s,c,d){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,i,a,o,s,c,d);for(var l in n){var p=n[l];if(Array.isArray(p)){if(l in $t.arrayKeywords)for(var m=0;m<p.length;m++)Ei(e,t,r,p[m],i+"/"+l+"/"+m,a,i,l,n,m)}else if(l in $t.propsKeywords){if(p&&typeof p=="object")for(var u in p)Ei(e,t,r,p[u],i+"/"+l+"/"+Oh(u),a,i,l,n,u)}else(l in $t.keywords||e.allKeys&&!(l in $t.skipKeywords))&&Ei(e,t,r,p,i+"/"+l,a,i,l,n)}r(n,i,a,o,s,c,d)}}function Oh(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var pn=R(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.getSchemaRefs=Me.resolveUrl=Me.normalizeId=Me._getFullPath=Me.getFullPath=Me.inlineRef=void 0;var Ch=U(),Th=$o(),xh=Jl(),Lh=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Vh(e,t=!0){return typeof e=="boolean"?!0:t===!0?!Oo(e):t?Gl(e)<=t:!1}Me.inlineRef=Vh;var Mh=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Oo(e){for(let t in e){if(Mh.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(Oo)||typeof r=="object"&&Oo(r))return!0}return!1}function Gl(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!Lh.has(r)&&(typeof e[r]=="object"&&(0,Ch.eachItem)(e[r],n=>t+=Gl(n)),t===1/0))return 1/0}return t}function Wl(e,t="",r){r!==!1&&(t=Nr(t));let n=e.parse(t);return Kl(e,n)}Me.getFullPath=Wl;function Kl(e,t){return e.serialize(t).split("#")[0]+"#"}Me._getFullPath=Kl;var qh=/#\/?$/;function Nr(e){return e?e.replace(qh,""):""}Me.normalizeId=Nr;function Uh(e,t,r){return r=Nr(r),e.resolve(t,r)}Me.resolveUrl=Uh;var Fh=/^[a-z_][-a-z0-9._]*$/i;function zh(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,i=Nr(e[r]||t),a={"":i},o=Wl(n,i,!1),s={},c=new Set;return xh(e,{allKeys:!0},(p,m,u,f)=>{if(f===void 0)return;let g=o+m,h=a[f];typeof p[r]=="string"&&(h=w.call(this,p[r])),_.call(this,p.$anchor),_.call(this,p.$dynamicAnchor),a[m]=h;function w(b){let A=this.opts.uriResolver.resolve;if(b=Nr(h?A(h,b):b),c.has(b))throw l(b);c.add(b);let y=this.refs[b];return typeof y=="string"&&(y=this.refs[y]),typeof y=="object"?d(p,y.schema,b):b!==Nr(g)&&(b[0]==="#"?(d(p,s[b],b),s[b]=p):this.refs[b]=g),b}function _(b){if(typeof b=="string"){if(!Fh.test(b))throw new Error(`invalid anchor "${b}"`);w.call(this,`#${b}`)}}}),s;function d(p,m,u){if(m!==void 0&&!Th(p,m))throw l(u)}function l(p){return new Error(`reference "${p}" resolves to more than one schema`)}}Me.getSchemaRefs=zh});var mn=R(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.getData=Ot.KeywordCxt=Ot.validateFunctionCode=void 0;var Ql=Nl(),Yl=dn(),To=Ao(),Ai=dn(),Bh=Tl(),fn=ql(),Co=Fl(),D=x(),T=Ge(),Jh=pn(),bt=U(),un=ln();function Gh(e){if(rd(e)&&(nd(e),td(e))){Yh(e);return}ed(e,()=>(0,Ql.topBoolOrEmptySchema)(e))}Ot.validateFunctionCode=Gh;function ed({gen:e,validateName:t,schema:r,schemaEnv:n,opts:i},a){i.code.es5?e.func(t,(0,D._)`${T.default.data}, ${T.default.valCxt}`,n.$async,()=>{e.code((0,D._)`"use strict"; ${Hl(r,i)}`),Kh(e,i),e.code(a)}):e.func(t,(0,D._)`${T.default.data}, ${Wh(i)}`,n.$async,()=>e.code(Hl(r,i)).code(a))}function Wh(e){return(0,D._)`{${T.default.instancePath}="", ${T.default.parentData}, ${T.default.parentDataProperty}, ${T.default.rootData}=${T.default.data}${e.dynamicRef?(0,D._)`, ${T.default.dynamicAnchors}={}`:D.nil}}={}`}function Kh(e,t){e.if(T.default.valCxt,()=>{e.var(T.default.instancePath,(0,D._)`${T.default.valCxt}.${T.default.instancePath}`),e.var(T.default.parentData,(0,D._)`${T.default.valCxt}.${T.default.parentData}`),e.var(T.default.parentDataProperty,(0,D._)`${T.default.valCxt}.${T.default.parentDataProperty}`),e.var(T.default.rootData,(0,D._)`${T.default.valCxt}.${T.default.rootData}`),t.dynamicRef&&e.var(T.default.dynamicAnchors,(0,D._)`${T.default.valCxt}.${T.default.dynamicAnchors}`)},()=>{e.var(T.default.instancePath,(0,D._)`""`),e.var(T.default.parentData,(0,D._)`undefined`),e.var(T.default.parentDataProperty,(0,D._)`undefined`),e.var(T.default.rootData,T.default.data),t.dynamicRef&&e.var(T.default.dynamicAnchors,(0,D._)`{}`)})}function Yh(e){let{schema:t,opts:r,gen:n}=e;ed(e,()=>{r.$comment&&t.$comment&&ad(e),ey(e),n.let(T.default.vErrors,null),n.let(T.default.errors,0),r.unevaluated&&Hh(e),id(e),ny(e)})}function Hh(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,D._)`${r}.evaluated`),t.if((0,D._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,D._)`${e.evaluated}.props`,(0,D._)`undefined`)),t.if((0,D._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,D._)`${e.evaluated}.items`,(0,D._)`undefined`))}function Hl(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,D._)`/*# sourceURL=${r} */`:D.nil}function Zh(e,t){if(rd(e)&&(nd(e),td(e))){Xh(e,t);return}(0,Ql.boolOrEmptySchema)(e,t)}function td({schema:e,self:t}){if(typeof e=="boolean")return!e;for(let r in e)if(t.RULES.all[r])return!0;return!1}function rd(e){return typeof e.schema!="boolean"}function Xh(e,t){let{schema:r,gen:n,opts:i}=e;i.$comment&&r.$comment&&ad(e),ty(e),ry(e);let a=n.const("_errs",T.default.errors);id(e,a),n.var(t,(0,D._)`${a} === ${T.default.errors}`)}function nd(e){(0,bt.checkUnknownRules)(e),Qh(e)}function id(e,t){if(e.opts.jtd)return Zl(e,[],!1,t);let r=(0,Yl.getSchemaTypes)(e.schema),n=(0,Yl.coerceAndCheckDataType)(e,r);Zl(e,r,!n,t)}function Qh(e){let{schema:t,errSchemaPath:r,opts:n,self:i}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,bt.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function ey(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,bt.checkStrictMode)(e,"default is ignored in the schema root")}function ty(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,Jh.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function ry(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function ad({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:i}){let a=r.$comment;if(i.$comment===!0)e.code((0,D._)`${T.default.self}.logger.log(${a})`);else if(typeof i.$comment=="function"){let o=(0,D.str)`${n}/$comment`,s=e.scopeValue("root",{ref:t.root});e.code((0,D._)`${T.default.self}.opts.$comment(${a}, ${o}, ${s}.schema)`)}}function ny(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:i,opts:a}=e;r.$async?t.if((0,D._)`${T.default.errors} === 0`,()=>t.return(T.default.data),()=>t.throw((0,D._)`new ${i}(${T.default.vErrors})`)):(t.assign((0,D._)`${n}.errors`,T.default.vErrors),a.unevaluated&&iy(e),t.return((0,D._)`${T.default.errors} === 0`))}function iy({gen:e,evaluated:t,props:r,items:n}){r instanceof D.Name&&e.assign((0,D._)`${t}.props`,r),n instanceof D.Name&&e.assign((0,D._)`${t}.items`,n)}function Zl(e,t,r,n){let{gen:i,schema:a,data:o,allErrors:s,opts:c,self:d}=e,{RULES:l}=d;if(a.$ref&&(c.ignoreKeywordsWithRef||!(0,bt.schemaHasRulesButRef)(a,l))){i.block(()=>sd(e,"$ref",l.all.$ref.definition));return}c.jtd||ay(e,t),i.block(()=>{for(let m of l.rules)p(m);p(l.post)});function p(m){(0,To.shouldUseGroup)(a,m)&&(m.type?(i.if((0,Ai.checkDataType)(m.type,o,c.strictNumbers)),Xl(e,m),t.length===1&&t[0]===m.type&&r&&(i.else(),(0,Ai.reportTypeError)(e)),i.endIf()):Xl(e,m),s||i.if((0,D._)`${T.default.errors} === ${n||0}`))}}function Xl(e,t){let{gen:r,schema:n,opts:{useDefaults:i}}=e;i&&(0,Bh.assignDefaults)(e,t.type),r.block(()=>{for(let a of t.rules)(0,To.shouldUseRule)(n,a)&&sd(e,a.keyword,a.definition,t.type)})}function ay(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(oy(e,t),e.opts.allowUnionTypes||sy(e,t),cy(e,e.dataTypes))}function oy(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{od(e.dataTypes,r)||xo(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),dy(e,t)}}function sy(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&xo(e,"use allowUnionTypes to allow union type keyword")}function cy(e,t){let r=e.self.RULES.all;for(let n in r){let i=r[n];if(typeof i=="object"&&(0,To.shouldUseRule)(e.schema,i)){let{type:a}=i.definition;a.length&&!a.some(o=>ly(t,o))&&xo(e,`missing type "${a.join(",")}" for keyword "${n}"`)}}}function ly(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function od(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function dy(e,t){let r=[];for(let n of e.dataTypes)od(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}function xo(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,bt.checkStrictMode)(e,t,e.opts.strictTypes)}var Ri=class{constructor(t,r,n){if((0,fn.validateKeywordUsage)(t,r,n),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=n,this.data=t.data,this.schema=t.schema[n],this.$data=r.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,bt.schemaRefOrVal)(t,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=r,this.$data)this.schemaCode=t.gen.const("vSchema",cd(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,fn.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=t.gen.const("_errs",T.default.errors))}result(t,r,n){this.failResult((0,D.not)(t),r,n)}failResult(t,r,n){this.gen.if(t),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,r){this.failResult((0,D.not)(t),void 0,r)}fail(t){if(t===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(t),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(t){if(!this.$data)return this.fail(t);let{schemaCode:r}=this;this.fail((0,D._)`${r} !== undefined && (${(0,D.or)(this.invalid$data(),t)})`)}error(t,r,n){if(r){this.setParams(r),this._error(t,n),this.setParams({});return}this._error(t,n)}_error(t,r){(t?un.reportExtraError:un.reportError)(this,this.def.error,r)}$dataError(){(0,un.reportError)(this,this.def.$dataError||un.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,un.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,r){r?Object.assign(this.params,t):this.params=t}block$data(t,r,n=D.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=D.nil,r=D.nil){if(!this.$data)return;let{gen:n,schemaCode:i,schemaType:a,def:o}=this;n.if((0,D.or)((0,D._)`${i} === undefined`,r)),t!==D.nil&&n.assign(t,!0),(a.length||o.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==D.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:i,it:a}=this;return(0,D.or)(o(),s());function o(){if(n.length){if(!(r instanceof D.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,D._)`${(0,Ai.checkDataTypes)(c,r,a.opts.strictNumbers,Ai.DataType.Wrong)}`}return D.nil}function s(){if(i.validateSchema){let c=t.scopeValue("validate$data",{ref:i.validateSchema});return(0,D._)`!${c}(${r})`}return D.nil}}subschema(t,r){let n=(0,Co.getSubschema)(this.it,t);(0,Co.extendSubschemaData)(n,this.it,t),(0,Co.extendSubschemaMode)(n,t);let i={...this.it,...n,items:void 0,props:void 0};return Zh(i,r),i}mergeEvaluated(t,r){let{it:n,gen:i}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=bt.mergeEvaluated.props(i,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=bt.mergeEvaluated.items(i,t.items,n.items,r)))}mergeValidEvaluated(t,r){let{it:n,gen:i}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return i.if(r,()=>this.mergeEvaluated(t,D.Name)),!0}};Ot.KeywordCxt=Ri;function sd(e,t,r,n){let i=new Ri(e,r,t);"code"in r?r.code(i,n):i.$data&&r.validate?(0,fn.funcKeywordCode)(i,r):"macro"in r?(0,fn.macroKeywordCode)(i,r):(r.compile||r.validate)&&(0,fn.funcKeywordCode)(i,r)}var py=/^\/(?:[^~]|~0|~1)*$/,uy=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function cd(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let i,a;if(e==="")return T.default.rootData;if(e[0]==="/"){if(!py.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);i=e,a=T.default.rootData}else{let d=uy.exec(e);if(!d)throw new Error(`Invalid JSON-pointer: ${e}`);let l=+d[1];if(i=d[2],i==="#"){if(l>=t)throw new Error(c("property/index",l));return n[t-l]}if(l>t)throw new Error(c("data",l));if(a=r[t-l],!i)return a}let o=a,s=i.split("/");for(let d of s)d&&(a=(0,D._)`${a}${(0,D.getProperty)((0,bt.unescapeJsonPointer)(d))}`,o=(0,D._)`${o} && ${a}`);return o;function c(d,l){return`Cannot access ${d} ${l} levels up, current level is ${t}`}}Ot.getData=cd});var Pi=R(Vo=>{"use strict";Object.defineProperty(Vo,"__esModule",{value:!0});var Lo=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};Vo.default=Lo});var gn=R(Uo=>{"use strict";Object.defineProperty(Uo,"__esModule",{value:!0});var Mo=pn(),qo=class extends Error{constructor(t,r,n,i){super(i||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Mo.resolveUrl)(t,r,n),this.missingSchema=(0,Mo.normalizeId)((0,Mo.getFullPath)(t,this.missingRef))}};Uo.default=qo});var hn=R(Ke=>{"use strict";Object.defineProperty(Ke,"__esModule",{value:!0});Ke.resolveSchema=Ke.getCompilingSchema=Ke.resolveRef=Ke.compileSchema=Ke.SchemaEnv=void 0;var nt=x(),fy=Pi(),Zt=Ge(),it=pn(),ld=U(),my=mn(),Dr=class{constructor(t){var r;this.refs={},this.dynamicAnchors={};let n;typeof t.schema=="object"&&(n=t.schema),this.schema=t.schema,this.schemaId=t.schemaId,this.root=t.root||this,this.baseId=(r=t.baseId)!==null&&r!==void 0?r:(0,it.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};Ke.SchemaEnv=Dr;function zo(e){let t=dd.call(this,e);if(t)return t;let r=(0,it.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:i}=this.opts.code,{ownProperties:a}=this.opts,o=new nt.CodeGen(this.scope,{es5:n,lines:i,ownProperties:a}),s;e.$async&&(s=o.scopeValue("Error",{ref:fy.default,code:(0,nt._)`require("ajv/dist/runtime/validation_error").default`}));let c=o.scopeName("validate");e.validateName=c;let d={gen:o,allErrors:this.opts.allErrors,data:Zt.default.data,parentData:Zt.default.parentData,parentDataProperty:Zt.default.parentDataProperty,dataNames:[Zt.default.data],dataPathArr:[nt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,nt.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:s,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:nt.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,nt._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(e),(0,my.validateFunctionCode)(d),o.optimize(this.opts.code.optimize);let p=o.toString();l=`${o.scopeRefs(Zt.default.scope)}return ${p}`,this.opts.code.process&&(l=this.opts.code.process(l,e));let u=new Function(`${Zt.default.self}`,`${Zt.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:u}),u.errors=null,u.schema=e.schema,u.schemaEnv=e,e.$async&&(u.$async=!0),this.opts.code.source===!0&&(u.source={validateName:c,validateCode:p,scopeValues:o._values}),this.opts.unevaluated){let{props:f,items:g}=d;u.evaluated={props:f instanceof nt.Name?void 0:f,items:g instanceof nt.Name?void 0:g,dynamicProps:f instanceof nt.Name,dynamicItems:g instanceof nt.Name},u.source&&(u.source.evaluated=(0,nt.stringify)(u.evaluated))}return e.validate=u,e}catch(p){throw delete e.validate,delete e.validateName,l&&this.logger.error("Error compiling schema, function code:",l),p}finally{this._compilations.delete(e)}}Ke.compileSchema=zo;function gy(e,t,r){var n;r=(0,it.resolveUrl)(this.opts.uriResolver,t,r);let i=e.refs[r];if(i)return i;let a=wy.call(this,e,r);if(a===void 0){let o=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:s}=this.opts;o&&(a=new Dr({schema:o,schemaId:s,root:e,baseId:t}))}if(a!==void 0)return e.refs[r]=hy.call(this,a)}Ke.resolveRef=gy;function hy(e){return(0,it.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:zo.call(this,e)}function dd(e){for(let t of this._compilations)if(yy(t,e))return t}Ke.getCompilingSchema=dd;function yy(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function wy(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||Ni.call(this,e,t)}function Ni(e,t){let r=this.opts.uriResolver.parse(t),n=(0,it._getFullPath)(this.opts.uriResolver,r),i=(0,it.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===i)return Fo.call(this,r,e);let a=(0,it.normalizeId)(n),o=this.refs[a]||this.schemas[a];if(typeof o=="string"){let s=Ni.call(this,e,o);return typeof s?.schema!="object"?void 0:Fo.call(this,r,s)}if(typeof o?.schema=="object"){if(o.validate||zo.call(this,o),a===(0,it.normalizeId)(t)){let{schema:s}=o,{schemaId:c}=this.opts,d=s[c];return d&&(i=(0,it.resolveUrl)(this.opts.uriResolver,i,d)),new Dr({schema:s,schemaId:c,root:e,baseId:i})}return Fo.call(this,r,o)}}Ke.resolveSchema=Ni;var vy=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Fo(e,{baseId:t,schema:r,root:n}){var i;if(((i=e.fragment)===null||i===void 0?void 0:i[0])!=="/")return;for(let s of e.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,ld.unescapeFragment)(s)];if(c===void 0)return;r=c;let d=typeof r=="object"&&r[this.opts.schemaId];!vy.has(s)&&d&&(t=(0,it.resolveUrl)(this.opts.uriResolver,t,d))}let a;if(typeof r!="boolean"&&r.$ref&&!(0,ld.schemaHasRulesButRef)(r,this.RULES)){let s=(0,it.resolveUrl)(this.opts.uriResolver,t,r.$ref);a=Ni.call(this,n,s)}let{schemaId:o}=this.opts;if(a=a||new Dr({schema:r,schemaId:o,root:n,baseId:t}),a.schema!==a.root.schema)return a}});var pd=R((dR,Iy)=>{Iy.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Go=R((pR,yd)=>{"use strict";var by=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),fd=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),Bo=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),md=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),ky=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Jo(e){let t="",r=0,n=0;for(n=0;n<e.length;n++)if(r=e[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n];break}for(n+=1;n<e.length;n++){if(r=e[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n]}return t}var _y=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function ud(e){return e.length=0,!0}function Ey(e,t,r){if(e.length){let n=Jo(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}function Ay(e){let t=0,r={error:!1,address:"",zone:""},n=[],i=[],a=!1,o=!1,s=Ey;for(let c=0;c<e.length;c++){let d=e[c];if(!(d==="["||d==="]"))if(d===":"){if(a===!0&&(o=!0),!s(i,n,r))break;if(++t>7){r.error=!0;break}c>0&&e[c-1]===":"&&(a=!0),n.push(":");continue}else if(d==="%"){if(!s(i,n,r))break;s=ud}else{i.push(d);continue}}return i.length&&(s===ud?r.zone=i.join(""):o?n.push(i.join("")):n.push(Jo(i))),r.address=n.join(""),r}function gd(e){if(Ry(e,":")<2)return{host:e,isIPV6:!1};let t=Ay(e);if(t.error)return{host:e,isIPV6:!1};{let r=t.address,n=t.address;return t.zone&&(r+="%"+t.zone,n+="%25"+t.zone),{host:r,isIPV6:!0,escapedHost:n}}}function Ry(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}function Py(e){let t=e,r=[],n=-1,i=0;for(;i=t.length;){if(i===1){if(t===".")break;if(t==="/"){r.push("/");break}else{r.push(t);break}}else if(i===2){if(t[0]==="."){if(t[1]===".")break;if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&(t[1]==="."||t[1]==="/")){r.push("/");break}}else if(i===3&&t==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(t[0]==="."){if(t[1]==="."){if(t[2]==="/"){t=t.slice(3);continue}}else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&t[1]==="."){if(t[2]==="/"){t=t.slice(2);continue}else if(t[2]==="."&&t[3]==="/"){t=t.slice(3),r.length!==0&&r.pop();continue}}if((n=t.indexOf("/",1))===-1){r.push(t);break}else r.push(t.slice(0,n)),t=t.slice(n)}return r.join("")}var Ny={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},Dy=/[@/?#:]/g,Sy=/[@/?#]/g;function hd(e,t){let r=t?Sy:Dy;return r.lastIndex=0,e.replace(r,n=>Ny[n])}function jy(e,t=!1){if(e.indexOf("%")===-1)return e;let r="";for(let n=0;n<e.length;n++){if(e[n]==="%"&&n+2<e.length){let i=e.slice(n+1,n+3);if(Bo(i)){let a=i.toUpperCase(),o=String.fromCharCode(parseInt(a,16));t&&md(o)?r+=o:r+="%"+a,n+=2;continue}}r+=e[n]}return r}function $y(e){let t="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){let n=e.slice(r+1,r+3);if(Bo(n)){let i=n.toUpperCase(),a=String.fromCharCode(parseInt(i,16));a!=="."&&md(a)?t+=a:t+="%"+i,r+=2;continue}}ky(e[r])?t+=e[r]:t+=escape(e[r])}return t}function Oy(e){let t="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){let n=e.slice(r+1,r+3);if(Bo(n)){t+="%"+n.toUpperCase(),r+=2;continue}}t+=escape(e[r])}return t}function Cy(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!fd(r)){let n=gd(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=hd(r,!1)}t.push(r)}return(typeof e.port=="number"||typeof e.port=="string")&&(t.push(":"),t.push(String(e.port))),t.length?t.join(""):void 0}yd.exports={nonSimpleDomain:_y,recomposeAuthority:Cy,reescapeHostDelimiters:hd,normalizePercentEncoding:jy,normalizePathEncoding:$y,escapePreservingEscapes:Oy,removeDotSegments:Py,isIPv4:fd,isUUID:by,normalizeIPv6:gd,stringArrayToHexStripped:Jo}});var kd=R((uR,bd)=>{"use strict";var{isUUID:Ty}=Go(),xy=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,Ly=["http","https","ws","wss","urn","urn:uuid"];function Vy(e){return Ly.indexOf(e)!==-1}function Wo(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]==="w"||e.scheme[0]==="W")&&(e.scheme[1]==="s"||e.scheme[1]==="S")&&(e.scheme[2]==="s"||e.scheme[2]==="S"):!1}function wd(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function vd(e){let t=String(e.scheme).toLowerCase()==="https";return(e.port===(t?443:80)||e.port==="")&&(e.port=void 0),e.path||(e.path="/"),e}function My(e){return e.secure=Wo(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function qy(e){if((e.port===(Wo(e)?443:80)||e.port==="")&&(e.port=void 0),typeof e.secure=="boolean"&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){let[t,r]=e.resourceName.split("?");e.path=t&&t!=="/"?t:void 0,e.query=r,e.resourceName=void 0}return e.fragment=void 0,e}function Uy(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(xy);if(r){let n=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];let i=`${n}:${t.nid||e.nid}`,a=Ko(i);e.path=void 0,a&&(e=a.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function Fy(e,t){if(e.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),i=`${r}:${t.nid||n}`,a=Ko(i);a&&(e=a.serialize(e,t));let o=e,s=e.nss;return o.path=`${n||t.nid}:${s}`,t.skipEscape=!0,o}function zy(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!Ty(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function By(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var Id={scheme:"http",domainHost:!0,parse:wd,serialize:vd},Jy={scheme:"https",domainHost:Id.domainHost,parse:wd,serialize:vd},Di={scheme:"ws",domainHost:!0,parse:My,serialize:qy},Gy={scheme:"wss",domainHost:Di.domainHost,parse:Di.parse,serialize:Di.serialize},Wy={scheme:"urn",parse:Uy,serialize:Fy,skipNormalize:!0},Ky={scheme:"urn:uuid",parse:zy,serialize:By,skipNormalize:!0},Si={http:Id,https:Jy,ws:Di,wss:Gy,urn:Wy,"urn:uuid":Ky};Object.setPrototypeOf(Si,null);function Ko(e){return e&&(Si[e]||Si[e.toLowerCase()])||void 0}bd.exports={wsIsSecure:Wo,SCHEMES:Si,isValidSchemeName:Vy,getSchemeHandler:Ko}});var Pd=R((fR,Oi)=>{"use strict";var{normalizeIPv6:Yy,removeDotSegments:yn,recomposeAuthority:Hy,normalizePercentEncoding:Zy,normalizePathEncoding:Xy,escapePreservingEscapes:Qy,reescapeHostDelimiters:ew,isIPv4:tw,nonSimpleDomain:rw}=Go(),{SCHEMES:nw,getSchemeHandler:Ed}=kd();function iw(e,t){return typeof e=="string"?e=pw(e,t):typeof e=="object"&&(e=$i(Xt(e,t),t)),e}function aw(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:i,malformedAuthorityOrPort:a}=ji(e,n),{parsed:o,malformedAuthorityOrPort:s}=ji(t,n);if(a||s)throw new Error(i.error||o.error||"URI is malformed.");let c=Ad(i,o,n,!0);return n.skipEscape=!0,Xt(c,n)}function Ad(e,t,r,n){let i={};return n||(e=$i(Xt(e,r),r),t=$i(Xt(t,r),r)),r=r||{},!r.tolerant&&t.scheme?(i.scheme=t.scheme,i.userinfo=t.userinfo,i.host=t.host,i.port=t.port,i.path=yn(t.path||""),i.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(i.userinfo=t.userinfo,i.host=t.host,i.port=t.port,i.path=yn(t.path||""),i.query=t.query):(t.path?(t.path[0]==="/"?i.path=yn(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?i.path="/"+t.path:e.path?i.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:i.path=t.path,i.path=yn(i.path)),i.query=t.query):(i.path=e.path,t.query!==void 0?i.query=t.query:i.query=e.query),i.userinfo=e.userinfo,i.host=e.host,i.port=e.port),i.scheme=e.scheme),i.fragment=t.fragment,i}function ow(e,t,r){let n=_d(e,r),i=_d(t,r);return n!==void 0&&i!==void 0&&n.toLowerCase()===i.toLowerCase()}function Xt(e,t){let r={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},n=Object.assign({},t),i=[],a=Ed(n.scheme||r.scheme);a&&a.serialize&&a.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=Zy(r.path):(r.path=Qy(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&i.push(r.scheme,":");let o=Hy(r);if(o!==void 0&&(n.reference!=="suffix"&&i.push("//"),i.push(o),r.path&&r.path[0]!=="/"&&i.push("/")),r.path!==void 0){let s=r.path;!n.absolutePath&&(!a||!a.absolutePath)&&(s=yn(s)),o===void 0&&s[0]==="/"&&s[1]==="/"&&(s="/%2F"+s.slice(2)),i.push(s)}return r.query!==void 0&&i.push("?",r.query),r.fragment!==void 0&&i.push("#",r.fragment),i.join("")}var sw=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,cw=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,lw=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function dw(e,t){if(t[2]!==void 0&&e.path&&e.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof e.port=="number"&&(e.port<0||e.port>65535))return"URI port is malformed."}function ji(e,t){let r=Object.assign({},t),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},i=!1,a=!1;r.reference==="suffix"&&(r.scheme?e=r.scheme+":"+e:e="//"+e);let o=e.match(cw);o!==null&&o[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",i=!0);let s=e.match(lw);if(s!==null){let d=s[1],l=d.replace(/[\t\n\r]/g,"");l.length>=2&&(l.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",i=!0):d.length!==l.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",i=!0))}let c=e.match(sw);if(c){n.scheme=c[1],n.userinfo=c[3],n.host=c[4],n.port=parseInt(c[5],10),n.path=c[6]||"",n.query=c[7],n.fragment=c[8],isNaN(n.port)&&(n.port=c[5]);let d=dw(n,c);if(d!==void 0&&(n.error=n.error||d,i=!0),n.host)if(tw(n.host)===!1){let m=Yy(n.host);n.host=m.host.toLowerCase(),a=m.isIPV6}else a=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let l=Ed(r.scheme||n.scheme);if(!r.unicodeSupport&&(!l||!l.unicodeSupport)&&n.host&&(r.domainHost||l&&l.domainHost)&&a===!1&&rw(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(p){n.error=n.error||"Host's domain name can not be converted to ASCII: "+p}if((!l||l&&!l.skipNormalize)&&(e.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=ew(unescape(n.host),a))),n.path&&(n.path=Xy(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}l&&l.parse&&l.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:i}}function $i(e,t){return ji(e,t).parsed}function pw(e,t){return Rd(e,t).normalized}function Rd(e,t){let{parsed:r,malformedAuthorityOrPort:n}=ji(e,t);return{normalized:n?e:Xt(r,t),malformedAuthorityOrPort:n}}function _d(e,t){if(typeof e=="string"){let{normalized:r,malformedAuthorityOrPort:n}=Rd(e,t);return n?void 0:r}if(typeof e=="object")return Xt(e,t)}var Yo={SCHEMES:nw,normalize:iw,resolve:aw,resolveComponent:Ad,equal:ow,serialize:Xt,parse:$i};Oi.exports=Yo;Oi.exports.default=Yo;Oi.exports.fastUri=Yo});var Dd=R(Ho=>{"use strict";Object.defineProperty(Ho,"__esModule",{value:!0});var Nd=Pd();Nd.code='require("ajv/dist/runtime/uri").default';Ho.default=Nd});var Ld=R(Ie=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.CodeGen=Ie.Name=Ie.nil=Ie.stringify=Ie.str=Ie._=Ie.KeywordCxt=void 0;var uw=mn();Object.defineProperty(Ie,"KeywordCxt",{enumerable:!0,get:function(){return uw.KeywordCxt}});var Sr=x();Object.defineProperty(Ie,"_",{enumerable:!0,get:function(){return Sr._}});Object.defineProperty(Ie,"str",{enumerable:!0,get:function(){return Sr.str}});Object.defineProperty(Ie,"stringify",{enumerable:!0,get:function(){return Sr.stringify}});Object.defineProperty(Ie,"nil",{enumerable:!0,get:function(){return Sr.nil}});Object.defineProperty(Ie,"Name",{enumerable:!0,get:function(){return Sr.Name}});Object.defineProperty(Ie,"CodeGen",{enumerable:!0,get:function(){return Sr.CodeGen}});var fw=Pi(),Cd=gn(),mw=Eo(),wn=hn(),gw=x(),vn=pn(),Ci=dn(),Xo=U(),Sd=pd(),hw=Dd(),Td=(e,t)=>new RegExp(e,t);Td.code="new RegExp";var yw=["removeAdditional","useDefaults","coerceTypes"],ww=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),vw={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},Iw={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},jd=200;function bw(e){var t,r,n,i,a,o,s,c,d,l,p,m,u,f,g,h,w,_,b,A,y,k,S,O,se;let $=e.strict,P=(t=e.code)===null||t===void 0?void 0:t.optimize,Y=P===!0||P===void 0?1:P||0,ne=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Td,Be=(i=e.uriResolver)!==null&&i!==void 0?i:hw.default;return{strictSchema:(o=(a=e.strictSchema)!==null&&a!==void 0?a:$)!==null&&o!==void 0?o:!0,strictNumbers:(c=(s=e.strictNumbers)!==null&&s!==void 0?s:$)!==null&&c!==void 0?c:!0,strictTypes:(l=(d=e.strictTypes)!==null&&d!==void 0?d:$)!==null&&l!==void 0?l:"log",strictTuples:(m=(p=e.strictTuples)!==null&&p!==void 0?p:$)!==null&&m!==void 0?m:"log",strictRequired:(f=(u=e.strictRequired)!==null&&u!==void 0?u:$)!==null&&f!==void 0?f:!1,code:e.code?{...e.code,optimize:Y,regExp:ne}:{optimize:Y,regExp:ne},loopRequired:(g=e.loopRequired)!==null&&g!==void 0?g:jd,loopEnum:(h=e.loopEnum)!==null&&h!==void 0?h:jd,meta:(w=e.meta)!==null&&w!==void 0?w:!0,messages:(_=e.messages)!==null&&_!==void 0?_:!0,inlineRefs:(b=e.inlineRefs)!==null&&b!==void 0?b:!0,schemaId:(A=e.schemaId)!==null&&A!==void 0?A:"$id",addUsedSchema:(y=e.addUsedSchema)!==null&&y!==void 0?y:!0,validateSchema:(k=e.validateSchema)!==null&&k!==void 0?k:!0,validateFormats:(S=e.validateFormats)!==null&&S!==void 0?S:!0,unicodeRegExp:(O=e.unicodeRegExp)!==null&&O!==void 0?O:!0,int32range:(se=e.int32range)!==null&&se!==void 0?se:!0,uriResolver:Be}}var In=class{constructor(t={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,t=this.opts={...t,...bw(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new gw.ValueScope({scope:{},prefixes:ww,es5:r,lines:n}),this.logger=Pw(t.logger);let i=t.validateFormats;t.validateFormats=!1,this.RULES=(0,mw.getRules)(),$d.call(this,vw,t,"NOT SUPPORTED"),$d.call(this,Iw,t,"DEPRECATED","warn"),this._metaOpts=Aw.call(this),t.formats&&_w.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&Ew.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),kw.call(this),t.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,i=Sd;n==="id"&&(i={...Sd},i.id=i.$id,delete i.$id),r&&t&&this.addMetaSchema(i,i[n],!1)}defaultMeta(){let{meta:t,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof t=="object"?t[r]||t:void 0}validate(t,r){let n;if(typeof t=="string"){if(n=this.getSchema(t),!n)throw new Error(`no schema with key or ref "${t}"`)}else n=this.compile(t);let i=n(r);return"$async"in n||(this.errors=n.errors),i}compile(t,r){let n=this._addSchema(t,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(t,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return i.call(this,t,r);async function i(l,p){await a.call(this,l.$schema);let m=this._addSchema(l,p);return m.validate||o.call(this,m)}async function a(l){l&&!this.getSchema(l)&&await i.call(this,{$ref:l},!0)}async function o(l){try{return this._compileSchemaEnv(l)}catch(p){if(!(p instanceof Cd.default))throw p;return s.call(this,p),await c.call(this,p.missingSchema),o.call(this,l)}}function s({missingSchema:l,missingRef:p}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${p} cannot be resolved`)}async function c(l){let p=await d.call(this,l);this.refs[l]||await a.call(this,p.$schema),this.refs[l]||this.addSchema(p,l,r)}async function d(l){let p=this._loading[l];if(p)return p;try{return await(this._loading[l]=n(l))}finally{delete this._loading[l]}}}addSchema(t,r,n,i=this.opts.validateSchema){if(Array.isArray(t)){for(let o of t)this.addSchema(o,void 0,n,i);return this}let a;if(typeof t=="object"){let{schemaId:o}=this.opts;if(a=t[o],a!==void 0&&typeof a!="string")throw new Error(`schema ${o} must be string`)}return r=(0,vn.normalizeId)(r||a),this._checkUnique(r),this.schemas[r]=this._addSchema(t,n,r,i,!0),this}addMetaSchema(t,r,n=this.opts.validateSchema){return this.addSchema(t,r,!0,n),this}validateSchema(t,r){if(typeof t=="boolean")return!0;let n;if(n=t.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let i=this.validate(n,t);if(!i&&r){let a="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(a);else throw new Error(a)}return i}getSchema(t){let r;for(;typeof(r=Od.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,i=new wn.SchemaEnv({schema:{},schemaId:n});if(r=wn.resolveSchema.call(this,i,t),!r)return;this.refs[t]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(t){if(t instanceof RegExp)return this._removeAllSchemas(this.schemas,t),this._removeAllSchemas(this.refs,t),this;switch(typeof t){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=Od.call(this,t);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[t],delete this.refs[t],this}case"object":{let r=t;this._cache.delete(r);let n=t[this.opts.schemaId];return n&&(n=(0,vn.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(t){for(let r of t)this.addKeyword(r);return this}addKeyword(t,r){let n;if(typeof t=="string")n=t,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof t=="object"&&r===void 0){if(r=t,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(Dw.call(this,n,r),!r)return(0,Xo.eachItem)(n,a=>Zo.call(this,a)),this;jw.call(this,r);let i={...r,type:(0,Ci.getJSONTypes)(r.type),schemaType:(0,Ci.getJSONTypes)(r.schemaType)};return(0,Xo.eachItem)(n,i.type.length===0?a=>Zo.call(this,a,i):a=>i.type.forEach(o=>Zo.call(this,a,i,o))),this}getKeyword(t){let r=this.RULES.all[t];return typeof r=="object"?r.definition:!!r}removeKeyword(t){let{RULES:r}=this;delete r.keywords[t],delete r.all[t];for(let n of r.rules){let i=n.rules.findIndex(a=>a.keyword===t);i>=0&&n.rules.splice(i,1)}return this}addFormat(t,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[t]=r,this}errorsText(t=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!t||t.length===0?"No errors":t.map(i=>`${n}${i.instancePath} ${i.message}`).reduce((i,a)=>i+r+a)}$dataMetaSchema(t,r){let n=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let i of r){let a=i.split("/").slice(1),o=t;for(let s of a)o=o[s];for(let s in n){let c=n[s];if(typeof c!="object")continue;let{$data:d}=c.definition,l=o[s];d&&l&&(o[s]=xd(l))}}return t}_removeAllSchemas(t,r){for(let n in t){let i=t[n];(!r||r.test(n))&&(typeof i=="string"?delete t[n]:i&&!i.meta&&(this._cache.delete(i.schema),delete t[n]))}}_addSchema(t,r,n,i=this.opts.validateSchema,a=this.opts.addUsedSchema){let o,{schemaId:s}=this.opts;if(typeof t=="object")o=t[s];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof t!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(t);if(c!==void 0)return c;n=(0,vn.normalizeId)(o||n);let d=vn.getSchemaRefs.call(this,t,n);return c=new wn.SchemaEnv({schema:t,schemaId:s,meta:r,baseId:n,localRefs:d}),this._cache.set(c.schema,c),a&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),i&&this.validateSchema(t,!0),c}_checkUnique(t){if(this.schemas[t]||this.refs[t])throw new Error(`schema with key or id "${t}" already exists`)}_compileSchemaEnv(t){if(t.meta?this._compileMetaSchema(t):wn.compileSchema.call(this,t),!t.validate)throw new Error("ajv implementation error");return t.validate}_compileMetaSchema(t){let r=this.opts;this.opts=this._metaOpts;try{wn.compileSchema.call(this,t)}finally{this.opts=r}}};In.ValidationError=fw.default;In.MissingRefError=Cd.default;Ie.default=In;function $d(e,t,r,n="error"){for(let i in e){let a=i;a in t&&this.logger[n](`${r}: option ${i}. ${e[a]}`)}}function Od(e){return e=(0,vn.normalizeId)(e),this.schemas[e]||this.refs[e]}function kw(){let e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function _w(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function Ew(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let t in e){let r=e[t];r.keyword||(r.keyword=t),this.addKeyword(r)}}function Aw(){let e={...this.opts};for(let t of yw)delete e[t];return e}var Rw={log(){},warn(){},error(){}};function Pw(e){if(e===!1)return Rw;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}var Nw=/^[a-z_$][a-z0-9_$:-]*$/i;function Dw(e,t){let{RULES:r}=this;if((0,Xo.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!Nw.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!t&&t.$data&&!("code"in t||"validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function Zo(e,t,r){var n;let i=t?.post;if(r&&i)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:a}=this,o=i?a.post:a.rules.find(({type:c})=>c===r);if(o||(o={type:r,rules:[]},a.rules.push(o)),a.keywords[e]=!0,!t)return;let s={keyword:e,definition:{...t,type:(0,Ci.getJSONTypes)(t.type),schemaType:(0,Ci.getJSONTypes)(t.schemaType)}};t.before?Sw.call(this,o,s,t.before):o.rules.push(s),a.all[e]=s,(n=t.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function Sw(e,t,r){let n=e.rules.findIndex(i=>i.keyword===r);n>=0?e.rules.splice(n,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}function jw(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=xd(t)),e.validateSchema=this.compile(t,!0))}var $w={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function xd(e){return{anyOf:[e,$w]}}});var Vd=R(Qo=>{"use strict";Object.defineProperty(Qo,"__esModule",{value:!0});var Ow={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Qo.default=Ow});var Li=R(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.callRef=Qt.getValidate=void 0;var Cw=gn(),Md=We(),qe=x(),jr=Ge(),qd=hn(),Ti=U(),Tw={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:n}=e,{baseId:i,schemaEnv:a,validateName:o,opts:s,self:c}=n,{root:d}=a;if((r==="#"||r==="#/")&&i===d.baseId)return p();let l=qd.resolveRef.call(c,d,i,r);if(l===void 0)throw new Cw.default(n.opts.uriResolver,i,r);if(l instanceof qd.SchemaEnv)return m(l);return u(l);function p(){if(a===d)return xi(e,o,a,a.$async);let f=t.scopeValue("root",{ref:d});return xi(e,(0,qe._)`${f}.validate`,d,d.$async)}function m(f){let g=Ud(e,f);xi(e,g,f,f.$async)}function u(f){let g=t.scopeValue("schema",s.code.source===!0?{ref:f,code:(0,qe.stringify)(f)}:{ref:f}),h=t.name("valid"),w=e.subschema({schema:f,dataTypes:[],schemaPath:qe.nil,topSchemaRef:g,errSchemaPath:r},h);e.mergeEvaluated(w),e.ok(h)}}};function Ud(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,qe._)`${r.scopeValue("wrapper",{ref:t})}.validate`}Qt.getValidate=Ud;function xi(e,t,r,n){let{gen:i,it:a}=e,{allErrors:o,schemaEnv:s,opts:c}=a,d=c.passContext?jr.default.this:qe.nil;n?l():p();function l(){if(!s.$async)throw new Error("async schema referenced by sync schema");let f=i.let("valid");i.try(()=>{i.code((0,qe._)`await ${(0,Md.callValidateCode)(e,t,d)}`),u(t),o||i.assign(f,!0)},g=>{i.if((0,qe._)`!(${g} instanceof ${a.ValidationError})`,()=>i.throw(g)),m(g),o||i.assign(f,!1)}),e.ok(f)}function p(){e.result((0,Md.callValidateCode)(e,t,d),()=>u(t),()=>m(t))}function m(f){let g=(0,qe._)`${f}.errors`;i.assign(jr.default.vErrors,(0,qe._)`${jr.default.vErrors} === null ? ${g} : ${jr.default.vErrors}.concat(${g})`),i.assign(jr.default.errors,(0,qe._)`${jr.default.vErrors}.length`)}function u(f){var g;if(!a.opts.unevaluated)return;let h=(g=r?.validate)===null||g===void 0?void 0:g.evaluated;if(a.props!==!0)if(h&&!h.dynamicProps)h.props!==void 0&&(a.props=Ti.mergeEvaluated.props(i,h.props,a.props));else{let w=i.var("props",(0,qe._)`${f}.evaluated.props`);a.props=Ti.mergeEvaluated.props(i,w,a.props,qe.Name)}if(a.items!==!0)if(h&&!h.dynamicItems)h.items!==void 0&&(a.items=Ti.mergeEvaluated.items(i,h.items,a.items));else{let w=i.var("items",(0,qe._)`${f}.evaluated.items`);a.items=Ti.mergeEvaluated.items(i,w,a.items,qe.Name)}}}Qt.callRef=xi;Qt.default=Tw});var Fd=R(es=>{"use strict";Object.defineProperty(es,"__esModule",{value:!0});var xw=Vd(),Lw=Li(),Vw=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",xw.default,Lw.default];es.default=Vw});var zd=R(ts=>{"use strict";Object.defineProperty(ts,"__esModule",{value:!0});var Vi=x(),Ct=Vi.operators,Mi={maximum:{okStr:"<=",ok:Ct.LTE,fail:Ct.GT},minimum:{okStr:">=",ok:Ct.GTE,fail:Ct.LT},exclusiveMaximum:{okStr:"<",ok:Ct.LT,fail:Ct.GTE},exclusiveMinimum:{okStr:">",ok:Ct.GT,fail:Ct.LTE}},Mw={message:({keyword:e,schemaCode:t})=>(0,Vi.str)`must be ${Mi[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,Vi._)`{comparison: ${Mi[e].okStr}, limit: ${t}}`},qw={keyword:Object.keys(Mi),type:"number",schemaType:"number",$data:!0,error:Mw,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,Vi._)`${r} ${Mi[t].fail} ${n} || isNaN(${r})`)}};ts.default=qw});var Bd=R(rs=>{"use strict";Object.defineProperty(rs,"__esModule",{value:!0});var bn=x(),Uw={message:({schemaCode:e})=>(0,bn.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,bn._)`{multipleOf: ${e}}`},Fw={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Uw,code(e){let{gen:t,data:r,schemaCode:n,it:i}=e,a=i.opts.multipleOfPrecision,o=t.let("res"),s=a?(0,bn._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${a}`:(0,bn._)`${o} !== parseInt(${o})`;e.fail$data((0,bn._)`(${n} === 0 || (${o} = ${r}/${n}, ${s}))`)}};rs.default=Fw});var Gd=R(ns=>{"use strict";Object.defineProperty(ns,"__esModule",{value:!0});function Jd(e){let t=e.length,r=0,n=0,i;for(;n<t;)r++,i=e.charCodeAt(n++),i>=55296&&i<=56319&&n<t&&(i=e.charCodeAt(n),(i&64512)===56320&&n++);return r}ns.default=Jd;Jd.code='require("ajv/dist/runtime/ucs2length").default'});var Wd=R(is=>{"use strict";Object.defineProperty(is,"__esModule",{value:!0});var er=x(),zw=U(),Bw=Gd(),Jw={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,er.str)`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>(0,er._)`{limit: ${e}}`},Gw={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Jw,code(e){let{keyword:t,data:r,schemaCode:n,it:i}=e,a=t==="maxLength"?er.operators.GT:er.operators.LT,o=i.opts.unicode===!1?(0,er._)`${r}.length`:(0,er._)`${(0,zw.useFunc)(e.gen,Bw.default)}(${r})`;e.fail$data((0,er._)`${o} ${a} ${n}`)}};is.default=Gw});var Kd=R(as=>{"use strict";Object.defineProperty(as,"__esModule",{value:!0});var Ww=We(),Kw=U(),$r=x(),Yw={message:({schemaCode:e})=>(0,$r.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,$r._)`{pattern: ${e}}`},Hw={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Yw,code(e){let{gen:t,data:r,$data:n,schema:i,schemaCode:a,it:o}=e,s=o.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=o.opts.code,d=c.code==="new RegExp"?(0,$r._)`new RegExp`:(0,Kw.useFunc)(t,c),l=t.let("valid");t.try(()=>t.assign(l,(0,$r._)`${d}(${a}, ${s}).test(${r})`),()=>t.assign(l,!1)),e.fail$data((0,$r._)`!${l}`)}else{let c=(0,Ww.usePattern)(e,i);e.fail$data((0,$r._)`!${c}.test(${r})`)}}};as.default=Hw});var Yd=R(os=>{"use strict";Object.defineProperty(os,"__esModule",{value:!0});var kn=x(),Zw={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,kn.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0,kn._)`{limit: ${e}}`},Xw={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Zw,code(e){let{keyword:t,data:r,schemaCode:n}=e,i=t==="maxProperties"?kn.operators.GT:kn.operators.LT;e.fail$data((0,kn._)`Object.keys(${r}).length ${i} ${n}`)}};os.default=Xw});var Hd=R(ss=>{"use strict";Object.defineProperty(ss,"__esModule",{value:!0});var _n=We(),En=x(),Qw=U(),ev={message:({params:{missingProperty:e}})=>(0,En.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,En._)`{missingProperty: ${e}}`},tv={keyword:"required",type:"object",schemaType:"array",$data:!0,error:ev,code(e){let{gen:t,schema:r,schemaCode:n,data:i,$data:a,it:o}=e,{opts:s}=o;if(!a&&r.length===0)return;let c=r.length>=s.loopRequired;if(o.allErrors?d():l(),s.strictRequired){let u=e.parentSchema.properties,{definedProperties:f}=e.it;for(let g of r)if(u?.[g]===void 0&&!f.has(g)){let h=o.schemaEnv.baseId+o.errSchemaPath,w=`required property "${g}" is not defined at "${h}" (strictRequired)`;(0,Qw.checkStrictMode)(o,w,o.opts.strictRequired)}}function d(){if(c||a)e.block$data(En.nil,p);else for(let u of r)(0,_n.checkReportMissingProp)(e,u)}function l(){let u=t.let("missing");if(c||a){let f=t.let("valid",!0);e.block$data(f,()=>m(u,f)),e.ok(f)}else t.if((0,_n.checkMissingProp)(e,r,u)),(0,_n.reportMissingProp)(e,u),t.else()}function p(){t.forOf("prop",n,u=>{e.setParams({missingProperty:u}),t.if((0,_n.noPropertyInData)(t,i,u,s.ownProperties),()=>e.error())})}function m(u,f){e.setParams({missingProperty:u}),t.forOf(u,n,()=>{t.assign(f,(0,_n.propertyInData)(t,i,u,s.ownProperties)),t.if((0,En.not)(f),()=>{e.error(),t.break()})},En.nil)}}};ss.default=tv});var Zd=R(cs=>{"use strict";Object.defineProperty(cs,"__esModule",{value:!0});var An=x(),rv={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,An.str)`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>(0,An._)`{limit: ${e}}`},nv={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:rv,code(e){let{keyword:t,data:r,schemaCode:n}=e,i=t==="maxItems"?An.operators.GT:An.operators.LT;e.fail$data((0,An._)`${r}.length ${i} ${n}`)}};cs.default=nv});var qi=R(ls=>{"use strict";Object.defineProperty(ls,"__esModule",{value:!0});var Xd=$o();Xd.code='require("ajv/dist/runtime/equal").default';ls.default=Xd});var Qd=R(ps=>{"use strict";Object.defineProperty(ps,"__esModule",{value:!0});var ds=dn(),be=x(),iv=U(),av=qi(),ov={message:({params:{i:e,j:t}})=>(0,be.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,be._)`{i: ${e}, j: ${t}}`},sv={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:ov,code(e){let{gen:t,data:r,$data:n,schema:i,parentSchema:a,schemaCode:o,it:s}=e;if(!n&&!i)return;let c=t.let("valid"),d=a.items?(0,ds.getSchemaTypes)(a.items):[];e.block$data(c,l,(0,be._)`${o} === false`),e.ok(c);function l(){let f=t.let("i",(0,be._)`${r}.length`),g=t.let("j");e.setParams({i:f,j:g}),t.assign(c,!0),t.if((0,be._)`${f} > 1`,()=>(p()?m:u)(f,g))}function p(){return d.length>0&&!d.some(f=>f==="object"||f==="array")}function m(f,g){let h=t.name("item"),w=(0,ds.checkDataTypes)(d,h,s.opts.strictNumbers,ds.DataType.Wrong),_=t.const("indices",(0,be._)`{}`);t.for((0,be._)`;${f}--;`,()=>{t.let(h,(0,be._)`${r}[${f}]`),t.if(w,(0,be._)`continue`),d.length>1&&t.if((0,be._)`typeof ${h} == "string"`,(0,be._)`${h} += "_"`),t.if((0,be._)`typeof ${_}[${h}] == "number"`,()=>{t.assign(g,(0,be._)`${_}[${h}]`),e.error(),t.assign(c,!1).break()}).code((0,be._)`${_}[${h}] = ${f}`)})}function u(f,g){let h=(0,iv.useFunc)(t,av.default),w=t.name("outer");t.label(w).for((0,be._)`;${f}--;`,()=>t.for((0,be._)`${g} = ${f}; ${g}--;`,()=>t.if((0,be._)`${h}(${r}[${f}], ${r}[${g}])`,()=>{e.error(),t.assign(c,!1).break(w)})))}}};ps.default=sv});var ep=R(fs=>{"use strict";Object.defineProperty(fs,"__esModule",{value:!0});var us=x(),cv=U(),lv=qi(),dv={message:"must be equal to constant",params:({schemaCode:e})=>(0,us._)`{allowedValue: ${e}}`},pv={keyword:"const",$data:!0,error:dv,code(e){let{gen:t,data:r,$data:n,schemaCode:i,schema:a}=e;n||a&&typeof a=="object"?e.fail$data((0,us._)`!${(0,cv.useFunc)(t,lv.default)}(${r}, ${i})`):e.fail((0,us._)`${a} !== ${r}`)}};fs.default=pv});var tp=R(ms=>{"use strict";Object.defineProperty(ms,"__esModule",{value:!0});var Rn=x(),uv=U(),fv=qi(),mv={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,Rn._)`{allowedValues: ${e}}`},gv={keyword:"enum",schemaType:"array",$data:!0,error:mv,code(e){let{gen:t,data:r,$data:n,schema:i,schemaCode:a,it:o}=e;if(!n&&i.length===0)throw new Error("enum must have non-empty array");let s=i.length>=o.opts.loopEnum,c,d=()=>c??(c=(0,uv.useFunc)(t,fv.default)),l;if(s||n)l=t.let("valid"),e.block$data(l,p);else{if(!Array.isArray(i))throw new Error("ajv implementation error");let u=t.const("vSchema",a);l=(0,Rn.or)(...i.map((f,g)=>m(u,g)))}e.pass(l);function p(){t.assign(l,!1),t.forOf("v",a,u=>t.if((0,Rn._)`${d()}(${r}, ${u})`,()=>t.assign(l,!0).break()))}function m(u,f){let g=i[f];return typeof g=="object"&&g!==null?(0,Rn._)`${d()}(${r}, ${u}[${f}])`:(0,Rn._)`${r} === ${g}`}}};ms.default=gv});var rp=R(gs=>{"use strict";Object.defineProperty(gs,"__esModule",{value:!0});var hv=zd(),yv=Bd(),wv=Wd(),vv=Kd(),Iv=Yd(),bv=Hd(),kv=Zd(),_v=Qd(),Ev=ep(),Av=tp(),Rv=[hv.default,yv.default,wv.default,vv.default,Iv.default,bv.default,kv.default,_v.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Ev.default,Av.default];gs.default=Rv});var ys=R(Pn=>{"use strict";Object.defineProperty(Pn,"__esModule",{value:!0});Pn.validateAdditionalItems=void 0;var tr=x(),hs=U(),Pv={message:({params:{len:e}})=>(0,tr.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,tr._)`{limit: ${e}}`},Nv={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Pv,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,hs.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}np(e,n)}};function np(e,t){let{gen:r,schema:n,data:i,keyword:a,it:o}=e;o.items=!0;let s=r.const("len",(0,tr._)`${i}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,tr._)`${s} <= ${t.length}`);else if(typeof n=="object"&&!(0,hs.alwaysValidSchema)(o,n)){let d=r.var("valid",(0,tr._)`${s} <= ${t.length}`);r.if((0,tr.not)(d),()=>c(d)),e.ok(d)}function c(d){r.forRange("i",t.length,s,l=>{e.subschema({keyword:a,dataProp:l,dataPropType:hs.Type.Num},d),o.allErrors||r.if((0,tr.not)(d),()=>r.break())})}}Pn.validateAdditionalItems=np;Pn.default=Nv});var ws=R(Nn=>{"use strict";Object.defineProperty(Nn,"__esModule",{value:!0});Nn.validateTuple=void 0;var ip=x(),Ui=U(),Dv=We(),Sv={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return ap(e,"additionalItems",t);r.items=!0,!(0,Ui.alwaysValidSchema)(r,t)&&e.ok((0,Dv.validateArray)(e))}};function ap(e,t,r=e.schema){let{gen:n,parentSchema:i,data:a,keyword:o,it:s}=e;l(i),s.opts.unevaluated&&r.length&&s.items!==!0&&(s.items=Ui.mergeEvaluated.items(n,r.length,s.items));let c=n.name("valid"),d=n.const("len",(0,ip._)`${a}.length`);r.forEach((p,m)=>{(0,Ui.alwaysValidSchema)(s,p)||(n.if((0,ip._)`${d} > ${m}`,()=>e.subschema({keyword:o,schemaProp:m,dataProp:m},c)),e.ok(c))});function l(p){let{opts:m,errSchemaPath:u}=s,f=r.length,g=f===p.minItems&&(f===p.maxItems||p[t]===!1);if(m.strictTuples&&!g){let h=`"${o}" is ${f}-tuple, but minItems or maxItems/${t} are not specified or different at path "${u}"`;(0,Ui.checkStrictMode)(s,h,m.strictTuples)}}}Nn.validateTuple=ap;Nn.default=Sv});var op=R(vs=>{"use strict";Object.defineProperty(vs,"__esModule",{value:!0});var jv=ws(),$v={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,jv.validateTuple)(e,"items")};vs.default=$v});var cp=R(Is=>{"use strict";Object.defineProperty(Is,"__esModule",{value:!0});var sp=x(),Ov=U(),Cv=We(),Tv=ys(),xv={message:({params:{len:e}})=>(0,sp.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,sp._)`{limit: ${e}}`},Lv={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:xv,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:i}=r;n.items=!0,!(0,Ov.alwaysValidSchema)(n,t)&&(i?(0,Tv.validateAdditionalItems)(e,i):e.ok((0,Cv.validateArray)(e)))}};Is.default=Lv});var lp=R(bs=>{"use strict";Object.defineProperty(bs,"__esModule",{value:!0});var Ye=x(),Fi=U(),Vv={message:({params:{min:e,max:t}})=>t===void 0?(0,Ye.str)`must contain at least ${e} valid item(s)`:(0,Ye.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,Ye._)`{minContains: ${e}}`:(0,Ye._)`{minContains: ${e}, maxContains: ${t}}`},Mv={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Vv,code(e){let{gen:t,schema:r,parentSchema:n,data:i,it:a}=e,o,s,{minContains:c,maxContains:d}=n;a.opts.next?(o=c===void 0?1:c,s=d):o=1;let l=t.const("len",(0,Ye._)`${i}.length`);if(e.setParams({min:o,max:s}),s===void 0&&o===0){(0,Fi.checkStrictMode)(a,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(s!==void 0&&o>s){(0,Fi.checkStrictMode)(a,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Fi.alwaysValidSchema)(a,r)){let g=(0,Ye._)`${l} >= ${o}`;s!==void 0&&(g=(0,Ye._)`${g} && ${l} <= ${s}`),e.pass(g);return}a.items=!0;let p=t.name("valid");s===void 0&&o===1?u(p,()=>t.if(p,()=>t.break())):o===0?(t.let(p,!0),s!==void 0&&t.if((0,Ye._)`${i}.length > 0`,m)):(t.let(p,!1),m()),e.result(p,()=>e.reset());function m(){let g=t.name("_valid"),h=t.let("count",0);u(g,()=>t.if(g,()=>f(h)))}function u(g,h){t.forRange("i",0,l,w=>{e.subschema({keyword:"contains",dataProp:w,dataPropType:Fi.Type.Num,compositeRule:!0},g),h()})}function f(g){t.code((0,Ye._)`${g}++`),s===void 0?t.if((0,Ye._)`${g} >= ${o}`,()=>t.assign(p,!0).break()):(t.if((0,Ye._)`${g} > ${s}`,()=>t.assign(p,!1).break()),o===1?t.assign(p,!0):t.if((0,Ye._)`${g} >= ${o}`,()=>t.assign(p,!0)))}}};bs.default=Mv});var zi=R(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.validateSchemaDeps=gt.validatePropertyDeps=gt.error=void 0;var ks=x(),qv=U(),Dn=We();gt.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,ks.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,ks._)`{property: ${e},
|
|
5
|
+
|| ${o} === "boolean" || ${i} === null`).assign(s,(0,L._)`[${i}]`)}}}function oh({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,L._)`${t} !== undefined`,()=>e.assign((0,L._)`${t}[${r}]`,n))}function Ro(e,t,r,n=Rr.Correct){let i=n===Rr.Correct?L.operators.EQ:L.operators.NEQ,a;switch(e){case"null":return(0,L._)`${t} ${i} null`;case"array":a=(0,L._)`Array.isArray(${t})`;break;case"object":a=(0,L._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":a=o((0,L._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":a=o();break;default:return(0,L._)`typeof ${t} ${i} ${e}`}return n===Rr.Correct?a:(0,L.not)(a);function o(s=L.nil){return(0,L.and)((0,L._)`typeof ${t} == "number"`,s,r?(0,L._)`isFinite(${t})`:L.nil)}}Ne.checkDataType=Ro;function Po(e,t,r,n){if(e.length===1)return Ro(e[0],t,r,n);let i,a=(0,$l.toHash)(e);if(a.array&&a.object){let o=(0,L._)`typeof ${t} != "object"`;i=a.null?o:(0,L._)`!${t} || ${o}`,delete a.null,delete a.array,delete a.object}else i=L.nil;a.number&&delete a.integer;for(let o in a)i=(0,L.and)(i,Ro(o,t,r,n));return i}Ne.checkDataTypes=Po;var sh={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,L._)`{type: ${e}}`:(0,L._)`{type: ${t}}`};function No(e){let t=ch(e);(0,th.reportError)(t,sh)}Ne.reportTypeError=No;function ch(e){let{gen:t,data:r,schema:n}=e,i=(0,$l.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:e}}});var xl=R(_i=>{"use strict";Object.defineProperty(_i,"__esModule",{value:!0});_i.assignDefaults=void 0;var Pr=x(),lh=U();function dh(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let i in r)Tl(e,i,r[i].default);else t==="array"&&Array.isArray(n)&&n.forEach((i,a)=>Tl(e,a,i.default))}_i.assignDefaults=dh;function Tl(e,t,r){let{gen:n,compositeRule:i,data:a,opts:o}=e;if(r===void 0)return;let s=(0,Pr._)`${a}${(0,Pr.getProperty)(t)}`;if(i){(0,lh.checkStrictMode)(e,`default is ignored for: ${s}`);return}let c=(0,Pr._)`${s} === undefined`;o.useDefaults==="empty"&&(c=(0,Pr._)`${c} || ${s} === null || ${s} === ""`),n.if(c,(0,Pr._)`${s} = ${(0,Pr.stringify)(r)}`)}});var We=R(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.validateUnion=ee.validateArray=ee.usePattern=ee.callValidateCode=ee.schemaProperties=ee.allSchemaProperties=ee.noPropertyInData=ee.propertyInData=ee.isOwnProperty=ee.hasPropFunc=ee.reportMissingProp=ee.checkMissingProp=ee.checkReportMissingProp=void 0;var ce=x(),Do=U(),St=Je(),ph=U();function uh(e,t){let{gen:r,data:n,it:i}=e;r.if(jo(r,n,t,i.opts.ownProperties),()=>{e.setParams({missingProperty:(0,ce._)`${t}`},!0),e.error()})}ee.checkReportMissingProp=uh;function fh({gen:e,data:t,it:{opts:r}},n,i){return(0,ce.or)(...n.map(a=>(0,ce.and)(jo(e,t,a,r.ownProperties),(0,ce._)`${i} = ${a}`)))}ee.checkMissingProp=fh;function mh(e,t){e.setParams({missingProperty:t},!0),e.error()}ee.reportMissingProp=mh;function Ll(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ce._)`Object.prototype.hasOwnProperty`})}ee.hasPropFunc=Ll;function So(e,t,r){return(0,ce._)`${Ll(e)}.call(${t}, ${r})`}ee.isOwnProperty=So;function gh(e,t,r,n){let i=(0,ce._)`${t}${(0,ce.getProperty)(r)} !== undefined`;return n?(0,ce._)`${i} && ${So(e,t,r)}`:i}ee.propertyInData=gh;function jo(e,t,r,n){let i=(0,ce._)`${t}${(0,ce.getProperty)(r)} === undefined`;return n?(0,ce.or)(i,(0,ce.not)(So(e,t,r))):i}ee.noPropertyInData=jo;function Vl(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}ee.allSchemaProperties=Vl;function hh(e,t){return Vl(t).filter(r=>!(0,Do.alwaysValidSchema)(e,t[r]))}ee.schemaProperties=hh;function yh({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:i,errorPath:a},it:o},s,c,d){let l=d?(0,ce._)`${e}, ${t}, ${n}${i}`:t,p=[[St.default.instancePath,(0,ce.strConcat)(St.default.instancePath,a)],[St.default.parentData,o.parentData],[St.default.parentDataProperty,o.parentDataProperty],[St.default.rootData,St.default.rootData]];o.opts.dynamicRef&&p.push([St.default.dynamicAnchors,St.default.dynamicAnchors]);let m=(0,ce._)`${l}, ${r.object(...p)}`;return c!==ce.nil?(0,ce._)`${s}.call(${c}, ${m})`:(0,ce._)`${s}(${m})`}ee.callValidateCode=yh;var wh=(0,ce._)`new RegExp`;function vh({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:i}=t.code,a=i(r,n);return e.scopeValue("pattern",{key:a.toString(),ref:a,code:(0,ce._)`${i.code==="new RegExp"?wh:(0,ph.useFunc)(e,i)}(${r}, ${n})`})}ee.usePattern=vh;function Ih(e){let{gen:t,data:r,keyword:n,it:i}=e,a=t.name("valid");if(i.allErrors){let s=t.let("valid",!0);return o(()=>t.assign(s,!1)),s}return t.var(a,!0),o(()=>t.break()),a;function o(s){let c=t.const("len",(0,ce._)`${r}.length`);t.forRange("i",0,c,d=>{e.subschema({keyword:n,dataProp:d,dataPropType:Do.Type.Num},a),t.if((0,ce.not)(a),s)})}}ee.validateArray=Ih;function bh(e){let{gen:t,schema:r,keyword:n,it:i}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,Do.alwaysValidSchema)(i,c))&&!i.opts.unevaluated)return;let o=t.let("valid",!1),s=t.name("_valid");t.block(()=>r.forEach((c,d)=>{let l=e.subschema({keyword:n,schemaProp:d,compositeRule:!0},s);t.assign(o,(0,ce._)`${o} || ${s}`),e.mergeValidEvaluated(l,s)||t.if((0,ce.not)(o))})),e.result(o,()=>e.reset(),()=>e.error(!0))}ee.validateUnion=bh});var Ul=R(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.validateKeywordUsage=ft.validSchemaType=ft.funcKeywordCode=ft.macroKeywordCode=void 0;var Ce=x(),Ht=Je(),kh=We(),_h=ln();function Eh(e,t){let{gen:r,keyword:n,schema:i,parentSchema:a,it:o}=e,s=t.macro.call(o.self,i,a,o),c=ql(r,n,s);o.opts.validateSchema!==!1&&o.self.validateSchema(s,!0);let d=r.name("valid");e.subschema({schema:s,schemaPath:Ce.nil,errSchemaPath:`${o.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},d),e.pass(d,()=>e.error(!0))}ft.macroKeywordCode=Eh;function Ah(e,t){var r;let{gen:n,keyword:i,schema:a,parentSchema:o,$data:s,it:c}=e;Ph(c,t);let d=!s&&t.compile?t.compile.call(c.self,a,o,c):t.validate,l=ql(n,i,d),p=n.let("valid");e.block$data(p,m),e.ok((r=t.valid)!==null&&r!==void 0?r:p);function m(){if(t.errors===!1)g(),t.modifying&&Ml(e),h(()=>e.error());else{let w=t.async?u():f();t.modifying&&Ml(e),h(()=>Rh(e,w))}}function u(){let w=n.let("ruleErrs",null);return n.try(()=>g((0,Ce._)`await `),_=>n.assign(p,!1).if((0,Ce._)`${_} instanceof ${c.ValidationError}`,()=>n.assign(w,(0,Ce._)`${_}.errors`),()=>n.throw(_))),w}function f(){let w=(0,Ce._)`${l}.errors`;return n.assign(w,null),g(Ce.nil),w}function g(w=t.async?(0,Ce._)`await `:Ce.nil){let _=c.opts.passContext?Ht.default.this:Ht.default.self,b=!("compile"in t&&!s||t.schema===!1);n.assign(p,(0,Ce._)`${w}${(0,kh.callValidateCode)(e,l,_,b)}`,t.modifying)}function h(w){var _;n.if((0,Ce.not)((_=t.valid)!==null&&_!==void 0?_:p),w)}}ft.funcKeywordCode=Ah;function Ml(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,Ce._)`${n.parentData}[${n.parentDataProperty}]`))}function Rh(e,t){let{gen:r}=e;r.if((0,Ce._)`Array.isArray(${t})`,()=>{r.assign(Ht.default.vErrors,(0,Ce._)`${Ht.default.vErrors} === null ? ${t} : ${Ht.default.vErrors}.concat(${t})`).assign(Ht.default.errors,(0,Ce._)`${Ht.default.vErrors}.length`),(0,_h.extendErrors)(e)},()=>e.error())}function Ph({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function ql(e,t,r){if(r===void 0)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Ce.stringify)(r)})}function Nh(e,t,r=!1){return!t.length||t.some(n=>n==="array"?Array.isArray(e):n==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==n||r&&typeof e>"u")}ft.validSchemaType=Nh;function Dh({schema:e,opts:t,self:r,errSchemaPath:n},i,a){if(Array.isArray(i.keyword)?!i.keyword.includes(a):i.keyword!==a)throw new Error("ajv implementation error");let o=i.dependencies;if(o?.some(s=>!Object.prototype.hasOwnProperty.call(e,s)))throw new Error(`parent schema must have dependencies of ${a}: ${o.join(",")}`);if(i.validateSchema&&!i.validateSchema(e[a])){let c=`keyword "${a}" value is invalid at path "${n}": `+r.errorsText(i.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}ft.validateKeywordUsage=Dh});var zl=R(jt=>{"use strict";Object.defineProperty(jt,"__esModule",{value:!0});jt.extendSubschemaMode=jt.extendSubschemaData=jt.getSubschema=void 0;var mt=x(),Fl=U();function Sh(e,{keyword:t,schemaProp:r,schema:n,schemaPath:i,errSchemaPath:a,topSchemaRef:o}){if(t!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let s=e.schema[t];return r===void 0?{schema:s,schemaPath:(0,mt._)`${e.schemaPath}${(0,mt.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:s[r],schemaPath:(0,mt._)`${e.schemaPath}${(0,mt.getProperty)(t)}${(0,mt.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,Fl.escapeFragment)(r)}`}}if(n!==void 0){if(i===void 0||a===void 0||o===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:i,topSchemaRef:o,errSchemaPath:a}}throw new Error('either "keyword" or "schema" must be passed')}jt.getSubschema=Sh;function jh(e,t,{dataProp:r,dataPropType:n,data:i,dataTypes:a,propertyName:o}){if(i!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:s}=t;if(r!==void 0){let{errorPath:d,dataPathArr:l,opts:p}=t,m=s.let("data",(0,mt._)`${t.data}${(0,mt.getProperty)(r)}`,!0);c(m),e.errorPath=(0,mt.str)`${d}${(0,Fl.getErrorPath)(r,n,p.jsPropertySyntax)}`,e.parentDataProperty=(0,mt._)`${r}`,e.dataPathArr=[...l,e.parentDataProperty]}if(i!==void 0){let d=i instanceof mt.Name?i:s.let("data",i,!0);c(d),o!==void 0&&(e.propertyName=o)}a&&(e.dataTypes=a);function c(d){e.data=d,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,d]}}jt.extendSubschemaData=jh;function $h(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:i,allErrors:a}){n!==void 0&&(e.compositeRule=n),i!==void 0&&(e.createErrors=i),a!==void 0&&(e.allErrors=a),e.jtdDiscriminator=t,e.jtdMetadata=r}jt.extendSubschemaMode=$h});var $o=R((iR,Bl)=>{"use strict";Bl.exports=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,i,a;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(i=n;i--!==0;)if(!e(t[i],r[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(a=Object.keys(t),n=a.length,n!==Object.keys(r).length)return!1;for(i=n;i--!==0;)if(!Object.prototype.hasOwnProperty.call(r,a[i]))return!1;for(i=n;i--!==0;){var o=a[i];if(!e(t[o],r[o]))return!1}return!0}return t!==t&&r!==r}});var Jl=R((aR,Gl)=>{"use strict";var $t=Gl.exports=function(e,t,r){typeof t=="function"&&(r=t,t={}),r=t.cb||r;var n=typeof r=="function"?r:r.pre||function(){},i=r.post||function(){};Ei(t,n,i,e,"",e)};$t.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};$t.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};$t.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};$t.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function Ei(e,t,r,n,i,a,o,s,c,d){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,i,a,o,s,c,d);for(var l in n){var p=n[l];if(Array.isArray(p)){if(l in $t.arrayKeywords)for(var m=0;m<p.length;m++)Ei(e,t,r,p[m],i+"/"+l+"/"+m,a,i,l,n,m)}else if(l in $t.propsKeywords){if(p&&typeof p=="object")for(var u in p)Ei(e,t,r,p[u],i+"/"+l+"/"+Oh(u),a,i,l,n,u)}else(l in $t.keywords||e.allKeys&&!(l in $t.skipKeywords))&&Ei(e,t,r,p,i+"/"+l,a,i,l,n)}r(n,i,a,o,s,c,d)}}function Oh(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var pn=R(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.getSchemaRefs=Me.resolveUrl=Me.normalizeId=Me._getFullPath=Me.getFullPath=Me.inlineRef=void 0;var Ch=U(),Th=$o(),xh=Jl(),Lh=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Vh(e,t=!0){return typeof e=="boolean"?!0:t===!0?!Oo(e):t?Wl(e)<=t:!1}Me.inlineRef=Vh;var Mh=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Oo(e){for(let t in e){if(Mh.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(Oo)||typeof r=="object"&&Oo(r))return!0}return!1}function Wl(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!Lh.has(r)&&(typeof e[r]=="object"&&(0,Ch.eachItem)(e[r],n=>t+=Wl(n)),t===1/0))return 1/0}return t}function Kl(e,t="",r){r!==!1&&(t=Nr(t));let n=e.parse(t);return Yl(e,n)}Me.getFullPath=Kl;function Yl(e,t){return e.serialize(t).split("#")[0]+"#"}Me._getFullPath=Yl;var qh=/#\/?$/;function Nr(e){return e?e.replace(qh,""):""}Me.normalizeId=Nr;function Uh(e,t,r){return r=Nr(r),e.resolve(t,r)}Me.resolveUrl=Uh;var Fh=/^[a-z_][-a-z0-9._]*$/i;function zh(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,i=Nr(e[r]||t),a={"":i},o=Kl(n,i,!1),s={},c=new Set;return xh(e,{allKeys:!0},(p,m,u,f)=>{if(f===void 0)return;let g=o+m,h=a[f];typeof p[r]=="string"&&(h=w.call(this,p[r])),_.call(this,p.$anchor),_.call(this,p.$dynamicAnchor),a[m]=h;function w(b){let A=this.opts.uriResolver.resolve;if(b=Nr(h?A(h,b):b),c.has(b))throw l(b);c.add(b);let y=this.refs[b];return typeof y=="string"&&(y=this.refs[y]),typeof y=="object"?d(p,y.schema,b):b!==Nr(g)&&(b[0]==="#"?(d(p,s[b],b),s[b]=p):this.refs[b]=g),b}function _(b){if(typeof b=="string"){if(!Fh.test(b))throw new Error(`invalid anchor "${b}"`);w.call(this,`#${b}`)}}}),s;function d(p,m,u){if(m!==void 0&&!Th(p,m))throw l(u)}function l(p){return new Error(`reference "${p}" resolves to more than one schema`)}}Me.getSchemaRefs=zh});var mn=R(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.getData=Ot.KeywordCxt=Ot.validateFunctionCode=void 0;var ed=Dl(),Hl=dn(),To=Ao(),Ai=dn(),Bh=xl(),fn=Ul(),Co=zl(),D=x(),T=Je(),Gh=pn(),bt=U(),un=ln();function Jh(e){if(nd(e)&&(id(e),rd(e))){Yh(e);return}td(e,()=>(0,ed.topBoolOrEmptySchema)(e))}Ot.validateFunctionCode=Jh;function td({gen:e,validateName:t,schema:r,schemaEnv:n,opts:i},a){i.code.es5?e.func(t,(0,D._)`${T.default.data}, ${T.default.valCxt}`,n.$async,()=>{e.code((0,D._)`"use strict"; ${Zl(r,i)}`),Kh(e,i),e.code(a)}):e.func(t,(0,D._)`${T.default.data}, ${Wh(i)}`,n.$async,()=>e.code(Zl(r,i)).code(a))}function Wh(e){return(0,D._)`{${T.default.instancePath}="", ${T.default.parentData}, ${T.default.parentDataProperty}, ${T.default.rootData}=${T.default.data}${e.dynamicRef?(0,D._)`, ${T.default.dynamicAnchors}={}`:D.nil}}={}`}function Kh(e,t){e.if(T.default.valCxt,()=>{e.var(T.default.instancePath,(0,D._)`${T.default.valCxt}.${T.default.instancePath}`),e.var(T.default.parentData,(0,D._)`${T.default.valCxt}.${T.default.parentData}`),e.var(T.default.parentDataProperty,(0,D._)`${T.default.valCxt}.${T.default.parentDataProperty}`),e.var(T.default.rootData,(0,D._)`${T.default.valCxt}.${T.default.rootData}`),t.dynamicRef&&e.var(T.default.dynamicAnchors,(0,D._)`${T.default.valCxt}.${T.default.dynamicAnchors}`)},()=>{e.var(T.default.instancePath,(0,D._)`""`),e.var(T.default.parentData,(0,D._)`undefined`),e.var(T.default.parentDataProperty,(0,D._)`undefined`),e.var(T.default.rootData,T.default.data),t.dynamicRef&&e.var(T.default.dynamicAnchors,(0,D._)`{}`)})}function Yh(e){let{schema:t,opts:r,gen:n}=e;td(e,()=>{r.$comment&&t.$comment&&od(e),ey(e),n.let(T.default.vErrors,null),n.let(T.default.errors,0),r.unevaluated&&Hh(e),ad(e),ny(e)})}function Hh(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,D._)`${r}.evaluated`),t.if((0,D._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,D._)`${e.evaluated}.props`,(0,D._)`undefined`)),t.if((0,D._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,D._)`${e.evaluated}.items`,(0,D._)`undefined`))}function Zl(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,D._)`/*# sourceURL=${r} */`:D.nil}function Zh(e,t){if(nd(e)&&(id(e),rd(e))){Xh(e,t);return}(0,ed.boolOrEmptySchema)(e,t)}function rd({schema:e,self:t}){if(typeof e=="boolean")return!e;for(let r in e)if(t.RULES.all[r])return!0;return!1}function nd(e){return typeof e.schema!="boolean"}function Xh(e,t){let{schema:r,gen:n,opts:i}=e;i.$comment&&r.$comment&&od(e),ty(e),ry(e);let a=n.const("_errs",T.default.errors);ad(e,a),n.var(t,(0,D._)`${a} === ${T.default.errors}`)}function id(e){(0,bt.checkUnknownRules)(e),Qh(e)}function ad(e,t){if(e.opts.jtd)return Xl(e,[],!1,t);let r=(0,Hl.getSchemaTypes)(e.schema),n=(0,Hl.coerceAndCheckDataType)(e,r);Xl(e,r,!n,t)}function Qh(e){let{schema:t,errSchemaPath:r,opts:n,self:i}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,bt.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function ey(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,bt.checkStrictMode)(e,"default is ignored in the schema root")}function ty(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,Gh.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function ry(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function od({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:i}){let a=r.$comment;if(i.$comment===!0)e.code((0,D._)`${T.default.self}.logger.log(${a})`);else if(typeof i.$comment=="function"){let o=(0,D.str)`${n}/$comment`,s=e.scopeValue("root",{ref:t.root});e.code((0,D._)`${T.default.self}.opts.$comment(${a}, ${o}, ${s}.schema)`)}}function ny(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:i,opts:a}=e;r.$async?t.if((0,D._)`${T.default.errors} === 0`,()=>t.return(T.default.data),()=>t.throw((0,D._)`new ${i}(${T.default.vErrors})`)):(t.assign((0,D._)`${n}.errors`,T.default.vErrors),a.unevaluated&&iy(e),t.return((0,D._)`${T.default.errors} === 0`))}function iy({gen:e,evaluated:t,props:r,items:n}){r instanceof D.Name&&e.assign((0,D._)`${t}.props`,r),n instanceof D.Name&&e.assign((0,D._)`${t}.items`,n)}function Xl(e,t,r,n){let{gen:i,schema:a,data:o,allErrors:s,opts:c,self:d}=e,{RULES:l}=d;if(a.$ref&&(c.ignoreKeywordsWithRef||!(0,bt.schemaHasRulesButRef)(a,l))){i.block(()=>cd(e,"$ref",l.all.$ref.definition));return}c.jtd||ay(e,t),i.block(()=>{for(let m of l.rules)p(m);p(l.post)});function p(m){(0,To.shouldUseGroup)(a,m)&&(m.type?(i.if((0,Ai.checkDataType)(m.type,o,c.strictNumbers)),Ql(e,m),t.length===1&&t[0]===m.type&&r&&(i.else(),(0,Ai.reportTypeError)(e)),i.endIf()):Ql(e,m),s||i.if((0,D._)`${T.default.errors} === ${n||0}`))}}function Ql(e,t){let{gen:r,schema:n,opts:{useDefaults:i}}=e;i&&(0,Bh.assignDefaults)(e,t.type),r.block(()=>{for(let a of t.rules)(0,To.shouldUseRule)(n,a)&&cd(e,a.keyword,a.definition,t.type)})}function ay(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(oy(e,t),e.opts.allowUnionTypes||sy(e,t),cy(e,e.dataTypes))}function oy(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{sd(e.dataTypes,r)||xo(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),dy(e,t)}}function sy(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&xo(e,"use allowUnionTypes to allow union type keyword")}function cy(e,t){let r=e.self.RULES.all;for(let n in r){let i=r[n];if(typeof i=="object"&&(0,To.shouldUseRule)(e.schema,i)){let{type:a}=i.definition;a.length&&!a.some(o=>ly(t,o))&&xo(e,`missing type "${a.join(",")}" for keyword "${n}"`)}}}function ly(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function sd(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function dy(e,t){let r=[];for(let n of e.dataTypes)sd(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}function xo(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,bt.checkStrictMode)(e,t,e.opts.strictTypes)}var Ri=class{constructor(t,r,n){if((0,fn.validateKeywordUsage)(t,r,n),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=n,this.data=t.data,this.schema=t.schema[n],this.$data=r.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,bt.schemaRefOrVal)(t,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=r,this.$data)this.schemaCode=t.gen.const("vSchema",ld(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,fn.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=t.gen.const("_errs",T.default.errors))}result(t,r,n){this.failResult((0,D.not)(t),r,n)}failResult(t,r,n){this.gen.if(t),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,r){this.failResult((0,D.not)(t),void 0,r)}fail(t){if(t===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(t),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(t){if(!this.$data)return this.fail(t);let{schemaCode:r}=this;this.fail((0,D._)`${r} !== undefined && (${(0,D.or)(this.invalid$data(),t)})`)}error(t,r,n){if(r){this.setParams(r),this._error(t,n),this.setParams({});return}this._error(t,n)}_error(t,r){(t?un.reportExtraError:un.reportError)(this,this.def.error,r)}$dataError(){(0,un.reportError)(this,this.def.$dataError||un.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,un.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,r){r?Object.assign(this.params,t):this.params=t}block$data(t,r,n=D.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=D.nil,r=D.nil){if(!this.$data)return;let{gen:n,schemaCode:i,schemaType:a,def:o}=this;n.if((0,D.or)((0,D._)`${i} === undefined`,r)),t!==D.nil&&n.assign(t,!0),(a.length||o.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==D.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:i,it:a}=this;return(0,D.or)(o(),s());function o(){if(n.length){if(!(r instanceof D.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,D._)`${(0,Ai.checkDataTypes)(c,r,a.opts.strictNumbers,Ai.DataType.Wrong)}`}return D.nil}function s(){if(i.validateSchema){let c=t.scopeValue("validate$data",{ref:i.validateSchema});return(0,D._)`!${c}(${r})`}return D.nil}}subschema(t,r){let n=(0,Co.getSubschema)(this.it,t);(0,Co.extendSubschemaData)(n,this.it,t),(0,Co.extendSubschemaMode)(n,t);let i={...this.it,...n,items:void 0,props:void 0};return Zh(i,r),i}mergeEvaluated(t,r){let{it:n,gen:i}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=bt.mergeEvaluated.props(i,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=bt.mergeEvaluated.items(i,t.items,n.items,r)))}mergeValidEvaluated(t,r){let{it:n,gen:i}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return i.if(r,()=>this.mergeEvaluated(t,D.Name)),!0}};Ot.KeywordCxt=Ri;function cd(e,t,r,n){let i=new Ri(e,r,t);"code"in r?r.code(i,n):i.$data&&r.validate?(0,fn.funcKeywordCode)(i,r):"macro"in r?(0,fn.macroKeywordCode)(i,r):(r.compile||r.validate)&&(0,fn.funcKeywordCode)(i,r)}var py=/^\/(?:[^~]|~0|~1)*$/,uy=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function ld(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let i,a;if(e==="")return T.default.rootData;if(e[0]==="/"){if(!py.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);i=e,a=T.default.rootData}else{let d=uy.exec(e);if(!d)throw new Error(`Invalid JSON-pointer: ${e}`);let l=+d[1];if(i=d[2],i==="#"){if(l>=t)throw new Error(c("property/index",l));return n[t-l]}if(l>t)throw new Error(c("data",l));if(a=r[t-l],!i)return a}let o=a,s=i.split("/");for(let d of s)d&&(a=(0,D._)`${a}${(0,D.getProperty)((0,bt.unescapeJsonPointer)(d))}`,o=(0,D._)`${o} && ${a}`);return o;function c(d,l){return`Cannot access ${d} ${l} levels up, current level is ${t}`}}Ot.getData=ld});var Pi=R(Vo=>{"use strict";Object.defineProperty(Vo,"__esModule",{value:!0});var Lo=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};Vo.default=Lo});var gn=R(Uo=>{"use strict";Object.defineProperty(Uo,"__esModule",{value:!0});var Mo=pn(),qo=class extends Error{constructor(t,r,n,i){super(i||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Mo.resolveUrl)(t,r,n),this.missingSchema=(0,Mo.normalizeId)((0,Mo.getFullPath)(t,this.missingRef))}};Uo.default=qo});var hn=R(Ke=>{"use strict";Object.defineProperty(Ke,"__esModule",{value:!0});Ke.resolveSchema=Ke.getCompilingSchema=Ke.resolveRef=Ke.compileSchema=Ke.SchemaEnv=void 0;var nt=x(),fy=Pi(),Zt=Je(),it=pn(),dd=U(),my=mn(),Dr=class{constructor(t){var r;this.refs={},this.dynamicAnchors={};let n;typeof t.schema=="object"&&(n=t.schema),this.schema=t.schema,this.schemaId=t.schemaId,this.root=t.root||this,this.baseId=(r=t.baseId)!==null&&r!==void 0?r:(0,it.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};Ke.SchemaEnv=Dr;function zo(e){let t=pd.call(this,e);if(t)return t;let r=(0,it.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:i}=this.opts.code,{ownProperties:a}=this.opts,o=new nt.CodeGen(this.scope,{es5:n,lines:i,ownProperties:a}),s;e.$async&&(s=o.scopeValue("Error",{ref:fy.default,code:(0,nt._)`require("ajv/dist/runtime/validation_error").default`}));let c=o.scopeName("validate");e.validateName=c;let d={gen:o,allErrors:this.opts.allErrors,data:Zt.default.data,parentData:Zt.default.parentData,parentDataProperty:Zt.default.parentDataProperty,dataNames:[Zt.default.data],dataPathArr:[nt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,nt.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:s,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:nt.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,nt._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(e),(0,my.validateFunctionCode)(d),o.optimize(this.opts.code.optimize);let p=o.toString();l=`${o.scopeRefs(Zt.default.scope)}return ${p}`,this.opts.code.process&&(l=this.opts.code.process(l,e));let u=new Function(`${Zt.default.self}`,`${Zt.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:u}),u.errors=null,u.schema=e.schema,u.schemaEnv=e,e.$async&&(u.$async=!0),this.opts.code.source===!0&&(u.source={validateName:c,validateCode:p,scopeValues:o._values}),this.opts.unevaluated){let{props:f,items:g}=d;u.evaluated={props:f instanceof nt.Name?void 0:f,items:g instanceof nt.Name?void 0:g,dynamicProps:f instanceof nt.Name,dynamicItems:g instanceof nt.Name},u.source&&(u.source.evaluated=(0,nt.stringify)(u.evaluated))}return e.validate=u,e}catch(p){throw delete e.validate,delete e.validateName,l&&this.logger.error("Error compiling schema, function code:",l),p}finally{this._compilations.delete(e)}}Ke.compileSchema=zo;function gy(e,t,r){var n;r=(0,it.resolveUrl)(this.opts.uriResolver,t,r);let i=e.refs[r];if(i)return i;let a=wy.call(this,e,r);if(a===void 0){let o=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:s}=this.opts;o&&(a=new Dr({schema:o,schemaId:s,root:e,baseId:t}))}if(a!==void 0)return e.refs[r]=hy.call(this,a)}Ke.resolveRef=gy;function hy(e){return(0,it.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:zo.call(this,e)}function pd(e){for(let t of this._compilations)if(yy(t,e))return t}Ke.getCompilingSchema=pd;function yy(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function wy(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||Ni.call(this,e,t)}function Ni(e,t){let r=this.opts.uriResolver.parse(t),n=(0,it._getFullPath)(this.opts.uriResolver,r),i=(0,it.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===i)return Fo.call(this,r,e);let a=(0,it.normalizeId)(n),o=this.refs[a]||this.schemas[a];if(typeof o=="string"){let s=Ni.call(this,e,o);return typeof s?.schema!="object"?void 0:Fo.call(this,r,s)}if(typeof o?.schema=="object"){if(o.validate||zo.call(this,o),a===(0,it.normalizeId)(t)){let{schema:s}=o,{schemaId:c}=this.opts,d=s[c];return d&&(i=(0,it.resolveUrl)(this.opts.uriResolver,i,d)),new Dr({schema:s,schemaId:c,root:e,baseId:i})}return Fo.call(this,r,o)}}Ke.resolveSchema=Ni;var vy=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Fo(e,{baseId:t,schema:r,root:n}){var i;if(((i=e.fragment)===null||i===void 0?void 0:i[0])!=="/")return;for(let s of e.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,dd.unescapeFragment)(s)];if(c===void 0)return;r=c;let d=typeof r=="object"&&r[this.opts.schemaId];!vy.has(s)&&d&&(t=(0,it.resolveUrl)(this.opts.uriResolver,t,d))}let a;if(typeof r!="boolean"&&r.$ref&&!(0,dd.schemaHasRulesButRef)(r,this.RULES)){let s=(0,it.resolveUrl)(this.opts.uriResolver,t,r.$ref);a=Ni.call(this,n,s)}let{schemaId:o}=this.opts;if(a=a||new Dr({schema:r,schemaId:o,root:n,baseId:t}),a.schema!==a.root.schema)return a}});var ud=R((pR,Iy)=>{Iy.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Jo=R((uR,wd)=>{"use strict";var by=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),md=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),Bo=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),gd=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),ky=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Go(e){let t="",r=0,n=0;for(n=0;n<e.length;n++)if(r=e[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n];break}for(n+=1;n<e.length;n++){if(r=e[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n]}return t}var _y=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function fd(e){return e.length=0,!0}function Ey(e,t,r){if(e.length){let n=Go(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}function Ay(e){let t=0,r={error:!1,address:"",zone:""},n=[],i=[],a=!1,o=!1,s=Ey;for(let c=0;c<e.length;c++){let d=e[c];if(!(d==="["||d==="]"))if(d===":"){if(a===!0&&(o=!0),!s(i,n,r))break;if(++t>7){r.error=!0;break}c>0&&e[c-1]===":"&&(a=!0),n.push(":");continue}else if(d==="%"){if(!s(i,n,r))break;s=fd}else{i.push(d);continue}}return i.length&&(s===fd?r.zone=i.join(""):o?n.push(i.join("")):n.push(Go(i))),r.address=n.join(""),r}function hd(e){if(Ry(e,":")<2)return{host:e,isIPV6:!1};let t=Ay(e);if(t.error)return{host:e,isIPV6:!1};{let r=t.address,n=t.address;return t.zone&&(r+="%"+t.zone,n+="%25"+t.zone),{host:r,isIPV6:!0,escapedHost:n}}}function Ry(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}function Py(e){let t=e,r=[],n=-1,i=0;for(;i=t.length;){if(i===1){if(t===".")break;if(t==="/"){r.push("/");break}else{r.push(t);break}}else if(i===2){if(t[0]==="."){if(t[1]===".")break;if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&(t[1]==="."||t[1]==="/")){r.push("/");break}}else if(i===3&&t==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(t[0]==="."){if(t[1]==="."){if(t[2]==="/"){t=t.slice(3);continue}}else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&t[1]==="."){if(t[2]==="/"){t=t.slice(2);continue}else if(t[2]==="."&&t[3]==="/"){t=t.slice(3),r.length!==0&&r.pop();continue}}if((n=t.indexOf("/",1))===-1){r.push(t);break}else r.push(t.slice(0,n)),t=t.slice(n)}return r.join("")}var Ny={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},Dy=/[@/?#:]/g,Sy=/[@/?#]/g;function yd(e,t){let r=t?Sy:Dy;return r.lastIndex=0,e.replace(r,n=>Ny[n])}function jy(e,t=!1){if(e.indexOf("%")===-1)return e;let r="";for(let n=0;n<e.length;n++){if(e[n]==="%"&&n+2<e.length){let i=e.slice(n+1,n+3);if(Bo(i)){let a=i.toUpperCase(),o=String.fromCharCode(parseInt(a,16));t&&gd(o)?r+=o:r+="%"+a,n+=2;continue}}r+=e[n]}return r}function $y(e){let t="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){let n=e.slice(r+1,r+3);if(Bo(n)){let i=n.toUpperCase(),a=String.fromCharCode(parseInt(i,16));a!=="."&&gd(a)?t+=a:t+="%"+i,r+=2;continue}}ky(e[r])?t+=e[r]:t+=escape(e[r])}return t}function Oy(e){let t="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){let n=e.slice(r+1,r+3);if(Bo(n)){t+="%"+n.toUpperCase(),r+=2;continue}}t+=escape(e[r])}return t}function Cy(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!md(r)){let n=hd(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=yd(r,!1)}t.push(r)}return(typeof e.port=="number"||typeof e.port=="string")&&(t.push(":"),t.push(String(e.port))),t.length?t.join(""):void 0}wd.exports={nonSimpleDomain:_y,recomposeAuthority:Cy,reescapeHostDelimiters:yd,normalizePercentEncoding:jy,normalizePathEncoding:$y,escapePreservingEscapes:Oy,removeDotSegments:Py,isIPv4:md,isUUID:by,normalizeIPv6:hd,stringArrayToHexStripped:Go}});var _d=R((fR,kd)=>{"use strict";var{isUUID:Ty}=Jo(),xy=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,Ly=["http","https","ws","wss","urn","urn:uuid"];function Vy(e){return Ly.indexOf(e)!==-1}function Wo(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]==="w"||e.scheme[0]==="W")&&(e.scheme[1]==="s"||e.scheme[1]==="S")&&(e.scheme[2]==="s"||e.scheme[2]==="S"):!1}function vd(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function Id(e){let t=String(e.scheme).toLowerCase()==="https";return(e.port===(t?443:80)||e.port==="")&&(e.port=void 0),e.path||(e.path="/"),e}function My(e){return e.secure=Wo(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function qy(e){if((e.port===(Wo(e)?443:80)||e.port==="")&&(e.port=void 0),typeof e.secure=="boolean"&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){let[t,r]=e.resourceName.split("?");e.path=t&&t!=="/"?t:void 0,e.query=r,e.resourceName=void 0}return e.fragment=void 0,e}function Uy(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(xy);if(r){let n=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];let i=`${n}:${t.nid||e.nid}`,a=Ko(i);e.path=void 0,a&&(e=a.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function Fy(e,t){if(e.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),i=`${r}:${t.nid||n}`,a=Ko(i);a&&(e=a.serialize(e,t));let o=e,s=e.nss;return o.path=`${n||t.nid}:${s}`,t.skipEscape=!0,o}function zy(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!Ty(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function By(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var bd={scheme:"http",domainHost:!0,parse:vd,serialize:Id},Gy={scheme:"https",domainHost:bd.domainHost,parse:vd,serialize:Id},Di={scheme:"ws",domainHost:!0,parse:My,serialize:qy},Jy={scheme:"wss",domainHost:Di.domainHost,parse:Di.parse,serialize:Di.serialize},Wy={scheme:"urn",parse:Uy,serialize:Fy,skipNormalize:!0},Ky={scheme:"urn:uuid",parse:zy,serialize:By,skipNormalize:!0},Si={http:bd,https:Gy,ws:Di,wss:Jy,urn:Wy,"urn:uuid":Ky};Object.setPrototypeOf(Si,null);function Ko(e){return e&&(Si[e]||Si[e.toLowerCase()])||void 0}kd.exports={wsIsSecure:Wo,SCHEMES:Si,isValidSchemeName:Vy,getSchemeHandler:Ko}});var Nd=R((mR,Oi)=>{"use strict";var{normalizeIPv6:Yy,removeDotSegments:yn,recomposeAuthority:Hy,normalizePercentEncoding:Zy,normalizePathEncoding:Xy,escapePreservingEscapes:Qy,reescapeHostDelimiters:ew,isIPv4:tw,nonSimpleDomain:rw}=Jo(),{SCHEMES:nw,getSchemeHandler:Ad}=_d();function iw(e,t){return typeof e=="string"?e=pw(e,t):typeof e=="object"&&(e=$i(Xt(e,t),t)),e}function aw(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:i,malformedAuthorityOrPort:a}=ji(e,n),{parsed:o,malformedAuthorityOrPort:s}=ji(t,n);if(a||s)throw new Error(i.error||o.error||"URI is malformed.");let c=Rd(i,o,n,!0);return n.skipEscape=!0,Xt(c,n)}function Rd(e,t,r,n){let i={};return n||(e=$i(Xt(e,r),r),t=$i(Xt(t,r),r)),r=r||{},!r.tolerant&&t.scheme?(i.scheme=t.scheme,i.userinfo=t.userinfo,i.host=t.host,i.port=t.port,i.path=yn(t.path||""),i.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(i.userinfo=t.userinfo,i.host=t.host,i.port=t.port,i.path=yn(t.path||""),i.query=t.query):(t.path?(t.path[0]==="/"?i.path=yn(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?i.path="/"+t.path:e.path?i.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:i.path=t.path,i.path=yn(i.path)),i.query=t.query):(i.path=e.path,t.query!==void 0?i.query=t.query:i.query=e.query),i.userinfo=e.userinfo,i.host=e.host,i.port=e.port),i.scheme=e.scheme),i.fragment=t.fragment,i}function ow(e,t,r){let n=Ed(e,r),i=Ed(t,r);return n!==void 0&&i!==void 0&&n.toLowerCase()===i.toLowerCase()}function Xt(e,t){let r={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},n=Object.assign({},t),i=[],a=Ad(n.scheme||r.scheme);a&&a.serialize&&a.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=Zy(r.path):(r.path=Qy(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&i.push(r.scheme,":");let o=Hy(r);if(o!==void 0&&(n.reference!=="suffix"&&i.push("//"),i.push(o),r.path&&r.path[0]!=="/"&&i.push("/")),r.path!==void 0){let s=r.path;!n.absolutePath&&(!a||!a.absolutePath)&&(s=yn(s)),o===void 0&&s[0]==="/"&&s[1]==="/"&&(s="/%2F"+s.slice(2)),i.push(s)}return r.query!==void 0&&i.push("?",r.query),r.fragment!==void 0&&i.push("#",r.fragment),i.join("")}var sw=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,cw=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,lw=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function dw(e,t){if(t[2]!==void 0&&e.path&&e.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof e.port=="number"&&(e.port<0||e.port>65535))return"URI port is malformed."}function ji(e,t){let r=Object.assign({},t),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},i=!1,a=!1;r.reference==="suffix"&&(r.scheme?e=r.scheme+":"+e:e="//"+e);let o=e.match(cw);o!==null&&o[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",i=!0);let s=e.match(lw);if(s!==null){let d=s[1],l=d.replace(/[\t\n\r]/g,"");l.length>=2&&(l.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",i=!0):d.length!==l.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",i=!0))}let c=e.match(sw);if(c){n.scheme=c[1],n.userinfo=c[3],n.host=c[4],n.port=parseInt(c[5],10),n.path=c[6]||"",n.query=c[7],n.fragment=c[8],isNaN(n.port)&&(n.port=c[5]);let d=dw(n,c);if(d!==void 0&&(n.error=n.error||d,i=!0),n.host)if(tw(n.host)===!1){let m=Yy(n.host);n.host=m.host.toLowerCase(),a=m.isIPV6}else a=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let l=Ad(r.scheme||n.scheme);if(!r.unicodeSupport&&(!l||!l.unicodeSupport)&&n.host&&(r.domainHost||l&&l.domainHost)&&a===!1&&rw(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(p){n.error=n.error||"Host's domain name can not be converted to ASCII: "+p}if((!l||l&&!l.skipNormalize)&&(e.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=ew(unescape(n.host),a))),n.path&&(n.path=Xy(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}l&&l.parse&&l.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:i}}function $i(e,t){return ji(e,t).parsed}function pw(e,t){return Pd(e,t).normalized}function Pd(e,t){let{parsed:r,malformedAuthorityOrPort:n}=ji(e,t);return{normalized:n?e:Xt(r,t),malformedAuthorityOrPort:n}}function Ed(e,t){if(typeof e=="string"){let{normalized:r,malformedAuthorityOrPort:n}=Pd(e,t);return n?void 0:r}if(typeof e=="object")return Xt(e,t)}var Yo={SCHEMES:nw,normalize:iw,resolve:aw,resolveComponent:Rd,equal:ow,serialize:Xt,parse:$i};Oi.exports=Yo;Oi.exports.default=Yo;Oi.exports.fastUri=Yo});var Sd=R(Ho=>{"use strict";Object.defineProperty(Ho,"__esModule",{value:!0});var Dd=Nd();Dd.code='require("ajv/dist/runtime/uri").default';Ho.default=Dd});var Vd=R(Ie=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.CodeGen=Ie.Name=Ie.nil=Ie.stringify=Ie.str=Ie._=Ie.KeywordCxt=void 0;var uw=mn();Object.defineProperty(Ie,"KeywordCxt",{enumerable:!0,get:function(){return uw.KeywordCxt}});var Sr=x();Object.defineProperty(Ie,"_",{enumerable:!0,get:function(){return Sr._}});Object.defineProperty(Ie,"str",{enumerable:!0,get:function(){return Sr.str}});Object.defineProperty(Ie,"stringify",{enumerable:!0,get:function(){return Sr.stringify}});Object.defineProperty(Ie,"nil",{enumerable:!0,get:function(){return Sr.nil}});Object.defineProperty(Ie,"Name",{enumerable:!0,get:function(){return Sr.Name}});Object.defineProperty(Ie,"CodeGen",{enumerable:!0,get:function(){return Sr.CodeGen}});var fw=Pi(),Td=gn(),mw=Eo(),wn=hn(),gw=x(),vn=pn(),Ci=dn(),Xo=U(),jd=ud(),hw=Sd(),xd=(e,t)=>new RegExp(e,t);xd.code="new RegExp";var yw=["removeAdditional","useDefaults","coerceTypes"],ww=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),vw={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},Iw={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},$d=200;function bw(e){var t,r,n,i,a,o,s,c,d,l,p,m,u,f,g,h,w,_,b,A,y,k,S,O,se;let $=e.strict,P=(t=e.code)===null||t===void 0?void 0:t.optimize,H=P===!0||P===void 0?1:P||0,ne=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:xd,Be=(i=e.uriResolver)!==null&&i!==void 0?i:hw.default;return{strictSchema:(o=(a=e.strictSchema)!==null&&a!==void 0?a:$)!==null&&o!==void 0?o:!0,strictNumbers:(c=(s=e.strictNumbers)!==null&&s!==void 0?s:$)!==null&&c!==void 0?c:!0,strictTypes:(l=(d=e.strictTypes)!==null&&d!==void 0?d:$)!==null&&l!==void 0?l:"log",strictTuples:(m=(p=e.strictTuples)!==null&&p!==void 0?p:$)!==null&&m!==void 0?m:"log",strictRequired:(f=(u=e.strictRequired)!==null&&u!==void 0?u:$)!==null&&f!==void 0?f:!1,code:e.code?{...e.code,optimize:H,regExp:ne}:{optimize:H,regExp:ne},loopRequired:(g=e.loopRequired)!==null&&g!==void 0?g:$d,loopEnum:(h=e.loopEnum)!==null&&h!==void 0?h:$d,meta:(w=e.meta)!==null&&w!==void 0?w:!0,messages:(_=e.messages)!==null&&_!==void 0?_:!0,inlineRefs:(b=e.inlineRefs)!==null&&b!==void 0?b:!0,schemaId:(A=e.schemaId)!==null&&A!==void 0?A:"$id",addUsedSchema:(y=e.addUsedSchema)!==null&&y!==void 0?y:!0,validateSchema:(k=e.validateSchema)!==null&&k!==void 0?k:!0,validateFormats:(S=e.validateFormats)!==null&&S!==void 0?S:!0,unicodeRegExp:(O=e.unicodeRegExp)!==null&&O!==void 0?O:!0,int32range:(se=e.int32range)!==null&&se!==void 0?se:!0,uriResolver:Be}}var In=class{constructor(t={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,t=this.opts={...t,...bw(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new gw.ValueScope({scope:{},prefixes:ww,es5:r,lines:n}),this.logger=Pw(t.logger);let i=t.validateFormats;t.validateFormats=!1,this.RULES=(0,mw.getRules)(),Od.call(this,vw,t,"NOT SUPPORTED"),Od.call(this,Iw,t,"DEPRECATED","warn"),this._metaOpts=Aw.call(this),t.formats&&_w.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&Ew.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),kw.call(this),t.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,i=jd;n==="id"&&(i={...jd},i.id=i.$id,delete i.$id),r&&t&&this.addMetaSchema(i,i[n],!1)}defaultMeta(){let{meta:t,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof t=="object"?t[r]||t:void 0}validate(t,r){let n;if(typeof t=="string"){if(n=this.getSchema(t),!n)throw new Error(`no schema with key or ref "${t}"`)}else n=this.compile(t);let i=n(r);return"$async"in n||(this.errors=n.errors),i}compile(t,r){let n=this._addSchema(t,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(t,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return i.call(this,t,r);async function i(l,p){await a.call(this,l.$schema);let m=this._addSchema(l,p);return m.validate||o.call(this,m)}async function a(l){l&&!this.getSchema(l)&&await i.call(this,{$ref:l},!0)}async function o(l){try{return this._compileSchemaEnv(l)}catch(p){if(!(p instanceof Td.default))throw p;return s.call(this,p),await c.call(this,p.missingSchema),o.call(this,l)}}function s({missingSchema:l,missingRef:p}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${p} cannot be resolved`)}async function c(l){let p=await d.call(this,l);this.refs[l]||await a.call(this,p.$schema),this.refs[l]||this.addSchema(p,l,r)}async function d(l){let p=this._loading[l];if(p)return p;try{return await(this._loading[l]=n(l))}finally{delete this._loading[l]}}}addSchema(t,r,n,i=this.opts.validateSchema){if(Array.isArray(t)){for(let o of t)this.addSchema(o,void 0,n,i);return this}let a;if(typeof t=="object"){let{schemaId:o}=this.opts;if(a=t[o],a!==void 0&&typeof a!="string")throw new Error(`schema ${o} must be string`)}return r=(0,vn.normalizeId)(r||a),this._checkUnique(r),this.schemas[r]=this._addSchema(t,n,r,i,!0),this}addMetaSchema(t,r,n=this.opts.validateSchema){return this.addSchema(t,r,!0,n),this}validateSchema(t,r){if(typeof t=="boolean")return!0;let n;if(n=t.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let i=this.validate(n,t);if(!i&&r){let a="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(a);else throw new Error(a)}return i}getSchema(t){let r;for(;typeof(r=Cd.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,i=new wn.SchemaEnv({schema:{},schemaId:n});if(r=wn.resolveSchema.call(this,i,t),!r)return;this.refs[t]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(t){if(t instanceof RegExp)return this._removeAllSchemas(this.schemas,t),this._removeAllSchemas(this.refs,t),this;switch(typeof t){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=Cd.call(this,t);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[t],delete this.refs[t],this}case"object":{let r=t;this._cache.delete(r);let n=t[this.opts.schemaId];return n&&(n=(0,vn.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(t){for(let r of t)this.addKeyword(r);return this}addKeyword(t,r){let n;if(typeof t=="string")n=t,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof t=="object"&&r===void 0){if(r=t,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(Dw.call(this,n,r),!r)return(0,Xo.eachItem)(n,a=>Zo.call(this,a)),this;jw.call(this,r);let i={...r,type:(0,Ci.getJSONTypes)(r.type),schemaType:(0,Ci.getJSONTypes)(r.schemaType)};return(0,Xo.eachItem)(n,i.type.length===0?a=>Zo.call(this,a,i):a=>i.type.forEach(o=>Zo.call(this,a,i,o))),this}getKeyword(t){let r=this.RULES.all[t];return typeof r=="object"?r.definition:!!r}removeKeyword(t){let{RULES:r}=this;delete r.keywords[t],delete r.all[t];for(let n of r.rules){let i=n.rules.findIndex(a=>a.keyword===t);i>=0&&n.rules.splice(i,1)}return this}addFormat(t,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[t]=r,this}errorsText(t=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!t||t.length===0?"No errors":t.map(i=>`${n}${i.instancePath} ${i.message}`).reduce((i,a)=>i+r+a)}$dataMetaSchema(t,r){let n=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let i of r){let a=i.split("/").slice(1),o=t;for(let s of a)o=o[s];for(let s in n){let c=n[s];if(typeof c!="object")continue;let{$data:d}=c.definition,l=o[s];d&&l&&(o[s]=Ld(l))}}return t}_removeAllSchemas(t,r){for(let n in t){let i=t[n];(!r||r.test(n))&&(typeof i=="string"?delete t[n]:i&&!i.meta&&(this._cache.delete(i.schema),delete t[n]))}}_addSchema(t,r,n,i=this.opts.validateSchema,a=this.opts.addUsedSchema){let o,{schemaId:s}=this.opts;if(typeof t=="object")o=t[s];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof t!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(t);if(c!==void 0)return c;n=(0,vn.normalizeId)(o||n);let d=vn.getSchemaRefs.call(this,t,n);return c=new wn.SchemaEnv({schema:t,schemaId:s,meta:r,baseId:n,localRefs:d}),this._cache.set(c.schema,c),a&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),i&&this.validateSchema(t,!0),c}_checkUnique(t){if(this.schemas[t]||this.refs[t])throw new Error(`schema with key or id "${t}" already exists`)}_compileSchemaEnv(t){if(t.meta?this._compileMetaSchema(t):wn.compileSchema.call(this,t),!t.validate)throw new Error("ajv implementation error");return t.validate}_compileMetaSchema(t){let r=this.opts;this.opts=this._metaOpts;try{wn.compileSchema.call(this,t)}finally{this.opts=r}}};In.ValidationError=fw.default;In.MissingRefError=Td.default;Ie.default=In;function Od(e,t,r,n="error"){for(let i in e){let a=i;a in t&&this.logger[n](`${r}: option ${i}. ${e[a]}`)}}function Cd(e){return e=(0,vn.normalizeId)(e),this.schemas[e]||this.refs[e]}function kw(){let e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function _w(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function Ew(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let t in e){let r=e[t];r.keyword||(r.keyword=t),this.addKeyword(r)}}function Aw(){let e={...this.opts};for(let t of yw)delete e[t];return e}var Rw={log(){},warn(){},error(){}};function Pw(e){if(e===!1)return Rw;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}var Nw=/^[a-z_$][a-z0-9_$:-]*$/i;function Dw(e,t){let{RULES:r}=this;if((0,Xo.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!Nw.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!t&&t.$data&&!("code"in t||"validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function Zo(e,t,r){var n;let i=t?.post;if(r&&i)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:a}=this,o=i?a.post:a.rules.find(({type:c})=>c===r);if(o||(o={type:r,rules:[]},a.rules.push(o)),a.keywords[e]=!0,!t)return;let s={keyword:e,definition:{...t,type:(0,Ci.getJSONTypes)(t.type),schemaType:(0,Ci.getJSONTypes)(t.schemaType)}};t.before?Sw.call(this,o,s,t.before):o.rules.push(s),a.all[e]=s,(n=t.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function Sw(e,t,r){let n=e.rules.findIndex(i=>i.keyword===r);n>=0?e.rules.splice(n,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}function jw(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=Ld(t)),e.validateSchema=this.compile(t,!0))}var $w={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Ld(e){return{anyOf:[e,$w]}}});var Md=R(Qo=>{"use strict";Object.defineProperty(Qo,"__esModule",{value:!0});var Ow={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Qo.default=Ow});var Li=R(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.callRef=Qt.getValidate=void 0;var Cw=gn(),qd=We(),qe=x(),jr=Je(),Ud=hn(),Ti=U(),Tw={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:n}=e,{baseId:i,schemaEnv:a,validateName:o,opts:s,self:c}=n,{root:d}=a;if((r==="#"||r==="#/")&&i===d.baseId)return p();let l=Ud.resolveRef.call(c,d,i,r);if(l===void 0)throw new Cw.default(n.opts.uriResolver,i,r);if(l instanceof Ud.SchemaEnv)return m(l);return u(l);function p(){if(a===d)return xi(e,o,a,a.$async);let f=t.scopeValue("root",{ref:d});return xi(e,(0,qe._)`${f}.validate`,d,d.$async)}function m(f){let g=Fd(e,f);xi(e,g,f,f.$async)}function u(f){let g=t.scopeValue("schema",s.code.source===!0?{ref:f,code:(0,qe.stringify)(f)}:{ref:f}),h=t.name("valid"),w=e.subschema({schema:f,dataTypes:[],schemaPath:qe.nil,topSchemaRef:g,errSchemaPath:r},h);e.mergeEvaluated(w),e.ok(h)}}};function Fd(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,qe._)`${r.scopeValue("wrapper",{ref:t})}.validate`}Qt.getValidate=Fd;function xi(e,t,r,n){let{gen:i,it:a}=e,{allErrors:o,schemaEnv:s,opts:c}=a,d=c.passContext?jr.default.this:qe.nil;n?l():p();function l(){if(!s.$async)throw new Error("async schema referenced by sync schema");let f=i.let("valid");i.try(()=>{i.code((0,qe._)`await ${(0,qd.callValidateCode)(e,t,d)}`),u(t),o||i.assign(f,!0)},g=>{i.if((0,qe._)`!(${g} instanceof ${a.ValidationError})`,()=>i.throw(g)),m(g),o||i.assign(f,!1)}),e.ok(f)}function p(){e.result((0,qd.callValidateCode)(e,t,d),()=>u(t),()=>m(t))}function m(f){let g=(0,qe._)`${f}.errors`;i.assign(jr.default.vErrors,(0,qe._)`${jr.default.vErrors} === null ? ${g} : ${jr.default.vErrors}.concat(${g})`),i.assign(jr.default.errors,(0,qe._)`${jr.default.vErrors}.length`)}function u(f){var g;if(!a.opts.unevaluated)return;let h=(g=r?.validate)===null||g===void 0?void 0:g.evaluated;if(a.props!==!0)if(h&&!h.dynamicProps)h.props!==void 0&&(a.props=Ti.mergeEvaluated.props(i,h.props,a.props));else{let w=i.var("props",(0,qe._)`${f}.evaluated.props`);a.props=Ti.mergeEvaluated.props(i,w,a.props,qe.Name)}if(a.items!==!0)if(h&&!h.dynamicItems)h.items!==void 0&&(a.items=Ti.mergeEvaluated.items(i,h.items,a.items));else{let w=i.var("items",(0,qe._)`${f}.evaluated.items`);a.items=Ti.mergeEvaluated.items(i,w,a.items,qe.Name)}}}Qt.callRef=xi;Qt.default=Tw});var zd=R(es=>{"use strict";Object.defineProperty(es,"__esModule",{value:!0});var xw=Md(),Lw=Li(),Vw=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",xw.default,Lw.default];es.default=Vw});var Bd=R(ts=>{"use strict";Object.defineProperty(ts,"__esModule",{value:!0});var Vi=x(),Ct=Vi.operators,Mi={maximum:{okStr:"<=",ok:Ct.LTE,fail:Ct.GT},minimum:{okStr:">=",ok:Ct.GTE,fail:Ct.LT},exclusiveMaximum:{okStr:"<",ok:Ct.LT,fail:Ct.GTE},exclusiveMinimum:{okStr:">",ok:Ct.GT,fail:Ct.LTE}},Mw={message:({keyword:e,schemaCode:t})=>(0,Vi.str)`must be ${Mi[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,Vi._)`{comparison: ${Mi[e].okStr}, limit: ${t}}`},qw={keyword:Object.keys(Mi),type:"number",schemaType:"number",$data:!0,error:Mw,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,Vi._)`${r} ${Mi[t].fail} ${n} || isNaN(${r})`)}};ts.default=qw});var Gd=R(rs=>{"use strict";Object.defineProperty(rs,"__esModule",{value:!0});var bn=x(),Uw={message:({schemaCode:e})=>(0,bn.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,bn._)`{multipleOf: ${e}}`},Fw={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Uw,code(e){let{gen:t,data:r,schemaCode:n,it:i}=e,a=i.opts.multipleOfPrecision,o=t.let("res"),s=a?(0,bn._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${a}`:(0,bn._)`${o} !== parseInt(${o})`;e.fail$data((0,bn._)`(${n} === 0 || (${o} = ${r}/${n}, ${s}))`)}};rs.default=Fw});var Wd=R(ns=>{"use strict";Object.defineProperty(ns,"__esModule",{value:!0});function Jd(e){let t=e.length,r=0,n=0,i;for(;n<t;)r++,i=e.charCodeAt(n++),i>=55296&&i<=56319&&n<t&&(i=e.charCodeAt(n),(i&64512)===56320&&n++);return r}ns.default=Jd;Jd.code='require("ajv/dist/runtime/ucs2length").default'});var Kd=R(is=>{"use strict";Object.defineProperty(is,"__esModule",{value:!0});var er=x(),zw=U(),Bw=Wd(),Gw={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,er.str)`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>(0,er._)`{limit: ${e}}`},Jw={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Gw,code(e){let{keyword:t,data:r,schemaCode:n,it:i}=e,a=t==="maxLength"?er.operators.GT:er.operators.LT,o=i.opts.unicode===!1?(0,er._)`${r}.length`:(0,er._)`${(0,zw.useFunc)(e.gen,Bw.default)}(${r})`;e.fail$data((0,er._)`${o} ${a} ${n}`)}};is.default=Jw});var Yd=R(as=>{"use strict";Object.defineProperty(as,"__esModule",{value:!0});var Ww=We(),Kw=U(),$r=x(),Yw={message:({schemaCode:e})=>(0,$r.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,$r._)`{pattern: ${e}}`},Hw={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Yw,code(e){let{gen:t,data:r,$data:n,schema:i,schemaCode:a,it:o}=e,s=o.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=o.opts.code,d=c.code==="new RegExp"?(0,$r._)`new RegExp`:(0,Kw.useFunc)(t,c),l=t.let("valid");t.try(()=>t.assign(l,(0,$r._)`${d}(${a}, ${s}).test(${r})`),()=>t.assign(l,!1)),e.fail$data((0,$r._)`!${l}`)}else{let c=(0,Ww.usePattern)(e,i);e.fail$data((0,$r._)`!${c}.test(${r})`)}}};as.default=Hw});var Hd=R(os=>{"use strict";Object.defineProperty(os,"__esModule",{value:!0});var kn=x(),Zw={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,kn.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0,kn._)`{limit: ${e}}`},Xw={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Zw,code(e){let{keyword:t,data:r,schemaCode:n}=e,i=t==="maxProperties"?kn.operators.GT:kn.operators.LT;e.fail$data((0,kn._)`Object.keys(${r}).length ${i} ${n}`)}};os.default=Xw});var Zd=R(ss=>{"use strict";Object.defineProperty(ss,"__esModule",{value:!0});var _n=We(),En=x(),Qw=U(),ev={message:({params:{missingProperty:e}})=>(0,En.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,En._)`{missingProperty: ${e}}`},tv={keyword:"required",type:"object",schemaType:"array",$data:!0,error:ev,code(e){let{gen:t,schema:r,schemaCode:n,data:i,$data:a,it:o}=e,{opts:s}=o;if(!a&&r.length===0)return;let c=r.length>=s.loopRequired;if(o.allErrors?d():l(),s.strictRequired){let u=e.parentSchema.properties,{definedProperties:f}=e.it;for(let g of r)if(u?.[g]===void 0&&!f.has(g)){let h=o.schemaEnv.baseId+o.errSchemaPath,w=`required property "${g}" is not defined at "${h}" (strictRequired)`;(0,Qw.checkStrictMode)(o,w,o.opts.strictRequired)}}function d(){if(c||a)e.block$data(En.nil,p);else for(let u of r)(0,_n.checkReportMissingProp)(e,u)}function l(){let u=t.let("missing");if(c||a){let f=t.let("valid",!0);e.block$data(f,()=>m(u,f)),e.ok(f)}else t.if((0,_n.checkMissingProp)(e,r,u)),(0,_n.reportMissingProp)(e,u),t.else()}function p(){t.forOf("prop",n,u=>{e.setParams({missingProperty:u}),t.if((0,_n.noPropertyInData)(t,i,u,s.ownProperties),()=>e.error())})}function m(u,f){e.setParams({missingProperty:u}),t.forOf(u,n,()=>{t.assign(f,(0,_n.propertyInData)(t,i,u,s.ownProperties)),t.if((0,En.not)(f),()=>{e.error(),t.break()})},En.nil)}}};ss.default=tv});var Xd=R(cs=>{"use strict";Object.defineProperty(cs,"__esModule",{value:!0});var An=x(),rv={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,An.str)`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>(0,An._)`{limit: ${e}}`},nv={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:rv,code(e){let{keyword:t,data:r,schemaCode:n}=e,i=t==="maxItems"?An.operators.GT:An.operators.LT;e.fail$data((0,An._)`${r}.length ${i} ${n}`)}};cs.default=nv});var qi=R(ls=>{"use strict";Object.defineProperty(ls,"__esModule",{value:!0});var Qd=$o();Qd.code='require("ajv/dist/runtime/equal").default';ls.default=Qd});var ep=R(ps=>{"use strict";Object.defineProperty(ps,"__esModule",{value:!0});var ds=dn(),be=x(),iv=U(),av=qi(),ov={message:({params:{i:e,j:t}})=>(0,be.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,be._)`{i: ${e}, j: ${t}}`},sv={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:ov,code(e){let{gen:t,data:r,$data:n,schema:i,parentSchema:a,schemaCode:o,it:s}=e;if(!n&&!i)return;let c=t.let("valid"),d=a.items?(0,ds.getSchemaTypes)(a.items):[];e.block$data(c,l,(0,be._)`${o} === false`),e.ok(c);function l(){let f=t.let("i",(0,be._)`${r}.length`),g=t.let("j");e.setParams({i:f,j:g}),t.assign(c,!0),t.if((0,be._)`${f} > 1`,()=>(p()?m:u)(f,g))}function p(){return d.length>0&&!d.some(f=>f==="object"||f==="array")}function m(f,g){let h=t.name("item"),w=(0,ds.checkDataTypes)(d,h,s.opts.strictNumbers,ds.DataType.Wrong),_=t.const("indices",(0,be._)`{}`);t.for((0,be._)`;${f}--;`,()=>{t.let(h,(0,be._)`${r}[${f}]`),t.if(w,(0,be._)`continue`),d.length>1&&t.if((0,be._)`typeof ${h} == "string"`,(0,be._)`${h} += "_"`),t.if((0,be._)`typeof ${_}[${h}] == "number"`,()=>{t.assign(g,(0,be._)`${_}[${h}]`),e.error(),t.assign(c,!1).break()}).code((0,be._)`${_}[${h}] = ${f}`)})}function u(f,g){let h=(0,iv.useFunc)(t,av.default),w=t.name("outer");t.label(w).for((0,be._)`;${f}--;`,()=>t.for((0,be._)`${g} = ${f}; ${g}--;`,()=>t.if((0,be._)`${h}(${r}[${f}], ${r}[${g}])`,()=>{e.error(),t.assign(c,!1).break(w)})))}}};ps.default=sv});var tp=R(fs=>{"use strict";Object.defineProperty(fs,"__esModule",{value:!0});var us=x(),cv=U(),lv=qi(),dv={message:"must be equal to constant",params:({schemaCode:e})=>(0,us._)`{allowedValue: ${e}}`},pv={keyword:"const",$data:!0,error:dv,code(e){let{gen:t,data:r,$data:n,schemaCode:i,schema:a}=e;n||a&&typeof a=="object"?e.fail$data((0,us._)`!${(0,cv.useFunc)(t,lv.default)}(${r}, ${i})`):e.fail((0,us._)`${a} !== ${r}`)}};fs.default=pv});var rp=R(ms=>{"use strict";Object.defineProperty(ms,"__esModule",{value:!0});var Rn=x(),uv=U(),fv=qi(),mv={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,Rn._)`{allowedValues: ${e}}`},gv={keyword:"enum",schemaType:"array",$data:!0,error:mv,code(e){let{gen:t,data:r,$data:n,schema:i,schemaCode:a,it:o}=e;if(!n&&i.length===0)throw new Error("enum must have non-empty array");let s=i.length>=o.opts.loopEnum,c,d=()=>c??(c=(0,uv.useFunc)(t,fv.default)),l;if(s||n)l=t.let("valid"),e.block$data(l,p);else{if(!Array.isArray(i))throw new Error("ajv implementation error");let u=t.const("vSchema",a);l=(0,Rn.or)(...i.map((f,g)=>m(u,g)))}e.pass(l);function p(){t.assign(l,!1),t.forOf("v",a,u=>t.if((0,Rn._)`${d()}(${r}, ${u})`,()=>t.assign(l,!0).break()))}function m(u,f){let g=i[f];return typeof g=="object"&&g!==null?(0,Rn._)`${d()}(${r}, ${u}[${f}])`:(0,Rn._)`${r} === ${g}`}}};ms.default=gv});var np=R(gs=>{"use strict";Object.defineProperty(gs,"__esModule",{value:!0});var hv=Bd(),yv=Gd(),wv=Kd(),vv=Yd(),Iv=Hd(),bv=Zd(),kv=Xd(),_v=ep(),Ev=tp(),Av=rp(),Rv=[hv.default,yv.default,wv.default,vv.default,Iv.default,bv.default,kv.default,_v.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Ev.default,Av.default];gs.default=Rv});var ys=R(Pn=>{"use strict";Object.defineProperty(Pn,"__esModule",{value:!0});Pn.validateAdditionalItems=void 0;var tr=x(),hs=U(),Pv={message:({params:{len:e}})=>(0,tr.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,tr._)`{limit: ${e}}`},Nv={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Pv,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,hs.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}ip(e,n)}};function ip(e,t){let{gen:r,schema:n,data:i,keyword:a,it:o}=e;o.items=!0;let s=r.const("len",(0,tr._)`${i}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,tr._)`${s} <= ${t.length}`);else if(typeof n=="object"&&!(0,hs.alwaysValidSchema)(o,n)){let d=r.var("valid",(0,tr._)`${s} <= ${t.length}`);r.if((0,tr.not)(d),()=>c(d)),e.ok(d)}function c(d){r.forRange("i",t.length,s,l=>{e.subschema({keyword:a,dataProp:l,dataPropType:hs.Type.Num},d),o.allErrors||r.if((0,tr.not)(d),()=>r.break())})}}Pn.validateAdditionalItems=ip;Pn.default=Nv});var ws=R(Nn=>{"use strict";Object.defineProperty(Nn,"__esModule",{value:!0});Nn.validateTuple=void 0;var ap=x(),Ui=U(),Dv=We(),Sv={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return op(e,"additionalItems",t);r.items=!0,!(0,Ui.alwaysValidSchema)(r,t)&&e.ok((0,Dv.validateArray)(e))}};function op(e,t,r=e.schema){let{gen:n,parentSchema:i,data:a,keyword:o,it:s}=e;l(i),s.opts.unevaluated&&r.length&&s.items!==!0&&(s.items=Ui.mergeEvaluated.items(n,r.length,s.items));let c=n.name("valid"),d=n.const("len",(0,ap._)`${a}.length`);r.forEach((p,m)=>{(0,Ui.alwaysValidSchema)(s,p)||(n.if((0,ap._)`${d} > ${m}`,()=>e.subschema({keyword:o,schemaProp:m,dataProp:m},c)),e.ok(c))});function l(p){let{opts:m,errSchemaPath:u}=s,f=r.length,g=f===p.minItems&&(f===p.maxItems||p[t]===!1);if(m.strictTuples&&!g){let h=`"${o}" is ${f}-tuple, but minItems or maxItems/${t} are not specified or different at path "${u}"`;(0,Ui.checkStrictMode)(s,h,m.strictTuples)}}}Nn.validateTuple=op;Nn.default=Sv});var sp=R(vs=>{"use strict";Object.defineProperty(vs,"__esModule",{value:!0});var jv=ws(),$v={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,jv.validateTuple)(e,"items")};vs.default=$v});var lp=R(Is=>{"use strict";Object.defineProperty(Is,"__esModule",{value:!0});var cp=x(),Ov=U(),Cv=We(),Tv=ys(),xv={message:({params:{len:e}})=>(0,cp.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,cp._)`{limit: ${e}}`},Lv={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:xv,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:i}=r;n.items=!0,!(0,Ov.alwaysValidSchema)(n,t)&&(i?(0,Tv.validateAdditionalItems)(e,i):e.ok((0,Cv.validateArray)(e)))}};Is.default=Lv});var dp=R(bs=>{"use strict";Object.defineProperty(bs,"__esModule",{value:!0});var Ye=x(),Fi=U(),Vv={message:({params:{min:e,max:t}})=>t===void 0?(0,Ye.str)`must contain at least ${e} valid item(s)`:(0,Ye.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,Ye._)`{minContains: ${e}}`:(0,Ye._)`{minContains: ${e}, maxContains: ${t}}`},Mv={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Vv,code(e){let{gen:t,schema:r,parentSchema:n,data:i,it:a}=e,o,s,{minContains:c,maxContains:d}=n;a.opts.next?(o=c===void 0?1:c,s=d):o=1;let l=t.const("len",(0,Ye._)`${i}.length`);if(e.setParams({min:o,max:s}),s===void 0&&o===0){(0,Fi.checkStrictMode)(a,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(s!==void 0&&o>s){(0,Fi.checkStrictMode)(a,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Fi.alwaysValidSchema)(a,r)){let g=(0,Ye._)`${l} >= ${o}`;s!==void 0&&(g=(0,Ye._)`${g} && ${l} <= ${s}`),e.pass(g);return}a.items=!0;let p=t.name("valid");s===void 0&&o===1?u(p,()=>t.if(p,()=>t.break())):o===0?(t.let(p,!0),s!==void 0&&t.if((0,Ye._)`${i}.length > 0`,m)):(t.let(p,!1),m()),e.result(p,()=>e.reset());function m(){let g=t.name("_valid"),h=t.let("count",0);u(g,()=>t.if(g,()=>f(h)))}function u(g,h){t.forRange("i",0,l,w=>{e.subschema({keyword:"contains",dataProp:w,dataPropType:Fi.Type.Num,compositeRule:!0},g),h()})}function f(g){t.code((0,Ye._)`${g}++`),s===void 0?t.if((0,Ye._)`${g} >= ${o}`,()=>t.assign(p,!0).break()):(t.if((0,Ye._)`${g} > ${s}`,()=>t.assign(p,!1).break()),o===1?t.assign(p,!0):t.if((0,Ye._)`${g} >= ${o}`,()=>t.assign(p,!0)))}}};bs.default=Mv});var zi=R(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.validateSchemaDeps=gt.validatePropertyDeps=gt.error=void 0;var ks=x(),qv=U(),Dn=We();gt.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,ks.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,ks._)`{property: ${e},
|
|
6
6
|
missingProperty: ${n},
|
|
7
7
|
depsCount: ${t},
|
|
8
|
-
deps: ${r}}`};var Uv={keyword:"dependencies",type:"object",schemaType:"object",error:gt.error,code(e){let[t,r]=Fv(e);dp(e,t),pp(e,r)}};function Fv({schema:e}){let t={},r={};for(let n in e){if(n==="__proto__")continue;let i=Array.isArray(e[n])?t:r;i[n]=e[n]}return[t,r]}function dp(e,t=e.schema){let{gen:r,data:n,it:i}=e;if(Object.keys(t).length===0)return;let a=r.let("missing");for(let o in t){let s=t[o];if(s.length===0)continue;let c=(0,Dn.propertyInData)(r,n,o,i.opts.ownProperties);e.setParams({property:o,depsCount:s.length,deps:s.join(", ")}),i.allErrors?r.if(c,()=>{for(let d of s)(0,Dn.checkReportMissingProp)(e,d)}):(r.if((0,ks._)`${c} && (${(0,Dn.checkMissingProp)(e,s,a)})`),(0,Dn.reportMissingProp)(e,a),r.else())}}gt.validatePropertyDeps=dp;function pp(e,t=e.schema){let{gen:r,data:n,keyword:i,it:a}=e,o=r.name("valid");for(let s in t)(0,qv.alwaysValidSchema)(a,t[s])||(r.if((0,Dn.propertyInData)(r,n,s,a.opts.ownProperties),()=>{let c=e.subschema({keyword:i,schemaProp:s},o);e.mergeValidEvaluated(c,o)},()=>r.var(o,!0)),e.ok(o))}gt.validateSchemaDeps=pp;gt.default=Uv});var fp=R(_s=>{"use strict";Object.defineProperty(_s,"__esModule",{value:!0});var up=x(),zv=U(),Bv={message:"property name must be valid",params:({params:e})=>(0,up._)`{propertyName: ${e.propertyName}}`},Jv={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Bv,code(e){let{gen:t,schema:r,data:n,it:i}=e;if((0,zv.alwaysValidSchema)(i,r))return;let a=t.name("valid");t.forIn("key",n,o=>{e.setParams({propertyName:o}),e.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},a),t.if((0,up.not)(a),()=>{e.error(!0),i.allErrors||t.break()})}),e.ok(a)}};_s.default=Jv});var As=R(Es=>{"use strict";Object.defineProperty(Es,"__esModule",{value:!0});var Bi=We(),at=x(),Gv=Ge(),Ji=U(),Wv={message:"must NOT have additional properties",params:({params:e})=>(0,at._)`{additionalProperty: ${e.additionalProperty}}`},Kv={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Wv,code(e){let{gen:t,schema:r,parentSchema:n,data:i,errsCount:a,it:o}=e;if(!a)throw new Error("ajv implementation error");let{allErrors:s,opts:c}=o;if(o.props=!0,c.removeAdditional!=="all"&&(0,Ji.alwaysValidSchema)(o,r))return;let d=(0,Bi.allSchemaProperties)(n.properties),l=(0,Bi.allSchemaProperties)(n.patternProperties);p(),e.ok((0,at._)`${a} === ${Gv.default.errors}`);function p(){t.forIn("key",i,h=>{!d.length&&!l.length?f(h):t.if(m(h),()=>f(h))})}function m(h){let w;if(d.length>8){let _=(0,Ji.schemaRefOrVal)(o,n.properties,"properties");w=(0,Bi.isOwnProperty)(t,_,h)}else d.length?w=(0,at.or)(...d.map(_=>(0,at._)`${h} === ${_}`)):w=at.nil;return l.length&&(w=(0,at.or)(w,...l.map(_=>(0,at._)`${(0,Bi.usePattern)(e,_)}.test(${h})`))),(0,at.not)(w)}function u(h){t.code((0,at._)`delete ${i}[${h}]`)}function f(h){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){u(h);return}if(r===!1){e.setParams({additionalProperty:h}),e.error(),s||t.break();return}if(typeof r=="object"&&!(0,Ji.alwaysValidSchema)(o,r)){let w=t.name("valid");c.removeAdditional==="failing"?(g(h,w,!1),t.if((0,at.not)(w),()=>{e.reset(),u(h)})):(g(h,w),s||t.if((0,at.not)(w),()=>t.break()))}}function g(h,w,_){let b={keyword:"additionalProperties",dataProp:h,dataPropType:Ji.Type.Str};_===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(b,w)}}};Es.default=Kv});var hp=R(Ps=>{"use strict";Object.defineProperty(Ps,"__esModule",{value:!0});var Yv=mn(),mp=We(),Rs=U(),gp=As(),Hv={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:i,it:a}=e;a.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&gp.default.code(new Yv.KeywordCxt(a,gp.default,"additionalProperties"));let o=(0,mp.allSchemaProperties)(r);for(let p of o)a.definedProperties.add(p);a.opts.unevaluated&&o.length&&a.props!==!0&&(a.props=Rs.mergeEvaluated.props(t,(0,Rs.toHash)(o),a.props));let s=o.filter(p=>!(0,Rs.alwaysValidSchema)(a,r[p]));if(s.length===0)return;let c=t.name("valid");for(let p of s)d(p)?l(p):(t.if((0,mp.propertyInData)(t,i,p,a.opts.ownProperties)),l(p),a.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(p),e.ok(c);function d(p){return a.opts.useDefaults&&!a.compositeRule&&r[p].default!==void 0}function l(p){e.subschema({keyword:"properties",schemaProp:p,dataProp:p},c)}}};Ps.default=Hv});var Ip=R(Ns=>{"use strict";Object.defineProperty(Ns,"__esModule",{value:!0});var yp=We(),Gi=x(),wp=U(),vp=U(),Zv={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:n,parentSchema:i,it:a}=e,{opts:o}=a,s=(0,yp.allSchemaProperties)(r),c=s.filter(g=>(0,wp.alwaysValidSchema)(a,r[g]));if(s.length===0||c.length===s.length&&(!a.opts.unevaluated||a.props===!0))return;let d=o.strictSchema&&!o.allowMatchingProperties&&i.properties,l=t.name("valid");a.props!==!0&&!(a.props instanceof Gi.Name)&&(a.props=(0,vp.evaluatedPropsToName)(t,a.props));let{props:p}=a;m();function m(){for(let g of s)d&&u(g),a.allErrors?f(g):(t.var(l,!0),f(g),t.if(l))}function u(g){for(let h in d)new RegExp(g).test(h)&&(0,wp.checkStrictMode)(a,`property ${h} matches pattern ${g} (use allowMatchingProperties)`)}function f(g){t.forIn("key",n,h=>{t.if((0,Gi._)`${(0,yp.usePattern)(e,g)}.test(${h})`,()=>{let w=c.includes(g);w||e.subschema({keyword:"patternProperties",schemaProp:g,dataProp:h,dataPropType:vp.Type.Str},l),a.opts.unevaluated&&p!==!0?t.assign((0,Gi._)`${p}[${h}]`,!0):!w&&!a.allErrors&&t.if((0,Gi.not)(l),()=>t.break())})})}}};Ns.default=Zv});var bp=R(Ds=>{"use strict";Object.defineProperty(Ds,"__esModule",{value:!0});var Xv=U(),Qv={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,Xv.alwaysValidSchema)(n,r)){e.fail();return}let i=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),e.failResult(i,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};Ds.default=Qv});var kp=R(Ss=>{"use strict";Object.defineProperty(Ss,"__esModule",{value:!0});var eI=We(),tI={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:eI.validateUnion,error:{message:"must match a schema in anyOf"}};Ss.default=tI});var _p=R(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});var Wi=x(),rI=U(),nI={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,Wi._)`{passingSchemas: ${e.passing}}`},iI={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:nI,code(e){let{gen:t,schema:r,parentSchema:n,it:i}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(i.opts.discriminator&&n.discriminator)return;let a=r,o=t.let("valid",!1),s=t.let("passing",null),c=t.name("_valid");e.setParams({passing:s}),t.block(d),e.result(o,()=>e.reset(),()=>e.error(!0));function d(){a.forEach((l,p)=>{let m;(0,rI.alwaysValidSchema)(i,l)?t.var(c,!0):m=e.subschema({keyword:"oneOf",schemaProp:p,compositeRule:!0},c),p>0&&t.if((0,Wi._)`${c} && ${o}`).assign(o,!1).assign(s,(0,Wi._)`[${s}, ${p}]`).else(),t.if(c,()=>{t.assign(o,!0),t.assign(s,p),m&&e.mergeEvaluated(m,Wi.Name)})})}}};js.default=iI});var Ep=R($s=>{"use strict";Object.defineProperty($s,"__esModule",{value:!0});var aI=U(),oI={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:r,it:n}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");let i=t.name("valid");r.forEach((a,o)=>{if((0,aI.alwaysValidSchema)(n,a))return;let s=e.subschema({keyword:"allOf",schemaProp:o},i);e.ok(i),e.mergeEvaluated(s)})}};$s.default=oI});var Pp=R(Os=>{"use strict";Object.defineProperty(Os,"__esModule",{value:!0});var Ki=x(),Rp=U(),sI={message:({params:e})=>(0,Ki.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,Ki._)`{failingKeyword: ${e.ifClause}}`},cI={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:sI,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,Rp.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=Ap(n,"then"),a=Ap(n,"else");if(!i&&!a)return;let o=t.let("valid",!0),s=t.name("_valid");if(c(),e.reset(),i&&a){let l=t.let("ifClause");e.setParams({ifClause:l}),t.if(s,d("then",l),d("else",l))}else i?t.if(s,d("then")):t.if((0,Ki.not)(s),d("else"));e.pass(o,()=>e.error(!0));function c(){let l=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},s);e.mergeEvaluated(l)}function d(l,p){return()=>{let m=e.subschema({keyword:l},s);t.assign(o,s),e.mergeValidEvaluated(m,o),p?t.assign(p,(0,Ki._)`${l}`):e.setParams({ifClause:l})}}}};function Ap(e,t){let r=e.schema[t];return r!==void 0&&!(0,Rp.alwaysValidSchema)(e,r)}Os.default=cI});var Np=R(Cs=>{"use strict";Object.defineProperty(Cs,"__esModule",{value:!0});var lI=U(),dI={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,lI.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Cs.default=dI});var Dp=R(Ts=>{"use strict";Object.defineProperty(Ts,"__esModule",{value:!0});var pI=ys(),uI=op(),fI=ws(),mI=cp(),gI=lp(),hI=zi(),yI=fp(),wI=As(),vI=hp(),II=Ip(),bI=bp(),kI=kp(),_I=_p(),EI=Ep(),AI=Pp(),RI=Np();function PI(e=!1){let t=[bI.default,kI.default,_I.default,EI.default,AI.default,RI.default,yI.default,wI.default,hI.default,vI.default,II.default];return e?t.push(uI.default,mI.default):t.push(pI.default,fI.default),t.push(gI.default),t}Ts.default=PI});var Ls=R(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.dynamicAnchor=void 0;var xs=x(),NI=Ge(),Sp=hn(),DI=Li(),SI={keyword:"$dynamicAnchor",schemaType:"string",code:e=>jp(e,e.schema)};function jp(e,t){let{gen:r,it:n}=e;n.schemaEnv.root.dynamicAnchors[t]=!0;let i=(0,xs._)`${NI.default.dynamicAnchors}${(0,xs.getProperty)(t)}`,a=n.errSchemaPath==="#"?n.validateName:jI(e);r.if((0,xs._)`!${i}`,()=>r.assign(i,a))}Sn.dynamicAnchor=jp;function jI(e){let{schemaEnv:t,schema:r,self:n}=e.it,{root:i,baseId:a,localRefs:o,meta:s}=t.root,{schemaId:c}=n.opts,d=new Sp.SchemaEnv({schema:r,schemaId:c,root:i,baseId:a,localRefs:o,meta:s});return Sp.compileSchema.call(n,d),(0,DI.getValidate)(e,d)}Sn.default=SI});var Vs=R(jn=>{"use strict";Object.defineProperty(jn,"__esModule",{value:!0});jn.dynamicRef=void 0;var $p=x(),$I=Ge(),Op=Li(),OI={keyword:"$dynamicRef",schemaType:"string",code:e=>Cp(e,e.schema)};function Cp(e,t){let{gen:r,keyword:n,it:i}=e;if(t[0]!=="#")throw new Error(`"${n}" only supports hash fragment reference`);let a=t.slice(1);if(i.allErrors)o();else{let c=r.let("valid",!1);o(c),e.ok(c)}function o(c){if(i.schemaEnv.root.dynamicAnchors[a]){let d=r.let("_v",(0,$p._)`${$I.default.dynamicAnchors}${(0,$p.getProperty)(a)}`);r.if(d,s(d,c),s(i.validateName,c))}else s(i.validateName,c)()}function s(c,d){return d?()=>r.block(()=>{(0,Op.callRef)(e,c),r.let(d,!0)}):()=>(0,Op.callRef)(e,c)}}jn.dynamicRef=Cp;jn.default=OI});var Tp=R(Ms=>{"use strict";Object.defineProperty(Ms,"__esModule",{value:!0});var CI=Ls(),TI=U(),xI={keyword:"$recursiveAnchor",schemaType:"boolean",code(e){e.schema?(0,CI.dynamicAnchor)(e,""):(0,TI.checkStrictMode)(e.it,"$recursiveAnchor: false is ignored")}};Ms.default=xI});var xp=R(qs=>{"use strict";Object.defineProperty(qs,"__esModule",{value:!0});var LI=Vs(),VI={keyword:"$recursiveRef",schemaType:"string",code:e=>(0,LI.dynamicRef)(e,e.schema)};qs.default=VI});var Lp=R(Us=>{"use strict";Object.defineProperty(Us,"__esModule",{value:!0});var MI=Ls(),qI=Vs(),UI=Tp(),FI=xp(),zI=[MI.default,qI.default,UI.default,FI.default];Us.default=zI});var Mp=R(Fs=>{"use strict";Object.defineProperty(Fs,"__esModule",{value:!0});var Vp=zi(),BI={keyword:"dependentRequired",type:"object",schemaType:"object",error:Vp.error,code:e=>(0,Vp.validatePropertyDeps)(e)};Fs.default=BI});var qp=R(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});var JI=zi(),GI={keyword:"dependentSchemas",type:"object",schemaType:"object",code:e=>(0,JI.validateSchemaDeps)(e)};zs.default=GI});var Up=R(Bs=>{"use strict";Object.defineProperty(Bs,"__esModule",{value:!0});var WI=U(),KI={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:e,parentSchema:t,it:r}){t.contains===void 0&&(0,WI.checkStrictMode)(r,`"${e}" without "contains" is ignored`)}};Bs.default=KI});var Fp=R(Js=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});var YI=Mp(),HI=qp(),ZI=Up(),XI=[YI.default,HI.default,ZI.default];Js.default=XI});var Bp=R(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});var Tt=x(),zp=U(),QI=Ge(),eb={message:"must NOT have unevaluated properties",params:({params:e})=>(0,Tt._)`{unevaluatedProperty: ${e.unevaluatedProperty}}`},tb={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:eb,code(e){let{gen:t,schema:r,data:n,errsCount:i,it:a}=e;if(!i)throw new Error("ajv implementation error");let{allErrors:o,props:s}=a;s instanceof Tt.Name?t.if((0,Tt._)`${s} !== true`,()=>t.forIn("key",n,p=>t.if(d(s,p),()=>c(p)))):s!==!0&&t.forIn("key",n,p=>s===void 0?c(p):t.if(l(s,p),()=>c(p))),a.props=!0,e.ok((0,Tt._)`${i} === ${QI.default.errors}`);function c(p){if(r===!1){e.setParams({unevaluatedProperty:p}),e.error(),o||t.break();return}if(!(0,zp.alwaysValidSchema)(a,r)){let m=t.name("valid");e.subschema({keyword:"unevaluatedProperties",dataProp:p,dataPropType:zp.Type.Str},m),o||t.if((0,Tt.not)(m),()=>t.break())}}function d(p,m){return(0,Tt._)`!${p} || !${p}[${m}]`}function l(p,m){let u=[];for(let f in p)p[f]===!0&&u.push((0,Tt._)`${m} !== ${f}`);return(0,Tt.and)(...u)}}};Gs.default=tb});var Gp=R(Ws=>{"use strict";Object.defineProperty(Ws,"__esModule",{value:!0});var rr=x(),Jp=U(),rb={message:({params:{len:e}})=>(0,rr.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,rr._)`{limit: ${e}}`},nb={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:rb,code(e){let{gen:t,schema:r,data:n,it:i}=e,a=i.items||0;if(a===!0)return;let o=t.const("len",(0,rr._)`${n}.length`);if(r===!1)e.setParams({len:a}),e.fail((0,rr._)`${o} > ${a}`);else if(typeof r=="object"&&!(0,Jp.alwaysValidSchema)(i,r)){let c=t.var("valid",(0,rr._)`${o} <= ${a}`);t.if((0,rr.not)(c),()=>s(c,a)),e.ok(c)}i.items=!0;function s(c,d){t.forRange("i",d,o,l=>{e.subschema({keyword:"unevaluatedItems",dataProp:l,dataPropType:Jp.Type.Num},c),i.allErrors||t.if((0,rr.not)(c),()=>t.break())})}}};Ws.default=nb});var Wp=R(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});var ib=Bp(),ab=Gp(),ob=[ib.default,ab.default];Ks.default=ob});var Kp=R(Ys=>{"use strict";Object.defineProperty(Ys,"__esModule",{value:!0});var fe=x(),sb={message:({schemaCode:e})=>(0,fe.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,fe._)`{format: ${e}}`},cb={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:sb,code(e,t){let{gen:r,data:n,$data:i,schema:a,schemaCode:o,it:s}=e,{opts:c,errSchemaPath:d,schemaEnv:l,self:p}=s;if(!c.validateFormats)return;i?m():u();function m(){let f=r.scopeValue("formats",{ref:p.formats,code:c.code.formats}),g=r.const("fDef",(0,fe._)`${f}[${o}]`),h=r.let("fType"),w=r.let("format");r.if((0,fe._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(h,(0,fe._)`${g}.type || "string"`).assign(w,(0,fe._)`${g}.validate`),()=>r.assign(h,(0,fe._)`"string"`).assign(w,g)),e.fail$data((0,fe.or)(_(),b()));function _(){return c.strictSchema===!1?fe.nil:(0,fe._)`${o} && !${w}`}function b(){let A=l.$async?(0,fe._)`(${g}.async ? await ${w}(${n}) : ${w}(${n}))`:(0,fe._)`${w}(${n})`,y=(0,fe._)`(typeof ${w} == "function" ? ${A} : ${w}.test(${n}))`;return(0,fe._)`${w} && ${w} !== true && ${h} === ${t} && !${y}`}}function u(){let f=p.formats[a];if(!f){_();return}if(f===!0)return;let[g,h,w]=b(f);g===t&&e.pass(A());function _(){if(c.strictSchema===!1){p.logger.warn(y());return}throw new Error(y());function y(){return`unknown format "${a}" ignored in schema at path "${d}"`}}function b(y){let k=y instanceof RegExp?(0,fe.regexpCode)(y):c.code.formats?(0,fe._)`${c.code.formats}${(0,fe.getProperty)(a)}`:void 0,S=r.scopeValue("formats",{key:a,ref:y,code:k});return typeof y=="object"&&!(y instanceof RegExp)?[y.type||"string",y.validate,(0,fe._)`${S}.validate`]:["string",y,S]}function A(){if(typeof f=="object"&&!(f instanceof RegExp)&&f.async){if(!l.$async)throw new Error("async format in sync schema");return(0,fe._)`await ${w}(${n})`}return typeof h=="function"?(0,fe._)`${w}(${n})`:(0,fe._)`${w}.test(${n})`}}}};Ys.default=cb});var Yp=R(Hs=>{"use strict";Object.defineProperty(Hs,"__esModule",{value:!0});var lb=Kp(),db=[lb.default];Hs.default=db});var Hp=R(Or=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});Or.contentVocabulary=Or.metadataVocabulary=void 0;Or.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Or.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Xp=R(Zs=>{"use strict";Object.defineProperty(Zs,"__esModule",{value:!0});var pb=Fd(),ub=rp(),fb=Dp(),mb=Lp(),gb=Fp(),hb=Wp(),yb=Yp(),Zp=Hp(),wb=[mb.default,pb.default,ub.default,(0,fb.default)(!0),yb.default,Zp.metadataVocabulary,Zp.contentVocabulary,gb.default,hb.default];Zs.default=wb});var eu=R(Yi=>{"use strict";Object.defineProperty(Yi,"__esModule",{value:!0});Yi.DiscrError=void 0;var Qp;(function(e){e.Tag="tag",e.Mapping="mapping"})(Qp||(Yi.DiscrError=Qp={}))});var ru=R(Qs=>{"use strict";Object.defineProperty(Qs,"__esModule",{value:!0});var Cr=x(),Xs=eu(),tu=hn(),vb=gn(),Ib=U(),bb={message:({params:{discrError:e,tagName:t}})=>e===Xs.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>(0,Cr._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`},kb={keyword:"discriminator",type:"object",schemaType:"object",error:bb,code(e){let{gen:t,data:r,schema:n,parentSchema:i,it:a}=e,{oneOf:o}=i;if(!a.opts.discriminator)throw new Error("discriminator: requires discriminator option");let s=n.propertyName;if(typeof s!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!o)throw new Error("discriminator: requires oneOf keyword");let c=t.let("valid",!1),d=t.const("tag",(0,Cr._)`${r}${(0,Cr.getProperty)(s)}`);t.if((0,Cr._)`typeof ${d} == "string"`,()=>l(),()=>e.error(!1,{discrError:Xs.DiscrError.Tag,tag:d,tagName:s})),e.ok(c);function l(){let u=m();t.if(!1);for(let f in u)t.elseIf((0,Cr._)`${d} === ${f}`),t.assign(c,p(u[f]));t.else(),e.error(!1,{discrError:Xs.DiscrError.Mapping,tag:d,tagName:s}),t.endIf()}function p(u){let f=t.name("valid"),g=e.subschema({keyword:"oneOf",schemaProp:u},f);return e.mergeEvaluated(g,Cr.Name),f}function m(){var u;let f={},g=w(i),h=!0;for(let A=0;A<o.length;A++){let y=o[A];if(y?.$ref&&!(0,Ib.schemaHasRulesButRef)(y,a.self.RULES)){let S=y.$ref;if(y=tu.resolveRef.call(a.self,a.schemaEnv.root,a.baseId,S),y instanceof tu.SchemaEnv&&(y=y.schema),y===void 0)throw new vb.default(a.opts.uriResolver,a.baseId,S)}let k=(u=y?.properties)===null||u===void 0?void 0:u[s];if(typeof k!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${s}"`);h=h&&(g||w(y)),_(k,A)}if(!h)throw new Error(`discriminator: "${s}" must be required`);return f;function w({required:A}){return Array.isArray(A)&&A.includes(s)}function _(A,y){if(A.const)b(A.const,y);else if(A.enum)for(let k of A.enum)b(k,y);else throw new Error(`discriminator: "properties/${s}" must have "const" or "enum"`)}function b(A,y){if(typeof A!="string"||A in f)throw new Error(`discriminator: "${s}" values must be unique strings`);f[A]=y}}}};Qs.default=kb});var nu=R((fP,_b)=>{_b.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}}});var iu=R((mP,Eb)=>{Eb.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}});var au=R((gP,Ab)=>{Ab.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}});var ou=R((hP,Rb)=>{Rb.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}});var su=R((yP,Pb)=>{Pb.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}});var cu=R((wP,Nb)=>{Nb.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}});var lu=R((vP,Db)=>{Db.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}});var du=R((IP,Sb)=>{Sb.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}});var pu=R(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});var jb=nu(),$b=iu(),Ob=au(),Cb=ou(),Tb=su(),xb=cu(),Lb=lu(),Vb=du(),Mb=["/properties"];function qb(e){return[jb,$b,Ob,Cb,Tb,t(this,xb),Lb,t(this,Vb)].forEach(r=>this.addMetaSchema(r,void 0,!1)),this;function t(r,n){return e?r.$dataMetaSchema(n,Mb):n}}ec.default=qb});var nr=R((le,rc)=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.MissingRefError=le.ValidationError=le.CodeGen=le.Name=le.nil=le.stringify=le.str=le._=le.KeywordCxt=le.Ajv2020=void 0;var Ub=Ld(),Fb=Xp(),zb=ru(),Bb=pu(),tc="https://json-schema.org/draft/2020-12/schema",Tr=class extends Ub.default{constructor(t={}){super({...t,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),Fb.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(zb.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:t,meta:r}=this.opts;r&&(Bb.default.call(this,t),this.refs["http://json-schema.org/schema"]=tc)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(tc)?tc:void 0)}};le.Ajv2020=Tr;rc.exports=le=Tr;rc.exports.Ajv2020=Tr;Object.defineProperty(le,"__esModule",{value:!0});le.default=Tr;var Jb=mn();Object.defineProperty(le,"KeywordCxt",{enumerable:!0,get:function(){return Jb.KeywordCxt}});var xr=x();Object.defineProperty(le,"_",{enumerable:!0,get:function(){return xr._}});Object.defineProperty(le,"str",{enumerable:!0,get:function(){return xr.str}});Object.defineProperty(le,"stringify",{enumerable:!0,get:function(){return xr.stringify}});Object.defineProperty(le,"nil",{enumerable:!0,get:function(){return xr.nil}});Object.defineProperty(le,"Name",{enumerable:!0,get:function(){return xr.Name}});Object.defineProperty(le,"CodeGen",{enumerable:!0,get:function(){return xr.CodeGen}});var Gb=Pi();Object.defineProperty(le,"ValidationError",{enumerable:!0,get:function(){return Gb.default}});var Wb=gn();Object.defineProperty(le,"MissingRefError",{enumerable:!0,get:function(){return Wb.default}})});import{readFile as te,readdir as Wm,realpath as pt}from"node:fs/promises";import{execFile as dA,spawn as pA}from"node:child_process";import N from"node:path";import{parseArgs as oe,promisify as uA}from"node:util";var X="^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$",ut="^sha256:[a-f0-9]{64}$";import{constants as ma}from"node:fs";import{lstat as Ek,mkdir as Wr,open as Pu,readFile as Mn,realpath as dr,rename as Ak,unlink as wc}from"node:fs/promises";import{randomUUID as vc}from"node:crypto";import ye from"node:path";var uu=br(nr(),1);var ke={type:"string",pattern:ut},Kb={type:"string",pattern:"^[a-z][a-z0-9.-]{2,127}$"},nc={type:"string",format:"date-time"},ic={enum:["typescript.typecheck","vitest.run","typescript.build","npm.pack-dry-run","workspace.structure","capability.assets","node.application-smoke","web.application-build","web.application-smoke","expo.application-config","expo.application-export","react.library-build","next.application-test","next.application-build","next.application-package","next.application-smoke","application.config-contract"]},fu={type:"object",additionalProperties:!1,required:["node","pnpm","typescript"],properties:{node:{type:"string",minLength:1,maxLength:64},pnpm:{type:"string",minLength:1,maxLength:64},typescript:{type:"string",minLength:1,maxLength:64}}},ac={$id:"https://schemas.dyyto.dev/platform/capability-bundle-release-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","capabilityId","version","integrity","consumerProfile","compatibility","assets","verifiers","exit"],properties:{schemaVersion:{const:1},capabilityId:{type:"string",pattern:X},version:{type:"string",minLength:1,maxLength:128},integrity:ke,consumerProfile:{enum:["blank-typescript-library","standalone-npm-package","react-component-library","nextjs-full-stack-application","workspace-root","workspace-npm-package","workspace-node-application","workspace-web-application","workspace-expo-application","any-project"]},kind:{enum:["profile","engineering-feature","integration-feature","domain-extension"]},dependencies:{type:"object",additionalProperties:!1,required:["profiles"],properties:{profiles:{type:"array",minItems:1,uniqueItems:!0,items:{type:"string",minLength:1,maxLength:128}},capabilities:{type:"array",minItems:1,uniqueItems:!0,items:{type:"string",pattern:X}}}},compatibility:fu,integration:{type:"object",additionalProperties:!1,required:["title","purpose","packages","codeAssets"],properties:{title:{type:"string",minLength:1,maxLength:128},purpose:{type:"string",minLength:1,maxLength:512},packages:{type:"array",items:{type:"object",additionalProperties:!1,required:["packageName","version","usage","imports"],properties:{packageName:{type:"string",minLength:1,maxLength:214},version:{type:"string",minLength:1,maxLength:128},usage:{enum:["runtime","development","build","test"]},imports:{type:"array",items:{type:"object",additionalProperties:!1,required:["importFrom","symbol"],properties:{importFrom:{type:"string",minLength:1,maxLength:214},symbol:{type:"string",minLength:1,maxLength:128},referencePath:{type:"string",minLength:1,maxLength:512}}}}}}},codeAssets:{type:"array",items:{type:"object",additionalProperties:!1,required:["sourcePath","targetPath","ownership"],properties:{sourcePath:{type:"string",minLength:1,maxLength:512},targetPath:{type:"string",minLength:1,maxLength:512},ownership:{enum:["owned-file","managed-region","seed-file"]}}}}}},assets:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["path","ownership","digest","mode"],properties:{path:{type:"string",minLength:1,maxLength:512},ownership:{enum:["owned-file","managed-region","seed-file"]},digest:ke,mode:{type:"integer",minimum:0,maximum:511},regionId:{type:"string",pattern:X},renderer:{enum:["npm-package-json-v1","npm-package-json-v2","react-component-package-json-v1","nextjs-application-package-json-v1","workspace-root-package-json-v1","node-application-package-json-v1","web-application-package-json-v1","expo-application-package-json-v1","application-config-contract-v1","application-config-binding-v1"]}},allOf:[{if:{properties:{ownership:{const:"managed-region"}},required:["ownership"]},then:{properties:{regionId:{type:"string",pattern:X}},required:["regionId"]},else:{not:{required:["regionId"]}}}]}},verifiers:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["id"],properties:{id:ic}}},exit:{type:"object",additionalProperties:!1,required:["ownedAssets"],properties:{ownedAssets:{type:"array",items:{type:"string",minLength:1,maxLength:512}}}}}},mu={type:"object",additionalProperties:!1,required:["registryId","packageName","version","integrity","tarballDigest","deliveryReceiptId","usage"],properties:{registryId:{type:"string",pattern:"^registry\\.[a-z0-9][a-z0-9.-]{1,126}$"},packageName:{type:"string",pattern:"^@[a-z0-9][a-z0-9._-]*/[a-z0-9][a-z0-9._-]*$",maxLength:214},version:{type:"string",pattern:"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)$",maxLength:64},integrity:{type:"string",pattern:"^sha512-[A-Za-z0-9+/]{86}==$"},tarballDigest:ke,deliveryReceiptId:ke,usage:{enum:["runtime","development"]}}},{$id:_P,...gu}=ac,Yb={...gu,$id:"https://schemas.dyyto.dev/platform/capability-bundle-release-v2.json",required:[...ac.required,"availability","packageSources"],properties:{...ac.properties,schemaVersion:{const:2},availability:{oneOf:[{type:"object",additionalProperties:!1,required:["maturity","visibility","sourceState"],properties:{maturity:{const:"candidate"},visibility:{const:"maintainers-only"},sourceState:{const:"local-artifact"}}},{type:"object",additionalProperties:!1,required:["maturity","visibility","sourceState"],properties:{maturity:{const:"candidate"},visibility:{const:"maintainers-only"},sourceState:{const:"development-registry"}}},{type:"object",additionalProperties:!1,required:["maturity","visibility","sourceState"],properties:{maturity:{const:"available"},visibility:{const:"catalog-consumers"},sourceState:{const:"registry-verified"}}},{type:"object",additionalProperties:!1,required:["maturity","visibility","reasonCode"],properties:{maturity:{const:"withdrawn"},visibility:{const:"existing-locks-only"},reasonCode:{type:"string",pattern:"^[A-Z][A-Z0-9_]{2,63}$"}}}]},packageSources:{type:"array",maxItems:128,items:mu}}},Hb={$id:"https://schemas.dyyto.dev/platform/capability-bundle-release.json",oneOf:[gu,(()=>{let{$id:e,...t}=Yb;return t})()]},Hi={$id:"https://schemas.dyyto.dev/platform/verification-result-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","verifierId","result","issuer","commandId","exitCode","stdoutDigest","stderrDigest","startedAt","completedAt","projectStateDigest","runtime"],properties:{schemaVersion:{const:1},verifierId:ic,result:{enum:["passed","failed"]},issuer:{enum:["dyyto-cli","test-harness","external-ci"]},commandId:ic,exitCode:{type:"integer",minimum:0,maximum:255},stdoutDigest:ke,stderrDigest:ke,startedAt:nc,completedAt:nc,projectStateDigest:ke,runtime:fu}},Zb={...Hi,$id:"https://schemas.dyyto.dev/platform/adoption-evidence-v1.json",required:[...Hi.required,"evidenceId","capabilityId","capabilityVersion","capabilityIntegrity"],properties:{...Hi.properties,evidenceId:ke,capabilityId:{type:"string",pattern:X},capabilityVersion:{type:"string",minLength:1,maxLength:128},capabilityIntegrity:ke}},Xb={$id:"https://schemas.dyyto.dev/platform/project-adoption-lock.json",type:"object",additionalProperties:!1,required:["schemaVersion","capabilities"],properties:{schemaVersion:{enum:[1,2]},capabilities:{type:"array",items:{type:"object",additionalProperties:!1,required:["capabilityId","version","integrity","consumerProfile","appliedPlanId","projectStateDigest","assets","evidenceIds","committedAt"],properties:{capabilityId:{type:"string",pattern:X},version:{type:"string",minLength:1,maxLength:128},integrity:ke,consumerProfile:{type:"string",minLength:1,maxLength:128},appliedPlanId:ke,projectStateDigest:ke,assets:{type:"array",items:{type:"object",additionalProperties:!1,required:["path","digest"],properties:{path:{type:"string",minLength:1,maxLength:512},digest:ke,ownership:{enum:["owned-file","managed-region","seed-file"]},regionId:{type:"string",pattern:X}},allOf:[{if:{properties:{ownership:{const:"managed-region"}},required:["ownership"]},then:{properties:{regionId:{type:"string",pattern:X}},required:["regionId"]}}]}},evidenceIds:{type:"array",items:ke},committedAt:nc,packageAdoption:{type:"object",additionalProperties:!1,required:["registryRevisions","sources","packageJsonDigest","lockfileDigest"],properties:{sourceChannel:{enum:["production","development"]},registryRevisions:{type:"array",items:{type:"object",additionalProperties:!1,required:["registryId","revision"],properties:{registryId:Kb,revision:ke}}},sources:{type:"array",minItems:1,maxItems:128,items:mu},packageJsonDigest:ke,lockfileDigest:ke}}}}}},allOf:[{if:{properties:{schemaVersion:{const:1}},required:["schemaVersion"]},then:{properties:{capabilities:{type:"array",items:{type:"object",not:{type:"object",properties:{packageAdoption:{}},required:["packageAdoption"]}}}}}}]},$n=new uu.Ajv2020({allErrors:!0,strict:!0});$n.addFormat("date-time",{type:"string",validate:e=>!Number.isNaN(Date.parse(e))});var Xi={capabilityBundleRelease:$n.compile(Hb),verificationResult:$n.compile(Hi),adoptionEvidence:$n.compile(Zb),projectAdoptionLock:$n.compile(Xb)},Zi=class extends Error{contract;issues;code="ADOPTION_CONTRACT_INVALID";constructor(t,r){super(`Invalid ${t} contract`),this.contract=t,this.issues=r}};function Qi(e,t,r){if(!t(r))throw new Zi(e,t.errors??[]);return r}var hu=e=>{let t=Qi("capabilityBundleRelease",Xi.capabilityBundleRelease,e);if(t.schemaVersion===2){let r=()=>{throw new Zi("capabilityBundleRelease",[])},n=t.packageSources;(t.availability.maturity==="candidate"&&t.availability.sourceState==="local-artifact"&&n.length!==0||t.availability.maturity==="candidate"&&t.availability.sourceState==="development-registry"&&n.length===0||t.availability.maturity!=="candidate"&&n.length===0)&&r();let i="",a=new Set;for(let s of n){let c=`${s.packageName}@${s.version}`;(c.localeCompare(i)<=0||a.has(c))&&r(),i=c,a.add(c)}let o=t.integration?.packages??[];(t.availability.maturity!=="candidate"||t.availability.sourceState==="development-registry")&&(o.length!==n.length||o.some(s=>!n.some(c=>c.packageName===s.packageName&&c.version===s.version&&c.usage===s.usage)))&&r()}return t},yu=e=>Qi("verificationResult",Xi.verificationResult,e),On=e=>Qi("adoptionEvidence",Xi.adoptionEvidence,e),Te=e=>Qi("projectAdoptionLock",Xi.projectAdoptionLock,e);import{lstat as sk,readFile as lc,realpath as dc}from"node:fs/promises";import Vr from"node:path";import{createHash as Qb}from"node:crypto";function v(e){return`sha256:${Qb("sha256").update(e).digest("hex")}`}function E(e){return Array.isArray(e)?`[${e.map(E).join(",")}]`:e!==null&&typeof e=="object"?`{${Object.entries(e).filter(([,r])=>r!==void 0).sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>`${JSON.stringify(r)}:${E(n)}`).join(",")}}`:JSON.stringify(e)}var ht=class extends Error{code="MANAGED_REGION_INVALID";constructor(t){super(t)}};function wu(e){if(!new RegExp(X).test(e))throw new ht("Region identity is invalid");return{begin:`<!-- dyyto:begin ${e} -->`,end:`<!-- dyyto:end ${e} -->`}}function ea(e,t){if(e.includes("\r"))throw new ht("Managed regions require LF newlines");let{begin:r,end:n}=wu(t),i=e.split(r).length-1,a=e.split(n).length-1;if(i!==1||a!==1)throw new ht("Managed region markers are unavailable or ambiguous");let o=e.indexOf(r)+r.length,s=e.indexOf(n,o),c=e.slice(o,s);if(/<!-- dyyto:(?:begin|end) /.test(c))throw new ht("Managed regions cannot overlap");return`${c.replace(/^\n+|\n+$/g,"")}
|
|
9
|
-
`}function
|
|
8
|
+
deps: ${r}}`};var Uv={keyword:"dependencies",type:"object",schemaType:"object",error:gt.error,code(e){let[t,r]=Fv(e);pp(e,t),up(e,r)}};function Fv({schema:e}){let t={},r={};for(let n in e){if(n==="__proto__")continue;let i=Array.isArray(e[n])?t:r;i[n]=e[n]}return[t,r]}function pp(e,t=e.schema){let{gen:r,data:n,it:i}=e;if(Object.keys(t).length===0)return;let a=r.let("missing");for(let o in t){let s=t[o];if(s.length===0)continue;let c=(0,Dn.propertyInData)(r,n,o,i.opts.ownProperties);e.setParams({property:o,depsCount:s.length,deps:s.join(", ")}),i.allErrors?r.if(c,()=>{for(let d of s)(0,Dn.checkReportMissingProp)(e,d)}):(r.if((0,ks._)`${c} && (${(0,Dn.checkMissingProp)(e,s,a)})`),(0,Dn.reportMissingProp)(e,a),r.else())}}gt.validatePropertyDeps=pp;function up(e,t=e.schema){let{gen:r,data:n,keyword:i,it:a}=e,o=r.name("valid");for(let s in t)(0,qv.alwaysValidSchema)(a,t[s])||(r.if((0,Dn.propertyInData)(r,n,s,a.opts.ownProperties),()=>{let c=e.subschema({keyword:i,schemaProp:s},o);e.mergeValidEvaluated(c,o)},()=>r.var(o,!0)),e.ok(o))}gt.validateSchemaDeps=up;gt.default=Uv});var mp=R(_s=>{"use strict";Object.defineProperty(_s,"__esModule",{value:!0});var fp=x(),zv=U(),Bv={message:"property name must be valid",params:({params:e})=>(0,fp._)`{propertyName: ${e.propertyName}}`},Gv={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Bv,code(e){let{gen:t,schema:r,data:n,it:i}=e;if((0,zv.alwaysValidSchema)(i,r))return;let a=t.name("valid");t.forIn("key",n,o=>{e.setParams({propertyName:o}),e.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},a),t.if((0,fp.not)(a),()=>{e.error(!0),i.allErrors||t.break()})}),e.ok(a)}};_s.default=Gv});var As=R(Es=>{"use strict";Object.defineProperty(Es,"__esModule",{value:!0});var Bi=We(),at=x(),Jv=Je(),Gi=U(),Wv={message:"must NOT have additional properties",params:({params:e})=>(0,at._)`{additionalProperty: ${e.additionalProperty}}`},Kv={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Wv,code(e){let{gen:t,schema:r,parentSchema:n,data:i,errsCount:a,it:o}=e;if(!a)throw new Error("ajv implementation error");let{allErrors:s,opts:c}=o;if(o.props=!0,c.removeAdditional!=="all"&&(0,Gi.alwaysValidSchema)(o,r))return;let d=(0,Bi.allSchemaProperties)(n.properties),l=(0,Bi.allSchemaProperties)(n.patternProperties);p(),e.ok((0,at._)`${a} === ${Jv.default.errors}`);function p(){t.forIn("key",i,h=>{!d.length&&!l.length?f(h):t.if(m(h),()=>f(h))})}function m(h){let w;if(d.length>8){let _=(0,Gi.schemaRefOrVal)(o,n.properties,"properties");w=(0,Bi.isOwnProperty)(t,_,h)}else d.length?w=(0,at.or)(...d.map(_=>(0,at._)`${h} === ${_}`)):w=at.nil;return l.length&&(w=(0,at.or)(w,...l.map(_=>(0,at._)`${(0,Bi.usePattern)(e,_)}.test(${h})`))),(0,at.not)(w)}function u(h){t.code((0,at._)`delete ${i}[${h}]`)}function f(h){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){u(h);return}if(r===!1){e.setParams({additionalProperty:h}),e.error(),s||t.break();return}if(typeof r=="object"&&!(0,Gi.alwaysValidSchema)(o,r)){let w=t.name("valid");c.removeAdditional==="failing"?(g(h,w,!1),t.if((0,at.not)(w),()=>{e.reset(),u(h)})):(g(h,w),s||t.if((0,at.not)(w),()=>t.break()))}}function g(h,w,_){let b={keyword:"additionalProperties",dataProp:h,dataPropType:Gi.Type.Str};_===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(b,w)}}};Es.default=Kv});var yp=R(Ps=>{"use strict";Object.defineProperty(Ps,"__esModule",{value:!0});var Yv=mn(),gp=We(),Rs=U(),hp=As(),Hv={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:i,it:a}=e;a.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&hp.default.code(new Yv.KeywordCxt(a,hp.default,"additionalProperties"));let o=(0,gp.allSchemaProperties)(r);for(let p of o)a.definedProperties.add(p);a.opts.unevaluated&&o.length&&a.props!==!0&&(a.props=Rs.mergeEvaluated.props(t,(0,Rs.toHash)(o),a.props));let s=o.filter(p=>!(0,Rs.alwaysValidSchema)(a,r[p]));if(s.length===0)return;let c=t.name("valid");for(let p of s)d(p)?l(p):(t.if((0,gp.propertyInData)(t,i,p,a.opts.ownProperties)),l(p),a.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(p),e.ok(c);function d(p){return a.opts.useDefaults&&!a.compositeRule&&r[p].default!==void 0}function l(p){e.subschema({keyword:"properties",schemaProp:p,dataProp:p},c)}}};Ps.default=Hv});var bp=R(Ns=>{"use strict";Object.defineProperty(Ns,"__esModule",{value:!0});var wp=We(),Ji=x(),vp=U(),Ip=U(),Zv={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:n,parentSchema:i,it:a}=e,{opts:o}=a,s=(0,wp.allSchemaProperties)(r),c=s.filter(g=>(0,vp.alwaysValidSchema)(a,r[g]));if(s.length===0||c.length===s.length&&(!a.opts.unevaluated||a.props===!0))return;let d=o.strictSchema&&!o.allowMatchingProperties&&i.properties,l=t.name("valid");a.props!==!0&&!(a.props instanceof Ji.Name)&&(a.props=(0,Ip.evaluatedPropsToName)(t,a.props));let{props:p}=a;m();function m(){for(let g of s)d&&u(g),a.allErrors?f(g):(t.var(l,!0),f(g),t.if(l))}function u(g){for(let h in d)new RegExp(g).test(h)&&(0,vp.checkStrictMode)(a,`property ${h} matches pattern ${g} (use allowMatchingProperties)`)}function f(g){t.forIn("key",n,h=>{t.if((0,Ji._)`${(0,wp.usePattern)(e,g)}.test(${h})`,()=>{let w=c.includes(g);w||e.subschema({keyword:"patternProperties",schemaProp:g,dataProp:h,dataPropType:Ip.Type.Str},l),a.opts.unevaluated&&p!==!0?t.assign((0,Ji._)`${p}[${h}]`,!0):!w&&!a.allErrors&&t.if((0,Ji.not)(l),()=>t.break())})})}}};Ns.default=Zv});var kp=R(Ds=>{"use strict";Object.defineProperty(Ds,"__esModule",{value:!0});var Xv=U(),Qv={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,Xv.alwaysValidSchema)(n,r)){e.fail();return}let i=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),e.failResult(i,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};Ds.default=Qv});var _p=R(Ss=>{"use strict";Object.defineProperty(Ss,"__esModule",{value:!0});var eI=We(),tI={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:eI.validateUnion,error:{message:"must match a schema in anyOf"}};Ss.default=tI});var Ep=R(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});var Wi=x(),rI=U(),nI={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,Wi._)`{passingSchemas: ${e.passing}}`},iI={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:nI,code(e){let{gen:t,schema:r,parentSchema:n,it:i}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(i.opts.discriminator&&n.discriminator)return;let a=r,o=t.let("valid",!1),s=t.let("passing",null),c=t.name("_valid");e.setParams({passing:s}),t.block(d),e.result(o,()=>e.reset(),()=>e.error(!0));function d(){a.forEach((l,p)=>{let m;(0,rI.alwaysValidSchema)(i,l)?t.var(c,!0):m=e.subschema({keyword:"oneOf",schemaProp:p,compositeRule:!0},c),p>0&&t.if((0,Wi._)`${c} && ${o}`).assign(o,!1).assign(s,(0,Wi._)`[${s}, ${p}]`).else(),t.if(c,()=>{t.assign(o,!0),t.assign(s,p),m&&e.mergeEvaluated(m,Wi.Name)})})}}};js.default=iI});var Ap=R($s=>{"use strict";Object.defineProperty($s,"__esModule",{value:!0});var aI=U(),oI={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:r,it:n}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");let i=t.name("valid");r.forEach((a,o)=>{if((0,aI.alwaysValidSchema)(n,a))return;let s=e.subschema({keyword:"allOf",schemaProp:o},i);e.ok(i),e.mergeEvaluated(s)})}};$s.default=oI});var Np=R(Os=>{"use strict";Object.defineProperty(Os,"__esModule",{value:!0});var Ki=x(),Pp=U(),sI={message:({params:e})=>(0,Ki.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,Ki._)`{failingKeyword: ${e.ifClause}}`},cI={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:sI,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,Pp.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=Rp(n,"then"),a=Rp(n,"else");if(!i&&!a)return;let o=t.let("valid",!0),s=t.name("_valid");if(c(),e.reset(),i&&a){let l=t.let("ifClause");e.setParams({ifClause:l}),t.if(s,d("then",l),d("else",l))}else i?t.if(s,d("then")):t.if((0,Ki.not)(s),d("else"));e.pass(o,()=>e.error(!0));function c(){let l=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},s);e.mergeEvaluated(l)}function d(l,p){return()=>{let m=e.subschema({keyword:l},s);t.assign(o,s),e.mergeValidEvaluated(m,o),p?t.assign(p,(0,Ki._)`${l}`):e.setParams({ifClause:l})}}}};function Rp(e,t){let r=e.schema[t];return r!==void 0&&!(0,Pp.alwaysValidSchema)(e,r)}Os.default=cI});var Dp=R(Cs=>{"use strict";Object.defineProperty(Cs,"__esModule",{value:!0});var lI=U(),dI={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,lI.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Cs.default=dI});var Sp=R(Ts=>{"use strict";Object.defineProperty(Ts,"__esModule",{value:!0});var pI=ys(),uI=sp(),fI=ws(),mI=lp(),gI=dp(),hI=zi(),yI=mp(),wI=As(),vI=yp(),II=bp(),bI=kp(),kI=_p(),_I=Ep(),EI=Ap(),AI=Np(),RI=Dp();function PI(e=!1){let t=[bI.default,kI.default,_I.default,EI.default,AI.default,RI.default,yI.default,wI.default,hI.default,vI.default,II.default];return e?t.push(uI.default,mI.default):t.push(pI.default,fI.default),t.push(gI.default),t}Ts.default=PI});var Ls=R(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.dynamicAnchor=void 0;var xs=x(),NI=Je(),jp=hn(),DI=Li(),SI={keyword:"$dynamicAnchor",schemaType:"string",code:e=>$p(e,e.schema)};function $p(e,t){let{gen:r,it:n}=e;n.schemaEnv.root.dynamicAnchors[t]=!0;let i=(0,xs._)`${NI.default.dynamicAnchors}${(0,xs.getProperty)(t)}`,a=n.errSchemaPath==="#"?n.validateName:jI(e);r.if((0,xs._)`!${i}`,()=>r.assign(i,a))}Sn.dynamicAnchor=$p;function jI(e){let{schemaEnv:t,schema:r,self:n}=e.it,{root:i,baseId:a,localRefs:o,meta:s}=t.root,{schemaId:c}=n.opts,d=new jp.SchemaEnv({schema:r,schemaId:c,root:i,baseId:a,localRefs:o,meta:s});return jp.compileSchema.call(n,d),(0,DI.getValidate)(e,d)}Sn.default=SI});var Vs=R(jn=>{"use strict";Object.defineProperty(jn,"__esModule",{value:!0});jn.dynamicRef=void 0;var Op=x(),$I=Je(),Cp=Li(),OI={keyword:"$dynamicRef",schemaType:"string",code:e=>Tp(e,e.schema)};function Tp(e,t){let{gen:r,keyword:n,it:i}=e;if(t[0]!=="#")throw new Error(`"${n}" only supports hash fragment reference`);let a=t.slice(1);if(i.allErrors)o();else{let c=r.let("valid",!1);o(c),e.ok(c)}function o(c){if(i.schemaEnv.root.dynamicAnchors[a]){let d=r.let("_v",(0,Op._)`${$I.default.dynamicAnchors}${(0,Op.getProperty)(a)}`);r.if(d,s(d,c),s(i.validateName,c))}else s(i.validateName,c)()}function s(c,d){return d?()=>r.block(()=>{(0,Cp.callRef)(e,c),r.let(d,!0)}):()=>(0,Cp.callRef)(e,c)}}jn.dynamicRef=Tp;jn.default=OI});var xp=R(Ms=>{"use strict";Object.defineProperty(Ms,"__esModule",{value:!0});var CI=Ls(),TI=U(),xI={keyword:"$recursiveAnchor",schemaType:"boolean",code(e){e.schema?(0,CI.dynamicAnchor)(e,""):(0,TI.checkStrictMode)(e.it,"$recursiveAnchor: false is ignored")}};Ms.default=xI});var Lp=R(qs=>{"use strict";Object.defineProperty(qs,"__esModule",{value:!0});var LI=Vs(),VI={keyword:"$recursiveRef",schemaType:"string",code:e=>(0,LI.dynamicRef)(e,e.schema)};qs.default=VI});var Vp=R(Us=>{"use strict";Object.defineProperty(Us,"__esModule",{value:!0});var MI=Ls(),qI=Vs(),UI=xp(),FI=Lp(),zI=[MI.default,qI.default,UI.default,FI.default];Us.default=zI});var qp=R(Fs=>{"use strict";Object.defineProperty(Fs,"__esModule",{value:!0});var Mp=zi(),BI={keyword:"dependentRequired",type:"object",schemaType:"object",error:Mp.error,code:e=>(0,Mp.validatePropertyDeps)(e)};Fs.default=BI});var Up=R(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});var GI=zi(),JI={keyword:"dependentSchemas",type:"object",schemaType:"object",code:e=>(0,GI.validateSchemaDeps)(e)};zs.default=JI});var Fp=R(Bs=>{"use strict";Object.defineProperty(Bs,"__esModule",{value:!0});var WI=U(),KI={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:e,parentSchema:t,it:r}){t.contains===void 0&&(0,WI.checkStrictMode)(r,`"${e}" without "contains" is ignored`)}};Bs.default=KI});var zp=R(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});var YI=qp(),HI=Up(),ZI=Fp(),XI=[YI.default,HI.default,ZI.default];Gs.default=XI});var Gp=R(Js=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});var Tt=x(),Bp=U(),QI=Je(),eb={message:"must NOT have unevaluated properties",params:({params:e})=>(0,Tt._)`{unevaluatedProperty: ${e.unevaluatedProperty}}`},tb={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:eb,code(e){let{gen:t,schema:r,data:n,errsCount:i,it:a}=e;if(!i)throw new Error("ajv implementation error");let{allErrors:o,props:s}=a;s instanceof Tt.Name?t.if((0,Tt._)`${s} !== true`,()=>t.forIn("key",n,p=>t.if(d(s,p),()=>c(p)))):s!==!0&&t.forIn("key",n,p=>s===void 0?c(p):t.if(l(s,p),()=>c(p))),a.props=!0,e.ok((0,Tt._)`${i} === ${QI.default.errors}`);function c(p){if(r===!1){e.setParams({unevaluatedProperty:p}),e.error(),o||t.break();return}if(!(0,Bp.alwaysValidSchema)(a,r)){let m=t.name("valid");e.subschema({keyword:"unevaluatedProperties",dataProp:p,dataPropType:Bp.Type.Str},m),o||t.if((0,Tt.not)(m),()=>t.break())}}function d(p,m){return(0,Tt._)`!${p} || !${p}[${m}]`}function l(p,m){let u=[];for(let f in p)p[f]===!0&&u.push((0,Tt._)`${m} !== ${f}`);return(0,Tt.and)(...u)}}};Js.default=tb});var Wp=R(Ws=>{"use strict";Object.defineProperty(Ws,"__esModule",{value:!0});var rr=x(),Jp=U(),rb={message:({params:{len:e}})=>(0,rr.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,rr._)`{limit: ${e}}`},nb={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:rb,code(e){let{gen:t,schema:r,data:n,it:i}=e,a=i.items||0;if(a===!0)return;let o=t.const("len",(0,rr._)`${n}.length`);if(r===!1)e.setParams({len:a}),e.fail((0,rr._)`${o} > ${a}`);else if(typeof r=="object"&&!(0,Jp.alwaysValidSchema)(i,r)){let c=t.var("valid",(0,rr._)`${o} <= ${a}`);t.if((0,rr.not)(c),()=>s(c,a)),e.ok(c)}i.items=!0;function s(c,d){t.forRange("i",d,o,l=>{e.subschema({keyword:"unevaluatedItems",dataProp:l,dataPropType:Jp.Type.Num},c),i.allErrors||t.if((0,rr.not)(c),()=>t.break())})}}};Ws.default=nb});var Kp=R(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});var ib=Gp(),ab=Wp(),ob=[ib.default,ab.default];Ks.default=ob});var Yp=R(Ys=>{"use strict";Object.defineProperty(Ys,"__esModule",{value:!0});var fe=x(),sb={message:({schemaCode:e})=>(0,fe.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,fe._)`{format: ${e}}`},cb={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:sb,code(e,t){let{gen:r,data:n,$data:i,schema:a,schemaCode:o,it:s}=e,{opts:c,errSchemaPath:d,schemaEnv:l,self:p}=s;if(!c.validateFormats)return;i?m():u();function m(){let f=r.scopeValue("formats",{ref:p.formats,code:c.code.formats}),g=r.const("fDef",(0,fe._)`${f}[${o}]`),h=r.let("fType"),w=r.let("format");r.if((0,fe._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(h,(0,fe._)`${g}.type || "string"`).assign(w,(0,fe._)`${g}.validate`),()=>r.assign(h,(0,fe._)`"string"`).assign(w,g)),e.fail$data((0,fe.or)(_(),b()));function _(){return c.strictSchema===!1?fe.nil:(0,fe._)`${o} && !${w}`}function b(){let A=l.$async?(0,fe._)`(${g}.async ? await ${w}(${n}) : ${w}(${n}))`:(0,fe._)`${w}(${n})`,y=(0,fe._)`(typeof ${w} == "function" ? ${A} : ${w}.test(${n}))`;return(0,fe._)`${w} && ${w} !== true && ${h} === ${t} && !${y}`}}function u(){let f=p.formats[a];if(!f){_();return}if(f===!0)return;let[g,h,w]=b(f);g===t&&e.pass(A());function _(){if(c.strictSchema===!1){p.logger.warn(y());return}throw new Error(y());function y(){return`unknown format "${a}" ignored in schema at path "${d}"`}}function b(y){let k=y instanceof RegExp?(0,fe.regexpCode)(y):c.code.formats?(0,fe._)`${c.code.formats}${(0,fe.getProperty)(a)}`:void 0,S=r.scopeValue("formats",{key:a,ref:y,code:k});return typeof y=="object"&&!(y instanceof RegExp)?[y.type||"string",y.validate,(0,fe._)`${S}.validate`]:["string",y,S]}function A(){if(typeof f=="object"&&!(f instanceof RegExp)&&f.async){if(!l.$async)throw new Error("async format in sync schema");return(0,fe._)`await ${w}(${n})`}return typeof h=="function"?(0,fe._)`${w}(${n})`:(0,fe._)`${w}.test(${n})`}}}};Ys.default=cb});var Hp=R(Hs=>{"use strict";Object.defineProperty(Hs,"__esModule",{value:!0});var lb=Yp(),db=[lb.default];Hs.default=db});var Zp=R(Or=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});Or.contentVocabulary=Or.metadataVocabulary=void 0;Or.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Or.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Qp=R(Zs=>{"use strict";Object.defineProperty(Zs,"__esModule",{value:!0});var pb=zd(),ub=np(),fb=Sp(),mb=Vp(),gb=zp(),hb=Kp(),yb=Hp(),Xp=Zp(),wb=[mb.default,pb.default,ub.default,(0,fb.default)(!0),yb.default,Xp.metadataVocabulary,Xp.contentVocabulary,gb.default,hb.default];Zs.default=wb});var tu=R(Yi=>{"use strict";Object.defineProperty(Yi,"__esModule",{value:!0});Yi.DiscrError=void 0;var eu;(function(e){e.Tag="tag",e.Mapping="mapping"})(eu||(Yi.DiscrError=eu={}))});var nu=R(Qs=>{"use strict";Object.defineProperty(Qs,"__esModule",{value:!0});var Cr=x(),Xs=tu(),ru=hn(),vb=gn(),Ib=U(),bb={message:({params:{discrError:e,tagName:t}})=>e===Xs.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>(0,Cr._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`},kb={keyword:"discriminator",type:"object",schemaType:"object",error:bb,code(e){let{gen:t,data:r,schema:n,parentSchema:i,it:a}=e,{oneOf:o}=i;if(!a.opts.discriminator)throw new Error("discriminator: requires discriminator option");let s=n.propertyName;if(typeof s!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!o)throw new Error("discriminator: requires oneOf keyword");let c=t.let("valid",!1),d=t.const("tag",(0,Cr._)`${r}${(0,Cr.getProperty)(s)}`);t.if((0,Cr._)`typeof ${d} == "string"`,()=>l(),()=>e.error(!1,{discrError:Xs.DiscrError.Tag,tag:d,tagName:s})),e.ok(c);function l(){let u=m();t.if(!1);for(let f in u)t.elseIf((0,Cr._)`${d} === ${f}`),t.assign(c,p(u[f]));t.else(),e.error(!1,{discrError:Xs.DiscrError.Mapping,tag:d,tagName:s}),t.endIf()}function p(u){let f=t.name("valid"),g=e.subschema({keyword:"oneOf",schemaProp:u},f);return e.mergeEvaluated(g,Cr.Name),f}function m(){var u;let f={},g=w(i),h=!0;for(let A=0;A<o.length;A++){let y=o[A];if(y?.$ref&&!(0,Ib.schemaHasRulesButRef)(y,a.self.RULES)){let S=y.$ref;if(y=ru.resolveRef.call(a.self,a.schemaEnv.root,a.baseId,S),y instanceof ru.SchemaEnv&&(y=y.schema),y===void 0)throw new vb.default(a.opts.uriResolver,a.baseId,S)}let k=(u=y?.properties)===null||u===void 0?void 0:u[s];if(typeof k!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${s}"`);h=h&&(g||w(y)),_(k,A)}if(!h)throw new Error(`discriminator: "${s}" must be required`);return f;function w({required:A}){return Array.isArray(A)&&A.includes(s)}function _(A,y){if(A.const)b(A.const,y);else if(A.enum)for(let k of A.enum)b(k,y);else throw new Error(`discriminator: "properties/${s}" must have "const" or "enum"`)}function b(A,y){if(typeof A!="string"||A in f)throw new Error(`discriminator: "${s}" values must be unique strings`);f[A]=y}}}};Qs.default=kb});var iu=R((mP,_b)=>{_b.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/schema",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0,"https://json-schema.org/draft/2020-12/vocab/applicator":!0,"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0,"https://json-schema.org/draft/2020-12/vocab/validation":!0,"https://json-schema.org/draft/2020-12/vocab/meta-data":!0,"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0,"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Core and Validation specifications meta-schema",allOf:[{$ref:"meta/core"},{$ref:"meta/applicator"},{$ref:"meta/unevaluated"},{$ref:"meta/validation"},{$ref:"meta/meta-data"},{$ref:"meta/format-annotation"},{$ref:"meta/content"}],type:["object","boolean"],$comment:"This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",properties:{definitions:{$comment:'"definitions" has been replaced by "$defs".',type:"object",additionalProperties:{$dynamicRef:"#meta"},deprecated:!0,default:{}},dependencies:{$comment:'"dependencies" has been split and replaced by "dependentSchemas" and "dependentRequired" in order to serve their differing semantics.',type:"object",additionalProperties:{anyOf:[{$dynamicRef:"#meta"},{$ref:"meta/validation#/$defs/stringArray"}]},deprecated:!0,default:{}},$recursiveAnchor:{$comment:'"$recursiveAnchor" has been replaced by "$dynamicAnchor".',$ref:"meta/core#/$defs/anchorString",deprecated:!0},$recursiveRef:{$comment:'"$recursiveRef" has been replaced by "$dynamicRef".',$ref:"meta/core#/$defs/uriReferenceString",deprecated:!0}}}});var au=R((gP,Eb)=>{Eb.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/applicator",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/applicator":!0},$dynamicAnchor:"meta",title:"Applicator vocabulary meta-schema",type:["object","boolean"],properties:{prefixItems:{$ref:"#/$defs/schemaArray"},items:{$dynamicRef:"#meta"},contains:{$dynamicRef:"#meta"},additionalProperties:{$dynamicRef:"#meta"},properties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},patternProperties:{type:"object",additionalProperties:{$dynamicRef:"#meta"},propertyNames:{format:"regex"},default:{}},dependentSchemas:{type:"object",additionalProperties:{$dynamicRef:"#meta"},default:{}},propertyNames:{$dynamicRef:"#meta"},if:{$dynamicRef:"#meta"},then:{$dynamicRef:"#meta"},else:{$dynamicRef:"#meta"},allOf:{$ref:"#/$defs/schemaArray"},anyOf:{$ref:"#/$defs/schemaArray"},oneOf:{$ref:"#/$defs/schemaArray"},not:{$dynamicRef:"#meta"}},$defs:{schemaArray:{type:"array",minItems:1,items:{$dynamicRef:"#meta"}}}}});var ou=R((hP,Ab)=>{Ab.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/unevaluated",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/unevaluated":!0},$dynamicAnchor:"meta",title:"Unevaluated applicator vocabulary meta-schema",type:["object","boolean"],properties:{unevaluatedItems:{$dynamicRef:"#meta"},unevaluatedProperties:{$dynamicRef:"#meta"}}}});var su=R((yP,Rb)=>{Rb.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/content",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/content":!0},$dynamicAnchor:"meta",title:"Content vocabulary meta-schema",type:["object","boolean"],properties:{contentEncoding:{type:"string"},contentMediaType:{type:"string"},contentSchema:{$dynamicRef:"#meta"}}}});var cu=R((wP,Pb)=>{Pb.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/core",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/core":!0},$dynamicAnchor:"meta",title:"Core vocabulary meta-schema",type:["object","boolean"],properties:{$id:{$ref:"#/$defs/uriReferenceString",$comment:"Non-empty fragments not allowed.",pattern:"^[^#]*#?$"},$schema:{$ref:"#/$defs/uriString"},$ref:{$ref:"#/$defs/uriReferenceString"},$anchor:{$ref:"#/$defs/anchorString"},$dynamicRef:{$ref:"#/$defs/uriReferenceString"},$dynamicAnchor:{$ref:"#/$defs/anchorString"},$vocabulary:{type:"object",propertyNames:{$ref:"#/$defs/uriString"},additionalProperties:{type:"boolean"}},$comment:{type:"string"},$defs:{type:"object",additionalProperties:{$dynamicRef:"#meta"}}},$defs:{anchorString:{type:"string",pattern:"^[A-Za-z_][-A-Za-z0-9._]*$"},uriString:{type:"string",format:"uri"},uriReferenceString:{type:"string",format:"uri-reference"}}}});var lu=R((vP,Nb)=>{Nb.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/format-annotation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/format-annotation":!0},$dynamicAnchor:"meta",title:"Format vocabulary meta-schema for annotation results",type:["object","boolean"],properties:{format:{type:"string"}}}});var du=R((IP,Db)=>{Db.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/meta-data",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/meta-data":!0},$dynamicAnchor:"meta",title:"Meta-data vocabulary meta-schema",type:["object","boolean"],properties:{title:{type:"string"},description:{type:"string"},default:!0,deprecated:{type:"boolean",default:!1},readOnly:{type:"boolean",default:!1},writeOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0}}}});var pu=R((bP,Sb)=>{Sb.exports={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://json-schema.org/draft/2020-12/meta/validation",$vocabulary:{"https://json-schema.org/draft/2020-12/vocab/validation":!0},$dynamicAnchor:"meta",title:"Validation vocabulary meta-schema",type:["object","boolean"],properties:{type:{anyOf:[{$ref:"#/$defs/simpleTypes"},{type:"array",items:{$ref:"#/$defs/simpleTypes"},minItems:1,uniqueItems:!0}]},const:!0,enum:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/$defs/nonNegativeInteger"},minLength:{$ref:"#/$defs/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},maxItems:{$ref:"#/$defs/nonNegativeInteger"},minItems:{$ref:"#/$defs/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},maxContains:{$ref:"#/$defs/nonNegativeInteger"},minContains:{$ref:"#/$defs/nonNegativeInteger",default:1},maxProperties:{$ref:"#/$defs/nonNegativeInteger"},minProperties:{$ref:"#/$defs/nonNegativeIntegerDefault0"},required:{$ref:"#/$defs/stringArray"},dependentRequired:{type:"object",additionalProperties:{$ref:"#/$defs/stringArray"}}},$defs:{nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{$ref:"#/$defs/nonNegativeInteger",default:0},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}}}});var uu=R(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});var jb=iu(),$b=au(),Ob=ou(),Cb=su(),Tb=cu(),xb=lu(),Lb=du(),Vb=pu(),Mb=["/properties"];function qb(e){return[jb,$b,Ob,Cb,Tb,t(this,xb),Lb,t(this,Vb)].forEach(r=>this.addMetaSchema(r,void 0,!1)),this;function t(r,n){return e?r.$dataMetaSchema(n,Mb):n}}ec.default=qb});var nr=R((le,rc)=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.MissingRefError=le.ValidationError=le.CodeGen=le.Name=le.nil=le.stringify=le.str=le._=le.KeywordCxt=le.Ajv2020=void 0;var Ub=Vd(),Fb=Qp(),zb=nu(),Bb=uu(),tc="https://json-schema.org/draft/2020-12/schema",Tr=class extends Ub.default{constructor(t={}){super({...t,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),Fb.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(zb.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:t,meta:r}=this.opts;r&&(Bb.default.call(this,t),this.refs["http://json-schema.org/schema"]=tc)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(tc)?tc:void 0)}};le.Ajv2020=Tr;rc.exports=le=Tr;rc.exports.Ajv2020=Tr;Object.defineProperty(le,"__esModule",{value:!0});le.default=Tr;var Gb=mn();Object.defineProperty(le,"KeywordCxt",{enumerable:!0,get:function(){return Gb.KeywordCxt}});var xr=x();Object.defineProperty(le,"_",{enumerable:!0,get:function(){return xr._}});Object.defineProperty(le,"str",{enumerable:!0,get:function(){return xr.str}});Object.defineProperty(le,"stringify",{enumerable:!0,get:function(){return xr.stringify}});Object.defineProperty(le,"nil",{enumerable:!0,get:function(){return xr.nil}});Object.defineProperty(le,"Name",{enumerable:!0,get:function(){return xr.Name}});Object.defineProperty(le,"CodeGen",{enumerable:!0,get:function(){return xr.CodeGen}});var Jb=Pi();Object.defineProperty(le,"ValidationError",{enumerable:!0,get:function(){return Jb.default}});var Wb=gn();Object.defineProperty(le,"MissingRefError",{enumerable:!0,get:function(){return Wb.default}})});import{readFile as te,readdir as Wm,realpath as pt}from"node:fs/promises";import{execFile as pA,spawn as uA}from"node:child_process";import N from"node:path";import{parseArgs as oe,promisify as fA}from"node:util";var X="^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$",ut="^sha256:[a-f0-9]{64}$";import{constants as ma}from"node:fs";import{lstat as Ek,mkdir as Wr,open as Nu,readFile as Mn,realpath as dr,rename as Ak,unlink as wc}from"node:fs/promises";import{randomUUID as vc}from"node:crypto";import ye from"node:path";var fu=br(nr(),1);var ke={type:"string",pattern:ut},Kb={type:"string",pattern:"^[a-z][a-z0-9.-]{2,127}$"},nc={type:"string",format:"date-time"},ic={enum:["typescript.typecheck","vitest.run","typescript.build","npm.pack-dry-run","workspace.structure","capability.assets","node.application-smoke","web.application-build","web.application-smoke","expo.application-config","expo.application-export","react.library-build","next.application-test","next.application-build","next.application-package","next.application-smoke","application.config-contract"]},mu={type:"object",additionalProperties:!1,required:["node","pnpm","typescript"],properties:{node:{type:"string",minLength:1,maxLength:64},pnpm:{type:"string",minLength:1,maxLength:64},typescript:{type:"string",minLength:1,maxLength:64}}},ac={$id:"https://schemas.dyyto.dev/platform/capability-bundle-release-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","capabilityId","version","integrity","consumerProfile","compatibility","assets","verifiers","exit"],properties:{schemaVersion:{const:1},capabilityId:{type:"string",pattern:X},version:{type:"string",minLength:1,maxLength:128},integrity:ke,consumerProfile:{enum:["blank-typescript-library","standalone-npm-package","react-component-library","nextjs-full-stack-application","workspace-root","workspace-npm-package","workspace-node-application","workspace-web-application","workspace-expo-application","any-project"]},kind:{enum:["profile","engineering-feature","integration-feature","domain-extension"]},dependencies:{type:"object",additionalProperties:!1,required:["profiles"],properties:{profiles:{type:"array",minItems:1,uniqueItems:!0,items:{type:"string",minLength:1,maxLength:128}},capabilities:{type:"array",minItems:1,uniqueItems:!0,items:{type:"string",pattern:X}}}},compatibility:mu,integration:{type:"object",additionalProperties:!1,required:["title","purpose","packages","codeAssets"],properties:{title:{type:"string",minLength:1,maxLength:128},purpose:{type:"string",minLength:1,maxLength:512},packages:{type:"array",items:{type:"object",additionalProperties:!1,required:["packageName","version","usage","imports"],properties:{packageName:{type:"string",minLength:1,maxLength:214},version:{type:"string",minLength:1,maxLength:128},usage:{enum:["runtime","development","build","test"]},imports:{type:"array",items:{type:"object",additionalProperties:!1,required:["importFrom","symbol"],properties:{importFrom:{type:"string",minLength:1,maxLength:214},symbol:{type:"string",minLength:1,maxLength:128},referencePath:{type:"string",minLength:1,maxLength:512}}}}}}},codeAssets:{type:"array",items:{type:"object",additionalProperties:!1,required:["sourcePath","targetPath","ownership"],properties:{sourcePath:{type:"string",minLength:1,maxLength:512},targetPath:{type:"string",minLength:1,maxLength:512},ownership:{enum:["owned-file","managed-region","seed-file"]}}}}}},assets:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["path","ownership","digest","mode"],properties:{path:{type:"string",minLength:1,maxLength:512},ownership:{enum:["owned-file","managed-region","seed-file"]},digest:ke,mode:{type:"integer",minimum:0,maximum:511},regionId:{type:"string",pattern:X},renderer:{enum:["npm-package-json-v1","npm-package-json-v2","react-component-package-json-v1","nextjs-application-package-json-v1","workspace-root-package-json-v1","node-application-package-json-v1","web-application-package-json-v1","expo-application-package-json-v1","application-config-contract-v1","application-config-binding-v1"]}},allOf:[{if:{properties:{ownership:{const:"managed-region"}},required:["ownership"]},then:{properties:{regionId:{type:"string",pattern:X}},required:["regionId"]},else:{not:{required:["regionId"]}}}]}},verifiers:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["id"],properties:{id:ic}}},exit:{type:"object",additionalProperties:!1,required:["ownedAssets"],properties:{ownedAssets:{type:"array",items:{type:"string",minLength:1,maxLength:512}}}}}},gu={type:"object",additionalProperties:!1,required:["registryId","packageName","version","integrity","tarballDigest","deliveryReceiptId","usage"],properties:{registryId:{type:"string",pattern:"^registry\\.[a-z0-9][a-z0-9.-]{1,126}$"},packageName:{type:"string",pattern:"^@[a-z0-9][a-z0-9._-]*/[a-z0-9][a-z0-9._-]*$",maxLength:214},version:{type:"string",pattern:"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)$",maxLength:64},integrity:{type:"string",pattern:"^sha512-[A-Za-z0-9+/]{86}==$"},tarballDigest:ke,deliveryReceiptId:ke,usage:{enum:["runtime","development"]}}},{$id:EP,...hu}=ac,Yb={...hu,$id:"https://schemas.dyyto.dev/platform/capability-bundle-release-v2.json",required:[...ac.required,"availability","packageSources"],properties:{...ac.properties,schemaVersion:{const:2},availability:{oneOf:[{type:"object",additionalProperties:!1,required:["maturity","visibility","sourceState"],properties:{maturity:{const:"candidate"},visibility:{const:"maintainers-only"},sourceState:{const:"local-artifact"}}},{type:"object",additionalProperties:!1,required:["maturity","visibility","sourceState"],properties:{maturity:{const:"candidate"},visibility:{const:"maintainers-only"},sourceState:{const:"development-registry"}}},{type:"object",additionalProperties:!1,required:["maturity","visibility","sourceState"],properties:{maturity:{const:"available"},visibility:{const:"catalog-consumers"},sourceState:{const:"registry-verified"}}},{type:"object",additionalProperties:!1,required:["maturity","visibility","reasonCode"],properties:{maturity:{const:"withdrawn"},visibility:{const:"existing-locks-only"},reasonCode:{type:"string",pattern:"^[A-Z][A-Z0-9_]{2,63}$"}}}]},packageSources:{type:"array",maxItems:128,items:gu}}},Hb={$id:"https://schemas.dyyto.dev/platform/capability-bundle-release.json",oneOf:[hu,(()=>{let{$id:e,...t}=Yb;return t})()]},Hi={$id:"https://schemas.dyyto.dev/platform/verification-result-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","verifierId","result","issuer","commandId","exitCode","stdoutDigest","stderrDigest","startedAt","completedAt","projectStateDigest","runtime"],properties:{schemaVersion:{const:1},verifierId:ic,result:{enum:["passed","failed"]},issuer:{enum:["dyyto-cli","test-harness","external-ci"]},commandId:ic,exitCode:{type:"integer",minimum:0,maximum:255},stdoutDigest:ke,stderrDigest:ke,startedAt:nc,completedAt:nc,projectStateDigest:ke,runtime:mu}},Zb={...Hi,$id:"https://schemas.dyyto.dev/platform/adoption-evidence-v1.json",required:[...Hi.required,"evidenceId","capabilityId","capabilityVersion","capabilityIntegrity"],properties:{...Hi.properties,evidenceId:ke,capabilityId:{type:"string",pattern:X},capabilityVersion:{type:"string",minLength:1,maxLength:128},capabilityIntegrity:ke}},Xb={$id:"https://schemas.dyyto.dev/platform/project-adoption-lock.json",type:"object",additionalProperties:!1,required:["schemaVersion","capabilities"],properties:{schemaVersion:{enum:[1,2]},capabilities:{type:"array",items:{type:"object",additionalProperties:!1,required:["capabilityId","version","integrity","consumerProfile","appliedPlanId","projectStateDigest","assets","evidenceIds","committedAt"],properties:{capabilityId:{type:"string",pattern:X},version:{type:"string",minLength:1,maxLength:128},integrity:ke,consumerProfile:{type:"string",minLength:1,maxLength:128},appliedPlanId:ke,projectStateDigest:ke,assets:{type:"array",items:{type:"object",additionalProperties:!1,required:["path","digest"],properties:{path:{type:"string",minLength:1,maxLength:512},digest:ke,ownership:{enum:["owned-file","managed-region","seed-file"]},regionId:{type:"string",pattern:X}},allOf:[{if:{properties:{ownership:{const:"managed-region"}},required:["ownership"]},then:{properties:{regionId:{type:"string",pattern:X}},required:["regionId"]}}]}},evidenceIds:{type:"array",items:ke},committedAt:nc,packageAdoption:{type:"object",additionalProperties:!1,required:["registryRevisions","sources","packageJsonDigest","lockfileDigest"],properties:{sourceChannel:{enum:["production","development"]},registryRevisions:{type:"array",items:{type:"object",additionalProperties:!1,required:["registryId","revision"],properties:{registryId:Kb,revision:ke}}},sources:{type:"array",minItems:1,maxItems:128,items:gu},packageJsonDigest:ke,lockfileDigest:ke}}}}}},allOf:[{if:{properties:{schemaVersion:{const:1}},required:["schemaVersion"]},then:{properties:{capabilities:{type:"array",items:{type:"object",not:{type:"object",properties:{packageAdoption:{}},required:["packageAdoption"]}}}}}}]},$n=new fu.Ajv2020({allErrors:!0,strict:!0});$n.addFormat("date-time",{type:"string",validate:e=>!Number.isNaN(Date.parse(e))});var Xi={capabilityBundleRelease:$n.compile(Hb),verificationResult:$n.compile(Hi),adoptionEvidence:$n.compile(Zb),projectAdoptionLock:$n.compile(Xb)},Zi=class extends Error{contract;issues;code="ADOPTION_CONTRACT_INVALID";constructor(t,r){super(`Invalid ${t} contract`),this.contract=t,this.issues=r}};function Qi(e,t,r){if(!t(r))throw new Zi(e,t.errors??[]);return r}var yu=e=>{let t=Qi("capabilityBundleRelease",Xi.capabilityBundleRelease,e);if(t.schemaVersion===2){let r=()=>{throw new Zi("capabilityBundleRelease",[])},n=t.packageSources;(t.availability.maturity==="candidate"&&t.availability.sourceState==="local-artifact"&&n.length!==0||t.availability.maturity==="candidate"&&t.availability.sourceState==="development-registry"&&n.length===0||t.availability.maturity!=="candidate"&&n.length===0)&&r();let i="",a=new Set;for(let s of n){let c=`${s.packageName}@${s.version}`;(c.localeCompare(i)<=0||a.has(c))&&r(),i=c,a.add(c)}let o=t.integration?.packages??[];(t.availability.maturity!=="candidate"||t.availability.sourceState==="development-registry")&&(o.length!==n.length||o.some(s=>!n.some(c=>c.packageName===s.packageName&&c.version===s.version&&c.usage===s.usage)))&&r()}return t},wu=e=>Qi("verificationResult",Xi.verificationResult,e),On=e=>Qi("adoptionEvidence",Xi.adoptionEvidence,e),Te=e=>Qi("projectAdoptionLock",Xi.projectAdoptionLock,e);import{lstat as sk,readFile as lc,realpath as dc}from"node:fs/promises";import Vr from"node:path";import{createHash as Qb}from"node:crypto";function v(e){return`sha256:${Qb("sha256").update(e).digest("hex")}`}function E(e){return Array.isArray(e)?`[${e.map(E).join(",")}]`:e!==null&&typeof e=="object"?`{${Object.entries(e).filter(([,r])=>r!==void 0).sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>`${JSON.stringify(r)}:${E(n)}`).join(",")}}`:JSON.stringify(e)}var ht=class extends Error{code="MANAGED_REGION_INVALID";constructor(t){super(t)}};function vu(e){if(!new RegExp(X).test(e))throw new ht("Region identity is invalid");return{begin:`<!-- dyyto:begin ${e} -->`,end:`<!-- dyyto:end ${e} -->`}}function ea(e,t){if(e.includes("\r"))throw new ht("Managed regions require LF newlines");let{begin:r,end:n}=vu(t),i=e.split(r).length-1,a=e.split(n).length-1;if(i!==1||a!==1)throw new ht("Managed region markers are unavailable or ambiguous");let o=e.indexOf(r)+r.length,s=e.indexOf(n,o),c=e.slice(o,s);if(/<!-- dyyto:(?:begin|end) /.test(c))throw new ht("Managed regions cannot overlap");return`${c.replace(/^\n+|\n+$/g,"")}
|
|
9
|
+
`}function Iu(e){let{begin:t,end:r}=vu(e.regionId);if(e.source.includes("\r")||e.content.includes("\r"))throw new ht("Managed regions require LF newlines");let n=e.source.split(t).length-1,i=e.source.split(r).length-1;if(n>1||i>1||n!==i)throw new ht("Managed region markers are ambiguous");let a=e.content.replace(/^\n+|\n+$/g,"");if(/<!-- dyyto:(?:begin|end) /.test(a))throw new ht("Managed regions cannot contain nested Dyyto markers");let o=`${t}
|
|
10
10
|
${a}
|
|
11
11
|
${r}`;if(n===0){let l=e.source.replace(/\n*$/g,"");return`${l}${l.length===0?"":`
|
|
12
12
|
|
|
13
13
|
`}${o}
|
|
14
|
-
`}let s=e.source.indexOf(t),c=e.source.indexOf(r,s)+r.length,d=e.source.slice(s+t.length,c-r.length);if(/<!-- dyyto:(?:begin|end) /.test(d))throw new ht("Managed regions cannot overlap");return`${e.source.slice(0,s)}${o}${e.source.slice(c)}`}import Iu from"node:path";var xt=class extends Error{assetPath;code="PLAN_PRECONDITION_FAILED";constructor(t,r){super(t),this.assetPath=r}};function ta(e){if(e.length===0||Iu.posix.isAbsolute(e)||Iu.win32.isAbsolute(e)||e.includes("\\")||e.split("/").some(t=>t===".."||t==="."))throw new xt("Asset path must be a normalized project-relative POSIX path",e)}function ek(e,t){ta(e.path);let r=e.kind==="merge"&&e.ownership==="managed-region"&&e.regionId!==void 0&&new RegExp(X).test(e.regionId);if((e.kind==="merge"||e.ownership==="managed-region"||e.regionId!==void 0)&&!r)throw new xt("Managed regions require merge ownership and a valid region identity",e.path);if(e.ownership==="user-file")return{...e,disposition:"conflict",conflictCode:"USER_OWNED"};let n=t?.exists??!1,i=t?.digest;return e.kind==="create"?n?e.desiredDigest!==void 0&&i===e.desiredDigest?{...e,disposition:"noop"}:{...e,disposition:"conflict",conflictCode:"UNEXPECTED_EXISTING"}:{...e,disposition:"ready"}:e.kind==="remove"&&!n?{...e,disposition:"noop"}:e.kind!=="remove"&&n&&e.desiredDigest===i?{...e,disposition:"noop"}:!n||e.baseDigest===void 0||i!==e.baseDigest?{...e,disposition:"conflict",conflictCode:"BASE_DIGEST_MISMATCH"}:{...e,disposition:"ready"}}function De(e){if(Number.isNaN(Date.parse(e.generatedAt))||Number.isNaN(Date.parse(e.expiresAt)))throw new xt("Plan timestamps must be valid ISO date-time values");if(Date.parse(e.expiresAt)<=Date.parse(e.generatedAt))throw new xt("Plan expiry must be later than generation time");let t=new Map;for(let s of e.observedAssets){if(ta(s.path),t.has(s.path))throw new xt("Observed asset paths must be unique",s.path);t.set(s.path,s)}let r=new Set,n=e.changes.map(s=>{if(r.has(s.path))throw new xt("Proposed change paths must be unique",s.path);return r.add(s.path),ek(s,t.get(s.path))}).sort((s,c)=>s.path.localeCompare(c.path)),i={action:e.action,capability:{capabilityId:e.capability.capabilityId,version:e.capability.version,integrity:e.capability.integrity},changes:e.changes,observedAssets:e.observedAssets,generatedAt:e.generatedAt,expiresAt:e.expiresAt,...e.packageAdoption===void 0?{}:{packageAdoption:e.packageAdoption}},a=v(E(i)),o={schemaVersion:1,action:e.action,state:n.some(s=>s.disposition==="conflict")?"conflicted":"reviewable",capability:i.capability,generatedAt:e.generatedAt,expiresAt:e.expiresAt,inputDigest:a,operations:n,...e.packageAdoption===void 0?{}:{packageAdoption:e.packageAdoption}};return{...o,planId:v(E(o))}}function ra(e){return v(E(e))}var bu=br(nr(),1);var Q={type:"string",pattern:ut},Lr={type:"string",pattern:X},or={type:"string",minLength:1,maxLength:128},ar={type:"string",minLength:1,maxLength:512,pattern:"^(?!/)(?!.*(?:^|/)\\.\\.(?:/|$))(?!.*\\\\).+$"},tk={$id:"https://schemas.dyyto.dev/platform/capability-release-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","capabilityId","version","integrity","assets","verifiers"],properties:{schemaVersion:{const:1},capabilityId:Lr,version:or,integrity:Q,assets:{type:"array",items:{type:"object",additionalProperties:!1,required:["path","ownership"],properties:{path:ar,ownership:{enum:["owned-file","managed-region","seed-file","shared-file","user-file"]},desiredDigest:Q}}},verifiers:{type:"array",items:{type:"object",additionalProperties:!1,required:["id","kind"],properties:{id:{type:"string",minLength:1,maxLength:128},kind:{enum:["command","file-digest"]}}}}}},rk={$id:"https://schemas.dyyto.dev/platform/project-manifest-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","capabilities"],properties:{schemaVersion:{const:1},template:{type:"object",additionalProperties:!1,required:["id","version"],properties:{id:Lr,version:or}},profile:{type:"object",additionalProperties:!1,required:["id","parameters"],properties:{id:{type:"string",pattern:X},parameters:{type:"object",minProperties:0,maxProperties:32,propertyNames:{pattern:"^[a-z][A-Za-z0-9]*$"},additionalProperties:{type:"string",maxLength:256}}}},capabilities:{type:"array",items:{type:"object",additionalProperties:!1,required:["capabilityId","version"],properties:{capabilityId:Lr,version:or}}}}},nk={$id:"https://schemas.dyyto.dev/platform/project-lock-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","capabilities"],properties:{schemaVersion:{const:1},capabilities:{type:"array",items:{type:"object",additionalProperties:!1,required:["capabilityId","version","integrity","appliedPlanId","assets","evidenceIds"],properties:{capabilityId:Lr,version:or,integrity:Q,appliedPlanId:Q,assets:{type:"array",items:{type:"object",additionalProperties:!1,required:["path","digest"],properties:{path:ar,digest:Q}}},evidenceIds:{type:"array",items:{type:"string",minLength:1,maxLength:256}}}}}}},ik={$id:"https://schemas.dyyto.dev/platform/evidence-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","evidenceId","capabilityId","capabilityVersion","verifierId","result","observedAt"],properties:{schemaVersion:{const:1},evidenceId:{type:"string",minLength:1,maxLength:256},capabilityId:Lr,capabilityVersion:or,verifierId:{type:"string",minLength:1,maxLength:128},result:{enum:["passed","failed"]},observedAt:{type:"string",format:"date-time"}}},ak={$id:"https://schemas.dyyto.dev/platform/change-plan-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","planId","action","state","capability","generatedAt","expiresAt","inputDigest","operations"],properties:{schemaVersion:{const:1},planId:Q,action:{enum:["adopt","upgrade","remove"]},state:{enum:["reviewable","conflicted"]},capability:{type:"object",additionalProperties:!1,required:["capabilityId","version","integrity"],properties:{capabilityId:Lr,version:or,integrity:Q}},generatedAt:{type:"string",format:"date-time"},expiresAt:{type:"string",format:"date-time"},inputDigest:Q,packageAdoption:{type:"object",additionalProperties:!1,required:["schemaVersion","packageJsonPreimageDigest","desiredPackageJsonDigest","lockfilePreimage","desiredLockfileDigest","registryRevisions","endpointBindings","sources","installPolicy"],properties:{schemaVersion:{enum:[1,2]},sourceChannel:{enum:["production","development"]},packageJsonPreimageDigest:Q,desiredPackageJsonDigest:Q,lockfilePreimage:{oneOf:[{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:{const:"absent"}}},{type:"object",additionalProperties:!1,required:["kind","digest"],properties:{kind:{const:"present"},digest:Q}}]},desiredLockfileDigest:Q,registryRevisions:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["registryId","revision"],properties:{registryId:{type:"string",minLength:1,maxLength:128},revision:Q}}},endpointBindings:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["registryId","registryConfigRevision","bindingDigest","expiresAt"],properties:{registryId:{type:"string",minLength:1,maxLength:128},registryConfigRevision:Q,bindingDigest:Q,expiresAt:{type:"string",format:"date-time"}}}},sources:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["registryId","packageName","version","integrity","tarballDigest","deliveryReceiptId","usage"],properties:{registryId:{type:"string",minLength:1,maxLength:128},packageName:{type:"string",pattern:"^@[a-z0-9][a-z0-9._-]*/[a-z0-9][a-z0-9._-]*$"},version:or,integrity:{type:"string",pattern:"^sha512-[A-Za-z0-9+/]+={0,2}$"},tarballDigest:Q,deliveryReceiptId:Q,usage:{enum:["runtime","development"]}}}},installPolicy:{type:"object",additionalProperties:!1,required:["ignoreScripts","allowWorkspaceProtocol","allowPublicRegistryFallback"],properties:{ignoreScripts:{const:!0},allowWorkspaceProtocol:{const:!1},allowPublicRegistryFallback:{const:!1}}},topology:{type:"object",additionalProperties:!1,required:["mode","unitRelativeRoot","unitImporterId","lockfilePath"],properties:{mode:{enum:["standalone","pnpm-shared-lockfile"]},unitRelativeRoot:ar,unitImporterId:ar,lockfilePath:{const:"pnpm-lock.yaml"},workspaceManifestPath:{const:"pnpm-workspace.yaml"},workspaceManifestDigest:Q}},preservedDependencies:{type:"array",items:{type:"object",additionalProperties:!1,required:["section","packageName","specifier"],properties:{section:{enum:["dependencies","devDependencies","optionalDependencies"]},packageName:{type:"string",minLength:1,maxLength:214},specifier:{type:"string",minLength:1,maxLength:512}}}},preservedImporterDigests:{type:"array",items:{type:"object",additionalProperties:!1,required:["importerId","preimageDigest","desiredDigest"],properties:{importerId:ar,preimageDigest:Q,desiredDigest:Q}}}},allOf:[{if:{properties:{schemaVersion:{const:1}},required:["schemaVersion"]},then:{properties:{topology:!1,preservedDependencies:!1,preservedImporterDigests:!1}}},{if:{properties:{schemaVersion:{const:2}},required:["schemaVersion"]},then:{required:["topology","preservedDependencies","preservedImporterDigests"]}}]},operations:{type:"array",items:{type:"object",additionalProperties:!1,required:["path","kind","ownership","disposition"],properties:{path:ar,kind:{enum:["create","replace","merge","remove"]},ownership:{enum:["owned-file","managed-region","seed-file","shared-file","user-file"]},desiredDigest:Q,baseDigest:Q,regionId:{type:"string",pattern:X},disposition:{enum:["ready","noop","conflict"]},conflictCode:{enum:["USER_OWNED","UNEXPECTED_EXISTING","BASE_DIGEST_MISMATCH"]}}}}}},ok={$id:"https://schemas.dyyto.dev/platform/transaction-journal-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","transactionId","planId","approvedPlanId","projectRootDigest","state","createdAt","updatedAt","operations","journalDigest"],properties:{schemaVersion:{const:1},transactionId:{type:"string",minLength:1,maxLength:128},planId:Q,approvedPlanId:Q,projectRootDigest:Q,state:{enum:["preparing","prepared","applying","applied","recovery-required","recovering","recovered"]},createdAt:{type:"string",format:"date-time"},updatedAt:{type:"string",format:"date-time"},operations:{type:"array",items:{type:"object",additionalProperties:!1,required:["index","path","kind","before","status"],properties:{index:{type:"integer",minimum:0},path:ar,kind:{enum:["create","replace","merge","remove"]},before:{oneOf:[{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:{const:"absent"}}},{type:"object",additionalProperties:!1,required:["kind","digest","mode","preimageDigest"],properties:{kind:{const:"present"},digest:Q,mode:{type:"integer",minimum:0,maximum:511},preimageDigest:Q}}]},desiredDigest:Q,status:{enum:["pending","applied","restored"]}}}},failure:{type:"object",additionalProperties:!1,required:["code"],properties:{code:{type:"string",minLength:1,maxLength:128},operationIndex:{type:"integer",minimum:0}}},journalDigest:Q}},ir=new bu.Ajv2020({allErrors:!0,strict:!0});ir.addFormat("date-time",{type:"string",validate:e=>!Number.isNaN(Date.parse(e))});var sc={capabilityRelease:ir.compile(tk),projectManifest:ir.compile(rk),projectLock:ir.compile(nk),evidence:ir.compile(ik),changePlan:ir.compile(ak),transactionJournal:ir.compile(ok)},oc=class extends Error{contract;issues;code="CONTRACT_INVALID";constructor(t,r){super(`Invalid ${t} contract`),this.contract=t,this.issues=r}};function cc(e,t,r){if(!t(r))throw new oc(e,t.errors??[]);return r}var J=e=>cc("projectManifest",sc.projectManifest,e);var Lt=e=>cc("changePlan",sc.changePlan,e),ku=e=>cc("transactionJournal",sc.transactionJournal,e);var M=class extends Error{code;assetPath;constructor(t,r,n){super(r),this.code=t,this.assetPath=n}};async function na(e){if(e.currentLock!==void 0){let a=await ia({...e,manifest:{schemaVersion:1,capabilities:[{capabilityId:e.release.release.capabilityId,version:e.release.release.version}]}});return{state:a.plan.state==="conflicted"?"drifted":"adopted",operations:a.plan.operations}}let t=await dc(Vr.resolve(e.projectRoot)),r=[],n=0,i=0;for(let a of e.release.release.assets){let o=await pc(t,a.path);o.exists&&(n+=1),o.digest===a.digest&&(i+=1),r.push({path:a.path,kind:"create",ownership:a.ownership,desiredDigest:a.ownership==="seed-file"&&o.digest?o.digest:a.digest,disposition:o.exists?a.ownership==="seed-file"||o.digest===a.digest?"noop":"conflict":"ready",...o.exists&&o.digest!==a.digest?{conflictCode:"UNEXPECTED_EXISTING"}:{}})}return n===0?{state:"planned",operations:r}:i===e.release.release.assets.length?{state:"applied-unverified",operations:r}:{state:"drifted",operations:r}}async function pc(e,t){let r=Vr.join(e,...t.split("/"));try{let n=await sk(r);if(!n.isFile()||n.isSymbolicLink())throw new M("PROJECT_STATE_INVALID","Blank profile target must be a regular file",t);return{path:t,exists:!0,digest:v(await lc(r))}}catch(n){if(n.code==="ENOENT")return{path:t,exists:!1};throw n}}async function sr(e){let t=await dc(Vr.resolve(e.projectRoot)),r=[];for(let n of e.expectedAssets){let i=await pc(t,n.path),a=i.exists&&i.digest===n.digest;if(n.ownership==="managed-region"&&n.regionId!==void 0&&i.exists)try{a=v(ea(await lc(Vr.join(t,...n.path.split("/")),"utf8"),n.regionId))===n.digest}catch{a=!1}if(!a)throw new M("PROJECT_STATE_INVALID","A managed project asset does not match the approved plan",n.path);r.push({path:n.path,digest:n.digest,...n.ownership===void 0?{}:{ownership:n.ownership},...n.regionId===void 0?{}:{regionId:n.regionId}})}return{assets:r,projectStateDigest:v(E(r))}}async function ia(e){let t=J(e.manifest);if(t.capabilities.filter(l=>l.capabilityId===e.release.release.capabilityId&&l.version===e.release.release.version).length!==1||t.capabilities.length!==1)throw new M("RELEASE_NOT_FOUND","Manifest must select exactly the loaded M3 capability release");let i=(e.currentLock===void 0?void 0:Te(e.currentLock))?.capabilities.find(l=>l.capabilityId===e.release.release.capabilityId);if(i!==void 0&&(i.version!==e.release.release.version||i.integrity!==e.release.release.integrity))throw new M("CONSUMER_PROFILE_UNSUPPORTED","M3 does not support upgrading a different locked release");let a=await dc(Vr.resolve(e.projectRoot)),o=[],s=[],c=new Map(e.release.contents);for(let l of e.release.release.assets){let p=await pc(a,l.path);if(o.push(p),p.exists&&i===void 0&&l.ownership!=="seed-file")throw new M("CONSUMER_PROFILE_UNSUPPORTED","Blank profile cannot adopt over an existing file without a lock",l.path);let m=l.ownership==="seed-file"&&p.digest?p.digest:l.digest;l.ownership==="seed-file"&&p.exists&&c.set(l.path,await lc(Vr.join(a,...l.path.split("/")))),s.push({path:l.path,kind:"create",ownership:l.ownership,desiredDigest:m})}let d={schemaVersion:1,capabilityId:e.release.release.capabilityId,version:e.release.release.version,integrity:e.release.release.integrity,assets:e.release.release.assets.map(l=>({path:l.path,ownership:l.ownership,desiredDigest:l.digest})),verifiers:e.release.release.verifiers.map(l=>({id:l.id,kind:"command"}))};return{manifest:t,release:e.release,plan:De({action:"adopt",capability:d,changes:s,observedAssets:o,generatedAt:e.generatedAt,expiresAt:e.expiresAt}),desiredContents:c}}import{chmod as lk,lstat as da,mkdir as Mr,open as Au,readFile as pa,realpath as dk,rename as ca,rm as uc,unlink as cr}from"node:fs/promises";import{constants as oa}from"node:fs";import{homedir as pk}from"node:os";import G from"node:path";import{randomUUID as Fr}from"node:crypto";function ck(e){let t=e?.code;return typeof t=="string"&&/^[A-Z0-9_]+$/.test(t)?t:"UNKNOWN"}async function He(e){let t=process.hrtime.bigint();try{let r=await e.run();return await _u(e.context,e.operation,e.bytes??0,t,"succeeded"),r}catch(r){throw await _u(e.context,e.operation,e.bytes??0,t,"failed",ck(r)),r}}async function _u(e,t,r,n,i,a){if(e?.sink===void 0)return;let o=process.hrtime.bigint(),s={schemaVersion:1,phase:e.phase,operation:t,pathCategory:e.pathCategory,bytes:r,barrierId:e.barrierId,startedMonotonicNs:n.toString(),completedMonotonicNs:o.toString(),result:i,...a===void 0?{}:{errorCategory:a}},c=Object.freeze({...s,eventId:v(E(s))});try{await e.sink(c)}catch{}}var Ru=Symbol("prepared-transaction"),Vt=new Map,uk=5*1024*1024,fk=25*1024*1024,Eu=8,la=class extends Error{};async function aa(e,t,r){try{await e?.onCheckpoint?.(t,r)}catch(n){throw new la("Simulated prepare crash",{cause:n})}}var C=class extends Error{code;relativePath;operationIndex;constructor(t,r,n,i){super(r),this.code=t,this.relativePath=n,this.operationIndex=i}};function Cn(e,t){let r=G.join(e,".dyyto"),n=G.join(r,"transactions",t);return{platformDirectory:r,lock:G.join(r,"transaction-lock.json"),transactionDirectory:n,journal:G.join(n,"journal.json"),preimages:G.join(n,"preimages"),quarantine:G.join(n,"quarantine")}}async function kt(e){try{return await da(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function zr(e,t=!1){if(e?.sink!==void 0)return{sink:e.sink,phase:e.phase,pathCategory:t?"directory":e.category,barrierId:e.barrierId}}function ot(e,t,r,n){return e===void 0?void 0:{sink:e,phase:t,category:r,barrierId:n}}async function Ze(e,t){let r=await Au(e,oa.O_RDONLY);try{await He({context:zr(t,!0),operation:"directory-sync",run:()=>r.sync()})}finally{await r.close()}}async function Tn(e,t,r=384,n){let i=await Au(e,oa.O_CREAT|oa.O_EXCL|oa.O_WRONLY,r);try{await He({context:zr(n),operation:"write",bytes:t.byteLength,run:()=>i.writeFile(t)}),await He({context:zr(n),operation:"file-sync",bytes:t.byteLength,run:()=>i.sync()})}finally{await i.close()}}async function fc(e,t,r){let n=G.dirname(e),i=G.join(n,`.tmp-${Fr()}`),a=Buffer.from(`${JSON.stringify(t,null,2)}
|
|
15
|
-
`);await Tn(i,a,384,r),await He({context:zr(r),operation:"rename",bytes:a.byteLength,run:()=>ca(i,e)}),await Ze(n,r)}function mc(e){return{...e,journalDigest:v(E(e))}}function mk(e){let t;try{t=
|
|
16
|
-
`),384,r),await Ze(G.dirname(e),r)}catch(n){throw n.code==="EEXIST"?new C("TRANSACTION_ACTIVE","Another platform transaction is active"):n}}async function sa(e){try{let t=JSON.parse(await pa(e,"utf8"));if(t.schemaVersion!==1||typeof t.transactionId!="string"||typeof t.planId!="string"||typeof t.startedAt!="string"||typeof t.nonce!="string")throw new Error("invalid lock");return t}catch{throw new C("JOURNAL_CORRUPTED","Transaction lock is invalid")}}function yk(e,t,r){return{[Ru]:!0,projectRoot:e,plan:t,transactionId:r}}async function wk(e,t){gk(e.plan,e.approvedPlanId,e.now);let r=await ua(e.projectRoot),n=hk(e.plan),i=new Set(e.plan.operations.filter(u=>u.kind!=="remove"&&u.disposition!=="conflict").map(u=>u.path));for(let u of e.desiredContents.keys())if(!i.has(u))throw new C("DESIRED_CONTENT_MISMATCH","Desired content is not declared by the plan",u);for(let u of n)if(Br(r,u.path),await qr(r,u.path),u.kind!=="remove"){let f=e.desiredContents.get(u.path);if(f===void 0||v(f)!==u.desiredDigest)throw new C("DESIRED_CONTENT_MISMATCH","Desired content digest does not match the plan",u.path)}let a=Cn(r,e.plan.planId);await Mr(a.platformDirectory,{recursive:!0,mode:448}),await qr(r,".dyyto");let o=Fr();await hc(a.lock,{schemaVersion:1,transactionId:o,planId:e.plan.planId,startedAt:e.now,nonce:Fr()},ot(t?.durabilityTrace,"prepare","lock",`${o}:prepare-lock`));let s=e.limits?.maxFileBytes??uk,c=e.limits?.maxTransactionBytes??fk,d=0,l=[],p=[],m=!1;try{if(await aa(t,"lock-created"),await kt(a.transactionDirectory))throw new C("PLAN_PRECONDITION_FAILED","This plan already has a transaction record");await Mr(a.preimages,{recursive:!0,mode:448}),await Mr(a.quarantine,{recursive:!0,mode:448}),m=!0;for(let[f,g]of n.entries()){let h=Br(r,g.path);await qr(r,g.path);let w=await Ur(h);if(g.kind==="create"){if(w!==void 0)throw new C("PLAN_PRECONDITION_FAILED","Create target now exists",g.path,f)}else if(w===void 0||w.digest!==g.baseDigest)throw new C("PLAN_PRECONDITION_FAILED","Target no longer matches plan base digest",g.path,f);let _={kind:"absent"};if(w!==void 0){if(d+=w.bytes.byteLength,w.bytes.byteLength>s||d>c)throw new C("PREIMAGE_LIMIT_EXCEEDED","Preimage size limit exceeded",g.path,f);let b=G.join(a.preimages,`${f}.bin`);await Tn(b,w.bytes,384,ot(t?.durabilityTrace,"prepare","preimage",`${o}:preimage:${f}`)),p.push(f),await aa(t,"preimage-written-pending-directory-sync",f),_={kind:"present",digest:w.digest,mode:w.mode,preimageDigest:v(w.bytes)}}l.push({index:f,path:g.path,kind:g.kind,before:_,...g.desiredDigest===void 0?{}:{desiredDigest:g.desiredDigest},status:"pending"})}if(p.length>0){await Ze(a.preimages,ot(t?.durabilityTrace,"prepare","directory",`${o}:preimages-directory-batch`));for(let f of p)await aa(t,"preimage-persisted",f)}let u=mc({schemaVersion:1,transactionId:o,planId:e.plan.planId,approvedPlanId:e.approvedPlanId,projectRootDigest:v(r),state:"prepared",createdAt:e.now,updatedAt:e.now,operations:l});return await fc(a.journal,u,ot(t?.durabilityTrace,"prepare","journal",`${o}:journal-prepared`)),Vt.set(o,{desiredContents:e.desiredContents,journal:u}),await aa(t,"journal-prepared"),yk(r,e.plan,o)}catch(u){if(u instanceof la)throw Vt.delete(o),new C("RECOVERY_REQUIRED","Prepare was interrupted; recovery is required");try{m&&await uc(a.transactionDirectory,{recursive:!0,force:!0}),await cr(a.lock),await Ze(a.platformDirectory)}catch{throw new C("RECOVERY_REQUIRED","Prepare failed and transaction lock could not be released")}throw u}}async function Jr(e){return wk(e)}async function vk(e,t,r,n){return Mt(e.journal,{...t,state:"recovery-required",updatedAt:new Date().toISOString(),failure:{code:"APPLY_INTERRUPTED",...r===void 0?{}:{operationIndex:r}}},ot(n,"apply","journal",`${t.transactionId}:recovery-required`))}async function Ik(e,t,r,n,i,a){let o=Br(e,n.path);await qr(e,n.path);let s=await Ur(o);if(n.before.kind==="absent"){if(s!==void 0)throw new C("PLAN_PRECONDITION_FAILED","Create target changed after prepare",n.path,n.index)}else if(s===void 0||s.digest!==n.before.digest)throw new C("PLAN_PRECONDITION_FAILED","Target changed after prepare",n.path,n.index);if(n.kind==="remove"){let p=G.join(t.quarantine,`${n.index}.bin`),m=ot(a?.durabilityTrace,"apply","target",`${r}:target:${n.index}`);return await He({context:zr(m),operation:"rename",run:()=>ca(o,p)}),await a?.onCheckpoint?.("target-renamed-pending-directory-sync",n.index),[G.dirname(o),t.quarantine]}let c=i.get(n.path);if(c===void 0||v(c)!==n.desiredDigest)throw new C("DESIRED_CONTENT_MISMATCH","Desired bytes are missing or changed",n.path,n.index);await Mr(G.dirname(o),{recursive:!0}),await qr(e,n.path);let d=G.join(G.dirname(o),`.dyyto-${r}-${n.index}.tmp`),l=ot(a?.durabilityTrace,"apply","target",`${r}:target:${n.index}`);return await Tn(d,c,n.before.kind==="present"?n.before.mode&511:420,l),await a?.onCheckpoint?.("temporary-file-synced",n.index),await He({context:zr(l),operation:"rename",bytes:c.byteLength,run:()=>ca(d,o)}),await a?.onCheckpoint?.("target-renamed-pending-directory-sync",n.index),[G.dirname(o)]}async function bk(e,t){let r=Vt.get(e.transactionId);if(r===void 0||e[Ru]!==!0)throw new C("PLAN_PRECONDITION_FAILED","Prepared transaction is not active");let n=Cn(e.projectRoot,e.plan.planId),i=await Mt(n.journal,{...r.journal,state:"applying",updatedAt:new Date().toISOString()},ot(t?.durabilityTrace,"apply","journal",`${e.transactionId}:applying`));try{await t?.onCheckpoint?.("prepared");let a=new Map;for(let o=0;o<i.operations.length;o+=Eu){let s=i.operations.slice(o,o+Eu),c=await Promise.allSettled(s.map(l=>Ik(e.projectRoot,n,e.transactionId,l,r.desiredContents,t))),d=c.find(l=>l.status==="rejected");if(d?.status==="rejected")throw d.reason;for(let l of c)if(l.status==="fulfilled")for(let p of l.value)a.has(p)||a.set(p,ot(t?.durabilityTrace,"apply","directory",`${e.transactionId}:target-directory-batch`))}for(let[o,s]of a)await Ze(o,s);for(let o of i.operations)await t?.onCheckpoint?.("target-renamed",o.index),o.status="applied",await t?.onCheckpoint?.("operation-applied",o.index);i=await Mt(n.journal,{...i,operations:i.operations,updatedAt:new Date().toISOString()},ot(t?.durabilityTrace,"apply","journal",`${e.transactionId}:operation-batch`));for(let o of i.operations)await t?.onCheckpoint?.("operation-journaled",o.index);return i=await Mt(n.journal,{...i,state:"applied",updatedAt:new Date().toISOString()},ot(t?.durabilityTrace,"apply","journal",`${e.transactionId}:applied`)),await t?.onCheckpoint?.("applied"),await cr(n.lock),await Ze(n.platformDirectory),Vt.delete(e.transactionId),lr(i)}catch(a){throw i=await vk(n,i,a instanceof C?a.operationIndex:void 0,t?.durabilityTrace),Vt.set(e.transactionId,{desiredContents:r.desiredContents,journal:i}),new C("RECOVERY_REQUIRED","Apply was interrupted; recovery is required")}}async function Gr(e){return bk(e)}function lr(e){return{transactionId:e.transactionId,planId:e.planId,state:e.state,operations:e.operations}}async function _t(e){let t=await ua(e.projectRoot),r=Cn(t,e.planId);if(!await kt(r.journal)){if(!await kt(r.lock))return null;let n=await sa(r.lock);return n.planId!==e.planId?null:{transactionId:n.transactionId,planId:n.planId,state:"preparing",operations:[]}}return lr(await gc(r.journal))}async function kk(e,t,r){await Mr(G.dirname(e),{recursive:!0});let n=G.join(G.dirname(e),`.dyyto-recover-${Fr()}.tmp`);await Tn(n,t,r&511),await ca(n,e),await lk(e,r&511),await Ze(G.dirname(e))}async function _k(e){let t=await ua(e.projectRoot),r=Cn(t,e.planId);if(!await kt(r.journal)){if(!await kt(r.lock))throw new C("JOURNAL_CORRUPTED","No transaction record exists");let i=await sa(r.lock);if(i.planId!==e.planId)throw new C("TRANSACTION_ACTIVE","Transaction lock belongs to another plan");await uc(r.transactionDirectory,{recursive:!0,force:!0}),await Mr(r.transactionDirectory,{recursive:!0,mode:448});let a=mc({schemaVersion:1,transactionId:i.transactionId,planId:i.planId,approvedPlanId:i.planId,projectRootDigest:v(t),state:"recovered",createdAt:i.startedAt,updatedAt:e.now,operations:[]});return await fc(r.journal,a),await cr(r.lock),await Ze(r.platformDirectory),lr(a)}let n=await gc(r.journal);if(n.state==="recovered")return lr(n);if(n.state==="applied"){for(let i of n.operations){let a=await Ur(Br(t,i.path));if(!(i.kind==="remove"?a===void 0:a?.digest===i.desiredDigest))throw new C("RECOVERY_CONFLICT","Completed transaction target changed before lock cleanup",i.path,i.index)}if(await kt(r.lock)){let i=await sa(r.lock);if(i.transactionId!==n.transactionId||i.planId!==n.planId)throw new C("TRANSACTION_ACTIVE","Transaction lock belongs to another transaction");await cr(r.lock),await Ze(r.platformDirectory)}return Vt.delete(n.transactionId),lr(n)}if(n.projectRootDigest!==v(t))throw new C("JOURNAL_CORRUPTED","Journal belongs to a different project root");if(await kt(r.lock)){let i=await sa(r.lock);if(i.transactionId!==n.transactionId||i.planId!==n.planId)throw new C("TRANSACTION_ACTIVE","Transaction lock belongs to another transaction")}else await hc(r.lock,{schemaVersion:1,transactionId:n.transactionId,planId:n.planId,startedAt:e.now,nonce:Fr()});n=await Mt(r.journal,{...n,state:"recovering",updatedAt:e.now});for(let i of[...n.operations].reverse()){if(i.status==="restored")continue;let a=Br(t,i.path);if(await qr(t,i.path),i.kind!=="remove"){let s=G.join(G.dirname(a),`.dyyto-${n.transactionId}-${i.index}.tmp`);if(await kt(s)){if((await Ur(s))?.digest!==i.desiredDigest)throw new C("RECOVERY_CONFLICT","Transaction temporary file was modified externally",i.path,i.index);await cr(s),await Ze(G.dirname(s))}}let o=await Ur(a);if(i.before.kind==="absent"){if(o!==void 0){if(o.digest!==i.desiredDigest)throw new C("RECOVERY_CONFLICT","Recovery would overwrite external content",i.path,i.index);await cr(a),await Ze(G.dirname(a))}}else if(o?.digest!==i.before.digest){let s=G.join(r.quarantine,`${i.index}.bin`),c=o?.digest===i.desiredDigest,d=i.kind==="remove"&&o===void 0&&await kt(s),l=e.approvedConflicts?.find(m=>m.path===i.path&&m.currentDigest===o?.digest);if(!c&&!d&&!l)throw new C("RECOVERY_CONFLICT","Recovery would overwrite external content",i.path,i.index);let p=await pa(G.join(r.preimages,`${i.index}.bin`));if(v(p)!==i.before.preimageDigest)throw new C("JOURNAL_CORRUPTED","Preimage digest is invalid",i.path,i.index);await kk(a,p,i.before.mode),d&&await uc(s,{force:!0})}i.status="restored",n=await Mt(r.journal,{...n,operations:n.operations,updatedAt:e.now}),await e.hooks?.onCheckpoint?.("operation-journaled",i.index)}return n=await Mt(r.journal,{...n,state:"recovered",updatedAt:e.now}),await cr(r.lock),await Ze(r.platformDirectory),Vt.delete(n.transactionId),lr(n)}async function xn(e){return _k(e)}async function yc(e){let t=await ua(e.projectRoot),r=Cn(t,e.planId),n=await gc(r.journal);if(n.state==="recovered")return lr(n);if(n.state!=="applied")throw new C("PLAN_PRECONDITION_FAILED","Only an applied transaction can be rolled back");let i;for(let a of n.operations){let o=await Ur(Br(t,a.path)),s=a.kind==="remove"?o===void 0:o?.digest===a.desiredDigest,c=a.before.kind==="absent"?o===void 0:o?.digest===a.before.digest;if(!s&&!c){i=a;break}}if(await hc(r.lock,{schemaVersion:1,transactionId:n.transactionId,planId:n.planId,startedAt:e.now,nonce:Fr()}),n=await Mt(r.journal,{...n,state:"recovery-required",updatedAt:e.now,failure:{code:e.failureCode}}),i!==void 0)throw new C("RECOVERY_CONFLICT","Rollback would overwrite external content",i.path,i.index);return Vt.set(n.transactionId,{desiredContents:new Map,journal:n}),xn({projectRoot:t,planId:e.planId,now:e.now})}var we=class extends Error{code;constructor(t,r){super(r),this.code=t}},Ln=class extends Error{};function qn(e,t){let r=ye.join(e,".dyyto"),n=ye.join(r,"metadata-transactions",t);return{platformDirectory:r,evidenceDirectory:ye.join(r,"evidence"),lockFile:ye.join(r,"project-lock.json"),transactionLock:ye.join(r,"metadata-lock.json"),transactionDirectory:n,journal:ye.join(n,"journal.json")}}async function qt(e){try{return await Ek(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Et(e,t,r){return e===void 0?void 0:{sink:e,category:t,barrierId:r}}function ha(e,t=!1){if(e!==void 0)return{sink:e.sink,phase:"metadata",pathCategory:t?"directory":e.category,barrierId:e.barrierId}}async function ya(e,t){let r=await Pu(e,ma.O_RDONLY);try{await He({context:ha(t,!0),operation:"directory-sync",run:()=>r.sync()})}finally{await r.close()}}async function Ic(e,t,r){let n=await Pu(e,ma.O_CREAT|ma.O_EXCL|ma.O_WRONLY,384);try{await He({context:ha(r),operation:"write",bytes:t.byteLength,run:()=>n.writeFile(t)}),await He({context:ha(r),operation:"file-sync",bytes:t.byteLength,run:()=>n.sync()})}finally{await n.close()}}async function Vn(e,t,r){let n=ye.dirname(e),i=ye.join(n,`.tmp-${vc()}`),a=Buffer.from(`${JSON.stringify(t,null,2)}
|
|
17
|
-
`);await Ic(i,a,r),await He({context:ha(r),operation:"rename",bytes:a.byteLength,run:()=>Ak(i,e)}),await ya(n,r)}function bc(e){return{...e,journalDigest:v(E(e))}}async function fa(e,t,r){let{journalDigest:n,...i}=t,a=bc(i);return await Vn(e,a,r),a}async function
|
|
18
|
-
`),r),await ya(ye.dirname(e),r)}catch(n){throw n.code==="EEXIST"?new we("METADATA_TRANSACTION_ACTIVE","Another metadata transaction is active"):n}}function
|
|
19
|
-
`),r),await ya(e,r)}async function Pk(e,t,r,n){if(await qt(e)){let i=Te(JSON.parse(await Mn(e,"utf8")));if(E(i)===E(t))return;if(r===void 0||v(E(i))!==r)throw new we("PROJECT_STATE_CHANGED","The project lock changed before metadata commit");await Vn(e,t,n);return}await Vn(e,t,n)}async function ga(e,t){try{await e?.onCheckpoint?.(t)}catch(r){throw new Ln("Simulated metadata crash",{cause:r})}}async function _c(e,t,r){let n=qn(e,t.planId),i=t;try{for(let a of i.evidence)await Rk(n.evidenceDirectory,a,Et(r?.durabilityTrace,"evidence",`${i.transactionId}:evidence`));return i=await fa(n.journal,{...i,state:"evidence-written",updatedAt:new Date().toISOString()},Et(r?.durabilityTrace,"journal",`${i.transactionId}:evidence-written`)),await ga(r,"evidence-written"),await Pk(n.lockFile,i.lock,i.previousLockDigest,Et(r?.durabilityTrace,"lock",`${i.transactionId}:project-lock`)),i=await fa(n.journal,{...i,state:"lock-written",updatedAt:new Date().toISOString()},Et(r?.durabilityTrace,"journal",`${i.transactionId}:lock-written`)),await ga(r,"lock-written"),i=await fa(n.journal,{...i,state:"committed",updatedAt:new Date().toISOString()},Et(r?.durabilityTrace,"journal",`${i.transactionId}:committed`)),await ga(r,"committed"),await wc(n.transactionLock),await ya(n.platformDirectory,Et(r?.durabilityTrace,"directory",`${i.transactionId}:unlock`)),i.lock}catch(a){if(a instanceof Ln)throw new we("METADATA_RECOVERY_REQUIRED","Metadata commit was interrupted");try{await fa(n.journal,{...i,state:"recovery-required",updatedAt:new Date().toISOString()},Et(r?.durabilityTrace,"journal",`${i.transactionId}:recovery-required`))}catch{}throw a}}async function Nk(e){let t=await dr(ye.resolve(e.projectRoot)),r=e.transactionRoot===void 0?t:await dr(ye.resolve(e.transactionRoot));if((await _t({projectRoot:r,planId:e.plan.planId}))?.state!=="applied")throw new we("APPLY_NOT_COMPLETED","The filesystem transaction is not applied");let i;try{i=await sr({projectRoot:t,expectedAssets:e.expectedAssets??e.release.assets.map(f=>({path:f.path,digest:f.digest}))})}catch{throw new we("PROJECT_STATE_CHANGED","Managed project assets no longer match the approved plan")}let o=
|
|
20
|
-
`)}async function Tk(e,t=!1){let r=ie.resolve(e),n=await yt(r).catch(()=>null);if(n===null||!n.isDirectory()||n.isSymbolicLink())throw new he("TARGET_INVALID","Workspace target must be a real existing directory");let i=await wt(r);for(let a of t?["AGENTS.md","README.md"]:["package.json","pnpm-workspace.yaml"]){let o=await yt(ie.join(i,a)).catch(()=>null);if(o===null||!o.isFile()||o.isSymbolicLink())throw new he("WORKSPACE_MARKER_MISSING",`Existing workspace must contain a real ${a}`)}if(await yt(ie.join(i,"project-capabilities.json")).catch(()=>null))throw new he("MANIFEST_EXISTS","Project manifest already exists");return i}async function xk(e,t){let r=ie.resolve(e),n=await yt(r).catch(()=>null);if(n===null||!n.isDirectory()||n.isSymbolicLink())throw new he("TARGET_INVALID","Project target must be a real existing directory");let i=await wt(r);for(let a of t){let o=await yt(ie.join(i,a)).catch(()=>null);if(o===null||!o.isFile()||o.isSymbolicLink())throw new he("WORKSPACE_MARKER_MISSING",`Existing project must contain a real ${a}`)}if(await yt(ie.join(i,"project-capabilities.json")).catch(()=>null))throw new he("MANIFEST_EXISTS","Project manifest already exists");return i}async function
|
|
21
|
-
`),i=r.capabilities[0],a=De({action:"adopt",capability:{schemaVersion:1,capabilityId:i.capabilityId,version:i.version,integrity:e.capabilityIntegrity,assets:[],verifiers:[]},changes:[{path:"project-capabilities.json",kind:"create",ownership:"owned-file",desiredDigest:v(n)}],observedAssets:[{path:"project-capabilities.json",exists:!1}],generatedAt:e.generatedAt,expiresAt:e.expiresAt});return{projectRoot:t,plan:a,desiredContents:new Map([["project-capabilities.json",n]])}}async function
|
|
22
|
-
`)}catch(i){throw i.code==="EEXIST"?new he("MANIFEST_EXISTS","Project manifest already exists"):i}return{projectRoot:r,manifest:t}}function Un(e){let{planId:t,...r}=e;if(ra(r)!==e.planId)throw new he("PLAN_INTEGRITY_INVALID","Saved plan integrity is invalid")}async function Mk(e){let t=await wt(ie.resolve(e.projectRoot)),r=Lt(e.plan);Un(r);let n=ie.join(t,".dyyto","plans");await
|
|
23
|
-
`)}catch(a){if(a.code!=="EEXIST")throw a;let o=Lt(JSON.parse(await Nc(i,"utf8")));if(Un(o),E(o)!==E(r))throw new he("PLAN_INTEGRITY_INVALID","Plan ID content mismatch")}return i}function Tu(e){return E({action:e.action,state:e.state,capability:e.capability,operations:e.operations,packageAdoption:e.packageAdoption})}async function pr(e){let t=await wt(ie.resolve(e.projectRoot)),r=e.transactionRoot===void 0?t:await wt(ie.resolve(e.transactionRoot)),n=Lt(e.plan);Un(n);let i=ie.join(t,".dyyto","plans"),a=await wa(i).catch(s=>{if(s.code==="ENOENT")return[];throw s}),o=[];for(let s of a.filter(c=>c.endsWith(".json")).sort()){let c=Lt(JSON.parse(await Nc(ie.join(i,s),"utf8")));Un(c),!await yt(ie.join(r,".dyyto","transactions",c.planId)).then(()=>!0).catch(l=>l.code==="ENOENT"?!1:Promise.reject(l))&&Date.parse(c.expiresAt)>Date.parse(e.now)&&Tu(c)===Tu(n)&&o.push(c)}return o.sort((s,c)=>s.generatedAt.localeCompare(c.generatedAt)),o[0]!==void 0?o[0]:(await Mk({projectRoot:t,plan:n}),n)}async function Fn(e){let t=await wt(ie.resolve(e.projectRoot)),r=ie.join(t,".dyyto","plans",`${e.planId}.json`);try{let n=Lt(JSON.parse(await Nc(r,"utf8")));if(Un(n),n.planId!==e.planId)throw new he("PLAN_INTEGRITY_INVALID","Saved plan identity mismatch");return n}catch(n){throw n.code==="ENOENT"?new he("PLAN_NOT_FOUND","Saved plan was not found"):n}}async function Ia(e,t=[],r,n=[]){let i=await wt(ie.resolve(e)),a=r===void 0?i:await wt(ie.resolve(r)),o=ie.join(i,".dyyto","plans"),s=await wa(o).catch(l=>{if(l.code==="ENOENT")return[];throw l}),c=[];for(let l of s.filter(p=>p.endsWith(".json")).sort()){let p=l.slice(0,-5),m=await Fn({projectRoot:i,planId:p}),u=await _t({projectRoot:a,planId:p}),f=await yt(ie.join(i,".dyyto","metadata-transactions",p)).then(()=>!0).catch(g=>g.code==="ENOENT"?!1:Promise.reject(g));u?.state==="applied"&&!f&&!t.includes(m.planId)&&(!n.includes(m.capability.capabilityId)||m.action==="upgrade"||m.action==="remove"||m.action==="adopt"&&m.operations.every(g=>g.disposition==="noop"))&&c.push(m)}let d=qk(c);if(d===void 0)throw new he("PLAN_NOT_FOUND",c.length===0?"No applied plan is available for verification":"More than one applied plan requires inspection before verification");return d}function qk(e){if(e.length===1)return e[0];if(e.length===0)return;let t=e[0]?.capability.capabilityId;if(!(t===void 0||e.some(r=>r.capability.capabilityId!==t)))return[...e].sort((r,n)=>r.generatedAt.localeCompare(n.generatedAt)).at(-1)}async function Dc(e){let t=await wt(ie.resolve(e)),r=ie.join(t,".dyyto","plans"),n=await wa(r).catch(a=>{if(a.code==="ENOENT")return[];throw a}),i=[];for(let a of n.filter(o=>o.endsWith(".json")).sort())i.push(await Fn({projectRoot:t,planId:a.slice(0,-5)}));return i}import{lstat as Uu,readFile as Uk,readdir as Fk,realpath as zk}from"node:fs/promises";import _e from"node:path";import{homedir as Fu}from"node:os";var Xe=class extends Error{code;constructor(t){super(t),this.code=t,this.name="WorkspaceTopologyError"}};async function zu(e){let t=_e.resolve(e),r=await Uu(t).catch(()=>null);if(!r?.isDirectory()||r.isSymbolicLink()||t===_e.parse(t).root||t===_e.resolve(Fu()))throw new Xe("WORKSPACE_PATH_UNSAFE");let n=await zk(t);if(n!==t)throw new Xe("WORKSPACE_PATH_UNSAFE");return n}async function ur(e){let t=await Uu(e).catch(()=>null);if(t!==null){if(!t.isFile()||t.isSymbolicLink())throw new Xe("WORKSPACE_PATH_UNSAFE");return Uk(e)}}function Bu(e){let t=e.split(/\r?\n/u),r=[],n=!1;for(let i of t){if(/^packages:\s*(?:#.*)?$/u.test(i)){n=!0;continue}if(!n)continue;let a=/^\s+-\s+["']?([^"'#]+?)["']?\s*(?:#.*)?$/u.exec(i);if(a){r.push(a[1].trim().replace(/^\.\//u,"").replace(/\/$/u,""));continue}if(i.trim()&&!/^\s/u.test(i))break}if(r.length===0)throw new Xe("WORKSPACE_MANIFEST_INVALID");return r}function Bk(e,t){if(e.includes("**")){let r=e.split("**",1)[0].replace(/\/$/u,"");return t===r||t.startsWith(`${r}/`)}if(e.endsWith("/*")){let r=e.slice(0,-2);return t.startsWith(`${r}/`)&&!t.slice(r.length+1).includes("/")}return e===t}async function Ju(e){let t=await zu(e),r=await ur(_e.join(t,"pnpm-workspace.yaml"));if(!r)throw new Xe("WORKSPACE_OWNER_MISSING");let n=new Map;for(let i of Bu(r.toString("utf8"))){let a=[];if(i.endsWith("/*")&&!i.slice(0,-2).includes("*")){let o=i.slice(0,-2),s=await Fk(_e.join(t,...o.split("/")),{withFileTypes:!0}).catch(()=>[]);for(let c of s)c.isDirectory()&&!c.isSymbolicLink()&&a.push(`${o}/${c.name}`)}else if(!i.includes("*"))a.push(i);else throw new Xe("WORKSPACE_MANIFEST_INVALID");for(let o of a){let s=await ur(_e.join(t,...o.split("/"),"package.json"));s&&n.set(o,s)}}return Object.freeze([...n].sort(([i],[a])=>i.localeCompare(a)).map(([i,a])=>Object.freeze({relativeRoot:i,bytes:a})))}async function Kr(e){let t=await zu(e);if(await ur(_e.join(t,"pnpm-lock.yaml")))return Object.freeze({schemaVersion:1,mode:"standalone",transactionRoot:t,unitRoot:t,unitRelativeRoot:".",unitImporterId:".",lockfilePath:"pnpm-lock.yaml"});if(await ur(_e.join(t,"pnpm-workspace.yaml")))throw new Xe("WORKSPACE_NESTED_UNSUPPORTED");let r=_e.dirname(t),n;for(;r!==_e.parse(r).root&&r!==_e.resolve(Fu());){let a=await ur(_e.join(r,"pnpm-workspace.yaml"));if(a){if(n)throw new Xe("WORKSPACE_NESTED_UNSUPPORTED");n={root:r,manifest:a};break}r=_e.dirname(r)}if(!n||!await ur(_e.join(n.root,"pnpm-lock.yaml"))||!await ur(_e.join(n.root,"project-capabilities.json")))throw new Xe("WORKSPACE_OWNER_MISSING");let i=_e.relative(n.root,t).split(_e.sep).join("/");if(!i||i.startsWith("../")||Bu(n.manifest.toString("utf8")).filter(a=>Bk(a,i)).length!==1)throw new Xe("WORKSPACE_UNIT_NOT_DECLARED");return Object.freeze({schemaVersion:1,mode:"pnpm-shared-lockfile",transactionRoot:n.root,unitRoot:t,unitRelativeRoot:i,unitImporterId:i,workspaceManifestPath:"pnpm-workspace.yaml",workspaceManifestDigest:v(n.manifest),lockfilePath:"pnpm-lock.yaml"})}var Gu=new Set(["preparing","prepared","applying","recovery-required","recovering"]);async function Sc(e){let t=await Dc(e);for(let r of t){let n=await _t({projectRoot:e,planId:r.planId});if(n!==null&&Gu.has(n.state))return{required:!0,kind:"filesystem",planId:r.planId,state:n.state}}for(let r of t){let n=await Pc({projectRoot:e,planId:r.planId});if(n!==null&&n.state!=="committed")return{required:!0,kind:"metadata",planId:r.planId,state:n.state}}return{required:!1}}async function Jk(e){let t=await Sc(e.projectRoot);if(!t.required)return{kind:"none",state:"not-required"};if(t.kind==="filesystem"){let r=await xn({projectRoot:e.projectRoot,planId:t.planId,now:e.now});return{kind:"filesystem",planId:t.planId,state:r.state}}return await Rc({projectRoot:e.projectRoot,planId:t.planId}),{kind:"metadata",planId:t.planId,state:"committed"}}async function Wu(e){let t=await Jk(e);if(t.kind!=="none")return t;let r=await Kr(e.projectRoot).catch(()=>{});if(r?.mode!=="pnpm-shared-lockfile")return t;let n=new Set((await Dc(e.projectRoot)).map(c=>c.planId)),i=await import("node:fs/promises").then(({readFile:c})=>c(`${r.transactionRoot}/.dyyto/transaction-lock.json`,"utf8")).catch(c=>c.code==="ENOENT"?void 0:Promise.reject(c));if(!i)return t;let a;try{let c=JSON.parse(i);if(typeof c.planId!="string"||!/^sha256:[a-f0-9]{64}$/u.test(c.planId)||!n.has(c.planId))return t;a=c.planId}catch{return t}let o=await _t({projectRoot:r.transactionRoot,planId:a});if(!o||!Gu.has(o.state))return t;let s=await xn({projectRoot:r.transactionRoot,planId:a,now:e.now});return{kind:"filesystem",planId:a,state:s.state}}import{lstat as Gk,readFile as jc,realpath as Ku}from"node:fs/promises";import zn from"node:path";var Wk=new Set(["MIT","Apache-2.0","UNLICENSED"]),Kk=new Set(["public","restricted","private"]),Yk=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/,Hk=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;function Zk(e){let t;try{t=new URL(e)}catch{throw new M("CONSUMER_PROFILE_UNSUPPORTED","repository must be a canonical public HTTPS URL")}if(t.protocol!=="https:"||t.username.length>0||t.password.length>0||t.search.length>0||t.hash.length>0||t.pathname==="/"||t.pathname.includes(".."))throw new M("CONSUMER_PROFILE_UNSUPPORTED","repository must be a canonical public HTTPS URL");t.pathname=t.pathname.replace(/\/$/,"").replace(/\.git$/,"");let r=t.href.replace(/\/$/,"");if(r!==e)throw new M("CONSUMER_PROFILE_UNSUPPORTED","repository URL must already be canonical");return r}function fr(e){if(e.profile?.id!=="workspace-node-application"&&e.profile?.id!=="workspace-web-application"&&e.profile?.id!=="workspace-expo-application"&&e.profile?.id!=="nextjs-full-stack-application")throw new M("CONSUMER_PROFILE_UNSUPPORTED","Manifest must select a workspace application profile");let t=Object.keys(e.profile.parameters),r=e.profile.parameters.name;if(t.length!==1||t[0]!=="name"||r===void 0||r.length>128||!/^[a-z0-9][a-z0-9._-]*$/.test(r))throw new M("CONSUMER_PROFILE_UNSUPPORTED","Application parameters must contain one valid lowercase name");return{name:r}}function Ft(e,t="standalone-npm-package"){if(e.profile?.id!==t)throw new M("CONSUMER_PROFILE_UNSUPPORTED",`Manifest must select ${t} profile`);let r=e.profile.parameters,n=Object.keys(r).sort(),i=e.capabilities.find(m=>m.capabilityId===`foundation.${t}`)?.version,a=i==="1.1.0"||i==="1.2.0"||t==="react-component-library",o=a?["license","name","publishAccess","repository","version"]:["license","name","publishAccess","version"];if(n.length!==o.length||n.some((m,u)=>m!==o[u]))throw new M("CONSUMER_PROFILE_UNSUPPORTED","Standalone npm profile parameters must be exact");let{name:s,version:c,license:d,publishAccess:l,repository:p}=r;if(s===void 0||s.length>214||!Yk.test(s))throw new M("CONSUMER_PROFILE_UNSUPPORTED","npm package name must be a valid lowercase name");if(c===void 0||!Hk.test(c))throw new M("CONSUMER_PROFILE_UNSUPPORTED","npm package version must be a stable SemVer");if(d===void 0||!Wk.has(d))throw new M("CONSUMER_PROFILE_UNSUPPORTED","license must be MIT, Apache-2.0, or UNLICENSED");if(l===void 0||!Kk.has(l))throw new M("CONSUMER_PROFILE_UNSUPPORTED","publish access must be public, restricted, or private");if(l==="restricted"&&!s.startsWith("@"))throw new M("CONSUMER_PROFILE_UNSUPPORTED","restricted access requires a scoped package name");return{name:s,version:c,license:d,publishAccess:l,...a?{repository:Zk(p)}:{}}}function $c(e){let t={name:e.name,version:e.version,...e.publishAccess==="private"?{private:!0}:{},license:e.license,...e.repository===void 0?{}:{repository:{type:"git",url:e.repository}},type:"module",sideEffects:!1,main:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"}},files:["dist"],engines:{node:">=24.18.0 <25",pnpm:"11.21.0"},packageManager:"pnpm@11.21.0",scripts:{build:"tsc -p tsconfig.build.json",typecheck:"tsc --noEmit -p tsconfig.json",test:"vitest run",check:"corepack pnpm typecheck && corepack pnpm test",prepack:"corepack pnpm check && corepack pnpm build"},...e.publishAccess==="private"?{}:{publishConfig:{access:e.publishAccess}},devDependencies:{"@types/node":"24.10.13",typescript:"6.0.3",vitest:"4.1.10"}};return Buffer.from(`${JSON.stringify(t,null,2)}
|
|
14
|
+
`}let s=e.source.indexOf(t),c=e.source.indexOf(r,s)+r.length,d=e.source.slice(s+t.length,c-r.length);if(/<!-- dyyto:(?:begin|end) /.test(d))throw new ht("Managed regions cannot overlap");return`${e.source.slice(0,s)}${o}${e.source.slice(c)}`}import bu from"node:path";var xt=class extends Error{assetPath;code="PLAN_PRECONDITION_FAILED";constructor(t,r){super(t),this.assetPath=r}};function ta(e){if(e.length===0||bu.posix.isAbsolute(e)||bu.win32.isAbsolute(e)||e.includes("\\")||e.split("/").some(t=>t===".."||t==="."))throw new xt("Asset path must be a normalized project-relative POSIX path",e)}function ek(e,t){ta(e.path);let r=e.kind==="merge"&&e.ownership==="managed-region"&&e.regionId!==void 0&&new RegExp(X).test(e.regionId);if((e.kind==="merge"||e.ownership==="managed-region"||e.regionId!==void 0)&&!r)throw new xt("Managed regions require merge ownership and a valid region identity",e.path);if(e.ownership==="user-file")return{...e,disposition:"conflict",conflictCode:"USER_OWNED"};let n=t?.exists??!1,i=t?.digest;return e.kind==="create"?n?e.desiredDigest!==void 0&&i===e.desiredDigest?{...e,disposition:"noop"}:{...e,disposition:"conflict",conflictCode:"UNEXPECTED_EXISTING"}:{...e,disposition:"ready"}:e.kind==="remove"&&!n?{...e,disposition:"noop"}:e.kind!=="remove"&&n&&e.desiredDigest===i?{...e,disposition:"noop"}:!n||e.baseDigest===void 0||i!==e.baseDigest?{...e,disposition:"conflict",conflictCode:"BASE_DIGEST_MISMATCH"}:{...e,disposition:"ready"}}function De(e){if(Number.isNaN(Date.parse(e.generatedAt))||Number.isNaN(Date.parse(e.expiresAt)))throw new xt("Plan timestamps must be valid ISO date-time values");if(Date.parse(e.expiresAt)<=Date.parse(e.generatedAt))throw new xt("Plan expiry must be later than generation time");let t=new Map;for(let s of e.observedAssets){if(ta(s.path),t.has(s.path))throw new xt("Observed asset paths must be unique",s.path);t.set(s.path,s)}let r=new Set,n=e.changes.map(s=>{if(r.has(s.path))throw new xt("Proposed change paths must be unique",s.path);return r.add(s.path),ek(s,t.get(s.path))}).sort((s,c)=>s.path.localeCompare(c.path)),i={action:e.action,capability:{capabilityId:e.capability.capabilityId,version:e.capability.version,integrity:e.capability.integrity},changes:e.changes,observedAssets:e.observedAssets,generatedAt:e.generatedAt,expiresAt:e.expiresAt,...e.packageAdoption===void 0?{}:{packageAdoption:e.packageAdoption}},a=v(E(i)),o={schemaVersion:1,action:e.action,state:n.some(s=>s.disposition==="conflict")?"conflicted":"reviewable",capability:i.capability,generatedAt:e.generatedAt,expiresAt:e.expiresAt,inputDigest:a,operations:n,...e.packageAdoption===void 0?{}:{packageAdoption:e.packageAdoption}};return{...o,planId:v(E(o))}}function ra(e){return v(E(e))}var ku=br(nr(),1);var Q={type:"string",pattern:ut},Lr={type:"string",pattern:X},or={type:"string",minLength:1,maxLength:128},ar={type:"string",minLength:1,maxLength:512,pattern:"^(?!/)(?!.*(?:^|/)\\.\\.(?:/|$))(?!.*\\\\).+$"},tk={$id:"https://schemas.dyyto.dev/platform/capability-release-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","capabilityId","version","integrity","assets","verifiers"],properties:{schemaVersion:{const:1},capabilityId:Lr,version:or,integrity:Q,assets:{type:"array",items:{type:"object",additionalProperties:!1,required:["path","ownership"],properties:{path:ar,ownership:{enum:["owned-file","managed-region","seed-file","shared-file","user-file"]},desiredDigest:Q}}},verifiers:{type:"array",items:{type:"object",additionalProperties:!1,required:["id","kind"],properties:{id:{type:"string",minLength:1,maxLength:128},kind:{enum:["command","file-digest"]}}}}}},rk={$id:"https://schemas.dyyto.dev/platform/project-manifest-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","capabilities"],properties:{schemaVersion:{const:1},template:{type:"object",additionalProperties:!1,required:["id","version"],properties:{id:Lr,version:or}},profile:{type:"object",additionalProperties:!1,required:["id","parameters"],properties:{id:{type:"string",pattern:X},parameters:{type:"object",minProperties:0,maxProperties:32,propertyNames:{pattern:"^[a-z][A-Za-z0-9]*$"},additionalProperties:{type:"string",maxLength:256}}}},capabilities:{type:"array",items:{type:"object",additionalProperties:!1,required:["capabilityId","version"],properties:{capabilityId:Lr,version:or}}}}},nk={$id:"https://schemas.dyyto.dev/platform/project-lock-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","capabilities"],properties:{schemaVersion:{const:1},capabilities:{type:"array",items:{type:"object",additionalProperties:!1,required:["capabilityId","version","integrity","appliedPlanId","assets","evidenceIds"],properties:{capabilityId:Lr,version:or,integrity:Q,appliedPlanId:Q,assets:{type:"array",items:{type:"object",additionalProperties:!1,required:["path","digest"],properties:{path:ar,digest:Q}}},evidenceIds:{type:"array",items:{type:"string",minLength:1,maxLength:256}}}}}}},ik={$id:"https://schemas.dyyto.dev/platform/evidence-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","evidenceId","capabilityId","capabilityVersion","verifierId","result","observedAt"],properties:{schemaVersion:{const:1},evidenceId:{type:"string",minLength:1,maxLength:256},capabilityId:Lr,capabilityVersion:or,verifierId:{type:"string",minLength:1,maxLength:128},result:{enum:["passed","failed"]},observedAt:{type:"string",format:"date-time"}}},ak={$id:"https://schemas.dyyto.dev/platform/change-plan-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","planId","action","state","capability","generatedAt","expiresAt","inputDigest","operations"],properties:{schemaVersion:{const:1},planId:Q,action:{enum:["adopt","upgrade","remove"]},state:{enum:["reviewable","conflicted"]},capability:{type:"object",additionalProperties:!1,required:["capabilityId","version","integrity"],properties:{capabilityId:Lr,version:or,integrity:Q}},generatedAt:{type:"string",format:"date-time"},expiresAt:{type:"string",format:"date-time"},inputDigest:Q,packageAdoption:{type:"object",additionalProperties:!1,required:["schemaVersion","packageJsonPreimageDigest","desiredPackageJsonDigest","lockfilePreimage","desiredLockfileDigest","registryRevisions","endpointBindings","sources","installPolicy"],properties:{schemaVersion:{enum:[1,2]},sourceChannel:{enum:["production","development"]},packageJsonPreimageDigest:Q,desiredPackageJsonDigest:Q,lockfilePreimage:{oneOf:[{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:{const:"absent"}}},{type:"object",additionalProperties:!1,required:["kind","digest"],properties:{kind:{const:"present"},digest:Q}}]},desiredLockfileDigest:Q,registryRevisions:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["registryId","revision"],properties:{registryId:{type:"string",minLength:1,maxLength:128},revision:Q}}},endpointBindings:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["registryId","registryConfigRevision","bindingDigest","expiresAt"],properties:{registryId:{type:"string",minLength:1,maxLength:128},registryConfigRevision:Q,bindingDigest:Q,expiresAt:{type:"string",format:"date-time"}}}},sources:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["registryId","packageName","version","integrity","tarballDigest","deliveryReceiptId","usage"],properties:{registryId:{type:"string",minLength:1,maxLength:128},packageName:{type:"string",pattern:"^@[a-z0-9][a-z0-9._-]*/[a-z0-9][a-z0-9._-]*$"},version:or,integrity:{type:"string",pattern:"^sha512-[A-Za-z0-9+/]+={0,2}$"},tarballDigest:Q,deliveryReceiptId:Q,usage:{enum:["runtime","development"]}}}},installPolicy:{type:"object",additionalProperties:!1,required:["ignoreScripts","allowWorkspaceProtocol","allowPublicRegistryFallback"],properties:{ignoreScripts:{const:!0},allowWorkspaceProtocol:{const:!1},allowPublicRegistryFallback:{const:!1}}},topology:{type:"object",additionalProperties:!1,required:["mode","unitRelativeRoot","unitImporterId","lockfilePath"],properties:{mode:{enum:["standalone","pnpm-shared-lockfile"]},unitRelativeRoot:ar,unitImporterId:ar,lockfilePath:{const:"pnpm-lock.yaml"},workspaceManifestPath:{const:"pnpm-workspace.yaml"},workspaceManifestDigest:Q}},preservedDependencies:{type:"array",items:{type:"object",additionalProperties:!1,required:["section","packageName","specifier"],properties:{section:{enum:["dependencies","devDependencies","optionalDependencies"]},packageName:{type:"string",minLength:1,maxLength:214},specifier:{type:"string",minLength:1,maxLength:512}}}},preservedImporterDigests:{type:"array",items:{type:"object",additionalProperties:!1,required:["importerId","preimageDigest","desiredDigest"],properties:{importerId:ar,preimageDigest:Q,desiredDigest:Q}}}},allOf:[{if:{properties:{schemaVersion:{const:1}},required:["schemaVersion"]},then:{properties:{topology:!1,preservedDependencies:!1,preservedImporterDigests:!1}}},{if:{properties:{schemaVersion:{const:2}},required:["schemaVersion"]},then:{required:["topology","preservedDependencies","preservedImporterDigests"]}}]},operations:{type:"array",items:{type:"object",additionalProperties:!1,required:["path","kind","ownership","disposition"],properties:{path:ar,kind:{enum:["create","replace","merge","remove"]},ownership:{enum:["owned-file","managed-region","seed-file","shared-file","user-file"]},desiredDigest:Q,baseDigest:Q,regionId:{type:"string",pattern:X},disposition:{enum:["ready","noop","conflict"]},conflictCode:{enum:["USER_OWNED","UNEXPECTED_EXISTING","BASE_DIGEST_MISMATCH"]}}}}}},ok={$id:"https://schemas.dyyto.dev/platform/transaction-journal-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","transactionId","planId","approvedPlanId","projectRootDigest","state","createdAt","updatedAt","operations","journalDigest"],properties:{schemaVersion:{const:1},transactionId:{type:"string",minLength:1,maxLength:128},planId:Q,approvedPlanId:Q,projectRootDigest:Q,state:{enum:["preparing","prepared","applying","applied","recovery-required","recovering","recovered"]},createdAt:{type:"string",format:"date-time"},updatedAt:{type:"string",format:"date-time"},operations:{type:"array",items:{type:"object",additionalProperties:!1,required:["index","path","kind","before","status"],properties:{index:{type:"integer",minimum:0},path:ar,kind:{enum:["create","replace","merge","remove"]},before:{oneOf:[{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:{const:"absent"}}},{type:"object",additionalProperties:!1,required:["kind","digest","mode","preimageDigest"],properties:{kind:{const:"present"},digest:Q,mode:{type:"integer",minimum:0,maximum:511},preimageDigest:Q}}]},desiredDigest:Q,status:{enum:["pending","applied","restored"]}}}},failure:{type:"object",additionalProperties:!1,required:["code"],properties:{code:{type:"string",minLength:1,maxLength:128},operationIndex:{type:"integer",minimum:0}}},journalDigest:Q}},ir=new ku.Ajv2020({allErrors:!0,strict:!0});ir.addFormat("date-time",{type:"string",validate:e=>!Number.isNaN(Date.parse(e))});var sc={capabilityRelease:ir.compile(tk),projectManifest:ir.compile(rk),projectLock:ir.compile(nk),evidence:ir.compile(ik),changePlan:ir.compile(ak),transactionJournal:ir.compile(ok)},oc=class extends Error{contract;issues;code="CONTRACT_INVALID";constructor(t,r){super(`Invalid ${t} contract`),this.contract=t,this.issues=r}};function cc(e,t,r){if(!t(r))throw new oc(e,t.errors??[]);return r}var G=e=>cc("projectManifest",sc.projectManifest,e);var Lt=e=>cc("changePlan",sc.changePlan,e),_u=e=>cc("transactionJournal",sc.transactionJournal,e);var M=class extends Error{code;assetPath;constructor(t,r,n){super(r),this.code=t,this.assetPath=n}};async function na(e){if(e.currentLock!==void 0){let a=await ia({...e,manifest:{schemaVersion:1,capabilities:[{capabilityId:e.release.release.capabilityId,version:e.release.release.version}]}});return{state:a.plan.state==="conflicted"?"drifted":"adopted",operations:a.plan.operations}}let t=await dc(Vr.resolve(e.projectRoot)),r=[],n=0,i=0;for(let a of e.release.release.assets){let o=await pc(t,a.path);o.exists&&(n+=1),o.digest===a.digest&&(i+=1),r.push({path:a.path,kind:"create",ownership:a.ownership,desiredDigest:a.ownership==="seed-file"&&o.digest?o.digest:a.digest,disposition:o.exists?a.ownership==="seed-file"||o.digest===a.digest?"noop":"conflict":"ready",...o.exists&&o.digest!==a.digest?{conflictCode:"UNEXPECTED_EXISTING"}:{}})}return n===0?{state:"planned",operations:r}:i===e.release.release.assets.length?{state:"applied-unverified",operations:r}:{state:"drifted",operations:r}}async function pc(e,t){let r=Vr.join(e,...t.split("/"));try{let n=await sk(r);if(!n.isFile()||n.isSymbolicLink())throw new M("PROJECT_STATE_INVALID","Blank profile target must be a regular file",t);return{path:t,exists:!0,digest:v(await lc(r))}}catch(n){if(n.code==="ENOENT")return{path:t,exists:!1};throw n}}async function sr(e){let t=await dc(Vr.resolve(e.projectRoot)),r=[];for(let n of e.expectedAssets){let i=await pc(t,n.path),a=i.exists&&i.digest===n.digest;if(n.ownership==="managed-region"&&n.regionId!==void 0&&i.exists)try{a=v(ea(await lc(Vr.join(t,...n.path.split("/")),"utf8"),n.regionId))===n.digest}catch{a=!1}if(!a)throw new M("PROJECT_STATE_INVALID","A managed project asset does not match the approved plan",n.path);r.push({path:n.path,digest:n.digest,...n.ownership===void 0?{}:{ownership:n.ownership},...n.regionId===void 0?{}:{regionId:n.regionId}})}return{assets:r,projectStateDigest:v(E(r))}}async function ia(e){let t=G(e.manifest);if(t.capabilities.filter(l=>l.capabilityId===e.release.release.capabilityId&&l.version===e.release.release.version).length!==1||t.capabilities.length!==1)throw new M("RELEASE_NOT_FOUND","Manifest must select exactly the loaded M3 capability release");let i=(e.currentLock===void 0?void 0:Te(e.currentLock))?.capabilities.find(l=>l.capabilityId===e.release.release.capabilityId);if(i!==void 0&&(i.version!==e.release.release.version||i.integrity!==e.release.release.integrity))throw new M("CONSUMER_PROFILE_UNSUPPORTED","M3 does not support upgrading a different locked release");let a=await dc(Vr.resolve(e.projectRoot)),o=[],s=[],c=new Map(e.release.contents);for(let l of e.release.release.assets){let p=await pc(a,l.path);if(o.push(p),p.exists&&i===void 0&&l.ownership!=="seed-file")throw new M("CONSUMER_PROFILE_UNSUPPORTED","Blank profile cannot adopt over an existing file without a lock",l.path);let m=l.ownership==="seed-file"&&p.digest?p.digest:l.digest;l.ownership==="seed-file"&&p.exists&&c.set(l.path,await lc(Vr.join(a,...l.path.split("/")))),s.push({path:l.path,kind:"create",ownership:l.ownership,desiredDigest:m})}let d={schemaVersion:1,capabilityId:e.release.release.capabilityId,version:e.release.release.version,integrity:e.release.release.integrity,assets:e.release.release.assets.map(l=>({path:l.path,ownership:l.ownership,desiredDigest:l.digest})),verifiers:e.release.release.verifiers.map(l=>({id:l.id,kind:"command"}))};return{manifest:t,release:e.release,plan:De({action:"adopt",capability:d,changes:s,observedAssets:o,generatedAt:e.generatedAt,expiresAt:e.expiresAt}),desiredContents:c}}import{chmod as lk,lstat as da,mkdir as Mr,open as Ru,readFile as pa,realpath as dk,rename as ca,rm as uc,unlink as cr}from"node:fs/promises";import{constants as oa}from"node:fs";import{homedir as pk}from"node:os";import J from"node:path";import{randomUUID as Fr}from"node:crypto";function ck(e){let t=e?.code;return typeof t=="string"&&/^[A-Z0-9_]+$/.test(t)?t:"UNKNOWN"}async function He(e){let t=process.hrtime.bigint();try{let r=await e.run();return await Eu(e.context,e.operation,e.bytes??0,t,"succeeded"),r}catch(r){throw await Eu(e.context,e.operation,e.bytes??0,t,"failed",ck(r)),r}}async function Eu(e,t,r,n,i,a){if(e?.sink===void 0)return;let o=process.hrtime.bigint(),s={schemaVersion:1,phase:e.phase,operation:t,pathCategory:e.pathCategory,bytes:r,barrierId:e.barrierId,startedMonotonicNs:n.toString(),completedMonotonicNs:o.toString(),result:i,...a===void 0?{}:{errorCategory:a}},c=Object.freeze({...s,eventId:v(E(s))});try{await e.sink(c)}catch{}}var Pu=Symbol("prepared-transaction"),Vt=new Map,uk=5*1024*1024,fk=25*1024*1024,Au=8,la=class extends Error{};async function aa(e,t,r){try{await e?.onCheckpoint?.(t,r)}catch(n){throw new la("Simulated prepare crash",{cause:n})}}var C=class extends Error{code;relativePath;operationIndex;constructor(t,r,n,i){super(r),this.code=t,this.relativePath=n,this.operationIndex=i}};function Cn(e,t){let r=J.join(e,".dyyto"),n=J.join(r,"transactions",t);return{platformDirectory:r,lock:J.join(r,"transaction-lock.json"),transactionDirectory:n,journal:J.join(n,"journal.json"),preimages:J.join(n,"preimages"),quarantine:J.join(n,"quarantine")}}async function kt(e){try{return await da(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function zr(e,t=!1){if(e?.sink!==void 0)return{sink:e.sink,phase:e.phase,pathCategory:t?"directory":e.category,barrierId:e.barrierId}}function ot(e,t,r,n){return e===void 0?void 0:{sink:e,phase:t,category:r,barrierId:n}}async function Ze(e,t){let r=await Ru(e,oa.O_RDONLY);try{await He({context:zr(t,!0),operation:"directory-sync",run:()=>r.sync()})}finally{await r.close()}}async function Tn(e,t,r=384,n){let i=await Ru(e,oa.O_CREAT|oa.O_EXCL|oa.O_WRONLY,r);try{await He({context:zr(n),operation:"write",bytes:t.byteLength,run:()=>i.writeFile(t)}),await He({context:zr(n),operation:"file-sync",bytes:t.byteLength,run:()=>i.sync()})}finally{await i.close()}}async function fc(e,t,r){let n=J.dirname(e),i=J.join(n,`.tmp-${Fr()}`),a=Buffer.from(`${JSON.stringify(t,null,2)}
|
|
15
|
+
`);await Tn(i,a,384,r),await He({context:zr(r),operation:"rename",bytes:a.byteLength,run:()=>ca(i,e)}),await Ze(n,r)}function mc(e){return{...e,journalDigest:v(E(e))}}function mk(e){let t;try{t=_u(e)}catch{throw new C("JOURNAL_CORRUPTED","Transaction journal shape is invalid")}let{journalDigest:r,...n}=t;if(r!==v(E(n)))throw new C("JOURNAL_CORRUPTED","Transaction journal digest or shape is invalid");let i=new Set;for(let[a,o]of t.operations.entries()){if(o.index!==a||i.has(o.path)||o.kind==="create"&&o.before.kind!=="absent"||o.kind!=="create"&&o.before.kind!=="present"||o.kind!=="remove"&&o.desiredDigest===void 0||o.kind==="remove"&&o.desiredDigest!==void 0)throw new C("JOURNAL_CORRUPTED","Transaction journal operation is inconsistent");i.add(o.path)}return t}async function gc(e){try{return mk(JSON.parse(await pa(e,"utf8")))}catch(t){throw t instanceof C?t:new C("JOURNAL_CORRUPTED","Transaction journal cannot be read")}}async function Mt(e,t,r){let{journalDigest:n,...i}=t,a=mc(i);return await fc(e,a,r),a}async function ua(e){let t=J.resolve(e),r=J.parse(t);if(t===r.root||t===J.resolve(pk()))throw new C("PROJECT_ROOT_UNSAFE","Project root cannot be the filesystem root or user home");let n=await da(t);if(!n.isDirectory()||n.isSymbolicLink())throw new C("PROJECT_ROOT_UNSAFE","Project root must be a real directory");let i=await dk(t);if(i!==t)throw new C("PROJECT_ROOT_UNSAFE","Project root cannot resolve through a symbolic link");return i}function Br(e,t){if((t===".dyyto"||t.startsWith(".dyyto/"))&&t!==".dyyto/application-config-binding.json"||t.length===0||J.posix.isAbsolute(t)||J.win32.isAbsolute(t)||t.includes("\\")||t.split("/").some(n=>n==="."||n===".."))throw new C("PROJECT_ROOT_UNSAFE","Target path is unsafe",t);let r=J.resolve(e,...t.split("/"));if(!r.startsWith(`${e}${J.sep}`))throw new C("PROJECT_ROOT_UNSAFE","Target escapes project root",t);return r}async function qr(e,t){let r=t.split("/"),n=e;for(let i of r){n=J.join(n,i);try{if((await da(n)).isSymbolicLink())throw new C("PATH_SYMLINK_UNSAFE","Symbolic links are not valid transaction targets",t)}catch(a){if(a.code==="ENOENT")return;throw a}}}async function Ur(e){try{let t=await da(e);if(!t.isFile()||t.isSymbolicLink())throw new C("PATH_SYMLINK_UNSAFE","Transaction target must be a regular file");let r=await pa(e);return{bytes:r,digest:v(r),mode:t.mode&511}}catch(t){if(t.code==="ENOENT")return;throw t}}function gk(e,t,r){Lt(e);let{planId:n,...i}=e;if(ra(i)!==e.planId)throw new C("PLAN_CONTENT_MISMATCH","Plan content does not match planId");if(e.planId!==t)throw new C("PLAN_APPROVAL_MISMATCH","Approval does not match planId");if(e.state!=="reviewable")throw new C("PLAN_PRECONDITION_FAILED","Only reviewable plans can be applied");if(Date.parse(e.expiresAt)<=Date.parse(r))throw new C("PLAN_EXPIRED","Plan has expired")}function hk(e){let t=e.operations.filter(r=>r.disposition==="ready");for(let r of t)if(!((r.ownership==="owned-file"||r.ownership==="seed-file")&&["create","replace","remove"].includes(r.kind)||r.ownership==="managed-region"&&r.kind==="merge"&&r.regionId!==void 0))throw new C("OPERATION_UNSUPPORTED","Operation ownership is not supported",r.path);return t}async function hc(e,t,r){try{await Tn(e,Buffer.from(`${JSON.stringify(t,null,2)}
|
|
16
|
+
`),384,r),await Ze(J.dirname(e),r)}catch(n){throw n.code==="EEXIST"?new C("TRANSACTION_ACTIVE","Another platform transaction is active"):n}}async function sa(e){try{let t=JSON.parse(await pa(e,"utf8"));if(t.schemaVersion!==1||typeof t.transactionId!="string"||typeof t.planId!="string"||typeof t.startedAt!="string"||typeof t.nonce!="string")throw new Error("invalid lock");return t}catch{throw new C("JOURNAL_CORRUPTED","Transaction lock is invalid")}}function yk(e,t,r){return{[Pu]:!0,projectRoot:e,plan:t,transactionId:r}}async function wk(e,t){gk(e.plan,e.approvedPlanId,e.now);let r=await ua(e.projectRoot),n=hk(e.plan),i=new Set(e.plan.operations.filter(u=>u.kind!=="remove"&&u.disposition!=="conflict").map(u=>u.path));for(let u of e.desiredContents.keys())if(!i.has(u))throw new C("DESIRED_CONTENT_MISMATCH","Desired content is not declared by the plan",u);for(let u of n)if(Br(r,u.path),await qr(r,u.path),u.kind!=="remove"){let f=e.desiredContents.get(u.path);if(f===void 0||v(f)!==u.desiredDigest)throw new C("DESIRED_CONTENT_MISMATCH","Desired content digest does not match the plan",u.path)}let a=Cn(r,e.plan.planId);await Mr(a.platformDirectory,{recursive:!0,mode:448}),await qr(r,".dyyto");let o=Fr();await hc(a.lock,{schemaVersion:1,transactionId:o,planId:e.plan.planId,startedAt:e.now,nonce:Fr()},ot(t?.durabilityTrace,"prepare","lock",`${o}:prepare-lock`));let s=e.limits?.maxFileBytes??uk,c=e.limits?.maxTransactionBytes??fk,d=0,l=[],p=[],m=!1;try{if(await aa(t,"lock-created"),await kt(a.transactionDirectory))throw new C("PLAN_PRECONDITION_FAILED","This plan already has a transaction record");await Mr(a.preimages,{recursive:!0,mode:448}),await Mr(a.quarantine,{recursive:!0,mode:448}),m=!0;for(let[f,g]of n.entries()){let h=Br(r,g.path);await qr(r,g.path);let w=await Ur(h);if(g.kind==="create"){if(w!==void 0)throw new C("PLAN_PRECONDITION_FAILED","Create target now exists",g.path,f)}else if(w===void 0||w.digest!==g.baseDigest)throw new C("PLAN_PRECONDITION_FAILED","Target no longer matches plan base digest",g.path,f);let _={kind:"absent"};if(w!==void 0){if(d+=w.bytes.byteLength,w.bytes.byteLength>s||d>c)throw new C("PREIMAGE_LIMIT_EXCEEDED","Preimage size limit exceeded",g.path,f);let b=J.join(a.preimages,`${f}.bin`);await Tn(b,w.bytes,384,ot(t?.durabilityTrace,"prepare","preimage",`${o}:preimage:${f}`)),p.push(f),await aa(t,"preimage-written-pending-directory-sync",f),_={kind:"present",digest:w.digest,mode:w.mode,preimageDigest:v(w.bytes)}}l.push({index:f,path:g.path,kind:g.kind,before:_,...g.desiredDigest===void 0?{}:{desiredDigest:g.desiredDigest},status:"pending"})}if(p.length>0){await Ze(a.preimages,ot(t?.durabilityTrace,"prepare","directory",`${o}:preimages-directory-batch`));for(let f of p)await aa(t,"preimage-persisted",f)}let u=mc({schemaVersion:1,transactionId:o,planId:e.plan.planId,approvedPlanId:e.approvedPlanId,projectRootDigest:v(r),state:"prepared",createdAt:e.now,updatedAt:e.now,operations:l});return await fc(a.journal,u,ot(t?.durabilityTrace,"prepare","journal",`${o}:journal-prepared`)),Vt.set(o,{desiredContents:e.desiredContents,journal:u}),await aa(t,"journal-prepared"),yk(r,e.plan,o)}catch(u){if(u instanceof la)throw Vt.delete(o),new C("RECOVERY_REQUIRED","Prepare was interrupted; recovery is required");try{m&&await uc(a.transactionDirectory,{recursive:!0,force:!0}),await cr(a.lock),await Ze(a.platformDirectory)}catch{throw new C("RECOVERY_REQUIRED","Prepare failed and transaction lock could not be released")}throw u}}async function Gr(e){return wk(e)}async function vk(e,t,r,n){return Mt(e.journal,{...t,state:"recovery-required",updatedAt:new Date().toISOString(),failure:{code:"APPLY_INTERRUPTED",...r===void 0?{}:{operationIndex:r}}},ot(n,"apply","journal",`${t.transactionId}:recovery-required`))}async function Ik(e,t,r,n,i,a){let o=Br(e,n.path);await qr(e,n.path);let s=await Ur(o);if(n.before.kind==="absent"){if(s!==void 0)throw new C("PLAN_PRECONDITION_FAILED","Create target changed after prepare",n.path,n.index)}else if(s===void 0||s.digest!==n.before.digest)throw new C("PLAN_PRECONDITION_FAILED","Target changed after prepare",n.path,n.index);if(n.kind==="remove"){let p=J.join(t.quarantine,`${n.index}.bin`),m=ot(a?.durabilityTrace,"apply","target",`${r}:target:${n.index}`);return await He({context:zr(m),operation:"rename",run:()=>ca(o,p)}),await a?.onCheckpoint?.("target-renamed-pending-directory-sync",n.index),[J.dirname(o),t.quarantine]}let c=i.get(n.path);if(c===void 0||v(c)!==n.desiredDigest)throw new C("DESIRED_CONTENT_MISMATCH","Desired bytes are missing or changed",n.path,n.index);await Mr(J.dirname(o),{recursive:!0}),await qr(e,n.path);let d=J.join(J.dirname(o),`.dyyto-${r}-${n.index}.tmp`),l=ot(a?.durabilityTrace,"apply","target",`${r}:target:${n.index}`);return await Tn(d,c,n.before.kind==="present"?n.before.mode&511:420,l),await a?.onCheckpoint?.("temporary-file-synced",n.index),await He({context:zr(l),operation:"rename",bytes:c.byteLength,run:()=>ca(d,o)}),await a?.onCheckpoint?.("target-renamed-pending-directory-sync",n.index),[J.dirname(o)]}async function bk(e,t){let r=Vt.get(e.transactionId);if(r===void 0||e[Pu]!==!0)throw new C("PLAN_PRECONDITION_FAILED","Prepared transaction is not active");let n=Cn(e.projectRoot,e.plan.planId),i=await Mt(n.journal,{...r.journal,state:"applying",updatedAt:new Date().toISOString()},ot(t?.durabilityTrace,"apply","journal",`${e.transactionId}:applying`));try{await t?.onCheckpoint?.("prepared");let a=new Map;for(let o=0;o<i.operations.length;o+=Au){let s=i.operations.slice(o,o+Au),c=await Promise.allSettled(s.map(l=>Ik(e.projectRoot,n,e.transactionId,l,r.desiredContents,t))),d=c.find(l=>l.status==="rejected");if(d?.status==="rejected")throw d.reason;for(let l of c)if(l.status==="fulfilled")for(let p of l.value)a.has(p)||a.set(p,ot(t?.durabilityTrace,"apply","directory",`${e.transactionId}:target-directory-batch`))}for(let[o,s]of a)await Ze(o,s);for(let o of i.operations)await t?.onCheckpoint?.("target-renamed",o.index),o.status="applied",await t?.onCheckpoint?.("operation-applied",o.index);i=await Mt(n.journal,{...i,operations:i.operations,updatedAt:new Date().toISOString()},ot(t?.durabilityTrace,"apply","journal",`${e.transactionId}:operation-batch`));for(let o of i.operations)await t?.onCheckpoint?.("operation-journaled",o.index);return i=await Mt(n.journal,{...i,state:"applied",updatedAt:new Date().toISOString()},ot(t?.durabilityTrace,"apply","journal",`${e.transactionId}:applied`)),await t?.onCheckpoint?.("applied"),await cr(n.lock),await Ze(n.platformDirectory),Vt.delete(e.transactionId),lr(i)}catch(a){throw i=await vk(n,i,a instanceof C?a.operationIndex:void 0,t?.durabilityTrace),Vt.set(e.transactionId,{desiredContents:r.desiredContents,journal:i}),new C("RECOVERY_REQUIRED","Apply was interrupted; recovery is required")}}async function Jr(e){return bk(e)}function lr(e){return{transactionId:e.transactionId,planId:e.planId,state:e.state,operations:e.operations}}async function _t(e){let t=await ua(e.projectRoot),r=Cn(t,e.planId);if(!await kt(r.journal)){if(!await kt(r.lock))return null;let n=await sa(r.lock);return n.planId!==e.planId?null:{transactionId:n.transactionId,planId:n.planId,state:"preparing",operations:[]}}return lr(await gc(r.journal))}async function kk(e,t,r){await Mr(J.dirname(e),{recursive:!0});let n=J.join(J.dirname(e),`.dyyto-recover-${Fr()}.tmp`);await Tn(n,t,r&511),await ca(n,e),await lk(e,r&511),await Ze(J.dirname(e))}async function _k(e){let t=await ua(e.projectRoot),r=Cn(t,e.planId);if(!await kt(r.journal)){if(!await kt(r.lock))throw new C("JOURNAL_CORRUPTED","No transaction record exists");let i=await sa(r.lock);if(i.planId!==e.planId)throw new C("TRANSACTION_ACTIVE","Transaction lock belongs to another plan");await uc(r.transactionDirectory,{recursive:!0,force:!0}),await Mr(r.transactionDirectory,{recursive:!0,mode:448});let a=mc({schemaVersion:1,transactionId:i.transactionId,planId:i.planId,approvedPlanId:i.planId,projectRootDigest:v(t),state:"recovered",createdAt:i.startedAt,updatedAt:e.now,operations:[]});return await fc(r.journal,a),await cr(r.lock),await Ze(r.platformDirectory),lr(a)}let n=await gc(r.journal);if(n.state==="recovered")return lr(n);if(n.state==="applied"){for(let i of n.operations){let a=await Ur(Br(t,i.path));if(!(i.kind==="remove"?a===void 0:a?.digest===i.desiredDigest))throw new C("RECOVERY_CONFLICT","Completed transaction target changed before lock cleanup",i.path,i.index)}if(await kt(r.lock)){let i=await sa(r.lock);if(i.transactionId!==n.transactionId||i.planId!==n.planId)throw new C("TRANSACTION_ACTIVE","Transaction lock belongs to another transaction");await cr(r.lock),await Ze(r.platformDirectory)}return Vt.delete(n.transactionId),lr(n)}if(n.projectRootDigest!==v(t))throw new C("JOURNAL_CORRUPTED","Journal belongs to a different project root");if(await kt(r.lock)){let i=await sa(r.lock);if(i.transactionId!==n.transactionId||i.planId!==n.planId)throw new C("TRANSACTION_ACTIVE","Transaction lock belongs to another transaction")}else await hc(r.lock,{schemaVersion:1,transactionId:n.transactionId,planId:n.planId,startedAt:e.now,nonce:Fr()});n=await Mt(r.journal,{...n,state:"recovering",updatedAt:e.now});for(let i of[...n.operations].reverse()){if(i.status==="restored")continue;let a=Br(t,i.path);if(await qr(t,i.path),i.kind!=="remove"){let s=J.join(J.dirname(a),`.dyyto-${n.transactionId}-${i.index}.tmp`);if(await kt(s)){if((await Ur(s))?.digest!==i.desiredDigest)throw new C("RECOVERY_CONFLICT","Transaction temporary file was modified externally",i.path,i.index);await cr(s),await Ze(J.dirname(s))}}let o=await Ur(a);if(i.before.kind==="absent"){if(o!==void 0){if(o.digest!==i.desiredDigest)throw new C("RECOVERY_CONFLICT","Recovery would overwrite external content",i.path,i.index);await cr(a),await Ze(J.dirname(a))}}else if(o?.digest!==i.before.digest){let s=J.join(r.quarantine,`${i.index}.bin`),c=o?.digest===i.desiredDigest,d=i.kind==="remove"&&o===void 0&&await kt(s),l=e.approvedConflicts?.find(m=>m.path===i.path&&m.currentDigest===o?.digest);if(!c&&!d&&!l)throw new C("RECOVERY_CONFLICT","Recovery would overwrite external content",i.path,i.index);let p=await pa(J.join(r.preimages,`${i.index}.bin`));if(v(p)!==i.before.preimageDigest)throw new C("JOURNAL_CORRUPTED","Preimage digest is invalid",i.path,i.index);await kk(a,p,i.before.mode),d&&await uc(s,{force:!0})}i.status="restored",n=await Mt(r.journal,{...n,operations:n.operations,updatedAt:e.now}),await e.hooks?.onCheckpoint?.("operation-journaled",i.index)}return n=await Mt(r.journal,{...n,state:"recovered",updatedAt:e.now}),await cr(r.lock),await Ze(r.platformDirectory),Vt.delete(n.transactionId),lr(n)}async function xn(e){return _k(e)}async function yc(e){let t=await ua(e.projectRoot),r=Cn(t,e.planId),n=await gc(r.journal);if(n.state==="recovered")return lr(n);if(n.state!=="applied")throw new C("PLAN_PRECONDITION_FAILED","Only an applied transaction can be rolled back");let i;for(let a of n.operations){let o=await Ur(Br(t,a.path)),s=a.kind==="remove"?o===void 0:o?.digest===a.desiredDigest,c=a.before.kind==="absent"?o===void 0:o?.digest===a.before.digest;if(!s&&!c){i=a;break}}if(await hc(r.lock,{schemaVersion:1,transactionId:n.transactionId,planId:n.planId,startedAt:e.now,nonce:Fr()}),n=await Mt(r.journal,{...n,state:"recovery-required",updatedAt:e.now,failure:{code:e.failureCode}}),i!==void 0)throw new C("RECOVERY_CONFLICT","Rollback would overwrite external content",i.path,i.index);return Vt.set(n.transactionId,{desiredContents:new Map,journal:n}),xn({projectRoot:t,planId:e.planId,now:e.now})}var we=class extends Error{code;constructor(t,r){super(r),this.code=t}},Ln=class extends Error{};function qn(e,t){let r=ye.join(e,".dyyto"),n=ye.join(r,"metadata-transactions",t);return{platformDirectory:r,evidenceDirectory:ye.join(r,"evidence"),lockFile:ye.join(r,"project-lock.json"),transactionLock:ye.join(r,"metadata-lock.json"),transactionDirectory:n,journal:ye.join(n,"journal.json")}}async function qt(e){try{return await Ek(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Et(e,t,r){return e===void 0?void 0:{sink:e,category:t,barrierId:r}}function ha(e,t=!1){if(e!==void 0)return{sink:e.sink,phase:"metadata",pathCategory:t?"directory":e.category,barrierId:e.barrierId}}async function ya(e,t){let r=await Nu(e,ma.O_RDONLY);try{await He({context:ha(t,!0),operation:"directory-sync",run:()=>r.sync()})}finally{await r.close()}}async function Ic(e,t,r){let n=await Nu(e,ma.O_CREAT|ma.O_EXCL|ma.O_WRONLY,384);try{await He({context:ha(r),operation:"write",bytes:t.byteLength,run:()=>n.writeFile(t)}),await He({context:ha(r),operation:"file-sync",bytes:t.byteLength,run:()=>n.sync()})}finally{await n.close()}}async function Vn(e,t,r){let n=ye.dirname(e),i=ye.join(n,`.tmp-${vc()}`),a=Buffer.from(`${JSON.stringify(t,null,2)}
|
|
17
|
+
`);await Ic(i,a,r),await He({context:ha(r),operation:"rename",bytes:a.byteLength,run:()=>Ak(i,e)}),await ya(n,r)}function bc(e){return{...e,journalDigest:v(E(e))}}async function fa(e,t,r){let{journalDigest:n,...i}=t,a=bc(i);return await Vn(e,a,r),a}async function Du(e){try{let t=JSON.parse(await Mn(e,"utf8")),{journalDigest:r,...n}=t;if(t.schemaVersion!==1||!Array.isArray(t.evidence)||r!==v(E(n)))throw new Error("invalid journal");return t.evidence.forEach(On),Te(t.lock),t}catch{throw new we("METADATA_JOURNAL_CORRUPTED","Metadata journal cannot be trusted")}}async function kc(e,t,r){try{await Ic(e,Buffer.from(`${JSON.stringify(t,null,2)}
|
|
18
|
+
`),r),await ya(ye.dirname(e),r)}catch(n){throw n.code==="EEXIST"?new we("METADATA_TRANSACTION_ACTIVE","Another metadata transaction is active"):n}}function Su(e,t){let r={...t,capabilityId:e.capabilityId,capabilityVersion:e.version,capabilityIntegrity:e.integrity};return{...r,evidenceId:v(E(r))}}function ju(e,t,r){let n=t.map(wu),i=e.verifiers.map(o=>o.id).sort(),a=n.map(o=>o.verifierId).sort();if(i.length!==a.length||i.some((o,s)=>o!==a[s]))throw new we("VERIFICATION_INCOMPLETE","Verification results do not cover the release verifier set");for(let o of n){if(o.commandId!==o.verifierId||o.result!=="passed"||o.exitCode!==0)throw new we("VERIFICATION_FAILED",`Verifier ${o.verifierId} did not pass`);if(o.projectStateDigest!==r)throw new we("PROJECT_STATE_CHANGED","Verification result belongs to a different project state")}return n}async function Rk(e,t,r){let n=ye.join(e,`${t.evidenceId}.json`);if(await qt(n)){let i=On(JSON.parse(await Mn(n,"utf8")));if(E(i)!==E(t))throw new we("METADATA_JOURNAL_CORRUPTED","Existing evidence content does not match its identity");return}await Ic(n,Buffer.from(`${JSON.stringify(t,null,2)}
|
|
19
|
+
`),r),await ya(e,r)}async function Pk(e,t,r,n){if(await qt(e)){let i=Te(JSON.parse(await Mn(e,"utf8")));if(E(i)===E(t))return;if(r===void 0||v(E(i))!==r)throw new we("PROJECT_STATE_CHANGED","The project lock changed before metadata commit");await Vn(e,t,n);return}await Vn(e,t,n)}async function ga(e,t){try{await e?.onCheckpoint?.(t)}catch(r){throw new Ln("Simulated metadata crash",{cause:r})}}async function _c(e,t,r){let n=qn(e,t.planId),i=t;try{for(let a of i.evidence)await Rk(n.evidenceDirectory,a,Et(r?.durabilityTrace,"evidence",`${i.transactionId}:evidence`));return i=await fa(n.journal,{...i,state:"evidence-written",updatedAt:new Date().toISOString()},Et(r?.durabilityTrace,"journal",`${i.transactionId}:evidence-written`)),await ga(r,"evidence-written"),await Pk(n.lockFile,i.lock,i.previousLockDigest,Et(r?.durabilityTrace,"lock",`${i.transactionId}:project-lock`)),i=await fa(n.journal,{...i,state:"lock-written",updatedAt:new Date().toISOString()},Et(r?.durabilityTrace,"journal",`${i.transactionId}:lock-written`)),await ga(r,"lock-written"),i=await fa(n.journal,{...i,state:"committed",updatedAt:new Date().toISOString()},Et(r?.durabilityTrace,"journal",`${i.transactionId}:committed`)),await ga(r,"committed"),await wc(n.transactionLock),await ya(n.platformDirectory,Et(r?.durabilityTrace,"directory",`${i.transactionId}:unlock`)),i.lock}catch(a){if(a instanceof Ln)throw new we("METADATA_RECOVERY_REQUIRED","Metadata commit was interrupted");try{await fa(n.journal,{...i,state:"recovery-required",updatedAt:new Date().toISOString()},Et(r?.durabilityTrace,"journal",`${i.transactionId}:recovery-required`))}catch{}throw a}}async function Nk(e){let t=await dr(ye.resolve(e.projectRoot)),r=e.transactionRoot===void 0?t:await dr(ye.resolve(e.transactionRoot));if((await _t({projectRoot:r,planId:e.plan.planId}))?.state!=="applied")throw new we("APPLY_NOT_COMPLETED","The filesystem transaction is not applied");let i;try{i=await sr({projectRoot:t,expectedAssets:e.expectedAssets??e.release.assets.map(f=>({path:f.path,digest:f.digest}))})}catch{throw new we("PROJECT_STATE_CHANGED","Managed project assets no longer match the approved plan")}let o=ju(e.release,e.verificationResults,i.projectStateDigest).map(f=>Su(e.release,f)),s={capabilityId:e.release.capabilityId,version:e.release.version,integrity:e.release.integrity,consumerProfile:e.release.consumerProfile,appliedPlanId:e.plan.planId,projectStateDigest:i.projectStateDigest,assets:i.assets,evidenceIds:o.map(f=>f.evidenceId).sort(),committedAt:e.committedAt,...e.plan.packageAdoption===void 0?{}:{packageAdoption:{...e.plan.packageAdoption.sourceChannel===void 0?{}:{sourceChannel:e.plan.packageAdoption.sourceChannel},registryRevisions:e.plan.packageAdoption.registryRevisions.map(f=>({...f})),sources:e.plan.packageAdoption.sources.map(f=>({...f})),packageJsonDigest:e.plan.packageAdoption.desiredPackageJsonDigest,lockfileDigest:e.plan.packageAdoption.desiredLockfileDigest}}},c=e.previousLock?.capabilities??[],d=e.previousLock!==void 0&&e.plan.action==="adopt"?[...c.filter(f=>f.capabilityId!==e.release.capabilityId),s].sort((f,g)=>f.capabilityId.localeCompare(g.capabilityId)):e.previousLock!==void 0&&e.plan.action==="upgrade"?[...c.filter(f=>f.capabilityId!==e.release.capabilityId),s].sort((f,g)=>f.capabilityId.localeCompare(g.capabilityId)):[s],l={schemaVersion:d.some(f=>f.packageAdoption!==void 0)?2:1,capabilities:d};Te(l);let p=qn(t,e.plan.planId);if(await Wr(p.platformDirectory,{recursive:!0,mode:448}),await Wr(p.evidenceDirectory,{recursive:!0,mode:448}),await qt(p.lockFile)&&e.previousLock===void 0){let f=Te(JSON.parse(await Mn(p.lockFile,"utf8")));if(E(f)===E(l))return f;throw new we("PROJECT_STATE_CHANGED","An incompatible project lock already exists")}let m=vc();if(await kc(p.transactionLock,{planId:e.plan.planId,transactionId:m,createdAt:e.committedAt},Et(e.hooks?.durabilityTrace,"lock",`${m}:metadata-lock`)),await qt(p.transactionDirectory))throw await wc(p.transactionLock),new we("METADATA_TRANSACTION_ACTIVE","This plan already has a metadata transaction");await Wr(p.transactionDirectory,{recursive:!0,mode:448});let u=bc({schemaVersion:1,planId:e.plan.planId,transactionId:m,state:"prepared",createdAt:e.committedAt,updatedAt:e.committedAt,evidence:o,lock:l,...e.previousLock===void 0?{}:{previousLockDigest:v(E(Te(e.previousLock)))}});await Vn(p.journal,u,Et(e.hooks?.durabilityTrace,"journal",`${m}:prepared`));try{await ga(e.hooks,"journal-prepared")}catch(f){throw f instanceof Ln?new we("METADATA_RECOVERY_REQUIRED","Metadata commit was interrupted"):f}return _c(t,u,e.hooks)}async function Ec(e){return Nk(e)}async function Ac(e){let t=await dr(ye.resolve(e.projectRoot)),r=e.transactionRoot===void 0?t:await dr(ye.resolve(e.transactionRoot));if((await _t({projectRoot:r,planId:e.plan.planId}))?.state!=="applied")throw new we("APPLY_NOT_COMPLETED","The filesystem transaction is not applied");let i=e.previousLock.capabilities.find(h=>h.capabilityId===e.release.capabilityId&&h.version===e.release.version);if(i===void 0)throw new we("PROJECT_STATE_CHANGED","The removed capability is not present in the project lock");let a=e.previousLock.capabilities.filter(h=>h!==i),o=e.plan.packageAdoption?.schemaVersion===2&&e.plan.packageAdoption.topology.mode==="pnpm-shared-lockfile"?`${e.plan.packageAdoption.topology.unitRelativeRoot}/`:"",s=new Map(e.plan.operations.flatMap(h=>h.desiredDigest===void 0||!h.path.startsWith(o)?[]:[[h.path.slice(o.length),h.desiredDigest]])),c=e.expectedAssets??a.flatMap(h=>h.assets).map(h=>({...h,digest:s.get(h.path)??h.digest})),d=await sr({projectRoot:t,expectedAssets:c}),p=ju(e.release,e.verificationResults,d.projectStateDigest).map(h=>Su(e.release,h)),m={schemaVersion:a.some(h=>h.packageAdoption!==void 0)?2:1,capabilities:a};Te(m);let u=qn(t,e.plan.planId);await Wr(u.platformDirectory,{recursive:!0,mode:448}),await Wr(u.evidenceDirectory,{recursive:!0,mode:448});let f=vc();await kc(u.transactionLock,{planId:e.plan.planId,transactionId:f,createdAt:e.committedAt}),await Wr(u.transactionDirectory,{recursive:!1,mode:448});let g=bc({schemaVersion:1,planId:e.plan.planId,transactionId:f,state:"prepared",createdAt:e.committedAt,updatedAt:e.committedAt,evidence:p,lock:m,previousLockDigest:v(E(Te(e.previousLock)))});return await Vn(u.journal,g),_c(t,g)}async function Rc(e){let t=await dr(ye.resolve(e.projectRoot)),r=qn(t,e.planId),n=await Du(r.journal);return n.state==="committed"?(await qt(r.transactionLock)&&await wc(r.transactionLock),n.lock):(await qt(r.transactionLock)||await kc(r.transactionLock,{planId:n.planId,transactionId:n.transactionId,createdAt:n.createdAt}),_c(t,n))}async function Pc(e){let t=await dr(ye.resolve(e.projectRoot)),r=qn(t,e.planId);if(!await qt(r.journal))return null;let n=await Du(r.journal);return{planId:n.planId,state:n.state}}async function Se(e){let t=await dr(ye.resolve(e)),r=ye.join(t,".dyyto","project-lock.json");return await qt(r)?Te(JSON.parse(await Mn(r,"utf8"))):null}import{lstat as Cu,readFile as $u,realpath as Ou}from"node:fs/promises";import Ut from"node:path";var st=class extends Error{code;assetPath;constructor(t,r,n){super(r),this.code=t,this.assetPath=n}};function Tu(e){return v(E(e))}async function Dk(e,t){let r=Ut.join(e,"assets",...t.split("/"));try{return await Cu(r),r}catch(n){if(n.code!=="ENOENT"||Ut.posix.basename(t)!==".gitignore")throw n}return Ut.join(e,"assets",...Ut.posix.dirname(t).split("/").filter(n=>n!=="."),"__dyyto_dotfiles__","gitignore")}async function ge(e){let t=await Ou(Ut.resolve(e)),r;try{r=yu(JSON.parse(await $u(Ut.join(t,"release.json"),"utf8")))}catch(c){throw c instanceof st?c:new st("RELEASE_INVALID","Capability release metadata is invalid")}let{integrity:n,...i}=r;if(Tu(i)!==n)throw new st("RELEASE_INTEGRITY_MISMATCH","Capability release integrity does not match metadata");let a=new Map,o=new Set,s="";for(let c of r.assets){try{ta(c.path)}catch{throw new st("RELEASE_ASSET_INVALID","Release asset path is unsafe",c.path)}if((c.path===".dyyto"||c.path.startsWith(".dyyto/"))&&c.path!==".dyyto/application-config-binding.json"||o.has(c.path)||c.path.localeCompare(s)<0)throw new st("RELEASE_ASSET_INVALID","Release assets must be unique, sorted and outside reserved .dyyto paths",c.path);o.add(c.path),s=c.path;let d=await Dk(t,c.path),l=await Ou(d),p=Ut.join(t,"assets");if(!l.startsWith(`${p}${Ut.sep}`))throw new st("RELEASE_ASSET_INVALID","Release asset escapes its bundle",c.path);let m=await Cu(d);if(!m.isFile()||m.isSymbolicLink())throw new st("RELEASE_ASSET_INVALID","Release asset must be a regular file",c.path);let u=await $u(d);if(v(u)!==c.digest)throw new st("RELEASE_ASSET_INTEGRITY_MISMATCH","Release asset digest does not match metadata",c.path);a.set(c.path,u)}if(r.exit.ownedAssets.length!==r.assets.length||r.exit.ownedAssets.some((c,d)=>c!==r.assets[d]?.path))throw new st("RELEASE_INVALID","Exit owned assets must exactly match release assets");return{release:r,contents:a}}import{link as Sk,open as Lu,lstat as yt,mkdir as Vu,readFile as Nc,readdir as wa,realpath as wt,rm as jk,unlink as $k}from"node:fs/promises";import ie from"node:path";var he=class extends Error{code;constructor(t,r){super(r),this.code=t,this.name="ProjectBootstrapError"}},Ok={schemaVersion:1,profile:{id:"workspace-root",parameters:{}},capabilities:[{capabilityId:"foundation.workspace-root",version:"1.2.0"}]};function Ck(){return new TextEncoder().encode(`${JSON.stringify(Ok,null,2)}
|
|
20
|
+
`)}async function Tk(e,t=!1){let r=ie.resolve(e),n=await yt(r).catch(()=>null);if(n===null||!n.isDirectory()||n.isSymbolicLink())throw new he("TARGET_INVALID","Workspace target must be a real existing directory");let i=await wt(r);for(let a of t?["AGENTS.md","README.md"]:["package.json","pnpm-workspace.yaml"]){let o=await yt(ie.join(i,a)).catch(()=>null);if(o===null||!o.isFile()||o.isSymbolicLink())throw new he("WORKSPACE_MARKER_MISSING",`Existing workspace must contain a real ${a}`)}if(await yt(ie.join(i,"project-capabilities.json")).catch(()=>null))throw new he("MANIFEST_EXISTS","Project manifest already exists");return i}async function xk(e,t){let r=ie.resolve(e),n=await yt(r).catch(()=>null);if(n===null||!n.isDirectory()||n.isSymbolicLink())throw new he("TARGET_INVALID","Project target must be a real existing directory");let i=await wt(r);for(let a of t){let o=await yt(ie.join(i,a)).catch(()=>null);if(o===null||!o.isFile()||o.isSymbolicLink())throw new he("WORKSPACE_MARKER_MISSING",`Existing project must contain a real ${a}`)}if(await yt(ie.join(i,"project-capabilities.json")).catch(()=>null))throw new he("MANIFEST_EXISTS","Project manifest already exists");return i}async function Mu(e){let t=await xk(e.projectRoot,e.requiredMarkers??["package.json"]),r=G(e.manifest),n=new TextEncoder().encode(`${JSON.stringify(r,null,2)}
|
|
21
|
+
`),i=r.capabilities[0],a=De({action:"adopt",capability:{schemaVersion:1,capabilityId:i.capabilityId,version:i.version,integrity:e.capabilityIntegrity,assets:[],verifiers:[]},changes:[{path:"project-capabilities.json",kind:"create",ownership:"owned-file",desiredDigest:v(n)}],observedAssets:[{path:"project-capabilities.json",exists:!1}],generatedAt:e.generatedAt,expiresAt:e.expiresAt});return{projectRoot:t,plan:a,desiredContents:new Map([["project-capabilities.json",n]])}}async function qu(e){let t=await Tk(e.projectRoot,e.documentationOnly===!0),r=Ck(),n=De({action:"adopt",capability:{schemaVersion:1,capabilityId:"foundation.workspace-root",version:"1.2.0",integrity:e.capabilityIntegrity,assets:[],verifiers:[]},changes:[{path:"project-capabilities.json",kind:"create",ownership:"owned-file",desiredDigest:v(r)}],observedAssets:[{path:"project-capabilities.json",exists:!1}],generatedAt:e.generatedAt,expiresAt:e.expiresAt});return{projectRoot:t,plan:n,desiredContents:new Map([["project-capabilities.json",r]])}}async function Lk(e){let t=await Lu(e,"r");try{await t.sync()}finally{await t.close()}}async function Uu(e,t){let r=`${e}.tmp-${process.pid}-${crypto.randomUUID()}`,n=await Lu(r,"wx",384);try{await n.writeFile(t,"utf8"),await n.sync()}finally{await n.close()}try{await Sk(r,e),await $k(r),await Lk(ie.dirname(e))}catch(i){throw await jk(r,{force:!0}),i}}async function Vk(e){let t=ie.resolve(e);try{let r=await yt(t);if(!r.isDirectory()||r.isSymbolicLink())throw new he("TARGET_INVALID","Project target must be a real directory");if((await wa(t)).length!==0)throw new he("TARGET_NOT_EMPTY","Project target must be empty")}catch(r){if(r.code!=="ENOENT")throw r;let n=ie.dirname(t),i=await yt(n).catch(()=>null);if(i===null||!i.isDirectory()||i.isSymbolicLink())throw new he("TARGET_INVALID","Project target parent must be a real directory");await Vu(t)}return wt(t)}async function va(e){let t=G(e.manifest),r=await Vk(e.projectRoot),n=ie.join(r,"project-capabilities.json");try{await Uu(n,`${JSON.stringify(t,null,2)}
|
|
22
|
+
`)}catch(i){throw i.code==="EEXIST"?new he("MANIFEST_EXISTS","Project manifest already exists"):i}return{projectRoot:r,manifest:t}}function Un(e){let{planId:t,...r}=e;if(ra(r)!==e.planId)throw new he("PLAN_INTEGRITY_INVALID","Saved plan integrity is invalid")}async function Mk(e){let t=await wt(ie.resolve(e.projectRoot)),r=Lt(e.plan);Un(r);let n=ie.join(t,".dyyto","plans");await Vu(n,{recursive:!0,mode:448});let i=ie.join(n,`${r.planId}.json`);try{await Uu(i,`${E(r)}
|
|
23
|
+
`)}catch(a){if(a.code!=="EEXIST")throw a;let o=Lt(JSON.parse(await Nc(i,"utf8")));if(Un(o),E(o)!==E(r))throw new he("PLAN_INTEGRITY_INVALID","Plan ID content mismatch")}return i}function xu(e){return E({action:e.action,state:e.state,capability:e.capability,operations:e.operations,packageAdoption:e.packageAdoption})}async function pr(e){let t=await wt(ie.resolve(e.projectRoot)),r=e.transactionRoot===void 0?t:await wt(ie.resolve(e.transactionRoot)),n=Lt(e.plan);Un(n);let i=ie.join(t,".dyyto","plans"),a=await wa(i).catch(s=>{if(s.code==="ENOENT")return[];throw s}),o=[];for(let s of a.filter(c=>c.endsWith(".json")).sort()){let c=Lt(JSON.parse(await Nc(ie.join(i,s),"utf8")));Un(c),!await yt(ie.join(r,".dyyto","transactions",c.planId)).then(()=>!0).catch(l=>l.code==="ENOENT"?!1:Promise.reject(l))&&Date.parse(c.expiresAt)>Date.parse(e.now)&&xu(c)===xu(n)&&o.push(c)}return o.sort((s,c)=>s.generatedAt.localeCompare(c.generatedAt)),o[0]!==void 0?o[0]:(await Mk({projectRoot:t,plan:n}),n)}async function Fn(e){let t=await wt(ie.resolve(e.projectRoot)),r=ie.join(t,".dyyto","plans",`${e.planId}.json`);try{let n=Lt(JSON.parse(await Nc(r,"utf8")));if(Un(n),n.planId!==e.planId)throw new he("PLAN_INTEGRITY_INVALID","Saved plan identity mismatch");return n}catch(n){throw n.code==="ENOENT"?new he("PLAN_NOT_FOUND","Saved plan was not found"):n}}async function Ia(e,t=[],r,n=[]){let i=await wt(ie.resolve(e)),a=r===void 0?i:await wt(ie.resolve(r)),o=ie.join(i,".dyyto","plans"),s=await wa(o).catch(l=>{if(l.code==="ENOENT")return[];throw l}),c=[];for(let l of s.filter(p=>p.endsWith(".json")).sort()){let p=l.slice(0,-5),m=await Fn({projectRoot:i,planId:p}),u=await _t({projectRoot:a,planId:p}),f=await yt(ie.join(i,".dyyto","metadata-transactions",p)).then(()=>!0).catch(g=>g.code==="ENOENT"?!1:Promise.reject(g));u?.state==="applied"&&!f&&!t.includes(m.planId)&&(!n.includes(m.capability.capabilityId)||m.action==="upgrade"||m.action==="remove"||m.action==="adopt"&&m.operations.every(g=>g.disposition==="noop"))&&c.push(m)}let d=qk(c);if(d===void 0)throw new he("PLAN_NOT_FOUND",c.length===0?"No applied plan is available for verification":"More than one applied plan requires inspection before verification");return d}function qk(e){if(e.length===1)return e[0];if(e.length===0)return;let t=e[0]?.capability.capabilityId;if(!(t===void 0||e.some(r=>r.capability.capabilityId!==t)))return[...e].sort((r,n)=>r.generatedAt.localeCompare(n.generatedAt)).at(-1)}async function Dc(e){let t=await wt(ie.resolve(e)),r=ie.join(t,".dyyto","plans"),n=await wa(r).catch(a=>{if(a.code==="ENOENT")return[];throw a}),i=[];for(let a of n.filter(o=>o.endsWith(".json")).sort())i.push(await Fn({projectRoot:t,planId:a.slice(0,-5)}));return i}import{lstat as Fu,readFile as Uk,readdir as Fk,realpath as zk}from"node:fs/promises";import _e from"node:path";import{homedir as zu}from"node:os";var Xe=class extends Error{code;constructor(t){super(t),this.code=t,this.name="WorkspaceTopologyError"}};async function Bu(e){let t=_e.resolve(e),r=await Fu(t).catch(()=>null);if(!r?.isDirectory()||r.isSymbolicLink()||t===_e.parse(t).root||t===_e.resolve(zu()))throw new Xe("WORKSPACE_PATH_UNSAFE");let n=await zk(t);if(n!==t)throw new Xe("WORKSPACE_PATH_UNSAFE");return n}async function ur(e){let t=await Fu(e).catch(()=>null);if(t!==null){if(!t.isFile()||t.isSymbolicLink())throw new Xe("WORKSPACE_PATH_UNSAFE");return Uk(e)}}function Gu(e){let t=e.split(/\r?\n/u),r=[],n=!1;for(let i of t){if(/^packages:\s*(?:#.*)?$/u.test(i)){n=!0;continue}if(!n)continue;let a=/^\s+-\s+["']?([^"'#]+?)["']?\s*(?:#.*)?$/u.exec(i);if(a){r.push(a[1].trim().replace(/^\.\//u,"").replace(/\/$/u,""));continue}if(i.trim()&&!/^\s/u.test(i))break}if(r.length===0)throw new Xe("WORKSPACE_MANIFEST_INVALID");return r}function Bk(e,t){if(e.includes("**")){let r=e.split("**",1)[0].replace(/\/$/u,"");return t===r||t.startsWith(`${r}/`)}if(e.endsWith("/*")){let r=e.slice(0,-2);return t.startsWith(`${r}/`)&&!t.slice(r.length+1).includes("/")}return e===t}async function Ju(e){let t=await Bu(e),r=await ur(_e.join(t,"pnpm-workspace.yaml"));if(!r)throw new Xe("WORKSPACE_OWNER_MISSING");let n=new Map;for(let i of Gu(r.toString("utf8"))){let a=[];if(i.endsWith("/*")&&!i.slice(0,-2).includes("*")){let o=i.slice(0,-2),s=await Fk(_e.join(t,...o.split("/")),{withFileTypes:!0}).catch(()=>[]);for(let c of s)c.isDirectory()&&!c.isSymbolicLink()&&a.push(`${o}/${c.name}`)}else if(!i.includes("*"))a.push(i);else throw new Xe("WORKSPACE_MANIFEST_INVALID");for(let o of a){let s=await ur(_e.join(t,...o.split("/"),"package.json"));s&&n.set(o,s)}}return Object.freeze([...n].sort(([i],[a])=>i.localeCompare(a)).map(([i,a])=>Object.freeze({relativeRoot:i,bytes:a})))}async function Kr(e){let t=await Bu(e);if(await ur(_e.join(t,"pnpm-lock.yaml")))return Object.freeze({schemaVersion:1,mode:"standalone",transactionRoot:t,unitRoot:t,unitRelativeRoot:".",unitImporterId:".",lockfilePath:"pnpm-lock.yaml"});if(await ur(_e.join(t,"pnpm-workspace.yaml")))throw new Xe("WORKSPACE_NESTED_UNSUPPORTED");let r=_e.dirname(t),n;for(;r!==_e.parse(r).root&&r!==_e.resolve(zu());){let a=await ur(_e.join(r,"pnpm-workspace.yaml"));if(a){if(n)throw new Xe("WORKSPACE_NESTED_UNSUPPORTED");n={root:r,manifest:a};break}r=_e.dirname(r)}if(!n||!await ur(_e.join(n.root,"pnpm-lock.yaml"))||!await ur(_e.join(n.root,"project-capabilities.json")))throw new Xe("WORKSPACE_OWNER_MISSING");let i=_e.relative(n.root,t).split(_e.sep).join("/");if(!i||i.startsWith("../")||Gu(n.manifest.toString("utf8")).filter(a=>Bk(a,i)).length!==1)throw new Xe("WORKSPACE_UNIT_NOT_DECLARED");return Object.freeze({schemaVersion:1,mode:"pnpm-shared-lockfile",transactionRoot:n.root,unitRoot:t,unitRelativeRoot:i,unitImporterId:i,workspaceManifestPath:"pnpm-workspace.yaml",workspaceManifestDigest:v(n.manifest),lockfilePath:"pnpm-lock.yaml"})}var Wu=new Set(["preparing","prepared","applying","recovery-required","recovering"]);async function Sc(e){let t=await Dc(e);for(let r of t){let n=await _t({projectRoot:e,planId:r.planId});if(n!==null&&Wu.has(n.state))return{required:!0,kind:"filesystem",planId:r.planId,state:n.state}}for(let r of t){let n=await Pc({projectRoot:e,planId:r.planId});if(n!==null&&n.state!=="committed")return{required:!0,kind:"metadata",planId:r.planId,state:n.state}}return{required:!1}}async function Gk(e){let t=await Sc(e.projectRoot);if(!t.required)return{kind:"none",state:"not-required"};if(t.kind==="filesystem"){let r=await xn({projectRoot:e.projectRoot,planId:t.planId,now:e.now});return{kind:"filesystem",planId:t.planId,state:r.state}}return await Rc({projectRoot:e.projectRoot,planId:t.planId}),{kind:"metadata",planId:t.planId,state:"committed"}}async function Ku(e){let t=await Gk(e);if(t.kind!=="none")return t;let r=await Kr(e.projectRoot).catch(()=>{});if(r?.mode!=="pnpm-shared-lockfile")return t;let n=new Set((await Dc(e.projectRoot)).map(c=>c.planId)),i=await import("node:fs/promises").then(({readFile:c})=>c(`${r.transactionRoot}/.dyyto/transaction-lock.json`,"utf8")).catch(c=>c.code==="ENOENT"?void 0:Promise.reject(c));if(!i)return t;let a;try{let c=JSON.parse(i);if(typeof c.planId!="string"||!/^sha256:[a-f0-9]{64}$/u.test(c.planId)||!n.has(c.planId))return t;a=c.planId}catch{return t}let o=await _t({projectRoot:r.transactionRoot,planId:a});if(!o||!Wu.has(o.state))return t;let s=await xn({projectRoot:r.transactionRoot,planId:a,now:e.now});return{kind:"filesystem",planId:a,state:s.state}}import{lstat as Jk,readFile as jc,realpath as Yu}from"node:fs/promises";import zn from"node:path";var Wk=new Set(["MIT","Apache-2.0","UNLICENSED"]),Kk=new Set(["public","restricted","private"]),Yk=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/,Hk=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;function Zk(e){let t;try{t=new URL(e)}catch{throw new M("CONSUMER_PROFILE_UNSUPPORTED","repository must be a canonical public HTTPS URL")}if(t.protocol!=="https:"||t.username.length>0||t.password.length>0||t.search.length>0||t.hash.length>0||t.pathname==="/"||t.pathname.includes(".."))throw new M("CONSUMER_PROFILE_UNSUPPORTED","repository must be a canonical public HTTPS URL");t.pathname=t.pathname.replace(/\/$/,"").replace(/\.git$/,"");let r=t.href.replace(/\/$/,"");if(r!==e)throw new M("CONSUMER_PROFILE_UNSUPPORTED","repository URL must already be canonical");return r}function fr(e){if(e.profile?.id!=="workspace-node-application"&&e.profile?.id!=="workspace-web-application"&&e.profile?.id!=="workspace-expo-application"&&e.profile?.id!=="nextjs-full-stack-application")throw new M("CONSUMER_PROFILE_UNSUPPORTED","Manifest must select a workspace application profile");let t=Object.keys(e.profile.parameters),r=e.profile.parameters.name;if(t.length!==1||t[0]!=="name"||r===void 0||r.length>128||!/^[a-z0-9][a-z0-9._-]*$/.test(r))throw new M("CONSUMER_PROFILE_UNSUPPORTED","Application parameters must contain one valid lowercase name");return{name:r}}function Ft(e,t="standalone-npm-package"){if(e.profile?.id!==t)throw new M("CONSUMER_PROFILE_UNSUPPORTED",`Manifest must select ${t} profile`);let r=e.profile.parameters,n=Object.keys(r).sort(),i=e.capabilities.find(m=>m.capabilityId===`foundation.${t}`)?.version,a=i==="1.1.0"||i==="1.2.0"||t==="react-component-library",o=a?["license","name","publishAccess","repository","version"]:["license","name","publishAccess","version"];if(n.length!==o.length||n.some((m,u)=>m!==o[u]))throw new M("CONSUMER_PROFILE_UNSUPPORTED","Standalone npm profile parameters must be exact");let{name:s,version:c,license:d,publishAccess:l,repository:p}=r;if(s===void 0||s.length>214||!Yk.test(s))throw new M("CONSUMER_PROFILE_UNSUPPORTED","npm package name must be a valid lowercase name");if(c===void 0||!Hk.test(c))throw new M("CONSUMER_PROFILE_UNSUPPORTED","npm package version must be a stable SemVer");if(d===void 0||!Wk.has(d))throw new M("CONSUMER_PROFILE_UNSUPPORTED","license must be MIT, Apache-2.0, or UNLICENSED");if(l===void 0||!Kk.has(l))throw new M("CONSUMER_PROFILE_UNSUPPORTED","publish access must be public, restricted, or private");if(l==="restricted"&&!s.startsWith("@"))throw new M("CONSUMER_PROFILE_UNSUPPORTED","restricted access requires a scoped package name");return{name:s,version:c,license:d,publishAccess:l,...a?{repository:Zk(p)}:{}}}function $c(e){let t={name:e.name,version:e.version,...e.publishAccess==="private"?{private:!0}:{},license:e.license,...e.repository===void 0?{}:{repository:{type:"git",url:e.repository}},type:"module",sideEffects:!1,main:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"}},files:["dist"],engines:{node:">=24.18.0 <25",pnpm:"11.21.0"},packageManager:"pnpm@11.21.0",scripts:{build:"tsc -p tsconfig.build.json",typecheck:"tsc --noEmit -p tsconfig.json",test:"vitest run",check:"corepack pnpm typecheck && corepack pnpm test",prepack:"corepack pnpm check && corepack pnpm build"},...e.publishAccess==="private"?{}:{publishConfig:{access:e.publishAccess}},devDependencies:{"@types/node":"24.10.13",typescript:"6.0.3",vitest:"4.1.10"}};return Buffer.from(`${JSON.stringify(t,null,2)}
|
|
24
24
|
`)}function Oc(e){return Buffer.from(`${JSON.stringify({name:e.name,version:e.version,...e.publishAccess==="private"?{private:!0}:{},license:e.license,repository:{type:"git",url:e.repository},type:"module",sideEffects:["**/*.css"],files:["dist"],main:"./dist/index.js",module:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./style.css":"./dist/style.css"},engines:{node:">=24.18.0 <25",pnpm:"11.21.0"},packageManager:"pnpm@11.21.0",scripts:{build:"vite build && tsc -p tsconfig.build.json",typecheck:"tsc --noEmit -p tsconfig.json",test:"vitest run","verify:bundle":"vite build && tsc -p tsconfig.build.json && node tooling/verify-bundle.mjs",check:"corepack pnpm typecheck && corepack pnpm test && corepack pnpm verify:bundle",prepack:"corepack pnpm check"},peerDependencies:{react:">=19.0.0 <20","react-dom":">=19.0.0 <20"},devDependencies:{"@testing-library/dom":"10.4.1","@testing-library/jest-dom":"6.9.1","@testing-library/react":"16.3.2","@types/node":"24.10.13","@types/react":"19.2.18","@types/react-dom":"19.2.4","@vitejs/plugin-react":"6.0.5",jsdom:"30.0.1",react:"19.2.8","react-dom":"19.2.8",typescript:"6.0.3",vite:"8.2.1",vitest:"4.1.10"},...e.publishAccess==="private"?{}:{publishConfig:{access:e.publishAccess}}},null,2)}
|
|
25
25
|
`)}function Xk(e){return Buffer.from(`${JSON.stringify({name:e,version:"0.0.0",private:!0,type:"module",engines:{node:">=24.18.0 <25",pnpm:"11.21.0"},packageManager:"pnpm@11.21.0",scripts:{build:"tsc -p tsconfig.build.json",typecheck:"tsc --noEmit -p tsconfig.json",test:"vitest run",check:"pnpm typecheck && pnpm test && pnpm build",start:"node dist/index.js"},devDependencies:{"@types/node":"24.10.13",typescript:"6.0.3",vitest:"4.1.10"}},null,2)}
|
|
26
26
|
`)}function Qk(e){return Buffer.from(`${JSON.stringify({name:e,version:"0.0.0",private:!0,type:"module",engines:{node:">=24.18.0 <25",pnpm:"11.21.0"},packageManager:"pnpm@11.21.0",scripts:{dev:"vite",build:"tsc -b && vite build",preview:"vite preview",typecheck:"tsc -b --pretty false",test:"vitest run",check:"pnpm typecheck && pnpm test && pnpm build"},dependencies:{react:"19.2.8","react-dom":"19.2.8"},devDependencies:{"@testing-library/dom":"10.4.1","@testing-library/jest-dom":"6.9.1","@testing-library/react":"16.3.2","@types/node":"24.10.13","@types/react":"19.2.18","@types/react-dom":"19.2.4","@vitejs/plugin-react":"6.0.5",jsdom:"30.0.1",typescript:"6.0.3",vite:"8.2.1",vitest:"4.1.10"}},null,2)}
|
|
27
27
|
`)}function e_(e){return Buffer.from(`${JSON.stringify({name:e,version:"0.0.0",private:!0,type:"module",engines:{node:">=24.18.0 <25",pnpm:"11.21.0"},packageManager:"pnpm@11.21.0",scripts:{dev:"next dev",build:"next build",start:"node .artifacts/standalone/server.js",typecheck:"tsc --noEmit",lint:"eslint .","test:unit":"vitest run","test:e2e":"playwright test",test:"pnpm test:unit && pnpm test:e2e",package:"pnpm build && node tooling/package-standalone.mjs",check:"pnpm lint && pnpm typecheck && pnpm test:unit && pnpm build"},dependencies:{next:"16.2.11",react:"19.2.8","react-dom":"19.2.8","server-only":"0.0.1"},devDependencies:{"@playwright/test":"1.62.1","@testing-library/dom":"10.4.1","@testing-library/jest-dom":"6.9.1","@testing-library/react":"16.3.2","@types/node":"24.10.13","@types/react":"19.2.18","@types/react-dom":"19.2.4","@vitejs/plugin-react":"6.0.5",eslint:"9.39.5","eslint-config-next":"16.2.11",jsdom:"30.0.1",typescript:"6.0.3",vitest:"4.1.10"}},null,2)}
|
|
28
28
|
`)}function t_(e){return Buffer.from(`${JSON.stringify({name:e,version:"0.0.0",private:!0,main:"expo-router/entry",engines:{node:">=24.18.0 <25",pnpm:"11.21.0"},packageManager:"pnpm@11.21.0",scripts:{dev:"expo start",android:"expo start --android",ios:"expo start --ios",web:"expo start --web",build:"expo export --platform web --output-dir dist",package:"corepack pnpm build && node tooling/verify-expo-export.mjs",typecheck:"tsc --noEmit",test:"vitest run",check:"corepack pnpm typecheck && corepack pnpm test && corepack pnpm package"},dependencies:{expo:"~57.0.15","expo-router":"~57.0.15","expo-status-bar":"~57.0.1",react:"19.2.3","react-dom":"19.2.3","react-native":"0.86.2","react-native-safe-area-context":"5.9.1","react-native-screens":"4.27.0","react-native-web":"0.21.2"},devDependencies:{"@types/node":"24.10.13","@types/react":"19.2.14",typescript:"6.0.3",vitest:"4.1.10"}},null,2)}
|
|
29
|
-
`)}async function
|
|
30
|
-
`),c=n.plan.operations.map(({disposition:u,conflictCode:f,...g})=>g);c.push({path:a,kind:"replace",ownership:"owned-file",baseDigest:v(o),desiredDigest:v(s)});let d=await Promise.all(c.map(u=>Yu(i,u.path))),l=De({action:"adopt",capability:{schemaVersion:1,capabilityId:e.release.release.capabilityId,version:e.release.release.version,integrity:e.release.release.integrity,assets:c.filter(u=>u.path!==a).map(u=>({path:u.path,ownership:u.ownership,desiredDigest:u.desiredDigest})),verifiers:e.release.release.verifiers.map(({id:u})=>({id:u,kind:"command"}))},changes:c,observedAssets:d,generatedAt:e.generatedAt,expiresAt:e.expiresAt}),p=new Map([...n.desiredContents,[a,s]]),m=new Map;for(let u of l.operations)u.disposition==="ready"&&u.kind!=="remove"&&m.set(u.path,p.get(u.path));return{...n,manifest:r,plan:l,desiredContents:m}}function Gn(e){return mr(e,"workspace-npm-package")}function Wn(e){return mr(e,"workspace-node-application")}function Kn(e){return mr(e,"workspace-web-application")}function Yn(e){return mr(e,"workspace-expo-application")}async function Hu(e){if(e.currentLock!==void 0){let n=await Bn(e);return{state:n.plan.state==="conflicted"?"drifted":"adopted",operations:n.plan.operations}}let t=await Bn({...e,allowExistingWithoutLock:!0});return t.plan.operations.filter(n=>n.disposition!=="ready").length===0?{state:"planned",operations:t.plan.operations}:t.plan.operations.every(n=>n.disposition==="noop")?{state:"applied-unverified",operations:t.plan.operations}:{state:"drifted",operations:t.plan.operations}}async function Zu(e){if(e.currentLock!==void 0){let n=await Jn(e);return{state:n.plan.state==="conflicted"?"drifted":"adopted",operations:n.plan.operations}}let t=await Jn({...e,allowExistingWithoutLock:!0});return t.plan.operations.filter(n=>n.disposition!=="ready").length===0?{state:"planned",operations:t.plan.operations}:t.plan.operations.every(n=>n.disposition==="noop")?{state:"applied-unverified",operations:t.plan.operations}:{state:"drifted",operations:t.plan.operations}}async function Xu(e){if(e.currentLock!==void 0){let n=await Yr(e);return{state:n.plan.state==="conflicted"?"drifted":"adopted",operations:n.plan.operations}}let t=await Yr({...e,allowExistingWithoutLock:!0});return t.plan.operations.filter(n=>n.disposition!=="ready").length===0?{state:"planned",operations:t.plan.operations}:t.plan.operations.every(n=>n.disposition==="noop")?{state:"applied-unverified",operations:t.plan.operations}:{state:"drifted",operations:t.plan.operations}}async function Qu(e){if(e.currentLock!==void 0){let n=await Gn(e);return{state:n.plan.state==="conflicted"?"drifted":"adopted",operations:n.plan.operations}}let t=await Gn({...e,allowExistingWithoutLock:!0});return t.plan.operations.filter(n=>n.disposition!=="ready").length===0?{state:"planned",operations:t.plan.operations}:t.plan.operations.every(n=>n.disposition==="noop")?{state:"applied-unverified",operations:t.plan.operations}:{state:"drifted",operations:t.plan.operations}}async function ef(e){if(e.currentLock!==void 0){let n=await Wn(e);return{state:n.plan.state==="conflicted"?"drifted":"adopted",operations:n.plan.operations}}let t=await Wn({...e,allowExistingWithoutLock:!0});return t.plan.operations.filter(n=>n.disposition!=="ready").length===0?{state:"planned",operations:t.plan.operations}:t.plan.operations.every(n=>n.disposition==="noop")?{state:"applied-unverified",operations:t.plan.operations}:{state:"drifted",operations:t.plan.operations}}async function tf(e){if(e.currentLock!==void 0){let n=await Kn(e);return{state:n.plan.state==="conflicted"?"drifted":"adopted",operations:n.plan.operations}}let t=await Kn({...e,allowExistingWithoutLock:!0});return t.plan.operations.filter(n=>n.disposition!=="ready").length===0?{state:"planned",operations:t.plan.operations}:t.plan.operations.every(n=>n.disposition==="noop")?{state:"applied-unverified",operations:t.plan.operations}:{state:"drifted",operations:t.plan.operations}}async function rf(e){if(e.currentLock!==void 0){let n=await Yn(e);return{state:n.plan.state==="conflicted"?"drifted":"adopted",operations:n.plan.operations}}let t=await Yn({...e,allowExistingWithoutLock:!0});return t.plan.operations.filter(n=>n.disposition!=="ready").length===0?{state:"planned",operations:t.plan.operations}:t.plan.operations.every(n=>n.disposition==="noop")?{state:"applied-unverified",operations:t.plan.operations}:{state:"drifted",operations:t.plan.operations}}import{lstat as P_,readFile as Va,realpath as N_}from"node:fs/promises";import ei from"node:path";var ct=class extends Error{code;constructor(t,r){super(r),this.code=t}},gr=/^sha256:[a-f0-9]{64}$/,r_=/^sha512-[A-Za-z0-9+/]{86}==$/,n_=/^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/,af=/^registry\.[a-z0-9][a-z0-9.-]{1,126}$/,i_=/^@[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*$/,nf=/^[a-z][a-z0-9._:-]{2,127}$/;function hr(e,t){let r=Object.keys(e).sort();return r.length===t.length&&r.every((n,i)=>n===[...t].sort()[i])}function a_(e){if(!hr(e,["registryId","tenantId","origin","scopes","authentication","capabilities","status"])||!af.test(e.registryId)||!nf.test(e.tenantId)||e.scopes.length===0||e.scopes.length>32||e.scopes.some((n,i)=>!/^@[a-z0-9][a-z0-9._-]*$/.test(n)||e.scopes.indexOf(n)!==i)||!hr(e.authentication,e.authentication.credentialRef===void 0?["kind"]:["kind","credentialRef"])||!hr(e.capabilities,["read","write","provenance","staging"])||!["workload-identity","short-lived-token","restricted-token","anonymous-test"].includes(e.authentication.kind)||e.authentication.kind==="anonymous-test"!=(e.authentication.credentialRef===void 0)||e.authentication.credentialRef!==void 0&&!nf.test(e.authentication.credentialRef))return!1;let t;try{t=new URL(e.origin)}catch{return!1}if(t.username||t.password||t.search||t.hash||!t.pathname.endsWith("/")||t.pathname.includes("..")||/%2f|%5c/iu.test(t.pathname))return!1;let r=t.hostname==="127.0.0.1"||t.hostname==="localhost"||t.hostname==="[::1]";return e.authentication.kind==="anonymous-test"&&(!r||t.protocol!=="http:")||e.authentication.kind!=="anonymous-test"&&t.protocol!=="https:"?!1:typeof e.capabilities.read=="boolean"&&typeof e.capabilities.write=="boolean"&&typeof e.capabilities.provenance=="boolean"&&typeof e.capabilities.staging=="boolean"&&(e.status==="enabled"||e.status==="disabled")}function o_(e){if(!a_(e))throw new ct("REGISTRY_CONFIG_INVALID","Registry configuration is invalid");let t={schemaVersion:1,...e};return Object.freeze({...t,scopes:Object.freeze([...e.scopes]),authentication:Object.freeze({...e.authentication}),capabilities:Object.freeze({...e.capabilities}),revision:v(E(t))})}function ba(e){let t=e;if(typeof t!="object"||t===null||!hr(t,["schemaVersion","revision","registryId","tenantId","origin","scopes","authentication","capabilities","status"])||t.schemaVersion!==1||!gr.test(t.revision))throw new ct("REGISTRY_CONFIG_INVALID","Registry configuration is invalid");let{schemaVersion:r,revision:n,...i}=t;if(o_(i).revision!==n)throw new ct("REGISTRY_CONFIG_INVALID","Registry configuration has been modified");return t}function s_(e,t){let r,n;try{r=new URL(e.origin),n=new URL(t)}catch{return!1}return n.username||n.password||n.search||n.hash||n.pathname!==r.pathname||n.protocol!==r.protocol||n.hostname!==r.hostname?!1:e.authentication.kind==="anonymous-test"||n.port===r.port}function c_(e,t){let r=ba(t);if(!hr(e,["registryId","registryConfigRevision","origin","resolvedAt","expiresAt"])||e.registryId!==r.registryId||e.registryConfigRevision!==r.revision||!s_(r,e.origin)||Number.isNaN(Date.parse(e.resolvedAt))||Number.isNaN(Date.parse(e.expiresAt))||Date.parse(e.expiresAt)<=Date.parse(e.resolvedAt))throw new ct("REGISTRY_ENDPOINT_BINDING_INVALID","Registry endpoint binding is invalid");let n={schemaVersion:1,...e};return Object.freeze({...n,bindingDigest:v(E(n))})}function of(e,t){let r=e;if(typeof r!="object"||r===null||!hr(r,["schemaVersion","bindingDigest","registryId","registryConfigRevision","origin","resolvedAt","expiresAt"])||r.schemaVersion!==1||!gr.test(r.bindingDigest))throw new ct("REGISTRY_ENDPOINT_BINDING_INVALID","Registry endpoint binding is invalid");let{schemaVersion:n,bindingDigest:i,...a}=r;if(c_(a,t).bindingDigest!==i)throw new ct("REGISTRY_ENDPOINT_BINDING_INVALID","Registry endpoint binding has been modified");return r}function l_(e){let t=["registryId","registryConfigRevision","packageName","version","integrity","tarballDigest","access","provenance","sourceDeliveryReceiptId","verifiedAt",...e.verificationIdentityDigest===void 0?[]:["verificationIdentityDigest"]];return hr(e,t)&&af.test(e.registryId)&&gr.test(e.registryConfigRevision)&&i_.test(e.packageName)&&n_.test(e.version)&&r_.test(e.integrity)&&gr.test(e.tarballDigest)&&gr.test(e.sourceDeliveryReceiptId)&&!Number.isNaN(Date.parse(e.verifiedAt))&&(e.access==="restricted"||e.access==="private")&&["registry-attested","external-attested","local-readback-verified","development-readback-verified","registry-verified-no-attestation"].includes(e.provenance)&&(e.provenance!=="registry-verified-no-attestation"?e.verificationIdentityDigest!==void 0&&gr.test(e.verificationIdentityDigest):e.verificationIdentityDigest===void 0)}function sf(e){if(!l_(e))throw new ct("PACKAGE_RECEIPT_INVALID","Package delivery receipt is invalid");let t={schemaVersion:1,...e};return Object.freeze({...t,receiptId:v(E(t))})}function cf(e){let t=e;if(typeof t!="object"||t===null||t.schemaVersion!==1||!gr.test(t.receiptId))throw new ct("PACKAGE_RECEIPT_INVALID","Package delivery receipt is invalid");let{schemaVersion:r,receiptId:n,...i}=t;if(sf(i).receiptId!==n)throw new ct("PACKAGE_RECEIPT_INVALID","Package delivery receipt has been modified");return t}var je=class extends Error{code;constructor(t){super(t),this.code=t,this.name="ResolutionEvidenceError"}};function xc(e){return v(E(e))}var Tc=/^sha256:[a-f0-9]{64}$/u,d_=/^sha512-[A-Za-z0-9+/]{86}==$/u,p_=/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u,ka=/^[a-z0-9][a-z0-9._/-]{0,255}$/u,u_=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u,f_=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*@[0-9][a-zA-Z0-9.+()_@/-]*$/u;function _a(e,t){let r=Object.keys(e).sort(),n=[...t].sort();return r.length===n.length&&r.every((i,a)=>i===n[a])}function m_(e){return v(E(e))}function g_(e){if(!_a(e,["schemaVersion","jobId","workerReleaseId","workerStateRevision","requestDigest","pnpmVersion","desiredLockfile","desiredLockDigest","importerFacts","packageFacts","snapshotClosureDigest","networkObservationDigest","cacheObservation","commandDigest","completedAt","expiresAt"])||e.schemaVersion!==1||e.pnpmVersion!=="11.21.0")throw new je("RESOLUTION_EVIDENCE_INVALID");if(![e.jobId,e.workerStateRevision,e.requestDigest,e.desiredLockDigest,e.snapshotClosureDigest,e.networkObservationDigest,e.commandDigest,e.cacheObservation.preimageRevision,e.cacheObservation.desiredRevision,e.cacheObservation.writesDigest].every(i=>Tc.test(i)))throw new je("RESOLUTION_EVIDENCE_INVALID");if(!ka.test(e.workerReleaseId)||!ka.test(e.cacheObservation.namespace)||e.desiredLockfile.byteLength===0||v(e.desiredLockfile)!==e.desiredLockDigest||Number.isNaN(Date.parse(e.completedAt))||Number.isNaN(Date.parse(e.expiresAt))||Date.parse(e.expiresAt)<=Date.parse(e.completedAt))throw new je("RESOLUTION_EVIDENCE_INVALID");if(!_a(e.cacheObservation,["namespace","preimageRevision","desiredRevision","writesDigest"])||e.importerFacts.length===0||e.packageFacts.length===0)throw new je("RESOLUTION_EVIDENCE_INVALID");if(e.importerFacts.some(i=>!_a(i,["importerId","manifestDigest","preimageDigest","desiredDigest"])||i.importerId!=="."&&!ka.test(i.importerId)||![i.manifestDigest,i.preimageDigest,i.desiredDigest].every(a=>Tc.test(a))))throw new je("RESOLUTION_EVIDENCE_INVALID");if(e.packageFacts.some(i=>!_a(i,["identity","packageName","version","integrity","registryId","managed","edgesDigest"])||!f_.test(i.identity)||!u_.test(i.packageName)||!ka.test(i.registryId)||!p_.test(i.version)||!d_.test(i.integrity)||typeof i.managed!="boolean"||!Tc.test(i.edgesDigest)))throw new je("RESOLUTION_EVIDENCE_INVALID");if(new Set(e.importerFacts.map(i=>i.importerId)).size!==e.importerFacts.length||new Set(e.packageFacts.map(i=>i.identity)).size!==e.packageFacts.length)throw new je("RESOLUTION_EVIDENCE_INVALID");let{jobId:t,desiredLockfile:r,...n}=e;if(m_(n)!==e.jobId)throw new je("RESOLUTION_EVIDENCE_INVALID")}function Lc(e,t){if(g_(e),Date.parse(t.now)>Date.parse(e.expiresAt))throw new je("RESOLUTION_EVIDENCE_EXPIRED");if(e.requestDigest!==t.requestDigest||e.pnpmVersion!==t.pnpmVersion||e.workerReleaseId!==t.workerReleaseId)throw new je("RESOLUTION_EVIDENCE_INVALID");let r=e.importerFacts.find(n=>n.importerId===t.targetImporterId);if(!r||r.manifestDigest!==t.targetManifestDigest)throw new je("RESOLUTION_EVIDENCE_IMPORTER_DRIFT");for(let n of t.preservedImporterDigests){let i=e.importerFacts.find(a=>a.importerId===n.importerId);if(!i||i.preimageDigest!==n.preimageDigest||i.desiredDigest!==n.preimageDigest)throw new je("RESOLUTION_EVIDENCE_IMPORTER_DRIFT")}for(let n of t.managedSources){let i=e.packageFacts.filter(a=>a.managed&&a.packageName===n.packageName);if(i.length!==1||i[0].registryId!==n.registryId||i[0].version!==n.version||i[0].integrity!==n.integrity)throw new je("RESOLUTION_EVIDENCE_SOURCE_MISMATCH")}if(e.packageFacts.filter(n=>n.managed).length!==t.managedSources.length)throw new je("RESOLUTION_EVIDENCE_SOURCE_MISMATCH");return e}var H=class extends Error{code;constructor(t,r){super(t,r),this.code=t,this.name="PackageAdoptionError"}};function Ra(e){let t={sourceChannel:e.sourceChannel,packageJsonPreimageDigest:e.packageJsonPreimageDigest,desiredPackageJsonDigest:e.desiredPackageJsonDigest,lockfilePreimage:{...e.lockfilePreimage},desiredLockfileDigest:e.desiredLockfileDigest,registryRevisions:e.registryRevisions.map(r=>({...r})),endpointBindings:e.endpointBindings.map(({registryId:r,registryConfigRevision:n,bindingDigest:i,expiresAt:a})=>({registryId:r,registryConfigRevision:n,bindingDigest:i,expiresAt:a})),sources:e.sources.map(r=>({...r})),installPolicy:{...e.installPolicy}};if(e.schemaVersion===1)return{schemaVersion:1,...t};if(!e.topology||!e.preservedDependencies||!e.preservedImporterDigests)throw new H("PACKAGE_SOURCE_POLICY_VIOLATION");return{schemaVersion:2,...t,topology:{...e.topology},preservedDependencies:e.preservedDependencies.map(r=>({...r})),preservedImporterDigests:e.preservedImporterDigests.map(r=>({...r}))}}var Ea=/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/u,lf=/^(?:workspace:|file:|link:|git(?:\+|:)|https?:|npm:)|[~^*<>=|]/u;function Vc(e){return Array.isArray(e)?`[${e.map(Vc).join(",")}]`:e!==null&&typeof e=="object"?`{${Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>`${JSON.stringify(t)}:${Vc(r)}`).join(",")}}`:JSON.stringify(e)}function At(e){let t;try{t=JSON.parse(Buffer.from(e).toString("utf8"))}catch{throw new H("PACKAGE_SOURCE_POLICY_VIOLATION")}if(!t||typeof t!="object"||Array.isArray(t))throw new H("PACKAGE_SOURCE_POLICY_VIOLATION");return t}function Qe(e){if(e===void 0)return{};if(!e||typeof e!="object"||Array.isArray(e))throw new H("PACKAGE_SOURCE_POLICY_VIOLATION");let t=Object.entries(e);if(t.some(([,r])=>typeof r!="string"))throw new H("PACKAGE_SOURCE_POLICY_VIOLATION");return Object.fromEntries(t)}function Aa(e){for(let t of[Qe(e.dependencies),Qe(e.devDependencies),Qe(e.optionalDependencies)])for(let[r,n]of Object.entries(t))if(r.startsWith("@aipt/")&&(!Ea.test(n)||lf.test(n)))throw new H("PACKAGE_SOURCE_POLICY_VIOLATION")}var h_=["dependencies","devDependencies","optionalDependencies"];function Pa(e,t){let r=[];for(let n of h_)for(let[i,a]of Object.entries(Qe(e[n]))){if(t.has(i)){if(!Ea.test(a))throw new H("PACKAGE_SOURCE_POLICY_VIOLATION");continue}if(/^(?:file:|link:|git(?:\+|:)|https?:|npm:)/u.test(a))throw new H("PACKAGE_SOURCE_POLICY_VIOLATION");r.push({section:n,packageName:i,specifier:a})}return r.sort((n,i)=>`${n.section}:${n.packageName}`.localeCompare(`${i.section}:${i.packageName}`))}function Mc(e){let t=At(e.packageJson);Aa(t);let r=Object.fromEntries(e.release.packageSources.filter(({usage:a})=>a==="runtime").map(({packageName:a,version:o})=>[a,o])),n=Object.fromEntries(e.release.packageSources.filter(({usage:a})=>a==="development").map(({packageName:a,version:o})=>[a,o])),i={...t,...Object.keys(r).length?{dependencies:{...Qe(t.dependencies),...r}}:{},...Object.keys(n).length?{devDependencies:{...Qe(t.devDependencies),...n}}:{}};return Buffer.from(`${JSON.stringify(i,null,2)}
|
|
29
|
+
`)}async function Hu(e,t){let r=zn.join(e,...t.split("/"));try{let n=await Jk(r);if(!n.isFile()||n.isSymbolicLink())throw new M("PROJECT_STATE_INVALID","Managed target must be a regular file",t);return{path:t,exists:!0,digest:v(await jc(r))}}catch(n){if(n.code==="ENOENT")return{path:t,exists:!1};throw n}}async function mr(e,t){let r=G(e.manifest),n=t==="workspace-node-application"||t==="workspace-web-application"||t==="workspace-expo-application"||t==="nextjs-full-stack-application"?t==="workspace-web-application"?Qk(fr(r).name):t==="workspace-expo-application"?t_(fr(r).name):t==="nextjs-full-stack-application"?e_(fr(r).name):Xk(fr(r).name):t==="react-component-library"?Oc(Ft(r,t)):$c(Ft(r,t));if(r.capabilities.filter(u=>u.capabilityId===e.release.release.capabilityId&&u.version===e.release.release.version).length!==1||e.release.release.consumerProfile!==t)throw new M("RELEASE_NOT_FOUND","Manifest must select exactly the loaded standalone npm release");let o=(e.currentLock===void 0?void 0:Te(e.currentLock))?.capabilities.find(u=>u.capabilityId===e.release.release.capabilityId);if(o!==void 0&&(o.version!==e.release.release.version||o.integrity!==e.release.release.integrity))throw new M("CONSUMER_PROFILE_UNSUPPORTED","Changing locked npm profile parameters or release is not supported");let s=new Map(e.release.contents);s.set("package.json",n);let c=await Yu(zn.resolve(e.projectRoot)),d=[],l=[];for(let u of e.release.release.assets){if(s.get(u.path)===void 0)throw new M("RELEASE_NOT_FOUND","Release asset content is unavailable",u.path);let g=await Hu(c,u.path);if(g.exists&&o===void 0&&e.allowExistingWithoutLock!==!0&&u.ownership!=="seed-file")throw new M("CONSUMER_PROFILE_UNSUPPORTED","Profile cannot adopt over an existing owned file without a lock",u.path);u.ownership==="seed-file"&&g.exists&&s.set(u.path,await jc(zn.join(c,...u.path.split("/"))));let h=v(s.get(u.path));d.push(g),l.push({path:u.path,kind:"create",ownership:u.ownership,desiredDigest:h})}let p={schemaVersion:1,capabilityId:e.release.release.capabilityId,version:e.release.release.version,integrity:e.release.release.integrity,assets:l.map(u=>({path:u.path,ownership:u.ownership,desiredDigest:u.desiredDigest})),verifiers:e.release.release.verifiers.map(({id:u})=>({id:u,kind:"command"}))},m=De({action:"adopt",capability:p,changes:l,observedAssets:d,generatedAt:e.generatedAt,expiresAt:e.expiresAt});return{manifest:r,release:e.release,plan:m,desiredContents:s}}function Bn(e){return mr(e,"standalone-npm-package")}function Gn(e){return mr(e,"react-component-library")}function Yr(e){return mr(e,"nextjs-full-stack-application")}async function Cc(e){let t=G(e.manifest);if(t.profile?.id!=="nextjs-full-stack-application"||e.release.release.consumerProfile!=="nextjs-full-stack-application"||e.release.release.assets.some(u=>u.ownership!=="seed-file"))throw new M("CONSUMER_PROFILE_UNSUPPORTED","Historical adoption requires a seed-only Next.js Profile Release");let r=G({...t,capabilities:[{capabilityId:e.release.release.capabilityId,version:e.release.release.version}]}),n=await Yr({...e,manifest:r}),i=await Yu(zn.resolve(e.projectRoot)),a="project-capabilities.json",o=await jc(zn.join(i,a)),s=Buffer.from(`${JSON.stringify(r,null,2)}
|
|
30
|
+
`),c=n.plan.operations.map(({disposition:u,conflictCode:f,...g})=>g);c.push({path:a,kind:"replace",ownership:"owned-file",baseDigest:v(o),desiredDigest:v(s)});let d=await Promise.all(c.map(u=>Hu(i,u.path))),l=De({action:"adopt",capability:{schemaVersion:1,capabilityId:e.release.release.capabilityId,version:e.release.release.version,integrity:e.release.release.integrity,assets:c.filter(u=>u.path!==a).map(u=>({path:u.path,ownership:u.ownership,desiredDigest:u.desiredDigest})),verifiers:e.release.release.verifiers.map(({id:u})=>({id:u,kind:"command"}))},changes:c,observedAssets:d,generatedAt:e.generatedAt,expiresAt:e.expiresAt}),p=new Map([...n.desiredContents,[a,s]]),m=new Map;for(let u of l.operations)u.disposition==="ready"&&u.kind!=="remove"&&m.set(u.path,p.get(u.path));return{...n,manifest:r,plan:l,desiredContents:m}}function Jn(e){return mr(e,"workspace-npm-package")}function Wn(e){return mr(e,"workspace-node-application")}function Kn(e){return mr(e,"workspace-web-application")}function Yn(e){return mr(e,"workspace-expo-application")}async function Zu(e){if(e.currentLock!==void 0){let n=await Bn(e);return{state:n.plan.state==="conflicted"?"drifted":"adopted",operations:n.plan.operations}}let t=await Bn({...e,allowExistingWithoutLock:!0});return t.plan.operations.filter(n=>n.disposition!=="ready").length===0?{state:"planned",operations:t.plan.operations}:t.plan.operations.every(n=>n.disposition==="noop")?{state:"applied-unverified",operations:t.plan.operations}:{state:"drifted",operations:t.plan.operations}}async function Xu(e){if(e.currentLock!==void 0){let n=await Gn(e);return{state:n.plan.state==="conflicted"?"drifted":"adopted",operations:n.plan.operations}}let t=await Gn({...e,allowExistingWithoutLock:!0});return t.plan.operations.filter(n=>n.disposition!=="ready").length===0?{state:"planned",operations:t.plan.operations}:t.plan.operations.every(n=>n.disposition==="noop")?{state:"applied-unverified",operations:t.plan.operations}:{state:"drifted",operations:t.plan.operations}}async function Qu(e){if(e.currentLock!==void 0){let n=await Yr(e);return{state:n.plan.state==="conflicted"?"drifted":"adopted",operations:n.plan.operations}}let t=await Yr({...e,allowExistingWithoutLock:!0});return t.plan.operations.filter(n=>n.disposition!=="ready").length===0?{state:"planned",operations:t.plan.operations}:t.plan.operations.every(n=>n.disposition==="noop")?{state:"applied-unverified",operations:t.plan.operations}:{state:"drifted",operations:t.plan.operations}}async function ef(e){if(e.currentLock!==void 0){let n=await Jn(e);return{state:n.plan.state==="conflicted"?"drifted":"adopted",operations:n.plan.operations}}let t=await Jn({...e,allowExistingWithoutLock:!0});return t.plan.operations.filter(n=>n.disposition!=="ready").length===0?{state:"planned",operations:t.plan.operations}:t.plan.operations.every(n=>n.disposition==="noop")?{state:"applied-unverified",operations:t.plan.operations}:{state:"drifted",operations:t.plan.operations}}async function tf(e){if(e.currentLock!==void 0){let n=await Wn(e);return{state:n.plan.state==="conflicted"?"drifted":"adopted",operations:n.plan.operations}}let t=await Wn({...e,allowExistingWithoutLock:!0});return t.plan.operations.filter(n=>n.disposition!=="ready").length===0?{state:"planned",operations:t.plan.operations}:t.plan.operations.every(n=>n.disposition==="noop")?{state:"applied-unverified",operations:t.plan.operations}:{state:"drifted",operations:t.plan.operations}}async function rf(e){if(e.currentLock!==void 0){let n=await Kn(e);return{state:n.plan.state==="conflicted"?"drifted":"adopted",operations:n.plan.operations}}let t=await Kn({...e,allowExistingWithoutLock:!0});return t.plan.operations.filter(n=>n.disposition!=="ready").length===0?{state:"planned",operations:t.plan.operations}:t.plan.operations.every(n=>n.disposition==="noop")?{state:"applied-unverified",operations:t.plan.operations}:{state:"drifted",operations:t.plan.operations}}async function nf(e){if(e.currentLock!==void 0){let n=await Yn(e);return{state:n.plan.state==="conflicted"?"drifted":"adopted",operations:n.plan.operations}}let t=await Yn({...e,allowExistingWithoutLock:!0});return t.plan.operations.filter(n=>n.disposition!=="ready").length===0?{state:"planned",operations:t.plan.operations}:t.plan.operations.every(n=>n.disposition==="noop")?{state:"applied-unverified",operations:t.plan.operations}:{state:"drifted",operations:t.plan.operations}}import{lstat as N_,readFile as Va,realpath as D_}from"node:fs/promises";import ei from"node:path";var ct=class extends Error{code;constructor(t,r){super(r),this.code=t}},gr=/^sha256:[a-f0-9]{64}$/,r_=/^sha512-[A-Za-z0-9+/]{86}==$/,n_=/^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/,of=/^registry\.[a-z0-9][a-z0-9.-]{1,126}$/,i_=/^@[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*$/,af=/^[a-z][a-z0-9._:-]{2,127}$/;function hr(e,t){let r=Object.keys(e).sort();return r.length===t.length&&r.every((n,i)=>n===[...t].sort()[i])}function a_(e){if(!hr(e,["registryId","tenantId","origin","scopes","authentication","capabilities","status"])||!of.test(e.registryId)||!af.test(e.tenantId)||e.scopes.length===0||e.scopes.length>32||e.scopes.some((n,i)=>!/^@[a-z0-9][a-z0-9._-]*$/.test(n)||e.scopes.indexOf(n)!==i)||!hr(e.authentication,e.authentication.credentialRef===void 0?["kind"]:["kind","credentialRef"])||!hr(e.capabilities,["read","write","provenance","staging"])||!["workload-identity","short-lived-token","restricted-token","anonymous-test"].includes(e.authentication.kind)||e.authentication.kind==="anonymous-test"!=(e.authentication.credentialRef===void 0)||e.authentication.credentialRef!==void 0&&!af.test(e.authentication.credentialRef))return!1;let t;try{t=new URL(e.origin)}catch{return!1}if(t.username||t.password||t.search||t.hash||!t.pathname.endsWith("/")||t.pathname.includes("..")||/%2f|%5c/iu.test(t.pathname))return!1;let r=t.hostname==="127.0.0.1"||t.hostname==="localhost"||t.hostname==="[::1]";return e.authentication.kind==="anonymous-test"&&(!r||t.protocol!=="http:")||e.authentication.kind!=="anonymous-test"&&t.protocol!=="https:"?!1:typeof e.capabilities.read=="boolean"&&typeof e.capabilities.write=="boolean"&&typeof e.capabilities.provenance=="boolean"&&typeof e.capabilities.staging=="boolean"&&(e.status==="enabled"||e.status==="disabled")}function o_(e){if(!a_(e))throw new ct("REGISTRY_CONFIG_INVALID","Registry configuration is invalid");let t={schemaVersion:1,...e};return Object.freeze({...t,scopes:Object.freeze([...e.scopes]),authentication:Object.freeze({...e.authentication}),capabilities:Object.freeze({...e.capabilities}),revision:v(E(t))})}function ba(e){let t=e;if(typeof t!="object"||t===null||!hr(t,["schemaVersion","revision","registryId","tenantId","origin","scopes","authentication","capabilities","status"])||t.schemaVersion!==1||!gr.test(t.revision))throw new ct("REGISTRY_CONFIG_INVALID","Registry configuration is invalid");let{schemaVersion:r,revision:n,...i}=t;if(o_(i).revision!==n)throw new ct("REGISTRY_CONFIG_INVALID","Registry configuration has been modified");return t}function s_(e,t){let r,n;try{r=new URL(e.origin),n=new URL(t)}catch{return!1}return n.username||n.password||n.search||n.hash||n.pathname!==r.pathname||n.protocol!==r.protocol||n.hostname!==r.hostname?!1:e.authentication.kind==="anonymous-test"||n.port===r.port}function c_(e,t){let r=ba(t);if(!hr(e,["registryId","registryConfigRevision","origin","resolvedAt","expiresAt"])||e.registryId!==r.registryId||e.registryConfigRevision!==r.revision||!s_(r,e.origin)||Number.isNaN(Date.parse(e.resolvedAt))||Number.isNaN(Date.parse(e.expiresAt))||Date.parse(e.expiresAt)<=Date.parse(e.resolvedAt))throw new ct("REGISTRY_ENDPOINT_BINDING_INVALID","Registry endpoint binding is invalid");let n={schemaVersion:1,...e};return Object.freeze({...n,bindingDigest:v(E(n))})}function sf(e,t){let r=e;if(typeof r!="object"||r===null||!hr(r,["schemaVersion","bindingDigest","registryId","registryConfigRevision","origin","resolvedAt","expiresAt"])||r.schemaVersion!==1||!gr.test(r.bindingDigest))throw new ct("REGISTRY_ENDPOINT_BINDING_INVALID","Registry endpoint binding is invalid");let{schemaVersion:n,bindingDigest:i,...a}=r;if(c_(a,t).bindingDigest!==i)throw new ct("REGISTRY_ENDPOINT_BINDING_INVALID","Registry endpoint binding has been modified");return r}function l_(e){let t=["registryId","registryConfigRevision","packageName","version","integrity","tarballDigest","access","provenance","sourceDeliveryReceiptId","verifiedAt",...e.verificationIdentityDigest===void 0?[]:["verificationIdentityDigest"]];return hr(e,t)&&of.test(e.registryId)&&gr.test(e.registryConfigRevision)&&i_.test(e.packageName)&&n_.test(e.version)&&r_.test(e.integrity)&&gr.test(e.tarballDigest)&&gr.test(e.sourceDeliveryReceiptId)&&!Number.isNaN(Date.parse(e.verifiedAt))&&(e.access==="restricted"||e.access==="private")&&["registry-attested","external-attested","local-readback-verified","development-readback-verified","registry-verified-no-attestation"].includes(e.provenance)&&(e.provenance!=="registry-verified-no-attestation"?e.verificationIdentityDigest!==void 0&&gr.test(e.verificationIdentityDigest):e.verificationIdentityDigest===void 0)}function cf(e){if(!l_(e))throw new ct("PACKAGE_RECEIPT_INVALID","Package delivery receipt is invalid");let t={schemaVersion:1,...e};return Object.freeze({...t,receiptId:v(E(t))})}function lf(e){let t=e;if(typeof t!="object"||t===null||t.schemaVersion!==1||!gr.test(t.receiptId))throw new ct("PACKAGE_RECEIPT_INVALID","Package delivery receipt is invalid");let{schemaVersion:r,receiptId:n,...i}=t;if(cf(i).receiptId!==n)throw new ct("PACKAGE_RECEIPT_INVALID","Package delivery receipt has been modified");return t}var je=class extends Error{code;constructor(t){super(t),this.code=t,this.name="ResolutionEvidenceError"}};function xc(e){return v(E(e))}var Tc=/^sha256:[a-f0-9]{64}$/u,d_=/^sha512-[A-Za-z0-9+/]{86}==$/u,p_=/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u,ka=/^[a-z0-9][a-z0-9._/-]{0,255}$/u,u_=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u,f_=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*@[0-9][a-zA-Z0-9.+()_@/-]*$/u;function _a(e,t){let r=Object.keys(e).sort(),n=[...t].sort();return r.length===n.length&&r.every((i,a)=>i===n[a])}function m_(e){return v(E(e))}function g_(e){if(!_a(e,["schemaVersion","jobId","workerReleaseId","workerStateRevision","requestDigest","pnpmVersion","desiredLockfile","desiredLockDigest","importerFacts","packageFacts","snapshotClosureDigest","networkObservationDigest","cacheObservation","commandDigest","completedAt","expiresAt"])||e.schemaVersion!==1||e.pnpmVersion!=="11.21.0")throw new je("RESOLUTION_EVIDENCE_INVALID");if(![e.jobId,e.workerStateRevision,e.requestDigest,e.desiredLockDigest,e.snapshotClosureDigest,e.networkObservationDigest,e.commandDigest,e.cacheObservation.preimageRevision,e.cacheObservation.desiredRevision,e.cacheObservation.writesDigest].every(i=>Tc.test(i)))throw new je("RESOLUTION_EVIDENCE_INVALID");if(!ka.test(e.workerReleaseId)||!ka.test(e.cacheObservation.namespace)||e.desiredLockfile.byteLength===0||v(e.desiredLockfile)!==e.desiredLockDigest||Number.isNaN(Date.parse(e.completedAt))||Number.isNaN(Date.parse(e.expiresAt))||Date.parse(e.expiresAt)<=Date.parse(e.completedAt))throw new je("RESOLUTION_EVIDENCE_INVALID");if(!_a(e.cacheObservation,["namespace","preimageRevision","desiredRevision","writesDigest"])||e.importerFacts.length===0||e.packageFacts.length===0)throw new je("RESOLUTION_EVIDENCE_INVALID");if(e.importerFacts.some(i=>!_a(i,["importerId","manifestDigest","preimageDigest","desiredDigest"])||i.importerId!=="."&&!ka.test(i.importerId)||![i.manifestDigest,i.preimageDigest,i.desiredDigest].every(a=>Tc.test(a))))throw new je("RESOLUTION_EVIDENCE_INVALID");if(e.packageFacts.some(i=>!_a(i,["identity","packageName","version","integrity","registryId","managed","edgesDigest"])||!f_.test(i.identity)||!u_.test(i.packageName)||!ka.test(i.registryId)||!p_.test(i.version)||!d_.test(i.integrity)||typeof i.managed!="boolean"||!Tc.test(i.edgesDigest)))throw new je("RESOLUTION_EVIDENCE_INVALID");if(new Set(e.importerFacts.map(i=>i.importerId)).size!==e.importerFacts.length||new Set(e.packageFacts.map(i=>i.identity)).size!==e.packageFacts.length)throw new je("RESOLUTION_EVIDENCE_INVALID");let{jobId:t,desiredLockfile:r,...n}=e;if(m_(n)!==e.jobId)throw new je("RESOLUTION_EVIDENCE_INVALID")}function Lc(e,t){if(g_(e),Date.parse(t.now)>Date.parse(e.expiresAt))throw new je("RESOLUTION_EVIDENCE_EXPIRED");if(e.requestDigest!==t.requestDigest||e.pnpmVersion!==t.pnpmVersion||e.workerReleaseId!==t.workerReleaseId)throw new je("RESOLUTION_EVIDENCE_INVALID");let r=e.importerFacts.find(n=>n.importerId===t.targetImporterId);if(!r||r.manifestDigest!==t.targetManifestDigest)throw new je("RESOLUTION_EVIDENCE_IMPORTER_DRIFT");for(let n of t.preservedImporterDigests){let i=e.importerFacts.find(a=>a.importerId===n.importerId);if(!i||i.preimageDigest!==n.preimageDigest||i.desiredDigest!==n.preimageDigest)throw new je("RESOLUTION_EVIDENCE_IMPORTER_DRIFT")}for(let n of t.managedSources){let i=e.packageFacts.filter(a=>a.managed&&a.packageName===n.packageName);if(i.length!==1||i[0].registryId!==n.registryId||i[0].version!==n.version||i[0].integrity!==n.integrity)throw new je("RESOLUTION_EVIDENCE_SOURCE_MISMATCH")}if(e.packageFacts.filter(n=>n.managed).length!==t.managedSources.length)throw new je("RESOLUTION_EVIDENCE_SOURCE_MISMATCH");return e}var Z=class extends Error{code;constructor(t,r){super(t,r),this.code=t,this.name="PackageAdoptionError"}};function Ra(e){let t={sourceChannel:e.sourceChannel,packageJsonPreimageDigest:e.packageJsonPreimageDigest,desiredPackageJsonDigest:e.desiredPackageJsonDigest,lockfilePreimage:{...e.lockfilePreimage},desiredLockfileDigest:e.desiredLockfileDigest,registryRevisions:e.registryRevisions.map(r=>({...r})),endpointBindings:e.endpointBindings.map(({registryId:r,registryConfigRevision:n,bindingDigest:i,expiresAt:a})=>({registryId:r,registryConfigRevision:n,bindingDigest:i,expiresAt:a})),sources:e.sources.map(r=>({...r})),installPolicy:{...e.installPolicy}};if(e.schemaVersion===1)return{schemaVersion:1,...t};if(!e.topology||!e.preservedDependencies||!e.preservedImporterDigests)throw new Z("PACKAGE_SOURCE_POLICY_VIOLATION");return{schemaVersion:2,...t,topology:{...e.topology},preservedDependencies:e.preservedDependencies.map(r=>({...r})),preservedImporterDigests:e.preservedImporterDigests.map(r=>({...r}))}}var Ea=/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/u,df=/^(?:workspace:|file:|link:|git(?:\+|:)|https?:|npm:)|[~^*<>=|]/u;function Vc(e){return Array.isArray(e)?`[${e.map(Vc).join(",")}]`:e!==null&&typeof e=="object"?`{${Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>`${JSON.stringify(t)}:${Vc(r)}`).join(",")}}`:JSON.stringify(e)}function At(e){let t;try{t=JSON.parse(Buffer.from(e).toString("utf8"))}catch{throw new Z("PACKAGE_SOURCE_POLICY_VIOLATION")}if(!t||typeof t!="object"||Array.isArray(t))throw new Z("PACKAGE_SOURCE_POLICY_VIOLATION");return t}function Qe(e){if(e===void 0)return{};if(!e||typeof e!="object"||Array.isArray(e))throw new Z("PACKAGE_SOURCE_POLICY_VIOLATION");let t=Object.entries(e);if(t.some(([,r])=>typeof r!="string"))throw new Z("PACKAGE_SOURCE_POLICY_VIOLATION");return Object.fromEntries(t)}function Aa(e){for(let t of[Qe(e.dependencies),Qe(e.devDependencies),Qe(e.optionalDependencies)])for(let[r,n]of Object.entries(t))if(r.startsWith("@aipt/")&&(!Ea.test(n)||df.test(n)))throw new Z("PACKAGE_SOURCE_POLICY_VIOLATION")}var h_=["dependencies","devDependencies","optionalDependencies"];function Pa(e,t){let r=[];for(let n of h_)for(let[i,a]of Object.entries(Qe(e[n]))){if(t.has(i)){if(!Ea.test(a))throw new Z("PACKAGE_SOURCE_POLICY_VIOLATION");continue}if(/^(?:file:|link:|git(?:\+|:)|https?:|npm:)/u.test(a))throw new Z("PACKAGE_SOURCE_POLICY_VIOLATION");r.push({section:n,packageName:i,specifier:a})}return r.sort((n,i)=>`${n.section}:${n.packageName}`.localeCompare(`${i.section}:${i.packageName}`))}function Mc(e){let t=At(e.packageJson);Aa(t);let r=Object.fromEntries(e.release.packageSources.filter(({usage:a})=>a==="runtime").map(({packageName:a,version:o})=>[a,o])),n=Object.fromEntries(e.release.packageSources.filter(({usage:a})=>a==="development").map(({packageName:a,version:o})=>[a,o])),i={...t,...Object.keys(r).length?{dependencies:{...Qe(t.dependencies),...r}}:{},...Object.keys(n).length?{devDependencies:{...Qe(t.devDependencies),...n}}:{}};return Buffer.from(`${JSON.stringify(i,null,2)}
|
|
31
31
|
`)}function Hn(e){let t=At(e.packageJson);Pa(t,new Set(e.release.packageSources.map(i=>i.packageName)));let r=Object.fromEntries(e.release.packageSources.filter(({usage:i})=>i==="runtime").map(({packageName:i,version:a})=>[i,a])),n=Object.fromEntries(e.release.packageSources.filter(({usage:i})=>i==="development").map(({packageName:i,version:a})=>[i,a]));return Buffer.from(`${JSON.stringify({...t,...Object.keys(r).length?{dependencies:{...Qe(t.dependencies),...r}}:{},...Object.keys(n).length?{devDependencies:{...Qe(t.devDependencies),...n}}:{}},null,2)}
|
|
32
32
|
`)}function qc(e){let t=At(e.packageJson);Aa(t);let r=Qe(t.dependencies),n=Qe(t.devDependencies);for(let a of e.remove)delete(a.usage==="runtime"?r:n)[a.packageName];let i={...t};return Object.keys(r).length===0?delete i.dependencies:i.dependencies=r,Object.keys(n).length===0?delete i.devDependencies:i.devDependencies=n,Buffer.from(`${JSON.stringify(i,null,2)}
|
|
33
33
|
`)}function Uc(e){let t=At(e.packageJson);Pa(t,new Set(e.remove.map(a=>a.packageName)));let r=Qe(t.dependencies),n=Qe(t.devDependencies);for(let a of e.remove)delete(a.usage==="runtime"?r:n)[a.packageName];let i={...t};return Object.keys(r).length===0?delete i.dependencies:i.dependencies=r,Object.keys(n).length===0?delete i.devDependencies:i.devDependencies=n,Buffer.from(`${JSON.stringify(i,null,2)}
|
|
34
|
-
`)}function
|
|
35
|
-
`),c=e.endpointBindings.filter(p=>n.some(m=>m.registryId===p.registryId)),d=[{path:"project-capabilities.json",kind:"replace",ownership:"owned-file",baseDigest:v(e.projectManifest),desiredDigest:v(s)},{path:"package.json",kind:"replace",ownership:"owned-file",baseDigest:v(e.packageJson),desiredDigest:v(i)},{path:"pnpm-lock.yaml",kind:"replace",ownership:"owned-file",baseDigest:v(e.currentLockfile),desiredDigest:v(e.desiredLockfile)},...t.assets.map(p=>({path:p.path,kind:"remove",ownership:p.ownership??"owned-file",baseDigest:p.digest}))];return{plan:De({action:"remove",capability:{schemaVersion:1,capabilityId:e.release.capabilityId,version:e.release.version,integrity:e.release.integrity,assets:t.assets.map(p=>({path:p.path,ownership:p.ownership??"owned-file",desiredDigest:p.digest})),verifiers:e.release.verifiers.map(p=>({id:p.id,kind:"file-digest"}))},changes:d,observedAssets:[...e.observedAssets],generatedAt:e.generatedAt,expiresAt:e.expiresAt,packageAdoption:{schemaVersion:1,sourceChannel:t.packageAdoption.sourceChannel??"production",packageJsonPreimageDigest:v(e.packageJson),desiredPackageJsonDigest:v(i),lockfilePreimage:{kind:"present",digest:v(e.currentLockfile)},desiredLockfileDigest:v(e.desiredLockfile),registryRevisions:t.packageAdoption.registryRevisions.map(p=>({...p})),endpointBindings:c.map(({registryId:p,registryConfigRevision:m,bindingDigest:u,expiresAt:f})=>({registryId:p,registryConfigRevision:m,bindingDigest:u,expiresAt:f})),sources:n.map(p=>({...p})),installPolicy:{ignoreScripts:!0,allowWorkspaceProtocol:!1,allowPublicRegistryFallback:!1}}}),desiredContents:new Map([["project-capabilities.json",s],["package.json",i],["pnpm-lock.yaml",e.desiredLockfile]]),removedSources:n}}function
|
|
36
|
-
`),p=g=>`${e.topology.unitRelativeRoot}/${g}`,m=e.endpointBindings.filter(g=>n.some(h=>h.registryId===g.registryId)),u=[{path:p("project-capabilities.json"),kind:"replace",ownership:"owned-file",baseDigest:v(e.projectManifest),desiredDigest:v(l)},{path:p("package.json"),kind:"replace",ownership:"owned-file",baseDigest:v(e.packageJson),desiredDigest:v(i)},{path:e.topology.lockfilePath,kind:"replace",ownership:"owned-file",baseDigest:v(e.currentLockfile),desiredDigest:s.desiredLockDigest},...t.assets.map(g=>({path:p(g.path),kind:"remove",ownership:g.ownership??"owned-file",baseDigest:g.digest}))];return{plan:De({action:"remove",capability:{schemaVersion:1,capabilityId:e.release.capabilityId,version:e.release.version,integrity:e.release.integrity,assets:t.assets.map(g=>({path:g.path,ownership:g.ownership??"owned-file",desiredDigest:g.digest})),verifiers:e.release.verifiers.map(g=>({id:g.id,kind:"file-digest"}))},changes:u,observedAssets:[...e.observedAssets],generatedAt:e.generatedAt,expiresAt:e.expiresAt,packageAdoption:{schemaVersion:2,sourceChannel:t.packageAdoption.sourceChannel??"production",packageJsonPreimageDigest:v(e.packageJson),desiredPackageJsonDigest:v(i),lockfilePreimage:{kind:"present",digest:v(e.currentLockfile)},desiredLockfileDigest:s.desiredLockDigest,registryRevisions:t.packageAdoption.registryRevisions.map(g=>({...g})),endpointBindings:m.map(({registryId:g,registryConfigRevision:h,bindingDigest:w,expiresAt:_})=>({registryId:g,registryConfigRevision:h,bindingDigest:w,expiresAt:_})),sources:n.map(g=>({...g})),installPolicy:{ignoreScripts:!0,allowWorkspaceProtocol:!1,allowPublicRegistryFallback:!1},topology:o,preservedDependencies:Pa(At(i),new Set(e.remainingSources.map(g=>g.packageName))),preservedImporterDigests:e.preservedImporterDigests.map(g=>({...g}))}}),desiredContents:new Map([[p("project-capabilities.json"),l],[p("package.json"),i],[e.topology.lockfilePath,s.desiredLockfile]]),removedSources:n,transactionRoot:e.transactionRoot}}function Na(e,t){let r=e.release.availability,n=r.maturity==="available"&&r.visibility==="catalog-consumers"&&r.sourceState==="registry-verified",i=r.maturity==="candidate"&&r.visibility==="maintainers-only"&&r.sourceState==="development-registry";if((t==="production"?!n:!i)||e.release.packageSources.length===0)throw new H("PACKAGE_SOURCE_NOT_FOUND");let a=At(e.packageJson),o=e.desiredBasePackageJson??e.packageJson,s=At(o),c="topology"in e,d=c?Pa(s,new Set(e.release.packageSources.map(y=>y.packageName))):void 0;c||Aa(a),c||Aa(s);let l=new Map(e.registryConfigs.map(y=>{let k=ba(y);return[k.registryId,k]})),p=new Map(e.endpointBindings.map(y=>{let k=l.get(y.registryId);if(k===void 0)throw new H("PACKAGE_SOURCE_NOT_FOUND");let S=of(y,k);return[S.registryId,S]})),m=new Map(e.receipts.map(y=>{let k=cf(y);return[k.receiptId,k]})),u=new Map(e.inspections.map(y=>[`${y.registryId}:${y.packageName}@${y.version}`,y])),f=new Map(e.release.packageSources.map(y=>[y.packageName,y])),g=c?Lc(e.resolutionEvidence,{requestDigest:xc({schemaVersion:1,pnpmVersion:"11.21.0",topology:e.topology,currentLockfileDigest:e.currentLockfile===void 0?null:v(e.currentLockfile),desiredPackageJsonDigest:v(Hn({release:e.release,packageJson:o})),sources:e.release.packageSources.map(({registryId:y,packageName:k,version:S,integrity:O})=>({registryId:y,packageName:k,version:S,integrity:O})),preservedImporterDigests:e.preservedImporterDigests.map(({importerId:y,preimageDigest:k})=>({importerId:y,preimageDigest:k}))}),pnpmVersion:"11.21.0",workerReleaseId:e.resolutionWorkerReleaseId,targetImporterId:e.topology.unitImporterId,targetManifestDigest:v(Hn({release:e.release,packageJson:o})),preservedImporterDigests:e.preservedImporterDigests.map(({importerId:y,preimageDigest:k})=>({importerId:y,preimageDigest:k})),managedSources:e.release.packageSources.map(({registryId:y,packageName:k,version:S,integrity:O})=>({registryId:y,packageName:k,version:S,integrity:O})),now:e.generatedAt}):void 0,h=c?{lockfile:g.desiredLockfile,packages:g.packageFacts.filter(y=>y.managed).map(({registryId:y,packageName:k,version:S,integrity:O})=>({registryId:y,packageName:k,version:S,integrity:O}))}:e.lockResolution;if(h.lockfile.byteLength===0||h.packages.length!==e.release.packageSources.length)throw new H("PACKAGE_SOURCE_POLICY_VIOLATION",{cause:new Error(`managed resolution count ${h.packages.length}/${e.release.packageSources.length}`)});let w=new Map(h.packages.map(y=>[y.packageName,y]));for(let y of e.release.packageSources){let k=l.get(y.registryId),S=p.get(y.registryId),O=m.get(y.deliveryReceiptId),se=u.get(`${y.registryId}:${y.packageName}@${y.version}`),$=w.get(y.packageName);if(O!==void 0&&(t==="production"&&O.provenance==="development-readback-verified"||t==="development"&&O.provenance!=="development-readback-verified"))throw new H("PACKAGE_SOURCE_POLICY_VIOLATION");if(!k||!S||Date.parse(S.expiresAt)<=Date.parse(e.expiresAt)||k.status!=="enabled"||!k.scopes.some(P=>y.packageName.startsWith(`${P}/`))||!O||!se||!$)throw new H("PACKAGE_SOURCE_NOT_FOUND");if(O.registryId!==y.registryId||O.registryConfigRevision!==k.revision||O.packageName!==y.packageName||O.version!==y.version||O.integrity!==y.integrity||O.tarballDigest!==y.tarballDigest||se.integrity!==y.integrity||se.tarballDigest!==y.tarballDigest||se.deliveryReceiptId!==y.deliveryReceiptId||$.registryId!==y.registryId||$.version!==y.version||$.integrity!==y.integrity)throw new H("PACKAGE_SOURCE_INTEGRITY_MISMATCH");if(!Ea.test(y.version)||se.lifecycleScripts.length>0)throw new H("PACKAGE_SOURCE_POLICY_VIOLATION");for(let[P,Y]of Object.entries(se.dependencies)){let ne=f.get(P);if(P.startsWith("@aipt/")&&(!ne||ne.version!==Y||!Ea.test(Y)))throw new H("PACKAGE_SOURCE_POLICY_VIOLATION",{cause:new Error(`undeclared internal dependency ${y.packageName}->${P}@${Y}`)});if(lf.test(Y))throw new H("PACKAGE_SOURCE_POLICY_VIOLATION")}}let _=c?Hn({release:e.release,packageJson:o}):Mc({release:e.release,packageJson:o}),b={schemaVersion:c?2:1,sourceChannel:t,capabilityId:e.release.capabilityId,capabilityVersion:e.release.version,capabilityIntegrity:e.release.integrity,consumerProfile:e.consumerProfile,generatedAt:e.generatedAt,expiresAt:e.expiresAt,packageJsonPreimageDigest:v(e.packageJson),desiredPackageJsonDigest:v(_),lockfilePreimage:Object.freeze(e.currentLockfile===void 0?{kind:"absent"}:{kind:"present",digest:v(e.currentLockfile)}),desiredLockfileDigest:v(h.lockfile),registryRevisions:Object.freeze([...l.values()].filter(y=>e.release.packageSources.some(k=>k.registryId===y.registryId)).map(({registryId:y,revision:k})=>Object.freeze({registryId:y,revision:k})).sort((y,k)=>y.registryId.localeCompare(k.registryId))),endpointBindings:Object.freeze([...p.values()].filter(y=>e.release.packageSources.some(k=>k.registryId===y.registryId)).map(({registryId:y,registryConfigRevision:k,bindingDigest:S,expiresAt:O})=>Object.freeze({registryId:y,registryConfigRevision:k,bindingDigest:S,expiresAt:O})).sort((y,k)=>y.registryId.localeCompare(k.registryId))),sources:Object.freeze(e.release.packageSources.map(y=>Object.freeze({...y}))),installPolicy:Object.freeze({ignoreScripts:!0,allowWorkspaceProtocol:!1,allowPublicRegistryFallback:!1}),...c?{topology:Object.freeze({...e.topology}),preservedDependencies:Object.freeze(d.map(y=>Object.freeze({...y}))),preservedImporterDigests:Object.freeze(e.preservedImporterDigests.map(y=>Object.freeze({...y})))}:{}},A=v(Vc(b));return Object.freeze({...b,planId:A,desiredPackageJson:_,desiredLockfile:h.lockfile})}function Da(e){return Na(e,"production")}function Sa(e){return Na(e,"development")}function ja(e){return Na(e,"production")}function $a(e){return Na(e,"development")}function y_(e){let t=e.packageAdoption;if(t===void 0)throw new H("PACKAGE_SOURCE_POLICY_VIOLATION");let r=t.schemaVersion===2&&t.topology.mode==="pnpm-shared-lockfile"?`${t.topology.unitRelativeRoot}/package.json`:"package.json",n=t.schemaVersion===2?t.topology.lockfilePath:"pnpm-lock.yaml",i=e.operations.filter(({path:l})=>l===r),a=e.operations.filter(({path:l})=>l===n);if(i.length!==1||a.length!==1)throw new H("PACKAGE_SOURCE_POLICY_VIOLATION");let o=i[0],s=a[0],c=o.kind==="replace"&&o.baseDigest===t.packageJsonPreimageDigest&&o.desiredDigest===t.desiredPackageJsonDigest&&o.disposition==="ready",d=s.kind===(t.lockfilePreimage.kind==="absent"?"create":"replace")&&(t.lockfilePreimage.kind==="absent"?s.baseDigest===void 0:s.baseDigest===t.lockfilePreimage.digest)&&s.desiredDigest===t.desiredLockfileDigest&&s.disposition==="ready";if(!c||!d)throw new H("PACKAGE_SOURCE_POLICY_VIOLATION")}async function uf(e){y_(e.plan);let t=!1;try{await e.packageManager.prepare({projectRoot:e.projectRoot,plan:e.plan});let r=await Jr({projectRoot:e.projectRoot,plan:e.plan,approvedPlanId:e.approvedPlanId,desiredContents:e.desiredContents,now:e.now}),n=await Gr(r);return t=!0,await e.packageManager.install({projectRoot:e.projectRoot,plan:e.plan}),await e.packageManager.verify({projectRoot:e.projectRoot,plan:e.plan}),n}catch(r){if(t){await yc({projectRoot:e.projectRoot,planId:e.plan.planId,now:new Date().toISOString(),failureCode:"PACKAGE_INSTALL_FAILED"});try{await e.packageManager.restore({projectRoot:e.projectRoot,plan:e.plan})}catch(n){throw new H("PACKAGE_INSTALL_RECOVERY_REQUIRED",{cause:n})}}throw r}finally{await e.packageManager.cleanup({projectRoot:e.projectRoot,plan:e.plan})}}var hf=br(nr(),1);var yf=["workspace-node-application","workspace-web-application","nextjs-full-stack-application"],wf="^[a-z0-9][a-z0-9._-]{0,127}$",Zn="^[A-Z][A-Z0-9_]{0,127}$",ff="^(?!/)(?!.*(?:^|/)\\.\\.(?:/|$))(?!.*(?:^|/)\\.(?:/|$))(?!.*\\\\)(?!.*[\\u0000-\\u001f]).+$",w_={$id:"https://schemas.dyyto.dev/platform/application-config-contract-v1.json",type:"object",additionalProperties:!1,required:["$schema","schemaVersion","kind","application","configDirectory","bindings"],properties:{$schema:{const:"https://schemas.dyyto.dev/platform/application-config-contract-v1.json"},schemaVersion:{const:1},kind:{const:"ApplicationConfigContract"},application:{type:"object",additionalProperties:!1,required:["id","profile"],properties:{id:{type:"string",pattern:wf},profile:{enum:yf}}},configDirectory:{type:"object",additionalProperties:!1,required:["rootEnvironmentVariable","relativeDirectory","environmentFile","materializationOwner"],properties:{rootEnvironmentVariable:{const:"IDP_CONFIG_DIR"},relativeDirectory:{type:"string",pattern:"^applications/[a-z0-9][a-z0-9._-]{0,127}$"},environmentFile:{const:".env"},materializationOwner:{const:"external-deployment-control-plane"}}},bindings:{type:"array",maxItems:128,items:{oneOf:[{type:"object",additionalProperties:!1,required:["name","kind","required"],properties:{name:{type:"string",pattern:Zn},kind:{const:"value"},required:{type:"boolean"},default:{type:"string",maxLength:1024}}},{type:"object",additionalProperties:!1,required:["name","kind","required","file"],properties:{name:{type:"string",pattern:Zn},runtimeEnvironmentVariable:{type:"string",pattern:Zn},kind:{const:"secret-file"},required:{type:"boolean"},file:{type:"string",maxLength:512,pattern:ff},provisioning:{oneOf:[{type:"object",additionalProperties:!1,required:["strategy"],properties:{strategy:{const:"external"}}},{type:"object",additionalProperties:!1,required:["strategy"],properties:{strategy:{const:"generated"},bytes:{type:"integer",minimum:16,maximum:128}}},{type:"object",additionalProperties:!1,required:["strategy","template"],properties:{strategy:{const:"derived"},template:{type:"string",minLength:1,maxLength:2048}}}]}}},{type:"object",additionalProperties:!1,required:["name","kind","required","file"],properties:{name:{type:"string",pattern:Zn},runtimeEnvironmentVariable:{type:"string",pattern:Zn},kind:{const:"certificate-file"},required:{type:"boolean"},file:{type:"string",maxLength:512,pattern:ff}}}]}}}},mf=new hf.Ajv2020({allErrors:!0,strict:!0}).compile(w_),gf=/(?:^|_)(?:PASSWORD|PASSWD|TOKEN|SECRET|PRIVATE_KEY|ACCESS_KEY|API_KEY|DATABASE_URL|CONNECTION_STRING|DSN|AUTHORIZATION|CREDENTIALS?)(?:_|$)/u,v_=/(?:^|_)(?:PRIVATE_KEY|PRIVATE|KEYPAIR|KEYSTORE|PKCS12|P12|PFX|KEY)(?:_|$)/u,$e=class extends Error{code;issues;constructor(t,r,n=[]){super(r),this.code=t,this.issues=n}};function vf(e){let t=J(e),r=t.profile?.id;if(!yf.includes(r))throw new $e("APPLICATION_CONFIG_CONTRACT_INVALID","\u73AF\u5883\u914D\u7F6E\u5951\u7EA6\u53EA\u652F\u6301\u53EF\u90E8\u7F72 Application Profile\u3002");let n=t.profile?.parameters??{},i=n.name;if(Object.keys(n).length!==1||typeof i!="string"||!new RegExp(wf,"u").test(i))throw new $e("APPLICATION_CONFIG_CONTRACT_INVALID","Application Manifest \u5FC5\u987B\u5305\u542B\u552F\u4E00\u4E14\u5408\u6CD5\u7684 name \u53C2\u6570\u3002");return{id:i,profile:r}}function Oa(e,t){if(!mf(e))throw new $e("APPLICATION_CONFIG_CONTRACT_INVALID","Application ConfigContract \u4E0D\u7B26\u5408 v1 Schema\u3002",mf.errors??[]);let r=e;if(r.configDirectory.relativeDirectory!==`applications/${r.application.id}`)throw new $e("APPLICATION_CONFIG_CONTRACT_INVALID","Config Dir \u76F8\u5BF9\u76EE\u5F55\u5FC5\u987B\u7531 Application identity \u552F\u4E00\u786E\u5B9A\u3002");let n=new Set,i=new Set,a=new Set;for(let l of r.bindings){if(n.has(l.name))throw new $e("APPLICATION_CONFIG_CONTRACT_INVALID",`\u73AF\u5883 Binding \u540D\u79F0\u91CD\u590D\uFF1A${l.name}`);if(n.add(l.name),l.kind==="value"){if(gf.test(l.name))throw new $e("APPLICATION_CONFIG_SECRET_LITERAL_FORBIDDEN",`\u654F\u611F\u914D\u7F6E ${l.name} \u5FC5\u987B\u4F7F\u7528\u6587\u4EF6 Binding\uFF0C\u7981\u6B62\u5728\u4ED3\u5E93\u4E2D\u58F0\u660E\u503C\u3002`);continue}if(!l.name.endsWith("_FILE"))throw new $e("APPLICATION_CONFIG_CONTRACT_INVALID",`\u6587\u4EF6 Binding ${l.name} \u5FC5\u987B\u4EE5 _FILE \u7ED3\u5C3E\u3002`);let p=l.runtimeEnvironmentVariable??l.name;if(i.has(p))throw new $e("APPLICATION_CONFIG_CONTRACT_INVALID",`\u8FD0\u884C\u65F6\u73AF\u5883\u53D8\u91CF\u540D\u79F0\u91CD\u590D\uFF1A${p}`);i.add(p);let m=l.kind==="secret-file"?"secrets/":"certs/";if(l.kind==="certificate-file"&&(gf.test(l.name)||v_.test(l.name)))throw new $e("APPLICATION_CONFIG_CONTRACT_INVALID",`${l.name} \u5305\u542B\u79C1\u5BC6\u6750\u6599\u8BED\u4E49\uFF0C\u5FC5\u987B\u4F7F\u7528 secret-file \u5E76\u653E\u5165 secrets/\uFF1Bcertificate-file \u53EA\u5141\u8BB8\u516C\u5F00\u8BC1\u4E66\u3002`);let u=l.file.split("/");if(!l.file.startsWith(m)||u.some(f=>f===""||f==="."||f===".."))throw new $e("APPLICATION_CONFIG_CONTRACT_INVALID",`${l.name} \u5FC5\u987B\u4F4D\u4E8E ${m} \u4E0B\u7684\u5177\u4F53\u6587\u4EF6\u3002`);if(a.has(l.file))throw new $e("APPLICATION_CONFIG_CONTRACT_INVALID",`\u914D\u7F6E\u6587\u4EF6 Binding \u8DEF\u5F84\u91CD\u590D\uFF1A${l.file}`);a.add(l.file)}let o=new Map(r.bindings.map(l=>[l.name,l])),s=new Set,c=new Set,d=l=>{if(c.has(l))return;if(s.has(l))throw new $e("APPLICATION_CONFIG_CONTRACT_INVALID",`\u6D3E\u751F\u914D\u7F6E\u5B58\u5728\u5FAA\u73AF\u5F15\u7528\uFF1A${l}`);s.add(l);let p=o.get(l);if(p?.kind==="secret-file"&&p.provisioning?.strategy==="derived")for(let m of p.provisioning.template.matchAll(/\$\{([A-Z][A-Z0-9_]{0,127})\}/gu)){let u=m[1],f=o.get(u);if(!f||f.kind==="certificate-file")throw new $e("APPLICATION_CONFIG_CONTRACT_INVALID",`${l}\u5F15\u7528\u672A\u77E5\u6216\u4E0D\u5141\u8BB8\u7684\u914D\u7F6E\uFF1A${u}`);d(u)}s.delete(l),c.add(l)};for(let l of o.keys())d(l);if(t!==void 0){let l=vf(t);if(r.application.id!==l.id||r.application.profile!==l.profile)throw new $e("APPLICATION_CONFIG_IDENTITY_MISMATCH","ConfigContract \u7684\u5E94\u7528\u8EAB\u4EFD\u6216 Profile \u4E0E Project Manifest \u4E0D\u4E00\u81F4\u3002")}return r}function Ca(e){let t=vf(e),r=t.profile==="workspace-web-application"?[]:[{name:"PORT",kind:"value",required:!1,default:"3000"}],n={$schema:"https://schemas.dyyto.dev/platform/application-config-contract-v1.json",schemaVersion:1,kind:"ApplicationConfigContract",application:t,configDirectory:{rootEnvironmentVariable:"IDP_CONFIG_DIR",relativeDirectory:`applications/${t.id}`,environmentFile:".env",materializationOwner:"external-deployment-control-plane"},bindings:r};return Oa(n,e),Buffer.from(`${JSON.stringify(n,null,2)}
|
|
37
|
-
`)}import{createHash as I_,X509Certificate as b_}from"node:crypto";import{lstat as Xn,readFile as et,realpath as Ta}from"node:fs/promises";import K from"node:path";var ue=class extends Error{code;constructor(t,r){super(r),this.code=t}};function
|
|
38
|
-
`)}function kf(e,t){let r=e;if(r?.$schema!=="https://schemas.dyyto.dev/platform/application-config-binding-v1.json"||r.schemaVersion!==1||r.kind!=="ApplicationConfigBinding"||r.environment?.name!=="local"||r.configDirectory?.rootEnvironmentVariable!=="APP_CONFIG_DIR"||r.configDirectory.scope!=="application-environment"||r.contract?.path!=="config/application-config.json"||r.materializationOwner!=="external-deployment-control-plane")throw new ue("APPLICATION_CONFIG_BINDING_INVALID","ApplicationConfigBinding\u4E0D\u7B26\u5408v1\u5408\u540C\u3002");if(!r.application||typeof r.application.id!="string"||typeof r.application.profile!="string")throw new ue("APPLICATION_CONFIG_BINDING_INVALID","ApplicationConfigBinding\u5E94\u7528\u8EAB\u4EFD\u65E0\u6548\u3002");if(t!==void 0){let n=bf(t);if(r.application.id!==n.id||r.application.profile!==n.profile)throw new ue("APPLICATION_CONFIG_BINDING_IDENTITY_MISMATCH","ApplicationConfigBinding\u4E0EProject Manifest\u8EAB\u4EFD\u4E0D\u4E00\u81F4\u3002")}return r}function k_(e){let t={};for(let[r,n]of e.split(/\r?\n/u).entries()){let i=n.trim();if(!i||i.startsWith("#"))continue;let a=/^([A-Z][A-Z0-9_]*)=(.*)$/u.exec(i),o=a?.[1],s=a?.[2];if(!o||s===void 0||o in t)throw new ue("APPLICATION_CONFIG_ENV_INVALID",`.env:${r+1}\u683C\u5F0F\u65E0\u6548\u6216\u53D8\u91CF\u91CD\u590D\u3002`);t[o]=s.trim().replace(/^(?:"([\s\S]*)"|'([\s\S]*)')$/u,"$1$2")}return t}function xa(e){return`sha256:${I_("sha256").update(e).digest("hex")}`}async function If(e,t,r){let n=await Xn(e).catch(()=>null);if(!n||!n.isFile()||n.isSymbolicLink()||n.nlink!==1||!r&&n.size===0||(n.mode&511&-385)!==0)throw new ue("APPLICATION_CONFIG_FILE_INVALID",`${t}\u4E0D\u5B58\u5728\u3001\u4E3A\u7A7A\u3001\u4E0D\u662F\u5B89\u5168\u666E\u901A\u6587\u4EF6\u6216\u6743\u9650\u8D85\u8FC70600\u3002`);return n}var __=new Set(["APPLICATION_CONFIG_FILE_INVALID","APPLICATION_CONFIG_REFERENCE_CHANGED"]),E_=new Set(["APP_CONFIG_DIR_REQUIRED","ENOENT"]);async function Fc({projectRoot:e,environment:t=process.env}){let r=await Ta(K.resolve(e)),n=K.join(r,"config/application-config.json");if(!await Xn(n).catch(()=>null))return{schemaVersion:1,application:null,environment:"local",configDirectory:null,contractDigest:null,state:"not-declared",needsConfigInit:!1,missingBindings:[],issueCode:"APPLICATION_CONFIG_CONTRACT_NOT_DECLARED",entries:[]};try{let[a,o]=await Promise.all([et(K.join(r,"project-capabilities.json")),et(n)]),s=JSON.parse(a.toString("utf8")),c=Oa(JSON.parse(o.toString("utf8")),s),d=await et(K.join(r,".dyyto/application-config-binding.json")).catch(p=>{if(p.code==="ENOENT")return null;throw p});if(!d)return{schemaVersion:1,application:c.application.id,environment:"local",configDirectory:null,contractDigest:xa(o),state:"invalid",needsConfigInit:!1,missingBindings:[],issueCode:"APPLICATION_CONFIG_BINDING_NOT_DECLARED",entries:[]};let l=kf(JSON.parse(d.toString("utf8")),s);try{let p=await Qn({projectRoot:r,environment:t}),m=p.entries.filter(f=>f.required&&!f.configured).map(f=>f.name),u=m.length?"incomplete":"ready";return{schemaVersion:1,...p,state:u,needsConfigInit:u==="incomplete",missingBindings:m}}catch(p){let m=p instanceof ue?p.code:p.code??"APPLICATION_CONFIG_UNKNOWN",u=E_.has(m)?"missing":__.has(m)?"incomplete":"invalid",f=await Ef(r,l.application.id,t).catch(()=>{});return{schemaVersion:1,application:l.application.id,environment:"local",configDirectory:f??null,contractDigest:xa(o),state:u,needsConfigInit:u==="missing"||u==="incomplete",missingBindings:u==="missing"?c.bindings.filter(g=>g.required).map(g=>g.name):[],issueCode:m,entries:[]}}}catch(a){let o=a instanceof ue||a instanceof Error&&"code"in a?String(a.code):"APPLICATION_CONFIG_INVALID";return{schemaVersion:1,application:null,environment:"local",configDirectory:null,contractDigest:null,state:"invalid",needsConfigInit:!1,missingBindings:[],issueCode:o,entries:[]}}}var A_=new Set(["workspace-node-application","workspace-web-application","workspace-expo-application","nextjs-full-stack-application"]);async function _f({workspaceRoot:e,environment:t=process.env}){let r=await Ta(K.resolve(e));if(J(JSON.parse(await et(K.join(r,"project-capabilities.json"),"utf8"))).profile?.id!=="workspace-root")throw new ue("APPLICATION_CONFIG_WORKSPACE_INVALID","\u914D\u7F6E\u5C31\u7EEA\u5EA6\u5DE5\u4F5C\u533A\u5FC5\u987B\u91C7\u7528workspace-root Profile\u3002");let i=await Ju(r),a=[];for(let s of i){let c=K.join(r,...s.relativeRoot.split("/")),d=K.join(c,"project-capabilities.json"),l=await et(d,"utf8").catch(()=>null),p=await Xn(K.join(c,"config/application-config.json")).then(f=>f.isFile()&&!f.isSymbolicLink()).catch(()=>!1),m="";if(l!==null)try{m=J(JSON.parse(l)).profile?.id??""}catch{p&&(m="invalid-application")}if(!A_.has(m)&&!p)continue;let u=await Fc({projectRoot:c,environment:t}).catch(f=>({schemaVersion:1,application:null,environment:"local",configDirectory:null,contractDigest:null,state:"invalid",needsConfigInit:!1,missingBindings:[],issueCode:f instanceof Error&&"code"in f?String(f.code):"APPLICATION_CONFIG_UNIT_INSPECTION_FAILED",entries:[]}));a.push({unit:s.relativeRoot,readiness:u})}let o=s=>a.filter(c=>c.readiness.state===s).length;return Object.freeze({schemaVersion:1,scope:"workspace",workspaceRoot:r,summary:Object.freeze({total:a.length,ready:o("ready"),missing:o("missing"),incomplete:o("incomplete"),invalid:o("invalid"),notDeclared:o("not-declared"),needsConfigInit:a.filter(s=>s.readiness.needsConfigInit).length}),applications:Object.freeze(a.map(s=>Object.freeze(s)))})}async function R_(e,t,r){let n=K.dirname(e);for(;n!==K.dirname(n);){try{if(JSON.parse(await et(K.join(n,"project-capabilities.json"),"utf8")).profile?.id==="workspace-root"){let a=K.relative(n,e);if(!/^(?:apps|services|packages)[/\\][a-z0-9][a-z0-9._-]*$/u.test(a))throw new ue("APPLICATION_CONFIG_WORKSPACE_UNIT_INVALID","Workspace\u5E94\u7528\u5FC5\u987B\u4F4D\u4E8Eapps/<name>\u3001services/<name>\u6216packages/<name>\u3002");return K.join(K.basename(n),a,r)}}catch(i){if(i instanceof ue)throw i}n=K.dirname(n)}return K.join(t,r)}async function Ef(e,t,r){let n=r.DYYTO_WORKBENCH_PROJECT_BINDINGS_FILE;if(n){if(!K.isAbsolute(n))throw new ue("WORKBENCH_PROJECT_BINDINGS_INVALID","\u5DE5\u4F5C\u53F0\u9879\u76EEBinding\u6587\u4EF6\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84\u3002");let a=await Xn(n).catch(()=>null);if(!a?.isFile()||a.isSymbolicLink()||a.nlink!==1||(a.mode&511&-385)!==0)throw new ue("WORKBENCH_PROJECT_BINDINGS_INVALID","\u5DE5\u4F5C\u53F0\u9879\u76EEBinding\u6587\u4EF6\u4E0D\u5B89\u5168\u3002");let o=JSON.parse(await et(n,"utf8"));if(o.schemaVersion!==1||!Array.isArray(o.projects))throw new ue("WORKBENCH_PROJECT_BINDINGS_INVALID","\u5DE5\u4F5C\u53F0\u9879\u76EEBinding\u7248\u672C\u65E0\u6548\u3002");let s=o.projects.filter(c=>typeof c.containerPath=="string"&&typeof c.configDirectory=="string"&&(e===c.containerPath||e.startsWith(`${c.containerPath}${K.sep}`))).sort((c,d)=>d.containerPath.length-c.containerPath.length);if(s[0])return s[0].configDirectory}let i=r.APP_CONFIG_DIR;if(i){if(!K.isAbsolute(i))throw new ue("APP_CONFIG_DIR_REQUIRED","APP_CONFIG_DIR\u5FC5\u987B\u662F\u7EDD\u5BF9\u4E1A\u52A1\u914D\u7F6E\u603B\u6839\u3002");return K.join(i,await R_(e,t,r.DYYTO_APPLICATION_ENVIRONMENT??"local"))}}async function Qn({projectRoot:e,environment:t=process.env}){let r=await Ta(K.resolve(e)),[n,i,a]=await Promise.all([et(K.join(r,"project-capabilities.json")),et(K.join(r,".dyyto/application-config-binding.json")),et(K.join(r,"config/application-config.json"))]),o=JSON.parse(n.toString("utf8")),s=kf(JSON.parse(i.toString("utf8")),o),c=Oa(JSON.parse(a.toString("utf8")),o),d=await Ef(r,s.application.id,t);if(!d||!K.isAbsolute(d))throw new ue("APP_CONFIG_DIR_REQUIRED","\u8BF7\u4E3A\u5F53\u524D\u9879\u76EE\u8BBE\u7F6E\u7EDD\u5BF9APP_CONFIG_DIR\u3002");let l=await Ta(d),p=await Xn(l);if(!p.isDirectory()||p.isSymbolicLink()||(p.mode&511&-449)!==0)throw new ue("APP_CONFIG_DIR_INVALID","APP_CONFIG_DIR\u5FC5\u987B\u662F\u6743\u9650\u4E0D\u8D85\u8FC70700\u7684\u666E\u901A\u76EE\u5F55\u3002");let m=K.relative(r,l);if(m===""||!m.startsWith("..")&&!K.isAbsolute(m))throw new ue("APP_CONFIG_DIR_INSIDE_PROJECT","APP_CONFIG_DIR\u4E0D\u80FD\u4F4D\u4E8E\u9879\u76EE\u4ED3\u5E93\u5185\u3002");let u=K.join(l,".env");await If(u,"\u5E94\u7528.env",c.bindings.length===0);let f=k_(await et(u,"utf8")),g=[];for(let h of c.bindings){if(h.kind==="value"){let O=f[h.name]??"";g.push({name:h.name,kind:h.kind,required:h.required,configured:O.length>0,source:"APP_CONFIG_DIR",display:O});continue}if(f[h.name]!==h.file)throw new ue("APPLICATION_CONFIG_REFERENCE_CHANGED",`${h.name}\u672A\u4FDD\u6301\u5408\u540C\u6587\u4EF6\u5F15\u7528\u3002`);let _=K.resolve(l,h.file),b=K.relative(l,_);if(!b||b.startsWith("..")||K.isAbsolute(b))throw new ue("APPLICATION_CONFIG_REFERENCE_ESCAPE",`${h.name}\u9003\u9038APP_CONFIG_DIR\u3002`);let A=await If(_,h.name,!0),y=await et(_),k=y.length>0,S;if(k&&h.kind==="certificate-file")try{let O=new b_(y);S={subject:O.subject,issuer:O.issuer,validFrom:O.validFrom,validTo:O.validTo}}catch{throw new ue("APPLICATION_CERTIFICATE_INVALID",`${h.name}\u4E0D\u662F\u6709\u6548X.509\u8BC1\u4E66\u3002`)}g.push({name:h.name,...h.runtimeEnvironmentVariable?{runtimeEnvironmentVariable:h.runtimeEnvironmentVariable}:{},kind:h.kind,required:h.required,configured:k,source:"APP_CONFIG_DIR",display:k?"\u5DF2\u914D\u7F6E":"\u672A\u914D\u7F6E",...k?{fingerprint:xa(y),updatedAt:A.mtime.toISOString()}:{},...S?{certificate:S}:{}})}return{application:s.application.id,environment:"local",configDirectory:l,contractDigest:xa(a),entries:g}}var yr="project-capabilities.json",Af=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;function D_(e,t){if(!Af.test(e)||!Af.test(t))throw new M("CONSUMER_PROFILE_UNSUPPORTED","Upgrade requires stable SemVer releases");let r=e.split(".").map(Number),n=t.split(".").map(Number);for(let i=0;i<3;i+=1)if(r[i]!==n[i])return r[i]-n[i];return 0}async function S_(e,t){let r=ei.join(e,...t.split("/"));try{let n=await P_(r);if(!n.isFile()||n.isSymbolicLink())throw new M("PROJECT_STATE_INVALID","Managed upgrade target must be a regular file",t);return{path:t,exists:!0,digest:v(await Va(r))}}catch(n){if(n.code==="ENOENT")return{path:t,exists:!1};throw n}}function Ma(e,t){let r=J(e),n=t.release,i=n.assets.find(o=>o.path==="package.json");if((n.consumerProfile==="standalone-npm-package"||n.consumerProfile==="workspace-npm-package")&&i?.renderer?.startsWith("npm-package-json-")===!0)return $c(Ft(r,n.consumerProfile));if(n.consumerProfile==="react-component-library"&&i?.renderer==="react-component-package-json-v1")return Oc(Ft(r,n.consumerProfile));let a=t.contents.get("package.json");if(a===void 0)throw new M("RELEASE_NOT_FOUND","Transition target package.json is unavailable");return a}async function zc(e){let t=J(e.manifest),r=Te(e.currentLock),n=e.sourceRelease.release,i=e.targetRelease.release,a=t.capabilities.find(P=>P.capabilityId===n.capabilityId),o=r.capabilities.find(P=>P.capabilityId===n.capabilityId),s=i.capabilityId!==n.capabilityId&&i.dependencies?.capabilities?.includes(n.capabilityId)===!0;if(a===void 0||o===void 0||a.capabilityId!==o.capabilityId||a.version!==o.version||n.capabilityId!==o.capabilityId||n.version!==o.version||n.integrity!==o.integrity||!s&&i.capabilityId!==o.capabilityId||i.consumerProfile!==o.consumerProfile||n.consumerProfile!==i.consumerProfile)throw new M("CONSUMER_PROFILE_UNSUPPORTED","Upgrade source, target, Manifest, and Lock must describe one compatible capability");if(!s&&D_(i.version,n.version)<=0)throw new M("CONSUMER_PROFILE_UNSUPPORTED","Upgrade target must be newer than the locked release");let c=await N_(ei.resolve(e.projectRoot)),d={...t,...e.targetTemplate===void 0?{}:{template:e.targetTemplate},capabilities:t.capabilities.map(P=>P.capabilityId===n.capabilityId?{capabilityId:i.capabilityId,version:i.version}:P)},l=new Map(e.targetRelease.contents);i.assets.some(P=>P.path==="package.json")&&l.set("package.json",Ma(d,e.targetRelease));for(let P of i.assets)P.renderer==="application-config-contract-v1"&&l.set(P.path,Ca(d)),P.renderer==="application-config-binding-v1"&&l.set(P.path,La(d));let p,m=c,u="package.json",f;if(i.schemaVersion===2&&i.availability.maturity!=="withdrawn"&&(i.packageSources?.length??0)>0){if(e.packageSource===void 0)throw new M("CONSUMER_PROFILE_UNSUPPORTED","Profile transition requires verified Package Source facts");let P=l.get("package.json");if(P===void 0)throw new M("RELEASE_NOT_FOUND","Transition target package.json is unavailable");let Y=await Va(ei.join(c,"package.json")),ne=e.packageSource.topology??{schemaVersion:1,mode:"standalone",transactionRoot:c,unitRoot:c,unitRelativeRoot:".",unitImporterId:".",lockfilePath:"pnpm-lock.yaml"};m=ne.transactionRoot,u=ne.mode==="pnpm-shared-lockfile"?`${ne.unitRelativeRoot}/package.json`:"package.json",f=ne.lockfilePath;let Be={release:i,registryConfigs:e.packageSource.registryConfigs,endpointBindings:e.packageSource.endpointBindings,receipts:e.packageSource.receipts,inspections:e.packageSource.inspections,consumerProfile:i.consumerProfile,packageJson:Y,desiredBasePackageJson:P,...e.packageSource.currentLockfile===void 0?{}:{currentLockfile:e.packageSource.currentLockfile},generatedAt:e.generatedAt,expiresAt:e.expiresAt};try{let tt=ne.mode==="pnpm-shared-lockfile"?(e.packageChannel==="development"?$a:ja)({...Be,topology:{mode:ne.mode,unitRelativeRoot:ne.unitRelativeRoot,unitImporterId:ne.unitImporterId,lockfilePath:ne.lockfilePath,workspaceManifestPath:ne.workspaceManifestPath,workspaceManifestDigest:ne.workspaceManifestDigest},preservedImporterDigests:e.packageSource.preservedImporterDigests??[],resolutionEvidence:e.packageSource.resolutionEvidence,resolutionWorkerReleaseId:e.packageSource.resolutionWorkerReleaseId}):(e.packageChannel==="development"?Sa:Da)({...Be,lockResolution:e.packageSource.lockResolution});p=Ra(tt),l.set("package.json",tt.desiredPackageJson),l.set(f,tt.desiredLockfile)}catch(tt){throw tt instanceof H?new M("CONSUMER_PROFILE_UNSUPPORTED",tt.code):tt}}let g=new Map(o.assets.filter(P=>P.path!==yr).map(P=>[P.path,P.digest])),h=new Map(i.assets.filter(P=>P.path!==yr).map(P=>{let Y=l.get(P.path);if(Y===void 0)throw new M("RELEASE_NOT_FOUND","Upgrade target asset content is unavailable",P.path);return[P.path,v(Y)]})),w=[...new Set([...g.keys(),...h.keys()])].sort(),_=[],b=[];for(let P of w){let Y=await S_(c,P);_.push(Y);let ne=g.get(P),Be=h.get(P),tt=i.assets.find(rg=>rg.path===P);if(tt?.ownership==="seed-file"&&Y.exists&&Y.digest!==void 0){h.set(P,Y.digest),l.set(P,await Va(ei.join(c,...P.split("/")))),b.push({path:P,kind:"replace",ownership:"seed-file",baseDigest:Y.digest,desiredDigest:Y.digest});continue}if(ne===void 0){if(Be===void 0)throw new M("RELEASE_NOT_FOUND","Target asset digest is unavailable",P);b.push({path:P,kind:"create",ownership:tt?.ownership??"owned-file",desiredDigest:Be})}else Be===void 0?b.push({path:P,kind:"remove",ownership:"owned-file",baseDigest:ne}):b.push({path:P,kind:"replace",ownership:tt?.ownership??"owned-file",baseDigest:ne,desiredDigest:Be})}if(p!==void 0&&f!==void 0){let P=e.packageSource?.currentLockfile;if(P===void 0)throw new M("CONSUMER_PROFILE_UNSUPPORTED","Transition lockfile preimage is unavailable");let Y=l.get(f);_.push({path:f,exists:!0,digest:v(P)}),b.push({path:f,kind:"replace",ownership:"owned-file",baseDigest:v(P),desiredDigest:v(Y)})}let A=await Va(ei.join(c,yr)),y=Buffer.from(`${JSON.stringify(d,null,2)}
|
|
39
|
-
`);_.push({path:yr,exists:!0,digest:v(A)}),b.push({path:yr,kind:"replace",ownership:"owned-file",baseDigest:v(A),desiredDigest:v(y)});let k={schemaVersion:1,capabilityId:i.capabilityId,version:i.version,integrity:i.integrity,assets:i.assets.filter(P=>P.path!==yr).map(P=>({path:P.path,ownership:P.ownership,desiredDigest:h.get(P.path)})),verifiers:i.verifiers.map(({id:P})=>({id:P,kind:"command"}))},S=m===c?b:b.map(P=>P.path===f?P:{...P,path:`${e.packageSource.topology.unitRelativeRoot}/${P.path}`}),O=m===c?_:_.map(P=>P.path===f?P:{...P,path:`${e.packageSource.topology.unitRelativeRoot}/${P.path}`}),se=De({action:"upgrade",capability:k,changes:S,observedAssets:O,generatedAt:e.generatedAt,expiresAt:e.expiresAt,...p===void 0?{}:{packageAdoption:p}});l.set(yr,y);let $=new Map;for(let P of se.operations){if(P.disposition!=="ready"||P.kind==="remove")continue;let
|
|
40
|
-
`,"utf8"),await i.sync()}finally{await i.close()}try{await j_(n,e),await T_(n),await x_(r)}catch(a){throw await C_(n,{force:!0}),a}}async function jf(e){let t=await dt(de.resolve(e.projectRoot)),r=Bc(e.plan),n=de.join(t,".dyyto","delivery","plans",`${r.planId}.json`);try{await ti(n,r)}catch(i){if(i.code!=="EEXIST")throw i;if(E(Bc(JSON.parse(await lt(n,"utf8"))))!==E(r))throw new j("DELIVERY_PRECONDITION_FAILED","Stored Delivery Plan content does not match its identity")}return r}async function zt(e){if(!Ee(e.planId))throw new j("DELIVERY_PLAN_NOT_FOUND","Delivery Plan identity is invalid");let t=await dt(de.resolve(e.projectRoot));try{let r=Bc(JSON.parse(await lt(de.join(t,".dyyto","delivery","plans",`${e.planId}.json`),"utf8")));if(r.planId!==e.planId)throw new j("DELIVERY_PRECONDITION_FAILED","Stored Delivery Plan identity does not match its path");return r}catch(r){throw r.code==="ENOENT"?new j("DELIVERY_PLAN_NOT_FOUND","Delivery Plan was not found"):r}}async function Yc(e){let t=await dt(de.resolve(e.projectRoot)),r=Wc(e.receipt),n=await zt({projectRoot:t,planId:r.planId});if(r.kind!==n.kind||r.adapterId!==n.target.adapterId||r.artifactDigest!==n.artifact.digest||r.target!==n.target.location)throw new j("DELIVERY_RECEIPT_INVALID","Delivery Receipt does not match its immutable Plan");if(r.schemaVersion===2){let a=await Hr({projectRoot:t,planId:r.planId});if(n.schemaVersion!==2||n.publication===void 0||a===null||r.npm.stageId!==a.stageId||r.npm.tarballDigest!==a.artifactDigest||r.npm.tag!==n.publication.tag||r.npm.access!==n.publication.access)throw new j("DELIVERY_RECEIPT_INVALID","Verified npm Receipt does not match its Plan and Stage Record")}let i=de.join(t,".dyyto","delivery","receipts",`${r.planId}.json`);try{await ti(i,r)}catch(a){if(a.code!=="EEXIST")throw a;let o=Wc(JSON.parse(await lt(i,"utf8")));if(E(o)!==E(r))throw new j("DELIVERY_RECEIPT_INVALID","A different Receipt already exists for this Plan");return o}return r}async function ri(e){if(!Ee(e.planId))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Receipt Plan identity is invalid");let t=await dt(de.resolve(e.projectRoot));try{let r=Wc(JSON.parse(await lt(de.join(t,".dyyto","delivery","receipts",`${e.planId}.json`),"utf8")));if(r.planId!==e.planId)throw new j("DELIVERY_RECEIPT_INVALID","Stored Delivery Receipt identity does not match its path");return r}catch(r){if(r.code==="ENOENT")return null;throw r}}async function $f(e){let t=await dt(de.resolve(e.projectRoot)),r=qa(e.record),n=await zt({projectRoot:t,planId:r.planId});if(n.schemaVersion!==2||n.kind!=="npm-publish"||r.artifactDigest!==n.artifact.digest)throw new j("DELIVERY_RECEIPT_INVALID","Delivery Attempt Record does not match an npm Plan v2");let i=de.join(t,".dyyto","delivery","attempts",`${r.planId}.json`);try{await ti(i,r)}catch(a){if(a.code!=="EEXIST")throw a;let o=qa(JSON.parse(await lt(i,"utf8")));if(E(o)!==E(r))throw new j("DELIVERY_RECEIPT_INVALID","A different Attempt Record already exists for this Plan");return o}return r}async function Of(e){if(!Ee(e.planId))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Attempt Plan identity is invalid");let t=await dt(de.resolve(e.projectRoot));try{let r=qa(JSON.parse(await lt(de.join(t,".dyyto","delivery","attempts",`${e.planId}.json`),"utf8")));if(r.planId!==e.planId)throw new j("DELIVERY_RECEIPT_INVALID","Stored Delivery Attempt identity does not match its path");return r}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Cf(e){let t=await dt(de.resolve(e.projectRoot)),r=de.join(t,".dyyto","delivery","attempts"),n;try{n=await O_(r)}catch(i){if(i.code==="ENOENT")return null;throw i}for(let i of n.sort()){if(!i.endsWith(".json"))continue;let a=qa(JSON.parse(await lt(de.join(r,i),"utf8")));if((await zt({projectRoot:t,planId:a.planId})).artifact.identity!==e.artifactIdentity)continue;let[s,c]=await Promise.all([Hr({projectRoot:t,planId:a.planId}),ri({projectRoot:t,planId:a.planId})]);if(s===null&&c===null)return a}return null}async function Tf(e){let t=await dt(de.resolve(e.projectRoot)),r=Jc(e.record),n=await zt({projectRoot:t,planId:r.planId});if(n.schemaVersion!==2||n.kind!=="npm-publish"||n.publication===void 0||r.artifactDigest!==n.artifact.digest)throw new j("DELIVERY_RECEIPT_INVALID","Delivery Stage Record does not match an npm Plan v2");let i=de.join(t,".dyyto","delivery","stages",`${r.planId}.json`);try{await ti(i,r)}catch(a){if(a.code!=="EEXIST")throw a;let o=Jc(JSON.parse(await lt(i,"utf8")));if(E(o)!==E(r))throw new j("DELIVERY_RECEIPT_INVALID","A different Stage Record already exists for this Plan");return o}return r}async function Hr(e){if(!Ee(e.planId))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Stage Plan identity is invalid");let t=await dt(de.resolve(e.projectRoot));try{let r=Jc(JSON.parse(await lt(de.join(t,".dyyto","delivery","stages",`${e.planId}.json`),"utf8")));if(r.planId!==e.planId)throw new j("DELIVERY_RECEIPT_INVALID","Stored Delivery Stage identity does not match its path");return r}catch(r){if(r.code==="ENOENT")return null;throw r}}async function xf(e){let t=await dt(de.resolve(e.projectRoot)),r=Gc(e.record),n=await Hr({projectRoot:t,planId:r.planId});if(n===null||r.stageId!==n.stageId||r.artifactDigest!==n.artifactDigest)throw new j("DELIVERY_RECEIPT_INVALID","Delivery Stage Review Record does not match its immutable Stage Record");let i=de.join(t,".dyyto","delivery","stage-reviews",`${r.planId}.json`);try{await ti(i,r)}catch(a){if(a.code!=="EEXIST")throw a;let o=Gc(JSON.parse(await lt(i,"utf8")));if(E(o)!==E(r))throw new j("DELIVERY_RECEIPT_INVALID","A different Stage Review Record already exists for this Plan");return o}return r}async function Lf(e){if(!Ee(e.planId))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Stage Review Plan identity is invalid");let t=await dt(de.resolve(e.projectRoot));try{let r=Gc(JSON.parse(await lt(de.join(t,".dyyto","delivery","stage-reviews",`${e.planId}.json`),"utf8")));if(r.planId!==e.planId)throw new j("DELIVERY_RECEIPT_INVALID","Stored Delivery Stage Review identity does not match its path");return r}catch(r){if(r.code==="ENOENT")return null;throw r}}import{readFile as tm,readdir as bE}from"node:fs/promises";import Xc from"node:path";import{mkdir as Hc,open as Ja,readFile as ii,readdir as Xf,rename as Ga,rm as Qf}from"node:fs/promises";import ve from"node:path";var L_=44;var Vf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",V_=new Uint8Array(64),qf=new Uint8Array(128);for(let e=0;e<Vf.length;e++){let t=Vf.charCodeAt(e);V_[e]=t,qf[t]=e}function ni(e,t){let r=0,n=0,i=0;do{let o=e.next();i=qf[o],r|=(i&31)<<n,n+=5}while(i&32);let a=r&1;return r>>>=1,a&&(r=-2147483648|-r),t+r}function Mf(e,t){return e.pos>=t?!1:e.peek()!==L_}var DN=1024*16;var M_=class{constructor(e){this.pos=0,this.buffer=e}next(){return this.buffer.charCodeAt(this.pos++)}peek(){return this.buffer.charCodeAt(this.pos)}indexOf(e){let{buffer:t,pos:r}=this,n=t.indexOf(e,r);return n===-1?t.length:n}};function Uf(e){let{length:t}=e,r=new M_(e),n=[],i=0,a=0,o=0,s=0,c=0;do{let d=r.indexOf(";"),l=[],p=!0,m=0;for(i=0;r.pos<d;){let u;i=ni(r,i),i<m&&(p=!1),m=i,Mf(r,d)?(a=ni(r,a),o=ni(r,o),s=ni(r,s),Mf(r,d)?(c=ni(r,c),u=[i,a,o,s,c]):u=[i,a,o,s]):u=[i],l.push(u),r.pos++}p||q_(l),n.push(l),r.pos=d+1}while(r.pos<=t);return n}function q_(e){e.sort(U_)}function U_(e,t){return e[0]-t[0]}var F_=/^[\w+.-]+:\/\//,z_=/^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/,B_=/^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;function J_(e){return F_.test(e)}function G_(e){return e.startsWith("//")}function Bf(e){return e.startsWith("/")}function W_(e){return e.startsWith("file:")}function Ff(e){return/^[.?#]/.test(e)}function Fa(e){let t=z_.exec(e);return Jf(t[1],t[2]||"",t[3],t[4]||"",t[5]||"/",t[6]||"",t[7]||"")}function K_(e){let t=B_.exec(e),r=t[2];return Jf("file:","",t[1]||"","",Bf(r)?r:"/"+r,t[3]||"",t[4]||"")}function Jf(e,t,r,n,i,a,o){return{scheme:e,user:t,host:r,port:n,path:i,query:a,hash:o,type:7}}function zf(e){if(G_(e)){let r=Fa("http:"+e);return r.scheme="",r.type=6,r}if(Bf(e)){let r=Fa("http://foo.com"+e);return r.scheme="",r.host="",r.type=5,r}if(W_(e))return K_(e);if(J_(e))return Fa(e);let t=Fa("http://foo.com/"+e);return t.scheme="",t.host="",t.type=e?e.startsWith("?")?3:e.startsWith("#")?2:4:1,t}function Y_(e){if(e.endsWith("/.."))return e;let t=e.lastIndexOf("/");return e.slice(0,t+1)}function H_(e,t){Gf(t,t.type),e.path==="/"?e.path=t.path:e.path=Y_(t.path)+e.path}function Gf(e,t){let r=t<=4,n=e.path.split("/"),i=1,a=0,o=!1;for(let c=1;c<n.length;c++){let d=n[c];if(!d){o=!0;continue}if(o=!1,d!=="."){if(d===".."){a?(o=!0,a--,i--):r&&(n[i++]=d);continue}n[i++]=d,a++}}let s="";for(let c=1;c<i;c++)s+="/"+n[c];(!s||o&&!s.endsWith("/.."))&&(s+="/"),e.path=s}function Wf(e,t){if(!e&&!t)return"";let r=zf(e),n=r.type;if(t&&n!==7){let a=zf(t),o=a.type;switch(n){case 1:r.hash=a.hash;case 2:r.query=a.query;case 3:case 4:H_(r,a);case 5:r.user=a.user,r.host=a.host,r.port=a.port;case 6:r.scheme=a.scheme}o>n&&(n=o)}Gf(r,n);let i=r.query+r.hash;switch(n){case 2:case 3:return i;case 4:{let a=r.path.slice(1);return a?Ff(t||e)&&!Ff(a)?"./"+a+i:a+i:i||"."}case 5:return r.path+i;default:return r.scheme+"//"+r.user+r.host+r.port+r.path+i}}function Z_(e){if(!e)return"";let t=e.lastIndexOf("/");return e.slice(0,t+1)}function X_(e,t){let r=Z_(e),n=t?t+"/":"";return i=>Wf(n+(i||""),r)}var Bt=0,Q_=1,eE=2,tE=3,rE=4;function nE(e,t){let r=Kf(e,0);if(r===e.length)return e;t||(e=e.slice());for(let n=r;n<e.length;n=Kf(e,n+1))e[n]=aE(e[n],t);return e}function Kf(e,t){for(let r=t;r<e.length;r++)if(!iE(e[r]))return r;return e.length}function iE(e){for(let t=1;t<e.length;t++)if(e[t][Bt]<e[t-1][Bt])return!1;return!0}function aE(e,t){return t||(e=e.slice()),e.sort(oE)}function oE(e,t){return e[Bt]-t[Bt]}var Ba=!1;function sE(e,t,r,n){for(;r<=n;){let i=r+(n-r>>1),a=e[i][Bt]-t;if(a===0)return Ba=!0,i;a<0?r=i+1:n=i-1}return Ba=!1,r-1}function cE(e,t,r){for(let n=r+1;n<e.length&&e[n][Bt]===t;r=n++);return r}function lE(e,t,r){for(let n=r-1;n>=0&&e[n][Bt]===t;r=n--);return r}function dE(){return{lastKey:-1,lastNeedle:-1,lastIndex:-1}}function pE(e,t,r,n){let{lastKey:i,lastNeedle:a,lastIndex:o}=r,s=0,c=e.length-1;if(n===i){if(t===a)return Ba=o!==-1&&e[o][Bt]===t,o;t>=a?s=o===-1?0:o:c=o}return r.lastKey=n,r.lastNeedle=t,r.lastIndex=sE(e,t,s,c)}function uE(e){return typeof e=="string"?JSON.parse(e):e}var fE="`line` must be greater than 0 (lines start at line 1)",mE="`column` must be greater than or equal to 0 (columns start at column 0)",Yf=-1,gE=1,Hf=class{constructor(e,t){let r=typeof e=="string";if(!r&&e._decodedMemo)return e;let n=uE(e),{version:i,file:a,names:o,sourceRoot:s,sources:c,sourcesContent:d}=n;this.version=i,this.file=a,this.names=o||[],this.sourceRoot=s,this.sources=c,this.sourcesContent=d,this.ignoreList=n.ignoreList||n.x_google_ignoreList||void 0;let l=X_(t,s);this.resolvedSources=c.map(l);let{mappings:p}=n;if(typeof p=="string")this._encoded=p,this._decoded=void 0;else if(Array.isArray(p))this._encoded=void 0,this._decoded=nE(p,r);else throw n.sections?new Error("TraceMap passed sectioned source map, please use FlattenMap export instead"):new Error(`invalid source map: ${JSON.stringify(n)}`);this._decodedMemo=dE(),this._bySources=void 0,this._bySourceMemos=void 0}};function hE(e){var t;return(t=e)._decoded||(t._decoded=Uf(e._encoded))}function Zf(e,t){let{line:r,column:n,bias:i}=t;if(r--,r<0)throw new Error(fE);if(n<0)throw new Error(mE);let a=hE(e);if(r>=a.length)return za(null,null,null,null);let o=a[r],s=yE(o,e._decodedMemo,r,n,i||gE);if(s===-1)return za(null,null,null,null);let c=o[s];if(c.length===1)return za(null,null,null,null);let{names:d,resolvedSources:l}=e;return za(l[c[Q_]],c[eE]+1,c[tE],c.length===5?d[c[rE]]:null)}function za(e,t,r,n){return{source:e,line:t,column:r,name:n}}function yE(e,t,r,n,i){let a=pE(e,n,t,r);return Ba?a=(i===Yf?cE:lE)(e,n,a):i===Yf&&a++,a===-1||a===e.length?-1:a}var me=class extends Error{code;constructor(t,r){super(r),this.code=t,this.name="RuntimeObservabilityError"}},Zc=/^sha256:[a-f0-9]{64}$/,em=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,wE=/^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$/,Wa=(e,t)=>Object.keys(e).every(r=>t.includes(r)),ai=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Zr=(e,t)=>e.replace(/[\u0000-\u001f\u007f]/g," ").replace(/([a-z]+:\/\/)[^/@\s]+@/gi,"$1").slice(0,t);function vE(e){if(!ai(e)||!Wa(e,["schemaVersion","eventId","occurredAt","applicationId","releaseId","deploymentId","kind","error","page","traceparent"]))throw new me("RUNTIME_ERROR_INVALID","Runtime Error Envelope contains unknown fields");if(!ai(e.error)||!ai(e.page)||!Wa(e.error,["type","message","frames"])||!Wa(e.page,["origin","path"]))throw new me("RUNTIME_ERROR_INVALID","Runtime Error Envelope structure is invalid");if(e.schemaVersion!==1||typeof e.eventId!="string"||!em.test(e.eventId)||typeof e.occurredAt!="string"||Number.isNaN(Date.parse(e.occurredAt))||typeof e.applicationId!="string"||e.applicationId.length<1||e.applicationId.length>128)throw new me("RUNTIME_ERROR_INVALID","Runtime Error Envelope identity is invalid");if(!["uncaught-error","unhandled-rejection","reported-error"].includes(e.kind))throw new me("RUNTIME_ERROR_INVALID","Runtime Error kind is invalid");for(let n of[e.releaseId,e.deploymentId])if(n!==void 0&&(typeof n!="string"||!Zc.test(n)))throw new me("RUNTIME_ERROR_IDENTITY_UNKNOWN","Runtime Error correlation identity is invalid");if(e.traceparent!==void 0&&(typeof e.traceparent!="string"||!wE.test(e.traceparent)))throw new me("RUNTIME_ERROR_INVALID","traceparent is invalid");if(typeof e.error.type!="string"||typeof e.error.message!="string"||!Array.isArray(e.error.frames)||e.error.frames.length>50||typeof e.page.origin!="string"||typeof e.page.path!="string")throw new me("RUNTIME_ERROR_INVALID","Runtime Error content is invalid");if(e.error.message.length>4096||e.error.type.length>256||e.page.path.length>2048)throw new me("RUNTIME_ERROR_TOO_LARGE","Runtime Error content exceeds a hard limit");let t=e.error.frames.map(n=>{if(!ai(n)||!Wa(n,["file","line","column","function"])||typeof n.file!="string"||n.file.length>2048)throw new me("RUNTIME_ERROR_INVALID","Runtime Error stack frame is invalid");for(let i of[n.line,n.column])if(i!==void 0&&(!Number.isSafeInteger(i)||Number(i)<1))throw new me("RUNTIME_ERROR_INVALID","Runtime Error stack location is invalid");if(n.function!==void 0&&(typeof n.function!="string"||n.function.length>256))throw new me("RUNTIME_ERROR_INVALID","Runtime Error stack function is invalid");return n}),r;try{r=new URL(e.page.origin)}catch{throw new me("RUNTIME_ERROR_INVALID","Runtime Error page origin is invalid")}if(r.origin!==e.page.origin||!e.page.path.startsWith("/")||e.page.path.includes("?")||e.page.path.includes("#"))throw new me("RUNTIME_ERROR_INVALID","Runtime Error page must contain only origin and path");return{...e,error:{...e.error,frames:t}}}function IE(e,t,r="unknown"){let n=e.error.frames.map(o=>({file:Zr(o.file,2048),...o.line===void 0?{}:{line:o.line},...o.column===void 0?{}:{column:o.column},...o.function===void 0?{}:{function:Zr(o.function,256)}})),i={type:Zr(e.error.type,256),message:Zr(e.error.message,4096),frames:n},a=v(E({type:i.type,message:i.message,frames:n.slice(0,5).map(({file:o,line:s,column:c})=>({file:o,line:s,column:c}))}));return{schemaVersion:1,eventId:e.eventId,occurredAt:e.occurredAt,receivedAt:t,applicationId:Zr(e.applicationId,128),...e.releaseId===void 0?{}:{releaseId:e.releaseId},...e.deploymentId===void 0?{}:{deploymentId:e.deploymentId},kind:e.kind,error:i,page:{origin:e.page.origin,path:Zr(e.page.path,2048)},...e.traceparent===void 0?{}:{traceparent:e.traceparent},fingerprint:a,state:e.releaseId===void 0?"persisted":"map-missing",correlation:r}}var wr=class{workspaceRoot;adapterId="observability.local";#e=Promise.resolve();constructor(t){this.workspaceRoot=t}directory(){return ve.join(ve.resolve(this.workspaceRoot),".dyyto","observability","events")}releases(){return ve.join(ve.resolve(this.workspaceRoot),".dyyto","observability","releases")}async accept(t,r){let n=vE(t);if(!r.allowedOrigins.includes(n.page.origin))throw new me("RUNTIME_ERROR_INVALID","Runtime Error origin is not registered");let i=r.resolveCorrelation===void 0?"unknown":await r.resolveCorrelation(n),a=IE(n,r.receivedAt,i);return this.#t(async()=>{let o=this.directory();await Hc(o,{recursive:!0,mode:448});let s=ve.join(o,`${a.eventId}.json`);try{let m=JSON.parse(await ii(s,"utf8")),u={...m,correlation:m.correlation??"unknown"};if(E({...u,receivedAt:a.receivedAt})!==E(a))throw new me("RUNTIME_ERROR_INVALID","eventId is already used for different content");return{eventId:a.eventId,state:u.state,duplicate:!0}}catch(m){if(m.code!=="ENOENT")throw m}let c=`${s}.tmp-${process.pid}-${crypto.randomUUID()}`,d=await Ja(c,"wx",384);try{await d.writeFile(`${E(a)}
|
|
41
|
-
`,"utf8"),await d.sync()}finally{await d.close()}await
|
|
42
|
-
`),await c.sync()}finally{await c.close()}return await
|
|
43
|
-
`),await d.sync()}finally{await d.close()}await
|
|
44
|
-
`),s=await ci(t,"project-capabilities.json");if(!s.exists||s.digest===void 0)throw new ae("CAPABILITY_DEPENDENCY_UNSATISFIED","Project manifest is unavailable");let c=[{path:"project-capabilities.json",kind:"replace",ownership:"owned-file",baseDigest:s.digest,desiredDigest:v(o)},...i.assets.map(m=>({path:m.path,kind:"remove",ownership:m.ownership??"owned-file",baseDigest:m.digest}))],d=await Promise.all(c.map(m=>ci(t,m.path))),l={schemaVersion:1,capabilityId:n.capabilityId,version:n.version,integrity:n.integrity,assets:i.assets.map(m=>({path:m.path,ownership:m.ownership??"owned-file",desiredDigest:m.digest})),verifiers:n.verifiers.map(m=>({id:m.id,kind:"file-digest"}))};return{plan:De({action:"remove",capability:l,changes:c,observedAssets:d,generatedAt:e.generatedAt,expiresAt:e.expiresAt}),manifest:a,desiredContents:new Map([["project-capabilities.json",o]]),transactionRoot:t,removedSources:[]}}async function ci(e,t){try{let r=await si(vr.join(e,...t.split("/")));return{path:t,exists:!0,digest:v(r)}}catch(r){if(r.code==="ENOENT")return{path:t,exists:!1};throw r}}async function
|
|
45
|
-
`),g=await ci(a,u);if(!g.exists||g.digest===void 0)throw new ae("CAPABILITY_DEPENDENCY_UNSATISFIED","The project manifest is unavailable");let h=[{path:u,kind:"replace",ownership:"owned-file",baseDigest:g.digest,desiredDigest:v(f)}],w=new Map([[u,f]]),_;if(n.schemaVersion===2&&n.packageSources.length>0){if(e.packageSource===void 0)throw new ae("CAPABILITY_RELEASE_VERSION_UNSUPPORTED","Capability Release v2 requires verified package source facts");let k;try{k=await si(vr.join(t,"package.json"))}catch{throw new ae("CAPABILITY_PACKAGE_SOURCE_INVALID","\u9879\u76EE package.json \u4E0D\u53EF\u7528\uFF0C\u65E0\u6CD5\u751F\u6210\u5305\u91C7\u7528\u8BA1\u5212")}try{let S=e.packageSource.currentLockfile??await si(vr.join(t,"pnpm-lock.yaml")).catch(ne=>ne.code==="ENOENT"?void 0:Promise.reject(ne)),O=e.packageSource.topology??{schemaVersion:1,mode:"standalone",transactionRoot:t,unitRoot:t,unitRelativeRoot:".",unitImporterId:".",lockfilePath:"pnpm-lock.yaml"},se=O.mode==="pnpm-shared-lockfile",$={mode:O.mode,unitRelativeRoot:O.unitRelativeRoot,unitImporterId:O.unitImporterId,lockfilePath:O.lockfilePath,...O.workspaceManifestPath?{workspaceManifestPath:O.workspaceManifestPath,workspaceManifestDigest:O.workspaceManifestDigest}:{}},P={registryConfigs:e.packageSource.registryConfigs,endpointBindings:e.packageSource.endpointBindings,receipts:e.packageSource.receipts,inspections:e.packageSource.inspections};if(se&&(!e.packageSource.resolutionEvidence||!e.packageSource.resolutionWorkerReleaseId))throw new H("PACKAGE_SOURCE_POLICY_VIOLATION");let Y=se?(e.packageChannel==="development"?$a:ja)({release:n,...P,consumerProfile:c,packageJson:k,currentLockfile:S,generatedAt:e.generatedAt,expiresAt:e.expiresAt,topology:$,preservedImporterDigests:e.packageSource.preservedImporterDigests??[],resolutionEvidence:e.packageSource.resolutionEvidence,resolutionWorkerReleaseId:e.packageSource.resolutionWorkerReleaseId}):(e.packageChannel==="development"?Sa:Da)({release:n,...P,lockResolution:e.packageSource.lockResolution,consumerProfile:c,packageJson:k,...S===void 0?{}:{currentLockfile:S},generatedAt:e.generatedAt,expiresAt:e.expiresAt});_=Ra(Y),h.push({path:o("package.json"),kind:"replace",ownership:"owned-file",baseDigest:Y.packageJsonPreimageDigest,desiredDigest:Y.desiredPackageJsonDigest}),w.set(o("package.json"),Y.desiredPackageJson),h.push({path:O.lockfilePath,kind:S===void 0?"create":"replace",ownership:"owned-file",...S===void 0?{}:{baseDigest:v(S)},desiredDigest:Y.desiredLockfileDigest}),w.set(O.lockfilePath,Y.desiredLockfile)}catch(S){throw S instanceof H?new ae("CAPABILITY_PACKAGE_SOURCE_INVALID",S.code):S}}for(let k of n.assets){let S=e.release.contents.get(k.path);if(S===void 0)throw new ae("CAPABILITY_KIND_UNSUPPORTED","Capability asset content is unavailable");let O=k.renderer==="application-config-contract-v1"?Ca(r):k.renderer==="application-config-binding-v1"?La(r):S;if(k.ownership==="managed-region"){if(k.regionId===void 0)throw new ae("CAPABILITY_KIND_UNSUPPORTED","Managed region identity is unavailable");let se;try{se=await si(vr.join(t,...k.path.split("/")))}catch{throw new ae("CAPABILITY_DEPENDENCY_UNSATISFIED","The managed shared file is unavailable")}let $=Buffer.from(vu({source:se.toString("utf8"),regionId:k.regionId,content:Buffer.from(O).toString("utf8")}));h.push({path:o(k.path),kind:"merge",ownership:"managed-region",regionId:k.regionId,baseDigest:v(se),desiredDigest:v($)}),w.set(o(k.path),$)}else{let se=await ci(t,k.path);if(k.ownership==="seed-file"&&se.exists){let $=await si(vr.join(t,...k.path.split("/")));h.push({path:o(k.path),kind:"create",ownership:"seed-file",desiredDigest:v($)}),w.set(o(k.path),$)}else h.push({path:o(k.path),kind:"create",ownership:k.ownership,desiredDigest:v(O)}),w.set(o(k.path),O)}}let b=await Promise.all(h.map(k=>ci(a,k.path))),A={schemaVersion:1,capabilityId:n.capabilityId,version:n.version,integrity:n.integrity,assets:h.filter(k=>k.path!==u&&k.path!==i?.lockfilePath).map(k=>({path:i?.mode==="pnpm-shared-lockfile"?k.path.slice(i.unitRelativeRoot.length+1):k.path,ownership:k.ownership,desiredDigest:k.desiredDigest})),verifiers:n.verifiers.map(k=>({id:k.id,kind:"file-digest"}))};return{plan:De({action:"adopt",capability:A,changes:h,observedAssets:b,generatedAt:e.generatedAt,expiresAt:e.expiresAt,..._===void 0?{}:{packageAdoption:_}}),manifest:m,desiredContents:w,transactionRoot:a,dependency:{profile:c,satisfied:!0}}}var om=br(nr(),1);var kE={$id:"https://schemas.dyyto.dev/platform/solution-catalog-entry-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","solutionId","version","integrity","title","summary","maturity","members","integration","exit"],properties:{schemaVersion:{const:1},solutionId:{type:"string",pattern:X},version:{type:"string",minLength:1,maxLength:128},integrity:{type:"string",pattern:ut},title:{type:"string",minLength:1,maxLength:80},summary:{type:"string",minLength:1,maxLength:240},maturity:{enum:["guided","automated"]},members:{type:"array",minItems:1,maxItems:32,items:{type:"object",additionalProperties:!1,required:["capabilityId","version","role","required"],properties:{capabilityId:{type:"string",pattern:X},version:{type:"string",minLength:1,maxLength:128},role:{type:"string",minLength:1,maxLength:80},required:{type:"boolean"}}}},integration:{type:"object",additionalProperties:!1,required:["prerequisites","steps","verification","result"],properties:{prerequisites:{type:"array",minItems:1,maxItems:16,items:{type:"string",minLength:1,maxLength:200}},steps:{type:"array",minItems:1,maxItems:32,items:{type:"object",additionalProperties:!1,required:["label","command"],properties:{label:{type:"string",minLength:1,maxLength:80},command:{type:"string",minLength:1,maxLength:2e3}}}},verification:{type:"array",minItems:1,maxItems:32,items:{type:"string",minLength:1,maxLength:1e3}},result:{type:"string",minLength:1,maxLength:400}}},exit:{type:"object",additionalProperties:!1,required:["summary"],properties:{summary:{type:"string",minLength:1,maxLength:400}}}}},sD=new om.Ajv2020({allErrors:!0,strict:!0}).compile(kE);var pm=br(nr(),1);import{readFile as _E,realpath as EE}from"node:fs/promises";import sm from"node:path";var cm="^[a-z0-9]+(?:[.-][a-z0-9]+)*$",lm="^(?!/)(?!.*(?:^|/)\\.\\.(?:/|$))(?!.*\\\\)[^\\u0000]+$",AE={$id:"https://schemas.dyyto.dev/platform/example-recipe-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","recipeId","version","integrity","title","locale","rootProfile","capabilities","expectedEntrypoint","verifiers","manualAcceptance","cleanup"],properties:{schemaVersion:{const:1},recipeId:{type:"string",pattern:cm},version:{type:"string",minLength:1,maxLength:128},integrity:{type:"string",pattern:ut},title:{type:"string",minLength:1,maxLength:80},locale:{const:"zh-CN"},rootProfile:{type:"object",additionalProperties:!1,required:["capabilityId","version"],properties:{capabilityId:{type:"string",pattern:X},version:{type:"string",minLength:1,maxLength:128}}},capabilities:{type:"array",minItems:1,maxItems:16,items:{type:"object",additionalProperties:!1,required:["capabilityId","version","channel"],properties:{capabilityId:{type:"string",pattern:X},version:{type:"string",minLength:1,maxLength:128},channel:{const:"development"}}}},expectedEntrypoint:{type:"string",pattern:lm,maxLength:240},verifiers:{type:"array",minItems:1,maxItems:16,uniqueItems:!0,items:{type:"string",pattern:cm}},manualAcceptance:{type:"array",minItems:1,maxItems:32,items:{type:"string",minLength:1,maxLength:240}},cleanup:{type:"object",additionalProperties:!1,required:["ownedStateDirectories"],properties:{ownedStateDirectories:{type:"array",maxItems:8,uniqueItems:!0,items:{type:"string",pattern:lm,maxLength:240}}}}}},dm=new pm.Ajv2020({allErrors:!0,strict:!0}).compile(AE),Ir=class extends Error{code;issues;constructor(t,r=[]){super(t),this.code=t,this.issues=r}};function RE(e){return v(E(e))}function PE(e){if(!dm(e))throw new Ir("EXAMPLE_RECIPE_INVALID",dm.errors??[]);let t=e,r=[t.rootProfile.capabilityId,...t.capabilities.map(n=>n.capabilityId)];if(new Set(r).size!==r.length||t.capabilities.some(n=>n.version.includes("workspace:")||n.capabilityId.includes("ai-education-poc")))throw new Ir("EXAMPLE_RECIPE_INVALID");return t}async function um(e){let t=await EE(sm.resolve(e)),r;try{r=PE(JSON.parse(await _E(sm.join(t,"recipe.json"),"utf8")))}catch(a){throw a instanceof Ir?a:new Ir("EXAMPLE_RECIPE_INVALID")}let{integrity:n,...i}=r;if(RE(i)!==n)throw new Ir("EXAMPLE_RECIPE_INTEGRITY_MISMATCH");return r}var gm=br(nr(),1);import{readFile as NE,realpath as DE}from"node:fs/promises";import fm from"node:path";var SE={$id:"https://schemas.dyyto.dev/platform/engineering-template-release-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","templateId","version","integrity","title","summary","status","profile","parameters","commands","technology","support","integration","metrics"],properties:{schemaVersion:{const:1},templateId:{type:"string",pattern:X},version:{type:"string",minLength:1,maxLength:128},integrity:{type:"string",pattern:ut},title:{type:"string",minLength:1,maxLength:80},summary:{type:"string",minLength:1,maxLength:240},status:{enum:["candidate","recommended","deprecated"]},profile:{type:"object",additionalProperties:!1,required:["id","capability"],properties:{id:{type:"string",pattern:X},capability:{type:"string",pattern:`${X.slice(1,-1)}@[0-9]+\\.[0-9]+\\.[0-9]+$`}}},parameters:{type:"array",minItems:0,maxItems:32,items:{type:"object",additionalProperties:!1,required:["id","required","description"],properties:{id:{type:"string",pattern:"^[a-z][A-Za-z0-9]*$"},required:{type:"boolean"},description:{type:"string",minLength:1,maxLength:160}}}},commands:{type:"object",minProperties:1,additionalProperties:!1,properties:{dev:{type:"string",pattern:"^[a-z][a-z0-9.:-]*$"},build:{type:"string",pattern:"^[a-z][a-z0-9.:-]*$"},test:{type:"string",pattern:"^[a-z][a-z0-9.:-]*$"},package:{type:"string",pattern:"^[a-z][a-z0-9.:-]*$"}}},technology:{type:"array",minItems:1,maxItems:32,items:{type:"object",additionalProperties:!1,required:["id","version","policy","verifiedAt","rationale","alternative","exit"],properties:{id:{type:"string",pattern:X},version:{type:"string",minLength:1,maxLength:64},policy:{enum:["recommended","allowed"]},verifiedAt:{type:"string",format:"date"},rationale:{type:"string",minLength:1,maxLength:240},alternative:{type:"string",minLength:1,maxLength:160},exit:{type:"string",minLength:1,maxLength:240}}}},support:{type:"object",additionalProperties:!1,required:["owner","tier","supportedFrom","supportedUntil","upgradeCadence","eolNoticeDays"],properties:{owner:{type:"string",pattern:X},tier:{const:"production"},supportedFrom:{type:"string",format:"date"},supportedUntil:{type:"string",format:"date"},upgradeCadence:{type:"string",minLength:1,maxLength:80},eolNoticeDays:{type:"integer",minimum:30,maximum:730}}},integration:{type:"object",additionalProperties:!1,required:["prerequisites","createCommand","result"],properties:{prerequisites:{type:"array",minItems:1,maxItems:16,items:{type:"string",minLength:1,maxLength:200}},createCommand:{type:"string",minLength:1,maxLength:2e3},result:{type:"string",minLength:1,maxLength:400}}},metrics:{type:"array",minItems:1,uniqueItems:!0,items:{enum:["time-to-green-build","time-to-first-business-commit","manual-engineering-edits","upgrade-conflicts"]}}}},mm=new gm.Ajv2020({allErrors:!0,strict:!0,formats:{date:/^\d{4}-\d{2}-\d{2}$/}}).compile(SE),Rt=class extends Error{code;issues;constructor(t,r=[]){super(t),this.code=t,this.issues=r}};function jE(e){return v(E(e))}function $E(e){if(!mm(e))throw new Rt("TEMPLATE_INVALID",mm.errors??[]);let t=e;if(new Set(t.parameters.map(r=>r.id)).size!==t.parameters.length||new Set(t.technology.map(r=>r.id)).size!==t.technology.length)throw new Rt("TEMPLATE_INVALID");if(Date.parse(t.support.supportedUntil)<=Date.parse(t.support.supportedFrom))throw new Rt("TEMPLATE_INVALID");return t}async function li(e,t=new Date){let r=await DE(fm.resolve(e)),n;try{n=$E(JSON.parse(await NE(fm.join(r,"template.json"),"utf8")))}catch(o){throw o instanceof Rt?o:new Rt("TEMPLATE_INVALID")}let{integrity:i,...a}=n;if(jE(a)!==i)throw new Rt("TEMPLATE_INTEGRITY_MISMATCH");if(n.status==="recommended"&&Date.parse(n.support.supportedUntil)<t.getTime())throw new Rt("TEMPLATE_SUPPORT_EXPIRED");return n}import{readFile as hm}from"node:fs/promises";import ym from"node:path";var OE=/^[A-Z][A-Z0-9_]*$/u,CE=/(?:API_KEY|ACCESS_KEY|SECRET|TOKEN|PASSWORD|PRIVATE_KEY|DATABASE_URL|POSTGRES_URL)$/u;function TE(e){let t=new Map;for(let r of e.split(/\r?\n/u)){let n=/^([A-Z][A-Z0-9_]*)=(.*)$/u.exec(r.trim());if(!n||!OE.test(n[1]))continue;let i=n[1],a=n[2].trim();t.set(i,{name:i,requirement:a.length===0?"conditional":"optional",secret:CE.test(i),configured:!1,source:".env.example",configuredSource:null})}return[...t.values()]}async function wm(e){let t=await hm(ym.join(e.projectRoot,".env.example"),"utf8").then(()=>".env.example").catch(()=>null),r=t?await hm(ym.join(e.projectRoot,t),"utf8"):"",n=await Qn({projectRoot:e.projectRoot}).catch(()=>null);return{commands:["dev","build","test","package"].flatMap(a=>e.commands[a]?[{id:a,script:e.commands[a],mode:a==="dev"?"managed-process":"foreground-task"}]:[]),environment:n?n.entries.map(a=>({name:a.name,...a.runtimeEnvironmentVariable?{runtimeEnvironmentVariable:a.runtimeEnvironmentVariable}:{},requirement:a.required?"conditional":"optional",kind:a.kind,secret:a.kind!=="value",configured:a.configured,source:"application-config-contract",configuredSource:"APP_CONFIG_DIR",display:a.display,...a.fingerprint?{fingerprint:a.fingerprint}:{}})):TE(r),environmentExample:t,productionValidation:{contract:!0,live:["provider-read","oss-write-read-delete"]}}}var vm={change:new Set(["plan","apply","upgrade","recover","baseline-next","add-package","add-application","add-feature"]),quality:new Set(["inspect","verify","doctor","maintenance","test","build"]),delivery:new Set(["package","delivery-plan","delivery-apply","delivery-inspect"])},Im=new Set(["queued","running","succeeded","failed","outcome-unknown","cancelled"]);function bm(e,t){if(!vm[t.plane]||t.state&&!Im.has(t.state)||t.limit!==void 0&&(!Number.isSafeInteger(t.limit)||t.limit<1||t.limit>200))throw new Error("OPERATION_FILTER_INVALID");let r=vm[t.plane],n=t.from?Date.parse(t.from):null,i=t.to?Date.parse(t.to):null;if(n!==null&&Number.isNaN(n)||i!==null&&Number.isNaN(i)||n!==null&&i!==null&&n>i)throw new Error("OPERATION_FILTER_INVALID");let a=e.filter(d=>r.has(d.operation)),o=[...new Map(a.map(d=>[d.projectId,{id:d.projectId,name:d.projectName}])).values()].sort((d,l)=>d.name.localeCompare(l.name)),s=a.filter(d=>(!t.projectId||d.projectId===t.projectId)&&(!t.state||d.state===t.state)&&(!t.kind||d.operation===t.kind)&&(n===null||Date.parse(d.createdAt)>=n)&&(i===null||Date.parse(d.createdAt)<=i)).sort((d,l)=>l.updatedAt.localeCompare(d.updatedAt)),c={total:s.length,running:s.filter(d=>d.state==="running"||d.state==="queued").length,succeeded:s.filter(d=>d.state==="succeeded").length,attention:s.filter(d=>d.state==="failed"||d.state==="outcome-unknown").length};return Object.freeze({schemaVersion:1,plane:t.plane,summary:Object.freeze(c),facets:Object.freeze({projects:Object.freeze(o),states:Object.freeze([...Im]),kinds:Object.freeze([...r])}),items:Object.freeze(s.slice(0,t.limit??50).map(Object.freeze)),hasMore:s.length>(t.limit??50)})}var di=class extends Error{code;constructor(t,r){super(r),this.code=t}},rl=/^sha256:[a-f0-9]{64}$/u,xE=/^sha512-[A-Za-z0-9+/]{86}==$/u,LE=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u,VE=/^(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)(?:-[0-9A-Za-z.-]+)?$/u,ME=/[\u0000-\u001f\u007f]/u;function Xr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function Qr(e,t){let r=Object.keys(e).sort(),n=[...t].sort();return r.length===n.length&&r.every((i,a)=>i===n[a])}function Pt(e,t=500){return typeof e=="string"&&e.length>0&&e.length<=t&&!ME.test(e)}function tl(e){return Pt(e,500)&&!e.startsWith("/")&&!e.startsWith("../")&&!e.includes("/../")&&!e.includes("\\")}function km(e,t=128){return Array.isArray(e)&&e.length<=t&&e.every(r=>Pt(r,500))&&e.every((r,n)=>n===0||e[n-1]<r)}function qE(e){return e===null?!0:!Xr(e)||!Qr(e,["fileName","digest","integrity","fileCount","unpackedBytes"])?!1:tl(e.fileName)&&rl.test(String(e.digest))&&xE.test(String(e.integrity))&&Number.isSafeInteger(e.fileCount)&&Number(e.fileCount)>0&&Number.isSafeInteger(e.unpackedBytes)&&Number(e.unpackedBytes)>0}function UE(e){if(!Xr(e)||!Qr(e,["schemaVersion","kind","packageName","version","title","summary","maturity","source","artifact","compatibility","exports","documentation","consumerEvidence"])||e.schemaVersion!==1||e.kind!=="PackageRelease"||!LE.test(e.packageName)||!VE.test(e.version)||!Pt(e.title,120)||!Pt(e.summary,1e3)||!["candidate","stable","deprecated"].includes(e.maturity)||!Xr(e.source)||!Qr(e.source,["repository","path","revision","treeDigest"])||!Pt(e.source.repository)||!tl(e.source.path)||!Pt(e.source.revision,200)||!rl.test(String(e.source.treeDigest))||!qE(e.artifact)||!Xr(e.compatibility)||!Qr(e.compatibility,["node","packageManager"])||!Pt(e.compatibility.node,100)||!Pt(e.compatibility.packageManager,100)||!km(e.exports)||!km(e.consumerEvidence)||!Xr(e.documentation))return!1;let t=e.documentation.knowledgeRef===void 0?["readme"]:["readme","knowledgeRef"];return!Qr(e.documentation,t)||!tl(e.documentation.readme)||e.documentation.knowledgeRef!==void 0&&!Pt(e.documentation.knowledgeRef,500)?!1:e.artifact!==null||e.maturity!=="stable"}function FE(e){let t={schemaVersion:1,kind:"PackageRelease",...e,source:Object.freeze({...e.source}),artifact:e.artifact===null?null:Object.freeze({...e.artifact}),compatibility:Object.freeze({...e.compatibility}),exports:Object.freeze([...e.exports]),documentation:Object.freeze({...e.documentation}),consumerEvidence:Object.freeze([...e.consumerEvidence])};if(!UE(t))throw new di("PACKAGE_RELEASE_INVALID","PackageRelease \u5185\u5BB9\u65E0\u6548");return Object.freeze({...t,releaseDigest:v(E(t))})}function _m(e){if(!Xr(e)||!Qr(e,["schemaVersion","kind","packageName","version","title","summary","maturity","source","artifact","compatibility","exports","documentation","consumerEvidence","releaseDigest"])||!rl.test(String(e.releaseDigest)))throw new di("PACKAGE_RELEASE_INVALID","PackageRelease \u7ED3\u6784\u65E0\u6548");let{releaseDigest:t,schemaVersion:r,kind:n,...i}=e,a=FE(i);if(a.releaseDigest!==t)throw new di("PACKAGE_RELEASE_MODIFIED","PackageRelease \u5DF2\u88AB\u4FEE\u6539");return a}import{lstat as zE,readFile as BE,realpath as JE}from"node:fs/promises";import Em from"node:path";async function Am(e){let t=await JE(Em.resolve(e.projectRoot)),r=new Set(e.excludeCapabilityIds??[]),n=new Map,i=[...e.lock.capabilities].sort((o,s)=>o.committedAt.localeCompare(s.committedAt)||o.capabilityId.localeCompare(s.capabilityId));for(let o of i)if(!r.has(o.capabilityId))for(let s of o.assets){let c=s.ownership??"owned-file",d=`${s.path}\0`;if(c==="managed-region")n.delete(d);else for(let p of n.keys())p.startsWith(d)&&n.delete(p);let l=c==="managed-region"?`${d}${s.regionId??""}`:d;n.set(l,{capabilityId:o.capabilityId,path:s.path,digest:s.digest,ownership:c,...s.regionId===void 0?{}:{regionId:s.regionId}})}let a=[];for(let o of[...n.values()].sort((s,c)=>s.path.localeCompare(c.path)||(s.regionId??"").localeCompare(c.regionId??"")||s.capabilityId.localeCompare(c.capabilityId))){let s=Em.join(t,...o.path.split("/")),d=await zE(s).then(async l=>{if(!l.isFile()||l.isSymbolicLink())return;let p=await BE(s);if(o.ownership!=="managed-region")return v(p);if(o.regionId!==void 0)try{return v(ea(p.toString("utf8"),o.regionId))}catch{return}}).catch(l=>l.code==="ENOENT"?void 0:Promise.reject(l))===o.digest;a.push({capabilityId:o.capabilityId,path:o.path,kind:"create",ownership:o.ownership,...o.regionId===void 0?{}:{regionId:o.regionId},desiredDigest:o.digest,disposition:d?"noop":"conflict",...d?{}:{conflictCode:"BASE_DIGEST_MISMATCH"}})}return a}var nl="0.1.38",pi={DEPENDENCIES_NOT_INSTALLED:4,VERIFIER_RUNTIME_INVALID:4},GE=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/u;function Rm(e,t){return typeof e=="string"&&e.length>0&&e.length<=t&&!GE.test(e)}function WE(e){let t={schemaVersion:1,kind:"dyyto-cli-domain-error",code:e.code,message:e.message,exitCode:pi[e.code],...e.nextStep===void 0?{}:{nextStep:e.nextStep}},r=KE(t);if(r===null)throw new TypeError("CLI domain error input is invalid");return r}function KE(e){try{if(typeof e!="object"||e===null||Object.getPrototypeOf(e)!==Object.prototype)return null;let t=Object.getOwnPropertyDescriptors(e);if(Reflect.ownKeys(t).some(s=>typeof s=="symbol"))return null;let r=Object.keys(t).sort(),n="nextStep"in t?["code","exitCode","kind","message","nextStep","schemaVersion"]:["code","exitCode","kind","message","schemaVersion"];if(r.length!==n.length||r.some((s,c)=>s!==n[c])||Object.values(t).some(s=>!("value"in s)))return null;let i=s=>t[s]?.value,a=i("code");if(i("schemaVersion")!==1||i("kind")!=="dyyto-cli-domain-error"||typeof a!="string"||!(a in pi)||i("exitCode")!==pi[a]||!Rm(i("message"),500))return null;let o=i("nextStep");return o!==void 0&&!Rm(o,500)?null:Object.freeze({schemaVersion:1,kind:"dyyto-cli-domain-error",code:a,message:i("message"),exitCode:4,...o===void 0?{}:{nextStep:o}})}catch{return null}}var xe=class extends Error{code;exitCode;nextStep;domainError;constructor(t){super(t.message),this.name="CliError",this.code=t.code,this.exitCode=t.exitCode,this.nextStep=t.nextStep,this.domainError=t.code in pi&&t.exitCode===pi[t.code]?WE({code:t.code,message:t.message,...t.nextStep===void 0?{}:{nextStep:t.nextStep}}):void 0}};var Pm=`Dyyto Engineering Platform CLI
|
|
34
|
+
`)}function pf(e){let t=e.currentLock.capabilities.find(p=>p.capabilityId===e.release.capabilityId&&p.version===e.release.version);if(!t?.packageAdoption)throw new Z("PACKAGE_SOURCE_NOT_FOUND");let r=new Set(e.currentLock.capabilities.filter(p=>p!==t).flatMap(p=>p.packageAdoption?.sources.map(m=>m.packageName)??[])),n=t.packageAdoption.sources.filter(p=>!r.has(p.packageName)),i=qc({packageJson:e.packageJson,remove:n}),a=At(e.projectManifest),o=Array.isArray(a.capabilities)?a.capabilities:[],s=Buffer.from(`${JSON.stringify({...a,capabilities:o.filter(p=>p.capabilityId!==e.release.capabilityId||p.version!==e.release.version)},null,2)}
|
|
35
|
+
`),c=e.endpointBindings.filter(p=>n.some(m=>m.registryId===p.registryId)),d=[{path:"project-capabilities.json",kind:"replace",ownership:"owned-file",baseDigest:v(e.projectManifest),desiredDigest:v(s)},{path:"package.json",kind:"replace",ownership:"owned-file",baseDigest:v(e.packageJson),desiredDigest:v(i)},{path:"pnpm-lock.yaml",kind:"replace",ownership:"owned-file",baseDigest:v(e.currentLockfile),desiredDigest:v(e.desiredLockfile)},...t.assets.map(p=>({path:p.path,kind:"remove",ownership:p.ownership??"owned-file",baseDigest:p.digest}))];return{plan:De({action:"remove",capability:{schemaVersion:1,capabilityId:e.release.capabilityId,version:e.release.version,integrity:e.release.integrity,assets:t.assets.map(p=>({path:p.path,ownership:p.ownership??"owned-file",desiredDigest:p.digest})),verifiers:e.release.verifiers.map(p=>({id:p.id,kind:"file-digest"}))},changes:d,observedAssets:[...e.observedAssets],generatedAt:e.generatedAt,expiresAt:e.expiresAt,packageAdoption:{schemaVersion:1,sourceChannel:t.packageAdoption.sourceChannel??"production",packageJsonPreimageDigest:v(e.packageJson),desiredPackageJsonDigest:v(i),lockfilePreimage:{kind:"present",digest:v(e.currentLockfile)},desiredLockfileDigest:v(e.desiredLockfile),registryRevisions:t.packageAdoption.registryRevisions.map(p=>({...p})),endpointBindings:c.map(({registryId:p,registryConfigRevision:m,bindingDigest:u,expiresAt:f})=>({registryId:p,registryConfigRevision:m,bindingDigest:u,expiresAt:f})),sources:n.map(p=>({...p})),installPolicy:{ignoreScripts:!0,allowWorkspaceProtocol:!1,allowPublicRegistryFallback:!1}}}),desiredContents:new Map([["project-capabilities.json",s],["package.json",i],["pnpm-lock.yaml",e.desiredLockfile]]),removedSources:n}}function uf(e){let t=e.currentLock.capabilities.find(g=>g.capabilityId===e.release.capabilityId&&g.version===e.release.version);if(!t?.packageAdoption||e.topology.mode!=="pnpm-shared-lockfile")throw new Z("PACKAGE_SOURCE_NOT_FOUND");let r=new Set(e.currentLock.capabilities.filter(g=>g!==t).flatMap(g=>g.packageAdoption?.sources.map(h=>h.packageName)??[])),n=t.packageAdoption.sources.filter(g=>!r.has(g.packageName)),i=Uc({packageJson:e.packageJson,remove:n}),a=e.remainingSources.map(({registryId:g,packageName:h,version:w,integrity:_})=>({registryId:g,packageName:h,version:w,integrity:_})),o={mode:e.topology.mode,unitRelativeRoot:e.topology.unitRelativeRoot,unitImporterId:e.topology.unitImporterId,lockfilePath:e.topology.lockfilePath,...e.topology.workspaceManifestPath?{workspaceManifestPath:e.topology.workspaceManifestPath,workspaceManifestDigest:e.topology.workspaceManifestDigest}:{}},s=Lc(e.resolutionEvidence,{requestDigest:xc({schemaVersion:1,pnpmVersion:"11.21.0",topology:o,currentLockfileDigest:v(e.currentLockfile),desiredPackageJsonDigest:v(i),sources:a,preservedImporterDigests:e.preservedImporterDigests.map(({importerId:g,preimageDigest:h})=>({importerId:g,preimageDigest:h}))}),pnpmVersion:"11.21.0",workerReleaseId:e.resolutionWorkerReleaseId,targetImporterId:e.topology.unitImporterId,targetManifestDigest:v(i),preservedImporterDigests:e.preservedImporterDigests.map(({importerId:g,preimageDigest:h})=>({importerId:g,preimageDigest:h})),managedSources:a,now:e.generatedAt}),c=At(e.projectManifest),d=Array.isArray(c.capabilities)?c.capabilities:[],l=Buffer.from(`${JSON.stringify({...c,capabilities:d.filter(g=>g.capabilityId!==e.release.capabilityId||g.version!==e.release.version)},null,2)}
|
|
36
|
+
`),p=g=>`${e.topology.unitRelativeRoot}/${g}`,m=e.endpointBindings.filter(g=>n.some(h=>h.registryId===g.registryId)),u=[{path:p("project-capabilities.json"),kind:"replace",ownership:"owned-file",baseDigest:v(e.projectManifest),desiredDigest:v(l)},{path:p("package.json"),kind:"replace",ownership:"owned-file",baseDigest:v(e.packageJson),desiredDigest:v(i)},{path:e.topology.lockfilePath,kind:"replace",ownership:"owned-file",baseDigest:v(e.currentLockfile),desiredDigest:s.desiredLockDigest},...t.assets.map(g=>({path:p(g.path),kind:"remove",ownership:g.ownership??"owned-file",baseDigest:g.digest}))];return{plan:De({action:"remove",capability:{schemaVersion:1,capabilityId:e.release.capabilityId,version:e.release.version,integrity:e.release.integrity,assets:t.assets.map(g=>({path:g.path,ownership:g.ownership??"owned-file",desiredDigest:g.digest})),verifiers:e.release.verifiers.map(g=>({id:g.id,kind:"file-digest"}))},changes:u,observedAssets:[...e.observedAssets],generatedAt:e.generatedAt,expiresAt:e.expiresAt,packageAdoption:{schemaVersion:2,sourceChannel:t.packageAdoption.sourceChannel??"production",packageJsonPreimageDigest:v(e.packageJson),desiredPackageJsonDigest:v(i),lockfilePreimage:{kind:"present",digest:v(e.currentLockfile)},desiredLockfileDigest:s.desiredLockDigest,registryRevisions:t.packageAdoption.registryRevisions.map(g=>({...g})),endpointBindings:m.map(({registryId:g,registryConfigRevision:h,bindingDigest:w,expiresAt:_})=>({registryId:g,registryConfigRevision:h,bindingDigest:w,expiresAt:_})),sources:n.map(g=>({...g})),installPolicy:{ignoreScripts:!0,allowWorkspaceProtocol:!1,allowPublicRegistryFallback:!1},topology:o,preservedDependencies:Pa(At(i),new Set(e.remainingSources.map(g=>g.packageName))),preservedImporterDigests:e.preservedImporterDigests.map(g=>({...g}))}}),desiredContents:new Map([[p("project-capabilities.json"),l],[p("package.json"),i],[e.topology.lockfilePath,s.desiredLockfile]]),removedSources:n,transactionRoot:e.transactionRoot}}function Na(e,t){let r=e.release.availability,n=r.maturity==="available"&&r.visibility==="catalog-consumers"&&r.sourceState==="registry-verified",i=r.maturity==="candidate"&&r.visibility==="maintainers-only"&&r.sourceState==="development-registry";if((t==="production"?!n:!i)||e.release.packageSources.length===0)throw new Z("PACKAGE_SOURCE_NOT_FOUND");let a=At(e.packageJson),o=e.desiredBasePackageJson??e.packageJson,s=At(o),c="topology"in e,d=c?Pa(s,new Set(e.release.packageSources.map(y=>y.packageName))):void 0;c||Aa(a),c||Aa(s);let l=new Map(e.registryConfigs.map(y=>{let k=ba(y);return[k.registryId,k]})),p=new Map(e.endpointBindings.map(y=>{let k=l.get(y.registryId);if(k===void 0)throw new Z("PACKAGE_SOURCE_NOT_FOUND");let S=sf(y,k);return[S.registryId,S]})),m=new Map(e.receipts.map(y=>{let k=lf(y);return[k.receiptId,k]})),u=new Map(e.inspections.map(y=>[`${y.registryId}:${y.packageName}@${y.version}`,y])),f=new Map(e.release.packageSources.map(y=>[y.packageName,y])),g=c?Lc(e.resolutionEvidence,{requestDigest:xc({schemaVersion:1,pnpmVersion:"11.21.0",topology:e.topology,currentLockfileDigest:e.currentLockfile===void 0?null:v(e.currentLockfile),desiredPackageJsonDigest:v(Hn({release:e.release,packageJson:o})),sources:e.release.packageSources.map(({registryId:y,packageName:k,version:S,integrity:O})=>({registryId:y,packageName:k,version:S,integrity:O})),preservedImporterDigests:e.preservedImporterDigests.map(({importerId:y,preimageDigest:k})=>({importerId:y,preimageDigest:k}))}),pnpmVersion:"11.21.0",workerReleaseId:e.resolutionWorkerReleaseId,targetImporterId:e.topology.unitImporterId,targetManifestDigest:v(Hn({release:e.release,packageJson:o})),preservedImporterDigests:e.preservedImporterDigests.map(({importerId:y,preimageDigest:k})=>({importerId:y,preimageDigest:k})),managedSources:e.release.packageSources.map(({registryId:y,packageName:k,version:S,integrity:O})=>({registryId:y,packageName:k,version:S,integrity:O})),now:e.generatedAt}):void 0,h=c?{lockfile:g.desiredLockfile,packages:g.packageFacts.filter(y=>y.managed).map(({registryId:y,packageName:k,version:S,integrity:O})=>({registryId:y,packageName:k,version:S,integrity:O}))}:e.lockResolution;if(h.lockfile.byteLength===0||h.packages.length!==e.release.packageSources.length)throw new Z("PACKAGE_SOURCE_POLICY_VIOLATION",{cause:new Error(`managed resolution count ${h.packages.length}/${e.release.packageSources.length}`)});let w=new Map(h.packages.map(y=>[y.packageName,y]));for(let y of e.release.packageSources){let k=l.get(y.registryId),S=p.get(y.registryId),O=m.get(y.deliveryReceiptId),se=u.get(`${y.registryId}:${y.packageName}@${y.version}`),$=w.get(y.packageName);if(O!==void 0&&(t==="production"&&O.provenance==="development-readback-verified"||t==="development"&&O.provenance!=="development-readback-verified"))throw new Z("PACKAGE_SOURCE_POLICY_VIOLATION");if(!k||!S||Date.parse(S.expiresAt)<=Date.parse(e.expiresAt)||k.status!=="enabled"||!k.scopes.some(P=>y.packageName.startsWith(`${P}/`))||!O||!se||!$)throw new Z("PACKAGE_SOURCE_NOT_FOUND");if(O.registryId!==y.registryId||O.registryConfigRevision!==k.revision||O.packageName!==y.packageName||O.version!==y.version||O.integrity!==y.integrity||O.tarballDigest!==y.tarballDigest||se.integrity!==y.integrity||se.tarballDigest!==y.tarballDigest||se.deliveryReceiptId!==y.deliveryReceiptId||$.registryId!==y.registryId||$.version!==y.version||$.integrity!==y.integrity)throw new Z("PACKAGE_SOURCE_INTEGRITY_MISMATCH");if(!Ea.test(y.version)||se.lifecycleScripts.length>0)throw new Z("PACKAGE_SOURCE_POLICY_VIOLATION");for(let[P,H]of Object.entries(se.dependencies)){let ne=f.get(P);if(P.startsWith("@aipt/")&&(!ne||ne.version!==H||!Ea.test(H)))throw new Z("PACKAGE_SOURCE_POLICY_VIOLATION",{cause:new Error(`undeclared internal dependency ${y.packageName}->${P}@${H}`)});if(df.test(H))throw new Z("PACKAGE_SOURCE_POLICY_VIOLATION")}}let _=c?Hn({release:e.release,packageJson:o}):Mc({release:e.release,packageJson:o}),b={schemaVersion:c?2:1,sourceChannel:t,capabilityId:e.release.capabilityId,capabilityVersion:e.release.version,capabilityIntegrity:e.release.integrity,consumerProfile:e.consumerProfile,generatedAt:e.generatedAt,expiresAt:e.expiresAt,packageJsonPreimageDigest:v(e.packageJson),desiredPackageJsonDigest:v(_),lockfilePreimage:Object.freeze(e.currentLockfile===void 0?{kind:"absent"}:{kind:"present",digest:v(e.currentLockfile)}),desiredLockfileDigest:v(h.lockfile),registryRevisions:Object.freeze([...l.values()].filter(y=>e.release.packageSources.some(k=>k.registryId===y.registryId)).map(({registryId:y,revision:k})=>Object.freeze({registryId:y,revision:k})).sort((y,k)=>y.registryId.localeCompare(k.registryId))),endpointBindings:Object.freeze([...p.values()].filter(y=>e.release.packageSources.some(k=>k.registryId===y.registryId)).map(({registryId:y,registryConfigRevision:k,bindingDigest:S,expiresAt:O})=>Object.freeze({registryId:y,registryConfigRevision:k,bindingDigest:S,expiresAt:O})).sort((y,k)=>y.registryId.localeCompare(k.registryId))),sources:Object.freeze(e.release.packageSources.map(y=>Object.freeze({...y}))),installPolicy:Object.freeze({ignoreScripts:!0,allowWorkspaceProtocol:!1,allowPublicRegistryFallback:!1}),...c?{topology:Object.freeze({...e.topology}),preservedDependencies:Object.freeze(d.map(y=>Object.freeze({...y}))),preservedImporterDigests:Object.freeze(e.preservedImporterDigests.map(y=>Object.freeze({...y})))}:{}},A=v(Vc(b));return Object.freeze({...b,planId:A,desiredPackageJson:_,desiredLockfile:h.lockfile})}function Da(e){return Na(e,"production")}function Sa(e){return Na(e,"development")}function ja(e){return Na(e,"production")}function $a(e){return Na(e,"development")}function y_(e){let t=e.packageAdoption;if(t===void 0)throw new Z("PACKAGE_SOURCE_POLICY_VIOLATION");let r=t.schemaVersion===2&&t.topology.mode==="pnpm-shared-lockfile"?`${t.topology.unitRelativeRoot}/package.json`:"package.json",n=t.schemaVersion===2?t.topology.lockfilePath:"pnpm-lock.yaml",i=e.operations.filter(({path:l})=>l===r),a=e.operations.filter(({path:l})=>l===n);if(i.length!==1||a.length!==1)throw new Z("PACKAGE_SOURCE_POLICY_VIOLATION");let o=i[0],s=a[0],c=o.kind==="replace"&&o.baseDigest===t.packageJsonPreimageDigest&&o.desiredDigest===t.desiredPackageJsonDigest&&o.disposition==="ready",d=s.kind===(t.lockfilePreimage.kind==="absent"?"create":"replace")&&(t.lockfilePreimage.kind==="absent"?s.baseDigest===void 0:s.baseDigest===t.lockfilePreimage.digest)&&s.desiredDigest===t.desiredLockfileDigest&&s.disposition==="ready";if(!c||!d)throw new Z("PACKAGE_SOURCE_POLICY_VIOLATION")}async function ff(e){y_(e.plan);let t=!1;try{await e.packageManager.prepare({projectRoot:e.projectRoot,plan:e.plan});let r=await Gr({projectRoot:e.projectRoot,plan:e.plan,approvedPlanId:e.approvedPlanId,desiredContents:e.desiredContents,now:e.now}),n=await Jr(r);return t=!0,await e.packageManager.install({projectRoot:e.projectRoot,plan:e.plan}),await e.packageManager.verify({projectRoot:e.projectRoot,plan:e.plan}),n}catch(r){if(t){await yc({projectRoot:e.projectRoot,planId:e.plan.planId,now:new Date().toISOString(),failureCode:"PACKAGE_INSTALL_FAILED"});try{await e.packageManager.restore({projectRoot:e.projectRoot,plan:e.plan})}catch(n){throw new Z("PACKAGE_INSTALL_RECOVERY_REQUIRED",{cause:n})}}throw r}finally{await e.packageManager.cleanup({projectRoot:e.projectRoot,plan:e.plan})}}var yf=br(nr(),1);var wf=["workspace-node-application","workspace-web-application","nextjs-full-stack-application"],vf="^[a-z0-9][a-z0-9._-]{0,127}$",Zn="^[A-Z][A-Z0-9_]{0,127}$",mf="^(?!/)(?!.*(?:^|/)\\.\\.(?:/|$))(?!.*(?:^|/)\\.(?:/|$))(?!.*\\\\)(?!.*[\\u0000-\\u001f]).+$",w_={$id:"https://schemas.dyyto.dev/platform/application-config-contract-v1.json",type:"object",additionalProperties:!1,required:["$schema","schemaVersion","kind","application","configDirectory","bindings"],properties:{$schema:{const:"https://schemas.dyyto.dev/platform/application-config-contract-v1.json"},schemaVersion:{const:1},kind:{const:"ApplicationConfigContract"},application:{type:"object",additionalProperties:!1,required:["id","profile"],properties:{id:{type:"string",pattern:vf},profile:{enum:wf}}},configDirectory:{type:"object",additionalProperties:!1,required:["rootEnvironmentVariable","relativeDirectory","environmentFile","materializationOwner"],properties:{rootEnvironmentVariable:{const:"IDP_CONFIG_DIR"},relativeDirectory:{type:"string",pattern:"^applications/[a-z0-9][a-z0-9._-]{0,127}$"},environmentFile:{const:".env"},materializationOwner:{const:"external-deployment-control-plane"}}},bindings:{type:"array",maxItems:128,items:{oneOf:[{type:"object",additionalProperties:!1,required:["name","kind","required"],properties:{name:{type:"string",pattern:Zn},kind:{const:"value"},required:{type:"boolean"},default:{type:"string",maxLength:1024}}},{type:"object",additionalProperties:!1,required:["name","kind","required","file"],properties:{name:{type:"string",pattern:Zn},runtimeEnvironmentVariable:{type:"string",pattern:Zn},kind:{const:"secret-file"},required:{type:"boolean"},file:{type:"string",maxLength:512,pattern:mf},provisioning:{oneOf:[{type:"object",additionalProperties:!1,required:["strategy"],properties:{strategy:{const:"external"}}},{type:"object",additionalProperties:!1,required:["strategy"],properties:{strategy:{const:"generated"},bytes:{type:"integer",minimum:16,maximum:128}}},{type:"object",additionalProperties:!1,required:["strategy","template"],properties:{strategy:{const:"derived"},template:{type:"string",minLength:1,maxLength:2048}}}]}}},{type:"object",additionalProperties:!1,required:["name","kind","required","file"],properties:{name:{type:"string",pattern:Zn},runtimeEnvironmentVariable:{type:"string",pattern:Zn},kind:{const:"certificate-file"},required:{type:"boolean"},file:{type:"string",maxLength:512,pattern:mf}}}]}}}},gf=new yf.Ajv2020({allErrors:!0,strict:!0}).compile(w_),hf=/(?:^|_)(?:PASSWORD|PASSWD|TOKEN|SECRET|PRIVATE_KEY|ACCESS_KEY|API_KEY|DATABASE_URL|CONNECTION_STRING|DSN|AUTHORIZATION|CREDENTIALS?)(?:_|$)/u,v_=/(?:^|_)(?:PRIVATE_KEY|PRIVATE|KEYPAIR|KEYSTORE|PKCS12|P12|PFX|KEY)(?:_|$)/u,$e=class extends Error{code;issues;constructor(t,r,n=[]){super(r),this.code=t,this.issues=n}};function If(e){let t=G(e),r=t.profile?.id;if(!wf.includes(r))throw new $e("APPLICATION_CONFIG_CONTRACT_INVALID","\u73AF\u5883\u914D\u7F6E\u5951\u7EA6\u53EA\u652F\u6301\u53EF\u90E8\u7F72 Application Profile\u3002");let n=t.profile?.parameters??{},i=n.name;if(Object.keys(n).length!==1||typeof i!="string"||!new RegExp(vf,"u").test(i))throw new $e("APPLICATION_CONFIG_CONTRACT_INVALID","Application Manifest \u5FC5\u987B\u5305\u542B\u552F\u4E00\u4E14\u5408\u6CD5\u7684 name \u53C2\u6570\u3002");return{id:i,profile:r}}function Oa(e,t){if(!gf(e))throw new $e("APPLICATION_CONFIG_CONTRACT_INVALID","Application ConfigContract \u4E0D\u7B26\u5408 v1 Schema\u3002",gf.errors??[]);let r=e;if(r.configDirectory.relativeDirectory!==`applications/${r.application.id}`)throw new $e("APPLICATION_CONFIG_CONTRACT_INVALID","Config Dir \u76F8\u5BF9\u76EE\u5F55\u5FC5\u987B\u7531 Application identity \u552F\u4E00\u786E\u5B9A\u3002");let n=new Set,i=new Set,a=new Set;for(let l of r.bindings){if(n.has(l.name))throw new $e("APPLICATION_CONFIG_CONTRACT_INVALID",`\u73AF\u5883 Binding \u540D\u79F0\u91CD\u590D\uFF1A${l.name}`);if(n.add(l.name),l.kind==="value"){if(hf.test(l.name))throw new $e("APPLICATION_CONFIG_SECRET_LITERAL_FORBIDDEN",`\u654F\u611F\u914D\u7F6E ${l.name} \u5FC5\u987B\u4F7F\u7528\u6587\u4EF6 Binding\uFF0C\u7981\u6B62\u5728\u4ED3\u5E93\u4E2D\u58F0\u660E\u503C\u3002`);continue}if(!l.name.endsWith("_FILE"))throw new $e("APPLICATION_CONFIG_CONTRACT_INVALID",`\u6587\u4EF6 Binding ${l.name} \u5FC5\u987B\u4EE5 _FILE \u7ED3\u5C3E\u3002`);let p=l.runtimeEnvironmentVariable??l.name;if(i.has(p))throw new $e("APPLICATION_CONFIG_CONTRACT_INVALID",`\u8FD0\u884C\u65F6\u73AF\u5883\u53D8\u91CF\u540D\u79F0\u91CD\u590D\uFF1A${p}`);i.add(p);let m=l.kind==="secret-file"?"secrets/":"certs/";if(l.kind==="certificate-file"&&(hf.test(l.name)||v_.test(l.name)))throw new $e("APPLICATION_CONFIG_CONTRACT_INVALID",`${l.name} \u5305\u542B\u79C1\u5BC6\u6750\u6599\u8BED\u4E49\uFF0C\u5FC5\u987B\u4F7F\u7528 secret-file \u5E76\u653E\u5165 secrets/\uFF1Bcertificate-file \u53EA\u5141\u8BB8\u516C\u5F00\u8BC1\u4E66\u3002`);let u=l.file.split("/");if(!l.file.startsWith(m)||u.some(f=>f===""||f==="."||f===".."))throw new $e("APPLICATION_CONFIG_CONTRACT_INVALID",`${l.name} \u5FC5\u987B\u4F4D\u4E8E ${m} \u4E0B\u7684\u5177\u4F53\u6587\u4EF6\u3002`);if(a.has(l.file))throw new $e("APPLICATION_CONFIG_CONTRACT_INVALID",`\u914D\u7F6E\u6587\u4EF6 Binding \u8DEF\u5F84\u91CD\u590D\uFF1A${l.file}`);a.add(l.file)}let o=new Map(r.bindings.map(l=>[l.name,l])),s=new Set,c=new Set,d=l=>{if(c.has(l))return;if(s.has(l))throw new $e("APPLICATION_CONFIG_CONTRACT_INVALID",`\u6D3E\u751F\u914D\u7F6E\u5B58\u5728\u5FAA\u73AF\u5F15\u7528\uFF1A${l}`);s.add(l);let p=o.get(l);if(p?.kind==="secret-file"&&p.provisioning?.strategy==="derived")for(let m of p.provisioning.template.matchAll(/\$\{([A-Z][A-Z0-9_]{0,127})\}/gu)){let u=m[1],f=o.get(u);if(!f||f.kind==="certificate-file")throw new $e("APPLICATION_CONFIG_CONTRACT_INVALID",`${l}\u5F15\u7528\u672A\u77E5\u6216\u4E0D\u5141\u8BB8\u7684\u914D\u7F6E\uFF1A${u}`);d(u)}s.delete(l),c.add(l)};for(let l of o.keys())d(l);if(t!==void 0){let l=If(t);if(r.application.id!==l.id||r.application.profile!==l.profile)throw new $e("APPLICATION_CONFIG_IDENTITY_MISMATCH","ConfigContract \u7684\u5E94\u7528\u8EAB\u4EFD\u6216 Profile \u4E0E Project Manifest \u4E0D\u4E00\u81F4\u3002")}return r}function Ca(e){let t=If(e),r=t.profile==="workspace-web-application"?[]:[{name:"PORT",kind:"value",required:!1,default:"3000"}],n={$schema:"https://schemas.dyyto.dev/platform/application-config-contract-v1.json",schemaVersion:1,kind:"ApplicationConfigContract",application:t,configDirectory:{rootEnvironmentVariable:"IDP_CONFIG_DIR",relativeDirectory:`applications/${t.id}`,environmentFile:".env",materializationOwner:"external-deployment-control-plane"},bindings:r};return Oa(n,e),Buffer.from(`${JSON.stringify(n,null,2)}
|
|
37
|
+
`)}import{createHash as I_,X509Certificate as b_}from"node:crypto";import{lstat as Xn,readFile as et,realpath as Ta}from"node:fs/promises";import K from"node:path";var ue=class extends Error{code;constructor(t,r){super(r),this.code=t}};function kf(e){let t=G(e),r=t.profile?.parameters?.name;if(typeof r!="string"||!/^[a-z0-9][a-z0-9._-]{0,127}$/u.test(r))throw new ue("APPLICATION_CONFIG_BINDING_IDENTITY_INVALID","\u9879\u76EE\u7F3A\u5C11\u5408\u6CD5Application identity\u3002");return{id:r,profile:t.profile.id}}function La(e){let t=kf(e);return Buffer.from(`${JSON.stringify({$schema:"https://schemas.dyyto.dev/platform/application-config-binding-v1.json",schemaVersion:1,kind:"ApplicationConfigBinding",application:t,environment:{name:"local"},configDirectory:{rootEnvironmentVariable:"APP_CONFIG_DIR",scope:"application-environment"},contract:{path:"config/application-config.json"},materializationOwner:"external-deployment-control-plane"},null,2)}
|
|
38
|
+
`)}function _f(e,t){let r=e;if(r?.$schema!=="https://schemas.dyyto.dev/platform/application-config-binding-v1.json"||r.schemaVersion!==1||r.kind!=="ApplicationConfigBinding"||r.environment?.name!=="local"||r.configDirectory?.rootEnvironmentVariable!=="APP_CONFIG_DIR"||r.configDirectory.scope!=="application-environment"||r.contract?.path!=="config/application-config.json"||r.materializationOwner!=="external-deployment-control-plane")throw new ue("APPLICATION_CONFIG_BINDING_INVALID","ApplicationConfigBinding\u4E0D\u7B26\u5408v1\u5408\u540C\u3002");if(!r.application||typeof r.application.id!="string"||typeof r.application.profile!="string")throw new ue("APPLICATION_CONFIG_BINDING_INVALID","ApplicationConfigBinding\u5E94\u7528\u8EAB\u4EFD\u65E0\u6548\u3002");if(t!==void 0){let n=kf(t);if(r.application.id!==n.id||r.application.profile!==n.profile)throw new ue("APPLICATION_CONFIG_BINDING_IDENTITY_MISMATCH","ApplicationConfigBinding\u4E0EProject Manifest\u8EAB\u4EFD\u4E0D\u4E00\u81F4\u3002")}return r}function k_(e){let t={};for(let[r,n]of e.split(/\r?\n/u).entries()){let i=n.trim();if(!i||i.startsWith("#"))continue;let a=/^([A-Z][A-Z0-9_]*)=(.*)$/u.exec(i),o=a?.[1],s=a?.[2];if(!o||s===void 0||o in t)throw new ue("APPLICATION_CONFIG_ENV_INVALID",`.env:${r+1}\u683C\u5F0F\u65E0\u6548\u6216\u53D8\u91CF\u91CD\u590D\u3002`);t[o]=s.trim().replace(/^(?:"([\s\S]*)"|'([\s\S]*)')$/u,"$1$2")}return t}function xa(e){return`sha256:${I_("sha256").update(e).digest("hex")}`}async function bf(e,t,r){let n=await Xn(e).catch(()=>null);if(!n||!n.isFile()||n.isSymbolicLink()||n.nlink!==1||!r&&n.size===0||(n.mode&511&-385)!==0)throw new ue("APPLICATION_CONFIG_FILE_INVALID",`${t}\u4E0D\u5B58\u5728\u3001\u4E3A\u7A7A\u3001\u4E0D\u662F\u5B89\u5168\u666E\u901A\u6587\u4EF6\u6216\u6743\u9650\u8D85\u8FC70600\u3002`);return n}function __(e){let t=new Map;for(let r of e)for(let n of r.readiness.entries){let i=n.runtimeEnvironmentVariable??n.name.replace(/_FILE$/u,""),a=t.get(i)??[];a.push({unit:r.unit,entry:n}),t.set(i,a)}return Object.freeze([...t.entries()].sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>{let i=n[0].entry,a=new Set(n.map(({entry:l})=>`${l.name}\0${l.kind}`)),o=n.filter(({entry:l})=>l.configured),s=new Set(o.map(({entry:l})=>l.kind==="value"?l.display:l.fingerprint??"")),c=a.size!==1,d=!c&&s.size<=1;return Object.freeze({name:i.name,...i.runtimeEnvironmentVariable?{runtimeEnvironmentVariable:i.runtimeEnvironmentVariable}:r!==i.name.replace(/_FILE$/u,"")?{runtimeEnvironmentVariable:r}:{},kind:i.kind,required:n.some(({entry:l})=>l.required),configured:!c&&d&&o.length===n.length,consistent:d,conflict:c,consumers:Object.freeze(n.map(({unit:l})=>l).sort()),configuredConsumers:Object.freeze(o.map(({unit:l})=>l).sort()),display:i.kind==="value"&&d&&o.length?i.display:c?"\u5408\u540C\u51B2\u7A81":d?o.length===n.length?"\u5DF2\u914D\u7F6E":"\u90E8\u5206\u914D\u7F6E":"\u503C\u4E0D\u4E00\u81F4"})}))}var E_=new Set(["APPLICATION_CONFIG_FILE_INVALID","APPLICATION_CONFIG_REFERENCE_CHANGED"]),A_=new Set(["APP_CONFIG_DIR_REQUIRED","ENOENT"]);async function Fc({projectRoot:e,environment:t=process.env}){let r=await Ta(K.resolve(e)),n=K.join(r,"config/application-config.json");if(!await Xn(n).catch(()=>null))return{schemaVersion:1,application:null,environment:"local",configDirectory:null,contractDigest:null,state:"not-declared",needsConfigInit:!1,missingBindings:[],issueCode:"APPLICATION_CONFIG_CONTRACT_NOT_DECLARED",entries:[]};try{let[a,o]=await Promise.all([et(K.join(r,"project-capabilities.json")),et(n)]),s=JSON.parse(a.toString("utf8")),c=Oa(JSON.parse(o.toString("utf8")),s),d=await et(K.join(r,".dyyto/application-config-binding.json")).catch(p=>{if(p.code==="ENOENT")return null;throw p});if(!d)return{schemaVersion:1,application:c.application.id,environment:"local",configDirectory:null,contractDigest:xa(o),state:"invalid",needsConfigInit:!1,missingBindings:[],issueCode:"APPLICATION_CONFIG_BINDING_NOT_DECLARED",entries:[]};let l=_f(JSON.parse(d.toString("utf8")),s);try{let p=await Qn({projectRoot:r,environment:t}),m=p.entries.filter(f=>f.required&&!f.configured).map(f=>f.name),u=m.length?"incomplete":"ready";return{schemaVersion:1,...p,state:u,needsConfigInit:u==="incomplete",missingBindings:m}}catch(p){let m=p instanceof ue?p.code:p.code??"APPLICATION_CONFIG_UNKNOWN",u=A_.has(m)?"missing":E_.has(m)?"incomplete":"invalid",f=await Ef(r,l.application.id,t).catch(()=>{});return{schemaVersion:1,application:l.application.id,environment:"local",configDirectory:f??null,contractDigest:xa(o),state:u,needsConfigInit:u==="missing"||u==="incomplete",missingBindings:u==="missing"?c.bindings.filter(g=>g.required).map(g=>g.name):[],issueCode:m,entries:[]}}}catch(a){let o=a instanceof ue||a instanceof Error&&"code"in a?String(a.code):"APPLICATION_CONFIG_INVALID";return{schemaVersion:1,application:null,environment:"local",configDirectory:null,contractDigest:null,state:"invalid",needsConfigInit:!1,missingBindings:[],issueCode:o,entries:[]}}}var R_=new Set(["workspace-node-application","workspace-web-application","workspace-expo-application","nextjs-full-stack-application"]);async function zc({workspaceRoot:e,environment:t=process.env}){let r=await Ta(K.resolve(e));if(G(JSON.parse(await et(K.join(r,"project-capabilities.json"),"utf8"))).profile?.id!=="workspace-root")throw new ue("APPLICATION_CONFIG_WORKSPACE_INVALID","\u914D\u7F6E\u5C31\u7EEA\u5EA6\u5DE5\u4F5C\u533A\u5FC5\u987B\u91C7\u7528workspace-root Profile\u3002");let i=await Ju(r),a=[];for(let s of i){let c=K.join(r,...s.relativeRoot.split("/")),d=K.join(c,"project-capabilities.json"),l=await et(d,"utf8").catch(()=>null),p=await Xn(K.join(c,"config/application-config.json")).then(f=>f.isFile()&&!f.isSymbolicLink()).catch(()=>!1),m="";if(l!==null)try{m=G(JSON.parse(l)).profile?.id??""}catch{p&&(m="invalid-application")}if(!R_.has(m)&&!p)continue;let u=await Fc({projectRoot:c,environment:t}).catch(f=>({schemaVersion:1,application:null,environment:"local",configDirectory:null,contractDigest:null,state:"invalid",needsConfigInit:!1,missingBindings:[],issueCode:f instanceof Error&&"code"in f?String(f.code):"APPLICATION_CONFIG_UNIT_INSPECTION_FAILED",entries:[]}));a.push({unit:s.relativeRoot,readiness:u})}let o=s=>a.filter(c=>c.readiness.state===s).length;return Object.freeze({schemaVersion:1,scope:"workspace",workspaceRoot:r,summary:Object.freeze({total:a.length,ready:o("ready"),missing:o("missing"),incomplete:o("incomplete"),invalid:o("invalid"),notDeclared:o("not-declared"),needsConfigInit:a.filter(s=>s.readiness.needsConfigInit).length}),applications:Object.freeze(a.map(s=>Object.freeze(s))),environment:__(a)})}async function P_(e,t,r){let n=K.dirname(e);for(;n!==K.dirname(n);){try{if(JSON.parse(await et(K.join(n,"project-capabilities.json"),"utf8")).profile?.id==="workspace-root"){let a=K.relative(n,e);if(!/^(?:apps|services|packages)[/\\][a-z0-9][a-z0-9._-]*$/u.test(a))throw new ue("APPLICATION_CONFIG_WORKSPACE_UNIT_INVALID","Workspace\u5E94\u7528\u5FC5\u987B\u4F4D\u4E8Eapps/<name>\u3001services/<name>\u6216packages/<name>\u3002");return K.join(K.basename(n),a,r)}}catch(i){if(i instanceof ue)throw i}n=K.dirname(n)}return K.join(t,r)}async function Ef(e,t,r){let n=r.DYYTO_WORKBENCH_PROJECT_BINDINGS_FILE;if(n){if(!K.isAbsolute(n))throw new ue("WORKBENCH_PROJECT_BINDINGS_INVALID","\u5DE5\u4F5C\u53F0\u9879\u76EEBinding\u6587\u4EF6\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84\u3002");let a=await Xn(n).catch(()=>null);if(!a?.isFile()||a.isSymbolicLink()||a.nlink!==1||(a.mode&511&-385)!==0)throw new ue("WORKBENCH_PROJECT_BINDINGS_INVALID","\u5DE5\u4F5C\u53F0\u9879\u76EEBinding\u6587\u4EF6\u4E0D\u5B89\u5168\u3002");let o=JSON.parse(await et(n,"utf8"));if(o.schemaVersion!==1||!Array.isArray(o.projects))throw new ue("WORKBENCH_PROJECT_BINDINGS_INVALID","\u5DE5\u4F5C\u53F0\u9879\u76EEBinding\u7248\u672C\u65E0\u6548\u3002");let s=o.projects.filter(c=>typeof c.containerPath=="string"&&typeof c.configDirectory=="string"&&(e===c.containerPath||e.startsWith(`${c.containerPath}${K.sep}`))).sort((c,d)=>d.containerPath.length-c.containerPath.length);if(s[0])return s[0].configDirectory}let i=r.APP_CONFIG_DIR;if(i){if(!K.isAbsolute(i))throw new ue("APP_CONFIG_DIR_REQUIRED","APP_CONFIG_DIR\u5FC5\u987B\u662F\u7EDD\u5BF9\u4E1A\u52A1\u914D\u7F6E\u603B\u6839\u3002");return K.join(i,await P_(e,t,r.DYYTO_APPLICATION_ENVIRONMENT??"local"))}}async function Qn({projectRoot:e,environment:t=process.env}){let r=await Ta(K.resolve(e)),[n,i,a]=await Promise.all([et(K.join(r,"project-capabilities.json")),et(K.join(r,".dyyto/application-config-binding.json")),et(K.join(r,"config/application-config.json"))]),o=JSON.parse(n.toString("utf8")),s=_f(JSON.parse(i.toString("utf8")),o),c=Oa(JSON.parse(a.toString("utf8")),o),d=await Ef(r,s.application.id,t);if(!d||!K.isAbsolute(d))throw new ue("APP_CONFIG_DIR_REQUIRED","\u8BF7\u4E3A\u5F53\u524D\u9879\u76EE\u8BBE\u7F6E\u7EDD\u5BF9APP_CONFIG_DIR\u3002");let l=await Ta(d),p=await Xn(l);if(!p.isDirectory()||p.isSymbolicLink()||(p.mode&511&-449)!==0)throw new ue("APP_CONFIG_DIR_INVALID","APP_CONFIG_DIR\u5FC5\u987B\u662F\u6743\u9650\u4E0D\u8D85\u8FC70700\u7684\u666E\u901A\u76EE\u5F55\u3002");let m=K.relative(r,l);if(m===""||!m.startsWith("..")&&!K.isAbsolute(m))throw new ue("APP_CONFIG_DIR_INSIDE_PROJECT","APP_CONFIG_DIR\u4E0D\u80FD\u4F4D\u4E8E\u9879\u76EE\u4ED3\u5E93\u5185\u3002");let u=K.join(l,".env");await bf(u,"\u5E94\u7528.env",c.bindings.length===0);let f=k_(await et(u,"utf8")),g=[];for(let h of c.bindings){if(h.kind==="value"){let O=f[h.name]??"";g.push({name:h.name,kind:h.kind,required:h.required,configured:O.length>0,source:"APP_CONFIG_DIR",display:O});continue}if(f[h.name]!==h.file)throw new ue("APPLICATION_CONFIG_REFERENCE_CHANGED",`${h.name}\u672A\u4FDD\u6301\u5408\u540C\u6587\u4EF6\u5F15\u7528\u3002`);let _=K.resolve(l,h.file),b=K.relative(l,_);if(!b||b.startsWith("..")||K.isAbsolute(b))throw new ue("APPLICATION_CONFIG_REFERENCE_ESCAPE",`${h.name}\u9003\u9038APP_CONFIG_DIR\u3002`);let A=await bf(_,h.name,!0),y=await et(_),k=y.length>0,S;if(k&&h.kind==="certificate-file")try{let O=new b_(y);S={subject:O.subject,issuer:O.issuer,validFrom:O.validFrom,validTo:O.validTo}}catch{throw new ue("APPLICATION_CERTIFICATE_INVALID",`${h.name}\u4E0D\u662F\u6709\u6548X.509\u8BC1\u4E66\u3002`)}g.push({name:h.name,...h.runtimeEnvironmentVariable?{runtimeEnvironmentVariable:h.runtimeEnvironmentVariable}:{},kind:h.kind,required:h.required,configured:k,source:"APP_CONFIG_DIR",display:k?"\u5DF2\u914D\u7F6E":"\u672A\u914D\u7F6E",...k?{fingerprint:xa(y),updatedAt:A.mtime.toISOString()}:{},...S?{certificate:S}:{}})}return{application:s.application.id,environment:"local",configDirectory:l,contractDigest:xa(a),entries:g}}var yr="project-capabilities.json",Af=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;function S_(e,t){if(!Af.test(e)||!Af.test(t))throw new M("CONSUMER_PROFILE_UNSUPPORTED","Upgrade requires stable SemVer releases");let r=e.split(".").map(Number),n=t.split(".").map(Number);for(let i=0;i<3;i+=1)if(r[i]!==n[i])return r[i]-n[i];return 0}async function j_(e,t){let r=ei.join(e,...t.split("/"));try{let n=await N_(r);if(!n.isFile()||n.isSymbolicLink())throw new M("PROJECT_STATE_INVALID","Managed upgrade target must be a regular file",t);return{path:t,exists:!0,digest:v(await Va(r))}}catch(n){if(n.code==="ENOENT")return{path:t,exists:!1};throw n}}function Ma(e,t){let r=G(e),n=t.release,i=n.assets.find(o=>o.path==="package.json");if((n.consumerProfile==="standalone-npm-package"||n.consumerProfile==="workspace-npm-package")&&i?.renderer?.startsWith("npm-package-json-")===!0)return $c(Ft(r,n.consumerProfile));if(n.consumerProfile==="react-component-library"&&i?.renderer==="react-component-package-json-v1")return Oc(Ft(r,n.consumerProfile));let a=t.contents.get("package.json");if(a===void 0)throw new M("RELEASE_NOT_FOUND","Transition target package.json is unavailable");return a}async function Bc(e){let t=G(e.manifest),r=Te(e.currentLock),n=e.sourceRelease.release,i=e.targetRelease.release,a=t.capabilities.find(P=>P.capabilityId===n.capabilityId),o=r.capabilities.find(P=>P.capabilityId===n.capabilityId),s=i.capabilityId!==n.capabilityId&&i.dependencies?.capabilities?.includes(n.capabilityId)===!0;if(a===void 0||o===void 0||a.capabilityId!==o.capabilityId||a.version!==o.version||n.capabilityId!==o.capabilityId||n.version!==o.version||n.integrity!==o.integrity||!s&&i.capabilityId!==o.capabilityId||i.consumerProfile!==o.consumerProfile||n.consumerProfile!==i.consumerProfile)throw new M("CONSUMER_PROFILE_UNSUPPORTED","Upgrade source, target, Manifest, and Lock must describe one compatible capability");if(!s&&S_(i.version,n.version)<=0)throw new M("CONSUMER_PROFILE_UNSUPPORTED","Upgrade target must be newer than the locked release");let c=await D_(ei.resolve(e.projectRoot)),d={...t,...e.targetTemplate===void 0?{}:{template:e.targetTemplate},capabilities:t.capabilities.map(P=>P.capabilityId===n.capabilityId?{capabilityId:i.capabilityId,version:i.version}:P)},l=new Map(e.targetRelease.contents);i.assets.some(P=>P.path==="package.json")&&l.set("package.json",Ma(d,e.targetRelease));for(let P of i.assets)P.renderer==="application-config-contract-v1"&&l.set(P.path,Ca(d)),P.renderer==="application-config-binding-v1"&&l.set(P.path,La(d));let p,m=c,u="package.json",f;if(i.schemaVersion===2&&i.availability.maturity!=="withdrawn"&&(i.packageSources?.length??0)>0){if(e.packageSource===void 0)throw new M("CONSUMER_PROFILE_UNSUPPORTED","Profile transition requires verified Package Source facts");let P=l.get("package.json");if(P===void 0)throw new M("RELEASE_NOT_FOUND","Transition target package.json is unavailable");let H=await Va(ei.join(c,"package.json")),ne=e.packageSource.topology??{schemaVersion:1,mode:"standalone",transactionRoot:c,unitRoot:c,unitRelativeRoot:".",unitImporterId:".",lockfilePath:"pnpm-lock.yaml"};m=ne.transactionRoot,u=ne.mode==="pnpm-shared-lockfile"?`${ne.unitRelativeRoot}/package.json`:"package.json",f=ne.lockfilePath;let Be={release:i,registryConfigs:e.packageSource.registryConfigs,endpointBindings:e.packageSource.endpointBindings,receipts:e.packageSource.receipts,inspections:e.packageSource.inspections,consumerProfile:i.consumerProfile,packageJson:H,desiredBasePackageJson:P,...e.packageSource.currentLockfile===void 0?{}:{currentLockfile:e.packageSource.currentLockfile},generatedAt:e.generatedAt,expiresAt:e.expiresAt};try{let tt=ne.mode==="pnpm-shared-lockfile"?(e.packageChannel==="development"?$a:ja)({...Be,topology:{mode:ne.mode,unitRelativeRoot:ne.unitRelativeRoot,unitImporterId:ne.unitImporterId,lockfilePath:ne.lockfilePath,workspaceManifestPath:ne.workspaceManifestPath,workspaceManifestDigest:ne.workspaceManifestDigest},preservedImporterDigests:e.packageSource.preservedImporterDigests??[],resolutionEvidence:e.packageSource.resolutionEvidence,resolutionWorkerReleaseId:e.packageSource.resolutionWorkerReleaseId}):(e.packageChannel==="development"?Sa:Da)({...Be,lockResolution:e.packageSource.lockResolution});p=Ra(tt),l.set("package.json",tt.desiredPackageJson),l.set(f,tt.desiredLockfile)}catch(tt){throw tt instanceof Z?new M("CONSUMER_PROFILE_UNSUPPORTED",tt.code):tt}}let g=new Map(o.assets.filter(P=>P.path!==yr).map(P=>[P.path,P.digest])),h=new Map(i.assets.filter(P=>P.path!==yr).map(P=>{let H=l.get(P.path);if(H===void 0)throw new M("RELEASE_NOT_FOUND","Upgrade target asset content is unavailable",P.path);return[P.path,v(H)]})),w=[...new Set([...g.keys(),...h.keys()])].sort(),_=[],b=[];for(let P of w){let H=await j_(c,P);_.push(H);let ne=g.get(P),Be=h.get(P),tt=i.assets.find(rg=>rg.path===P);if(tt?.ownership==="seed-file"&&H.exists&&H.digest!==void 0){h.set(P,H.digest),l.set(P,await Va(ei.join(c,...P.split("/")))),b.push({path:P,kind:"replace",ownership:"seed-file",baseDigest:H.digest,desiredDigest:H.digest});continue}if(ne===void 0){if(Be===void 0)throw new M("RELEASE_NOT_FOUND","Target asset digest is unavailable",P);b.push({path:P,kind:"create",ownership:tt?.ownership??"owned-file",desiredDigest:Be})}else Be===void 0?b.push({path:P,kind:"remove",ownership:"owned-file",baseDigest:ne}):b.push({path:P,kind:"replace",ownership:tt?.ownership??"owned-file",baseDigest:ne,desiredDigest:Be})}if(p!==void 0&&f!==void 0){let P=e.packageSource?.currentLockfile;if(P===void 0)throw new M("CONSUMER_PROFILE_UNSUPPORTED","Transition lockfile preimage is unavailable");let H=l.get(f);_.push({path:f,exists:!0,digest:v(P)}),b.push({path:f,kind:"replace",ownership:"owned-file",baseDigest:v(P),desiredDigest:v(H)})}let A=await Va(ei.join(c,yr)),y=Buffer.from(`${JSON.stringify(d,null,2)}
|
|
39
|
+
`);_.push({path:yr,exists:!0,digest:v(A)}),b.push({path:yr,kind:"replace",ownership:"owned-file",baseDigest:v(A),desiredDigest:v(y)});let k={schemaVersion:1,capabilityId:i.capabilityId,version:i.version,integrity:i.integrity,assets:i.assets.filter(P=>P.path!==yr).map(P=>({path:P.path,ownership:P.ownership,desiredDigest:h.get(P.path)})),verifiers:i.verifiers.map(({id:P})=>({id:P,kind:"command"}))},S=m===c?b:b.map(P=>P.path===f?P:{...P,path:`${e.packageSource.topology.unitRelativeRoot}/${P.path}`}),O=m===c?_:_.map(P=>P.path===f?P:{...P,path:`${e.packageSource.topology.unitRelativeRoot}/${P.path}`}),se=De({action:"upgrade",capability:k,changes:S,observedAssets:O,generatedAt:e.generatedAt,expiresAt:e.expiresAt,...p===void 0?{}:{packageAdoption:p}});l.set(yr,y);let $=new Map;for(let P of se.operations){if(P.disposition!=="ready"||P.kind==="remove")continue;let H=m===c?"":`${e.packageSource.topology.unitRelativeRoot}/`,ne=P.path===f?P.path:P.path.startsWith(H)?P.path.slice(H.length):P.path,Be=l.get(ne);if(Be===void 0)throw new M("RELEASE_NOT_FOUND","Upgrade desired content is unavailable",P.path);$.set(P.path,Be)}return{sourceLock:r,targetManifest:d,release:e.targetRelease,plan:se,desiredContents:$,transactionRoot:m}}import{link as $_,mkdir as O_,open as Rf,readFile as lt,readdir as C_,realpath as dt,rm as T_,unlink as x_}from"node:fs/promises";import de from"node:path";var j=class extends Error{code;constructor(t,r){super(r),this.code=t,this.name="DeliveryError"}};function Ee(e){return/^sha256:[a-f0-9]{64}$/.test(e)}function Pf(e){return v(E(e))}function Yc(e){if(!Ee(e.project.lockDigest)||!Ee(e.project.appliedPlanId)||!Ee(e.artifact.digest))throw new j("DELIVERY_PRECONDITION_FAILED","Delivery identities must use canonical SHA-256 digests");if(Date.parse(e.expiresAt)<=Date.parse(e.createdAt)||Number.isNaN(Date.parse(e.createdAt)))throw new j("DELIVERY_PRECONDITION_FAILED","Delivery plan expiry must follow creation time");if(e.kind==="npm-publish"&&(e.artifact.type!=="npm-package"||e.target.adapterId!=="registry.npmjs"||e.risk!=="irreversible-publish")||e.kind==="application-deploy"&&(e.artifact.type!=="node-application"&&e.artifact.type!=="web-application"||e.target.adapterId!=="deployment.local-docker"||e.risk!=="local-reversible-deployment")||e.kind==="artifact-publication"&&(e.artifact.type!=="published-package"||e.target.adapterId!=="publication.offline-web"&&e.target.adapterId!=="publication.hosted-static"||(e.target.adapterId==="publication.offline-web"?e.risk!=="local-reversible-publication":e.risk!=="external-reversible-publication"))||e.kind==="hosted-static"&&(e.artifact.type!=="web-bundle"||e.target.adapterId!=="publication.hosted-static"||e.risk!=="external-reversible-publication"))throw new j("DELIVERY_PROJECT_UNSUPPORTED","Delivery kind, artifact, target, and risk must be compatible");if(e.kind==="npm-publish"&&e.publication!==void 0){let r=e.publication,n=r.execution;if(r.mode!=="staged"||r.access!=="public"||r.authentication!=="trusted-publishing"||r.trustedAction!=="stage-only"||r.provenance!=="required"||!/^[a-z0-9][a-z0-9._-]*$/.test(r.tag)||n?.provider!=="github-actions"&&n?.provider!=="gitlab-ci"||!n.repository||!n.workflow||!n.ref||Object.values(n).some(i=>typeof i!="string"||i.length>512||/[\u0000-\u001f\u007f]/.test(i)))throw new j("DELIVERY_PRECONDITION_FAILED","npm publication policy is invalid")}if(e.kind!=="npm-publish"&&e.publication!==void 0)throw new j("DELIVERY_PRECONDITION_FAILED","Publication policy is only valid for npm delivery");let t={schemaVersion:e.kind==="npm-publish"&&e.publication!==void 0?2:1,...e,state:"reviewable"};return{...t,planId:Pf(t)}}function Gc(e){let t=e;if(t?.schemaVersion!==1&&t?.schemaVersion!==2||t.state!=="reviewable")throw new j("DELIVERY_PRECONDITION_FAILED","Delivery Plan is invalid or has been modified");if(t.schemaVersion===2&&(t.kind!=="npm-publish"||t.publication===void 0)||t.schemaVersion===1&&t.publication!==void 0)throw new j("DELIVERY_PRECONDITION_FAILED","Delivery Plan schema and publication policy do not match");let{planId:r,...n}=t;if(Pf(n)!==r)throw new j("DELIVERY_PRECONDITION_FAILED","Delivery Plan is invalid or has been modified");return Yc({kind:t.kind,project:t.project,artifact:t.artifact,target:t.target,risk:t.risk,createdAt:t.createdAt,expiresAt:t.expiresAt,...t.publication===void 0?{}:{publication:t.publication}})}function Nf(e){if(!Ee(e.planId)||!Ee(e.artifactDigest)||!/^[A-Za-z0-9._:-]{1,256}$/.test(e.stageId)||Number.isNaN(Date.parse(e.createdAt)))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Stage Record identities are invalid");let t={schemaVersion:1,...e,status:"registry-accepted"};return{...t,recordId:v(E(t))}}function Df(e){if(!Ee(e.planId)||!Ee(e.artifactDigest)||Number.isNaN(Date.parse(e.startedAt)))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Attempt Record identities are invalid");let t={schemaVersion:1,...e,status:"remote-write-started"};return{...t,recordId:v(E(t))}}function qa(e){let t=e,{recordId:r,...n}=t??{};if(t?.schemaVersion!==1||t.status!=="remote-write-started"||r!==v(E(n)))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Attempt Record is invalid or has been modified");return t}function Jc(e){let t=e,{recordId:r,...n}=t??{};if(t?.schemaVersion!==1||t.status!=="registry-accepted"||r!==v(E(n)))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Stage Record is invalid or has been modified");return t}function Sf(e){if(!Ee(e.planId)||!Ee(e.artifactDigest)||!/^[A-Za-z0-9._:-]{1,256}$/.test(e.stageId)||Number.isNaN(Date.parse(e.reviewedAt)))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Stage Review Record identities are invalid");let t={schemaVersion:1,...e,status:"artifact-digest-verified"};return{...t,recordId:v(E(t))}}function Wc(e){let t=e,{recordId:r,...n}=t??{};if(t?.schemaVersion!==1||t.status!=="artifact-digest-verified"||r!==v(E(n)))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Stage Review Record is invalid or has been modified");return t}function Ua(e){if(!Ee(e.planId)||!Ee(e.artifactDigest)||e.externalIdentity.length===0)throw new j("DELIVERY_RECEIPT_INVALID","Delivery Receipt identities are invalid");if("npm"in e){let r=e.npm;if(e.adapterId!=="registry.npmjs"||r===void 0||r.stageId.length===0||r.registry!=="https://registry.npmjs.org"||r.tarballDigest!==e.artifactDigest||r.access!=="public"||!/^[a-z0-9][a-z0-9._-]*$/.test(r.tag)||r.provenance!=="registry-attested"||!Ee(r.attestationUrlDigest))throw new j("DELIVERY_RECEIPT_INVALID","Verified npm Receipt facts are incomplete or inconsistent");let n={schemaVersion:2,...e,status:"verified"};return{...n,receiptId:v(E(n))}}if(e.kind==="npm-publish"||e.kind==="application-deploy"&&e.adapterId!=="deployment.local-docker"||e.kind==="artifact-publication"&&e.adapterId!=="publication.offline-web"&&e.adapterId!=="publication.hosted-static"||e.kind==="hosted-static"&&(e.adapterId!=="publication.hosted-static"||e.details.renderMode!=="csr"))throw new j("DELIVERY_RECEIPT_INVALID","Application or artifact Delivery Receipt facts are invalid");let t={schemaVersion:1,...e,status:"verified"};return{...t,receiptId:v(E(t))}}function Kc(e){let t=e,{receiptId:r,...n}=t??{};if(t?.schemaVersion!==1&&t?.schemaVersion!==2||t.status!=="verified"||r!==v(E(n)))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Receipt is invalid or has been modified");let{receiptId:i,schemaVersion:a,status:o,...s}=t;return Ua(s)}async function L_(e){let t=await Rf(e,"r");try{await t.sync()}finally{await t.close()}}async function ti(e,t){let r=de.dirname(e);await O_(r,{recursive:!0,mode:448});let n=`${e}.tmp-${process.pid}-${crypto.randomUUID()}`,i=await Rf(n,"wx",384);try{await i.writeFile(`${E(t)}
|
|
40
|
+
`,"utf8"),await i.sync()}finally{await i.close()}try{await $_(n,e),await x_(n),await L_(r)}catch(a){throw await T_(n,{force:!0}),a}}async function jf(e){let t=await dt(de.resolve(e.projectRoot)),r=Gc(e.plan),n=de.join(t,".dyyto","delivery","plans",`${r.planId}.json`);try{await ti(n,r)}catch(i){if(i.code!=="EEXIST")throw i;if(E(Gc(JSON.parse(await lt(n,"utf8"))))!==E(r))throw new j("DELIVERY_PRECONDITION_FAILED","Stored Delivery Plan content does not match its identity")}return r}async function zt(e){if(!Ee(e.planId))throw new j("DELIVERY_PLAN_NOT_FOUND","Delivery Plan identity is invalid");let t=await dt(de.resolve(e.projectRoot));try{let r=Gc(JSON.parse(await lt(de.join(t,".dyyto","delivery","plans",`${e.planId}.json`),"utf8")));if(r.planId!==e.planId)throw new j("DELIVERY_PRECONDITION_FAILED","Stored Delivery Plan identity does not match its path");return r}catch(r){throw r.code==="ENOENT"?new j("DELIVERY_PLAN_NOT_FOUND","Delivery Plan was not found"):r}}async function Hc(e){let t=await dt(de.resolve(e.projectRoot)),r=Kc(e.receipt),n=await zt({projectRoot:t,planId:r.planId});if(r.kind!==n.kind||r.adapterId!==n.target.adapterId||r.artifactDigest!==n.artifact.digest||r.target!==n.target.location)throw new j("DELIVERY_RECEIPT_INVALID","Delivery Receipt does not match its immutable Plan");if(r.schemaVersion===2){let a=await Hr({projectRoot:t,planId:r.planId});if(n.schemaVersion!==2||n.publication===void 0||a===null||r.npm.stageId!==a.stageId||r.npm.tarballDigest!==a.artifactDigest||r.npm.tag!==n.publication.tag||r.npm.access!==n.publication.access)throw new j("DELIVERY_RECEIPT_INVALID","Verified npm Receipt does not match its Plan and Stage Record")}let i=de.join(t,".dyyto","delivery","receipts",`${r.planId}.json`);try{await ti(i,r)}catch(a){if(a.code!=="EEXIST")throw a;let o=Kc(JSON.parse(await lt(i,"utf8")));if(E(o)!==E(r))throw new j("DELIVERY_RECEIPT_INVALID","A different Receipt already exists for this Plan");return o}return r}async function ri(e){if(!Ee(e.planId))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Receipt Plan identity is invalid");let t=await dt(de.resolve(e.projectRoot));try{let r=Kc(JSON.parse(await lt(de.join(t,".dyyto","delivery","receipts",`${e.planId}.json`),"utf8")));if(r.planId!==e.planId)throw new j("DELIVERY_RECEIPT_INVALID","Stored Delivery Receipt identity does not match its path");return r}catch(r){if(r.code==="ENOENT")return null;throw r}}async function $f(e){let t=await dt(de.resolve(e.projectRoot)),r=qa(e.record),n=await zt({projectRoot:t,planId:r.planId});if(n.schemaVersion!==2||n.kind!=="npm-publish"||r.artifactDigest!==n.artifact.digest)throw new j("DELIVERY_RECEIPT_INVALID","Delivery Attempt Record does not match an npm Plan v2");let i=de.join(t,".dyyto","delivery","attempts",`${r.planId}.json`);try{await ti(i,r)}catch(a){if(a.code!=="EEXIST")throw a;let o=qa(JSON.parse(await lt(i,"utf8")));if(E(o)!==E(r))throw new j("DELIVERY_RECEIPT_INVALID","A different Attempt Record already exists for this Plan");return o}return r}async function Of(e){if(!Ee(e.planId))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Attempt Plan identity is invalid");let t=await dt(de.resolve(e.projectRoot));try{let r=qa(JSON.parse(await lt(de.join(t,".dyyto","delivery","attempts",`${e.planId}.json`),"utf8")));if(r.planId!==e.planId)throw new j("DELIVERY_RECEIPT_INVALID","Stored Delivery Attempt identity does not match its path");return r}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Cf(e){let t=await dt(de.resolve(e.projectRoot)),r=de.join(t,".dyyto","delivery","attempts"),n;try{n=await C_(r)}catch(i){if(i.code==="ENOENT")return null;throw i}for(let i of n.sort()){if(!i.endsWith(".json"))continue;let a=qa(JSON.parse(await lt(de.join(r,i),"utf8")));if((await zt({projectRoot:t,planId:a.planId})).artifact.identity!==e.artifactIdentity)continue;let[s,c]=await Promise.all([Hr({projectRoot:t,planId:a.planId}),ri({projectRoot:t,planId:a.planId})]);if(s===null&&c===null)return a}return null}async function Tf(e){let t=await dt(de.resolve(e.projectRoot)),r=Jc(e.record),n=await zt({projectRoot:t,planId:r.planId});if(n.schemaVersion!==2||n.kind!=="npm-publish"||n.publication===void 0||r.artifactDigest!==n.artifact.digest)throw new j("DELIVERY_RECEIPT_INVALID","Delivery Stage Record does not match an npm Plan v2");let i=de.join(t,".dyyto","delivery","stages",`${r.planId}.json`);try{await ti(i,r)}catch(a){if(a.code!=="EEXIST")throw a;let o=Jc(JSON.parse(await lt(i,"utf8")));if(E(o)!==E(r))throw new j("DELIVERY_RECEIPT_INVALID","A different Stage Record already exists for this Plan");return o}return r}async function Hr(e){if(!Ee(e.planId))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Stage Plan identity is invalid");let t=await dt(de.resolve(e.projectRoot));try{let r=Jc(JSON.parse(await lt(de.join(t,".dyyto","delivery","stages",`${e.planId}.json`),"utf8")));if(r.planId!==e.planId)throw new j("DELIVERY_RECEIPT_INVALID","Stored Delivery Stage identity does not match its path");return r}catch(r){if(r.code==="ENOENT")return null;throw r}}async function xf(e){let t=await dt(de.resolve(e.projectRoot)),r=Wc(e.record),n=await Hr({projectRoot:t,planId:r.planId});if(n===null||r.stageId!==n.stageId||r.artifactDigest!==n.artifactDigest)throw new j("DELIVERY_RECEIPT_INVALID","Delivery Stage Review Record does not match its immutable Stage Record");let i=de.join(t,".dyyto","delivery","stage-reviews",`${r.planId}.json`);try{await ti(i,r)}catch(a){if(a.code!=="EEXIST")throw a;let o=Wc(JSON.parse(await lt(i,"utf8")));if(E(o)!==E(r))throw new j("DELIVERY_RECEIPT_INVALID","A different Stage Review Record already exists for this Plan");return o}return r}async function Lf(e){if(!Ee(e.planId))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Stage Review Plan identity is invalid");let t=await dt(de.resolve(e.projectRoot));try{let r=Wc(JSON.parse(await lt(de.join(t,".dyyto","delivery","stage-reviews",`${e.planId}.json`),"utf8")));if(r.planId!==e.planId)throw new j("DELIVERY_RECEIPT_INVALID","Stored Delivery Stage Review identity does not match its path");return r}catch(r){if(r.code==="ENOENT")return null;throw r}}import{readFile as tm,readdir as kE}from"node:fs/promises";import Qc from"node:path";import{mkdir as Zc,open as Ga,readFile as ii,readdir as Xf,rename as Ja,rm as Qf}from"node:fs/promises";import ve from"node:path";var V_=44;var Vf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",M_=new Uint8Array(64),qf=new Uint8Array(128);for(let e=0;e<Vf.length;e++){let t=Vf.charCodeAt(e);M_[e]=t,qf[t]=e}function ni(e,t){let r=0,n=0,i=0;do{let o=e.next();i=qf[o],r|=(i&31)<<n,n+=5}while(i&32);let a=r&1;return r>>>=1,a&&(r=-2147483648|-r),t+r}function Mf(e,t){return e.pos>=t?!1:e.peek()!==V_}var SN=1024*16;var q_=class{constructor(e){this.pos=0,this.buffer=e}next(){return this.buffer.charCodeAt(this.pos++)}peek(){return this.buffer.charCodeAt(this.pos)}indexOf(e){let{buffer:t,pos:r}=this,n=t.indexOf(e,r);return n===-1?t.length:n}};function Uf(e){let{length:t}=e,r=new q_(e),n=[],i=0,a=0,o=0,s=0,c=0;do{let d=r.indexOf(";"),l=[],p=!0,m=0;for(i=0;r.pos<d;){let u;i=ni(r,i),i<m&&(p=!1),m=i,Mf(r,d)?(a=ni(r,a),o=ni(r,o),s=ni(r,s),Mf(r,d)?(c=ni(r,c),u=[i,a,o,s,c]):u=[i,a,o,s]):u=[i],l.push(u),r.pos++}p||U_(l),n.push(l),r.pos=d+1}while(r.pos<=t);return n}function U_(e){e.sort(F_)}function F_(e,t){return e[0]-t[0]}var z_=/^[\w+.-]+:\/\//,B_=/^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/,G_=/^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;function J_(e){return z_.test(e)}function W_(e){return e.startsWith("//")}function Bf(e){return e.startsWith("/")}function K_(e){return e.startsWith("file:")}function Ff(e){return/^[.?#]/.test(e)}function Fa(e){let t=B_.exec(e);return Gf(t[1],t[2]||"",t[3],t[4]||"",t[5]||"/",t[6]||"",t[7]||"")}function Y_(e){let t=G_.exec(e),r=t[2];return Gf("file:","",t[1]||"","",Bf(r)?r:"/"+r,t[3]||"",t[4]||"")}function Gf(e,t,r,n,i,a,o){return{scheme:e,user:t,host:r,port:n,path:i,query:a,hash:o,type:7}}function zf(e){if(W_(e)){let r=Fa("http:"+e);return r.scheme="",r.type=6,r}if(Bf(e)){let r=Fa("http://foo.com"+e);return r.scheme="",r.host="",r.type=5,r}if(K_(e))return Y_(e);if(J_(e))return Fa(e);let t=Fa("http://foo.com/"+e);return t.scheme="",t.host="",t.type=e?e.startsWith("?")?3:e.startsWith("#")?2:4:1,t}function H_(e){if(e.endsWith("/.."))return e;let t=e.lastIndexOf("/");return e.slice(0,t+1)}function Z_(e,t){Jf(t,t.type),e.path==="/"?e.path=t.path:e.path=H_(t.path)+e.path}function Jf(e,t){let r=t<=4,n=e.path.split("/"),i=1,a=0,o=!1;for(let c=1;c<n.length;c++){let d=n[c];if(!d){o=!0;continue}if(o=!1,d!=="."){if(d===".."){a?(o=!0,a--,i--):r&&(n[i++]=d);continue}n[i++]=d,a++}}let s="";for(let c=1;c<i;c++)s+="/"+n[c];(!s||o&&!s.endsWith("/.."))&&(s+="/"),e.path=s}function Wf(e,t){if(!e&&!t)return"";let r=zf(e),n=r.type;if(t&&n!==7){let a=zf(t),o=a.type;switch(n){case 1:r.hash=a.hash;case 2:r.query=a.query;case 3:case 4:Z_(r,a);case 5:r.user=a.user,r.host=a.host,r.port=a.port;case 6:r.scheme=a.scheme}o>n&&(n=o)}Jf(r,n);let i=r.query+r.hash;switch(n){case 2:case 3:return i;case 4:{let a=r.path.slice(1);return a?Ff(t||e)&&!Ff(a)?"./"+a+i:a+i:i||"."}case 5:return r.path+i;default:return r.scheme+"//"+r.user+r.host+r.port+r.path+i}}function X_(e){if(!e)return"";let t=e.lastIndexOf("/");return e.slice(0,t+1)}function Q_(e,t){let r=X_(e),n=t?t+"/":"";return i=>Wf(n+(i||""),r)}var Bt=0,eE=1,tE=2,rE=3,nE=4;function iE(e,t){let r=Kf(e,0);if(r===e.length)return e;t||(e=e.slice());for(let n=r;n<e.length;n=Kf(e,n+1))e[n]=oE(e[n],t);return e}function Kf(e,t){for(let r=t;r<e.length;r++)if(!aE(e[r]))return r;return e.length}function aE(e){for(let t=1;t<e.length;t++)if(e[t][Bt]<e[t-1][Bt])return!1;return!0}function oE(e,t){return t||(e=e.slice()),e.sort(sE)}function sE(e,t){return e[Bt]-t[Bt]}var Ba=!1;function cE(e,t,r,n){for(;r<=n;){let i=r+(n-r>>1),a=e[i][Bt]-t;if(a===0)return Ba=!0,i;a<0?r=i+1:n=i-1}return Ba=!1,r-1}function lE(e,t,r){for(let n=r+1;n<e.length&&e[n][Bt]===t;r=n++);return r}function dE(e,t,r){for(let n=r-1;n>=0&&e[n][Bt]===t;r=n--);return r}function pE(){return{lastKey:-1,lastNeedle:-1,lastIndex:-1}}function uE(e,t,r,n){let{lastKey:i,lastNeedle:a,lastIndex:o}=r,s=0,c=e.length-1;if(n===i){if(t===a)return Ba=o!==-1&&e[o][Bt]===t,o;t>=a?s=o===-1?0:o:c=o}return r.lastKey=n,r.lastNeedle=t,r.lastIndex=cE(e,t,s,c)}function fE(e){return typeof e=="string"?JSON.parse(e):e}var mE="`line` must be greater than 0 (lines start at line 1)",gE="`column` must be greater than or equal to 0 (columns start at column 0)",Yf=-1,hE=1,Hf=class{constructor(e,t){let r=typeof e=="string";if(!r&&e._decodedMemo)return e;let n=fE(e),{version:i,file:a,names:o,sourceRoot:s,sources:c,sourcesContent:d}=n;this.version=i,this.file=a,this.names=o||[],this.sourceRoot=s,this.sources=c,this.sourcesContent=d,this.ignoreList=n.ignoreList||n.x_google_ignoreList||void 0;let l=Q_(t,s);this.resolvedSources=c.map(l);let{mappings:p}=n;if(typeof p=="string")this._encoded=p,this._decoded=void 0;else if(Array.isArray(p))this._encoded=void 0,this._decoded=iE(p,r);else throw n.sections?new Error("TraceMap passed sectioned source map, please use FlattenMap export instead"):new Error(`invalid source map: ${JSON.stringify(n)}`);this._decodedMemo=pE(),this._bySources=void 0,this._bySourceMemos=void 0}};function yE(e){var t;return(t=e)._decoded||(t._decoded=Uf(e._encoded))}function Zf(e,t){let{line:r,column:n,bias:i}=t;if(r--,r<0)throw new Error(mE);if(n<0)throw new Error(gE);let a=yE(e);if(r>=a.length)return za(null,null,null,null);let o=a[r],s=wE(o,e._decodedMemo,r,n,i||hE);if(s===-1)return za(null,null,null,null);let c=o[s];if(c.length===1)return za(null,null,null,null);let{names:d,resolvedSources:l}=e;return za(l[c[eE]],c[tE]+1,c[rE],c.length===5?d[c[nE]]:null)}function za(e,t,r,n){return{source:e,line:t,column:r,name:n}}function wE(e,t,r,n,i){let a=uE(e,n,t,r);return Ba?a=(i===Yf?lE:dE)(e,n,a):i===Yf&&a++,a===-1||a===e.length?-1:a}var me=class extends Error{code;constructor(t,r){super(r),this.code=t,this.name="RuntimeObservabilityError"}},Xc=/^sha256:[a-f0-9]{64}$/,em=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,vE=/^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$/,Wa=(e,t)=>Object.keys(e).every(r=>t.includes(r)),ai=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Zr=(e,t)=>e.replace(/[\u0000-\u001f\u007f]/g," ").replace(/([a-z]+:\/\/)[^/@\s]+@/gi,"$1").slice(0,t);function IE(e){if(!ai(e)||!Wa(e,["schemaVersion","eventId","occurredAt","applicationId","releaseId","deploymentId","kind","error","page","traceparent"]))throw new me("RUNTIME_ERROR_INVALID","Runtime Error Envelope contains unknown fields");if(!ai(e.error)||!ai(e.page)||!Wa(e.error,["type","message","frames"])||!Wa(e.page,["origin","path"]))throw new me("RUNTIME_ERROR_INVALID","Runtime Error Envelope structure is invalid");if(e.schemaVersion!==1||typeof e.eventId!="string"||!em.test(e.eventId)||typeof e.occurredAt!="string"||Number.isNaN(Date.parse(e.occurredAt))||typeof e.applicationId!="string"||e.applicationId.length<1||e.applicationId.length>128)throw new me("RUNTIME_ERROR_INVALID","Runtime Error Envelope identity is invalid");if(!["uncaught-error","unhandled-rejection","reported-error"].includes(e.kind))throw new me("RUNTIME_ERROR_INVALID","Runtime Error kind is invalid");for(let n of[e.releaseId,e.deploymentId])if(n!==void 0&&(typeof n!="string"||!Xc.test(n)))throw new me("RUNTIME_ERROR_IDENTITY_UNKNOWN","Runtime Error correlation identity is invalid");if(e.traceparent!==void 0&&(typeof e.traceparent!="string"||!vE.test(e.traceparent)))throw new me("RUNTIME_ERROR_INVALID","traceparent is invalid");if(typeof e.error.type!="string"||typeof e.error.message!="string"||!Array.isArray(e.error.frames)||e.error.frames.length>50||typeof e.page.origin!="string"||typeof e.page.path!="string")throw new me("RUNTIME_ERROR_INVALID","Runtime Error content is invalid");if(e.error.message.length>4096||e.error.type.length>256||e.page.path.length>2048)throw new me("RUNTIME_ERROR_TOO_LARGE","Runtime Error content exceeds a hard limit");let t=e.error.frames.map(n=>{if(!ai(n)||!Wa(n,["file","line","column","function"])||typeof n.file!="string"||n.file.length>2048)throw new me("RUNTIME_ERROR_INVALID","Runtime Error stack frame is invalid");for(let i of[n.line,n.column])if(i!==void 0&&(!Number.isSafeInteger(i)||Number(i)<1))throw new me("RUNTIME_ERROR_INVALID","Runtime Error stack location is invalid");if(n.function!==void 0&&(typeof n.function!="string"||n.function.length>256))throw new me("RUNTIME_ERROR_INVALID","Runtime Error stack function is invalid");return n}),r;try{r=new URL(e.page.origin)}catch{throw new me("RUNTIME_ERROR_INVALID","Runtime Error page origin is invalid")}if(r.origin!==e.page.origin||!e.page.path.startsWith("/")||e.page.path.includes("?")||e.page.path.includes("#"))throw new me("RUNTIME_ERROR_INVALID","Runtime Error page must contain only origin and path");return{...e,error:{...e.error,frames:t}}}function bE(e,t,r="unknown"){let n=e.error.frames.map(o=>({file:Zr(o.file,2048),...o.line===void 0?{}:{line:o.line},...o.column===void 0?{}:{column:o.column},...o.function===void 0?{}:{function:Zr(o.function,256)}})),i={type:Zr(e.error.type,256),message:Zr(e.error.message,4096),frames:n},a=v(E({type:i.type,message:i.message,frames:n.slice(0,5).map(({file:o,line:s,column:c})=>({file:o,line:s,column:c}))}));return{schemaVersion:1,eventId:e.eventId,occurredAt:e.occurredAt,receivedAt:t,applicationId:Zr(e.applicationId,128),...e.releaseId===void 0?{}:{releaseId:e.releaseId},...e.deploymentId===void 0?{}:{deploymentId:e.deploymentId},kind:e.kind,error:i,page:{origin:e.page.origin,path:Zr(e.page.path,2048)},...e.traceparent===void 0?{}:{traceparent:e.traceparent},fingerprint:a,state:e.releaseId===void 0?"persisted":"map-missing",correlation:r}}var wr=class{workspaceRoot;adapterId="observability.local";#e=Promise.resolve();constructor(t){this.workspaceRoot=t}directory(){return ve.join(ve.resolve(this.workspaceRoot),".dyyto","observability","events")}releases(){return ve.join(ve.resolve(this.workspaceRoot),".dyyto","observability","releases")}async accept(t,r){let n=IE(t);if(!r.allowedOrigins.includes(n.page.origin))throw new me("RUNTIME_ERROR_INVALID","Runtime Error origin is not registered");let i=r.resolveCorrelation===void 0?"unknown":await r.resolveCorrelation(n),a=bE(n,r.receivedAt,i);return this.#t(async()=>{let o=this.directory();await Zc(o,{recursive:!0,mode:448});let s=ve.join(o,`${a.eventId}.json`);try{let m=JSON.parse(await ii(s,"utf8")),u={...m,correlation:m.correlation??"unknown"};if(E({...u,receivedAt:a.receivedAt})!==E(a))throw new me("RUNTIME_ERROR_INVALID","eventId is already used for different content");return{eventId:a.eventId,state:u.state,duplicate:!0}}catch(m){if(m.code!=="ENOENT")throw m}let c=`${s}.tmp-${process.pid}-${crypto.randomUUID()}`,d=await Ga(c,"wx",384);try{await d.writeFile(`${E(a)}
|
|
41
|
+
`,"utf8"),await d.sync()}finally{await d.close()}await Ja(c,s);let l=await Ga(o,"r");try{await l.sync()}finally{await l.close()}await this.rotate(),a.releaseId!==void 0&&await this.resymbolicate(a.releaseId);let p=JSON.parse(await ii(s,"utf8"));return{eventId:a.eventId,state:p.state,duplicate:!1}})}#t(t){let r=this.#e.then(t,t);return this.#e=r.catch(()=>{}),r}async quarantine(t){let r=ve.join(this.directory(),t),n=ve.join(ve.resolve(this.workspaceRoot),".dyyto","observability","quarantine");await Zc(n,{recursive:!0,mode:448}),await Ja(r,ve.join(n,`${Date.now()}-${t}`))}async all(){let t=await Xf(this.directory()).catch(()=>[]),r=[];for(let n of t){if(!n.endsWith(".json")){n.includes(".tmp-")&&await this.quarantine(n).catch(()=>{});continue}try{let i=JSON.parse(await ii(ve.join(this.directory(),n),"utf8"));if(i.eventId!==n.slice(0,-5))throw new Error("identity mismatch");r.push({...i,correlation:i.correlation??"unknown"})}catch{await this.quarantine(n).catch(()=>{})}}return r.sort((n,i)=>i.occurredAt.localeCompare(n.occurredAt)||n.eventId.localeCompare(i.eventId))}selected(t,r){return t.filter(n=>(!r.applicationId||n.applicationId===r.applicationId)&&(!r.releaseId||n.releaseId===r.releaseId)&&(!r.deploymentId||n.deploymentId===r.deploymentId))}cursor(t,r){let n=E({v:1,offset:t,snapshot:r});return Buffer.from(E({content:n,digest:v(n)})).toString("base64url")}parseCursor(t,r){try{let n=JSON.parse(Buffer.from(t,"base64url").toString("utf8"));if(typeof n.content!="string"||n.digest!==v(n.content))throw new Error("tampered");let i=JSON.parse(n.content);if(i.v!==1||!Number.isSafeInteger(i.offset)||i.offset<0||i.snapshot!==r)throw new Error("expired");return i.offset}catch{throw new me("OBSERVABILITY_CURSOR_EXPIRED","Runtime Error query cursor is invalid or expired")}}async list(t){let r=Math.max(1,Math.min(t.limit??100,100)),n=this.selected(await this.all(),t),i=v(E(n.map(s=>s.eventId))),a=t.cursor===void 0?0:this.parseCursor(t.cursor,i),o=n.slice(a,a+r);return{events:o,...a+o.length<n.length?{nextCursor:this.cursor(a+o.length,i)}:{}}}async get(t){if(!em.test(t))throw new me("RUNTIME_ERROR_INVALID","Runtime Error eventId is invalid");let r=`${t}.json`;try{let n=JSON.parse(await ii(ve.join(this.directory(),r),"utf8"));if(n.eventId!==t)throw new Error("identity mismatch");return{...n,correlation:n.correlation??"unknown"}}catch(n){if(n.code==="ENOENT")return null;throw await this.quarantine(r).catch(()=>{}),new me("OBSERVABILITY_STORE_DAMAGED","Runtime Error record is damaged and has been quarantined")}}async summary(t){let r=this.selected(await this.all(),t),n=new Map;for(let i of r){let a=n.get(i.fingerprint);a?a.count+=1:n.set(i.fingerprint,{count:1,latestAt:i.occurredAt,event:i})}return{total:r.length,groups:[...n.entries()].map(([i,a])=>({fingerprint:i,...a}))}}async rotate(){let t=await this.all(),n=t.reduce((i,a)=>Math.max(i,Date.parse(a.receivedAt)),0)-10080*60*1e3;for(let i of t.slice(1e4))await Qf(ve.join(this.directory(),`${i.eventId}.json`),{force:!0});for(let i of t.slice(0,1e4))Date.parse(i.receivedAt)<n&&await Qf(ve.join(this.directory(),`${i.eventId}.json`),{force:!0})}async registerSourceMap(t){if(!Xc.test(t.releaseId)||!Xc.test(t.assetDigest)||!/^[A-Za-z0-9._/-]+\.js$/.test(t.asset)||t.asset.includes("..")||!ai(t.map)||"sourcesContent"in t.map)throw new me("RUNTIME_ERROR_INVALID","Source Map registration is invalid or contains sourcesContent");let r=Buffer.from(E(t.map)),n=v(r),i=ve.join(this.releases(),t.releaseId);await Zc(i,{recursive:!0,mode:448});let a=v(t.asset),o=ve.join(i,`${a}.json`),s={releaseId:t.releaseId,asset:t.asset,assetDigest:t.assetDigest,mapDigest:n,registeredAt:t.registeredAt},c=await Ga(`${o}.tmp`,"w",384);try{await c.writeFile(`${E({registration:s,map:t.map})}
|
|
42
|
+
`),await c.sync()}finally{await c.close()}return await Ja(`${o}.tmp`,o),await this.resymbolicate(t.releaseId),s}async resymbolicate(t){let r=await Xf(ve.join(this.releases(),t)).catch(()=>[]),n=[];for(let i of r)try{n.push(JSON.parse(await ii(ve.join(this.releases(),t,i),"utf8")))}catch{}for(let i of(await this.all()).filter(a=>a.releaseId===t&&a.state==="map-missing")){let a=!1,o=i.error.frames.map(l=>{let p=n.find(m=>new URL(l.file,"http://local").pathname.endsWith(`/${m.registration.asset}`));if(!p||l.line===void 0||l.column===void 0)return l;try{let m=Zf(new Hf(p.map),{line:l.line,column:Math.max(0,l.column-1)});return m.source===null||m.line===null||m.column===null?l:(a=!0,{...l,source:m.source.replace(/^file:\/\//,""),sourceLine:m.line,sourceColumn:m.column+1})}catch{return l}});if(!a)continue;let s={...i,error:{...i.error,frames:o},state:"symbolicated"},c=ve.join(this.directory(),`${i.eventId}.json`),d=await Ga(`${c}.tmp`,"w",384);try{await d.writeFile(`${E(s)}
|
|
43
|
+
`),await d.sync()}finally{await d.close()}await Ja(`${c}.tmp`,c)}}};var Ue=(e,t,r,n,i)=>({code:e,severity:t,fact:r,message:n,...i===void 0?{}:{action:i}});async function oi(e){if(e.lock.capabilities.length===0||e.lock.capabilities.some(r=>r.evidenceIds.length===0))return[Ue("EVIDENCE_INVALID","critical","evidence","\u5DF2\u9A8C\u8BC1\u9501\u7F3A\u5C11\u5B8C\u6574\u8BC1\u636E\u5F15\u7528\u3002","\u91CD\u65B0\u8FD0\u884C\u9A8C\u8BC1\uFF1B\u82E5\u4E8B\u52A1\u672A\u5B8C\u6210\uFF0C\u5148\u6267\u884C\u5B89\u5168\u6062\u590D\u3002")];for(let r of e.lock.capabilities)for(let n of r.evidenceIds)try{let i=On(JSON.parse(await tm(Qc.join(e.projectRoot,".dyyto","evidence",`${n}.json`),"utf8")));if(i.evidenceId!==n||i.capabilityId!==r.capabilityId||i.capabilityVersion!==r.version||i.capabilityIntegrity!==r.integrity||i.projectStateDigest!==r.projectStateDigest||i.result!=="passed")return[Ue("EVIDENCE_INVALID","critical","evidence","\u91C7\u7528\u8BC1\u636E\u4E0E\u5DF2\u9A8C\u8BC1\u9501\u7684\u8EAB\u4EFD\u6216\u5DE5\u7A0B\u72B6\u6001\u4E0D\u4E00\u81F4\u3002","\u91CD\u65B0\u8FD0\u884C\u9A8C\u8BC1\uFF1B\u82E5\u73B0\u573A\u5DF2\u53D8\u5316\uFF0C\u5148\u68C0\u67E5\u5E76\u91CD\u65B0\u89C4\u5212\u3002")]}catch{return[Ue("EVIDENCE_INVALID","critical","evidence","\u91C7\u7528\u8BC1\u636E\u7F3A\u5931\u3001\u635F\u574F\u6216\u4E0D\u7B26\u5408\u5951\u7EA6\u3002","\u91CD\u65B0\u8FD0\u884C\u9A8C\u8BC1\uFF1B\u82E5\u4E8B\u52A1\u672A\u5B8C\u6210\uFF0C\u5148\u6267\u884C\u5B89\u5168\u6062\u590D\u3002")]}let t=e.lock.capabilities.reduce((r,n)=>r+n.evidenceIds.length,0);return[Ue("EVIDENCE_VALID","info","evidence",`\u5DF2\u6838\u9A8C ${e.lock.capabilities.length} \u9879\u80FD\u529B\u7684 ${t} \u6761\u91C7\u7528\u8BC1\u636E\u3002`)]}function el(e){return e==="adopted"?[]:e==="planned"?[Ue("ADOPTION_PLANNED","warning","lock","\u80FD\u529B\u91C7\u7528\u4ECD\u5904\u4E8E\u8BA1\u5212\u9636\u6BB5\u3002","\u5BA1\u9605\u5E76\u6279\u51C6\u7CBE\u786E Plan\u3002")]:e==="applied-unverified"?[Ue("VERIFICATION_REQUIRED","warning","evidence","\u53D8\u66F4\u5DF2\u5E94\u7528\u4F46\u5C1A\u672A\u5F62\u6210\u9A8C\u8BC1\u8BC1\u636E\u3002","\u8FD0\u884C\u9A8C\u8BC1\u5E76\u63D0\u4EA4\u91C7\u7528\u9501\u3002")]:e==="drifted"?[Ue("REPOSITORY_DRIFT","warning","repository","\u5DE5\u7A0B\u73B0\u573A\u4E0E\u5DF2\u9501\u5B9A\u4E8B\u5B9E\u4E0D\u4E00\u81F4\u3002","\u68C0\u67E5\u5DEE\u5F02\u5E76\u91CD\u65B0\u89C4\u5212\uFF0C\u5E73\u53F0\u4E0D\u4F1A\u8986\u76D6\u7528\u6237\u4FEE\u6539\u3002")]:e==="recovery-required"?[Ue("RECOVERY_REQUIRED","critical","recovery","\u68C0\u6D4B\u5230\u672A\u5B8C\u6210\u7684\u6301\u4E45\u5316\u4E8B\u52A1\u3002","\u5148\u6267\u884C\u5B89\u5168\u6062\u590D\uFF0C\u518D\u7EE7\u7EED\u5176\u4ED6\u64CD\u4F5C\u3002")]:[Ue("FACT_INVALID","critical","manifest","\u5DE5\u7A0B\u5355\u5143\u4E8B\u5B9E\u65E0\u6CD5\u5B89\u5168\u8BFB\u53D6\u3002","\u4FEE\u590D\u8BE5\u5355\u5143\u7684 Manifest \u6216\u5143\u6570\u636E\u540E\u91CD\u65B0\u8BCA\u65AD\u3002")]}async function rm(e){try{let r=JSON.parse(await tm(Qc.join(e.workspaceRoot,".dyyto","observability","config.json"),"utf8"));if(!Array.isArray(r.applications)||!r.applications.includes(e.applicationId))return[Ue("OBSERVABILITY_NOT_CONFIGURED","warning","repository","\u5F53\u524D Web \u5E94\u7528\u5C1A\u672A\u914D\u7F6E\u8FD0\u884C\u65F6\u9519\u8BEF\u91C7\u96C6\u3002","\u767B\u8BB0\u5E94\u7528 Origin\uFF0C\u5E76\u542F\u52A8\u672C\u5730\u91C7\u96C6\u7AEF\u3002")]}catch{return[Ue("OBSERVABILITY_NOT_CONFIGURED","warning","repository","\u5F53\u524D Web \u5E94\u7528\u5C1A\u672A\u914D\u7F6E\u8FD0\u884C\u65F6\u9519\u8BEF\u91C7\u96C6\u3002","\u767B\u8BB0\u5E94\u7528 Origin\uFF0C\u5E76\u542F\u52A8\u672C\u5730\u91C7\u96C6\u7AEF\u3002")]}await new wr(e.workspaceRoot).list({applicationId:e.applicationId});let t=(await kE(Qc.join(e.workspaceRoot,".dyyto","observability","quarantine")).catch(()=>[])).length;return t>0?[Ue("OBSERVABILITY_STORE_DAMAGED","critical","repository",`\u8FD0\u884C\u65F6\u9519\u8BEF\u672C\u5730\u5B58\u50A8\u5DF2\u9694\u79BB ${t} \u6761\u635F\u574F\u8BB0\u5F55\uFF0C\u5065\u5EB7\u4E8B\u4EF6\u4ECD\u53EF\u67E5\u8BE2\u3002`,"\u68C0\u67E5\u672C\u673A\u78C1\u76D8\u72B6\u6001\uFF0C\u5E76\u663E\u5F0F\u5904\u7406\u9694\u79BB\u8BB0\u5F55\u3002")]:[Ue("OBSERVABILITY_CONFIGURED","info","repository","\u8FD0\u884C\u65F6\u9519\u8BEF\u91C7\u96C6\u914D\u7F6E\u4E0E\u672C\u5730\u5B58\u50A8\u53EF\u8BFB\u53D6\u3002")]}function nm(e){let t=e.units.map(n=>{let i=n.findings.some(a=>a.severity==="critical")?"blocked":n.findings.some(a=>a.severity==="warning")?"attention":"healthy";return{...n,status:i}}),r={total:t.length,healthy:t.filter(n=>n.status==="healthy").length,attention:t.filter(n=>n.status==="attention").length,blocked:t.filter(n=>n.status==="blocked").length};return{schemaVersion:1,workspace:e.workspace,generatedAt:e.generatedAt,status:r.blocked>0?"blocked":r.attention>0?"attention":"healthy",summary:r,units:t}}import{readFile as si,realpath as im}from"node:fs/promises";import vr from"node:path";var ae=class extends Error{code;constructor(t,r){super(r),this.code=t}};async function am(e){let t=await im(vr.resolve(e.projectRoot)),r=G(e.manifest),n=e.release.release,i=e.currentLock.capabilities.find(m=>m.capabilityId===n.capabilityId&&m.version===n.version);if(!i||i.packageAdoption!==void 0)throw new ae("CAPABILITY_RELEASE_VERSION_UNSUPPORTED","Asset-only removal requires an adopted Capability without package ownership");let a=G({...r,capabilities:r.capabilities.filter(m=>m.capabilityId!==n.capabilityId)}),o=Buffer.from(`${JSON.stringify(a,null,2)}
|
|
44
|
+
`),s=await ci(t,"project-capabilities.json");if(!s.exists||s.digest===void 0)throw new ae("CAPABILITY_DEPENDENCY_UNSATISFIED","Project manifest is unavailable");let c=[{path:"project-capabilities.json",kind:"replace",ownership:"owned-file",baseDigest:s.digest,desiredDigest:v(o)},...i.assets.map(m=>({path:m.path,kind:"remove",ownership:m.ownership??"owned-file",baseDigest:m.digest}))],d=await Promise.all(c.map(m=>ci(t,m.path))),l={schemaVersion:1,capabilityId:n.capabilityId,version:n.version,integrity:n.integrity,assets:i.assets.map(m=>({path:m.path,ownership:m.ownership??"owned-file",desiredDigest:m.digest})),verifiers:n.verifiers.map(m=>({id:m.id,kind:"file-digest"}))};return{plan:De({action:"remove",capability:l,changes:c,observedAssets:d,generatedAt:e.generatedAt,expiresAt:e.expiresAt}),manifest:a,desiredContents:new Map([["project-capabilities.json",o]]),transactionRoot:t,removedSources:[]}}async function ci(e,t){try{let r=await si(vr.join(e,...t.split("/")));return{path:t,exists:!0,digest:v(r)}}catch(r){if(r.code==="ENOENT")return{path:t,exists:!1};throw r}}async function tl(e){if(e.release.release.schemaVersion===2&&e.release.release.packageSources.length>0&&e.packageSource===void 0)throw new ae("CAPABILITY_RELEASE_VERSION_UNSUPPORTED","Capability Release v2 requires verified package source facts");let t=await im(vr.resolve(e.projectRoot)),r=G(e.manifest),n=e.release.release,i=e.packageSource?.topology,a=i?.transactionRoot??t,o=k=>i?.mode==="pnpm-shared-lockfile"?`${i.unitRelativeRoot}/${k}`:k;if(n.kind!=="engineering-feature"||n.consumerProfile!=="any-project")throw new ae("CAPABILITY_KIND_UNSUPPORTED","Only an addable engineering feature can use this lifecycle");if(r.capabilities.some(k=>k.capabilityId===n.capabilityId))throw new ae("CAPABILITY_ALREADY_SELECTED","The capability is already selected by this project");let s=r.profile?.id,c=s==="typescript-library"?"blank-typescript-library":s,d=n.dependencies?.profiles??[],l=e.currentLock.capabilities.find(k=>k.consumerProfile===c);if(c===void 0||!d.includes(c)||l===void 0)throw new ae("CAPABILITY_DEPENDENCY_UNSATISFIED","The project profile does not satisfy this capability dependency");if((n.dependencies?.capabilities??[]).some(k=>!r.capabilities.some(S=>S.capabilityId===k)||!e.currentLock.capabilities.some(S=>S.capabilityId===k)))throw new ae("CAPABILITY_DEPENDENCY_UNSATISFIED","A required project capability is not adopted and verified");let m=G({...r,capabilities:[...r.capabilities,{capabilityId:n.capabilityId,version:n.version}]}),u=o("project-capabilities.json"),f=Buffer.from(`${JSON.stringify(m,null,2)}
|
|
45
|
+
`),g=await ci(a,u);if(!g.exists||g.digest===void 0)throw new ae("CAPABILITY_DEPENDENCY_UNSATISFIED","The project manifest is unavailable");let h=[{path:u,kind:"replace",ownership:"owned-file",baseDigest:g.digest,desiredDigest:v(f)}],w=new Map([[u,f]]),_;if(n.schemaVersion===2&&n.packageSources.length>0){if(e.packageSource===void 0)throw new ae("CAPABILITY_RELEASE_VERSION_UNSUPPORTED","Capability Release v2 requires verified package source facts");let k;try{k=await si(vr.join(t,"package.json"))}catch{throw new ae("CAPABILITY_PACKAGE_SOURCE_INVALID","\u9879\u76EE package.json \u4E0D\u53EF\u7528\uFF0C\u65E0\u6CD5\u751F\u6210\u5305\u91C7\u7528\u8BA1\u5212")}try{let S=e.packageSource.currentLockfile??await si(vr.join(t,"pnpm-lock.yaml")).catch(ne=>ne.code==="ENOENT"?void 0:Promise.reject(ne)),O=e.packageSource.topology??{schemaVersion:1,mode:"standalone",transactionRoot:t,unitRoot:t,unitRelativeRoot:".",unitImporterId:".",lockfilePath:"pnpm-lock.yaml"},se=O.mode==="pnpm-shared-lockfile",$={mode:O.mode,unitRelativeRoot:O.unitRelativeRoot,unitImporterId:O.unitImporterId,lockfilePath:O.lockfilePath,...O.workspaceManifestPath?{workspaceManifestPath:O.workspaceManifestPath,workspaceManifestDigest:O.workspaceManifestDigest}:{}},P={registryConfigs:e.packageSource.registryConfigs,endpointBindings:e.packageSource.endpointBindings,receipts:e.packageSource.receipts,inspections:e.packageSource.inspections};if(se&&(!e.packageSource.resolutionEvidence||!e.packageSource.resolutionWorkerReleaseId))throw new Z("PACKAGE_SOURCE_POLICY_VIOLATION");let H=se?(e.packageChannel==="development"?$a:ja)({release:n,...P,consumerProfile:c,packageJson:k,currentLockfile:S,generatedAt:e.generatedAt,expiresAt:e.expiresAt,topology:$,preservedImporterDigests:e.packageSource.preservedImporterDigests??[],resolutionEvidence:e.packageSource.resolutionEvidence,resolutionWorkerReleaseId:e.packageSource.resolutionWorkerReleaseId}):(e.packageChannel==="development"?Sa:Da)({release:n,...P,lockResolution:e.packageSource.lockResolution,consumerProfile:c,packageJson:k,...S===void 0?{}:{currentLockfile:S},generatedAt:e.generatedAt,expiresAt:e.expiresAt});_=Ra(H),h.push({path:o("package.json"),kind:"replace",ownership:"owned-file",baseDigest:H.packageJsonPreimageDigest,desiredDigest:H.desiredPackageJsonDigest}),w.set(o("package.json"),H.desiredPackageJson),h.push({path:O.lockfilePath,kind:S===void 0?"create":"replace",ownership:"owned-file",...S===void 0?{}:{baseDigest:v(S)},desiredDigest:H.desiredLockfileDigest}),w.set(O.lockfilePath,H.desiredLockfile)}catch(S){throw S instanceof Z?new ae("CAPABILITY_PACKAGE_SOURCE_INVALID",S.code):S}}for(let k of n.assets){let S=e.release.contents.get(k.path);if(S===void 0)throw new ae("CAPABILITY_KIND_UNSUPPORTED","Capability asset content is unavailable");let O=k.renderer==="application-config-contract-v1"?Ca(r):k.renderer==="application-config-binding-v1"?La(r):S;if(k.ownership==="managed-region"){if(k.regionId===void 0)throw new ae("CAPABILITY_KIND_UNSUPPORTED","Managed region identity is unavailable");let se;try{se=await si(vr.join(t,...k.path.split("/")))}catch{throw new ae("CAPABILITY_DEPENDENCY_UNSATISFIED","The managed shared file is unavailable")}let $=Buffer.from(Iu({source:se.toString("utf8"),regionId:k.regionId,content:Buffer.from(O).toString("utf8")}));h.push({path:o(k.path),kind:"merge",ownership:"managed-region",regionId:k.regionId,baseDigest:v(se),desiredDigest:v($)}),w.set(o(k.path),$)}else{let se=await ci(t,k.path);if(k.ownership==="seed-file"&&se.exists){let $=await si(vr.join(t,...k.path.split("/")));h.push({path:o(k.path),kind:"create",ownership:"seed-file",desiredDigest:v($)}),w.set(o(k.path),$)}else h.push({path:o(k.path),kind:"create",ownership:k.ownership,desiredDigest:v(O)}),w.set(o(k.path),O)}}let b=await Promise.all(h.map(k=>ci(a,k.path))),A={schemaVersion:1,capabilityId:n.capabilityId,version:n.version,integrity:n.integrity,assets:h.filter(k=>k.path!==u&&k.path!==i?.lockfilePath).map(k=>({path:i?.mode==="pnpm-shared-lockfile"?k.path.slice(i.unitRelativeRoot.length+1):k.path,ownership:k.ownership,desiredDigest:k.desiredDigest})),verifiers:n.verifiers.map(k=>({id:k.id,kind:"file-digest"}))};return{plan:De({action:"adopt",capability:A,changes:h,observedAssets:b,generatedAt:e.generatedAt,expiresAt:e.expiresAt,..._===void 0?{}:{packageAdoption:_}}),manifest:m,desiredContents:w,transactionRoot:a,dependency:{profile:c,satisfied:!0}}}var om=br(nr(),1);var _E={$id:"https://schemas.dyyto.dev/platform/solution-catalog-entry-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","solutionId","version","integrity","title","summary","maturity","members","integration","exit"],properties:{schemaVersion:{const:1},solutionId:{type:"string",pattern:X},version:{type:"string",minLength:1,maxLength:128},integrity:{type:"string",pattern:ut},title:{type:"string",minLength:1,maxLength:80},summary:{type:"string",minLength:1,maxLength:240},maturity:{enum:["guided","automated"]},members:{type:"array",minItems:1,maxItems:32,items:{type:"object",additionalProperties:!1,required:["capabilityId","version","role","required"],properties:{capabilityId:{type:"string",pattern:X},version:{type:"string",minLength:1,maxLength:128},role:{type:"string",minLength:1,maxLength:80},required:{type:"boolean"}}}},integration:{type:"object",additionalProperties:!1,required:["prerequisites","steps","verification","result"],properties:{prerequisites:{type:"array",minItems:1,maxItems:16,items:{type:"string",minLength:1,maxLength:200}},steps:{type:"array",minItems:1,maxItems:32,items:{type:"object",additionalProperties:!1,required:["label","command"],properties:{label:{type:"string",minLength:1,maxLength:80},command:{type:"string",minLength:1,maxLength:2e3}}}},verification:{type:"array",minItems:1,maxItems:32,items:{type:"string",minLength:1,maxLength:1e3}},result:{type:"string",minLength:1,maxLength:400}}},exit:{type:"object",additionalProperties:!1,required:["summary"],properties:{summary:{type:"string",minLength:1,maxLength:400}}}}},cD=new om.Ajv2020({allErrors:!0,strict:!0}).compile(_E);var pm=br(nr(),1);import{readFile as EE,realpath as AE}from"node:fs/promises";import sm from"node:path";var cm="^[a-z0-9]+(?:[.-][a-z0-9]+)*$",lm="^(?!/)(?!.*(?:^|/)\\.\\.(?:/|$))(?!.*\\\\)[^\\u0000]+$",RE={$id:"https://schemas.dyyto.dev/platform/example-recipe-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","recipeId","version","integrity","title","locale","rootProfile","capabilities","expectedEntrypoint","verifiers","manualAcceptance","cleanup"],properties:{schemaVersion:{const:1},recipeId:{type:"string",pattern:cm},version:{type:"string",minLength:1,maxLength:128},integrity:{type:"string",pattern:ut},title:{type:"string",minLength:1,maxLength:80},locale:{const:"zh-CN"},rootProfile:{type:"object",additionalProperties:!1,required:["capabilityId","version"],properties:{capabilityId:{type:"string",pattern:X},version:{type:"string",minLength:1,maxLength:128}}},capabilities:{type:"array",minItems:1,maxItems:16,items:{type:"object",additionalProperties:!1,required:["capabilityId","version","channel"],properties:{capabilityId:{type:"string",pattern:X},version:{type:"string",minLength:1,maxLength:128},channel:{const:"development"}}}},expectedEntrypoint:{type:"string",pattern:lm,maxLength:240},verifiers:{type:"array",minItems:1,maxItems:16,uniqueItems:!0,items:{type:"string",pattern:cm}},manualAcceptance:{type:"array",minItems:1,maxItems:32,items:{type:"string",minLength:1,maxLength:240}},cleanup:{type:"object",additionalProperties:!1,required:["ownedStateDirectories"],properties:{ownedStateDirectories:{type:"array",maxItems:8,uniqueItems:!0,items:{type:"string",pattern:lm,maxLength:240}}}}}},dm=new pm.Ajv2020({allErrors:!0,strict:!0}).compile(RE),Ir=class extends Error{code;issues;constructor(t,r=[]){super(t),this.code=t,this.issues=r}};function PE(e){return v(E(e))}function NE(e){if(!dm(e))throw new Ir("EXAMPLE_RECIPE_INVALID",dm.errors??[]);let t=e,r=[t.rootProfile.capabilityId,...t.capabilities.map(n=>n.capabilityId)];if(new Set(r).size!==r.length||t.capabilities.some(n=>n.version.includes("workspace:")||n.capabilityId.includes("ai-education-poc")))throw new Ir("EXAMPLE_RECIPE_INVALID");return t}async function um(e){let t=await AE(sm.resolve(e)),r;try{r=NE(JSON.parse(await EE(sm.join(t,"recipe.json"),"utf8")))}catch(a){throw a instanceof Ir?a:new Ir("EXAMPLE_RECIPE_INVALID")}let{integrity:n,...i}=r;if(PE(i)!==n)throw new Ir("EXAMPLE_RECIPE_INTEGRITY_MISMATCH");return r}var gm=br(nr(),1);import{readFile as DE,realpath as SE}from"node:fs/promises";import fm from"node:path";var jE={$id:"https://schemas.dyyto.dev/platform/engineering-template-release-v1.json",type:"object",additionalProperties:!1,required:["schemaVersion","templateId","version","integrity","title","summary","status","profile","parameters","commands","technology","support","integration","metrics"],properties:{schemaVersion:{const:1},templateId:{type:"string",pattern:X},version:{type:"string",minLength:1,maxLength:128},integrity:{type:"string",pattern:ut},title:{type:"string",minLength:1,maxLength:80},summary:{type:"string",minLength:1,maxLength:240},status:{enum:["candidate","recommended","deprecated"]},profile:{type:"object",additionalProperties:!1,required:["id","capability"],properties:{id:{type:"string",pattern:X},capability:{type:"string",pattern:`${X.slice(1,-1)}@[0-9]+\\.[0-9]+\\.[0-9]+$`}}},parameters:{type:"array",minItems:0,maxItems:32,items:{type:"object",additionalProperties:!1,required:["id","required","description"],properties:{id:{type:"string",pattern:"^[a-z][A-Za-z0-9]*$"},required:{type:"boolean"},description:{type:"string",minLength:1,maxLength:160}}}},commands:{type:"object",minProperties:1,additionalProperties:!1,properties:{dev:{type:"string",pattern:"^[a-z][a-z0-9.:-]*$"},build:{type:"string",pattern:"^[a-z][a-z0-9.:-]*$"},test:{type:"string",pattern:"^[a-z][a-z0-9.:-]*$"},package:{type:"string",pattern:"^[a-z][a-z0-9.:-]*$"}}},technology:{type:"array",minItems:1,maxItems:32,items:{type:"object",additionalProperties:!1,required:["id","version","policy","verifiedAt","rationale","alternative","exit"],properties:{id:{type:"string",pattern:X},version:{type:"string",minLength:1,maxLength:64},policy:{enum:["recommended","allowed"]},verifiedAt:{type:"string",format:"date"},rationale:{type:"string",minLength:1,maxLength:240},alternative:{type:"string",minLength:1,maxLength:160},exit:{type:"string",minLength:1,maxLength:240}}}},support:{type:"object",additionalProperties:!1,required:["owner","tier","supportedFrom","supportedUntil","upgradeCadence","eolNoticeDays"],properties:{owner:{type:"string",pattern:X},tier:{const:"production"},supportedFrom:{type:"string",format:"date"},supportedUntil:{type:"string",format:"date"},upgradeCadence:{type:"string",minLength:1,maxLength:80},eolNoticeDays:{type:"integer",minimum:30,maximum:730}}},integration:{type:"object",additionalProperties:!1,required:["prerequisites","createCommand","result"],properties:{prerequisites:{type:"array",minItems:1,maxItems:16,items:{type:"string",minLength:1,maxLength:200}},createCommand:{type:"string",minLength:1,maxLength:2e3},result:{type:"string",minLength:1,maxLength:400}}},metrics:{type:"array",minItems:1,uniqueItems:!0,items:{enum:["time-to-green-build","time-to-first-business-commit","manual-engineering-edits","upgrade-conflicts"]}}}},mm=new gm.Ajv2020({allErrors:!0,strict:!0,formats:{date:/^\d{4}-\d{2}-\d{2}$/}}).compile(jE),Rt=class extends Error{code;issues;constructor(t,r=[]){super(t),this.code=t,this.issues=r}};function $E(e){return v(E(e))}function OE(e){if(!mm(e))throw new Rt("TEMPLATE_INVALID",mm.errors??[]);let t=e;if(new Set(t.parameters.map(r=>r.id)).size!==t.parameters.length||new Set(t.technology.map(r=>r.id)).size!==t.technology.length)throw new Rt("TEMPLATE_INVALID");if(Date.parse(t.support.supportedUntil)<=Date.parse(t.support.supportedFrom))throw new Rt("TEMPLATE_INVALID");return t}async function li(e,t=new Date){let r=await SE(fm.resolve(e)),n;try{n=OE(JSON.parse(await DE(fm.join(r,"template.json"),"utf8")))}catch(o){throw o instanceof Rt?o:new Rt("TEMPLATE_INVALID")}let{integrity:i,...a}=n;if($E(a)!==i)throw new Rt("TEMPLATE_INTEGRITY_MISMATCH");if(n.status==="recommended"&&Date.parse(n.support.supportedUntil)<t.getTime())throw new Rt("TEMPLATE_SUPPORT_EXPIRED");return n}import{readFile as hm}from"node:fs/promises";import ym from"node:path";var CE=/^[A-Z][A-Z0-9_]*$/u,TE=/(?:API_KEY|ACCESS_KEY|SECRET|TOKEN|PASSWORD|PRIVATE_KEY|DATABASE_URL|POSTGRES_URL)$/u;function xE(e){let t=new Map;for(let r of e.split(/\r?\n/u)){let n=/^([A-Z][A-Z0-9_]*)=(.*)$/u.exec(r.trim());if(!n||!CE.test(n[1]))continue;let i=n[1],a=n[2].trim();t.set(i,{name:i,requirement:a.length===0?"conditional":"optional",secret:TE.test(i),configured:!1,source:".env.example",configuredSource:null})}return[...t.values()]}async function wm(e){let t=await hm(ym.join(e.projectRoot,".env.example"),"utf8").then(()=>".env.example").catch(()=>null),r=t?await hm(ym.join(e.projectRoot,t),"utf8"):"",n=await Qn({projectRoot:e.projectRoot}).catch(()=>null);return{commands:["dev","build","test","package"].flatMap(a=>e.commands[a]?[{id:a,script:e.commands[a],mode:a==="dev"?"managed-process":"foreground-task"}]:[]),environment:n?n.entries.map(a=>({name:a.name,...a.runtimeEnvironmentVariable?{runtimeEnvironmentVariable:a.runtimeEnvironmentVariable}:{},requirement:a.required?"conditional":"optional",kind:a.kind,secret:a.kind!=="value",configured:a.configured,source:"application-config-contract",configuredSource:"APP_CONFIG_DIR",display:a.display,...a.fingerprint?{fingerprint:a.fingerprint}:{}})):xE(r),environmentExample:t,productionValidation:{contract:!0,live:["provider-read","oss-write-read-delete"]}}}var vm={change:new Set(["plan","apply","upgrade","recover","baseline-next","add-package","add-application","add-feature"]),quality:new Set(["inspect","verify","doctor","maintenance","test","build"]),delivery:new Set(["package","delivery-plan","delivery-apply","delivery-inspect"])},Im=new Set(["queued","running","succeeded","failed","outcome-unknown","cancelled"]);function bm(e,t){if(!vm[t.plane]||t.state&&!Im.has(t.state)||t.limit!==void 0&&(!Number.isSafeInteger(t.limit)||t.limit<1||t.limit>200))throw new Error("OPERATION_FILTER_INVALID");let r=vm[t.plane],n=t.from?Date.parse(t.from):null,i=t.to?Date.parse(t.to):null;if(n!==null&&Number.isNaN(n)||i!==null&&Number.isNaN(i)||n!==null&&i!==null&&n>i)throw new Error("OPERATION_FILTER_INVALID");let a=e.filter(d=>r.has(d.operation)),o=[...new Map(a.map(d=>[d.projectId,{id:d.projectId,name:d.projectName}])).values()].sort((d,l)=>d.name.localeCompare(l.name)),s=a.filter(d=>(!t.projectId||d.projectId===t.projectId)&&(!t.state||d.state===t.state)&&(!t.kind||d.operation===t.kind)&&(n===null||Date.parse(d.createdAt)>=n)&&(i===null||Date.parse(d.createdAt)<=i)).sort((d,l)=>l.updatedAt.localeCompare(d.updatedAt)),c={total:s.length,running:s.filter(d=>d.state==="running"||d.state==="queued").length,succeeded:s.filter(d=>d.state==="succeeded").length,attention:s.filter(d=>d.state==="failed"||d.state==="outcome-unknown").length};return Object.freeze({schemaVersion:1,plane:t.plane,summary:Object.freeze(c),facets:Object.freeze({projects:Object.freeze(o),states:Object.freeze([...Im]),kinds:Object.freeze([...r])}),items:Object.freeze(s.slice(0,t.limit??50).map(Object.freeze)),hasMore:s.length>(t.limit??50)})}var di=class extends Error{code;constructor(t,r){super(r),this.code=t}},nl=/^sha256:[a-f0-9]{64}$/u,LE=/^sha512-[A-Za-z0-9+/]{86}==$/u,VE=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u,ME=/^(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)(?:-[0-9A-Za-z.-]+)?$/u,qE=/[\u0000-\u001f\u007f]/u;function Xr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype}function Qr(e,t){let r=Object.keys(e).sort(),n=[...t].sort();return r.length===n.length&&r.every((i,a)=>i===n[a])}function Pt(e,t=500){return typeof e=="string"&&e.length>0&&e.length<=t&&!qE.test(e)}function rl(e){return Pt(e,500)&&!e.startsWith("/")&&!e.startsWith("../")&&!e.includes("/../")&&!e.includes("\\")}function km(e,t=128){return Array.isArray(e)&&e.length<=t&&e.every(r=>Pt(r,500))&&e.every((r,n)=>n===0||e[n-1]<r)}function UE(e){return e===null?!0:!Xr(e)||!Qr(e,["fileName","digest","integrity","fileCount","unpackedBytes"])?!1:rl(e.fileName)&&nl.test(String(e.digest))&&LE.test(String(e.integrity))&&Number.isSafeInteger(e.fileCount)&&Number(e.fileCount)>0&&Number.isSafeInteger(e.unpackedBytes)&&Number(e.unpackedBytes)>0}function FE(e){if(!Xr(e)||!Qr(e,["schemaVersion","kind","packageName","version","title","summary","maturity","source","artifact","compatibility","exports","documentation","consumerEvidence"])||e.schemaVersion!==1||e.kind!=="PackageRelease"||!VE.test(e.packageName)||!ME.test(e.version)||!Pt(e.title,120)||!Pt(e.summary,1e3)||!["candidate","stable","deprecated"].includes(e.maturity)||!Xr(e.source)||!Qr(e.source,["repository","path","revision","treeDigest"])||!Pt(e.source.repository)||!rl(e.source.path)||!Pt(e.source.revision,200)||!nl.test(String(e.source.treeDigest))||!UE(e.artifact)||!Xr(e.compatibility)||!Qr(e.compatibility,["node","packageManager"])||!Pt(e.compatibility.node,100)||!Pt(e.compatibility.packageManager,100)||!km(e.exports)||!km(e.consumerEvidence)||!Xr(e.documentation))return!1;let t=e.documentation.knowledgeRef===void 0?["readme"]:["readme","knowledgeRef"];return!Qr(e.documentation,t)||!rl(e.documentation.readme)||e.documentation.knowledgeRef!==void 0&&!Pt(e.documentation.knowledgeRef,500)?!1:e.artifact!==null||e.maturity!=="stable"}function zE(e){let t={schemaVersion:1,kind:"PackageRelease",...e,source:Object.freeze({...e.source}),artifact:e.artifact===null?null:Object.freeze({...e.artifact}),compatibility:Object.freeze({...e.compatibility}),exports:Object.freeze([...e.exports]),documentation:Object.freeze({...e.documentation}),consumerEvidence:Object.freeze([...e.consumerEvidence])};if(!FE(t))throw new di("PACKAGE_RELEASE_INVALID","PackageRelease \u5185\u5BB9\u65E0\u6548");return Object.freeze({...t,releaseDigest:v(E(t))})}function _m(e){if(!Xr(e)||!Qr(e,["schemaVersion","kind","packageName","version","title","summary","maturity","source","artifact","compatibility","exports","documentation","consumerEvidence","releaseDigest"])||!nl.test(String(e.releaseDigest)))throw new di("PACKAGE_RELEASE_INVALID","PackageRelease \u7ED3\u6784\u65E0\u6548");let{releaseDigest:t,schemaVersion:r,kind:n,...i}=e,a=zE(i);if(a.releaseDigest!==t)throw new di("PACKAGE_RELEASE_MODIFIED","PackageRelease \u5DF2\u88AB\u4FEE\u6539");return a}import{lstat as BE,readFile as GE,realpath as JE}from"node:fs/promises";import Em from"node:path";async function Am(e){let t=await JE(Em.resolve(e.projectRoot)),r=new Set(e.excludeCapabilityIds??[]),n=new Map,i=[...e.lock.capabilities].sort((o,s)=>o.committedAt.localeCompare(s.committedAt)||o.capabilityId.localeCompare(s.capabilityId));for(let o of i)if(!r.has(o.capabilityId))for(let s of o.assets){let c=s.ownership??"owned-file",d=`${s.path}\0`;if(c==="managed-region")n.delete(d);else for(let p of n.keys())p.startsWith(d)&&n.delete(p);let l=c==="managed-region"?`${d}${s.regionId??""}`:d;n.set(l,{capabilityId:o.capabilityId,path:s.path,digest:s.digest,ownership:c,...s.regionId===void 0?{}:{regionId:s.regionId}})}let a=[];for(let o of[...n.values()].sort((s,c)=>s.path.localeCompare(c.path)||(s.regionId??"").localeCompare(c.regionId??"")||s.capabilityId.localeCompare(c.capabilityId))){let s=Em.join(t,...o.path.split("/")),d=await BE(s).then(async l=>{if(!l.isFile()||l.isSymbolicLink())return;let p=await GE(s);if(o.ownership!=="managed-region")return v(p);if(o.regionId!==void 0)try{return v(ea(p.toString("utf8"),o.regionId))}catch{return}}).catch(l=>l.code==="ENOENT"?void 0:Promise.reject(l))===o.digest;a.push({capabilityId:o.capabilityId,path:o.path,kind:"create",ownership:o.ownership,...o.regionId===void 0?{}:{regionId:o.regionId},desiredDigest:o.digest,disposition:d?"noop":"conflict",...d?{}:{conflictCode:"BASE_DIGEST_MISMATCH"}})}return a}var il="0.1.40",pi={DEPENDENCIES_NOT_INSTALLED:4,VERIFIER_RUNTIME_INVALID:4},WE=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/u;function Rm(e,t){return typeof e=="string"&&e.length>0&&e.length<=t&&!WE.test(e)}function KE(e){let t={schemaVersion:1,kind:"dyyto-cli-domain-error",code:e.code,message:e.message,exitCode:pi[e.code],...e.nextStep===void 0?{}:{nextStep:e.nextStep}},r=YE(t);if(r===null)throw new TypeError("CLI domain error input is invalid");return r}function YE(e){try{if(typeof e!="object"||e===null||Object.getPrototypeOf(e)!==Object.prototype)return null;let t=Object.getOwnPropertyDescriptors(e);if(Reflect.ownKeys(t).some(s=>typeof s=="symbol"))return null;let r=Object.keys(t).sort(),n="nextStep"in t?["code","exitCode","kind","message","nextStep","schemaVersion"]:["code","exitCode","kind","message","schemaVersion"];if(r.length!==n.length||r.some((s,c)=>s!==n[c])||Object.values(t).some(s=>!("value"in s)))return null;let i=s=>t[s]?.value,a=i("code");if(i("schemaVersion")!==1||i("kind")!=="dyyto-cli-domain-error"||typeof a!="string"||!(a in pi)||i("exitCode")!==pi[a]||!Rm(i("message"),500))return null;let o=i("nextStep");return o!==void 0&&!Rm(o,500)?null:Object.freeze({schemaVersion:1,kind:"dyyto-cli-domain-error",code:a,message:i("message"),exitCode:4,...o===void 0?{}:{nextStep:o}})}catch{return null}}var xe=class extends Error{code;exitCode;nextStep;domainError;constructor(t){super(t.message),this.name="CliError",this.code=t.code,this.exitCode=t.exitCode,this.nextStep=t.nextStep,this.domainError=t.code in pi&&t.exitCode===pi[t.code]?KE({code:t.code,message:t.message,...t.nextStep===void 0?{}:{nextStep:t.nextStep}}):void 0}};var Pm=`Dyyto Engineering Platform CLI
|
|
46
46
|
|
|
47
47
|
Usage:
|
|
48
48
|
dyyto <command> [options]
|
|
@@ -52,6 +52,9 @@ Commands:
|
|
|
52
52
|
dyyto context resolve --project DIR \u89E3\u6790\u5F53\u524D\u5206\u652F\u7684\u5185\u5BB9\u5BFB\u5740\u5DE5\u7A0B\u4E0A\u4E0B\u6587
|
|
53
53
|
dyyto ready --project DIR \u68C0\u67E5\u4E0A\u4E0B\u6587\u3001\u914D\u7F6E\u4E0E\u5DE5\u7A0B\u5F00\u53D1\u5C31\u7EEA\u72B6\u6001
|
|
54
54
|
dyyto dev session start|show|finish \u7BA1\u7406\u76F4\u63A5\u5F00\u53D1\u4E0E\u9700\u6C42\u4EFB\u52A1\u5171\u7528\u7684\u5F00\u53D1 Session
|
|
55
|
+
dyyto dev specify --input FILE \u751F\u6210\u5E76\u5E94\u7528 Spec\u3001Plan \u4E0E TaskSet
|
|
56
|
+
dyyto dev knowledge release \u53D1\u5E03\u5F53\u524D revision \u7684\u9886\u57DF\u4E0E\u4EA7\u54C1\u77E5\u8BC6
|
|
57
|
+
dyyto dev verify \u9A8C\u8BC1 Session\u3001\u89C4\u683C\u3001\u77E5\u8BC6\u4E0E Agent \u4E0A\u4E0B\u6587
|
|
55
58
|
dyyto agents sync --project DIR [--apply] \u540C\u6B65\u591A\u7F16\u7801Agent\u9002\u914D\u5668
|
|
56
59
|
dyyto agents remove --project DIR [--apply] \u5B89\u5168\u79FB\u9664\u53D7\u7BA1Agent\u9002\u914D\u5668
|
|
57
60
|
dyyto docs show --id ID \u8BFB\u53D6npm\u5305\u5185\u7A33\u5B9A\u6587\u6863
|
|
@@ -102,86 +105,86 @@ Options:
|
|
|
102
105
|
--json Emit one machine-readable JSON object
|
|
103
106
|
--help Show help
|
|
104
107
|
--version Show version
|
|
105
|
-
`;import{lstat as
|
|
108
|
+
`;import{lstat as US,readFile as HE,readdir as ZE}from"node:fs/promises";import Dm from"node:path";var Nm={"workspace-node-application":"foundation.workspace-node-application@1.1.0","workspace-web-application":"foundation.workspace-web-application@1.1.0","workspace-expo-application":"foundation.workspace-expo-application@1.0.0","nextjs-full-stack-application":"foundation.nextjs-full-stack-application@1.0.0"};function Sm(e,t="package"){let r=t==="fixture"?"fixtures":"packages";return new RegExp(`^${r}/[a-z0-9][a-z0-9._-]*$`).test(e)?void 0:`Package path must be exactly ${r}/<lowercase-slug>.`}function jm(e,t,r){if(!(t in Nm))return"Add application requires a supported --profile.";let n=Nm[t];if(r!==n)return`Add application with profile ${t} requires --capability ${n}.`;if(!/^apps\/[a-z0-9][a-z0-9._-]*$/.test(e))return/^services\/[a-z0-9][a-z0-9._-]*$/.test(e)?t==="workspace-node-application"?void 0:"Service applications require profile workspace-node-application.":"Application path must be exactly apps/<lowercase-slug> or services/<lowercase-slug>."}async function Ka(e,t,r){for(let n of await ZE(Dm.join(e,t),{withFileTypes:!0}).catch(()=>[]))if(!(!n.isDirectory()||n.isSymbolicLink()))try{if(JSON.parse(await HE(Dm.join(e,t,n.name,"project-capabilities.json"),"utf8")).profile?.parameters?.name===r)return!0}catch(i){if(i.code!=="ENOENT")throw i}return!1}async function $m(e,t){return await Ka(e,"apps",t)||await Ka(e,"services",t)}import{lstat as Om,mkdir as ol,readFile as Cm,realpath as al,rm as XE,writeFile as Tm}from"node:fs/promises";import Fe from"node:path";var ze=class extends Error{constructor(r,n){super(r,n===void 0?void 0:{cause:n});this.code=r}code},QE=e=>E(e),xm=e=>v(QE(e));async function Lm(e,t){let r=await al(Fe.resolve(e)),n=Fe.join(r,".examples");await ol(n,{recursive:!0});let i=await al(n),a=Fe.resolve(r,t);if(Fe.dirname(a)!==i||Fe.basename(a).startsWith(".")||Fe.basename(a).length<1)throw new ze("SCAFFOLD_ARGUMENT_INVALID");if(await Om(a).then(()=>!0).catch(o=>o.code==="ENOENT"?!1:Promise.reject(o)))throw new ze("SCAFFOLD_TARGET_CONFLICT");return{workspaceRoot:r,output:a,outputRelativePath:Fe.relative(r,a)}}async function Vm(e){let t=e.artifactFallbackBundles??[];if(!/^sha256:[a-f0-9]{64}$/u.test(e.artifactBundle)||t.some(c=>!/^sha256:[a-f0-9]{64}$/u.test(c))||new Set([e.artifactBundle,...t]).size!==1+t.length||!Number.isSafeInteger(e.artifactPort)||e.artifactPort<1||e.artifactPort>65535)throw new ze("SCAFFOLD_ARGUMENT_INVALID");let r=await Lm(e.workspaceRoot,e.output),n=e.now??new Date().toISOString(),i={schemaVersion:1,state:"reviewable",recipeId:e.recipe.recipeId,recipeVersion:e.recipe.version,recipeIntegrity:e.recipe.integrity,workspaceRoot:r.workspaceRoot,outputRelativePath:r.outputRelativePath,locale:e.recipe.locale,channel:"development",artifactBundle:e.artifactBundle,artifactFallbackBundles:t,artifactPort:e.artifactPort,generatedAt:n,expiresAt:new Date(Date.parse(n)+30*6e4).toISOString()},a={...i,planId:xm(i)},o=Fe.join(r.workspaceRoot,".dyyto","scaffold-plans");await ol(o,{recursive:!0});let s=Fe.join(o,`${a.planId}.json`);return await Tm(s,`${E(a)}
|
|
106
109
|
`,{flag:"wx",mode:384}).catch(async c=>{if(c.code!=="EEXIST"||await Cm(s,"utf8")!==`${E(a)}
|
|
107
|
-
`)throw new ze("SCAFFOLD_PLAN_INVALID")}),a}async function
|
|
108
|
-
`,{flag:"wx",mode:384}),{evidenceId:a,output:r.output,receipts:n}}import{lstat as ui,readFile as ol,readdir as eA,realpath as sl}from"node:fs/promises";import pe from"node:path";var qm={capabilities:pe.resolve(import.meta.dirname,"catalog"),packages:pe.resolve(import.meta.dirname,"package-releases")};function tA(e){let t=new Map;for(let[r,n]of e.split(/\r?\n/u).entries()){let i=n.trim();if(i===""||i.startsWith("#"))continue;if(i.startsWith("export "))throw new Error(`Dyyto \u7EC4\u4EF6 .env:${r+1} \u4E0D\u5141\u8BB8\u4F7F\u7528 export`);let a=/^([A-Z][A-Z0-9_]*)=(.*)$/u.exec(i);if(!a)throw new Error(`Dyyto \u7EC4\u4EF6 .env:${r+1} \u4E0D\u662F\u4E25\u683C KEY=VALUE \u683C\u5F0F`);if(t.has(a[1]))throw new Error(`Dyyto \u7EC4\u4EF6 .env:${r+1} \u5305\u542B\u91CD\u590D\u53D8\u91CF ${a[1]}`);let o=a[2].trim();if((o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'"))&&(o=o.slice(1,-1)),/[`$][({]?/u.test(o))throw new Error(`Dyyto \u7EC4\u4EF6 .env:${r+1} \u4E0D\u5141\u8BB8\u547D\u4EE4\u6216\u53D8\u91CF\u5C55\u5F00`);t.set(a[1],o)}return t}async function Um(e,t){let r=await ui(e);if(!r.isFile()||r.isSymbolicLink()||r.nlink!==1)throw new Error(`${t}\u5FC5\u987B\u662F\u666E\u901A\u975E\u94FE\u63A5\u6587\u4EF6`);if(typeof process.getuid=="function"&&r.uid!==process.getuid())throw new Error(`${t}\u5FC5\u987B\u7531\u5F53\u524D\u7528\u6237\u62E5\u6709`);if((r.mode&511&-385)!==0)throw new Error(`${t}\u6743\u9650\u8FC7\u5BBD\uFF0C\u6700\u5927\u5141\u8BB80600`)}async function Ya(e,t){let r=await ui(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t}\u5FC5\u987B\u662F\u666E\u901A\u76EE\u5F55\u4E14\u4E0D\u80FD\u662F\u7B26\u53F7\u94FE\u63A5`);if(typeof process.getuid=="function"&&r.uid!==process.getuid())throw new Error(`${t}\u5FC5\u987B\u7531\u5F53\u524D\u7528\u6237\u62E5\u6709`);if((r.mode&511&-449)!==0)throw new Error(`${t}\u6743\u9650\u8FC7\u5BBD\uFF0C\u6700\u5927\u5141\u8BB80700`);return sl(e)}async function rA(e){let t=e;for(;;){if(await ui(pe.join(t,".git")).then(()=>!0).catch(n=>n.code==="ENOENT"?!1:Promise.reject(n)))throw new Error(`IDP_CONFIG_DIR \u5FC5\u987B\u4F4D\u4E8E Git \u4ED3\u5E93\u5916\uFF1A${t}`);let r=pe.dirname(t);if(r===t)return;t=r}}async function nA(e){if(!pe.isAbsolute(e))throw new Error("IDP_CONFIG_DIR \u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");let t=await Ya(e,"IDP_CONFIG_DIR");await rA(t);let r=await Ya(pe.join(t,"components"),"components"),n=await Ya(pe.join(r,"dyyto"),"Dyyto \u914D\u7F6E\u76EE\u5F55"),i=pe.relative(t,n);if(i.startsWith("..")||pe.isAbsolute(i))throw new Error("Dyyto \u914D\u7F6E\u76EE\u5F55\u8D8A\u8FC7 IDP_CONFIG_DIR");let a=pe.join(n,".env");await Um(a,"Dyyto \u7EC4\u4EF6 .env");let o=tA(await ol(a,"utf8")).get("DYYTO_PACKAGE_CATALOG_DIRS_FILE");if(o===void 0||o==="")return[];if(pe.isAbsolute(o)||o.includes("\0")||/[*?{}[\]]/u.test(o))throw new Error("DYYTO_PACKAGE_CATALOG_DIRS_FILE \u5FC5\u987B\u662F\u7EC4\u4EF6\u76EE\u5F55\u5185\u7684\u666E\u901A\u76F8\u5BF9\u6587\u4EF6\u8DEF\u5F84");let s=pe.resolve(n,o),c=pe.relative(n,s);if(c===""||c.startsWith("..")||pe.isAbsolute(c))throw new Error("DYYTO_PACKAGE_CATALOG_DIRS_FILE \u5FC5\u987B\u4F4D\u4E8E\u7EC4\u4EF6\u914D\u7F6E\u76EE\u5F55\u5185");let d=n;for(let u of c.split(pe.sep).slice(0,-1))d=await Ya(pe.join(d,u),"Package Catalog Binding \u7236\u76EE\u5F55");let l=await sl(pe.dirname(s)),p=pe.relative(n,l);if(p.startsWith("..")||pe.isAbsolute(p))throw new Error("Package Catalog Binding \u89E3\u6790\u540E\u8D8A\u8FC7\u7EC4\u4EF6\u914D\u7F6E\u76EE\u5F55");await Um(s,"Package Catalog Binding");let m=[];for(let u of(await ol(s,"utf8")).split(/\r?\n/u)){let f=u.trim();if(f===""||f.startsWith("#"))continue;if(!pe.isAbsolute(f))throw new Error("Package Catalog Binding \u4E2D\u7684\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");let g=await ui(f);if(!g.isDirectory()||g.isSymbolicLink())throw new Error("Package Catalog Binding \u5FC5\u987B\u6307\u5411\u666E\u901A\u76EE\u5F55");let h=await sl(f),w=await ui(h);if(!w.isDirectory()||w.isSymbolicLink())throw new Error("Package Catalog Binding \u5FC5\u987B\u6307\u5411\u666E\u901A\u76EE\u5F55");m.includes(h)||m.push(h)}return m.sort()}async function iA(){let e=process.env.IDP_CONFIG_DIR,t=e===void 0?[]:await nA(e);return{capabilities:qm.capabilities,packages:[qm.packages,...t]}}async function Ha(e){return(await eA(e,{withFileTypes:!0})).filter(t=>t.isDirectory()&&!t.isSymbolicLink()).map(t=>t.name).sort()}function aA(e,t){let r=a=>a.split("-",1)[0].split(".").map(Number),n=r(e),i=r(t);for(let a=0;a<3;a+=1){let o=(n[a]??0)-(i[a]??0);if(o!==0)return o}return e.localeCompare(t)}function oA(e){let t=e.schemaVersion===2?e.availability.maturity:"legacy-unverified",r="consumerProfile"in e?e.consumerProfile:"\u591A\u79CD\u5DE5\u7A0B Profile";return{kind:"capability",ref:`capability:${e.capabilityId}@${e.version}`,id:e.capabilityId,version:e.version,title:e.capabilityId,summary:`\u9002\u7528\u4E8E ${r} \u7684\u5DE5\u7A0B\u80FD\u529B\u53D1\u884C\u3002`,maturity:t,integrity:e.integrity}}function sA(e){return{kind:"package",ref:`package:${e.packageName}@${e.version}`,id:e.packageName,version:e.version,title:e.title,summary:e.summary,maturity:e.maturity,integrity:e.releaseDigest}}async function cA(e){let t=[];for(let r of await Ha(e))for(let n of await Ha(pe.join(e,r))){let i=`capability:${r}@${n}`;t.push(ge(pe.join(e,r,n)).then(a=>({entry:{item:oA(a.release),release:a.release}})).catch(()=>({diagnostic:{ref:i,code:"CATALOG_RELEASE_INVALID",message:"Capability \u53D1\u884C\u672A\u901A\u8FC7\u5B8C\u6574\u6027\u6821\u9A8C"}})))}return(await Promise.all(t)).reduce((r,n)=>(n.entry!==void 0&&r.entries.push(n.entry),n.diagnostic!==void 0&&r.diagnostics.push(n.diagnostic),r),{entries:[],diagnostics:[]})}async function lA(e){let t=[];for(let r of await Ha(e))for(let n of await Ha(pe.join(e,r))){let i=pe.join(e,r,n,"release.json"),a=`package:${r}@${n}`;t.push(ol(i,"utf8").then(o=>{let s=_m(JSON.parse(o));return{entry:{item:sA(s),release:s}}}).catch(()=>({diagnostic:{ref:a,code:"CATALOG_RELEASE_INVALID",message:"PackageRelease \u672A\u901A\u8FC7\u5B8C\u6574\u6027\u6821\u9A8C"}})))}return(await Promise.all(t)).reduce((r,n)=>(n.entry!==void 0&&r.entries.push(n.entry),n.diagnostic!==void 0&&r.diagnostics.push(n.diagnostic),r),{entries:[],diagnostics:[]})}async function Fm(e){let t=e??await iA(),r=typeof t.packages=="string"?[t.packages]:[...t.packages],[n,...i]=await Promise.all([cA(t.capabilities),...r.map(lA)]),a=[...n.entries,...i.flatMap(d=>d.entries)].sort((d,l)=>d.item.ref.localeCompare(l.item.ref)),o=[],s=new Set,c=[];for(let d of a)s.has(d.item.ref)?c.push({ref:d.item.ref,code:"CATALOG_RELEASE_DUPLICATE",message:"\u591A\u4E2A Catalog Source \u58F0\u660E\u4E86\u540C\u4E00\u4E0D\u53EF\u53D8\u53D1\u884C ref"}):(s.add(d.item.ref),o.push(d));return{entries:o,diagnostics:[...n.diagnostics,...i.flatMap(d=>d.diagnostics),...c].sort((d,l)=>d.ref.localeCompare(l.ref))}}async function zm(e){let t=(e.query??"").trim().toLocaleLowerCase("zh-CN"),r=await Fm(e.roots),n=new Map;for(let{item:o}of r.entries){if(e.kind!==void 0&&o.kind!==e.kind)continue;let s=[o.id,o.version,o.title,o.summary,o.maturity].join(" ").toLocaleLowerCase("zh-CN");if(t!==""&&!s.includes(t))continue;let c=`${o.kind}:${o.id}`,d=n.get(c);(d===void 0||aA(d.version,o.version)<0)&&n.set(c,o)}let i=[...n.values()].sort((o,s)=>o.ref.localeCompare(s.ref)),a=e.limit??50;return{query:t,total:i.length,items:i.slice(0,a),diagnostics:r.diagnostics}}async function Bm(e){let t=e.ref.startsWith("package:")||e.ref.startsWith("capability:")?e.ref:`${e.ref.startsWith("@")?"package":"capability"}:${e.ref}`,r=await Fm(e.roots),n=r.entries.find(({item:a})=>a.ref===t),i=r.diagnostics.find(a=>a.ref===t);if(i?.code==="CATALOG_RELEASE_DUPLICATE")throw new Error(`\u53D1\u884C ref \u5728\u591A\u4E2A Catalog Source \u4E2D\u91CD\u590D\uFF1A${e.ref}`);if(n===void 0&&i!==void 0)throw new Error(`\u53D1\u884C\u672A\u901A\u8FC7\u5B8C\u6574\u6027\u6821\u9A8C\uFF1A${e.ref}`);if(n===void 0)throw new Error(`\u76EE\u5F55\u4E2D\u4E0D\u5B58\u5728\u53D1\u884C\uFF1A${e.ref}`);return n}var fi={"typescript-library":"foundation.typescript-quality@1.0.0","standalone-npm-package":"foundation.standalone-npm-package@1.2.0","workspace-root":"foundation.workspace-root@1.1.0","workspace-npm-package":"foundation.workspace-npm-package@1.2.0","workspace-node-application":"foundation.workspace-node-application@1.1.0","workspace-web-application":"foundation.workspace-web-application@1.1.0","workspace-expo-application":"foundation.workspace-expo-application@1.0.0","react-component-library":"foundation.react-component-library@1.1.0","workspace-react-component-library":"foundation.workspace-react-component-library@1.2.0","nextjs-full-stack-application":"foundation.nextjs-full-stack-application@1.0.0"},Km=uA(dA),fA=new Set(["template.typescript-library@1.0.0","template.typescript-library@1.1.0","template.react-component-library@1.0.0","template.react-component-library@1.1.0","template.nextjs-full-stack-application@1.0.0","template.expo-react-native-application@1.0.0","template.node-api-application@1.0.0","template.workspace-root@1.0.0","template.workspace-root@1.1.0","template.workspace-root@1.2.0","template.workspace-npm-package@1.0.0","template.workspace-react-component-library@1.0.0","template.workspace-react-component-library@1.1.0","template.workspace-react-component-library@1.2.0","template.web-frontend-application@1.0.0"]),Ym=(e,t)=>e==="foundation.workspace-root"&&t==="1.4.0"?{id:"template.workspace-root",version:"1.1.0"}:e==="foundation.workspace-root"&&t==="1.5.0"?{id:"template.workspace-root",version:"1.2.0"}:void 0,Za={"workspace-npm-package":{id:"template.workspace-npm-package",version:"1.0.0"},"react-component-library":{id:"template.workspace-react-component-library",version:"1.2.0"},"workspace-web-application":{id:"template.web-frontend-application",version:"1.0.0"},"workspace-node-application":{id:"template.node-api-application",version:"1.0.0"},"workspace-expo-application":{id:"template.expo-react-native-application",version:"1.0.0"},"nextjs-full-stack-application":{id:"template.nextjs-full-stack-application",version:"1.0.0"}};function Hm(e){return e.capabilities.flatMap(t=>t.assets).filter(t=>t.ownership!=="seed-file")}async function Xa(e,t,r,n){if(t.release.schemaVersion!==2||t.release.packageSources.length===0)return;if(r.packageSourceProvider===void 0)throw new ae("CAPABILITY_RELEASE_VERSION_UNSUPPORTED","Capability Release v2 requires a trusted Package Source Provider");let i=await te(N.join(e,"package.json")),a=await r.packageSourceProvider.inspect({projectRoot:e,release:t.release}),{resolvePnpmLock:o}=await import("./optional-runtime.js"),s=await Kr(e),c=await te(N.join(s.transactionRoot,s.lockfilePath)).catch(p=>p.code==="ENOENT"?void 0:Promise.reject(p));if(s.mode==="pnpm-shared-lockfile"){if(!c)throw new ae("CAPABILITY_PACKAGE_SOURCE_INVALID","Workspace shared lockfile is unavailable");if(!r.resolutionWorkerProvider)throw new ae("CAPABILITY_PACKAGE_SOURCE_INVALID","Shared workspace package adoption requires verified Resolution Worker Evidence");let p=Hn({release:t.release,packageJson:n??i}),m=new Date,u=new Date(m.getTime()+1800*1e3).toISOString(),f=await r.resolutionWorkerProvider.resolveWorkspace({topology:s,desiredPackageJson:p,currentLockfile:c,sources:t.release.packageSources,registryConfigs:a.registryConfigs,endpointBindings:a.endpointBindings,generatedAt:m.toISOString(),expiresAt:u});return{...a,lockResolution:{lockfile:f.evidence.desiredLockfile,packages:f.evidence.packageFacts.filter(g=>g.managed).map(({registryId:g,packageName:h,version:w,integrity:_})=>({registryId:g,packageName:h,version:w,integrity:_}))},resolutionEvidence:f.evidence,resolutionWorkerReleaseId:f.workerReleaseId,topology:s,currentLockfile:c,preservedImporterDigests:f.preservedImporterDigests}}let d=Mc({release:t.release,packageJson:n??i}),l=await o({desiredPackageJson:d,...c===void 0?{}:{currentLockfile:c},sources:t.release.packageSources,registries:a.registryConfigs,endpointBindings:a.endpointBindings});return{...a,lockResolution:l,topology:s,...c===void 0?{}:{currentLockfile:c},preservedImporterDigests:[]}}async function Zm(e,t,r,n){let i=r.capabilities.find(b=>b.capabilityId===t.release.capabilityId&&b.version===t.release.version);if(i&&!i.packageAdoption){let b=JSON.parse(await te(N.join(e,"project-capabilities.json"),"utf8")),A=new Date;return am({projectRoot:e,manifest:b,release:t,currentLock:r,generatedAt:A.toISOString(),expiresAt:new Date(A.getTime()+30*6e4).toISOString()})}if(t.release.schemaVersion!==2||n.packageSourceProvider===void 0)throw new ae("CAPABILITY_RELEASE_VERSION_UNSUPPORTED","Package removal requires a trusted Package Source Provider");if(!i?.packageAdoption)throw new ae("CAPABILITY_RELEASE_VERSION_UNSUPPORTED","Package removal requires Lock v2 ownership facts");let a=await n.packageSourceProvider.inspect({projectRoot:e,release:t.release}),o=await te(N.join(e,"package.json")),s=await te(N.join(e,"project-capabilities.json")),c=await Kr(e),d=await te(N.join(c.transactionRoot,c.lockfilePath)),l=new Set(r.capabilities.filter(b=>b!==i).flatMap(b=>b.packageAdoption?.sources.map(A=>A.packageName)??[])),p=i.packageAdoption.sources.filter(b=>!l.has(b.packageName)),m=c.mode==="pnpm-shared-lockfile"?Uc({packageJson:o,remove:p}):qc({packageJson:o,remove:p}),u=r.capabilities.filter(b=>b!==i).flatMap(b=>b.packageAdoption?.sources??[]),f=new Date,g=new Date(f.getTime()+1800*1e3).toISOString();if(c.mode==="pnpm-shared-lockfile"){if(!n.resolutionWorkerProvider)throw new ae("CAPABILITY_PACKAGE_SOURCE_INVALID","Shared workspace package removal requires verified Resolution Worker Evidence");let b=await n.resolutionWorkerProvider.resolveWorkspace({topology:c,desiredPackageJson:m,currentLockfile:d,sources:u,registryConfigs:a.registryConfigs,endpointBindings:a.endpointBindings,generatedAt:f.toISOString(),expiresAt:g}),A=[`${c.unitRelativeRoot}/project-capabilities.json`,`${c.unitRelativeRoot}/package.json`,c.lockfilePath,...i.assets.map(k=>`${c.unitRelativeRoot}/${k.path}`)],y=await Promise.all(A.map(async k=>te(N.join(c.transactionRoot,...k.split("/"))).then(S=>({path:k,exists:!0,digest:v(S)})).catch(S=>S.code==="ENOENT"?{path:k,exists:!1}:Promise.reject(S))));return{...pf({release:t.release,currentLock:r,projectManifest:s,packageJson:o,currentLockfile:d,endpointBindings:a.endpointBindings,observedAssets:y,topology:c,transactionRoot:c.transactionRoot,preservedImporterDigests:b.preservedImporterDigests,resolutionEvidence:b.evidence,resolutionWorkerReleaseId:b.workerReleaseId,remainingSources:u,generatedAt:f.toISOString(),expiresAt:g}),registryConfigs:a.registryConfigs,endpointBindings:a.endpointBindings}}let{resolvePnpmLock:h}=await import("./optional-runtime.js"),w=await h({desiredPackageJson:m,currentLockfile:d,sources:u,registrySources:[...u,...i.packageAdoption.sources],registries:a.registryConfigs,endpointBindings:a.endpointBindings}),_=await Promise.all(["project-capabilities.json","package.json","pnpm-lock.yaml",...i.assets.map(b=>b.path)].map(async b=>te(N.join(e,...b.split("/"))).then(A=>({path:b,exists:!0,digest:v(A)})).catch(A=>A.code==="ENOENT"?{path:b,exists:!1}:Promise.reject(A))));return{...df({release:t.release,currentLock:r,projectManifest:s,packageJson:o,currentLockfile:d,desiredLockfile:w.lockfile,endpointBindings:a.endpointBindings,observedAssets:_,generatedAt:f.toISOString(),expiresAt:g}),registryConfigs:a.registryConfigs,endpointBindings:a.endpointBindings}}function F(e){return e.includes("--json")?"json":"human"}function I(e){throw new xe({code:"CLI_ARGUMENT_INVALID",message:e,exitCode:2,nextStep:"Run dyyto --help."})}function Ae(e,t){return!/^[a-z0-9][a-z0-9.-]*$/u.test(e)||!/^\d+\.\d+\.\d+$/u.test(t)?I("The selected capability release identifier is invalid."):N.resolve(import.meta.dirname,"catalog",e,t)}function Qa(e,t){return fA.has(`${e}@${t}`)?N.resolve(import.meta.dirname,"templates",e,t):I("The selected template release is not bundled with this CLI.")}function mA(e,t){return!/^[a-z0-9]+(?:[.-][a-z0-9]+)*$/.test(e)||!/^\d+\.\d+\.\d+$/.test(t)?I("The selected example recipe identity or version is invalid."):N.resolve(import.meta.dirname,"recipes",e,t)}function Z(e){let t=N.relative(process.cwd(),e);return t.length>0&&t!==".."&&!t.startsWith(`..${N.sep}`)?t:N.basename(e)}async function eo(e){let t=JSON.parse(await te(N.join(e,"project-capabilities.json"),"utf8")),r=t.capabilities?.[0];if(r===void 0)return I("Project manifest must select one capability.");let n=await ge(Ae(r.capabilityId,r.version)),i=await Se(e).catch(()=>null),a=new Date,s=await(t.profile?.id==="standalone-npm-package"?Bn:t.profile?.id==="react-component-library"?Jn:t.profile?.id==="nextjs-full-stack-application"?Yr:t.profile?.id==="workspace-npm-package"?Gn:t.profile?.id==="workspace-node-application"?Wn:t.profile?.id==="workspace-web-application"?Kn:t.profile?.id==="workspace-expo-application"?Yn:ia)({projectRoot:e,manifest:t,release:n,...i===null?{}:{currentLock:i},generatedAt:a.toISOString(),expiresAt:new Date(a.getTime()+1800*1e3).toISOString()});return pr({projectRoot:e,plan:s.plan,now:a.toISOString()})}async function Xm(e){let t;try{t=oe({args:[...e],allowPositionals:!0,strict:!0,options:{json:{type:"boolean"},profile:{type:"string"},template:{type:"string"},capability:{type:"string"},name:{type:"string"},version:{type:"string"},license:{type:"string"},"publish-access":{type:"string"},repository:{type:"string"}}})}catch{return I("Create arguments are invalid.")}if(t.positionals.length!==1)return I("Create requires exactly one directory.");let r=t.values.template,n;if(typeof r=="string"){let[g,h]=r.split("@");n=await li(Qa(g,h))}let i=n?.profile.id??t.values.profile;if(i!=="typescript-library"&&i!=="standalone-npm-package"&&i!=="react-component-library"&&i!=="nextjs-full-stack-application"&&i!=="workspace-root")return I("Create requires a supported --profile.");let a=t.values.capability,o=i==="workspace-root"&&a==="foundation.workspace-root@1.0.0"||i==="standalone-npm-package"&&a==="foundation.standalone-npm-package@1.0.0",s=n?.profile.capability??(o?a:fi[i]);if(n!==void 0&&s.split("@")[0]!==fi[i].split("@")[0])return I(`Template ${n.templateId} is adopted with dyyto add, not dyyto create.`);if(n===void 0&&a!==s)return I(`Create requires --capability ${s}.`);if(n!==void 0&&a!==void 0)return I("Create with --template does not accept --capability.");let[c,d]=s.split("@"),l={};if(i==="standalone-npm-package"||i==="react-component-library"){let g=t.values.name,h=t.values.version,w=t.values.license,_=t.values["publish-access"],b=t.values.repository;if([g,h,w,_].some(A=>typeof A!="string")||d==="1.1.0"&&typeof b!="string")return I(`Standalone npm package requires --name, --version, --license, --publish-access${d==="1.1.0"?", and --repository":""}.`);l={name:String(g),version:String(h),license:String(w),publishAccess:String(_),...typeof b=="string"?{repository:b}:{}}}else if(i==="nextjs-full-stack-application"){if(typeof t.values.name!="string")return I("Next.js application requires --name.");l={name:t.values.name}}let p={schemaVersion:1,...n===void 0?{}:{template:{id:n.templateId,version:n.version}},profile:{id:i,parameters:l},capabilities:[{capabilityId:c,version:d}]};(i==="standalone-npm-package"||i==="react-component-library")&&Ft(J(p),i),i==="nextjs-full-stack-application"&&fr(J(p));let m=await va({projectRoot:t.positionals[0],manifest:p}),u=await eo(m.projectRoot),f=Z(m.projectRoot);return{outputMode:F(e),human:`Project '${f}' initialized.
|
|
110
|
+
`)throw new ze("SCAFFOLD_PLAN_INVALID")}),a}async function eA(e,t){if(!/^sha256:[a-f0-9]{64}$/u.test(t))throw new ze("SCAFFOLD_PLAN_INVALID");let r=await al(Fe.resolve(e)),n;try{n=JSON.parse(await Cm(Fe.join(r,".dyyto","scaffold-plans",`${t}.json`),"utf8"))}catch{throw new ze("SCAFFOLD_PLAN_NOT_FOUND")}let{planId:i,...a}=n;if(i!==t||xm(a)!==t||n.workspaceRoot!==r||Date.parse(n.expiresAt)<=Date.now())throw new ze("SCAFFOLD_PLAN_INVALID");return n}async function Mm(e){let t=await eA(e.workspaceRoot,e.approvedPlanId);if(t.recipeId!==e.recipe.recipeId||t.recipeVersion!==e.recipe.version||t.recipeIntegrity!==e.recipe.integrity)throw new ze("SCAFFOLD_PLAN_INVALID");let r=await Lm(t.workspaceRoot,t.outputRelativePath),n;try{n=await e.execute(r.output,t)}catch(s){throw await Om(r.output).then(()=>!0).catch(()=>!1)&&await XE(r.output,{recursive:!0,force:!0}),new ze("SCAFFOLD_APPLY_FAILED",s)}let i={schemaVersion:1,scaffoldPlanId:t.planId,recipeIntegrity:t.recipeIntegrity,outputRelativePath:t.outputRelativePath,state:"adopted",receipts:n},a=v(E(i)),o=Fe.join(t.workspaceRoot,".dyyto","scaffold-evidence");return await ol(o,{recursive:!0}),await Tm(Fe.join(o,`${a}.json`),`${E({...i,evidenceId:a})}
|
|
111
|
+
`,{flag:"wx",mode:384}),{evidenceId:a,output:r.output,receipts:n}}import{lstat as ui,readFile as sl,readdir as tA,realpath as cl}from"node:fs/promises";import pe from"node:path";var qm={capabilities:pe.resolve(import.meta.dirname,"catalog"),packages:pe.resolve(import.meta.dirname,"package-releases")};function rA(e){let t=new Map;for(let[r,n]of e.split(/\r?\n/u).entries()){let i=n.trim();if(i===""||i.startsWith("#"))continue;if(i.startsWith("export "))throw new Error(`Dyyto \u7EC4\u4EF6 .env:${r+1} \u4E0D\u5141\u8BB8\u4F7F\u7528 export`);let a=/^([A-Z][A-Z0-9_]*)=(.*)$/u.exec(i);if(!a)throw new Error(`Dyyto \u7EC4\u4EF6 .env:${r+1} \u4E0D\u662F\u4E25\u683C KEY=VALUE \u683C\u5F0F`);if(t.has(a[1]))throw new Error(`Dyyto \u7EC4\u4EF6 .env:${r+1} \u5305\u542B\u91CD\u590D\u53D8\u91CF ${a[1]}`);let o=a[2].trim();if((o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'"))&&(o=o.slice(1,-1)),/[`$][({]?/u.test(o))throw new Error(`Dyyto \u7EC4\u4EF6 .env:${r+1} \u4E0D\u5141\u8BB8\u547D\u4EE4\u6216\u53D8\u91CF\u5C55\u5F00`);t.set(a[1],o)}return t}async function Um(e,t){let r=await ui(e);if(!r.isFile()||r.isSymbolicLink()||r.nlink!==1)throw new Error(`${t}\u5FC5\u987B\u662F\u666E\u901A\u975E\u94FE\u63A5\u6587\u4EF6`);if(typeof process.getuid=="function"&&r.uid!==process.getuid())throw new Error(`${t}\u5FC5\u987B\u7531\u5F53\u524D\u7528\u6237\u62E5\u6709`);if((r.mode&511&-385)!==0)throw new Error(`${t}\u6743\u9650\u8FC7\u5BBD\uFF0C\u6700\u5927\u5141\u8BB80600`)}async function Ya(e,t){let r=await ui(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t}\u5FC5\u987B\u662F\u666E\u901A\u76EE\u5F55\u4E14\u4E0D\u80FD\u662F\u7B26\u53F7\u94FE\u63A5`);if(typeof process.getuid=="function"&&r.uid!==process.getuid())throw new Error(`${t}\u5FC5\u987B\u7531\u5F53\u524D\u7528\u6237\u62E5\u6709`);if((r.mode&511&-449)!==0)throw new Error(`${t}\u6743\u9650\u8FC7\u5BBD\uFF0C\u6700\u5927\u5141\u8BB80700`);return cl(e)}async function nA(e){let t=e;for(;;){if(await ui(pe.join(t,".git")).then(()=>!0).catch(n=>n.code==="ENOENT"?!1:Promise.reject(n)))throw new Error(`IDP_CONFIG_DIR \u5FC5\u987B\u4F4D\u4E8E Git \u4ED3\u5E93\u5916\uFF1A${t}`);let r=pe.dirname(t);if(r===t)return;t=r}}async function iA(e){if(!pe.isAbsolute(e))throw new Error("IDP_CONFIG_DIR \u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");let t=await Ya(e,"IDP_CONFIG_DIR");await nA(t);let r=await Ya(pe.join(t,"components"),"components"),n=await Ya(pe.join(r,"dyyto"),"Dyyto \u914D\u7F6E\u76EE\u5F55"),i=pe.relative(t,n);if(i.startsWith("..")||pe.isAbsolute(i))throw new Error("Dyyto \u914D\u7F6E\u76EE\u5F55\u8D8A\u8FC7 IDP_CONFIG_DIR");let a=pe.join(n,".env");await Um(a,"Dyyto \u7EC4\u4EF6 .env");let o=rA(await sl(a,"utf8")).get("DYYTO_PACKAGE_CATALOG_DIRS_FILE");if(o===void 0||o==="")return[];if(pe.isAbsolute(o)||o.includes("\0")||/[*?{}[\]]/u.test(o))throw new Error("DYYTO_PACKAGE_CATALOG_DIRS_FILE \u5FC5\u987B\u662F\u7EC4\u4EF6\u76EE\u5F55\u5185\u7684\u666E\u901A\u76F8\u5BF9\u6587\u4EF6\u8DEF\u5F84");let s=pe.resolve(n,o),c=pe.relative(n,s);if(c===""||c.startsWith("..")||pe.isAbsolute(c))throw new Error("DYYTO_PACKAGE_CATALOG_DIRS_FILE \u5FC5\u987B\u4F4D\u4E8E\u7EC4\u4EF6\u914D\u7F6E\u76EE\u5F55\u5185");let d=n;for(let u of c.split(pe.sep).slice(0,-1))d=await Ya(pe.join(d,u),"Package Catalog Binding \u7236\u76EE\u5F55");let l=await cl(pe.dirname(s)),p=pe.relative(n,l);if(p.startsWith("..")||pe.isAbsolute(p))throw new Error("Package Catalog Binding \u89E3\u6790\u540E\u8D8A\u8FC7\u7EC4\u4EF6\u914D\u7F6E\u76EE\u5F55");await Um(s,"Package Catalog Binding");let m=[];for(let u of(await sl(s,"utf8")).split(/\r?\n/u)){let f=u.trim();if(f===""||f.startsWith("#"))continue;if(!pe.isAbsolute(f))throw new Error("Package Catalog Binding \u4E2D\u7684\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");let g=await ui(f);if(!g.isDirectory()||g.isSymbolicLink())throw new Error("Package Catalog Binding \u5FC5\u987B\u6307\u5411\u666E\u901A\u76EE\u5F55");let h=await cl(f),w=await ui(h);if(!w.isDirectory()||w.isSymbolicLink())throw new Error("Package Catalog Binding \u5FC5\u987B\u6307\u5411\u666E\u901A\u76EE\u5F55");m.includes(h)||m.push(h)}return m.sort()}async function aA(){let e=process.env.IDP_CONFIG_DIR,t=e===void 0?[]:await iA(e);return{capabilities:qm.capabilities,packages:[qm.packages,...t]}}async function Ha(e){return(await tA(e,{withFileTypes:!0})).filter(t=>t.isDirectory()&&!t.isSymbolicLink()).map(t=>t.name).sort()}function oA(e,t){let r=a=>a.split("-",1)[0].split(".").map(Number),n=r(e),i=r(t);for(let a=0;a<3;a+=1){let o=(n[a]??0)-(i[a]??0);if(o!==0)return o}return e.localeCompare(t)}function sA(e){let t=e.schemaVersion===2?e.availability.maturity:"legacy-unverified",r="consumerProfile"in e?e.consumerProfile:"\u591A\u79CD\u5DE5\u7A0B Profile";return{kind:"capability",ref:`capability:${e.capabilityId}@${e.version}`,id:e.capabilityId,version:e.version,title:e.capabilityId,summary:`\u9002\u7528\u4E8E ${r} \u7684\u5DE5\u7A0B\u80FD\u529B\u53D1\u884C\u3002`,maturity:t,integrity:e.integrity}}function cA(e){return{kind:"package",ref:`package:${e.packageName}@${e.version}`,id:e.packageName,version:e.version,title:e.title,summary:e.summary,maturity:e.maturity,integrity:e.releaseDigest}}async function lA(e){let t=[];for(let r of await Ha(e))for(let n of await Ha(pe.join(e,r))){let i=`capability:${r}@${n}`;t.push(ge(pe.join(e,r,n)).then(a=>({entry:{item:sA(a.release),release:a.release}})).catch(()=>({diagnostic:{ref:i,code:"CATALOG_RELEASE_INVALID",message:"Capability \u53D1\u884C\u672A\u901A\u8FC7\u5B8C\u6574\u6027\u6821\u9A8C"}})))}return(await Promise.all(t)).reduce((r,n)=>(n.entry!==void 0&&r.entries.push(n.entry),n.diagnostic!==void 0&&r.diagnostics.push(n.diagnostic),r),{entries:[],diagnostics:[]})}async function dA(e){let t=[];for(let r of await Ha(e))for(let n of await Ha(pe.join(e,r))){let i=pe.join(e,r,n,"release.json"),a=`package:${r}@${n}`;t.push(sl(i,"utf8").then(o=>{let s=_m(JSON.parse(o));return{entry:{item:cA(s),release:s}}}).catch(()=>({diagnostic:{ref:a,code:"CATALOG_RELEASE_INVALID",message:"PackageRelease \u672A\u901A\u8FC7\u5B8C\u6574\u6027\u6821\u9A8C"}})))}return(await Promise.all(t)).reduce((r,n)=>(n.entry!==void 0&&r.entries.push(n.entry),n.diagnostic!==void 0&&r.diagnostics.push(n.diagnostic),r),{entries:[],diagnostics:[]})}async function Fm(e){let t=e??await aA(),r=typeof t.packages=="string"?[t.packages]:[...t.packages],[n,...i]=await Promise.all([lA(t.capabilities),...r.map(dA)]),a=[...n.entries,...i.flatMap(d=>d.entries)].sort((d,l)=>d.item.ref.localeCompare(l.item.ref)),o=[],s=new Set,c=[];for(let d of a)s.has(d.item.ref)?c.push({ref:d.item.ref,code:"CATALOG_RELEASE_DUPLICATE",message:"\u591A\u4E2A Catalog Source \u58F0\u660E\u4E86\u540C\u4E00\u4E0D\u53EF\u53D8\u53D1\u884C ref"}):(s.add(d.item.ref),o.push(d));return{entries:o,diagnostics:[...n.diagnostics,...i.flatMap(d=>d.diagnostics),...c].sort((d,l)=>d.ref.localeCompare(l.ref))}}async function zm(e){let t=(e.query??"").trim().toLocaleLowerCase("zh-CN"),r=await Fm(e.roots),n=new Map;for(let{item:o}of r.entries){if(e.kind!==void 0&&o.kind!==e.kind)continue;let s=[o.id,o.version,o.title,o.summary,o.maturity].join(" ").toLocaleLowerCase("zh-CN");if(t!==""&&!s.includes(t))continue;let c=`${o.kind}:${o.id}`,d=n.get(c);(d===void 0||oA(d.version,o.version)<0)&&n.set(c,o)}let i=[...n.values()].sort((o,s)=>o.ref.localeCompare(s.ref)),a=e.limit??50;return{query:t,total:i.length,items:i.slice(0,a),diagnostics:r.diagnostics}}async function Bm(e){let t=e.ref.startsWith("package:")||e.ref.startsWith("capability:")?e.ref:`${e.ref.startsWith("@")?"package":"capability"}:${e.ref}`,r=await Fm(e.roots),n=r.entries.find(({item:a})=>a.ref===t),i=r.diagnostics.find(a=>a.ref===t);if(i?.code==="CATALOG_RELEASE_DUPLICATE")throw new Error(`\u53D1\u884C ref \u5728\u591A\u4E2A Catalog Source \u4E2D\u91CD\u590D\uFF1A${e.ref}`);if(n===void 0&&i!==void 0)throw new Error(`\u53D1\u884C\u672A\u901A\u8FC7\u5B8C\u6574\u6027\u6821\u9A8C\uFF1A${e.ref}`);if(n===void 0)throw new Error(`\u76EE\u5F55\u4E2D\u4E0D\u5B58\u5728\u53D1\u884C\uFF1A${e.ref}`);return n}var fi={"typescript-library":"foundation.typescript-quality@1.0.0","standalone-npm-package":"foundation.standalone-npm-package@1.2.0","workspace-root":"foundation.workspace-root@1.1.0","workspace-npm-package":"foundation.workspace-npm-package@1.2.0","workspace-node-application":"foundation.workspace-node-application@1.1.0","workspace-web-application":"foundation.workspace-web-application@1.1.0","workspace-expo-application":"foundation.workspace-expo-application@1.0.0","react-component-library":"foundation.react-component-library@1.1.0","workspace-react-component-library":"foundation.workspace-react-component-library@1.2.0","nextjs-full-stack-application":"foundation.nextjs-full-stack-application@1.0.0"},Km=fA(pA),mA=new Set(["template.typescript-library@1.0.0","template.typescript-library@1.1.0","template.react-component-library@1.0.0","template.react-component-library@1.1.0","template.nextjs-full-stack-application@1.0.0","template.expo-react-native-application@1.0.0","template.node-api-application@1.0.0","template.workspace-root@1.0.0","template.workspace-root@1.1.0","template.workspace-root@1.2.0","template.workspace-npm-package@1.0.0","template.workspace-react-component-library@1.0.0","template.workspace-react-component-library@1.1.0","template.workspace-react-component-library@1.2.0","template.web-frontend-application@1.0.0"]),Ym=(e,t)=>e==="foundation.workspace-root"&&t==="1.4.0"?{id:"template.workspace-root",version:"1.1.0"}:e==="foundation.workspace-root"&&t==="1.5.0"?{id:"template.workspace-root",version:"1.2.0"}:void 0,Za={"workspace-npm-package":{id:"template.workspace-npm-package",version:"1.0.0"},"react-component-library":{id:"template.workspace-react-component-library",version:"1.2.0"},"workspace-web-application":{id:"template.web-frontend-application",version:"1.0.0"},"workspace-node-application":{id:"template.node-api-application",version:"1.0.0"},"workspace-expo-application":{id:"template.expo-react-native-application",version:"1.0.0"},"nextjs-full-stack-application":{id:"template.nextjs-full-stack-application",version:"1.0.0"}};function Hm(e){return e.capabilities.flatMap(t=>t.assets).filter(t=>t.ownership!=="seed-file")}async function Xa(e,t,r,n){if(t.release.schemaVersion!==2||t.release.packageSources.length===0)return;if(r.packageSourceProvider===void 0)throw new ae("CAPABILITY_RELEASE_VERSION_UNSUPPORTED","Capability Release v2 requires a trusted Package Source Provider");let i=await te(N.join(e,"package.json")),a=await r.packageSourceProvider.inspect({projectRoot:e,release:t.release}),{resolvePnpmLock:o}=await import("./optional-runtime.js"),s=await Kr(e),c=await te(N.join(s.transactionRoot,s.lockfilePath)).catch(p=>p.code==="ENOENT"?void 0:Promise.reject(p));if(s.mode==="pnpm-shared-lockfile"){if(!c)throw new ae("CAPABILITY_PACKAGE_SOURCE_INVALID","Workspace shared lockfile is unavailable");if(!r.resolutionWorkerProvider)throw new ae("CAPABILITY_PACKAGE_SOURCE_INVALID","Shared workspace package adoption requires verified Resolution Worker Evidence");let p=Hn({release:t.release,packageJson:n??i}),m=new Date,u=new Date(m.getTime()+1800*1e3).toISOString(),f=await r.resolutionWorkerProvider.resolveWorkspace({topology:s,desiredPackageJson:p,currentLockfile:c,sources:t.release.packageSources,registryConfigs:a.registryConfigs,endpointBindings:a.endpointBindings,generatedAt:m.toISOString(),expiresAt:u});return{...a,lockResolution:{lockfile:f.evidence.desiredLockfile,packages:f.evidence.packageFacts.filter(g=>g.managed).map(({registryId:g,packageName:h,version:w,integrity:_})=>({registryId:g,packageName:h,version:w,integrity:_}))},resolutionEvidence:f.evidence,resolutionWorkerReleaseId:f.workerReleaseId,topology:s,currentLockfile:c,preservedImporterDigests:f.preservedImporterDigests}}let d=Mc({release:t.release,packageJson:n??i}),l=await o({desiredPackageJson:d,...c===void 0?{}:{currentLockfile:c},sources:t.release.packageSources,registries:a.registryConfigs,endpointBindings:a.endpointBindings});return{...a,lockResolution:l,topology:s,...c===void 0?{}:{currentLockfile:c},preservedImporterDigests:[]}}async function Zm(e,t,r,n){let i=r.capabilities.find(b=>b.capabilityId===t.release.capabilityId&&b.version===t.release.version);if(i&&!i.packageAdoption){let b=JSON.parse(await te(N.join(e,"project-capabilities.json"),"utf8")),A=new Date;return am({projectRoot:e,manifest:b,release:t,currentLock:r,generatedAt:A.toISOString(),expiresAt:new Date(A.getTime()+30*6e4).toISOString()})}if(t.release.schemaVersion!==2||n.packageSourceProvider===void 0)throw new ae("CAPABILITY_RELEASE_VERSION_UNSUPPORTED","Package removal requires a trusted Package Source Provider");if(!i?.packageAdoption)throw new ae("CAPABILITY_RELEASE_VERSION_UNSUPPORTED","Package removal requires Lock v2 ownership facts");let a=await n.packageSourceProvider.inspect({projectRoot:e,release:t.release}),o=await te(N.join(e,"package.json")),s=await te(N.join(e,"project-capabilities.json")),c=await Kr(e),d=await te(N.join(c.transactionRoot,c.lockfilePath)),l=new Set(r.capabilities.filter(b=>b!==i).flatMap(b=>b.packageAdoption?.sources.map(A=>A.packageName)??[])),p=i.packageAdoption.sources.filter(b=>!l.has(b.packageName)),m=c.mode==="pnpm-shared-lockfile"?Uc({packageJson:o,remove:p}):qc({packageJson:o,remove:p}),u=r.capabilities.filter(b=>b!==i).flatMap(b=>b.packageAdoption?.sources??[]),f=new Date,g=new Date(f.getTime()+1800*1e3).toISOString();if(c.mode==="pnpm-shared-lockfile"){if(!n.resolutionWorkerProvider)throw new ae("CAPABILITY_PACKAGE_SOURCE_INVALID","Shared workspace package removal requires verified Resolution Worker Evidence");let b=await n.resolutionWorkerProvider.resolveWorkspace({topology:c,desiredPackageJson:m,currentLockfile:d,sources:u,registryConfigs:a.registryConfigs,endpointBindings:a.endpointBindings,generatedAt:f.toISOString(),expiresAt:g}),A=[`${c.unitRelativeRoot}/project-capabilities.json`,`${c.unitRelativeRoot}/package.json`,c.lockfilePath,...i.assets.map(k=>`${c.unitRelativeRoot}/${k.path}`)],y=await Promise.all(A.map(async k=>te(N.join(c.transactionRoot,...k.split("/"))).then(S=>({path:k,exists:!0,digest:v(S)})).catch(S=>S.code==="ENOENT"?{path:k,exists:!1}:Promise.reject(S))));return{...uf({release:t.release,currentLock:r,projectManifest:s,packageJson:o,currentLockfile:d,endpointBindings:a.endpointBindings,observedAssets:y,topology:c,transactionRoot:c.transactionRoot,preservedImporterDigests:b.preservedImporterDigests,resolutionEvidence:b.evidence,resolutionWorkerReleaseId:b.workerReleaseId,remainingSources:u,generatedAt:f.toISOString(),expiresAt:g}),registryConfigs:a.registryConfigs,endpointBindings:a.endpointBindings}}let{resolvePnpmLock:h}=await import("./optional-runtime.js"),w=await h({desiredPackageJson:m,currentLockfile:d,sources:u,registrySources:[...u,...i.packageAdoption.sources],registries:a.registryConfigs,endpointBindings:a.endpointBindings}),_=await Promise.all(["project-capabilities.json","package.json","pnpm-lock.yaml",...i.assets.map(b=>b.path)].map(async b=>te(N.join(e,...b.split("/"))).then(A=>({path:b,exists:!0,digest:v(A)})).catch(A=>A.code==="ENOENT"?{path:b,exists:!1}:Promise.reject(A))));return{...pf({release:t.release,currentLock:r,projectManifest:s,packageJson:o,currentLockfile:d,desiredLockfile:w.lockfile,endpointBindings:a.endpointBindings,observedAssets:_,generatedAt:f.toISOString(),expiresAt:g}),registryConfigs:a.registryConfigs,endpointBindings:a.endpointBindings}}function F(e){return e.includes("--json")?"json":"human"}function I(e){throw new xe({code:"CLI_ARGUMENT_INVALID",message:e,exitCode:2,nextStep:"Run dyyto --help."})}function Ae(e,t){return!/^[a-z0-9][a-z0-9.-]*$/u.test(e)||!/^\d+\.\d+\.\d+$/u.test(t)?I("The selected capability release identifier is invalid."):N.resolve(import.meta.dirname,"catalog",e,t)}function Qa(e,t){return mA.has(`${e}@${t}`)?N.resolve(import.meta.dirname,"templates",e,t):I("The selected template release is not bundled with this CLI.")}function gA(e,t){return!/^[a-z0-9]+(?:[.-][a-z0-9]+)*$/.test(e)||!/^\d+\.\d+\.\d+$/.test(t)?I("The selected example recipe identity or version is invalid."):N.resolve(import.meta.dirname,"recipes",e,t)}function Y(e){let t=N.relative(process.cwd(),e);return t.length>0&&t!==".."&&!t.startsWith(`..${N.sep}`)?t:N.basename(e)}async function eo(e){let t=JSON.parse(await te(N.join(e,"project-capabilities.json"),"utf8")),r=t.capabilities?.[0];if(r===void 0)return I("Project manifest must select one capability.");let n=await ge(Ae(r.capabilityId,r.version)),i=await Se(e).catch(()=>null),a=new Date,s=await(t.profile?.id==="standalone-npm-package"?Bn:t.profile?.id==="react-component-library"?Gn:t.profile?.id==="nextjs-full-stack-application"?Yr:t.profile?.id==="workspace-npm-package"?Jn:t.profile?.id==="workspace-node-application"?Wn:t.profile?.id==="workspace-web-application"?Kn:t.profile?.id==="workspace-expo-application"?Yn:ia)({projectRoot:e,manifest:t,release:n,...i===null?{}:{currentLock:i},generatedAt:a.toISOString(),expiresAt:new Date(a.getTime()+1800*1e3).toISOString()});return pr({projectRoot:e,plan:s.plan,now:a.toISOString()})}async function Xm(e){let t;try{t=oe({args:[...e],allowPositionals:!0,strict:!0,options:{json:{type:"boolean"},profile:{type:"string"},template:{type:"string"},capability:{type:"string"},name:{type:"string"},version:{type:"string"},license:{type:"string"},"publish-access":{type:"string"},repository:{type:"string"}}})}catch{return I("Create arguments are invalid.")}if(t.positionals.length!==1)return I("Create requires exactly one directory.");let r=t.values.template,n;if(typeof r=="string"){let[g,h]=r.split("@");n=await li(Qa(g,h))}let i=n?.profile.id??t.values.profile;if(i!=="typescript-library"&&i!=="standalone-npm-package"&&i!=="react-component-library"&&i!=="nextjs-full-stack-application"&&i!=="workspace-root")return I("Create requires a supported --profile.");let a=t.values.capability,o=i==="workspace-root"&&a==="foundation.workspace-root@1.0.0"||i==="standalone-npm-package"&&a==="foundation.standalone-npm-package@1.0.0",s=n?.profile.capability??(o?a:fi[i]);if(n!==void 0&&s.split("@")[0]!==fi[i].split("@")[0])return I(`Template ${n.templateId} is adopted with dyyto add, not dyyto create.`);if(n===void 0&&a!==s)return I(`Create requires --capability ${s}.`);if(n!==void 0&&a!==void 0)return I("Create with --template does not accept --capability.");let[c,d]=s.split("@"),l={};if(i==="standalone-npm-package"||i==="react-component-library"){let g=t.values.name,h=t.values.version,w=t.values.license,_=t.values["publish-access"],b=t.values.repository;if([g,h,w,_].some(A=>typeof A!="string")||d==="1.1.0"&&typeof b!="string")return I(`Standalone npm package requires --name, --version, --license, --publish-access${d==="1.1.0"?", and --repository":""}.`);l={name:String(g),version:String(h),license:String(w),publishAccess:String(_),...typeof b=="string"?{repository:b}:{}}}else if(i==="nextjs-full-stack-application"){if(typeof t.values.name!="string")return I("Next.js application requires --name.");l={name:t.values.name}}let p={schemaVersion:1,...n===void 0?{}:{template:{id:n.templateId,version:n.version}},profile:{id:i,parameters:l},capabilities:[{capabilityId:c,version:d}]};(i==="standalone-npm-package"||i==="react-component-library")&&Ft(G(p),i),i==="nextjs-full-stack-application"&&fr(G(p));let m=await va({projectRoot:t.positionals[0],manifest:p}),u=await eo(m.projectRoot),f=Y(m.projectRoot);return{outputMode:F(e),human:`Project '${f}' initialized.
|
|
109
112
|
Plan: ${u.planId}
|
|
110
113
|
State: ${u.state}
|
|
111
|
-
Next: dyyto apply --project ${f} --approve ${u.planId}`,value:{schemaVersion:1,ok:!0,command:"create",result:{project:f,profile:i,...n===void 0?{}:{template:`${n.templateId}@${n.version}`},capability:s,plan:u}}}}async function
|
|
114
|
+
Next: dyyto apply --project ${f} --approve ${u.planId}`,value:{schemaVersion:1,ok:!0,command:"create",result:{project:f,profile:i,...n===void 0?{}:{template:`${n.templateId}@${n.version}`},capability:s,plan:u}}}}async function hA(e){let[t,...r]=e,n;try{n=oe({args:r,allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},approve:{type:"string"},profile:{type:"string"},capability:{type:"string"},"documentation-only":{type:"boolean"}}})}catch{return I("Retrofit arguments are invalid.")}if(t!=="plan"&&t!=="apply")return I("Retrofit requires plan or apply.");if(typeof n.values.project!="string")return I("Retrofit requires --project <directory>.");if(n.values.capability!==void 0&&typeof n.values.capability!="string")return I("Retrofit --capability is invalid.");if(n.values.profile!==void 0&&typeof n.values.profile!="string")return I("Retrofit --profile is invalid.");let i=n.values.capability??"foundation.workspace-root@1.2.0",a=/^([a-z][a-z0-9.-]*)@([0-9A-Za-z.-]+)$/u.exec(i);if(!a)return I("Retrofit --capability is invalid.");let o=await ge(Ae(a[1],a[2])),s=n.values.profile??"workspace-root";if(o.release.consumerProfile!==s)return I("Retrofit profile and capability are incompatible.");let c=new Date,d=s==="workspace-root"?await qu({projectRoot:n.values.project,capabilityIntegrity:o.release.integrity,generatedAt:c.toISOString(),expiresAt:new Date(c.getTime()+1800*1e3).toISOString(),...n.values["documentation-only"]===!0?{documentationOnly:!0}:{}}):await Mu({projectRoot:n.values.project,manifest:{schemaVersion:1,profile:{id:s,parameters:{}},capabilities:[{capabilityId:a[1],version:a[2]}]},capabilityIntegrity:o.release.integrity,generatedAt:c.toISOString(),expiresAt:new Date(c.getTime()+1800*1e3).toISOString()}),l=Y(d.projectRoot);if(t==="plan"){if(n.values.approve!==void 0)return I("Retrofit plan does not accept --approve.");let f=await pr({projectRoot:d.projectRoot,plan:d.plan,now:c.toISOString()});return{outputMode:F(e),human:`Project: ${l}
|
|
112
115
|
Plan: ${f.planId}
|
|
113
116
|
State: ${f.state}
|
|
114
117
|
Files: project-capabilities.json
|
|
115
|
-
Next: dyyto retrofit apply --project ${l} --approve ${f.planId}${n.values["documentation-only"]===!0?" --documentation-only":""}`,value:{schemaVersion:1,ok:!0,command:"retrofit-plan",result:{project:l,plan:f}}}}if(typeof n.values.approve!="string")return I("Retrofit apply requires --approve <planId>.");let p=await Fn({projectRoot:d.projectRoot,planId:n.values.approve}),m=await
|
|
118
|
+
Next: dyyto retrofit apply --project ${l} --approve ${f.planId}${n.values["documentation-only"]===!0?" --documentation-only":""}`,value:{schemaVersion:1,ok:!0,command:"retrofit-plan",result:{project:l,plan:f}}}}if(typeof n.values.approve!="string")return I("Retrofit apply requires --approve <planId>.");let p=await Fn({projectRoot:d.projectRoot,planId:n.values.approve}),m=await Gr({projectRoot:d.projectRoot,plan:p,approvedPlanId:n.values.approve,desiredContents:d.desiredContents,now:c.toISOString()}),u=await Jr(m);return{outputMode:F(e),human:`Project: ${l}
|
|
116
119
|
Plan: ${p.planId}
|
|
117
120
|
State: ${u.state}
|
|
118
|
-
Files applied: ${u.operations.length}`,value:{schemaVersion:1,ok:!0,command:"retrofit-apply",result:{project:l,planId:p.planId,transaction:u}}}}async function
|
|
121
|
+
Files applied: ${u.operations.length}`,value:{schemaVersion:1,ok:!0,command:"retrofit-apply",result:{project:l,planId:p.planId,transaction:u}}}}async function yA(e,t){let r;try{r=oe({args:[...t],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"}}})}catch{return I(`${e} arguments are invalid.`)}if(typeof r.values.project!="string")return I(`${e} requires --project.`);let n=await pt(N.resolve(r.values.project)),i=G(JSON.parse(await te(N.join(n,"project-capabilities.json"),"utf8")));if(i.template===void 0)return I("The project does not declare an engineering template.");let a=await li(Qa(i.template.id,i.template.version)),o=a.commands[e];if(o===void 0)return I(`Template ${a.templateId} does not support ${e}.`);let s=o==="npm.pack-dry-run"?["pnpm","pack","--dry-run"]:["pnpm","run",o],c=Date.now();if(e==="dev"){if(await new Promise((u,f)=>{let g=uA("corepack",s,{cwd:n,env:{...process.env,NO_COLOR:"1"},stdio:"inherit"}),h=()=>g.kill("SIGINT"),w=()=>g.kill("SIGTERM");process.once("SIGINT",h),process.once("SIGTERM",w),g.once("error",f),g.once("close",_=>{process.off("SIGINT",h),process.off("SIGTERM",w),u(_??1)})})!==0)throw new xe({code:"CLI_INTERNAL_ERROR",message:"The development server stopped with an error.",exitCode:1});let m={template:`${a.templateId}@${a.version}`,command:o,durationMs:Date.now()-c,stdout:""};return{outputMode:F(t),human:`dev completed for '${Y(n)}'.`,value:{schemaVersion:1,ok:!0,command:e,result:m}}}let d=await Km("corepack",s,{cwd:n,env:{...process.env,NO_COLOR:"1"},timeout:3e5,maxBuffer:4*1024*1024}),l={template:`${a.templateId}@${a.version}`,command:o,durationMs:Date.now()-c,stdout:d.stdout.trim()};return{outputMode:F(t),human:`${e} completed for '${Y(n)}'.`,value:{schemaVersion:1,ok:!0,command:e,result:l}}}async function wA(e){let t;try{t=oe({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},workspace:{type:"string"},path:{type:"string"},name:{type:"string"},version:{type:"string"},license:{type:"string"},"publish-access":{type:"string"},repository:{type:"string"},capability:{type:"string"},kind:{type:"string"},profile:{type:"string"}}})}catch{return I("Add package arguments are invalid.")}if([t.values.workspace,t.values.path,t.values.name,t.values.version,t.values.license,t.values["publish-access"],t.values.repository].some(_=>typeof _!="string"))return I("Add package requires workspace, path, name, version, license, publish access, and repository.");let n=t.values.profile??"workspace-npm-package";if(n!=="workspace-npm-package"&&n!=="react-component-library")return I("Add package requires a supported --profile.");let i=n==="react-component-library"?fi["workspace-react-component-library"]:fi["workspace-npm-package"];if(t.values.capability!==i)return I(`Add package requires --capability ${i}.`);if(t.values.kind!==void 0&&t.values.kind!=="fixture")return I("Add package --kind only accepts fixture.");let a=t.values.kind==="fixture"?"fixture":"package",o=String(t.values.path),s=Sm(o,a);if(s!==void 0)return I(s);let c=await pt(N.resolve(String(t.values.workspace))),d=JSON.parse(await te(N.join(c,"project-capabilities.json"),"utf8"));if(d.profile?.id!=="workspace-root")return I("The selected directory is not a Dyyto workspace root.");let l=d.capabilities?.[0];if(l?.capabilityId!=="foundation.workspace-root")return I("Workspace root capability is invalid.");let p=await Se(c);if(p===null){let _=await ge(Ae(l.capabilityId,l.version)),b=new Date;if((await na({projectRoot:c,release:_,generatedAt:b.toISOString(),expiresAt:new Date(b.getTime()+1800*1e3).toISOString()})).state!=="applied-unverified")return I("Workspace root must be applied before adding a package.")}if(p!==null){try{await sr({projectRoot:c,expectedAssets:Hm(p)})}catch{return I("Workspace root locked assets have drifted; adding a package is blocked.")}if((await oi({projectRoot:c,lock:p})).some(b=>b.code!=="EVIDENCE_VALID"))return I("Workspace root adoption evidence is invalid; adding a package is blocked.")}if(await Ka(c,a==="fixture"?"fixtures":"packages",String(t.values.name)))return I("A workspace package already uses this npm name.");let[m,u]=i.split("@"),f={schemaVersion:1,...Za[n]===void 0?{}:{template:Za[n]},profile:{id:n,parameters:{name:String(t.values.name),version:String(t.values.version),license:String(t.values.license),publishAccess:String(t.values["publish-access"]),repository:String(t.values.repository)}},capabilities:[{capabilityId:m,version:u}]};Ft(G(f),n);let g=await va({projectRoot:N.join(c,...o.split("/")),manifest:f}),h=await eo(g.projectRoot),w=Y(g.projectRoot);return{outputMode:F(e),human:`Workspace package '${o}' initialized.
|
|
119
122
|
Plan: ${h.planId}
|
|
120
123
|
State: ${h.state}
|
|
121
|
-
Next: dyyto apply --project ${w} --approve ${h.planId}`,value:{schemaVersion:1,ok:!0,command:"add-package",result:{project:w,workspace:
|
|
124
|
+
Next: dyyto apply --project ${w} --approve ${h.planId}`,value:{schemaVersion:1,ok:!0,command:"add-package",result:{project:w,workspace:Y(c),path:o,plan:h}}}}async function vA(e){let t;try{t=oe({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},workspace:{type:"string"},path:{type:"string"},name:{type:"string"},profile:{type:"string"},capability:{type:"string"}}})}catch{return I("Add application arguments are invalid.")}if([t.values.workspace,t.values.path,t.values.name].some(w=>typeof w!="string"))return I("Add application requires workspace, path, and name.");let r=t.values.profile??"workspace-node-application";if(r!=="workspace-node-application"&&r!=="workspace-web-application"&&r!=="workspace-expo-application"&&r!=="nextjs-full-stack-application")return I("Add application requires a supported --profile.");let n=r,i=fi[n],a=String(t.values.path),o=jm(a,n,typeof t.values.capability=="string"?t.values.capability:void 0);if(o!==void 0)return I(o);let s=await pt(N.resolve(String(t.values.workspace))),c=JSON.parse(await te(N.join(s,"project-capabilities.json"),"utf8"));if(c.profile?.id!=="workspace-root")return I("The selected directory is not a Dyyto workspace root.");let d=c.capabilities?.[0];if(d?.capabilityId!=="foundation.workspace-root"||!["1.1.0","1.2.0","1.3.0","1.4.0","1.5.0"].includes(d.version))return I("Workspace applications require a supported foundation.workspace-root release.");if(a.startsWith("services/")&&!["1.3.0","1.4.0","1.5.0"].includes(d.version))return I("Workspace service applications require foundation.workspace-root@1.3.0 or newer.");let l=await Se(s);if(l===null){let w=await ge(Ae(d.capabilityId,d.version)),_=new Date;if((await na({projectRoot:s,release:w,generatedAt:_.toISOString(),expiresAt:new Date(_.getTime()+1800*1e3).toISOString()})).state!=="applied-unverified")return I("Workspace root must be applied before adding an application.")}if(l!==null){try{await sr({projectRoot:s,expectedAssets:Hm(l)})}catch{return I("Workspace root locked assets have drifted; adding an application is blocked.")}if((await oi({projectRoot:s,lock:l})).some(_=>_.code!=="EVIDENCE_VALID"))return I("Workspace root adoption evidence is invalid; adding an application is blocked.")}if(await $m(s,String(t.values.name)))return I("A workspace application already uses this name.");let[p,m]=i.split("@"),u={schemaVersion:1,...Za[n]===void 0?{}:{template:Za[n]},profile:{id:n,parameters:{name:String(t.values.name)}},capabilities:[{capabilityId:p,version:m}]};fr(G(u));let f=await va({projectRoot:N.join(s,...a.split("/")),manifest:u}),g=await eo(f.projectRoot),h=Y(f.projectRoot);return{outputMode:F(e),human:`Workspace application '${a}' initialized.
|
|
122
125
|
Plan: ${g.planId}
|
|
123
126
|
State: ${g.state}
|
|
124
|
-
Next: dyyto apply --project ${h} --approve ${g.planId}`,value:{schemaVersion:1,ok:!0,command:"add-application",result:{project:h,workspace:
|
|
127
|
+
Next: dyyto apply --project ${h} --approve ${g.planId}`,value:{schemaVersion:1,ok:!0,command:"add-application",result:{project:h,workspace:Y(s),path:a,plan:g}}}}async function Qm(e,t){let r;try{r=oe({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},capability:{type:"string"},channel:{type:"string"},"artifact-workspace":{type:"string"},"artifact-bundle":{type:"string"},"artifact-fallback-bundle":{type:"string",multiple:!0},"artifact-port":{type:"string"}}})}catch{return I("Add feature arguments are invalid.")}if(typeof r.values.project!="string"||typeof r.values.capability!="string")return I("Add feature requires --project and --capability.");if(r.values.channel!==void 0&&r.values.channel!=="development")return I("--channel only accepts development; omit it for production.");let n=await pt(N.resolve(r.values.project)),i=JSON.parse(await te(N.join(n,"project-capabilities.json"),"utf8")),a=await Se(n);if(a===null)return I("Add feature requires an adopted project with a verified Profile Lock.");let[o,s]=to(r.values.capability),c=await ge(Ae(o,s)),d=new Date,l;try{let u=await Xa(n,c,t);l=await tl({projectRoot:n,manifest:i,release:c,currentLock:a,generatedAt:d.toISOString(),expiresAt:new Date(d.getTime()+1800*1e3).toISOString(),...r.values.channel==="development"?{packageChannel:"development"}:{},...u===void 0?{}:{packageSource:u}})}catch(u){throw u instanceof ae?new xe({code:u.code,message:u.message,exitCode:3,nextStep:"Review the selected project Profile and current capabilities."}):u}let p=await pr({projectRoot:n,plan:l.plan,now:d.toISOString(),transactionRoot:l.transactionRoot}),m=Y(n);return{outputMode:F(e),human:`Project: ${m}
|
|
125
128
|
Feature: ${o}@${s}
|
|
126
129
|
Dependency: ${l.dependency.profile} satisfied
|
|
127
130
|
Plan: ${p.planId}
|
|
128
131
|
State: ${p.state}
|
|
129
|
-
Next: dyyto apply --project ${m} --approve ${p.planId}`,value:{schemaVersion:1,ok:!0,command:"add-feature",result:{project:m,capability:r.values.capability,dependency:l.dependency,plan:p}}}}async function
|
|
132
|
+
Next: dyyto apply --project ${m} --approve ${p.planId}`,value:{schemaVersion:1,ok:!0,command:"add-feature",result:{project:m,capability:r.values.capability,dependency:l.dependency,plan:p}}}}async function IA(e,t){let r;try{r=oe({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},capability:{type:"string"},"artifact-workspace":{type:"string"},"artifact-bundle":{type:"string"},"artifact-port":{type:"string"}}})}catch{return I("Remove feature arguments are invalid.")}if(typeof r.values.project!="string"||typeof r.values.capability!="string")return I("Remove feature requires --project and --capability.");let n=await pt(N.resolve(r.values.project)),i=await Se(n);if(i===null)return I("Remove feature requires a verified Lock.");let[a,o]=to(r.values.capability),s=await ge(Ae(a,o)),c=await Zm(n,s,i,t),d=await pr({projectRoot:n,plan:c.plan,now:new Date().toISOString(),..."transactionRoot"in c?{transactionRoot:c.transactionRoot}:{}}),l=Y(n);return{outputMode:F(e),human:`Project: ${l}
|
|
130
133
|
\u79FB\u9664\u80FD\u529B\uFF1A${a}@${o}
|
|
131
134
|
\u72EC\u5360\u5305\uFF1A${c.removedSources.map(p=>`${p.packageName}@${p.version}`).join("\u3001")||"\u65E0\uFF08\u5171\u4EAB\u5305\u5C06\u4FDD\u7559\uFF09"}
|
|
132
135
|
Plan: ${d.planId}
|
|
133
136
|
State: ${d.state}
|
|
134
|
-
Next: dyyto apply --project ${l} --approve ${d.planId}`,value:{schemaVersion:1,ok:!0,command:"remove-feature",result:{project:l,capability:r.values.capability,removedSources:c.removedSources,plan:d}}}}async function
|
|
137
|
+
Next: dyyto apply --project ${l} --approve ${d.planId}`,value:{schemaVersion:1,ok:!0,command:"remove-feature",result:{project:l,capability:r.values.capability,removedSources:c.removedSources,plan:d}}}}async function bA(e){let t;try{t=oe({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"}}})}catch{return I("Plan arguments are invalid.")}if(typeof t.values.project!="string")return I("Plan requires --project <directory>.");let r=N.resolve(t.values.project),n=await eo(r),i=Y(r),a=n.state==="reviewable"?`Next: dyyto apply --project ${i} --approve ${n.planId}`:"Resolve the reported conflicts before applying.";return{outputMode:F(e),human:`Project: ${i}
|
|
135
138
|
Plan: ${n.planId}
|
|
136
139
|
State: ${n.state}
|
|
137
|
-
${a}`,value:{schemaVersion:1,ok:!0,command:"plan",result:{project:i,plan:n}}}}function to(e){let t=e.lastIndexOf("@");return t<=0||t===e.length-1?I("Capability selection must be capabilityId@version."):[e.slice(0,t),e.slice(t+1)]}async function
|
|
140
|
+
${a}`,value:{schemaVersion:1,ok:!0,command:"plan",result:{project:i,plan:n}}}}function to(e){let t=e.lastIndexOf("@");return t<=0||t===e.length-1?I("Capability selection must be capabilityId@version."):[e.slice(0,t),e.slice(t+1)]}async function kA(e){let t;try{t=oe({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},capability:{type:"string"}}})}catch{return I("Baseline arguments are invalid.")}if(typeof t.values.project!="string"||typeof t.values.capability!="string")return I("Baseline requires --project and --capability.");let r=N.resolve(t.values.project);if(await Se(r)!==null)return I("Baseline is only for a historical project without a Lock.");let[n,i]=to(t.values.capability),a=await ge(Ae(n,i)),o=JSON.parse(await te(N.join(r,"project-capabilities.json"),"utf8")),s=new Date,c=await Cc({projectRoot:r,manifest:o,release:a,generatedAt:s.toISOString(),expiresAt:new Date(s.getTime()+1800*1e3).toISOString()}),d=await pr({projectRoot:r,plan:c.plan,now:s.toISOString()}),l=Y(r);return{outputMode:F(e),human:`Project: ${l}
|
|
138
141
|
Baseline: ${n}@${i}
|
|
139
142
|
Plan: ${d.planId}
|
|
140
143
|
State: ${d.state}
|
|
141
144
|
Preserved seed files: ${d.operations.filter(p=>p.ownership==="seed-file"&&p.disposition==="noop").length}
|
|
142
|
-
Next: dyyto apply --project ${l} --approve ${d.planId}`,value:{schemaVersion:1,ok:!0,command:"baseline",result:{project:l,plan:d}}}}async function
|
|
145
|
+
Next: dyyto apply --project ${l} --approve ${d.planId}`,value:{schemaVersion:1,ok:!0,command:"baseline",result:{project:l,plan:d}}}}async function _A(e,t){let r;try{r=oe({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},to:{type:"string"},repository:{type:"string"},channel:{type:"string"},"artifact-workspace":{type:"string"},"artifact-bundle":{type:"string"},"artifact-port":{type:"string"}}})}catch{return I("Upgrade arguments are invalid.")}if(typeof r.values.project!="string"||typeof r.values.to!="string")return I("Upgrade requires --project <directory> and --to <capabilityId@version>.");if(r.values.channel!==void 0&&r.values.channel!=="development")return I("--channel only accepts development; omit it for production.");let n=N.resolve(r.values.project),i=JSON.parse(await te(N.join(n,"project-capabilities.json"),"utf8")),[a,o]=to(r.values.to),s=i.capabilities?.find(k=>k.capabilityId===a);if(s===void 0)return I(`Upgrade requires ${a} to be adopted by the project.`);let c=await Se(n);if(c===null)return I("Upgrade requires an adopted project with a verified Lock.");let d=(i.profile.id==="standalone-npm-package"||i.profile.id==="workspace-npm-package")&&o==="1.1.0";if(d){if(typeof r.values.repository!="string")return I("npm package upgrade to 1.1.0 requires --repository.");i={...i,profile:{...i.profile,parameters:{...i.profile.parameters,repository:r.values.repository}}}}else if(r.values.repository!==void 0)return I("--repository is only valid for an npm package upgrade to 1.1.0.");let l=await ge(Ae(s.capabilityId,s.version)),p=await ge(Ae(a,o)),m={...i,capabilities:i.capabilities.map(k=>k.capabilityId===a?{capabilityId:a,version:o}:k)},u=p.release.schemaVersion===2&&p.release.availability.maturity!=="withdrawn"&&p.release.packageSources.length>0,f=u?Ma(m,p):void 0,g=u?await Xa(n,p,t,f):void 0,h=Ym(a,o),w=new Date,_=await Bc({projectRoot:n,manifest:i,currentLock:c,sourceRelease:l,targetRelease:p,...h===void 0?{}:{targetTemplate:h},generatedAt:w.toISOString(),expiresAt:new Date(w.getTime()+1800*1e3).toISOString(),...r.values.channel==="development"?{packageChannel:"development"}:{},...g===void 0?{}:{packageSource:g}}),b=await pr({projectRoot:n,plan:_.plan,now:w.toISOString(),transactionRoot:_.transactionRoot}),A=Y(n),y=b.state==="reviewable"?`Next: dyyto apply --project ${A} --approve ${b.planId}${d?` --repository ${r.values.repository}`:""}`:"Resolve the reported conflicts before applying.";return{outputMode:F(e),human:`Project: ${A}
|
|
143
146
|
Upgrade: ${s.version} -> ${o}
|
|
144
147
|
Plan: ${b.planId}
|
|
145
148
|
State: ${b.state}
|
|
146
|
-
${y}`,value:{schemaVersion:1,ok:!0,command:"upgrade",result:{project:A,source:`${s.capabilityId}@${s.version}`,target:r.values.to,plan:b}}}}async function
|
|
149
|
+
${y}`,value:{schemaVersion:1,ok:!0,command:"upgrade",result:{project:A,source:`${s.capabilityId}@${s.version}`,target:r.values.to,plan:b}}}}async function ll(e,t){let r;try{r=oe({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},approve:{type:"string"},repository:{type:"string"},"artifact-workspace":{type:"string"},"artifact-bundle":{type:"string"},"artifact-fallback-bundle":{type:"string",multiple:!0},"artifact-port":{type:"string"}}})}catch{return I("Apply arguments are invalid.")}if(typeof r.values.project!="string")return I("Apply requires --project <directory>.");if(typeof r.values.approve!="string")return I("Apply requires --approve <planId>.");let n=N.resolve(r.values.project),i=JSON.parse(await te(N.join(n,"project-capabilities.json"),"utf8")),a=i.capabilities?.[0];if(a===void 0)return I("Project manifest must select one capability.");let o=await Fn({projectRoot:n,planId:r.values.approve}),s=new Date,c,d,l;if(o.action==="remove"){let u=await Se(n);if(u===null)return I("Remove apply requires the verified Lock.");let f=await Zm(n,await ge(Ae(o.capability.capabilityId,o.capability.version)),u,t);c=f,d="registryConfigs"in f?f.registryConfigs:void 0,l="endpointBindings"in f?f.endpointBindings:void 0}else if(o.action==="upgrade"){let u=await Se(n),f=u?.capabilities.find(y=>y.capabilityId===o.capability.capabilityId);if(u===null||f===void 0)return I("Upgrade apply requires the verified source Lock.");if((f.consumerProfile==="standalone-npm-package"||f.consumerProfile==="workspace-npm-package")&&o.capability.version==="1.1.0"){if(typeof r.values.repository!="string")return I("npm package upgrade apply requires the approved --repository value.");i={...i,profile:{...i.profile,parameters:{...i.profile.parameters,repository:r.values.repository}}}}else if(r.values.repository!==void 0)return I("--repository is not valid for this apply operation.");let g=await ge(Ae(o.capability.capabilityId,o.capability.version)),h={...i,capabilities:i.capabilities.map(y=>y.capabilityId===o.capability.capabilityId?{capabilityId:o.capability.capabilityId,version:o.capability.version}:y)},w=g.release.schemaVersion===2&&g.release.availability.maturity!=="withdrawn"&&g.release.packageSources.length>0,_=w?Ma(h,g):void 0,b=w?await Xa(n,g,t,_):void 0;d=b?.registryConfigs,l=b?.endpointBindings;let A=Ym(o.capability.capabilityId,o.capability.version);c=await Bc({projectRoot:n,manifest:i,currentLock:u,sourceRelease:await ge(Ae(f.capabilityId,f.version)),targetRelease:g,...A===void 0?{}:{targetTemplate:A},generatedAt:s.toISOString(),expiresAt:new Date(s.getTime()+1800*1e3).toISOString(),...o.packageAdoption?.sourceChannel==="development"?{packageChannel:"development"}:{},...b===void 0?{}:{packageSource:b}})}else if(o.action==="adopt"&&i.profile?.id==="nextjs-full-stack-application"&&i.capabilities?.[0]?.capabilityId===o.capability.capabilityId&&i.capabilities?.[0]?.version!==o.capability.version)c=await Cc({projectRoot:n,manifest:i,release:await ge(Ae(o.capability.capabilityId,o.capability.version)),generatedAt:s.toISOString(),expiresAt:new Date(s.getTime()+1800*1e3).toISOString()});else if(i.capabilities?.some(u=>u.capabilityId===o.capability.capabilityId&&u.version===o.capability.version)){let u=await ge(Ae(a.capabilityId,a.version)),f=await Se(n).catch(()=>null);c=await(i.profile?.id==="standalone-npm-package"?Bn:i.profile?.id==="react-component-library"?Gn:i.profile?.id==="nextjs-full-stack-application"?Yr:i.profile?.id==="workspace-npm-package"?Jn:i.profile?.id==="workspace-node-application"?Wn:i.profile?.id==="workspace-web-application"?Kn:i.profile?.id==="workspace-expo-application"?Yn:ia)({projectRoot:n,manifest:i,release:u,...f===null?{}:{currentLock:f},generatedAt:s.toISOString(),expiresAt:new Date(s.getTime()+1800*1e3).toISOString()})}else{let u=await Se(n);if(u===null)return I("Feature apply requires the verified Profile Lock.");let f=await ge(Ae(o.capability.capabilityId,o.capability.version)),g=await Xa(n,f,t);d=g?.registryConfigs,l=g?.endpointBindings,c=await tl({projectRoot:n,manifest:i,release:f,currentLock:u,generatedAt:s.toISOString(),expiresAt:new Date(s.getTime()+1800*1e3).toISOString(),...o.packageAdoption?.sourceChannel==="development"?{packageChannel:"development"}:{},...g===void 0?{}:{packageSource:g}})}let p;if(o.packageAdoption!==void 0){if(d===void 0)throw new ae("CAPABILITY_RELEASE_VERSION_UNSUPPORTED","Package adoption requires a trusted Package Source Provider");let{createPnpmPackageManagerPort:u}=await import("./optional-runtime.js");if(l===void 0)throw new ae("CAPABILITY_RELEASE_VERSION_UNSUPPORTED","Package adoption requires Endpoint Bindings");p=await ff({projectRoot:c.transactionRoot??n,plan:o,approvedPlanId:r.values.approve,desiredContents:c.desiredContents,now:new Date().toISOString(),packageManager:u({registries:d,endpointBindings:l,...t.packageStoreRoot===void 0?{}:{storeRoot:t.packageStoreRoot}})})}else{let u=await Gr({projectRoot:n,plan:o,approvedPlanId:r.values.approve,desiredContents:c.desiredContents,now:new Date().toISOString()});p=await Jr(u)}let m=Y(n);return{outputMode:F(e),human:`Project: ${m}
|
|
147
150
|
Plan: ${o.planId}
|
|
148
151
|
State: ${p.state}
|
|
149
152
|
Files applied: ${p.operations.length}
|
|
150
|
-
`+(o.packageAdoption===void 0?`Next: cd ${m} && corepack pnpm install`:`Next: dyyto verify --project ${m}`),value:{schemaVersion:1,ok:!0,command:"apply",result:{project:m,planId:o.planId,transaction:p}}}}async function
|
|
153
|
+
`+(o.packageAdoption===void 0?`Next: cd ${m} && corepack pnpm install`:`Next: dyyto verify --project ${m}`),value:{schemaVersion:1,ok:!0,command:"apply",result:{project:m,planId:o.planId,transaction:p}}}}async function EA(e,t){let r;try{r=oe({args:[...e],allowPositionals:!0,strict:!0,options:{json:{type:"boolean"},output:{type:"string"},locale:{type:"string"},channel:{type:"string"},approve:{type:"string"},"recipe-version":{type:"string"},"artifact-workspace":{type:"string"},"artifact-bundle":{type:"string"},"artifact-fallback-bundle":{type:"string",multiple:!0},"artifact-port":{type:"string"}}})}catch{return I("Scaffold example arguments are invalid.")}if(r.positionals.length!==1||typeof r.values.output!="string"||r.values.locale!=="zh-CN"||r.values.channel!=="development"||typeof r.values["recipe-version"]!="string"||typeof r.values["artifact-workspace"]!="string"||typeof r.values["artifact-bundle"]!="string"||typeof r.values["artifact-port"]!="string")return I("Scaffold example requires recipe, --recipe-version, --output, --locale zh-CN, --channel development and exact Artifact source arguments.");let n=r.positionals[0];if(typeof n!="string")return I("Scaffold example recipe identifier is invalid.");let i=await um(gA(n,r.values["recipe-version"])),a=Number(r.values["artifact-port"]),o=r.values["artifact-workspace"],s=r.values["artifact-bundle"],c=r.values["artifact-fallback-bundle"],d=Array.isArray(c)?c.filter(u=>typeof u=="string"):[],l=r.values.approve;if(l===void 0){let u=await Vm({workspaceRoot:o,output:r.values.output,recipe:i,artifactBundle:s,artifactFallbackBundles:d,artifactPort:a});return{outputMode:F(e),human:`\u793A\u4F8B\uFF1A${i.title}
|
|
151
154
|
Plan\uFF1A${u.planId}
|
|
152
155
|
\u72B6\u6001\uFF1A\u7B49\u5F85\u9636\u6BB5\u6279\u51C6
|
|
153
|
-
Next\uFF1A\u91CD\u590D\u672C\u547D\u4EE4\u5E76\u6DFB\u52A0 --approve ${u.planId}`,value:{schemaVersion:1,ok:!0,command:"scaffold-example-plan",result:{plan:u}}}}if(typeof l!="string")return I("Scaffold example --approve must be an exact Plan ID.");let p=["--artifact-workspace",o,"--artifact-bundle",s,...d.flatMap(u=>["--artifact-fallback-bundle",u]),"--artifact-port",String(a)],m;try{m=await Mm({workspaceRoot:o,approvedPlanId:l,recipe:i,execute:async(u,f)=>{if(f.artifactBundle!==s||JSON.stringify(f.artifactFallbackBundles)!==JSON.stringify(d)||f.artifactPort!==a)throw new Error("SCAFFOLD_SOURCE_PLAN_MISMATCH");let g=[],w=(await Xm([u,"--profile","nextjs-full-stack-application","--capability",`${i.rootProfile.capabilityId}@${i.rootProfile.version}`,"--name",i.recipeId])).value.result.plan.planId;await
|
|
156
|
+
Next\uFF1A\u91CD\u590D\u672C\u547D\u4EE4\u5E76\u6DFB\u52A0 --approve ${u.planId}`,value:{schemaVersion:1,ok:!0,command:"scaffold-example-plan",result:{plan:u}}}}if(typeof l!="string")return I("Scaffold example --approve must be an exact Plan ID.");let p=["--artifact-workspace",o,"--artifact-bundle",s,...d.flatMap(u=>["--artifact-fallback-bundle",u]),"--artifact-port",String(a)],m;try{m=await Mm({workspaceRoot:o,approvedPlanId:l,recipe:i,execute:async(u,f)=>{if(f.artifactBundle!==s||JSON.stringify(f.artifactFallbackBundles)!==JSON.stringify(d)||f.artifactPort!==a)throw new Error("SCAFFOLD_SOURCE_PLAN_MISMATCH");let g=[],w=(await Xm([u,"--profile","nextjs-full-stack-application","--capability",`${i.rootProfile.capabilityId}@${i.rootProfile.version}`,"--name",i.recipeId])).value.result.plan.planId;await ll(["--project",u,"--approve",w],t),g.push(w),await Km("corepack",["pnpm","install","--no-frozen-lockfile","--ignore-scripts"],{cwd:u,env:{...process.env,CI:"true",NO_COLOR:"1",pnpm_config_store_dir:N.join(o,".dyyto","resolution-worker","store","shared")},timeout:3e5,maxBuffer:4*1024*1024}),await dl(["--project",u]);for(let _ of i.capabilities){let b=`${_.capabilityId}@${_.version}`;try{let y=(await Qm(["--project",u,"--capability",b,"--channel",_.channel,...p],t)).value.result.plan.planId;await ll(["--project",u,"--approve",y,...p],t),await dl(["--project",u]),g.push(y)}catch(A){throw new Error(`SCAFFOLD_CAPABILITY_FAILED:${b}:${A instanceof Error?A.message:"UNKNOWN"}`,{cause:A})}}return g}})}catch(u){let f=u instanceof ze&&u.cause instanceof Error?u.cause.message:"SCAFFOLD_APPLY_FAILED";throw new xe({code:"SCAFFOLD_APPLY_FAILED",message:`\u793A\u4F8B\u811A\u624B\u67B6\u6267\u884C\u5931\u8D25\uFF1A${f}`,exitCode:1,nextStep:"\u68C0\u67E5\u5931\u8D25\u7684 Capability \u4E0E\u4E8B\u52A1 Evidence\uFF0C\u4FEE\u590D\u540E\u91CD\u65B0\u751F\u6210 Plan\u3002"})}return{outputMode:F(e),human:`\u793A\u4F8B\u5DF2\u751F\u6210\uFF1A${N.relative(process.cwd(),m.output)}
|
|
154
157
|
Evidence\uFF1A${m.evidenceId}
|
|
155
|
-
\u72B6\u6001\uFF1Aadopted`,value:{schemaVersion:1,ok:!0,command:"scaffold-example-apply",result:m}}}function mi(e,t){let r;try{r=oe({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"}}})}catch{return I(`${t} arguments are invalid.`)}return typeof r.values.project!="string"?I(`${t} requires --project <directory>.`):{projectRoot:N.resolve(r.values.project),outputMode:F(e)}}async function
|
|
158
|
+
\u72B6\u6001\uFF1Aadopted`,value:{schemaVersion:1,ok:!0,command:"scaffold-example-apply",result:m}}}function mi(e,t){let r;try{r=oe({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"}}})}catch{return I(`${t} arguments are invalid.`)}return typeof r.values.project!="string"?I(`${t} requires --project <directory>.`):{projectRoot:N.resolve(r.values.project),outputMode:F(e)}}async function dl(e){let{projectRoot:t,outputMode:r}=mi(e,"Verify"),n=JSON.parse(await te(N.join(t,"project-capabilities.json"),"utf8")),i=await Se(t),a=await Kr(t).catch(()=>{}),o;try{let h=i?.capabilities.map(_=>_.appliedPlanId)??[],w=i?.capabilities.map(_=>_.capabilityId)??[];try{o=await Ia(t,h,t,w)}catch(_){if(!(_ instanceof he)||_.code!=="PLAN_NOT_FOUND"||a===void 0)throw _;o=await Ia(t,h,a.transactionRoot,w)}}catch(h){if(!(h instanceof he)||h.code!=="PLAN_NOT_FOUND"||i===null)throw h;let _=(await pl(["--project",t,"--json"])).value.result,b=await oi({projectRoot:t,lock:i});if(_.state!=="adopted"||b.some(y=>y.code!=="EVIDENCE_VALID"))throw new xe({code:"VERIFICATION_STATE_INVALID",message:"The adopted project has drifted or its verification evidence is invalid.",exitCode:4,nextStep:"Run dyyto inspect and dyyto doctor before creating a new plan."});let A=Y(t);return{outputMode:r,human:`Project: ${A}
|
|
156
159
|
State: adopted
|
|
157
|
-
Verification: already committed`,value:{schemaVersion:1,ok:!0,command:"verify",result:{project:A,state:"adopted",reused:!0,lock:i}}}}let s=await ge(Ae(o.capability.capabilityId,o.capability.version)),c=o.packageAdoption===void 0?void 0:a?.transactionRoot;if(i?.capabilities.some(h=>h.appliedPlanId===o.planId)){let h=
|
|
160
|
+
Verification: already committed`,value:{schemaVersion:1,ok:!0,command:"verify",result:{project:A,state:"adopted",reused:!0,lock:i}}}}let s=await ge(Ae(o.capability.capabilityId,o.capability.version)),c=o.packageAdoption===void 0?void 0:a?.transactionRoot;if(i?.capabilities.some(h=>h.appliedPlanId===o.planId)){let h=Y(t);return{outputMode:r,human:`Project: ${h}
|
|
158
161
|
State: adopted
|
|
159
|
-
Verification: already committed`,value:{schemaVersion:1,ok:!0,command:"verify",result:{project:h,state:"adopted",reused:!0}}}}if(o.action==="remove"){if(i===null)return I("Remove verification requires the previous verified Lock.");let h=i.capabilities.find($=>$.capabilityId===o.capability.capabilityId&&$.version===o.capability.version);if(h===void 0){let $=
|
|
162
|
+
Verification: already committed`,value:{schemaVersion:1,ok:!0,command:"verify",result:{project:h,state:"adopted",reused:!0}}}}if(o.action==="remove"){if(i===null)return I("Remove verification requires the previous verified Lock.");let h=i.capabilities.find($=>$.capabilityId===o.capability.capabilityId&&$.version===o.capability.version);if(h===void 0){let $=Y(t);return{outputMode:r,human:`Project: ${$}
|
|
160
163
|
State: removed
|
|
161
|
-
Verification: already committed`,value:{schemaVersion:1,ok:!0,command:"verify",result:{project:$,state:"removed",reused:!0,lock:i}}}}let w=o.packageAdoption?.schemaVersion===2&&o.packageAdoption.topology.mode==="pnpm-shared-lockfile"?`${o.packageAdoption.topology.unitRelativeRoot}/`:"",_=new Map(o.operations.flatMap($=>$.desiredDigest===void 0||!$.path.startsWith(w)?[]:[[$.path.slice(w.length),$.desiredDigest]])),b=i.capabilities.filter($=>$!==h),A=[...b].filter($=>$.packageAdoption!==void 0).sort(($,P)=>$.committedAt.localeCompare(P.committedAt)).at(-1)?.packageAdoption,y=b.flatMap($=>$.assets).map($=>({...$,digest:_.get($.path)??($.path==="package.json"?A?.packageJsonDigest:void 0)??$.digest})),{executeRemovalVerification:k}=await import("./optional-runtime.js"),S=await k({projectRoot:t,release:s,remainingAssets:y,removedPaths:h.assets.map($=>$.path)}),O=await Ac({projectRoot:t,...c===void 0?{}:{transactionRoot:c},plan:o,release:s.release,verificationResults:S.results,committedAt:new Date().toISOString(),previousLock:i,expectedAssets:y}),se=
|
|
164
|
+
Verification: already committed`,value:{schemaVersion:1,ok:!0,command:"verify",result:{project:$,state:"removed",reused:!0,lock:i}}}}let w=o.packageAdoption?.schemaVersion===2&&o.packageAdoption.topology.mode==="pnpm-shared-lockfile"?`${o.packageAdoption.topology.unitRelativeRoot}/`:"",_=new Map(o.operations.flatMap($=>$.desiredDigest===void 0||!$.path.startsWith(w)?[]:[[$.path.slice(w.length),$.desiredDigest]])),b=i.capabilities.filter($=>$!==h),A=[...b].filter($=>$.packageAdoption!==void 0).sort(($,P)=>$.committedAt.localeCompare(P.committedAt)).at(-1)?.packageAdoption,y=b.flatMap($=>$.assets).map($=>({...$,digest:_.get($.path)??($.path==="package.json"?A?.packageJsonDigest:void 0)??$.digest})),{executeRemovalVerification:k}=await import("./optional-runtime.js"),S=await k({projectRoot:t,release:s,remainingAssets:y,removedPaths:h.assets.map($=>$.path)}),O=await Ac({projectRoot:t,...c===void 0?{}:{transactionRoot:c},plan:o,release:s.release,verificationResults:S.results,committedAt:new Date().toISOString(),previousLock:i,expectedAssets:y}),se=Y(t);return{outputMode:r,human:`Project: ${se}
|
|
162
165
|
State: removed
|
|
163
166
|
${S.summaries.map($=>`${$.verifierId}: ${$.result}`).join(`
|
|
164
|
-
`)}`,value:{schemaVersion:1,ok:!0,command:"verify",result:{project:se,state:"removed",verifiers:S.summaries,lock:O}}}}let d=o.packageAdoption?.schemaVersion===2&&o.packageAdoption.topology.mode==="pnpm-shared-lockfile"?`${o.packageAdoption.topology.unitRelativeRoot}/`:"",l=(s.release.kind==="engineering-feature"?s.release.assets.map(h=>({path:h.path,desiredDigest:h.ownership==="managed-region"?h.digest:o.operations.find(w=>w.path===`${d}${h.path}`)?.desiredDigest,ownership:h.ownership,regionId:h.regionId})):o.action==="upgrade"?s.release.assets.map(h=>({path:h.path,desiredDigest:o.operations.find(w=>w.path===`${d}${h.path}`)?.desiredDigest,ownership:h.ownership,regionId:h.regionId})):o.operations).map(({path:h,desiredDigest:w,ownership:_,regionId:b})=>w===void 0?I("Applied plan is missing a desired asset digest."):{path:h,digest:w,ownership:_==="managed-region"?"managed-region":_==="seed-file"?"seed-file":"owned-file",...b===void 0?{}:{regionId:b}}),{executeVerification:p}=await import("./optional-runtime.js"),m=await p({projectRoot:t,release:s,expectedAssets:l}),u=o.action==="adopt"&&o.operations.every(h=>h.disposition==="noop")&&i?.capabilities.some(h=>h.capabilityId===o.capability.capabilityId)===!0,f=await Ec({projectRoot:t,...c===void 0?{}:{transactionRoot:c},plan:o,release:s.release,verificationResults:m.results,committedAt:new Date().toISOString(),expectedAssets:l,...(o.action==="upgrade"||s.release.kind==="engineering-feature"||u)&&i!==null?{previousLock:i}:{}}),g=
|
|
167
|
+
`)}`,value:{schemaVersion:1,ok:!0,command:"verify",result:{project:se,state:"removed",verifiers:S.summaries,lock:O}}}}let d=o.packageAdoption?.schemaVersion===2&&o.packageAdoption.topology.mode==="pnpm-shared-lockfile"?`${o.packageAdoption.topology.unitRelativeRoot}/`:"",l=(s.release.kind==="engineering-feature"?s.release.assets.map(h=>({path:h.path,desiredDigest:h.ownership==="managed-region"?h.digest:o.operations.find(w=>w.path===`${d}${h.path}`)?.desiredDigest,ownership:h.ownership,regionId:h.regionId})):o.action==="upgrade"?s.release.assets.map(h=>({path:h.path,desiredDigest:o.operations.find(w=>w.path===`${d}${h.path}`)?.desiredDigest,ownership:h.ownership,regionId:h.regionId})):o.operations).map(({path:h,desiredDigest:w,ownership:_,regionId:b})=>w===void 0?I("Applied plan is missing a desired asset digest."):{path:h,digest:w,ownership:_==="managed-region"?"managed-region":_==="seed-file"?"seed-file":"owned-file",...b===void 0?{}:{regionId:b}}),{executeVerification:p}=await import("./optional-runtime.js"),m=await p({projectRoot:t,release:s,expectedAssets:l}),u=o.action==="adopt"&&o.operations.every(h=>h.disposition==="noop")&&i?.capabilities.some(h=>h.capabilityId===o.capability.capabilityId)===!0,f=await Ec({projectRoot:t,...c===void 0?{}:{transactionRoot:c},plan:o,release:s.release,verificationResults:m.results,committedAt:new Date().toISOString(),expectedAssets:l,...(o.action==="upgrade"||s.release.kind==="engineering-feature"||u)&&i!==null?{previousLock:i}:{}}),g=Y(t);return{outputMode:r,human:`Project: ${g}
|
|
165
168
|
State: adopted
|
|
166
169
|
`+m.summaries.map(h=>`${h.verifierId}: ${h.result}`).join(`
|
|
167
|
-
`),value:{schemaVersion:1,ok:!0,command:"verify",result:{project:g,state:"adopted",verifiers:m.summaries,lock:f}}}}async function
|
|
170
|
+
`),value:{schemaVersion:1,ok:!0,command:"verify",result:{project:g,state:"adopted",verifiers:m.summaries,lock:f}}}}async function pl(e){let{projectRoot:t,outputMode:r}=mi(e,"Inspect"),n=await Sc(t),i=Y(t);if(n.required)return{outputMode:r,human:`Project: ${i}
|
|
168
171
|
State: recovery-required
|
|
169
172
|
Transaction: ${n.kind}
|
|
170
173
|
Next: dyyto recover --project ${i}`,value:{schemaVersion:1,ok:!0,command:"inspect",result:{project:i,state:"recovery-required",recovery:n}}};let a=JSON.parse(await te(N.join(t,"project-capabilities.json"),"utf8")),o=a.capabilities?.[0];if(o===void 0)return I("Project manifest must select one capability.");let s=await ge(Ae(o.capabilityId,o.version)),c=await Se(t);try{let A=await Ia(t,c?.capabilities.map(y=>y.appliedPlanId)??[],t,c?.capabilities.map(y=>y.capabilityId)??[]);if(A.action==="upgrade"||A.action==="adopt")return{outputMode:r,human:`Project: ${i}
|
|
171
174
|
State: applied-unverified
|
|
172
175
|
Plan: ${A.planId}
|
|
173
|
-
Next: dyyto verify --project ${i}`,value:{schemaVersion:1,ok:!0,command:"inspect",result:{project:i,state:"applied-unverified",operations:A.operations,lock:c}}}}catch{}let d=new Date,l={projectRoot:t,release:s,...c===null?{}:{currentLock:c},generatedAt:d.toISOString(),expiresAt:new Date(d.getTime()+1800*1e3).toISOString()},p=a.profile?.id==="standalone-npm-package"?await
|
|
176
|
+
Next: dyyto verify --project ${i}`,value:{schemaVersion:1,ok:!0,command:"inspect",result:{project:i,state:"applied-unverified",operations:A.operations,lock:c}}}}catch{}let d=new Date,l={projectRoot:t,release:s,...c===null?{}:{currentLock:c},generatedAt:d.toISOString(),expiresAt:new Date(d.getTime()+1800*1e3).toISOString()},p=a.profile?.id==="standalone-npm-package"?await Zu({...l,manifest:a}):a.profile?.id==="react-component-library"?await Xu({...l,manifest:a}):a.profile?.id==="nextjs-full-stack-application"?await Qu({...l,manifest:a}):a.profile?.id==="workspace-npm-package"?await ef({...l,manifest:a}):a.profile?.id==="workspace-node-application"?await tf({...l,manifest:a}):a.profile?.id==="workspace-web-application"?await rf({...l,manifest:a}):a.profile?.id==="workspace-expo-application"?await nf({...l,manifest:a}):await na(l),m=c===null?void 0:[...c.capabilities].filter(A=>A.packageAdoption!==void 0).sort((A,y)=>A.committedAt.localeCompare(y.committedAt)).at(-1)?.packageAdoption?.packageJsonDigest,u=m===void 0?void 0:await te(N.join(t,"package.json")).then(v).catch(()=>{}),f=p.operations.map(A=>A.path==="package.json"&&u===m?{...A,desiredDigest:m,disposition:"noop",conflictCode:void 0}:A),g=c===null?[]:await Am({projectRoot:t,lock:c,excludeCapabilityIds:[o.capabilityId]}),h=g.some(A=>A.disposition==="conflict"),w=m!==void 0&&f.every(A=>A.disposition==="noop")?{...p,state:"adopted"}:p,_={...w,state:h?"drifted":w.state,operations:[...f,...g]},b=c?.capabilities.flatMap(A=>A.packageAdoption?.sources.map(y=>({capabilityId:A.capabilityId,registryId:y.registryId,packageName:y.packageName,version:y.version,integrity:y.integrity}))??[])??[];return{outputMode:r,human:`Project: ${i}
|
|
174
177
|
State: ${_.state}
|
|
175
178
|
`+_.operations.map(A=>`${A.path}: ${A.disposition}`).join(`
|
|
176
179
|
`)+(b.length===0?"":`
|
|
177
180
|
\u5305\u6765\u6E90\uFF1A
|
|
178
181
|
${b.map(A=>`- ${A.packageName}@${A.version}\uFF08Registry: ${A.registryId}\uFF0C\u5B8C\u6574\u6027\u5DF2\u9501\u5B9A\uFF09`).join(`
|
|
179
|
-
`)}`),value:{schemaVersion:1,ok:!0,command:"inspect",result:{project:i,..._,lock:c,packageSources:b}}}}async function
|
|
182
|
+
`)}`),value:{schemaVersion:1,ok:!0,command:"inspect",result:{project:i,..._,lock:c,packageSources:b}}}}async function AA(e){let{projectRoot:t,outputMode:r}=mi(e,"Recover"),n=await Ku({projectRoot:t,now:new Date().toISOString()}),i=Y(t);return{outputMode:r,human:n.kind==="none"?`Project: ${i}
|
|
180
183
|
Recovery: not-required`:`Project: ${i}
|
|
181
184
|
Recovery: ${n.kind}
|
|
182
|
-
State: ${n.state}`,value:{schemaVersion:1,ok:!0,command:"recover",result:{project:i,recovery:n}}}}function eg(e,t){let r;try{r=oe({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},command:{type:"string"},after:{type:"string"}}})}catch{return I(`${t} arguments are invalid.`)}return typeof r.values.project!="string"?I(`${t} requires --project.`):{parsed:r,projectRoot:N.resolve(r.values.project),outputMode:F(e)}}async function
|
|
185
|
+
State: ${n.state}`,value:{schemaVersion:1,ok:!0,command:"recover",result:{project:i,recovery:n}}}}function eg(e,t){let r;try{r=oe({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},command:{type:"string"},after:{type:"string"}}})}catch{return I(`${t} arguments are invalid.`)}return typeof r.values.project!="string"?I(`${t} requires --project.`):{parsed:r,projectRoot:N.resolve(r.values.project),outputMode:F(e)}}async function RA(e,t){let{parsed:r,projectRoot:n,outputMode:i}=eg(t,"Lifecycle"),a=r.values.command;if((e==="start"||e==="restart")&&a!=="dev")return I("Lifecycle start/restart requires the supported --command dev.");try{let{projectProcessLogs:o,projectProcessStatus:s,startProjectProcess:c,stopProjectProcess:d}=await import("./optional-runtime.js"),l;if(e==="status")l=await s(n);else if(e==="logs"){let m=r.values.after===void 0?0:Number(r.values.after);if(!Number.isSafeInteger(m)||m<0)return I("Lifecycle logs --after must be a non-negative integer cursor.");l=await o(n,m)}else if(e==="start")await Gm(n,"dev"),l=await c(n,"dev");else if(e==="stop")l=await d(n);else if(e==="restart")await Gm(n,"dev"),await d(n),l=await c(n,"dev");else return I("Lifecycle action must be start, stop, restart, status, or logs.");let p=Y(n);return{outputMode:i,human:`Project: ${p}
|
|
183
186
|
Lifecycle: ${e}
|
|
184
|
-
State: ${"state"in l?l.state:"available"}`,value:{schemaVersion:1,ok:!0,command:`lifecycle-${e}`,result:{project:p,...l,projectRoot:void 0}}}}catch(o){let s=typeof o=="object"&&o!==null&&"code"in o?String(o.code):"PROJECT_PROCESS_FAILED";throw new xe({code:s,message:o instanceof Error?o.message:"Project lifecycle operation failed.",exitCode:4,nextStep:"Inspect lifecycle status and project logs before retrying."})}}async function
|
|
187
|
+
State: ${"state"in l?l.state:"available"}`,value:{schemaVersion:1,ok:!0,command:`lifecycle-${e}`,result:{project:p,...l,projectRoot:void 0}}}}catch(o){let s=typeof o=="object"&&o!==null&&"code"in o?String(o.code):"PROJECT_PROCESS_FAILED";throw new xe({code:s,message:o instanceof Error?o.message:"Project lifecycle operation failed.",exitCode:4,nextStep:"Inspect lifecycle status and project logs before retrying."})}}async function Gm(e,t){let r=G(JSON.parse(await te(N.join(e,"project-capabilities.json"),"utf8")));if(r.template===void 0)throw new xe({code:"PROJECT_COMMAND_UNSUPPORTED",message:"Managed lifecycle requires a formal Template Release.",exitCode:4,nextStep:"Use the project's standard package script directly or adopt a supported Template."});if((await li(Qa(r.template.id,r.template.version))).commands[t]!==t)throw new xe({code:"PROJECT_COMMAND_UNSUPPORTED",message:"The selected Template does not declare the requested lifecycle command.",exitCode:4,nextStep:"Choose a command declared by the project's Template Release."})}async function PA(e){let{projectRoot:t,outputMode:r}=eg(e,"Integrations"),{projectIntegrations:n}=await import("./optional-runtime.js"),i=await n(t),a=Y(t),o=i.details.flatMap(d=>[`${d.title} (${d.capabilityId}@${d.version}) [${d.status}]`,` ${d.purpose}`,...d.packages.map(l=>` package ${l.packageName}@${l.version} [${l.state}]`),...d.packages.flatMap(l=>l.imports.map(p=>` import { ${p.symbol} } from '${p.importFrom}'${p.referencePath?` -> ${p.referencePath}`:""}`)),...d.codeAssets.map(l=>` asset ${l.sourcePath} -> ${l.targetPath} (${l.ownership})`)]),s=d=>i.platformDependencies.filter(l=>l.source===d).length,c=i.platformDependencies.map(d=>` platform ${d.packageName} ${d.version} [${d.source}]`);return{outputMode:r,human:`Project: ${a}
|
|
185
188
|
Declared: ${i.declared.length}
|
|
186
189
|
Locked: ${i.locked.length}
|
|
187
190
|
Verified: ${i.verified.length}
|
|
@@ -189,7 +192,7 @@ Findings: ${i.findings.length}
|
|
|
189
192
|
Unmanaged platform dependencies: ${i.platformDependencies.length} (workspace ${s("workspace")} / registry ${s("registry")} / other ${s("other")})
|
|
190
193
|
|
|
191
194
|
${[...o,...c].join(`
|
|
192
|
-
`)}`,value:{schemaVersion:1,ok:!0,command:"integrations",result:{project:a,...i,projectRoot:void 0}}}}async function
|
|
195
|
+
`)}`,value:{schemaVersion:1,ok:!0,command:"integrations",result:{project:a,...i,projectRoot:void 0}}}}async function NA(e){let t;try{t=oe({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},source:{type:"string"},registry:{type:"string"},approve:{type:"string"},verify:{type:"string"},install:{type:"boolean"}}})}catch{return I("Packages switch arguments are invalid.")}if(typeof t.values.project!="string")return I("Packages switch requires --project.");let r=[t.values.approve,t.values.verify].filter(f=>typeof f=="string").length;if(r>1)return I("Packages switch accepts only one of --approve or --verify.");let{applyAndInstallPackageSourceSwitch:n,applyPackageSourceSwitch:i,switchProjectPackageSources:a,verifyPackageSourceSwitch:o,PackageSourceSwitchError:s}=await import("./optional-runtime.js"),c=t.values.source??"workspace";if(r===0&&c!=="workspace"&&c!=="public"&&c!=="private")return I("Packages switch requires --source workspace|public|private.");let d=N.resolve(t.values.project),l=await(typeof t.values.approve=="string"?t.values.install===!0?n({projectRoot:d,approvedPlanId:t.values.approve}):i({projectRoot:d,approvedPlanId:t.values.approve}):typeof t.values.verify=="string"?o({projectRoot:d,planId:t.values.verify}):a({projectRoot:d,scope:"@aipt/",source:c,...typeof t.values.registry=="string"?{registry:t.values.registry}:{}})).catch(f=>{throw f instanceof s?new xe({code:f.code,message:f.message,exitCode:4,nextStep:"Run dyyto packages switch --help."}):f}),p=Y(l.projectRoot),m=l.changes.map(f=>` ${f.field} ${f.packageName}: ${f.from} -> ${f.to}`),u=l.state==="reviewable"?`\u5BA1\u6838\u4E0D\u53EF\u53D8 Plan \u540E\u4F7F\u7528 --approve ${l.planId} \u7CBE\u786E\u6279\u51C6\u3002`:l.state==="applied"?`\u4F7F\u7528 --verify ${l.planId} \u9A8C\u8BC1\u3002`:"Package source manifest \u5DF2\u4E0E\u6279\u51C6\u7684 Plan \u4E00\u81F4\u3002";return{outputMode:F(e),human:`\u9879\u76EE\uFF1A${p}
|
|
193
196
|
\u6765\u6E90\uFF1A${l.source}
|
|
194
197
|
Registry\uFF1A${l.registry??"workspace protocol"}
|
|
195
198
|
\u72B6\u6001\uFF1A${l.state}
|
|
@@ -201,14 +204,15 @@ Packages\uFF1A${l.packages.length}
|
|
|
201
204
|
${m.join(`
|
|
202
205
|
`)}${m.length>0?`
|
|
203
206
|
|
|
204
|
-
`:""}\u4E0B\u4E00\u6B65\uFF1A${u}`,value:{schemaVersion:1,ok:!0,command:"packages switch",result:{project:p,source:l.source,registry:l.registry,state:l.state,planId:l.planId,packages:l.packages,changes:l.changes,written:l.written,...l.installVerified===void 0?{}:{installVerified:l.installVerified},...l.lockfileDigest===void 0?{}:{lockfileDigest:l.lockfileDigest}}}}}async function
|
|
207
|
+
`:""}\u4E0B\u4E00\u6B65\uFF1A${u}`,value:{schemaVersion:1,ok:!0,command:"packages switch",result:{project:p,source:l.source,registry:l.registry,state:l.state,planId:l.planId,packages:l.packages,changes:l.changes,written:l.written,...l.installVerified===void 0?{}:{installVerified:l.installVerified},...l.lockfileDigest===void 0?{}:{lockfileDigest:l.lockfileDigest}}}}}async function DA(e){let{projectRoot:t,outputMode:r}=mi(e,"Inspect"),n=G(JSON.parse(await te(N.join(t,"project-capabilities.json"),"utf8")));if(n.profile?.id==="workspace-root"){let s=await zc({workspaceRoot:t}),c=s.environment.map(d=>({name:d.name,...d.runtimeEnvironmentVariable?{runtimeEnvironmentVariable:d.runtimeEnvironmentVariable}:{},requirement:d.required?"conditional":"optional",kind:d.kind,secret:d.kind!=="value",configured:d.configured,source:"application-config-contract",configuredSource:"APP_CONFIG_DIR",display:d.display,consumers:d.consumers,configuredConsumers:d.configuredConsumers,conflict:d.conflict,consistent:d.consistent}));return{outputMode:r,human:`Workspace: ${Y(t)}
|
|
208
|
+
Environment: ${c.filter(d=>d.configured).length}/${c.length} configured`,value:{schemaVersion:1,ok:!0,command:"maintenance",result:{project:Y(t),template:"workspace-aggregate",commands:[],environment:c,environmentExample:null,productionValidation:{contract:!0,live:[]},applications:s.applications,summary:s.summary}}}}if(n.template===void 0)throw new xe({code:"PROJECT_MAINTENANCE_UNAVAILABLE",message:"Project maintenance requires a formal Template Release.",exitCode:4,nextStep:"Adopt a supported engineering template."});let i=await li(Qa(n.template.id,n.template.version)),a=await wm({projectRoot:t,commands:i.commands}),o=Y(t);return{outputMode:r,human:`Project: ${o}
|
|
205
209
|
Commands: ${a.commands.map(s=>s.id).join(", ")}
|
|
206
|
-
Environment: ${a.environment.filter(s=>s.configured).length}/${a.environment.length} configured`,value:{schemaVersion:1,ok:!0,command:"maintenance",result:{project:o,template:`${i.templateId}@${i.version}`,...a}}}}async function
|
|
210
|
+
Environment: ${a.environment.filter(s=>s.configured).length}/${a.environment.length} configured`,value:{schemaVersion:1,ok:!0,command:"maintenance",result:{project:o,template:`${i.templateId}@${i.version}`,...a}}}}async function SA(e){let{projectRoot:t,outputMode:r}=mi(e,"Inspect"),n=await Qn({projectRoot:t}).catch(i=>{throw new xe({code:i instanceof Error&&"code"in i?String(i.code):"APPLICATION_CONFIG_UNAVAILABLE",message:i instanceof Error?i.message:"\u5E94\u7528\u914D\u7F6E\u4E0D\u53EF\u7528\u3002",exitCode:4,nextStep:"\u8BBE\u7F6E\u8BE5\u9879\u76EE\u72EC\u4EAB\u7684\u7EDD\u5BF9APP_CONFIG_DIR\uFF0C\u5E76\u7531\u90E8\u7F72\u63A7\u5236\u9762\u5B8C\u6210config init\u3002"})});return{outputMode:r,human:`\u5E94\u7528\uFF1A${n.application}
|
|
207
211
|
\u73AF\u5883\uFF1A${n.environment}
|
|
208
212
|
Config Dir\uFF1A${n.configDirectory}
|
|
209
213
|
\u5DF2\u914D\u7F6E\uFF1A${n.entries.filter(i=>i.configured).length}/${n.entries.length}
|
|
210
214
|
${n.entries.map(i=>`${i.name}: ${i.display}`).join(`
|
|
211
|
-
`)}`,value:{schemaVersion:1,ok:!0,command:"config-inspect",result:n}}}async function
|
|
215
|
+
`)}`,value:{schemaVersion:1,ok:!0,command:"config-inspect",result:n}}}async function jA(e){let t;try{t=oe({args:[...e],allowPositionals:!1,strict:!0,options:{project:{type:"string"},workspace:{type:"string"},check:{type:"boolean"},json:{type:"boolean"}}})}catch{return I("Config readiness arguments are invalid.")}let r=t.values.project,n=t.values.workspace;if(typeof r=="string"==(typeof n=="string"))return I("Config readiness requires exactly one of --project or --workspace.");let i=F(e);if(typeof n=="string"){let c=await zc({workspaceRoot:N.resolve(n)}),d=c.applications.map(p=>`${p.unit}: ${p.readiness.state}${p.readiness.issueCode?` (${p.readiness.issueCode})`:""}`),l=t.values.check===!0?c.summary.invalid>0?4:c.summary.ready===c.summary.total?0:3:0;return{outputMode:i,human:`\u5DE5\u4F5C\u533A\uFF1A${Y(c.workspaceRoot)}
|
|
212
216
|
\u5E94\u7528\uFF1A${c.summary.total}
|
|
213
217
|
\u5C31\u7EEA\uFF1A${c.summary.ready}
|
|
214
218
|
\u5F85\u521D\u59CB\u5316\uFF1A${c.summary.needsConfigInit}
|
|
@@ -220,17 +224,17 @@ ${d.join(`
|
|
|
220
224
|
\u73AF\u5883\uFF1A${a.environment}
|
|
221
225
|
\u72B6\u6001\uFF1A${a.state}
|
|
222
226
|
Config Dir\uFF1A${a.configDirectory??"\u672A\u7269\u5316"}${o}${a.issueCode?`
|
|
223
|
-
\u95EE\u9898\uFF1A${a.issueCode}`:""}`,value:{schemaVersion:1,ok:!0,command:"config-readiness",result:a},...s?{exitCode:s}:{}}}async function
|
|
227
|
+
\u95EE\u9898\uFF1A${a.issueCode}`:""}`,value:{schemaVersion:1,ok:!0,command:"config-readiness",result:a},...s?{exitCode:s}:{}}}async function $A(e){let t;try{t=oe({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},plane:{type:"string"},state:{type:"string"},kind:{type:"string"},limit:{type:"string"}}})}catch{return I("Operations arguments are invalid.")}if(typeof t.values.project!="string"||!["change","quality","delivery"].includes(t.values.plane))return I("Operations requires --project and --plane change|quality|delivery.");let r=await pt(N.resolve(t.values.project)),n=Y(r),i=[];for(let o of await Wm(N.join(r,".dyyto","workbench","tasks")).catch(()=>[]))if(o.endsWith(".json"))try{let s=JSON.parse(await te(N.join(r,".dyyto","workbench","tasks",o),"utf8"));s.taskId&&typeof s.operation=="string"&&typeof s.state=="string"&&typeof s.createdAt=="string"&&typeof s.updatedAt=="string"&&i.push({id:s.taskId,projectId:".",projectName:n,operation:s.operation,state:s.state,createdAt:s.createdAt,updatedAt:s.updatedAt,...s.correlationId?{correlationId:s.correlationId}:{}})}catch{}let a=bm(i,{plane:t.values.plane,...typeof t.values.state=="string"?{state:t.values.state}:{},...typeof t.values.kind=="string"?{kind:t.values.kind}:{},...typeof t.values.limit=="string"?{limit:Number(t.values.limit)}:{}});return{outputMode:F(e),human:`Project: ${n}
|
|
224
228
|
Operations: ${a.plane}
|
|
225
229
|
Total: ${a.summary.total}
|
|
226
|
-
Attention: ${a.summary.attention}`,value:{schemaVersion:1,ok:!0,command:"operations",result:{project:n,...a}}}}async function
|
|
230
|
+
Attention: ${a.summary.attention}`,value:{schemaVersion:1,ok:!0,command:"operations",result:{project:n,...a}}}}async function OA(e){let t;try{t=oe({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},workspace:{type:"string"}}})}catch{return I("Doctor arguments are invalid.")}if(typeof t.values.workspace!="string")return I("Doctor requires --workspace.");let r=await pt(N.resolve(t.values.workspace));if(G(JSON.parse(await te(N.join(r,"project-capabilities.json"),"utf8"))).profile?.id!=="workspace-root")return I("Doctor requires a workspace-root project.");let i=[{unit:".",kind:"root",projectRoot:r}];for(let s of["packages","apps"])for(let c of await Wm(N.join(r,s),{withFileTypes:!0}).catch(()=>[])){if(!c.isDirectory()||c.isSymbolicLink())continue;let d=N.join(r,s,c.name);try{await te(N.join(d,"project-capabilities.json"))}catch{continue}i.push({unit:`${s}/${c.name}`,kind:s==="packages"?"package":"application",projectRoot:d})}let a=[];for(let s of i){let c="invalid",d;try{let p=(await pl(["--project",s.projectRoot,"--json"])).value.result;c=p.state??"invalid",d=el(c),c==="adopted"&&p.lock!==null&&typeof p.lock=="object"?d.push(...await oi({projectRoot:s.projectRoot,lock:p.lock})):c==="adopted"&&d.push({code:"EVIDENCE_INVALID",severity:"critical",fact:"evidence",message:"\u5DF2\u91C7\u7528\u5355\u5143\u7F3A\u5C11\u53EF\u6838\u9A8C\u7684\u91C7\u7528\u9501\u3002",action:"\u91CD\u65B0\u8FD0\u884C\u9A8C\u8BC1\u5E76\u63D0\u4EA4\u91C7\u7528\u9501\u3002"})}catch{d=el("invalid")}try{let l=G(JSON.parse(await te(N.join(s.projectRoot,"project-capabilities.json"),"utf8")));l.profile?.id==="workspace-web-application"&&d.push(...await rm({workspaceRoot:r,applicationId:String(l.profile.parameters.name)}))}catch{}a.push({unit:s.unit,kind:s.kind,state:c,findings:d})}let o=nm({workspace:N.basename(r),generatedAt:new Date().toISOString(),units:a});return{outputMode:F(e),human:`Workspace: ${o.workspace}
|
|
227
231
|
Status: ${o.status}
|
|
228
232
|
Units: ${o.summary.total}
|
|
229
233
|
Healthy: ${o.summary.healthy}
|
|
230
234
|
Attention: ${o.summary.attention}
|
|
231
235
|
Blocked: ${o.summary.blocked}
|
|
232
236
|
`+o.units.map(s=>`${s.unit}: ${s.status} (${s.findings.map(c=>c.code).join(", ")})`).join(`
|
|
233
|
-
`),value:{schemaVersion:1,ok:!0,command:"doctor",result:o}}}async function
|
|
237
|
+
`),value:{schemaVersion:1,ok:!0,command:"doctor",result:o}}}async function ul(e){let{LocalDockerDeploymentAdapter:t,NpmjsPublisherAdapter:r,HostedStaticPublicationAdapter:n}=await import("./optional-runtime.js");return e==="npm-publish"?new r:e==="application-deploy"?new t:e==="hosted-static"?new n:I("Delivery kind must be npm-publish, application-deploy, or hosted-static.")}function Jm(e){return e.length<=16?e:`${e.slice(0,12)}\u2026`}async function tg(e){let t=G(JSON.parse(await te(N.join(e,"project-capabilities.json"),"utf8"))),r=await Se(e),n=r?.capabilities[0];if(r===null||n===void 0||r.capabilities.length!==1)return I("Delivery requires one adopted capability Lock.");if(t.profile===void 0||t.capabilities[0]?.capabilityId!==n.capabilityId||t.capabilities[0]?.version!==n.version)return I("Manifest and verified Lock must identify the same adopted capability.");let i=n.assets.filter(a=>!a.path.startsWith("src/"));return await sr({projectRoot:e,expectedAssets:i}),{manifest:t,lock:r,locked:n,lockDigest:v(E(r))}}async function CA(e){let t;try{t=oe({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},kind:{type:"string"},provider:{type:"string"},repository:{type:"string"},workflow:{type:"string"},ref:{type:"string"},environment:{type:"string"}}})}catch{return I("Delivery plan arguments are invalid.")}if(typeof t.values.project!="string"||typeof t.values.kind!="string")return I("Delivery plan requires --project and --kind.");let r=N.resolve(t.values.project),n=await tg(r),a=await(await ul(t.values.kind)).prepare({projectRoot:r,profile:n.manifest.profile.id,parameters:n.manifest.profile.parameters});if(t.values.kind==="npm-publish"&&await Cf({projectRoot:r,artifactIdentity:a.artifact.identity})!==null)throw new j("NPM_REGISTRY_OUTCOME_UNKNOWN","An earlier Delivery Plan started a remote write for this exact npm version without a resolved Registry outcome");let o=t.values.kind==="npm-publish"?(()=>{let l=t.values.provider,p=t.values.repository,m=t.values.workflow,u=t.values.ref;if(l!=="github-actions"&&l!=="gitlab-ci"||typeof p!="string"||typeof m!="string"||typeof u!="string")throw new j("DELIVERY_PRECONDITION_FAILED","Secure npm Delivery Plan requires --provider, --repository, --workflow and --ref.");return{mode:"staged",access:"public",tag:"latest",authentication:"trusted-publishing",trustedAction:"stage-only",provenance:"required",execution:{provider:l,repository:p,workflow:m,ref:u,...typeof t.values.environment=="string"?{environment:t.values.environment}:{}}}})():void 0;if(o!==void 0){let l=JSON.parse(await te(N.join(r,"package.json"),"utf8")),p=typeof l.repository=="string"?l.repository:l.repository!==null&&typeof l.repository=="object"?l.repository.url:void 0,m=`https://${o.execution.provider==="github-actions"?"github.com":"gitlab.com"}/${o.execution.repository}`;if(p!==m)throw new j("NPM_PROVENANCE_REQUIRED","package.json repository does not match the trusted publishing repository identity")}let s=new Date,c=Yc({kind:t.values.kind,project:{profile:n.manifest.profile.id,lockDigest:n.lockDigest,appliedPlanId:n.locked.appliedPlanId},artifact:a.artifact,target:a.target,risk:t.values.kind==="npm-publish"?"irreversible-publish":t.values.kind==="hosted-static"?"external-reversible-publication":"local-reversible-deployment",createdAt:s.toISOString(),expiresAt:new Date(s.getTime()+1800*1e3).toISOString(),...o===void 0?{}:{publication:o}});await jf({projectRoot:r,plan:c});let d=Y(r);return{outputMode:F(e),human:`Project: ${d}
|
|
234
238
|
Delivery: ${c.kind}
|
|
235
239
|
Artifact: ${c.artifact.identity}
|
|
236
240
|
Target: ${c.target.location}
|
|
@@ -242,20 +246,20 @@ Execution: ${c.publication.execution.provider}:${c.publication.execution.reposit
|
|
|
242
246
|
Approval: maintainer 2FA required outside Dyyto`}
|
|
243
247
|
Plan: ${c.planId}
|
|
244
248
|
State: reviewable
|
|
245
|
-
Next: dyyto delivery apply --project ${d} --approve ${c.planId}`,value:{schemaVersion:1,ok:!0,command:"delivery-plan",result:{project:d,plan:c}}}}async function
|
|
249
|
+
Next: dyyto delivery apply --project ${d} --approve ${c.planId}`,value:{schemaVersion:1,ok:!0,command:"delivery-plan",result:{project:d,plan:c}}}}async function TA(e){let t;try{t=oe({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},approve:{type:"string"}}})}catch{return I("Delivery apply arguments are invalid.")}if(typeof t.values.project!="string"||typeof t.values.approve!="string")return I("Delivery apply requires --project and --approve <planId>.");let r=N.resolve(t.values.project),n=await zt({projectRoot:r,planId:t.values.approve}),i=await ri({projectRoot:r,planId:n.planId}),a=Y(r);if(i!==null)return{outputMode:F(e),human:`Project: ${a}
|
|
246
250
|
Delivery: verified
|
|
247
251
|
Receipt: ${i.receiptId}`,value:{schemaVersion:1,ok:!0,command:"delivery-apply",result:{project:a,reused:!0,receipt:i}}};let o=n.kind==="npm-publish"?await Hr({projectRoot:r,planId:n.planId}):null;if(o!==null)return{outputMode:F(e),human:`Project: ${a}
|
|
248
252
|
Delivery: staged
|
|
249
|
-
Stage: ${
|
|
250
|
-
State: approval-pending`,value:{schemaVersion:1,ok:!0,command:"delivery-apply",result:{project:a,reused:!0,state:"staged",record:o}}};if((n.kind==="npm-publish"?await Of({projectRoot:r,planId:n.planId}):null)!==null)throw new j("NPM_REGISTRY_OUTCOME_UNKNOWN","This Plan already started a remote stage write without a committed Stage Record");if(Date.parse(n.expiresAt)<=Date.now())throw new j("DELIVERY_PLAN_EXPIRED","Delivery Plan has expired");let c=await tg(r);if(c.lockDigest!==n.project.lockDigest||c.locked.appliedPlanId!==n.project.appliedPlanId)throw new j("DELIVERY_PRECONDITION_FAILED","Adoption Lock changed after Delivery Plan approval");let d=await
|
|
253
|
+
Stage: ${Jm(o.stageId)}
|
|
254
|
+
State: approval-pending`,value:{schemaVersion:1,ok:!0,command:"delivery-apply",result:{project:a,reused:!0,state:"staged",record:o}}};if((n.kind==="npm-publish"?await Of({projectRoot:r,planId:n.planId}):null)!==null)throw new j("NPM_REGISTRY_OUTCOME_UNKNOWN","This Plan already started a remote stage write without a committed Stage Record");if(Date.parse(n.expiresAt)<=Date.now())throw new j("DELIVERY_PLAN_EXPIRED","Delivery Plan has expired");let c=await tg(r);if(c.lockDigest!==n.project.lockDigest||c.locked.appliedPlanId!==n.project.appliedPlanId)throw new j("DELIVERY_PRECONDITION_FAILED","Adoption Lock changed after Delivery Plan approval");let d=await ul(n.kind),l=await d.prepare({projectRoot:r,profile:c.manifest.profile.id,parameters:c.manifest.profile.parameters});if(E(l.artifact)!==E(n.artifact)||E(l.target)!==E(n.target))throw new j("DELIVERY_PRECONDITION_FAILED","Artifact or target changed after Delivery Plan approval");let p=await d.execute({projectRoot:r,plan:n,...n.kind==="npm-publish"?{onRemoteWriteStarting:async()=>{await $f({projectRoot:r,record:Df({planId:n.planId,artifactDigest:n.artifact.digest,startedAt:new Date().toISOString()})})}}:{}});if(n.kind==="npm-publish"){let u=Nf({planId:n.planId,stageId:p.externalIdentity,artifactDigest:n.artifact.digest,createdAt:new Date().toISOString()});return await Tf({projectRoot:r,record:u}),{outputMode:F(e),human:`Project: ${a}
|
|
251
255
|
Delivery: staged
|
|
252
|
-
Stage: ${
|
|
253
|
-
State: approval-pending`,value:{schemaVersion:1,ok:!0,command:"delivery-apply",result:{project:a,state:"staged",record:u}}}}if(n.kind==="application-deploy"&&(await d.inspect({projectRoot:r,plan:n})).state!=="verified")throw new j("DELIVERY_EXECUTION_UNKNOWN","Docker deployment outcome could not be verified");let m=Ua({planId:n.planId,kind:n.kind,adapterId:n.target.adapterId,artifactDigest:n.artifact.digest,target:n.target.location,externalIdentity:p.externalIdentity,completedAt:new Date().toISOString(),details:p.details});return await
|
|
256
|
+
Stage: ${Jm(u.stageId)}
|
|
257
|
+
State: approval-pending`,value:{schemaVersion:1,ok:!0,command:"delivery-apply",result:{project:a,state:"staged",record:u}}}}if(n.kind==="application-deploy"&&(await d.inspect({projectRoot:r,plan:n})).state!=="verified")throw new j("DELIVERY_EXECUTION_UNKNOWN","Docker deployment outcome could not be verified");let m=Ua({planId:n.planId,kind:n.kind,adapterId:n.target.adapterId,artifactDigest:n.artifact.digest,target:n.target.location,externalIdentity:p.externalIdentity,completedAt:new Date().toISOString(),details:p.details});return await Hc({projectRoot:r,receipt:m}),{outputMode:F(e),human:`Project: ${a}
|
|
254
258
|
Delivery: verified
|
|
255
259
|
Receipt: ${m.receiptId}
|
|
256
|
-
External: ${m.externalIdentity}`,value:{schemaVersion:1,ok:!0,command:"delivery-apply",result:{project:a,receipt:m}}}}async function
|
|
260
|
+
External: ${m.externalIdentity}`,value:{schemaVersion:1,ok:!0,command:"delivery-apply",result:{project:a,receipt:m}}}}async function xA(e){let t;try{t=oe({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},plan:{type:"string"},"stage-artifact":{type:"string"}}})}catch{return I("Delivery inspect arguments are invalid.")}if(typeof t.values.project!="string"||typeof t.values.plan!="string")return I("Delivery inspect requires --project and --plan <planId>.");let r=N.resolve(t.values.project),n=await zt({projectRoot:r,planId:t.values.plan}),i=await ri({projectRoot:r,planId:n.planId}),a=Y(r);if(i!==null)return{outputMode:F(e),human:`Project: ${a}
|
|
257
261
|
Delivery: verified
|
|
258
|
-
Plan: ${n.planId}`,value:{schemaVersion:1,ok:!0,command:"delivery-inspect",result:{project:a,state:"verified",plan:n,receipt:i}}};let o=n.kind==="npm-publish"?await Hr({projectRoot:r,planId:n.planId}):null,s=n.kind==="npm-publish"?await Lf({projectRoot:r,planId:n.planId}):null;if(typeof t.values["stage-artifact"]=="string"){if(n.kind!=="npm-publish"||o===null)throw new j("DELIVERY_PRECONDITION_FAILED","Stage artifact review requires an existing npm Stage Record");let d=v(await te(N.resolve(t.values["stage-artifact"])));if(d!==n.artifact.digest||d!==o.artifactDigest)throw new j("DELIVERY_PRECONDITION_FAILED","Reviewed stage artifact does not match the approved Delivery Plan");s=Sf({planId:n.planId,stageId:o.stageId,artifactDigest:d,reviewedAt:new Date().toISOString()}),await xf({projectRoot:r,record:s})}let c=await(await
|
|
262
|
+
Plan: ${n.planId}`,value:{schemaVersion:1,ok:!0,command:"delivery-inspect",result:{project:a,state:"verified",plan:n,receipt:i}}};let o=n.kind==="npm-publish"?await Hr({projectRoot:r,planId:n.planId}):null,s=n.kind==="npm-publish"?await Lf({projectRoot:r,planId:n.planId}):null;if(typeof t.values["stage-artifact"]=="string"){if(n.kind!=="npm-publish"||o===null)throw new j("DELIVERY_PRECONDITION_FAILED","Stage artifact review requires an existing npm Stage Record");let d=v(await te(N.resolve(t.values["stage-artifact"])));if(d!==n.artifact.digest||d!==o.artifactDigest)throw new j("DELIVERY_PRECONDITION_FAILED","Reviewed stage artifact does not match the approved Delivery Plan");s=Sf({planId:n.planId,stageId:o.stageId,artifactDigest:d,reviewedAt:new Date().toISOString()}),await xf({projectRoot:r,record:s})}let c=await(await ul(n.kind)).inspect({projectRoot:r,plan:n});if(n.kind==="npm-publish"&&o!==null&&c.state==="verified"){if(n.schemaVersion!==2||n.publication===void 0||c.details.artifactDigest!==n.artifact.digest||c.details.provenance!=="registry-attestation-present"||c.details.provenanceUrlDigest===void 0)throw new j("NPM_PROVENANCE_REQUIRED","Registry inspection did not prove the approved npm artifact and provenance");let d=Ua({planId:n.planId,kind:n.kind,adapterId:"registry.npmjs",artifactDigest:n.artifact.digest,target:n.target.location,externalIdentity:n.artifact.identity,completedAt:new Date().toISOString(),npm:{stageId:o.stageId,registry:"https://registry.npmjs.org",tarballDigest:n.artifact.digest,access:n.publication.access,tag:n.publication.tag,provenance:"registry-attested",attestationUrlDigest:c.details.provenanceUrlDigest}});return await Hc({projectRoot:r,receipt:d}),{outputMode:F(e),human:`Project: ${a}
|
|
259
263
|
Delivery: verified
|
|
260
264
|
Plan: ${n.planId}`,value:{schemaVersion:1,ok:!0,command:"delivery-inspect",result:{project:a,state:"verified",plan:n,stage:o,review:s,receipt:d,adapter:c}}}}if(n.kind==="npm-publish"&&o!==null){let d=c.state==="absent"||c.state==="staged"?"approval-pending":c.state;return{outputMode:F(e),human:`Project: ${a}
|
|
261
265
|
Delivery: staged
|
|
@@ -263,17 +267,17 @@ Plan: ${n.planId}
|
|
|
263
267
|
Artifact review: ${s===null?"pending":"verified"}
|
|
264
268
|
State: ${d}`,value:{schemaVersion:1,ok:!0,command:"delivery-inspect",result:{project:a,state:d,plan:n,stage:o,review:s,receipt:null,adapter:c}}}}if(n.kind==="npm-publish"&&c.state==="verified")throw new j("NPM_REGISTRY_OUTCOME_UNKNOWN","Live npm artifact is visible but no immutable Stage Record exists for this Plan");return{outputMode:F(e),human:`Project: ${a}
|
|
265
269
|
Delivery: ${c.state}
|
|
266
|
-
Plan: ${n.planId}`,value:{schemaVersion:1,ok:!0,command:"delivery-inspect",result:{project:a,state:c.state,plan:n,receipt:null,adapter:c}}}}async function
|
|
267
|
-
`),value:{schemaVersion:1,ok:!0,command:"observe-errors",result:{...a,summary:o}}}}async function
|
|
270
|
+
Plan: ${n.planId}`,value:{schemaVersion:1,ok:!0,command:"delivery-inspect",result:{project:a,state:c.state,plan:n,receipt:null,adapter:c}}}}async function LA(e){let t;try{t=oe({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},workspace:{type:"string"},application:{type:"string"},limit:{type:"string"},cursor:{type:"string"}}})}catch{return I("Observe errors arguments are invalid.")}if(typeof t.values.workspace!="string")return I("Observe errors requires --workspace.");let r=await pt(N.resolve(t.values.workspace)),n=new wr(r),i={...typeof t.values.application=="string"?{applicationId:t.values.application}:{},...typeof t.values.limit=="string"?{limit:Number(t.values.limit)}:{},...typeof t.values.cursor=="string"?{cursor:t.values.cursor}:{}},[a,o]=await Promise.all([n.list(i),n.summary(i)]);return{outputMode:F(e),human:a.events.length===0?"\u672A\u53D1\u73B0\u8FD0\u884C\u65F6\u9519\u8BEF\u3002":a.events.map(s=>`${s.occurredAt} ${s.applicationId} ${s.error.type}: ${s.error.message} (${s.state}, ${s.correlation})`).join(`
|
|
271
|
+
`),value:{schemaVersion:1,ok:!0,command:"observe-errors",result:{...a,summary:o}}}}async function VA(e){let t;try{t=oe({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},workspace:{type:"string"},id:{type:"string"}}})}catch{return I("Observe error arguments are invalid.")}if(typeof t.values.workspace!="string"||typeof t.values.id!="string")return I("Observe error requires --workspace and --id.");let r=await new wr(await pt(N.resolve(t.values.workspace))).get(t.values.id);if(r===null)throw new xe({code:"RUNTIME_ERROR_NOT_FOUND",message:"Runtime Error Event was not found.",exitCode:4,nextStep:"List recent errors and verify the event ID."});return{outputMode:F(e),human:`${r.error.type}: ${r.error.message}
|
|
268
272
|
State: ${r.state}
|
|
269
273
|
Correlation: ${r.correlation}
|
|
270
274
|
Release: ${r.releaseId??"unknown"}
|
|
271
|
-
Deployment: ${r.deploymentId??"unknown"}`,value:{schemaVersion:1,ok:!0,command:"observe-error",result:{event:r}}}}async function
|
|
275
|
+
Deployment: ${r.deploymentId??"unknown"}`,value:{schemaVersion:1,ok:!0,command:"observe-error",result:{event:r}}}}async function MA(e){let t;try{t=oe({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},project:{type:"string"},workspace:{type:"string"}}})}catch{return I("Observe release register arguments are invalid.")}if(typeof t.values.project!="string")return I("Observe release register requires --project.");let r=await pt(N.resolve(t.values.project)),n=await pt(N.resolve(typeof t.values.workspace=="string"?t.values.workspace:N.join(r,"../.."))),{registerWebRelease:i}=await import("./optional-runtime.js"),a=await i({workspaceRoot:n,projectRoot:r});return{outputMode:F(e),human:`Release: ${a.releaseId}
|
|
272
276
|
Source Maps: ${a.registrations.length}
|
|
273
|
-
\u516C\u5F00\u4EA7\u7269\u5DF2\u79FB\u9664 .map \u6587\u4EF6\u3002`,value:{schemaVersion:1,ok:!0,command:"observe-release-register",result:a}}}async function
|
|
277
|
+
\u516C\u5F00\u4EA7\u7269\u5DF2\u79FB\u9664 .map \u6587\u4EF6\u3002`,value:{schemaVersion:1,ok:!0,command:"observe-release-register",result:a}}}async function qA(e){let t;try{t=oe({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},query:{type:"string"},kind:{type:"string"},limit:{type:"string"}}})}catch{return I("Catalog search \u53C2\u6570\u65E0\u6548\u3002")}let r=t.values.kind;if(r!==void 0&&r!=="all"&&r!=="package"&&r!=="capability")return I("Catalog search --kind \u53EA\u63A5\u53D7 all\u3001package \u6216 capability\u3002");let n=t.values.limit===void 0?50:Number(t.values.limit);if(!Number.isSafeInteger(n)||n<1||n>200)return I("Catalog search --limit \u5FC5\u987B\u662F 1 \u5230 200 \u7684\u6574\u6570\u3002");let i=await zm({...typeof t.values.query=="string"?{query:t.values.query}:{},...r==="package"||r==="capability"?{kind:r}:{},limit:n}),a=i.items.length===0?"\u76EE\u5F55\u4E2D\u6CA1\u6709\u5339\u914D\u7684\u5DE5\u7A0B\u80FD\u529B\u3002":i.items.map(o=>`${o.ref}
|
|
274
278
|
${o.summary}
|
|
275
279
|
\u6210\u719F\u5EA6\uFF1A${o.maturity}`).join(`
|
|
276
|
-
`);return{outputMode:F(e),human:a,value:{schemaVersion:1,ok:!0,command:"catalog-search",result:i}}}async function
|
|
280
|
+
`);return{outputMode:F(e),human:a,value:{schemaVersion:1,ok:!0,command:"catalog-search",result:i}}}async function UA(e){let t;try{t=oe({args:[...e],allowPositionals:!1,strict:!0,options:{json:{type:"boolean"},ref:{type:"string"}}})}catch{return I("Catalog show \u53C2\u6570\u65E0\u6548\u3002")}if(typeof t.values.ref!="string"||t.values.ref.trim()==="")return I("Catalog show \u9700\u8981 --ref\u3002");let r=await Bm({ref:t.values.ref});return{outputMode:F(e),human:`${r.item.ref}
|
|
277
281
|
${r.item.summary}
|
|
278
282
|
\u6210\u719F\u5EA6\uFF1A${r.item.maturity}
|
|
279
|
-
\u5B8C\u6574\u6027\uFF1A${r.item.integrity}`,value:{schemaVersion:1,ok:!0,command:"catalog-show",result:r}}}async function
|
|
283
|
+
\u5B8C\u6574\u6027\uFF1A${r.item.integrity}`,value:{schemaVersion:1,ok:!0,command:"catalog-show",result:r}}}async function lj(e,t={}){let r=e[0]==="--"?e.slice(1):e,n=F(r);if(r[0]==="--version"&&r.every(o=>o==="--version"||o==="--json"))return{outputMode:n,human:il,value:{schemaVersion:1,ok:!0,command:"version",result:{version:il}}};if(r.length===0||r[0]==="--help"||r[0]==="-h")return{outputMode:n,human:Pm,value:{schemaVersion:1,ok:!0,command:"help",result:{usage:"dyyto <command> [options]"}}};let[i,...a]=r;return i==="catalog"&&a[0]==="search"?qA(a.slice(1)):i==="catalog"&&a[0]==="show"?UA(a.slice(1)):i==="create"?Xm(a):i==="scaffold"&&a[0]==="example"?EA(a.slice(1),t):i==="retrofit"?hA(a):i==="dev"||i==="build"||i==="test"||i==="package"?yA(i,a):i==="add"&&a[0]==="package"?wA(a.slice(1)):i==="add"&&a[0]==="application"?vA(a.slice(1)):i==="add"&&a[0]==="feature"?Qm(a.slice(1),t):i==="remove"&&a[0]==="feature"?IA(a.slice(1),t):i==="plan"?bA(a):i==="upgrade"?_A(a,t):i==="apply"?ll(a,t):i==="verify"?dl(a):i==="inspect"?pl(a):i==="doctor"?OA(a):i==="recover"?AA(a):i==="lifecycle"&&typeof a[0]=="string"?RA(a[0],a.slice(1)):i==="packages"&&a[0]==="switch"?NA(a.slice(1)):i==="integrations"?PA(a):i==="maintenance"?DA(a):i==="config"&&a[0]==="inspect"?SA(a.slice(1)):i==="config"&&a[0]==="readiness"?jA(a.slice(1)):i==="operations"?$A(a):i==="baseline"?kA(a):i==="delivery"&&a[0]==="plan"?CA(a.slice(1)):i==="delivery"&&a[0]==="apply"?TA(a.slice(1)):i==="delivery"&&a[0]==="inspect"?xA(a.slice(1)):i==="observe"&&a[0]==="errors"?LA(a.slice(1)):i==="observe"&&a[0]==="error"?VA(a.slice(1)):i==="observe"&&a[0]==="release"&&a[1]==="register"?MA(a.slice(2)):I(`Unknown command '${i}'.`)}export{lj as runApplication};
|