@aipt/cli 0.1.44 → 0.1.48
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 +178 -178
- package/dist/application.js +98 -98
- package/dist/chunk.js +1 -1
- package/dist/optional-runtime.js +28 -28
- package/dist/package-releases/aipt--cli/0.1.43/release.json +29 -0
- package/dist/package-releases/aipt--cli/0.1.44/release.json +29 -0
- package/dist/package-releases/aipt--cli/0.1.45/release.json +29 -0
- package/dist/package-releases/aipt--cli/0.1.46/release.json +29 -0
- package/dist/package-releases/aipt--cli/0.1.47/release.json +29 -0
- package/dist/package-releases/aipt--cli/0.1.48/release.json +29 -0
- package/dist/package-releases/aipt--idp-setup/0.1.16/release.json +31 -0
- package/dist/package-releases/aipt--idp-setup/0.1.17/release.json +31 -0
- package/dist/package-releases/aipt--idp-setup/0.1.18/release.json +31 -0
- package/dist/package-releases/aipt--idp-setup/0.1.19/release.json +31 -0
- package/dist/package-releases/aipt--platform-kernel/0.1.14/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 +23 -21
package/dist/application.js
CHANGED
|
@@ -1,48 +1,48 @@
|
|
|
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
|
|
1
|
+
var ag=Object.create;var ml=Object.defineProperty;var og=Object.getOwnPropertyDescriptor;var sg=Object.getOwnPropertyNames;var cg=Object.getPrototypeOf,lg=Object.prototype.hasOwnProperty;var P=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var dg=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of sg(t))!lg.call(e,i)&&i!==r&&ml(e,i,{get:()=>t[i],enumerable:!(n=og(t,i))||n.enumerable});return e};var br=(e,t,r)=>(r=e!=null?ag(cg(e)):{},dg(t||!e||!e.__esModule?ml(r,"default",{value:e,enumerable:!0}):r,e));var rn=P(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 gl(e,...t){let r=[e[0]],n=0;for(;n<t.length;)io(r,t[n]),r.push(e[++n]);return new Ge(r)}W._=gl;var no=new Ge("+");function hl(e,...t){let r=[tn(e[0])],n=0;for(;n<t.length;)r.push(no),io(r,t[n]),r.push(no,tn(e[++n]));return pg(r),new Ge(r)}W.str=hl;function io(e,t){t instanceof Ge?e.push(...t._items):t instanceof Gt?e.push(t):e.push(mg(t))}W.addCodeArg=io;function pg(e){let t=1;for(;t<e.length-1;){if(e[t]===no){let r=ug(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function ug(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 fg(e,t){return t.emptyStr()?e:e.emptyStr()?t:hl`${e}${t}`}W.strConcat=fg;function mg(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:tn(Array.isArray(e)?e.join(","):e)}function gg(e){return new Ge(tn(e))}W.stringify=gg;function tn(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}W.safeStringify=tn;function hg(e){return typeof e=="string"&&W.IDENTIFIER.test(e)?new Ge(`.${e}`):gl`[${e}]`}W.getProperty=hg;function yg(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=yg;function wg(e){return new Ge(e.toString())}W.regexpCode=wg});var so=P(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.ValueScope=Ve.ValueScopeName=Ve.Scope=Ve.varKinds=Ve.UsedValueState=void 0;var Le=rn(),ao=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 vg=(0,Le._)`\n`,oo=class extends hi{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?vg: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 ao(d);c.set(d,gi.Completed)})}return a}};Ve.ValueScope=oo});var x=P(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=so(),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=so();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}},co=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)}},lo=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}},po=class extends vt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},uo=class extends vt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},fo=class extends vt{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},mo=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)||(Ig(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}},go=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(yl(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 ho=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)}},yo=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 wo=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 vo=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 go]}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 co(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 lo(t,V.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==z.nil&&this._leafNode(new mo(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 ho(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 yo(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 po(t))}break(t){return this._leafNode(new uo(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 wo;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 fo(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=vo;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 Ig(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function yl(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,z._)`!${Io(e)}`}V.not=yl;var bg=wl(V.operators.AND);function kg(...e){return e.reduce(bg)}V.and=kg;var _g=wl(V.operators.OR);function Eg(...e){return e.reduce(_g)}V.or=Eg;function wl(e){return(t,r)=>t===z.nil?r:r===z.nil?t:(0,z._)`${Io(t)} ${e} ${Io(r)}`}function Io(e){return e instanceof z.Name?e:(0,z._)`(${e})`}});var F=P(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(),Ag=rn();function Rg(e){let t={};for(let r of e)t[r]=!0;return t}q.toHash=Rg;function Pg(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(bl(e,t),!kl(t,e.self.RULES.all))}q.alwaysValidSchema=Pg;function bl(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]||Al(e,`unknown keyword: "${a}"`)}q.checkUnknownRules=bl;function kl(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}q.schemaHasRules=kl;function Ng(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=Ng;function Dg({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=Dg;function Sg(e){return _l(decodeURIComponent(e))}q.unescapeFragment=Sg;function jg(e){return encodeURIComponent(ko(e))}q.escapeFragment=jg;function ko(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}q.escapeJsonPointer=ko;function _l(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}q.unescapeJsonPointer=_l;function $g(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}q.eachItem=$g;function vl({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:vl({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} || {}`),_o(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:El}),items:vl({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 El(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,re._)`{}`);return t!==void 0&&_o(e,r,t),r}q.evaluatedPropsToName=El;function _o(e,t,r){Object.keys(r).forEach(n=>e.assign((0,re._)`${t}${(0,re.getProperty)(n)}`,!0))}q.setEvaluated=_o;var Il={};function Og(e,t){return e.scopeValue("func",{ref:t,code:Il[t.code]||(Il[t.code]=new Ag._Code(t.code))})}q.useFunc=Og;var bo;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(bo||(q.Type=bo={}));function Cg(e,t,r){if(e instanceof re.Name){let n=t===bo.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():"/"+ko(e)}q.getErrorPath=Cg;function Al(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=Al});var Je=P(Eo=>{"use strict";Object.defineProperty(Eo,"__esModule",{value:!0});var Pe=x(),Tg={data:new Pe.Name("data"),valCxt:new Pe.Name("valCxt"),instancePath:new Pe.Name("instancePath"),parentData:new Pe.Name("parentData"),parentDataProperty:new Pe.Name("parentDataProperty"),rootData:new Pe.Name("rootData"),dynamicAnchors:new Pe.Name("dynamicAnchors"),vErrors:new Pe.Name("vErrors"),errors:new Pe.Name("errors"),this:new Pe.Name("this"),self:new Pe.Name("self"),scope:new Pe.Name("scope"),json:new Pe.Name("json"),jsonPos:new Pe.Name("jsonPos"),jsonLen:new Pe.Name("jsonLen"),jsonPart:new Pe.Name("jsonPart")};Eo.default=Tg});var ln=P(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.extendErrors=Ne.resetErrorsCount=Ne.reportExtraError=Ne.reportError=Ne.keyword$DataError=Ne.keywordError=void 0;var G=x(),ki=F(),Ce=Je();Ne.keywordError={message:({keyword:e})=>(0,G.str)`must pass "${e}" keyword validation`};Ne.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,G.str)`"${e}" keyword must be ${t} ($data)`:(0,G.str)`"${e}" keyword is invalid ($data)`};function xg(e,t=Ne.keywordError,r,n){let{it:i}=e,{gen:a,compositeRule:o,allErrors:s}=i,c=Nl(e,t,r);n??(o||s)?Rl(a,c):Pl(i,(0,G._)`[${c}]`)}Ne.reportError=xg;function Lg(e,t=Ne.keywordError,r){let{it:n}=e,{gen:i,compositeRule:a,allErrors:o}=n,s=Nl(e,t,r);Rl(i,s),a||o||Pl(n,Ce.default.vErrors)}Ne.reportExtraError=Lg;function Vg(e,t){e.assign(Ce.default.errors,t),e.if((0,G._)`${Ce.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,G._)`${Ce.default.vErrors}.length`,t),()=>e.assign(Ce.default.vErrors,null)))}Ne.resetErrorsCount=Vg;function Mg({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,Ce.default.errors,s=>{e.const(o,(0,G._)`${Ce.default.vErrors}[${s}]`),e.if((0,G._)`${o}.instancePath === undefined`,()=>e.assign((0,G._)`${o}.instancePath`,(0,G.strConcat)(Ce.default.instancePath,a.errorPath))),e.assign((0,G._)`${o}.schemaPath`,(0,G.str)`${a.errSchemaPath}/${t}`),a.opts.verbose&&(e.assign((0,G._)`${o}.schema`,r),e.assign((0,G._)`${o}.data`,n))})}Ne.extendErrors=Mg;function Rl(e,t){let r=e.const("err",t);e.if((0,G._)`${Ce.default.vErrors} === null`,()=>e.assign(Ce.default.vErrors,(0,G._)`[${r}]`),(0,G._)`${Ce.default.vErrors}.push(${r})`),e.code((0,G._)`${Ce.default.errors}++`)}function Pl(e,t){let{gen:r,validateName:n,schemaEnv:i}=e;i.$async?r.throw((0,G._)`new ${e.ValidationError}(${t})`):(r.assign((0,G._)`${n}.errors`,t),r.return(!1))}var Yt={keyword:new G.Name("keyword"),schemaPath:new G.Name("schemaPath"),params:new G.Name("params"),propertyName:new G.Name("propertyName"),message:new G.Name("message"),schema:new G.Name("schema"),parentSchema:new G.Name("parentSchema")};function Nl(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,G._)`{}`:qg(e,t,r)}function qg(e,t,r={}){let{gen:n,it:i}=e,a=[Fg(i,r),Ug(e,r)];return zg(e,t,a),n.object(...a)}function Fg({errorPath:e},{instancePath:t}){let r=t?(0,G.str)`${e}${(0,ki.getErrorPath)(t,ki.Type.Str)}`:e;return[Ce.default.instancePath,(0,G.strConcat)(Ce.default.instancePath,r)]}function Ug({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let i=n?t:(0,G.str)`${t}/${e}`;return r&&(i=(0,G.str)`${i}${(0,ki.getErrorPath)(r,ki.Type.Str)}`),[Yt.schemaPath,i]}function zg(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,G._)`{}`]),c.messages&&n.push([Yt.message,typeof r=="function"?r(e):r]),c.verbose&&n.push([Yt.schema,o],[Yt.parentSchema,(0,G._)`${l}${p}`],[Ce.default.data,a]),d&&n.push([Yt.propertyName,d])}});var Sl=P(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});Er.boolOrEmptySchema=Er.topBoolOrEmptySchema=void 0;var Bg=ln(),Gg=x(),Jg=Je(),Wg={message:"boolean schema is false"};function Kg(e){let{gen:t,schema:r,validateName:n}=e;r===!1?Dl(e,!1):typeof r=="object"&&r.$async===!0?t.return(Jg.default.data):(t.assign((0,Gg._)`${n}.errors`,null),t.return(!0))}Er.topBoolOrEmptySchema=Kg;function Yg(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),Dl(e)):r.var(t,!0)}Er.boolOrEmptySchema=Yg;function Dl(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,Bg.reportError)(i,Wg,void 0,t)}});var Ao=P(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});Ar.getRules=Ar.isJSONType=void 0;var Hg=["string","number","integer","boolean","null","object","array"],Zg=new Set(Hg);function Xg(e){return typeof e=="string"&&Zg.has(e)}Ar.isJSONType=Xg;function Qg(){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=Qg});var Ro=P(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.shouldUseRule=Dt.shouldUseGroup=Dt.schemaHasRulesForType=void 0;function eh({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&jl(e,n)}Dt.schemaHasRulesForType=eh;function jl(e,t){return t.rules.some(r=>$l(e,r))}Dt.shouldUseGroup=jl;function $l(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=$l});var dn=P(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.reportTypeError=De.checkDataTypes=De.checkDataType=De.coerceAndCheckDataType=De.getJSONTypes=De.getSchemaTypes=De.DataType=void 0;var th=Ao(),rh=Ro(),nh=ln(),L=x(),Ol=F(),Rr;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(Rr||(De.DataType=Rr={}));function ih(e){let t=Cl(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}De.getSchemaTypes=ih;function Cl(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(th.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}De.getJSONTypes=Cl;function ah(e,t){let{gen:r,data:n,opts:i}=e,a=oh(t,i.coerceTypes),o=t.length>0&&!(a.length===0&&t.length===1&&(0,rh.schemaHasRulesForType)(e,t[0]));if(o){let s=No(t,n,i.strictNumbers,Rr.Wrong);r.if(s,()=>{a.length?sh(e,t,a):Do(e)})}return o}De.coerceAndCheckDataType=ah;var Tl=new Set(["string","number","integer","boolean","null"]);function oh(e,t){return t?e.filter(r=>Tl.has(r)||t==="array"&&r==="array"):[]}function sh(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(No(t,i,a.strictNumbers),()=>n.assign(s,i))),n.if((0,L._)`${s} !== undefined`);for(let d of r)(Tl.has(d)||d==="array"&&a.coerceTypes==="array")&&c(d);n.else(),Do(e),n.endIf(),n.if((0,L._)`${s} !== undefined`,()=>{n.assign(i,s),ch(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,$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},
|
|
5
|
+
|| ${o} === "boolean" || ${i} === null`).assign(s,(0,L._)`[${i}]`)}}}function ch({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,L._)`${t} !== undefined`,()=>e.assign((0,L._)`${t}[${r}]`,n))}function Po(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)}}De.checkDataType=Po;function No(e,t,r,n){if(e.length===1)return Po(e[0],t,r,n);let i,a=(0,Ol.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,Po(o,t,r,n));return i}De.checkDataTypes=No;var lh={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,L._)`{type: ${e}}`:(0,L._)`{type: ${t}}`};function Do(e){let t=dh(e);(0,nh.reportError)(t,lh)}De.reportTypeError=Do;function dh(e){let{gen:t,data:r,schema:n}=e,i=(0,Ol.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:e}}});var Ll=P(_i=>{"use strict";Object.defineProperty(_i,"__esModule",{value:!0});_i.assignDefaults=void 0;var Pr=x(),ph=F();function uh(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let i in r)xl(e,i,r[i].default);else t==="array"&&Array.isArray(n)&&n.forEach((i,a)=>xl(e,a,i.default))}_i.assignDefaults=uh;function xl(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,ph.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=P(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.validateUnion=te.validateArray=te.usePattern=te.callValidateCode=te.schemaProperties=te.allSchemaProperties=te.noPropertyInData=te.propertyInData=te.isOwnProperty=te.hasPropFunc=te.reportMissingProp=te.checkMissingProp=te.checkReportMissingProp=void 0;var ce=x(),So=F(),St=Je(),fh=F();function mh(e,t){let{gen:r,data:n,it:i}=e;r.if($o(r,n,t,i.opts.ownProperties),()=>{e.setParams({missingProperty:(0,ce._)`${t}`},!0),e.error()})}te.checkReportMissingProp=mh;function gh({gen:e,data:t,it:{opts:r}},n,i){return(0,ce.or)(...n.map(a=>(0,ce.and)($o(e,t,a,r.ownProperties),(0,ce._)`${i} = ${a}`)))}te.checkMissingProp=gh;function hh(e,t){e.setParams({missingProperty:t},!0),e.error()}te.reportMissingProp=hh;function Vl(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ce._)`Object.prototype.hasOwnProperty`})}te.hasPropFunc=Vl;function jo(e,t,r){return(0,ce._)`${Vl(e)}.call(${t}, ${r})`}te.isOwnProperty=jo;function yh(e,t,r,n){let i=(0,ce._)`${t}${(0,ce.getProperty)(r)} !== undefined`;return n?(0,ce._)`${i} && ${jo(e,t,r)}`:i}te.propertyInData=yh;function $o(e,t,r,n){let i=(0,ce._)`${t}${(0,ce.getProperty)(r)} === undefined`;return n?(0,ce.or)(i,(0,ce.not)(jo(e,t,r))):i}te.noPropertyInData=$o;function Ml(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}te.allSchemaProperties=Ml;function wh(e,t){return Ml(t).filter(r=>!(0,So.alwaysValidSchema)(e,t[r]))}te.schemaProperties=wh;function vh({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 f=(0,ce._)`${l}, ${r.object(...p)}`;return c!==ce.nil?(0,ce._)`${s}.call(${c}, ${f})`:(0,ce._)`${s}(${f})`}te.callValidateCode=vh;var Ih=(0,ce._)`new RegExp`;function bh({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"?Ih:(0,fh.useFunc)(e,i)}(${r}, ${n})`})}te.usePattern=bh;function kh(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:So.Type.Num},a),t.if((0,ce.not)(a),s)})}}te.validateArray=kh;function _h(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,So.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))}te.validateUnion=_h});var Ul=P(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.validateKeywordUsage=ft.validSchemaType=ft.funcKeywordCode=ft.macroKeywordCode=void 0;var Te=x(),Ht=Je(),Eh=We(),Ah=ln();function Rh(e,t){let{gen:r,keyword:n,schema:i,parentSchema:a,it:o}=e,s=t.macro.call(o.self,i,a,o),c=Fl(r,n,s);o.opts.validateSchema!==!1&&o.self.validateSchema(s,!0);let d=r.name("valid");e.subschema({schema:s,schemaPath:Te.nil,errSchemaPath:`${o.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},d),e.pass(d,()=>e.error(!0))}ft.macroKeywordCode=Rh;function Ph(e,t){var r;let{gen:n,keyword:i,schema:a,parentSchema:o,$data:s,it:c}=e;Dh(c,t);let d=!s&&t.compile?t.compile.call(c.self,a,o,c):t.validate,l=Fl(n,i,d),p=n.let("valid");e.block$data(p,f),e.ok((r=t.valid)!==null&&r!==void 0?r:p);function f(){if(t.errors===!1)g(),t.modifying&&ql(e),h(()=>e.error());else{let y=t.async?u():m();t.modifying&&ql(e),h(()=>Nh(e,y))}}function u(){let y=n.let("ruleErrs",null);return n.try(()=>g((0,Te._)`await `),k=>n.assign(p,!1).if((0,Te._)`${k} instanceof ${c.ValidationError}`,()=>n.assign(y,(0,Te._)`${k}.errors`),()=>n.throw(k))),y}function m(){let y=(0,Te._)`${l}.errors`;return n.assign(y,null),g(Te.nil),y}function g(y=t.async?(0,Te._)`await `:Te.nil){let k=c.opts.passContext?Ht.default.this:Ht.default.self,b=!("compile"in t&&!s||t.schema===!1);n.assign(p,(0,Te._)`${y}${(0,Eh.callValidateCode)(e,l,k,b)}`,t.modifying)}function h(y){var k;n.if((0,Te.not)((k=t.valid)!==null&&k!==void 0?k:p),y)}}ft.funcKeywordCode=Ph;function ql(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,Te._)`${n.parentData}[${n.parentDataProperty}]`))}function Nh(e,t){let{gen:r}=e;r.if((0,Te._)`Array.isArray(${t})`,()=>{r.assign(Ht.default.vErrors,(0,Te._)`${Ht.default.vErrors} === null ? ${t} : ${Ht.default.vErrors}.concat(${t})`).assign(Ht.default.errors,(0,Te._)`${Ht.default.vErrors}.length`),(0,Ah.extendErrors)(e)},()=>e.error())}function Dh({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function Fl(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,Te.stringify)(r)})}function Sh(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=Sh;function jh({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=jh});var Bl=P(jt=>{"use strict";Object.defineProperty(jt,"__esModule",{value:!0});jt.extendSubschemaMode=jt.extendSubschemaData=jt.getSubschema=void 0;var mt=x(),zl=F();function $h(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,zl.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=$h;function Oh(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,f=s.let("data",(0,mt._)`${t.data}${(0,mt.getProperty)(r)}`,!0);c(f),e.errorPath=(0,mt.str)`${d}${(0,zl.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=Oh;function Ch(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=Ch});var Oo=P((sR,Gl)=>{"use strict";Gl.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 Wl=P((cR,Jl)=>{"use strict";var $t=Jl.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 f=0;f<p.length;f++)Ei(e,t,r,p[f],i+"/"+l+"/"+f,a,i,l,n,f)}else if(l in $t.propsKeywords){if(p&&typeof p=="object")for(var u in p)Ei(e,t,r,p[u],i+"/"+l+"/"+Th(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 Th(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var pn=P(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.getSchemaRefs=Me.resolveUrl=Me.normalizeId=Me._getFullPath=Me.getFullPath=Me.inlineRef=void 0;var xh=F(),Lh=Oo(),Vh=Wl(),Mh=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function qh(e,t=!0){return typeof e=="boolean"?!0:t===!0?!Co(e):t?Kl(e)<=t:!1}Me.inlineRef=qh;var Fh=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Co(e){for(let t in e){if(Fh.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(Co)||typeof r=="object"&&Co(r))return!0}return!1}function Kl(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!Mh.has(r)&&(typeof e[r]=="object"&&(0,xh.eachItem)(e[r],n=>t+=Kl(n)),t===1/0))return 1/0}return t}function Yl(e,t="",r){r!==!1&&(t=Nr(t));let n=e.parse(t);return Hl(e,n)}Me.getFullPath=Yl;function Hl(e,t){return e.serialize(t).split("#")[0]+"#"}Me._getFullPath=Hl;var Uh=/#\/?$/;function Nr(e){return e?e.replace(Uh,""):""}Me.normalizeId=Nr;function zh(e,t,r){return r=Nr(r),e.resolve(t,r)}Me.resolveUrl=zh;var Bh=/^[a-z_][-a-z0-9._]*$/i;function Gh(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,i=Nr(e[r]||t),a={"":i},o=Yl(n,i,!1),s={},c=new Set;return Vh(e,{allKeys:!0},(p,f,u,m)=>{if(m===void 0)return;let g=o+f,h=a[m];typeof p[r]=="string"&&(h=y.call(this,p[r])),k.call(this,p.$anchor),k.call(this,p.$dynamicAnchor),a[f]=h;function y(b){let E=this.opts.uriResolver.resolve;if(b=Nr(h?E(h,b):b),c.has(b))throw l(b);c.add(b);let w=this.refs[b];return typeof w=="string"&&(w=this.refs[w]),typeof w=="object"?d(p,w.schema,b):b!==Nr(g)&&(b[0]==="#"?(d(p,s[b],b),s[b]=p):this.refs[b]=g),b}function k(b){if(typeof b=="string"){if(!Bh.test(b))throw new Error(`invalid anchor "${b}"`);y.call(this,`#${b}`)}}}),s;function d(p,f,u){if(f!==void 0&&!Lh(p,f))throw l(u)}function l(p){return new Error(`reference "${p}" resolves to more than one schema`)}}Me.getSchemaRefs=Gh});var mn=P(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.getData=Ot.KeywordCxt=Ot.validateFunctionCode=void 0;var td=Sl(),Zl=dn(),xo=Ro(),Ai=dn(),Jh=Ll(),fn=Ul(),To=Bl(),D=x(),T=Je(),Wh=pn(),bt=F(),un=ln();function Kh(e){if(id(e)&&(ad(e),nd(e))){Zh(e);return}rd(e,()=>(0,td.topBoolOrEmptySchema)(e))}Ot.validateFunctionCode=Kh;function rd({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"; ${Xl(r,i)}`),Hh(e,i),e.code(a)}):e.func(t,(0,D._)`${T.default.data}, ${Yh(i)}`,n.$async,()=>e.code(Xl(r,i)).code(a))}function Yh(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 Hh(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 Zh(e){let{schema:t,opts:r,gen:n}=e;rd(e,()=>{r.$comment&&t.$comment&&sd(e),ry(e),n.let(T.default.vErrors,null),n.let(T.default.errors,0),r.unevaluated&&Xh(e),od(e),ay(e)})}function Xh(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 Xl(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 Qh(e,t){if(id(e)&&(ad(e),nd(e))){ey(e,t);return}(0,td.boolOrEmptySchema)(e,t)}function nd({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 id(e){return typeof e.schema!="boolean"}function ey(e,t){let{schema:r,gen:n,opts:i}=e;i.$comment&&r.$comment&&sd(e),ny(e),iy(e);let a=n.const("_errs",T.default.errors);od(e,a),n.var(t,(0,D._)`${a} === ${T.default.errors}`)}function ad(e){(0,bt.checkUnknownRules)(e),ty(e)}function od(e,t){if(e.opts.jtd)return Ql(e,[],!1,t);let r=(0,Zl.getSchemaTypes)(e.schema),n=(0,Zl.coerceAndCheckDataType)(e,r);Ql(e,r,!n,t)}function ty(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 ry(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 ny(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,Wh.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function iy(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function sd({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 ay(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&&oy(e),t.return((0,D._)`${T.default.errors} === 0`))}function oy({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 Ql(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(()=>ld(e,"$ref",l.all.$ref.definition));return}c.jtd||sy(e,t),i.block(()=>{for(let f of l.rules)p(f);p(l.post)});function p(f){(0,xo.shouldUseGroup)(a,f)&&(f.type?(i.if((0,Ai.checkDataType)(f.type,o,c.strictNumbers)),ed(e,f),t.length===1&&t[0]===f.type&&r&&(i.else(),(0,Ai.reportTypeError)(e)),i.endIf()):ed(e,f),s||i.if((0,D._)`${T.default.errors} === ${n||0}`))}}function ed(e,t){let{gen:r,schema:n,opts:{useDefaults:i}}=e;i&&(0,Jh.assignDefaults)(e,t.type),r.block(()=>{for(let a of t.rules)(0,xo.shouldUseRule)(n,a)&&ld(e,a.keyword,a.definition,t.type)})}function sy(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(cy(e,t),e.opts.allowUnionTypes||ly(e,t),dy(e,e.dataTypes))}function cy(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{cd(e.dataTypes,r)||Lo(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),uy(e,t)}}function ly(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&Lo(e,"use allowUnionTypes to allow union type keyword")}function dy(e,t){let r=e.self.RULES.all;for(let n in r){let i=r[n];if(typeof i=="object"&&(0,xo.shouldUseRule)(e.schema,i)){let{type:a}=i.definition;a.length&&!a.some(o=>py(t,o))&&Lo(e,`missing type "${a.join(",")}" for keyword "${n}"`)}}}function py(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function cd(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function uy(e,t){let r=[];for(let n of e.dataTypes)cd(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}function Lo(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",dd(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,To.getSubschema)(this.it,t);(0,To.extendSubschemaData)(n,this.it,t),(0,To.extendSubschemaMode)(n,t);let i={...this.it,...n,items:void 0,props:void 0};return Qh(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 ld(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 fy=/^\/(?:[^~]|~0|~1)*$/,my=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function dd(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let i,a;if(e==="")return T.default.rootData;if(e[0]==="/"){if(!fy.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);i=e,a=T.default.rootData}else{let d=my.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=dd});var Pi=P(Mo=>{"use strict";Object.defineProperty(Mo,"__esModule",{value:!0});var Vo=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};Mo.default=Vo});var gn=P(Uo=>{"use strict";Object.defineProperty(Uo,"__esModule",{value:!0});var qo=pn(),Fo=class extends Error{constructor(t,r,n,i){super(i||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,qo.resolveUrl)(t,r,n),this.missingSchema=(0,qo.normalizeId)((0,qo.getFullPath)(t,this.missingRef))}};Uo.default=Fo});var hn=P(Ke=>{"use strict";Object.defineProperty(Ke,"__esModule",{value:!0});Ke.resolveSchema=Ke.getCompilingSchema=Ke.resolveRef=Ke.compileSchema=Ke.SchemaEnv=void 0;var nt=x(),gy=Pi(),Zt=Je(),it=pn(),pd=F(),hy=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 Bo(e){let t=ud.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:gy.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,hy.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:m,items:g}=d;u.evaluated={props:m instanceof nt.Name?void 0:m,items:g instanceof nt.Name?void 0:g,dynamicProps:m 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=Bo;function yy(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=Iy.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]=wy.call(this,a)}Ke.resolveRef=yy;function wy(e){return(0,it.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:Bo.call(this,e)}function ud(e){for(let t of this._compilations)if(vy(t,e))return t}Ke.getCompilingSchema=ud;function vy(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function Iy(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 zo.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:zo.call(this,r,s)}if(typeof o?.schema=="object"){if(o.validate||Bo.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 zo.call(this,r,o)}}Ke.resolveSchema=Ni;var by=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function zo(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,pd.unescapeFragment)(s)];if(c===void 0)return;r=c;let d=typeof r=="object"&&r[this.opts.schemaId];!by.has(s)&&d&&(t=(0,it.resolveUrl)(this.opts.uriResolver,t,d))}let a;if(typeof r!="boolean"&&r.$ref&&!(0,pd.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 fd=P((mR,ky)=>{ky.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 Wo=P((gR,vd)=>{"use strict";var _y=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),gd=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),Go=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),hd=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),Ey=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 Ay=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function md(e){return e.length=0,!0}function Ry(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 Py(e){let t=0,r={error:!1,address:"",zone:""},n=[],i=[],a=!1,o=!1,s=Ry;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=md}else{i.push(d);continue}}return i.length&&(s===md?r.zone=i.join(""):o?n.push(i.join("")):n.push(Jo(i))),r.address=n.join(""),r}function yd(e){if(Ny(e,":")<2)return{host:e,isIPV6:!1};let t=Py(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 Ny(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}function Dy(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 Sy={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},jy=/[@/?#:]/g,$y=/[@/?#]/g;function wd(e,t){let r=t?$y:jy;return r.lastIndex=0,e.replace(r,n=>Sy[n])}function Oy(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(Go(i)){let a=i.toUpperCase(),o=String.fromCharCode(parseInt(a,16));t&&hd(o)?r+=o:r+="%"+a,n+=2;continue}}r+=e[n]}return r}function Cy(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(Go(n)){let i=n.toUpperCase(),a=String.fromCharCode(parseInt(i,16));a!=="."&&hd(a)?t+=a:t+="%"+i,r+=2;continue}}Ey(e[r])?t+=e[r]:t+=escape(e[r])}return t}function Ty(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(Go(n)){t+="%"+n.toUpperCase(),r+=2;continue}}t+=escape(e[r])}return t}function xy(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!gd(r)){let n=yd(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=wd(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}vd.exports={nonSimpleDomain:Ay,recomposeAuthority:xy,reescapeHostDelimiters:wd,normalizePercentEncoding:Oy,normalizePathEncoding:Cy,escapePreservingEscapes:Ty,removeDotSegments:Dy,isIPv4:gd,isUUID:_y,normalizeIPv6:yd,stringArrayToHexStripped:Jo}});var Ed=P((hR,_d)=>{"use strict";var{isUUID:Ly}=Wo(),Vy=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,My=["http","https","ws","wss","urn","urn:uuid"];function qy(e){return My.indexOf(e)!==-1}function Ko(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 Id(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function bd(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 Fy(e){return e.secure=Ko(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function Uy(e){if((e.port===(Ko(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 zy(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(Vy);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=Yo(i);e.path=void 0,a&&(e=a.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function By(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=Yo(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 Gy(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!Ly(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function Jy(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var kd={scheme:"http",domainHost:!0,parse:Id,serialize:bd},Wy={scheme:"https",domainHost:kd.domainHost,parse:Id,serialize:bd},Di={scheme:"ws",domainHost:!0,parse:Fy,serialize:Uy},Ky={scheme:"wss",domainHost:Di.domainHost,parse:Di.parse,serialize:Di.serialize},Yy={scheme:"urn",parse:zy,serialize:By,skipNormalize:!0},Hy={scheme:"urn:uuid",parse:Gy,serialize:Jy,skipNormalize:!0},Si={http:kd,https:Wy,ws:Di,wss:Ky,urn:Yy,"urn:uuid":Hy};Object.setPrototypeOf(Si,null);function Yo(e){return e&&(Si[e]||Si[e.toLowerCase()])||void 0}_d.exports={wsIsSecure:Ko,SCHEMES:Si,isValidSchemeName:qy,getSchemeHandler:Yo}});var Dd=P((yR,Oi)=>{"use strict";var{normalizeIPv6:Zy,removeDotSegments:yn,recomposeAuthority:Xy,normalizePercentEncoding:Qy,normalizePathEncoding:ew,escapePreservingEscapes:tw,reescapeHostDelimiters:rw,isIPv4:nw,nonSimpleDomain:iw}=Wo(),{SCHEMES:aw,getSchemeHandler:Rd}=Ed();function ow(e,t){return typeof e=="string"?e=fw(e,t):typeof e=="object"&&(e=$i(Xt(e,t),t)),e}function sw(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=Pd(i,o,n,!0);return n.skipEscape=!0,Xt(c,n)}function Pd(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 cw(e,t,r){let n=Ad(e,r),i=Ad(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=Rd(n.scheme||r.scheme);a&&a.serialize&&a.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=Qy(r.path):(r.path=tw(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&i.push(r.scheme,":");let o=Xy(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 lw=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,dw=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,pw=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function uw(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(dw);o!==null&&o[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",i=!0);let s=e.match(pw);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(lw);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=uw(n,c);if(d!==void 0&&(n.error=n.error||d,i=!0),n.host)if(nw(n.host)===!1){let f=Zy(n.host);n.host=f.host.toLowerCase(),a=f.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=Rd(r.scheme||n.scheme);if(!r.unicodeSupport&&(!l||!l.unicodeSupport)&&n.host&&(r.domainHost||l&&l.domainHost)&&a===!1&&iw(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=rw(unescape(n.host),a))),n.path&&(n.path=ew(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 fw(e,t){return Nd(e,t).normalized}function Nd(e,t){let{parsed:r,malformedAuthorityOrPort:n}=ji(e,t);return{normalized:n?e:Xt(r,t),malformedAuthorityOrPort:n}}function Ad(e,t){if(typeof e=="string"){let{normalized:r,malformedAuthorityOrPort:n}=Nd(e,t);return n?void 0:r}if(typeof e=="object")return Xt(e,t)}var Ho={SCHEMES:aw,normalize:ow,resolve:sw,resolveComponent:Pd,equal:cw,serialize:Xt,parse:$i};Oi.exports=Ho;Oi.exports.default=Ho;Oi.exports.fastUri=Ho});var jd=P(Zo=>{"use strict";Object.defineProperty(Zo,"__esModule",{value:!0});var Sd=Dd();Sd.code='require("ajv/dist/runtime/uri").default';Zo.default=Sd});var Md=P(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 mw=mn();Object.defineProperty(Ie,"KeywordCxt",{enumerable:!0,get:function(){return mw.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 gw=Pi(),xd=gn(),hw=Ao(),wn=hn(),yw=x(),vn=pn(),Ci=dn(),Qo=F(),$d=fd(),ww=jd(),Ld=(e,t)=>new RegExp(e,t);Ld.code="new RegExp";var vw=["removeAdditional","useDefaults","coerceTypes"],Iw=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),bw={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."},kw={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Od=200;function _w(e){var t,r,n,i,a,o,s,c,d,l,p,f,u,m,g,h,y,k,b,E,w,_,S,O,se;let $=e.strict,R=(t=e.code)===null||t===void 0?void 0:t.optimize,Y=R===!0||R===void 0?1:R||0,ne=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Ld,Be=(i=e.uriResolver)!==null&&i!==void 0?i:ww.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:(f=(p=e.strictTuples)!==null&&p!==void 0?p:$)!==null&&f!==void 0?f:"log",strictRequired:(m=(u=e.strictRequired)!==null&&u!==void 0?u:$)!==null&&m!==void 0?m:!1,code:e.code?{...e.code,optimize:Y,regExp:ne}:{optimize:Y,regExp:ne},loopRequired:(g=e.loopRequired)!==null&&g!==void 0?g:Od,loopEnum:(h=e.loopEnum)!==null&&h!==void 0?h:Od,meta:(y=e.meta)!==null&&y!==void 0?y:!0,messages:(k=e.messages)!==null&&k!==void 0?k:!0,inlineRefs:(b=e.inlineRefs)!==null&&b!==void 0?b:!0,schemaId:(E=e.schemaId)!==null&&E!==void 0?E:"$id",addUsedSchema:(w=e.addUsedSchema)!==null&&w!==void 0?w:!0,validateSchema:(_=e.validateSchema)!==null&&_!==void 0?_:!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,..._w(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new yw.ValueScope({scope:{},prefixes:Iw,es5:r,lines:n}),this.logger=Dw(t.logger);let i=t.validateFormats;t.validateFormats=!1,this.RULES=(0,hw.getRules)(),Cd.call(this,bw,t,"NOT SUPPORTED"),Cd.call(this,kw,t,"DEPRECATED","warn"),this._metaOpts=Pw.call(this),t.formats&&Aw.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&Rw.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),Ew.call(this),t.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,i=$d;n==="id"&&(i={...$d},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 f=this._addSchema(l,p);return f.validate||o.call(this,f)}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 xd.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=Td.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=Td.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(jw.call(this,n,r),!r)return(0,Qo.eachItem)(n,a=>Xo.call(this,a)),this;Ow.call(this,r);let i={...r,type:(0,Ci.getJSONTypes)(r.type),schemaType:(0,Ci.getJSONTypes)(r.schemaType)};return(0,Qo.eachItem)(n,i.type.length===0?a=>Xo.call(this,a,i):a=>i.type.forEach(o=>Xo.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]=Vd(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=gw.default;In.MissingRefError=xd.default;Ie.default=In;function Cd(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 Td(e){return e=(0,vn.normalizeId)(e),this.schemas[e]||this.refs[e]}function Ew(){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 Aw(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function Rw(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 Pw(){let e={...this.opts};for(let t of vw)delete e[t];return e}var Nw={log(){},warn(){},error(){}};function Dw(e){if(e===!1)return Nw;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 Sw=/^[a-z_$][a-z0-9_$:-]*$/i;function jw(e,t){let{RULES:r}=this;if((0,Qo.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!Sw.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 Xo(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?$w.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 $w(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 Ow(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=Vd(t)),e.validateSchema=this.compile(t,!0))}var Cw={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Vd(e){return{anyOf:[e,Cw]}}});var qd=P(es=>{"use strict";Object.defineProperty(es,"__esModule",{value:!0});var Tw={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};es.default=Tw});var Li=P(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.callRef=Qt.getValidate=void 0;var xw=gn(),Fd=We(),qe=x(),jr=Je(),Ud=hn(),Ti=F(),Lw={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 xw.default(n.opts.uriResolver,i,r);if(l instanceof Ud.SchemaEnv)return f(l);return u(l);function p(){if(a===d)return xi(e,o,a,a.$async);let m=t.scopeValue("root",{ref:d});return xi(e,(0,qe._)`${m}.validate`,d,d.$async)}function f(m){let g=zd(e,m);xi(e,g,m,m.$async)}function u(m){let g=t.scopeValue("schema",s.code.source===!0?{ref:m,code:(0,qe.stringify)(m)}:{ref:m}),h=t.name("valid"),y=e.subschema({schema:m,dataTypes:[],schemaPath:qe.nil,topSchemaRef:g,errSchemaPath:r},h);e.mergeEvaluated(y),e.ok(h)}}};function zd(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=zd;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 m=i.let("valid");i.try(()=>{i.code((0,qe._)`await ${(0,Fd.callValidateCode)(e,t,d)}`),u(t),o||i.assign(m,!0)},g=>{i.if((0,qe._)`!(${g} instanceof ${a.ValidationError})`,()=>i.throw(g)),f(g),o||i.assign(m,!1)}),e.ok(m)}function p(){e.result((0,Fd.callValidateCode)(e,t,d),()=>u(t),()=>f(t))}function f(m){let g=(0,qe._)`${m}.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(m){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 y=i.var("props",(0,qe._)`${m}.evaluated.props`);a.props=Ti.mergeEvaluated.props(i,y,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 y=i.var("items",(0,qe._)`${m}.evaluated.items`);a.items=Ti.mergeEvaluated.items(i,y,a.items,qe.Name)}}}Qt.callRef=xi;Qt.default=Lw});var Bd=P(ts=>{"use strict";Object.defineProperty(ts,"__esModule",{value:!0});var Vw=qd(),Mw=Li(),qw=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Vw.default,Mw.default];ts.default=qw});var Gd=P(rs=>{"use strict";Object.defineProperty(rs,"__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}},Fw={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}}`},Uw={keyword:Object.keys(Mi),type:"number",schemaType:"number",$data:!0,error:Fw,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,Vi._)`${r} ${Mi[t].fail} ${n} || isNaN(${r})`)}};rs.default=Uw});var Jd=P(ns=>{"use strict";Object.defineProperty(ns,"__esModule",{value:!0});var bn=x(),zw={message:({schemaCode:e})=>(0,bn.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,bn._)`{multipleOf: ${e}}`},Bw={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:zw,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}))`)}};ns.default=Bw});var Kd=P(is=>{"use strict";Object.defineProperty(is,"__esModule",{value:!0});function Wd(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}is.default=Wd;Wd.code='require("ajv/dist/runtime/ucs2length").default'});var Yd=P(as=>{"use strict";Object.defineProperty(as,"__esModule",{value:!0});var er=x(),Gw=F(),Jw=Kd(),Ww={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}}`},Kw={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Ww,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,Gw.useFunc)(e.gen,Jw.default)}(${r})`;e.fail$data((0,er._)`${o} ${a} ${n}`)}};as.default=Kw});var Hd=P(os=>{"use strict";Object.defineProperty(os,"__esModule",{value:!0});var Yw=We(),Hw=F(),$r=x(),Zw={message:({schemaCode:e})=>(0,$r.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,$r._)`{pattern: ${e}}`},Xw={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Zw,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,Hw.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,Yw.usePattern)(e,i);e.fail$data((0,$r._)`!${c}.test(${r})`)}}};os.default=Xw});var Zd=P(ss=>{"use strict";Object.defineProperty(ss,"__esModule",{value:!0});var kn=x(),Qw={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}}`},ev={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Qw,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}`)}};ss.default=ev});var Xd=P(cs=>{"use strict";Object.defineProperty(cs,"__esModule",{value:!0});var _n=We(),En=x(),tv=F(),rv={message:({params:{missingProperty:e}})=>(0,En.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,En._)`{missingProperty: ${e}}`},nv={keyword:"required",type:"object",schemaType:"array",$data:!0,error:rv,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:m}=e.it;for(let g of r)if(u?.[g]===void 0&&!m.has(g)){let h=o.schemaEnv.baseId+o.errSchemaPath,y=`required property "${g}" is not defined at "${h}" (strictRequired)`;(0,tv.checkStrictMode)(o,y,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 m=t.let("valid",!0);e.block$data(m,()=>f(u,m)),e.ok(m)}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 f(u,m){e.setParams({missingProperty:u}),t.forOf(u,n,()=>{t.assign(m,(0,_n.propertyInData)(t,i,u,s.ownProperties)),t.if((0,En.not)(m),()=>{e.error(),t.break()})},En.nil)}}};cs.default=nv});var Qd=P(ls=>{"use strict";Object.defineProperty(ls,"__esModule",{value:!0});var An=x(),iv={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}}`},av={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:iv,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}`)}};ls.default=av});var qi=P(ds=>{"use strict";Object.defineProperty(ds,"__esModule",{value:!0});var ep=Oo();ep.code='require("ajv/dist/runtime/equal").default';ds.default=ep});var tp=P(us=>{"use strict";Object.defineProperty(us,"__esModule",{value:!0});var ps=dn(),be=x(),ov=F(),sv=qi(),cv={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}}`},lv={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:cv,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,ps.getSchemaTypes)(a.items):[];e.block$data(c,l,(0,be._)`${o} === false`),e.ok(c);function l(){let m=t.let("i",(0,be._)`${r}.length`),g=t.let("j");e.setParams({i:m,j:g}),t.assign(c,!0),t.if((0,be._)`${m} > 1`,()=>(p()?f:u)(m,g))}function p(){return d.length>0&&!d.some(m=>m==="object"||m==="array")}function f(m,g){let h=t.name("item"),y=(0,ps.checkDataTypes)(d,h,s.opts.strictNumbers,ps.DataType.Wrong),k=t.const("indices",(0,be._)`{}`);t.for((0,be._)`;${m}--;`,()=>{t.let(h,(0,be._)`${r}[${m}]`),t.if(y,(0,be._)`continue`),d.length>1&&t.if((0,be._)`typeof ${h} == "string"`,(0,be._)`${h} += "_"`),t.if((0,be._)`typeof ${k}[${h}] == "number"`,()=>{t.assign(g,(0,be._)`${k}[${h}]`),e.error(),t.assign(c,!1).break()}).code((0,be._)`${k}[${h}] = ${m}`)})}function u(m,g){let h=(0,ov.useFunc)(t,sv.default),y=t.name("outer");t.label(y).for((0,be._)`;${m}--;`,()=>t.for((0,be._)`${g} = ${m}; ${g}--;`,()=>t.if((0,be._)`${h}(${r}[${m}], ${r}[${g}])`,()=>{e.error(),t.assign(c,!1).break(y)})))}}};us.default=lv});var rp=P(ms=>{"use strict";Object.defineProperty(ms,"__esModule",{value:!0});var fs=x(),dv=F(),pv=qi(),uv={message:"must be equal to constant",params:({schemaCode:e})=>(0,fs._)`{allowedValue: ${e}}`},fv={keyword:"const",$data:!0,error:uv,code(e){let{gen:t,data:r,$data:n,schemaCode:i,schema:a}=e;n||a&&typeof a=="object"?e.fail$data((0,fs._)`!${(0,dv.useFunc)(t,pv.default)}(${r}, ${i})`):e.fail((0,fs._)`${a} !== ${r}`)}};ms.default=fv});var np=P(gs=>{"use strict";Object.defineProperty(gs,"__esModule",{value:!0});var Rn=x(),mv=F(),gv=qi(),hv={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,Rn._)`{allowedValues: ${e}}`},yv={keyword:"enum",schemaType:"array",$data:!0,error:hv,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,mv.useFunc)(t,gv.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((m,g)=>f(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 f(u,m){let g=i[m];return typeof g=="object"&&g!==null?(0,Rn._)`${d()}(${r}, ${u}[${m}])`:(0,Rn._)`${r} === ${g}`}}};gs.default=yv});var ip=P(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});var wv=Gd(),vv=Jd(),Iv=Yd(),bv=Hd(),kv=Zd(),_v=Xd(),Ev=Qd(),Av=tp(),Rv=rp(),Pv=np(),Nv=[wv.default,vv.default,Iv.default,bv.default,kv.default,_v.default,Ev.default,Av.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Rv.default,Pv.default];hs.default=Nv});var ws=P(Pn=>{"use strict";Object.defineProperty(Pn,"__esModule",{value:!0});Pn.validateAdditionalItems=void 0;var tr=x(),ys=F(),Dv={message:({params:{len:e}})=>(0,tr.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,tr._)`{limit: ${e}}`},Sv={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Dv,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,ys.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}ap(e,n)}};function ap(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,ys.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:ys.Type.Num},d),o.allErrors||r.if((0,tr.not)(d),()=>r.break())})}}Pn.validateAdditionalItems=ap;Pn.default=Sv});var vs=P(Nn=>{"use strict";Object.defineProperty(Nn,"__esModule",{value:!0});Nn.validateTuple=void 0;var op=x(),Fi=F(),jv=We(),$v={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return sp(e,"additionalItems",t);r.items=!0,!(0,Fi.alwaysValidSchema)(r,t)&&e.ok((0,jv.validateArray)(e))}};function sp(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=Fi.mergeEvaluated.items(n,r.length,s.items));let c=n.name("valid"),d=n.const("len",(0,op._)`${a}.length`);r.forEach((p,f)=>{(0,Fi.alwaysValidSchema)(s,p)||(n.if((0,op._)`${d} > ${f}`,()=>e.subschema({keyword:o,schemaProp:f,dataProp:f},c)),e.ok(c))});function l(p){let{opts:f,errSchemaPath:u}=s,m=r.length,g=m===p.minItems&&(m===p.maxItems||p[t]===!1);if(f.strictTuples&&!g){let h=`"${o}" is ${m}-tuple, but minItems or maxItems/${t} are not specified or different at path "${u}"`;(0,Fi.checkStrictMode)(s,h,f.strictTuples)}}}Nn.validateTuple=sp;Nn.default=$v});var cp=P(Is=>{"use strict";Object.defineProperty(Is,"__esModule",{value:!0});var Ov=vs(),Cv={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,Ov.validateTuple)(e,"items")};Is.default=Cv});var dp=P(bs=>{"use strict";Object.defineProperty(bs,"__esModule",{value:!0});var lp=x(),Tv=F(),xv=We(),Lv=ws(),Vv={message:({params:{len:e}})=>(0,lp.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,lp._)`{limit: ${e}}`},Mv={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Vv,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:i}=r;n.items=!0,!(0,Tv.alwaysValidSchema)(n,t)&&(i?(0,Lv.validateAdditionalItems)(e,i):e.ok((0,xv.validateArray)(e)))}};bs.default=Mv});var pp=P(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});var Ye=x(),Ui=F(),qv={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}}`},Fv={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:qv,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,Ui.checkStrictMode)(a,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(s!==void 0&&o>s){(0,Ui.checkStrictMode)(a,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Ui.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`,f)):(t.let(p,!1),f()),e.result(p,()=>e.reset());function f(){let g=t.name("_valid"),h=t.let("count",0);u(g,()=>t.if(g,()=>m(h)))}function u(g,h){t.forRange("i",0,l,y=>{e.subschema({keyword:"contains",dataProp:y,dataPropType:Ui.Type.Num,compositeRule:!0},g),h()})}function m(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)))}}};ks.default=Fv});var zi=P(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.validateSchemaDeps=gt.validatePropertyDeps=gt.error=void 0;var _s=x(),Uv=F(),Dn=We();gt.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,_s.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,_s._)`{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);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
|
|
8
|
+
deps: ${r}}`};var zv={keyword:"dependencies",type:"object",schemaType:"object",error:gt.error,code(e){let[t,r]=Bv(e);up(e,t),fp(e,r)}};function Bv({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 up(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,_s._)`${c} && (${(0,Dn.checkMissingProp)(e,s,a)})`),(0,Dn.reportMissingProp)(e,a),r.else())}}gt.validatePropertyDeps=up;function fp(e,t=e.schema){let{gen:r,data:n,keyword:i,it:a}=e,o=r.name("valid");for(let s in t)(0,Uv.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=fp;gt.default=zv});var gp=P(Es=>{"use strict";Object.defineProperty(Es,"__esModule",{value:!0});var mp=x(),Gv=F(),Jv={message:"property name must be valid",params:({params:e})=>(0,mp._)`{propertyName: ${e.propertyName}}`},Wv={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Jv,code(e){let{gen:t,schema:r,data:n,it:i}=e;if((0,Gv.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,mp.not)(a),()=>{e.error(!0),i.allErrors||t.break()})}),e.ok(a)}};Es.default=Wv});var Rs=P(As=>{"use strict";Object.defineProperty(As,"__esModule",{value:!0});var Bi=We(),at=x(),Kv=Je(),Gi=F(),Yv={message:"must NOT have additional properties",params:({params:e})=>(0,at._)`{additionalProperty: ${e.additionalProperty}}`},Hv={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Yv,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} === ${Kv.default.errors}`);function p(){t.forIn("key",i,h=>{!d.length&&!l.length?m(h):t.if(f(h),()=>m(h))})}function f(h){let y;if(d.length>8){let k=(0,Gi.schemaRefOrVal)(o,n.properties,"properties");y=(0,Bi.isOwnProperty)(t,k,h)}else d.length?y=(0,at.or)(...d.map(k=>(0,at._)`${h} === ${k}`)):y=at.nil;return l.length&&(y=(0,at.or)(y,...l.map(k=>(0,at._)`${(0,Bi.usePattern)(e,k)}.test(${h})`))),(0,at.not)(y)}function u(h){t.code((0,at._)`delete ${i}[${h}]`)}function m(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 y=t.name("valid");c.removeAdditional==="failing"?(g(h,y,!1),t.if((0,at.not)(y),()=>{e.reset(),u(h)})):(g(h,y),s||t.if((0,at.not)(y),()=>t.break()))}}function g(h,y,k){let b={keyword:"additionalProperties",dataProp:h,dataPropType:Gi.Type.Str};k===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(b,y)}}};As.default=Hv});var wp=P(Ns=>{"use strict";Object.defineProperty(Ns,"__esModule",{value:!0});var Zv=mn(),hp=We(),Ps=F(),yp=Rs(),Xv={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&&yp.default.code(new Zv.KeywordCxt(a,yp.default,"additionalProperties"));let o=(0,hp.allSchemaProperties)(r);for(let p of o)a.definedProperties.add(p);a.opts.unevaluated&&o.length&&a.props!==!0&&(a.props=Ps.mergeEvaluated.props(t,(0,Ps.toHash)(o),a.props));let s=o.filter(p=>!(0,Ps.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,hp.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)}}};Ns.default=Xv});var kp=P(Ds=>{"use strict";Object.defineProperty(Ds,"__esModule",{value:!0});var vp=We(),Ji=x(),Ip=F(),bp=F(),Qv={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,vp.allSchemaProperties)(r),c=s.filter(g=>(0,Ip.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,bp.evaluatedPropsToName)(t,a.props));let{props:p}=a;f();function f(){for(let g of s)d&&u(g),a.allErrors?m(g):(t.var(l,!0),m(g),t.if(l))}function u(g){for(let h in d)new RegExp(g).test(h)&&(0,Ip.checkStrictMode)(a,`property ${h} matches pattern ${g} (use allowMatchingProperties)`)}function m(g){t.forIn("key",n,h=>{t.if((0,Ji._)`${(0,vp.usePattern)(e,g)}.test(${h})`,()=>{let y=c.includes(g);y||e.subschema({keyword:"patternProperties",schemaProp:g,dataProp:h,dataPropType:bp.Type.Str},l),a.opts.unevaluated&&p!==!0?t.assign((0,Ji._)`${p}[${h}]`,!0):!y&&!a.allErrors&&t.if((0,Ji.not)(l),()=>t.break())})})}}};Ds.default=Qv});var _p=P(Ss=>{"use strict";Object.defineProperty(Ss,"__esModule",{value:!0});var eI=F(),tI={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,eI.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"}};Ss.default=tI});var Ep=P(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});var rI=We(),nI={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:rI.validateUnion,error:{message:"must match a schema in anyOf"}};js.default=nI});var Ap=P($s=>{"use strict";Object.defineProperty($s,"__esModule",{value:!0});var Wi=x(),iI=F(),aI={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,Wi._)`{passingSchemas: ${e.passing}}`},oI={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:aI,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 f;(0,iI.alwaysValidSchema)(i,l)?t.var(c,!0):f=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),f&&e.mergeEvaluated(f,Wi.Name)})})}}};$s.default=oI});var Rp=P(Os=>{"use strict";Object.defineProperty(Os,"__esModule",{value:!0});var sI=F(),cI={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,sI.alwaysValidSchema)(n,a))return;let s=e.subschema({keyword:"allOf",schemaProp:o},i);e.ok(i),e.mergeEvaluated(s)})}};Os.default=cI});var Dp=P(Cs=>{"use strict";Object.defineProperty(Cs,"__esModule",{value:!0});var Ki=x(),Np=F(),lI={message:({params:e})=>(0,Ki.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,Ki._)`{failingKeyword: ${e.ifClause}}`},dI={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:lI,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,Np.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=Pp(n,"then"),a=Pp(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 f=e.subschema({keyword:l},s);t.assign(o,s),e.mergeValidEvaluated(f,o),p?t.assign(p,(0,Ki._)`${l}`):e.setParams({ifClause:l})}}}};function Pp(e,t){let r=e.schema[t];return r!==void 0&&!(0,Np.alwaysValidSchema)(e,r)}Cs.default=dI});var Sp=P(Ts=>{"use strict";Object.defineProperty(Ts,"__esModule",{value:!0});var pI=F(),uI={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,pI.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Ts.default=uI});var jp=P(xs=>{"use strict";Object.defineProperty(xs,"__esModule",{value:!0});var fI=ws(),mI=cp(),gI=vs(),hI=dp(),yI=pp(),wI=zi(),vI=gp(),II=Rs(),bI=wp(),kI=kp(),_I=_p(),EI=Ep(),AI=Ap(),RI=Rp(),PI=Dp(),NI=Sp();function DI(e=!1){let t=[_I.default,EI.default,AI.default,RI.default,PI.default,NI.default,vI.default,II.default,wI.default,bI.default,kI.default];return e?t.push(mI.default,hI.default):t.push(fI.default,gI.default),t.push(yI.default),t}xs.default=DI});var Vs=P(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.dynamicAnchor=void 0;var Ls=x(),SI=Je(),$p=hn(),jI=Li(),$I={keyword:"$dynamicAnchor",schemaType:"string",code:e=>Op(e,e.schema)};function Op(e,t){let{gen:r,it:n}=e;n.schemaEnv.root.dynamicAnchors[t]=!0;let i=(0,Ls._)`${SI.default.dynamicAnchors}${(0,Ls.getProperty)(t)}`,a=n.errSchemaPath==="#"?n.validateName:OI(e);r.if((0,Ls._)`!${i}`,()=>r.assign(i,a))}Sn.dynamicAnchor=Op;function OI(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 $p.SchemaEnv({schema:r,schemaId:c,root:i,baseId:a,localRefs:o,meta:s});return $p.compileSchema.call(n,d),(0,jI.getValidate)(e,d)}Sn.default=$I});var Ms=P(jn=>{"use strict";Object.defineProperty(jn,"__esModule",{value:!0});jn.dynamicRef=void 0;var Cp=x(),CI=Je(),Tp=Li(),TI={keyword:"$dynamicRef",schemaType:"string",code:e=>xp(e,e.schema)};function xp(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,Cp._)`${CI.default.dynamicAnchors}${(0,Cp.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,Tp.callRef)(e,c),r.let(d,!0)}):()=>(0,Tp.callRef)(e,c)}}jn.dynamicRef=xp;jn.default=TI});var Lp=P(qs=>{"use strict";Object.defineProperty(qs,"__esModule",{value:!0});var xI=Vs(),LI=F(),VI={keyword:"$recursiveAnchor",schemaType:"boolean",code(e){e.schema?(0,xI.dynamicAnchor)(e,""):(0,LI.checkStrictMode)(e.it,"$recursiveAnchor: false is ignored")}};qs.default=VI});var Vp=P(Fs=>{"use strict";Object.defineProperty(Fs,"__esModule",{value:!0});var MI=Ms(),qI={keyword:"$recursiveRef",schemaType:"string",code:e=>(0,MI.dynamicRef)(e,e.schema)};Fs.default=qI});var Mp=P(Us=>{"use strict";Object.defineProperty(Us,"__esModule",{value:!0});var FI=Vs(),UI=Ms(),zI=Lp(),BI=Vp(),GI=[FI.default,UI.default,zI.default,BI.default];Us.default=GI});var Fp=P(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});var qp=zi(),JI={keyword:"dependentRequired",type:"object",schemaType:"object",error:qp.error,code:e=>(0,qp.validatePropertyDeps)(e)};zs.default=JI});var Up=P(Bs=>{"use strict";Object.defineProperty(Bs,"__esModule",{value:!0});var WI=zi(),KI={keyword:"dependentSchemas",type:"object",schemaType:"object",code:e=>(0,WI.validateSchemaDeps)(e)};Bs.default=KI});var zp=P(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});var YI=F(),HI={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:e,parentSchema:t,it:r}){t.contains===void 0&&(0,YI.checkStrictMode)(r,`"${e}" without "contains" is ignored`)}};Gs.default=HI});var Bp=P(Js=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});var ZI=Fp(),XI=Up(),QI=zp(),eb=[ZI.default,XI.default,QI.default];Js.default=eb});var Jp=P(Ws=>{"use strict";Object.defineProperty(Ws,"__esModule",{value:!0});var Tt=x(),Gp=F(),tb=Je(),rb={message:"must NOT have unevaluated properties",params:({params:e})=>(0,Tt._)`{unevaluatedProperty: ${e.unevaluatedProperty}}`},nb={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:rb,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} === ${tb.default.errors}`);function c(p){if(r===!1){e.setParams({unevaluatedProperty:p}),e.error(),o||t.break();return}if(!(0,Gp.alwaysValidSchema)(a,r)){let f=t.name("valid");e.subschema({keyword:"unevaluatedProperties",dataProp:p,dataPropType:Gp.Type.Str},f),o||t.if((0,Tt.not)(f),()=>t.break())}}function d(p,f){return(0,Tt._)`!${p} || !${p}[${f}]`}function l(p,f){let u=[];for(let m in p)p[m]===!0&&u.push((0,Tt._)`${f} !== ${m}`);return(0,Tt.and)(...u)}}};Ws.default=nb});var Kp=P(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});var rr=x(),Wp=F(),ib={message:({params:{len:e}})=>(0,rr.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,rr._)`{limit: ${e}}`},ab={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:ib,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,Wp.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:Wp.Type.Num},c),i.allErrors||t.if((0,rr.not)(c),()=>t.break())})}}};Ks.default=ab});var Yp=P(Ys=>{"use strict";Object.defineProperty(Ys,"__esModule",{value:!0});var ob=Jp(),sb=Kp(),cb=[ob.default,sb.default];Ys.default=cb});var Hp=P(Hs=>{"use strict";Object.defineProperty(Hs,"__esModule",{value:!0});var fe=x(),lb={message:({schemaCode:e})=>(0,fe.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,fe._)`{format: ${e}}`},db={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:lb,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?f():u();function f(){let m=r.scopeValue("formats",{ref:p.formats,code:c.code.formats}),g=r.const("fDef",(0,fe._)`${m}[${o}]`),h=r.let("fType"),y=r.let("format");r.if((0,fe._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(h,(0,fe._)`${g}.type || "string"`).assign(y,(0,fe._)`${g}.validate`),()=>r.assign(h,(0,fe._)`"string"`).assign(y,g)),e.fail$data((0,fe.or)(k(),b()));function k(){return c.strictSchema===!1?fe.nil:(0,fe._)`${o} && !${y}`}function b(){let E=l.$async?(0,fe._)`(${g}.async ? await ${y}(${n}) : ${y}(${n}))`:(0,fe._)`${y}(${n})`,w=(0,fe._)`(typeof ${y} == "function" ? ${E} : ${y}.test(${n}))`;return(0,fe._)`${y} && ${y} !== true && ${h} === ${t} && !${w}`}}function u(){let m=p.formats[a];if(!m){k();return}if(m===!0)return;let[g,h,y]=b(m);g===t&&e.pass(E());function k(){if(c.strictSchema===!1){p.logger.warn(w());return}throw new Error(w());function w(){return`unknown format "${a}" ignored in schema at path "${d}"`}}function b(w){let _=w instanceof RegExp?(0,fe.regexpCode)(w):c.code.formats?(0,fe._)`${c.code.formats}${(0,fe.getProperty)(a)}`:void 0,S=r.scopeValue("formats",{key:a,ref:w,code:_});return typeof w=="object"&&!(w instanceof RegExp)?[w.type||"string",w.validate,(0,fe._)`${S}.validate`]:["string",w,S]}function E(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!l.$async)throw new Error("async format in sync schema");return(0,fe._)`await ${y}(${n})`}return typeof h=="function"?(0,fe._)`${y}(${n})`:(0,fe._)`${y}.test(${n})`}}}};Hs.default=db});var Zp=P(Zs=>{"use strict";Object.defineProperty(Zs,"__esModule",{value:!0});var pb=Hp(),ub=[pb.default];Zs.default=ub});var Xp=P(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 eu=P(Xs=>{"use strict";Object.defineProperty(Xs,"__esModule",{value:!0});var fb=Bd(),mb=ip(),gb=jp(),hb=Mp(),yb=Bp(),wb=Yp(),vb=Zp(),Qp=Xp(),Ib=[hb.default,fb.default,mb.default,(0,gb.default)(!0),vb.default,Qp.metadataVocabulary,Qp.contentVocabulary,yb.default,wb.default];Xs.default=Ib});var ru=P(Yi=>{"use strict";Object.defineProperty(Yi,"__esModule",{value:!0});Yi.DiscrError=void 0;var tu;(function(e){e.Tag="tag",e.Mapping="mapping"})(tu||(Yi.DiscrError=tu={}))});var iu=P(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});var Cr=x(),Qs=ru(),nu=hn(),bb=gn(),kb=F(),_b={message:({params:{discrError:e,tagName:t}})=>e===Qs.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}}`},Eb={keyword:"discriminator",type:"object",schemaType:"object",error:_b,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:Qs.DiscrError.Tag,tag:d,tagName:s})),e.ok(c);function l(){let u=f();t.if(!1);for(let m in u)t.elseIf((0,Cr._)`${d} === ${m}`),t.assign(c,p(u[m]));t.else(),e.error(!1,{discrError:Qs.DiscrError.Mapping,tag:d,tagName:s}),t.endIf()}function p(u){let m=t.name("valid"),g=e.subschema({keyword:"oneOf",schemaProp:u},m);return e.mergeEvaluated(g,Cr.Name),m}function f(){var u;let m={},g=y(i),h=!0;for(let E=0;E<o.length;E++){let w=o[E];if(w?.$ref&&!(0,kb.schemaHasRulesButRef)(w,a.self.RULES)){let S=w.$ref;if(w=nu.resolveRef.call(a.self,a.schemaEnv.root,a.baseId,S),w instanceof nu.SchemaEnv&&(w=w.schema),w===void 0)throw new bb.default(a.opts.uriResolver,a.baseId,S)}let _=(u=w?.properties)===null||u===void 0?void 0:u[s];if(typeof _!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${s}"`);h=h&&(g||y(w)),k(_,E)}if(!h)throw new Error(`discriminator: "${s}" must be required`);return m;function y({required:E}){return Array.isArray(E)&&E.includes(s)}function k(E,w){if(E.const)b(E.const,w);else if(E.enum)for(let _ of E.enum)b(_,w);else throw new Error(`discriminator: "properties/${s}" must have "const" or "enum"`)}function b(E,w){if(typeof E!="string"||E in m)throw new Error(`discriminator: "${s}" values must be unique strings`);m[E]=w}}}};ec.default=Eb});var au=P((yP,Ab)=>{Ab.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 ou=P((wP,Rb)=>{Rb.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 su=P((vP,Pb)=>{Pb.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 cu=P((IP,Nb)=>{Nb.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 lu=P((bP,Db)=>{Db.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 du=P((kP,Sb)=>{Sb.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 pu=P((_P,jb)=>{jb.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 uu=P((EP,$b)=>{$b.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 fu=P(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});var Ob=au(),Cb=ou(),Tb=su(),xb=cu(),Lb=lu(),Vb=du(),Mb=pu(),qb=uu(),Fb=["/properties"];function Ub(e){return[Ob,Cb,Tb,xb,Lb,t(this,Vb),Mb,t(this,qb)].forEach(r=>this.addMetaSchema(r,void 0,!1)),this;function t(r,n){return e?r.$dataMetaSchema(n,Fb):n}}tc.default=Ub});var nr=P((le,nc)=>{"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 zb=Md(),Bb=eu(),Gb=iu(),Jb=fu(),rc="https://json-schema.org/draft/2020-12/schema",Tr=class extends zb.default{constructor(t={}){super({...t,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),Bb.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(Gb.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:t,meta:r}=this.opts;r&&(Jb.default.call(this,t),this.refs["http://json-schema.org/schema"]=rc)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(rc)?rc:void 0)}};le.Ajv2020=Tr;nc.exports=le=Tr;nc.exports.Ajv2020=Tr;Object.defineProperty(le,"__esModule",{value:!0});le.default=Tr;var Wb=mn();Object.defineProperty(le,"KeywordCxt",{enumerable:!0,get:function(){return Wb.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 Kb=Pi();Object.defineProperty(le,"ValidationError",{enumerable:!0,get:function(){return Kb.default}});var Yb=gn();Object.defineProperty(le,"MissingRefError",{enumerable:!0,get:function(){return Yb.default}})});import{lstat as fA,readFile as X,readdir as Ym,realpath as pt}from"node:fs/promises";import{execFile as mA,spawn as gA}from"node:child_process";import N from"node:path";import{parseArgs as oe,promisify as hA}from"node:util";var Q="^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$",ut="^sha256:[a-f0-9]{64}$";import{constants as ma}from"node:fs";import{lstat as Rk,mkdir as Wr,open as Du,readFile as Mn,realpath as dr,rename as Pk,unlink as vc}from"node:fs/promises";import{randomUUID as Ic}from"node:crypto";import ye from"node:path";var mu=br(nr(),1);var ke={type:"string",pattern:ut},Hb={type:"string",pattern:"^[a-z][a-z0-9.-]{2,127}$"},ic={type:"string",format:"date-time"},ac={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"]},gu={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}}},oc={$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:Q},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:Q}}}},compatibility:gu,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:Q},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-contract-v2","application-config-binding-v1"]}},allOf:[{if:{properties:{ownership:{const:"managed-region"}},required:["ownership"]},then:{properties:{regionId:{type:"string",pattern:Q}},required:["regionId"]},else:{not:{required:["regionId"]}}}]}},verifiers:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["id"],properties:{id:ac}}},exit:{type:"object",additionalProperties:!1,required:["ownedAssets"],properties:{ownedAssets:{type:"array",items:{type:"string",minLength:1,maxLength:512}}}}}},hu={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:PP,...yu}=oc,Zb={...yu,$id:"https://schemas.dyyto.dev/platform/capability-bundle-release-v2.json",required:[...oc.required,"availability","packageSources"],properties:{...oc.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:hu}}},Xb={$id:"https://schemas.dyyto.dev/platform/capability-bundle-release.json",oneOf:[yu,(()=>{let{$id:e,...t}=Zb;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:ac,result:{enum:["passed","failed"]},issuer:{enum:["dyyto-cli","test-harness","external-ci"]},commandId:ac,exitCode:{type:"integer",minimum:0,maximum:255},stdoutDigest:ke,stderrDigest:ke,startedAt:ic,completedAt:ic,projectStateDigest:ke,runtime:gu}},Qb={...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:Q},capabilityVersion:{type:"string",minLength:1,maxLength:128},capabilityIntegrity:ke}},ek={$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:Q},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:Q}},allOf:[{if:{properties:{ownership:{const:"managed-region"}},required:["ownership"]},then:{properties:{regionId:{type:"string",pattern:Q}},required:["regionId"]}}]}},evidenceIds:{type:"array",items:ke},committedAt:ic,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:Hb,revision:ke}}},sources:{type:"array",minItems:1,maxItems:128,items:hu},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 mu.Ajv2020({allErrors:!0,strict:!0});$n.addFormat("date-time",{type:"string",validate:e=>!Number.isNaN(Date.parse(e))});var Xi={capabilityBundleRelease:$n.compile(Xb),verificationResult:$n.compile(Hi),adoptionEvidence:$n.compile(Qb),projectAdoptionLock:$n.compile(ek)},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 wu=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},vu=e=>Qi("verificationResult",Xi.verificationResult,e),On=e=>Qi("adoptionEvidence",Xi.adoptionEvidence,e),xe=e=>Qi("projectAdoptionLock",Xi.projectAdoptionLock,e);import{lstat as lk,readFile as dc,realpath as pc}from"node:fs/promises";import Vr from"node:path";import{createHash as tk}from"node:crypto";function v(e){return`sha256:${tk("sha256").update(e).digest("hex")}`}function A(e){return Array.isArray(e)?`[${e.map(A).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)}:${A(n)}`).join(",")}}`:JSON.stringify(e)}var ht=class extends Error{code="MANAGED_REGION_INVALID";constructor(t){super(t)}};function Iu(e){if(!new RegExp(Q).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}=Iu(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 bu(e){let{begin:t,end:r}=Iu(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 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
|
|
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
|
|
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
|
|
20
|
-
`)}async function
|
|
21
|
-
`),i=r.capabilities[0],a=
|
|
22
|
-
`)}catch(i){throw i.code==="EEXIST"?new he("MANIFEST_EXISTS","Project manifest already exists"):i}return{projectRoot:r,manifest:t}}function
|
|
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
|
-
`)}function
|
|
25
|
-
`)}function
|
|
26
|
-
`)}function
|
|
27
|
-
`)}function
|
|
28
|
-
`)}function
|
|
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=>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)}
|
|
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 ku 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||ku.posix.isAbsolute(e)||ku.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 rk(e,t){ta(e.path);let r=e.kind==="merge"&&e.ownership==="managed-region"&&e.regionId!==void 0&&new RegExp(Q).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 Se(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),rk(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(A(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(A(o))}}function ra(e){return v(A(e))}var _u=br(nr(),1);var ee={type:"string",pattern:ut},Lr={type:"string",pattern:Q},or={type:"string",minLength:1,maxLength:128},ar={type:"string",minLength:1,maxLength:512,pattern:"^(?!/)(?!.*(?:^|/)\\.\\.(?:/|$))(?!.*\\\\).+$"},nk={$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:ee,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:ee}}},verifiers:{type:"array",items:{type:"object",additionalProperties:!1,required:["id","kind"],properties:{id:{type:"string",minLength:1,maxLength:128},kind:{enum:["command","file-digest"]}}}}}},ik={$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:Q},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}}}}},ak={$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:ee,appliedPlanId:ee,assets:{type:"array",items:{type:"object",additionalProperties:!1,required:["path","digest"],properties:{path:ar,digest:ee}}},evidenceIds:{type:"array",items:{type:"string",minLength:1,maxLength:256}}}}}}},ok={$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"}}},sk={$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:ee,action:{enum:["adopt","upgrade","remove"]},state:{enum:["reviewable","conflicted"]},capability:{type:"object",additionalProperties:!1,required:["capabilityId","version","integrity"],properties:{capabilityId:Lr,version:or,integrity:ee}},generatedAt:{type:"string",format:"date-time"},expiresAt:{type:"string",format:"date-time"},inputDigest:ee,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:ee,desiredPackageJsonDigest:ee,lockfilePreimage:{oneOf:[{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:{const:"absent"}}},{type:"object",additionalProperties:!1,required:["kind","digest"],properties:{kind:{const:"present"},digest:ee}}]},desiredLockfileDigest:ee,registryRevisions:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["registryId","revision"],properties:{registryId:{type:"string",minLength:1,maxLength:128},revision:ee}}},endpointBindings:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["registryId","registryConfigRevision","bindingDigest","expiresAt"],properties:{registryId:{type:"string",minLength:1,maxLength:128},registryConfigRevision:ee,bindingDigest:ee,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:ee,deliveryReceiptId:ee,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:ee}},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:ee,desiredDigest:ee}}}},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:ee,baseDigest:ee,regionId:{type:"string",pattern:Q},disposition:{enum:["ready","noop","conflict"]},conflictCode:{enum:["USER_OWNED","UNEXPECTED_EXISTING","BASE_DIGEST_MISMATCH"]}}}}}},ck={$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:ee,approvedPlanId:ee,projectRootDigest:ee,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:ee,mode:{type:"integer",minimum:0,maximum:511},preimageDigest:ee}}]},desiredDigest:ee,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:ee}},ir=new _u.Ajv2020({allErrors:!0,strict:!0});ir.addFormat("date-time",{type:"string",validate:e=>!Number.isNaN(Date.parse(e))});var cc={capabilityRelease:ir.compile(nk),projectManifest:ir.compile(ik),projectLock:ir.compile(ak),evidence:ir.compile(ok),changePlan:ir.compile(sk),transactionJournal:ir.compile(ck)},sc=class extends Error{contract;issues;code="CONTRACT_INVALID";constructor(t,r){super(`Invalid ${t} contract`),this.contract=t,this.issues=r}};function lc(e,t,r){if(!t(r))throw new sc(e,t.errors??[]);return r}var B=e=>lc("projectManifest",cc.projectManifest,e);var Lt=e=>lc("changePlan",cc.changePlan,e),Eu=e=>lc("transactionJournal",cc.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 pc(Vr.resolve(e.projectRoot)),r=[],n=0,i=0;for(let a of e.release.release.assets){let o=await uc(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 uc(e,t){let r=Vr.join(e,...t.split("/"));try{let n=await lk(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 dc(r))}}catch(n){if(n.code==="ENOENT")return{path:t,exists:!1};throw n}}async function sr(e){let t=await pc(Vr.resolve(e.projectRoot)),r=[];for(let n of e.expectedAssets){let i=await uc(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 dc(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(A(r))}}async function ia(e){let t=B(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:xe(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 pc(Vr.resolve(e.projectRoot)),o=[],s=[],c=new Map(e.release.contents);for(let l of e.release.release.assets){let p=await uc(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 f=l.ownership==="seed-file"&&p.digest?p.digest:l.digest;l.ownership==="seed-file"&&p.exists&&c.set(l.path,await dc(Vr.join(a,...l.path.split("/")))),s.push({path:l.path,kind:"create",ownership:l.ownership,desiredDigest:f})}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:Se({action:"adopt",capability:d,changes:s,observedAssets:o,generatedAt:e.generatedAt,expiresAt:e.expiresAt}),desiredContents:c}}import{chmod as pk,lstat as da,mkdir as Mr,open as Pu,readFile as pa,realpath as uk,rename as ca,rm as fc,unlink as cr}from"node:fs/promises";import{constants as oa}from"node:fs";import{homedir as fk}from"node:os";import J from"node:path";import{randomUUID as Ur}from"node:crypto";function dk(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 Au(e.context,e.operation,e.bytes??0,t,"succeeded"),r}catch(r){throw await Au(e.context,e.operation,e.bytes??0,t,"failed",dk(r)),r}}async function Au(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(A(s))});try{await e.sink(c)}catch{}}var Nu=Symbol("prepared-transaction"),Vt=new Map,mk=5*1024*1024,gk=25*1024*1024,Ru=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 Pu(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 Pu(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 mc(e,t,r){let n=J.dirname(e),i=J.join(n,`.tmp-${Ur()}`),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 gc(e){return{...e,journalDigest:v(A(e))}}function hk(e){let t;try{t=Eu(e)}catch{throw new C("JOURNAL_CORRUPTED","Transaction journal shape is invalid")}let{journalDigest:r,...n}=t;if(r!==v(A(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 hc(e){try{return hk(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=gc(i);return await mc(e,a,r),a}async function ua(e){let t=J.resolve(e),r=J.parse(t);if(t===r.root||t===J.resolve(fk()))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 uk(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 Fr(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 yk(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 wk(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 yc(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 vk(e,t,r){return{[Nu]:!0,projectRoot:e,plan:t,transactionId:r}}async function Ik(e,t){yk(e.plan,e.approvedPlanId,e.now);let r=await ua(e.projectRoot),n=wk(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 m=e.desiredContents.get(u.path);if(m===void 0||v(m)!==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=Ur();await yc(a.lock,{schemaVersion:1,transactionId:o,planId:e.plan.planId,startedAt:e.now,nonce:Ur()},ot(t?.durabilityTrace,"prepare","lock",`${o}:prepare-lock`));let s=e.limits?.maxFileBytes??mk,c=e.limits?.maxTransactionBytes??gk,d=0,l=[],p=[],f=!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}),f=!0;for(let[m,g]of n.entries()){let h=Br(r,g.path);await qr(r,g.path);let y=await Fr(h);if(g.kind==="create"){if(y!==void 0)throw new C("PLAN_PRECONDITION_FAILED","Create target now exists",g.path,m)}else if(y===void 0||y.digest!==g.baseDigest)throw new C("PLAN_PRECONDITION_FAILED","Target no longer matches plan base digest",g.path,m);let k={kind:"absent"};if(y!==void 0){if(d+=y.bytes.byteLength,y.bytes.byteLength>s||d>c)throw new C("PREIMAGE_LIMIT_EXCEEDED","Preimage size limit exceeded",g.path,m);let b=J.join(a.preimages,`${m}.bin`);await Tn(b,y.bytes,384,ot(t?.durabilityTrace,"prepare","preimage",`${o}:preimage:${m}`)),p.push(m),await aa(t,"preimage-written-pending-directory-sync",m),k={kind:"present",digest:y.digest,mode:y.mode,preimageDigest:v(y.bytes)}}l.push({index:m,path:g.path,kind:g.kind,before:k,...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 m of p)await aa(t,"preimage-persisted",m)}let u=gc({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 mc(a.journal,u,ot(t?.durabilityTrace,"prepare","journal",`${o}:journal-prepared`)),Vt.set(o,{desiredContents:e.desiredContents,journal:u}),await aa(t,"journal-prepared"),vk(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{f&&await fc(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 Ik(e)}async function bk(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 kk(e,t,r,n,i,a){let o=Br(e,n.path);await qr(e,n.path);let s=await Fr(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`),f=ot(a?.durabilityTrace,"apply","target",`${r}:target:${n.index}`);return await He({context:zr(f),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 _k(e,t){let r=Vt.get(e.transactionId);if(r===void 0||e[Nu]!==!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+=Ru){let s=i.operations.slice(o,o+Ru),c=await Promise.allSettled(s.map(l=>kk(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 bk(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 _k(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 hc(r.journal))}async function Ek(e,t,r){await Mr(J.dirname(e),{recursive:!0});let n=J.join(J.dirname(e),`.dyyto-recover-${Ur()}.tmp`);await Tn(n,t,r&511),await ca(n,e),await pk(e,r&511),await Ze(J.dirname(e))}async function Ak(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 fc(r.transactionDirectory,{recursive:!0,force:!0}),await Mr(r.transactionDirectory,{recursive:!0,mode:448});let a=gc({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 mc(r.journal,a),await cr(r.lock),await Ze(r.platformDirectory),lr(a)}let n=await hc(r.journal);if(n.state==="recovered")return lr(n);if(n.state==="applied"){for(let i of n.operations){let a=await Fr(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 yc(r.lock,{schemaVersion:1,transactionId:n.transactionId,planId:n.planId,startedAt:e.now,nonce:Ur()});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 Fr(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 Fr(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(f=>f.path===i.path&&f.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 Ek(a,p,i.before.mode),d&&await fc(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 Ak(e)}async function wc(e){let t=await ua(e.projectRoot),r=Cn(t,e.planId),n=await hc(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 Fr(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 yc(r.lock,{schemaVersion:1,transactionId:n.transactionId,planId:n.planId,startedAt:e.now,nonce:Ur()}),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 Rk(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 Du(e,ma.O_RDONLY);try{await He({context:ha(t,!0),operation:"directory-sync",run:()=>r.sync()})}finally{await r.close()}}async function bc(e,t,r){let n=await Du(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-${Ic()}`),a=Buffer.from(`${JSON.stringify(t,null,2)}
|
|
17
|
+
`);await bc(i,a,r),await He({context:ha(r),operation:"rename",bytes:a.byteLength,run:()=>Pk(i,e)}),await ya(n,r)}function kc(e){return{...e,journalDigest:v(A(e))}}async function fa(e,t,r){let{journalDigest:n,...i}=t,a=kc(i);return await Vn(e,a,r),a}async function Su(e){try{let t=JSON.parse(await Mn(e,"utf8")),{journalDigest:r,...n}=t;if(t.schemaVersion!==1||!Array.isArray(t.evidence)||r!==v(A(n)))throw new Error("invalid journal");return t.evidence.forEach(On),xe(t.lock),t}catch{throw new we("METADATA_JOURNAL_CORRUPTED","Metadata journal cannot be trusted")}}async function _c(e,t,r){try{await bc(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 ju(e,t){let r={...t,capabilityId:e.capabilityId,capabilityVersion:e.version,capabilityIntegrity:e.integrity};return{...r,evidenceId:v(A(r))}}function $u(e,t,r){let n=t.map(vu),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 Nk(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(A(i)!==A(t))throw new we("METADATA_JOURNAL_CORRUPTED","Existing evidence content does not match its identity");return}await bc(n,Buffer.from(`${JSON.stringify(t,null,2)}
|
|
19
|
+
`),r),await ya(e,r)}async function Dk(e,t,r,n){if(await qt(e)){let i=xe(JSON.parse(await Mn(e,"utf8")));if(A(i)===A(t))return;if(r===void 0||v(A(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 Ec(e,t,r){let n=qn(e,t.planId),i=t;try{for(let a of i.evidence)await Nk(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 Dk(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 vc(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 Sk(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(m=>({path:m.path,digest:m.digest}))})}catch{throw new we("PROJECT_STATE_CHANGED","Managed project assets no longer match the approved plan")}let o=$u(e.release,e.verificationResults,i.projectStateDigest).map(m=>ju(e.release,m)),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(m=>m.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(m=>({...m})),sources:e.plan.packageAdoption.sources.map(m=>({...m})),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(m=>m.capabilityId!==e.release.capabilityId),s].sort((m,g)=>m.capabilityId.localeCompare(g.capabilityId)):e.previousLock!==void 0&&e.plan.action==="upgrade"?[...c.filter(m=>m.capabilityId!==e.release.capabilityId),s].sort((m,g)=>m.capabilityId.localeCompare(g.capabilityId)):[s],l={schemaVersion:d.some(m=>m.packageAdoption!==void 0)?2:1,capabilities:d};xe(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 m=xe(JSON.parse(await Mn(p.lockFile,"utf8")));if(A(m)===A(l))return m;throw new we("PROJECT_STATE_CHANGED","An incompatible project lock already exists")}let f=Ic();if(await _c(p.transactionLock,{planId:e.plan.planId,transactionId:f,createdAt:e.committedAt},Et(e.hooks?.durabilityTrace,"lock",`${f}:metadata-lock`)),await qt(p.transactionDirectory))throw await vc(p.transactionLock),new we("METADATA_TRANSACTION_ACTIVE","This plan already has a metadata transaction");await Wr(p.transactionDirectory,{recursive:!0,mode:448});let u=kc({schemaVersion:1,planId:e.plan.planId,transactionId:f,state:"prepared",createdAt:e.committedAt,updatedAt:e.committedAt,evidence:o,lock:l,...e.previousLock===void 0?{}:{previousLockDigest:v(A(xe(e.previousLock)))}});await Vn(p.journal,u,Et(e.hooks?.durabilityTrace,"journal",`${f}:prepared`));try{await ga(e.hooks,"journal-prepared")}catch(m){throw m instanceof Ln?new we("METADATA_RECOVERY_REQUIRED","Metadata commit was interrupted"):m}return Ec(t,u,e.hooks)}async function Ac(e){return Sk(e)}async function Rc(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=$u(e.release,e.verificationResults,d.projectStateDigest).map(h=>ju(e.release,h)),f={schemaVersion:a.some(h=>h.packageAdoption!==void 0)?2:1,capabilities:a};xe(f);let u=qn(t,e.plan.planId);await Wr(u.platformDirectory,{recursive:!0,mode:448}),await Wr(u.evidenceDirectory,{recursive:!0,mode:448});let m=Ic();await _c(u.transactionLock,{planId:e.plan.planId,transactionId:m,createdAt:e.committedAt}),await Wr(u.transactionDirectory,{recursive:!1,mode:448});let g=kc({schemaVersion:1,planId:e.plan.planId,transactionId:m,state:"prepared",createdAt:e.committedAt,updatedAt:e.committedAt,evidence:p,lock:f,previousLockDigest:v(A(xe(e.previousLock)))});return await Vn(u.journal,g),Ec(t,g)}async function Pc(e){let t=await dr(ye.resolve(e.projectRoot)),r=qn(t,e.planId),n=await Su(r.journal);return n.state==="committed"?(await qt(r.transactionLock)&&await vc(r.transactionLock),n.lock):(await qt(r.transactionLock)||await _c(r.transactionLock,{planId:n.planId,transactionId:n.transactionId,createdAt:n.createdAt}),Ec(t,n))}async function Nc(e){let t=await dr(ye.resolve(e.projectRoot)),r=qn(t,e.planId);if(!await qt(r.journal))return null;let n=await Su(r.journal);return{planId:n.planId,state:n.state}}async function je(e){let t=await dr(ye.resolve(e)),r=ye.join(t,".dyyto","project-lock.json");return await qt(r)?xe(JSON.parse(await Mn(r,"utf8"))):null}import{lstat as Tu,readFile as Ou,realpath as Cu}from"node:fs/promises";import Ft from"node:path";var st=class extends Error{code;assetPath;constructor(t,r,n){super(r),this.code=t,this.assetPath=n}};function xu(e){return v(A(e))}async function jk(e,t){let r=Ft.join(e,"assets",...t.split("/"));try{return await Tu(r),r}catch(n){if(n.code!=="ENOENT"||Ft.posix.basename(t)!==".gitignore")throw n}return Ft.join(e,"assets",...Ft.posix.dirname(t).split("/").filter(n=>n!=="."),"__dyyto_dotfiles__","gitignore")}async function ge(e){let t=await Cu(Ft.resolve(e)),r;try{r=wu(JSON.parse(await Ou(Ft.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(xu(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 jk(t,c.path),l=await Cu(d),p=Ft.join(t,"assets");if(!l.startsWith(`${p}${Ft.sep}`))throw new st("RELEASE_ASSET_INVALID","Release asset escapes its bundle",c.path);let f=await Tu(d);if(!f.isFile()||f.isSymbolicLink())throw new st("RELEASE_ASSET_INVALID","Release asset must be a regular file",c.path);let u=await Ou(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 $k,open as Vu,lstat as yt,mkdir as Mu,readFile as Dc,readdir as wa,realpath as wt,rm as Ok,unlink as Ck}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"}},Tk={schemaVersion:1,profile:{id:"workspace-root",parameters:{}},capabilities:[{capabilityId:"foundation.workspace-root",version:"1.2.0"}]};function xk(){return new TextEncoder().encode(`${JSON.stringify(Tk,null,2)}
|
|
20
|
+
`)}async function Lk(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 Vk(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 qu(e){let t=await Vk(e.projectRoot,e.requiredMarkers??["package.json"]),r=B(e.manifest),n=new TextEncoder().encode(`${JSON.stringify(r,null,2)}
|
|
21
|
+
`),i=r.capabilities[0],a=Se({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 Fu(e){let t=await Lk(e.projectRoot,e.documentationOnly===!0),r=xk(),n=Se({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 Mk(e){let t=await Vu(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 Vu(r,"wx",384);try{await n.writeFile(t,"utf8"),await n.sync()}finally{await n.close()}try{await $k(r,e),await Ck(r),await Mk(ie.dirname(e))}catch(i){throw await Ok(r,{force:!0}),i}}async function qk(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 Mu(t)}return wt(t)}async function va(e){let t=B(e.manifest),r=await qk(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 Fn(e){let{planId:t,...r}=e;if(ra(r)!==e.planId)throw new he("PLAN_INTEGRITY_INVALID","Saved plan integrity is invalid")}async function Fk(e){let t=await wt(ie.resolve(e.projectRoot)),r=Lt(e.plan);Fn(r);let n=ie.join(t,".dyyto","plans");await Mu(n,{recursive:!0,mode:448});let i=ie.join(n,`${r.planId}.json`);try{await Uu(i,`${A(r)}
|
|
23
|
+
`)}catch(a){if(a.code!=="EEXIST")throw a;let o=Lt(JSON.parse(await Dc(i,"utf8")));if(Fn(o),A(o)!==A(r))throw new he("PLAN_INTEGRITY_INVALID","Plan ID content mismatch")}return i}function Lu(e){return A({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);Fn(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 Dc(ie.join(i,s),"utf8")));Fn(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)&&Lu(c)===Lu(n)&&o.push(c)}return o.sort((s,c)=>s.generatedAt.localeCompare(c.generatedAt)),o[0]!==void 0?o[0]:(await Fk({projectRoot:t,plan:n}),n)}async function Un(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 Dc(r,"utf8")));if(Fn(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),f=await Un({projectRoot:i,planId:p}),u=await _t({projectRoot:a,planId:p}),m=await yt(ie.join(i,".dyyto","metadata-transactions",p)).then(()=>!0).catch(g=>g.code==="ENOENT"?!1:Promise.reject(g));u?.state==="applied"&&!m&&!t.includes(f.planId)&&(!n.includes(f.capability.capabilityId)||f.action==="upgrade"||f.action==="remove"||f.action==="adopt"&&f.operations.every(g=>g.disposition==="noop"))&&c.push(f)}let d=Uk(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 Uk(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 Sc(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 Un({projectRoot:t,planId:a.slice(0,-5)}));return i}import{lstat as zu,readFile as zk,readdir as Bk,realpath as Gk}from"node:fs/promises";import _e from"node:path";import{homedir as Bu}from"node:os";var Xe=class extends Error{code;constructor(t){super(t),this.code=t,this.name="WorkspaceTopologyError"}};async function Gu(e){let t=_e.resolve(e),r=await zu(t).catch(()=>null);if(!r?.isDirectory()||r.isSymbolicLink()||t===_e.parse(t).root||t===_e.resolve(Bu()))throw new Xe("WORKSPACE_PATH_UNSAFE");let n=await Gk(t);if(n!==t)throw new Xe("WORKSPACE_PATH_UNSAFE");return n}async function ur(e){let t=await zu(e).catch(()=>null);if(t!==null){if(!t.isFile()||t.isSymbolicLink())throw new Xe("WORKSPACE_PATH_UNSAFE");return zk(e)}}function Ju(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 Jk(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 Wu(e){let t=await Gu(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 Ju(r.toString("utf8"))){let a=[];if(i.endsWith("/*")&&!i.slice(0,-2).includes("*")){let o=i.slice(0,-2),s=await Bk(_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 Gu(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(Bu());){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("../")||Ju(n.manifest.toString("utf8")).filter(a=>Jk(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 Ku=new Set(["preparing","prepared","applying","recovery-required","recovering"]);async function jc(e){let t=await Sc(e);for(let r of t){let n=await _t({projectRoot:e,planId:r.planId});if(n!==null&&Ku.has(n.state))return{required:!0,kind:"filesystem",planId:r.planId,state:n.state}}for(let r of t){let n=await Nc({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 Wk(e){let t=await jc(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 Pc({projectRoot:e.projectRoot,planId:t.planId}),{kind:"metadata",planId:t.planId,state:"committed"}}async function Yu(e){let t=await Wk(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 Sc(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||!Ku.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 Kk,readFile as $c,realpath as Hu}from"node:fs/promises";import zn from"node:path";var Yk=new Set(["MIT","Apache-2.0","UNLICENSED"]),Hk=new Set(["public","restricted","private"]),Zk=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/,Xk=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;function Qk(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 Ut(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(f=>f.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((f,u)=>f!==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||!Zk.test(s))throw new M("CONSUMER_PROFILE_UNSUPPORTED","npm package name must be a valid lowercase name");if(c===void 0||!Xk.test(c))throw new M("CONSUMER_PROFILE_UNSUPPORTED","npm package version must be a stable SemVer");if(d===void 0||!Yk.has(d))throw new M("CONSUMER_PROFILE_UNSUPPORTED","license must be MIT, Apache-2.0, or UNLICENSED");if(l===void 0||!Hk.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:Qk(p)}:{}}}function Oc(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
|
+
`)}function Cc(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
|
+
`)}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:{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
|
+
`)}function t_(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
|
+
`)}function r_(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
|
+
`)}function n_(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 Zu(e,t){let r=zn.join(e,...t.split("/"));try{let n=await Kk(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 $c(r))}}catch(n){if(n.code==="ENOENT")return{path:t,exists:!1};throw n}}async function mr(e,t){let r=B(e.manifest),n=t==="workspace-node-application"||t==="workspace-web-application"||t==="workspace-expo-application"||t==="nextjs-full-stack-application"?t==="workspace-web-application"?t_(fr(r).name):t==="workspace-expo-application"?n_(fr(r).name):t==="nextjs-full-stack-application"?r_(fr(r).name):e_(fr(r).name):t==="react-component-library"?Cc(Ut(r,t)):Oc(Ut(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:xe(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 Hu(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 Zu(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 $c(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"}))},f=Se({action:"adopt",capability:p,changes:l,observedAssets:d,generatedAt:e.generatedAt,expiresAt:e.expiresAt});return{manifest:r,release:e.release,plan:f,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 Tc(e){let t=B(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=B({...t,capabilities:[{capabilityId:e.release.release.capabilityId,version:e.release.release.version}]}),n=await Yr({...e,manifest:r}),i=await Hu(zn.resolve(e.projectRoot)),a="project-capabilities.json",o=await $c(zn.join(i,a)),s=Buffer.from(`${JSON.stringify(r,null,2)}
|
|
30
|
+
`),c=n.plan.operations.map(({disposition:u,conflictCode:m,...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=>Zu(i,u.path))),l=Se({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]]),f=new Map;for(let u of l.operations)u.disposition==="ready"&&u.kind!=="remove"&&f.set(u.path,p.get(u.path));return{...n,manifest:r,plan:l,desiredContents:f}}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 Xu(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 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 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 tf(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 rf(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 nf(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 af(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 S_,readFile as Ma,realpath as j_}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}$/,i_=/^sha512-[A-Za-z0-9+/]{86}==$/,a_=/^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/,sf=/^registry\.[a-z0-9][a-z0-9.-]{1,126}$/,o_=/^@[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*$/,of=/^[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 s_(e){if(!hr(e,["registryId","tenantId","origin","scopes","authentication","capabilities","status"])||!sf.test(e.registryId)||!of.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&&!of.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 c_(e){if(!s_(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(A(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(c_(i).revision!==n)throw new ct("REGISTRY_CONFIG_INVALID","Registry configuration has been modified");return t}function l_(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 d_(e,t){let r=ba(t);if(!hr(e,["registryId","registryConfigRevision","origin","resolvedAt","expiresAt"])||e.registryId!==r.registryId||e.registryConfigRevision!==r.revision||!l_(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(A(n))})}function cf(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(d_(a,t).bindingDigest!==i)throw new ct("REGISTRY_ENDPOINT_BINDING_INVALID","Registry endpoint binding has been modified");return r}function p_(e){let t=["registryId","registryConfigRevision","packageName","version","integrity","tarballDigest","access","provenance","sourceDeliveryReceiptId","verifiedAt",...e.verificationIdentityDigest===void 0?[]:["verificationIdentityDigest"]];return hr(e,t)&&sf.test(e.registryId)&&gr.test(e.registryConfigRevision)&&o_.test(e.packageName)&&a_.test(e.version)&&i_.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 lf(e){if(!p_(e))throw new ct("PACKAGE_RECEIPT_INVALID","Package delivery receipt is invalid");let t={schemaVersion:1,...e};return Object.freeze({...t,receiptId:v(A(t))})}function df(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(lf(i).receiptId!==n)throw new ct("PACKAGE_RECEIPT_INVALID","Package delivery receipt has been modified");return t}var $e=class extends Error{code;constructor(t){super(t),this.code=t,this.name="ResolutionEvidenceError"}};function Lc(e){return v(A(e))}var xc=/^sha256:[a-f0-9]{64}$/u,u_=/^sha512-[A-Za-z0-9+/]{86}==$/u,f_=/^(?: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,m_=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u,g_=/^(?:@[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 h_(e){return v(A(e))}function y_(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 $e("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=>xc.test(i)))throw new $e("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 $e("RESOLUTION_EVIDENCE_INVALID");if(!_a(e.cacheObservation,["namespace","preimageRevision","desiredRevision","writesDigest"])||e.importerFacts.length===0||e.packageFacts.length===0)throw new $e("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=>xc.test(a))))throw new $e("RESOLUTION_EVIDENCE_INVALID");if(e.packageFacts.some(i=>!_a(i,["identity","packageName","version","integrity","registryId","managed","edgesDigest"])||!g_.test(i.identity)||!m_.test(i.packageName)||!ka.test(i.registryId)||!f_.test(i.version)||!u_.test(i.integrity)||typeof i.managed!="boolean"||!xc.test(i.edgesDigest)))throw new $e("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 $e("RESOLUTION_EVIDENCE_INVALID");let{jobId:t,desiredLockfile:r,...n}=e;if(h_(n)!==e.jobId)throw new $e("RESOLUTION_EVIDENCE_INVALID")}function Vc(e,t){if(y_(e),Date.parse(t.now)>Date.parse(e.expiresAt))throw new $e("RESOLUTION_EVIDENCE_EXPIRED");if(e.requestDigest!==t.requestDigest||e.pnpmVersion!==t.pnpmVersion||e.workerReleaseId!==t.workerReleaseId)throw new $e("RESOLUTION_EVIDENCE_INVALID");let r=e.importerFacts.find(n=>n.importerId===t.targetImporterId);if(!r||r.manifestDigest!==t.targetManifestDigest)throw new $e("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 $e("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 $e("RESOLUTION_EVIDENCE_SOURCE_MISMATCH")}if(e.packageFacts.filter(n=>n.managed).length!==t.managedSources.length)throw new $e("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,pf=/^(?:workspace:|file:|link:|git(?:\+|:)|https?:|npm:)|[~^*<>=|]/u;function Mc(e){return Array.isArray(e)?`[${e.map(Mc).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)}:${Mc(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)||pf.test(n)))throw new Z("PACKAGE_SOURCE_POLICY_VIOLATION")}var w_=["dependencies","devDependencies","optionalDependencies"];function Pa(e,t){let r=[];for(let n of w_)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 qc(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
|
-
`)}function
|
|
32
|
+
`)}function Fc(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(
|
|
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
|
|
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
|
-
`);
|
|
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
|
|
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(
|
|
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.42",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
|
|
34
|
+
`)}function uf(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(f=>f.packageName)??[])),n=t.packageAdoption.sources.filter(p=>!r.has(p.packageName)),i=Fc({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(f=>f.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:Se({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:f,bindingDigest:u,expiresAt:m})=>({registryId:p,registryConfigRevision:f,bindingDigest:u,expiresAt:m})),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 ff(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:y,integrity:k})=>({registryId:g,packageName:h,version:y,integrity:k})),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=Vc(e.resolutionEvidence,{requestDigest:Lc({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}`,f=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:Se({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:f.map(({registryId:g,registryConfigRevision:h,bindingDigest:y,expiresAt:k})=>({registryId:g,registryConfigRevision:h,bindingDigest:y,expiresAt:k})),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(w=>w.packageName))):void 0;c||Aa(a),c||Aa(s);let l=new Map(e.registryConfigs.map(w=>{let _=ba(w);return[_.registryId,_]})),p=new Map(e.endpointBindings.map(w=>{let _=l.get(w.registryId);if(_===void 0)throw new Z("PACKAGE_SOURCE_NOT_FOUND");let S=cf(w,_);return[S.registryId,S]})),f=new Map(e.receipts.map(w=>{let _=df(w);return[_.receiptId,_]})),u=new Map(e.inspections.map(w=>[`${w.registryId}:${w.packageName}@${w.version}`,w])),m=new Map(e.release.packageSources.map(w=>[w.packageName,w])),g=c?Vc(e.resolutionEvidence,{requestDigest:Lc({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:w,packageName:_,version:S,integrity:O})=>({registryId:w,packageName:_,version:S,integrity:O})),preservedImporterDigests:e.preservedImporterDigests.map(({importerId:w,preimageDigest:_})=>({importerId:w,preimageDigest:_}))}),pnpmVersion:"11.21.0",workerReleaseId:e.resolutionWorkerReleaseId,targetImporterId:e.topology.unitImporterId,targetManifestDigest:v(Hn({release:e.release,packageJson:o})),preservedImporterDigests:e.preservedImporterDigests.map(({importerId:w,preimageDigest:_})=>({importerId:w,preimageDigest:_})),managedSources:e.release.packageSources.map(({registryId:w,packageName:_,version:S,integrity:O})=>({registryId:w,packageName:_,version:S,integrity:O})),now:e.generatedAt}):void 0,h=c?{lockfile:g.desiredLockfile,packages:g.packageFacts.filter(w=>w.managed).map(({registryId:w,packageName:_,version:S,integrity:O})=>({registryId:w,packageName:_,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 y=new Map(h.packages.map(w=>[w.packageName,w]));for(let w of e.release.packageSources){let _=l.get(w.registryId),S=p.get(w.registryId),O=f.get(w.deliveryReceiptId),se=u.get(`${w.registryId}:${w.packageName}@${w.version}`),$=y.get(w.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(!_||!S||Date.parse(S.expiresAt)<=Date.parse(e.expiresAt)||_.status!=="enabled"||!_.scopes.some(R=>w.packageName.startsWith(`${R}/`))||!O||!se||!$)throw new Z("PACKAGE_SOURCE_NOT_FOUND");if(O.registryId!==w.registryId||O.registryConfigRevision!==_.revision||O.packageName!==w.packageName||O.version!==w.version||O.integrity!==w.integrity||O.tarballDigest!==w.tarballDigest||se.integrity!==w.integrity||se.tarballDigest!==w.tarballDigest||se.deliveryReceiptId!==w.deliveryReceiptId||$.registryId!==w.registryId||$.version!==w.version||$.integrity!==w.integrity)throw new Z("PACKAGE_SOURCE_INTEGRITY_MISMATCH");if(!Ea.test(w.version)||se.lifecycleScripts.length>0)throw new Z("PACKAGE_SOURCE_POLICY_VIOLATION");for(let[R,Y]of Object.entries(se.dependencies)){let ne=m.get(R);if(R.startsWith("@aipt/")&&(!ne||ne.version!==Y||!Ea.test(Y)))throw new Z("PACKAGE_SOURCE_POLICY_VIOLATION",{cause:new Error(`undeclared internal dependency ${w.packageName}->${R}@${Y}`)});if(pf.test(Y))throw new Z("PACKAGE_SOURCE_POLICY_VIOLATION")}}let k=c?Hn({release:e.release,packageJson:o}):qc({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(k),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(w=>e.release.packageSources.some(_=>_.registryId===w.registryId)).map(({registryId:w,revision:_})=>Object.freeze({registryId:w,revision:_})).sort((w,_)=>w.registryId.localeCompare(_.registryId))),endpointBindings:Object.freeze([...p.values()].filter(w=>e.release.packageSources.some(_=>_.registryId===w.registryId)).map(({registryId:w,registryConfigRevision:_,bindingDigest:S,expiresAt:O})=>Object.freeze({registryId:w,registryConfigRevision:_,bindingDigest:S,expiresAt:O})).sort((w,_)=>w.registryId.localeCompare(_.registryId))),sources:Object.freeze(e.release.packageSources.map(w=>Object.freeze({...w}))),installPolicy:Object.freeze({ignoreScripts:!0,allowWorkspaceProtocol:!1,allowPublicRegistryFallback:!1}),...c?{topology:Object.freeze({...e.topology}),preservedDependencies:Object.freeze(d.map(w=>Object.freeze({...w}))),preservedImporterDigests:Object.freeze(e.preservedImporterDigests.map(w=>Object.freeze({...w})))}:{}},E=v(Mc(b));return Object.freeze({...b,planId:E,desiredPackageJson:k,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 v_(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 mf(e){v_(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 wc({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 wf=br(nr(),1);var vf=["workspace-node-application","workspace-web-application","nextjs-full-stack-application"],If="^[a-z0-9][a-z0-9._-]{0,127}$",Zn="^[A-Z][A-Z0-9_]{0,127}$",gf="^(?!/)(?!.*(?:^|/)\\.\\.(?:/|$))(?!.*(?:^|/)\\.(?:/|$))(?!.*\\\\)(?!.*[\\u0000-\\u001f]).+$",I_={$id:"https://schemas.dyyto.dev/platform/application-config-contract-v1.json",type:"object",additionalProperties:!1,required:["$schema","schemaVersion","kind","application","configDirectory","bindings"],properties:{$schema:{enum:["https://schemas.dyyto.dev/platform/application-config-contract-v1.json","https://schemas.dyyto.dev/platform/application-config-contract-v2.json"]},schemaVersion:{enum:[1,2]},kind:{const:"ApplicationConfigContract"},application:{type:"object",additionalProperties:!1,required:["id","profile"],properties:{id:{type:"string",pattern:If},profile:{enum:vf}}},configDirectory:{type:"object",additionalProperties:!1,required:["rootEnvironmentVariable","relativeDirectory","environmentFile","materializationOwner"],properties:{rootEnvironmentVariable:{enum:["IDP_CONFIG_DIR","APP_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:gf},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:gf}}}]}}}},hf=new wf.Ajv2020({allErrors:!0,strict:!0}).compile(I_),yf=/(?:^|_)(?:PASSWORD|PASSWD|TOKEN|SECRET|PRIVATE_KEY|ACCESS_KEY|API_KEY|DATABASE_URL|CONNECTION_STRING|DSN|AUTHORIZATION|CREDENTIALS?)(?:_|$)/u,b_=/(?:^|_)(?:PRIVATE_KEY|PRIVATE|KEYPAIR|KEYSTORE|PKCS12|P12|PFX|KEY)(?:_|$)/u,Ee=class extends Error{code;issues;constructor(t,r,n=[]){super(r),this.code=t,this.issues=n}};function bf(e){let t=B(e),r=t.profile?.id;if(!vf.includes(r))throw new Ee("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(If,"u").test(i))throw new Ee("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(!hf(e))throw new Ee("APPLICATION_CONFIG_CONTRACT_INVALID","Application ConfigContract \u4E0D\u7B26\u5408 v1 Schema\u3002",hf.errors??[]);let r=e,n=`https://schemas.dyyto.dev/platform/application-config-contract-v${r.schemaVersion}.json`,i=r.schemaVersion===2?"APP_CONFIG_DIR":"IDP_CONFIG_DIR";if(r.$schema!==n||r.configDirectory.rootEnvironmentVariable!==i)throw new Ee("APPLICATION_CONFIG_CONTRACT_INVALID","Application ConfigContract \u7684Schema\u7248\u672C\u4E0E\u914D\u7F6E\u6839\u4E0D\u4E00\u81F4\u3002");if(r.configDirectory.relativeDirectory!==`applications/${r.application.id}`)throw new Ee("APPLICATION_CONFIG_CONTRACT_INVALID","Config Dir \u76F8\u5BF9\u76EE\u5F55\u5FC5\u987B\u7531 Application identity \u552F\u4E00\u786E\u5B9A\u3002");let a=new Set,o=new Set,s=new Set;for(let f of r.bindings){if(a.has(f.name))throw new Ee("APPLICATION_CONFIG_CONTRACT_INVALID",`\u73AF\u5883 Binding \u540D\u79F0\u91CD\u590D\uFF1A${f.name}`);if(a.add(f.name),f.kind==="value"){if(yf.test(f.name))throw new Ee("APPLICATION_CONFIG_SECRET_LITERAL_FORBIDDEN",`\u654F\u611F\u914D\u7F6E ${f.name} \u5FC5\u987B\u4F7F\u7528\u6587\u4EF6 Binding\uFF0C\u7981\u6B62\u5728\u4ED3\u5E93\u4E2D\u58F0\u660E\u503C\u3002`);continue}if(!f.name.endsWith("_FILE"))throw new Ee("APPLICATION_CONFIG_CONTRACT_INVALID",`\u6587\u4EF6 Binding ${f.name} \u5FC5\u987B\u4EE5 _FILE \u7ED3\u5C3E\u3002`);let u=f.runtimeEnvironmentVariable??f.name;if(o.has(u))throw new Ee("APPLICATION_CONFIG_CONTRACT_INVALID",`\u8FD0\u884C\u65F6\u73AF\u5883\u53D8\u91CF\u540D\u79F0\u91CD\u590D\uFF1A${u}`);o.add(u);let m=f.kind==="secret-file"?"secrets/":"certs/";if(f.kind==="certificate-file"&&(yf.test(f.name)||b_.test(f.name)))throw new Ee("APPLICATION_CONFIG_CONTRACT_INVALID",`${f.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 g=f.file.split("/");if(!f.file.startsWith(m)||g.some(h=>h===""||h==="."||h===".."))throw new Ee("APPLICATION_CONFIG_CONTRACT_INVALID",`${f.name} \u5FC5\u987B\u4F4D\u4E8E ${m} \u4E0B\u7684\u5177\u4F53\u6587\u4EF6\u3002`);if(s.has(f.file))throw new Ee("APPLICATION_CONFIG_CONTRACT_INVALID",`\u914D\u7F6E\u6587\u4EF6 Binding \u8DEF\u5F84\u91CD\u590D\uFF1A${f.file}`);s.add(f.file)}let c=new Map(r.bindings.map(f=>[f.name,f])),d=new Set,l=new Set,p=f=>{if(l.has(f))return;if(d.has(f))throw new Ee("APPLICATION_CONFIG_CONTRACT_INVALID",`\u6D3E\u751F\u914D\u7F6E\u5B58\u5728\u5FAA\u73AF\u5F15\u7528\uFF1A${f}`);d.add(f);let u=c.get(f);if(u?.kind==="secret-file"&&u.provisioning?.strategy==="derived")for(let m of u.provisioning.template.matchAll(/\$\{([A-Z][A-Z0-9_]{0,127})\}/gu)){let g=m[1],h=c.get(g);if(!h||h.kind==="certificate-file")throw new Ee("APPLICATION_CONFIG_CONTRACT_INVALID",`${f}\u5F15\u7528\u672A\u77E5\u6216\u4E0D\u5141\u8BB8\u7684\u914D\u7F6E\uFF1A${g}`);p(g)}d.delete(f),l.add(f)};for(let f of c.keys())p(f);if(t!==void 0){let f=bf(t);if(r.application.id!==f.id||r.application.profile!==f.profile)throw new Ee("APPLICATION_CONFIG_IDENTITY_MISMATCH","ConfigContract \u7684\u5E94\u7528\u8EAB\u4EFD\u6216 Profile \u4E0E Project Manifest \u4E0D\u4E00\u81F4\u3002")}return r}function kf(e,t){let r=bf(e),n=r.profile==="workspace-web-application"?[]:[{name:"PORT",kind:"value",required:!1,default:"3000"}],i={$schema:t===2?"https://schemas.dyyto.dev/platform/application-config-contract-v2.json":"https://schemas.dyyto.dev/platform/application-config-contract-v1.json",schemaVersion:t,kind:"ApplicationConfigContract",application:r,configDirectory:{rootEnvironmentVariable:t===2?"APP_CONFIG_DIR":"IDP_CONFIG_DIR",relativeDirectory:`applications/${r.id}`,environmentFile:".env",materializationOwner:"external-deployment-control-plane"},bindings:n};return Oa(i,e),Buffer.from(`${JSON.stringify(i,null,2)}
|
|
37
|
+
`)}function Ca(e){return kf(e,2)}function Ta(e){return kf(e,1)}import{createHash as k_,X509Certificate as __}from"node:crypto";import{lstat as Xn,readFile as et,realpath as xa}from"node:fs/promises";import H from"node:path";var de=class extends Error{code;constructor(t,r){super(r),this.code=t}};function Ef(e){let t=B(e),r=t.profile?.parameters?.name;if(typeof r!="string"||!/^[a-z0-9][a-z0-9._-]{0,127}$/u.test(r))throw new de("APPLICATION_CONFIG_BINDING_IDENTITY_INVALID","\u9879\u76EE\u7F3A\u5C11\u5408\u6CD5Application identity\u3002");return{id:r,profile:t.profile.id}}function Va(e){let t=Ef(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 Af(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 de("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 de("APPLICATION_CONFIG_BINDING_INVALID","ApplicationConfigBinding\u5E94\u7528\u8EAB\u4EFD\u65E0\u6548\u3002");if(t!==void 0){let n=Ef(t);if(r.application.id!==n.id||r.application.profile!==n.profile)throw new de("APPLICATION_CONFIG_BINDING_IDENTITY_MISMATCH","ApplicationConfigBinding\u4E0EProject Manifest\u8EAB\u4EFD\u4E0D\u4E00\u81F4\u3002")}return r}function E_(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 de("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 La(e){return`sha256:${k_("sha256").update(e).digest("hex")}`}async function _f(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 de("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 A_(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 R_=new Set(["APPLICATION_CONFIG_FILE_INVALID","APPLICATION_CONFIG_REFERENCE_CHANGED"]),P_=new Set(["APP_CONFIG_DIR_REQUIRED","ENOENT"]);async function zc({projectRoot:e,environment:t=process.env}){let r=await xa(H.resolve(e)),n=H.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(H.join(r,"project-capabilities.json")),et(n)]),s=JSON.parse(a.toString("utf8")),c=Oa(JSON.parse(o.toString("utf8")),s),d=await et(H.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:La(o),state:"invalid",needsConfigInit:!1,missingBindings:[],issueCode:"APPLICATION_CONFIG_BINDING_NOT_DECLARED",entries:[]};let l=Af(JSON.parse(d.toString("utf8")),s);try{let p=await Qn({projectRoot:r,environment:t}),f=p.entries.filter(m=>m.required&&!m.configured).map(m=>m.name),u=f.length?"incomplete":"ready";return{schemaVersion:1,...p,state:u,needsConfigInit:u==="incomplete",missingBindings:f}}catch(p){let f=p instanceof de?p.code:p.code??"APPLICATION_CONFIG_UNKNOWN",u=P_.has(f)?"missing":R_.has(f)?"incomplete":"invalid",m=await Rf(r,l.application.id,t).catch(()=>{});return{schemaVersion:1,application:l.application.id,environment:"local",configDirectory:m??null,contractDigest:La(o),state:u,needsConfigInit:u==="missing"||u==="incomplete",missingBindings:u==="missing"?c.bindings.filter(g=>g.required).map(g=>g.name):[],issueCode:f,entries:[]}}}catch(a){let o=a instanceof de||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 N_=new Set(["workspace-node-application","workspace-web-application","workspace-expo-application","nextjs-full-stack-application"]);async function Bc({workspaceRoot:e,environment:t=process.env}){let r=await xa(H.resolve(e));if(B(JSON.parse(await et(H.join(r,"project-capabilities.json"),"utf8"))).profile?.id!=="workspace-root")throw new de("APPLICATION_CONFIG_WORKSPACE_INVALID","\u914D\u7F6E\u5C31\u7EEA\u5EA6\u5DE5\u4F5C\u533A\u5FC5\u987B\u91C7\u7528workspace-root Profile\u3002");let i=await Wu(r),a=[];for(let s of i){let c=H.join(r,...s.relativeRoot.split("/")),d=H.join(c,"project-capabilities.json"),l=await et(d,"utf8").catch(()=>null),p=await Xn(H.join(c,"config/application-config.json")).then(m=>m.isFile()&&!m.isSymbolicLink()).catch(()=>!1),f="";if(l!==null)try{f=B(JSON.parse(l)).profile?.id??""}catch{p&&(f="invalid-application")}if(!N_.has(f)&&!p)continue;let u=await zc({projectRoot:c,environment:t}).catch(m=>({schemaVersion:1,application:null,environment:"local",configDirectory:null,contractDigest:null,state:"invalid",needsConfigInit:!1,missingBindings:[],issueCode:m instanceof Error&&"code"in m?String(m.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_(a)})}async function D_(e,t,r){let n=H.dirname(e);for(;n!==H.dirname(n);){try{let i=JSON.parse(await et(H.join(n,"project-capabilities.json"),"utf8"));if(i.profile?.id==="workspace-root"){let a=i.profile.parameters?.name;if(typeof a!="string"||!/^[a-z0-9][a-z0-9._-]{0,127}$/u.test(a))throw new de("APPLICATION_CONFIG_WORKSPACE_IDENTITY_REQUIRED","Workspace Manifest\u5FC5\u987B\u58F0\u660E\u7A33\u5B9Aprofile.parameters.name\uFF0C\u7981\u6B62\u6309\u76EE\u5F55\u540D\u63A8\u65AD\u3002");let o=H.relative(n,e);if(!/^(?:apps|services|packages)[/\\][a-z0-9][a-z0-9._-]*$/u.test(o))throw new de("APPLICATION_CONFIG_WORKSPACE_UNIT_INVALID","Workspace\u5E94\u7528\u5FC5\u987B\u4F4D\u4E8Eapps/<name>\u3001services/<name>\u6216packages/<name>\u3002");return H.join(a,o,r)}}catch(i){if(i instanceof de)throw i}n=H.dirname(n)}return H.join(t,r)}async function Rf(e,t,r){let n=r.DYYTO_WORKBENCH_PROJECT_BINDINGS_FILE;if(n){if(!H.isAbsolute(n))throw new de("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 de("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 de("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}${H.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(!H.isAbsolute(i))throw new de("APP_CONFIG_DIR_REQUIRED","APP_CONFIG_DIR\u5FC5\u987B\u662F\u7EDD\u5BF9\u4E1A\u52A1\u914D\u7F6E\u603B\u6839\u3002");return H.join(i,await D_(e,t,r.DYYTO_APPLICATION_ENVIRONMENT??"local"))}}async function Qn({projectRoot:e,environment:t=process.env}){let r=await xa(H.resolve(e)),[n,i,a]=await Promise.all([et(H.join(r,"project-capabilities.json")),et(H.join(r,".dyyto/application-config-binding.json")),et(H.join(r,"config/application-config.json"))]),o=JSON.parse(n.toString("utf8")),s=Af(JSON.parse(i.toString("utf8")),o),c=Oa(JSON.parse(a.toString("utf8")),o),d=await Rf(r,s.application.id,t);if(!d||!H.isAbsolute(d))throw new de("APP_CONFIG_DIR_REQUIRED","\u8BF7\u4E3A\u5F53\u524D\u9879\u76EE\u8BBE\u7F6E\u7EDD\u5BF9APP_CONFIG_DIR\u3002");let l=await xa(d),p=await Xn(l);if(!p.isDirectory()||p.isSymbolicLink()||(p.mode&511&-449)!==0)throw new de("APP_CONFIG_DIR_INVALID","APP_CONFIG_DIR\u5FC5\u987B\u662F\u6743\u9650\u4E0D\u8D85\u8FC70700\u7684\u666E\u901A\u76EE\u5F55\u3002");let f=H.relative(r,l);if(f===""||!f.startsWith("..")&&!H.isAbsolute(f))throw new de("APP_CONFIG_DIR_INSIDE_PROJECT","APP_CONFIG_DIR\u4E0D\u80FD\u4F4D\u4E8E\u9879\u76EE\u4ED3\u5E93\u5185\u3002");let u=H.join(l,".env");await _f(u,"\u5E94\u7528.env",c.bindings.length===0);let m=E_(await et(u,"utf8")),g=[];for(let h of c.bindings){if(h.kind==="value"){let O=m[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(m[h.name]!==h.file)throw new de("APPLICATION_CONFIG_REFERENCE_CHANGED",`${h.name}\u672A\u4FDD\u6301\u5408\u540C\u6587\u4EF6\u5F15\u7528\u3002`);let k=H.resolve(l,h.file),b=H.relative(l,k);if(!b||b.startsWith("..")||H.isAbsolute(b))throw new de("APPLICATION_CONFIG_REFERENCE_ESCAPE",`${h.name}\u9003\u9038APP_CONFIG_DIR\u3002`);let E=await _f(k,h.name,!0),w=await et(k),_=w.length>0,S;if(_&&h.kind==="certificate-file")try{let O=new __(w);S={subject:O.subject,issuer:O.issuer,validFrom:O.validFrom,validTo:O.validTo}}catch{throw new de("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:_,source:"APP_CONFIG_DIR",display:_?"\u5DF2\u914D\u7F6E":"\u672A\u914D\u7F6E",..._?{fingerprint:La(w),updatedAt:E.mtime.toISOString()}:{},...S?{certificate:S}:{}})}return{application:s.application.id,environment:"local",configDirectory:l,contractDigest:La(a),entries:g}}var yr="project-capabilities.json",Pf=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;function $_(e,t){if(!Pf.test(e)||!Pf.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 O_(e,t){let r=ei.join(e,...t.split("/"));try{let n=await S_(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 Ma(r))}}catch(n){if(n.code==="ENOENT")return{path:t,exists:!1};throw n}}function qa(e,t){let r=B(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 Oc(Ut(r,n.consumerProfile));if(n.consumerProfile==="react-component-library"&&i?.renderer==="react-component-package-json-v1")return Cc(Ut(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 Gc(e){let t=B(e.manifest),r=xe(e.currentLock),n=e.sourceRelease.release,i=e.targetRelease.release,a=t.capabilities.find(R=>R.capabilityId===n.capabilityId),o=r.capabilities.find(R=>R.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&&$_(i.version,n.version)<=0)throw new M("CONSUMER_PROFILE_UNSUPPORTED","Upgrade target must be newer than the locked release");let c=await j_(ei.resolve(e.projectRoot)),d={...t,...e.targetTemplate===void 0?{}:{template:e.targetTemplate},capabilities:t.capabilities.map(R=>R.capabilityId===n.capabilityId?{capabilityId:i.capabilityId,version:i.version}:R)},l=new Map(e.targetRelease.contents);i.assets.some(R=>R.path==="package.json")&&l.set("package.json",qa(d,e.targetRelease));for(let R of i.assets)R.renderer==="application-config-contract-v1"&&l.set(R.path,Ta(d)),R.renderer==="application-config-contract-v2"&&l.set(R.path,Ca(d)),R.renderer==="application-config-binding-v1"&&l.set(R.path,Va(d));let p,f=c,u="package.json",m;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 R=l.get("package.json");if(R===void 0)throw new M("RELEASE_NOT_FOUND","Transition target package.json is unavailable");let Y=await Ma(ei.join(c,"package.json")),ne=e.packageSource.topology??{schemaVersion:1,mode:"standalone",transactionRoot:c,unitRoot:c,unitRelativeRoot:".",unitImporterId:".",lockfilePath:"pnpm-lock.yaml"};f=ne.transactionRoot,u=ne.mode==="pnpm-shared-lockfile"?`${ne.unitRelativeRoot}/package.json`:"package.json",m=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:R,...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(m,tt.desiredLockfile)}catch(tt){throw tt instanceof Z?new M("CONSUMER_PROFILE_UNSUPPORTED",tt.code):tt}}let g=new Map(o.assets.filter(R=>R.path!==yr).map(R=>[R.path,R.digest])),h=new Map(i.assets.filter(R=>R.path!==yr).map(R=>{let Y=l.get(R.path);if(Y===void 0)throw new M("RELEASE_NOT_FOUND","Upgrade target asset content is unavailable",R.path);return[R.path,v(Y)]})),y=[...new Set([...g.keys(),...h.keys()])].sort(),k=[],b=[];for(let R of y){let Y=await O_(c,R);k.push(Y);let ne=g.get(R),Be=h.get(R),tt=i.assets.find(ig=>ig.path===R);if(tt?.ownership==="seed-file"&&Y.exists&&Y.digest!==void 0){h.set(R,Y.digest),l.set(R,await Ma(ei.join(c,...R.split("/")))),b.push({path:R,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",R);b.push({path:R,kind:"create",ownership:tt?.ownership??"owned-file",desiredDigest:Be})}else Be===void 0?b.push({path:R,kind:"remove",ownership:"owned-file",baseDigest:ne}):b.push({path:R,kind:"replace",ownership:tt?.ownership??"owned-file",baseDigest:ne,desiredDigest:Be})}if(p!==void 0&&m!==void 0){let R=e.packageSource?.currentLockfile;if(R===void 0)throw new M("CONSUMER_PROFILE_UNSUPPORTED","Transition lockfile preimage is unavailable");let Y=l.get(m);k.push({path:m,exists:!0,digest:v(R)}),b.push({path:m,kind:"replace",ownership:"owned-file",baseDigest:v(R),desiredDigest:v(Y)})}let E=await Ma(ei.join(c,yr)),w=Buffer.from(`${JSON.stringify(d,null,2)}
|
|
39
|
+
`);k.push({path:yr,exists:!0,digest:v(E)}),b.push({path:yr,kind:"replace",ownership:"owned-file",baseDigest:v(E),desiredDigest:v(w)});let _={schemaVersion:1,capabilityId:i.capabilityId,version:i.version,integrity:i.integrity,assets:i.assets.filter(R=>R.path!==yr).map(R=>({path:R.path,ownership:R.ownership,desiredDigest:h.get(R.path)})),verifiers:i.verifiers.map(({id:R})=>({id:R,kind:"command"}))},S=f===c?b:b.map(R=>R.path===m?R:{...R,path:`${e.packageSource.topology.unitRelativeRoot}/${R.path}`}),O=f===c?k:k.map(R=>R.path===m?R:{...R,path:`${e.packageSource.topology.unitRelativeRoot}/${R.path}`}),se=Se({action:"upgrade",capability:_,changes:S,observedAssets:O,generatedAt:e.generatedAt,expiresAt:e.expiresAt,...p===void 0?{}:{packageAdoption:p}});l.set(yr,w);let $=new Map;for(let R of se.operations){if(R.disposition!=="ready"||R.kind==="remove")continue;let Y=f===c?"":`${e.packageSource.topology.unitRelativeRoot}/`,ne=R.path===m?R.path:R.path.startsWith(Y)?R.path.slice(Y.length):R.path,Be=l.get(ne);if(Be===void 0)throw new M("RELEASE_NOT_FOUND","Upgrade desired content is unavailable",R.path);$.set(R.path,Be)}return{sourceLock:r,targetManifest:d,release:e.targetRelease,plan:se,desiredContents:$,transactionRoot:f}}import{link as C_,mkdir as T_,open as Nf,readFile as lt,readdir as x_,realpath as dt,rm as L_,unlink as V_}from"node:fs/promises";import pe from"node:path";var j=class extends Error{code;constructor(t,r){super(r),this.code=t,this.name="DeliveryError"}};function Ae(e){return/^sha256:[a-f0-9]{64}$/.test(e)}function Df(e){return v(A(e))}function Hc(e){if(!Ae(e.project.lockDigest)||!Ae(e.project.appliedPlanId)||!Ae(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:Df(t)}}function Jc(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(Df(n)!==r)throw new j("DELIVERY_PRECONDITION_FAILED","Delivery Plan is invalid or has been modified");return Hc({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 Sf(e){if(!Ae(e.planId)||!Ae(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(A(t))}}function jf(e){if(!Ae(e.planId)||!Ae(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(A(t))}}function Fa(e){let t=e,{recordId:r,...n}=t??{};if(t?.schemaVersion!==1||t.status!=="remote-write-started"||r!==v(A(n)))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Attempt Record is invalid or has been modified");return t}function Wc(e){let t=e,{recordId:r,...n}=t??{};if(t?.schemaVersion!==1||t.status!=="registry-accepted"||r!==v(A(n)))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Stage Record is invalid or has been modified");return t}function $f(e){if(!Ae(e.planId)||!Ae(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(A(t))}}function Kc(e){let t=e,{recordId:r,...n}=t??{};if(t?.schemaVersion!==1||t.status!=="artifact-digest-verified"||r!==v(A(n)))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Stage Review Record is invalid or has been modified");return t}function Ua(e){if(!Ae(e.planId)||!Ae(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"||!Ae(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(A(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(A(t))}}function Yc(e){let t=e,{receiptId:r,...n}=t??{};if(t?.schemaVersion!==1&&t?.schemaVersion!==2||t.status!=="verified"||r!==v(A(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 M_(e){let t=await Nf(e,"r");try{await t.sync()}finally{await t.close()}}async function ti(e,t){let r=pe.dirname(e);await T_(r,{recursive:!0,mode:448});let n=`${e}.tmp-${process.pid}-${crypto.randomUUID()}`,i=await Nf(n,"wx",384);try{await i.writeFile(`${A(t)}
|
|
40
|
+
`,"utf8"),await i.sync()}finally{await i.close()}try{await C_(n,e),await V_(n),await M_(r)}catch(a){throw await L_(n,{force:!0}),a}}async function Of(e){let t=await dt(pe.resolve(e.projectRoot)),r=Jc(e.plan),n=pe.join(t,".dyyto","delivery","plans",`${r.planId}.json`);try{await ti(n,r)}catch(i){if(i.code!=="EEXIST")throw i;if(A(Jc(JSON.parse(await lt(n,"utf8"))))!==A(r))throw new j("DELIVERY_PRECONDITION_FAILED","Stored Delivery Plan content does not match its identity")}return r}async function zt(e){if(!Ae(e.planId))throw new j("DELIVERY_PLAN_NOT_FOUND","Delivery Plan identity is invalid");let t=await dt(pe.resolve(e.projectRoot));try{let r=Jc(JSON.parse(await lt(pe.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 Zc(e){let t=await dt(pe.resolve(e.projectRoot)),r=Yc(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=pe.join(t,".dyyto","delivery","receipts",`${r.planId}.json`);try{await ti(i,r)}catch(a){if(a.code!=="EEXIST")throw a;let o=Yc(JSON.parse(await lt(i,"utf8")));if(A(o)!==A(r))throw new j("DELIVERY_RECEIPT_INVALID","A different Receipt already exists for this Plan");return o}return r}async function ri(e){if(!Ae(e.planId))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Receipt Plan identity is invalid");let t=await dt(pe.resolve(e.projectRoot));try{let r=Yc(JSON.parse(await lt(pe.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 Cf(e){let t=await dt(pe.resolve(e.projectRoot)),r=Fa(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=pe.join(t,".dyyto","delivery","attempts",`${r.planId}.json`);try{await ti(i,r)}catch(a){if(a.code!=="EEXIST")throw a;let o=Fa(JSON.parse(await lt(i,"utf8")));if(A(o)!==A(r))throw new j("DELIVERY_RECEIPT_INVALID","A different Attempt Record already exists for this Plan");return o}return r}async function Tf(e){if(!Ae(e.planId))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Attempt Plan identity is invalid");let t=await dt(pe.resolve(e.projectRoot));try{let r=Fa(JSON.parse(await lt(pe.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 xf(e){let t=await dt(pe.resolve(e.projectRoot)),r=pe.join(t,".dyyto","delivery","attempts"),n;try{n=await x_(r)}catch(i){if(i.code==="ENOENT")return null;throw i}for(let i of n.sort()){if(!i.endsWith(".json"))continue;let a=Fa(JSON.parse(await lt(pe.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 Lf(e){let t=await dt(pe.resolve(e.projectRoot)),r=Wc(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=pe.join(t,".dyyto","delivery","stages",`${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(A(o)!==A(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(!Ae(e.planId))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Stage Plan identity is invalid");let t=await dt(pe.resolve(e.projectRoot));try{let r=Wc(JSON.parse(await lt(pe.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 Vf(e){let t=await dt(pe.resolve(e.projectRoot)),r=Kc(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=pe.join(t,".dyyto","delivery","stage-reviews",`${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(A(o)!==A(r))throw new j("DELIVERY_RECEIPT_INVALID","A different Stage Review Record already exists for this Plan");return o}return r}async function Mf(e){if(!Ae(e.planId))throw new j("DELIVERY_RECEIPT_INVALID","Delivery Stage Review Plan identity is invalid");let t=await dt(pe.resolve(e.projectRoot));try{let r=Kc(JSON.parse(await lt(pe.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 nm,readdir as EE}from"node:fs/promises";import el from"node:path";import{mkdir as Xc,open as Ja,readFile as ii,readdir as em,rename as Wa,rm as tm}from"node:fs/promises";import ve from"node:path";var q_=44;var qf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",F_=new Uint8Array(64),Uf=new Uint8Array(128);for(let e=0;e<qf.length;e++){let t=qf.charCodeAt(e);F_[e]=t,Uf[t]=e}function ni(e,t){let r=0,n=0,i=0;do{let o=e.next();i=Uf[o],r|=(i&31)<<n,n+=5}while(i&32);let a=r&1;return r>>>=1,a&&(r=-2147483648|-r),t+r}function Ff(e,t){return e.pos>=t?!1:e.peek()!==q_}var ON=1024*16;var U_=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 zf(e){let{length:t}=e,r=new U_(e),n=[],i=0,a=0,o=0,s=0,c=0;do{let d=r.indexOf(";"),l=[],p=!0,f=0;for(i=0;r.pos<d;){let u;i=ni(r,i),i<f&&(p=!1),f=i,Ff(r,d)?(a=ni(r,a),o=ni(r,o),s=ni(r,s),Ff(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||z_(l),n.push(l),r.pos=d+1}while(r.pos<=t);return n}function z_(e){e.sort(B_)}function B_(e,t){return e[0]-t[0]}var G_=/^[\w+.-]+:\/\//,J_=/^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/,W_=/^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;function K_(e){return G_.test(e)}function Y_(e){return e.startsWith("//")}function Jf(e){return e.startsWith("/")}function H_(e){return e.startsWith("file:")}function Bf(e){return/^[.?#]/.test(e)}function za(e){let t=J_.exec(e);return Wf(t[1],t[2]||"",t[3],t[4]||"",t[5]||"/",t[6]||"",t[7]||"")}function Z_(e){let t=W_.exec(e),r=t[2];return Wf("file:","",t[1]||"","",Jf(r)?r:"/"+r,t[3]||"",t[4]||"")}function Wf(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 Gf(e){if(Y_(e)){let r=za("http:"+e);return r.scheme="",r.type=6,r}if(Jf(e)){let r=za("http://foo.com"+e);return r.scheme="",r.host="",r.type=5,r}if(H_(e))return Z_(e);if(K_(e))return za(e);let t=za("http://foo.com/"+e);return t.scheme="",t.host="",t.type=e?e.startsWith("?")?3:e.startsWith("#")?2:4:1,t}function X_(e){if(e.endsWith("/.."))return e;let t=e.lastIndexOf("/");return e.slice(0,t+1)}function Q_(e,t){Kf(t,t.type),e.path==="/"?e.path=t.path:e.path=X_(t.path)+e.path}function Kf(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 Yf(e,t){if(!e&&!t)return"";let r=Gf(e),n=r.type;if(t&&n!==7){let a=Gf(t),o=a.type;switch(n){case 1:r.hash=a.hash;case 2:r.query=a.query;case 3:case 4:Q_(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)}Kf(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?Bf(t||e)&&!Bf(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 eE(e){if(!e)return"";let t=e.lastIndexOf("/");return e.slice(0,t+1)}function tE(e,t){let r=eE(e),n=t?t+"/":"";return i=>Yf(n+(i||""),r)}var Bt=0,rE=1,nE=2,iE=3,aE=4;function oE(e,t){let r=Hf(e,0);if(r===e.length)return e;t||(e=e.slice());for(let n=r;n<e.length;n=Hf(e,n+1))e[n]=cE(e[n],t);return e}function Hf(e,t){for(let r=t;r<e.length;r++)if(!sE(e[r]))return r;return e.length}function sE(e){for(let t=1;t<e.length;t++)if(e[t][Bt]<e[t-1][Bt])return!1;return!0}function cE(e,t){return t||(e=e.slice()),e.sort(lE)}function lE(e,t){return e[Bt]-t[Bt]}var Ga=!1;function dE(e,t,r,n){for(;r<=n;){let i=r+(n-r>>1),a=e[i][Bt]-t;if(a===0)return Ga=!0,i;a<0?r=i+1:n=i-1}return Ga=!1,r-1}function pE(e,t,r){for(let n=r+1;n<e.length&&e[n][Bt]===t;r=n++);return r}function uE(e,t,r){for(let n=r-1;n>=0&&e[n][Bt]===t;r=n--);return r}function fE(){return{lastKey:-1,lastNeedle:-1,lastIndex:-1}}function mE(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 Ga=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=dE(e,t,s,c)}function gE(e){return typeof e=="string"?JSON.parse(e):e}var hE="`line` must be greater than 0 (lines start at line 1)",yE="`column` must be greater than or equal to 0 (columns start at column 0)",Zf=-1,wE=1,Xf=class{constructor(e,t){let r=typeof e=="string";if(!r&&e._decodedMemo)return e;let n=gE(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=tE(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=oE(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=fE(),this._bySources=void 0,this._bySourceMemos=void 0}};function vE(e){var t;return(t=e)._decoded||(t._decoded=zf(e._encoded))}function Qf(e,t){let{line:r,column:n,bias:i}=t;if(r--,r<0)throw new Error(hE);if(n<0)throw new Error(yE);let a=vE(e);if(r>=a.length)return Ba(null,null,null,null);let o=a[r],s=IE(o,e._decodedMemo,r,n,i||wE);if(s===-1)return Ba(null,null,null,null);let c=o[s];if(c.length===1)return Ba(null,null,null,null);let{names:d,resolvedSources:l}=e;return Ba(l[c[rE]],c[nE]+1,c[iE],c.length===5?d[c[aE]]:null)}function Ba(e,t,r,n){return{source:e,line:t,column:r,name:n}}function IE(e,t,r,n,i){let a=mE(e,n,t,r);return Ga?a=(i===Zf?pE:uE)(e,n,a):i===Zf&&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"}},Qc=/^sha256:[a-f0-9]{64}$/,rm=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,bE=/^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$/,Ka=(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 kE(e){if(!ai(e)||!Ka(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)||!Ka(e.error,["type","message","frames"])||!Ka(e.page,["origin","path"]))throw new me("RUNTIME_ERROR_INVALID","Runtime Error Envelope structure is invalid");if(e.schemaVersion!==1||typeof e.eventId!="string"||!rm.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"||!Qc.test(n)))throw new me("RUNTIME_ERROR_IDENTITY_UNKNOWN","Runtime Error correlation identity is invalid");if(e.traceparent!==void 0&&(typeof e.traceparent!="string"||!bE.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)||!Ka(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 _E(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(A({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=kE(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=_E(n,r.receivedAt,i);return this.#t(async()=>{let o=this.directory();await Xc(o,{recursive:!0,mode:448});let s=ve.join(o,`${a.eventId}.json`);try{let f=JSON.parse(await ii(s,"utf8")),u={...f,correlation:f.correlation??"unknown"};if(A({...u,receivedAt:a.receivedAt})!==A(a))throw new me("RUNTIME_ERROR_INVALID","eventId is already used for different content");return{eventId:a.eventId,state:u.state,duplicate:!0}}catch(f){if(f.code!=="ENOENT")throw f}let c=`${s}.tmp-${process.pid}-${crypto.randomUUID()}`,d=await Ja(c,"wx",384);try{await d.writeFile(`${A(a)}
|
|
41
|
+
`,"utf8"),await d.sync()}finally{await d.close()}await Wa(c,s);let l=await Ja(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 Xc(n,{recursive:!0,mode:448}),await Wa(r,ve.join(n,`${Date.now()}-${t}`))}async all(){let t=await em(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=A({v:1,offset:t,snapshot:r});return Buffer.from(A({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(A(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(!rm.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 tm(ve.join(this.directory(),`${i.eventId}.json`),{force:!0});for(let i of t.slice(0,1e4))Date.parse(i.receivedAt)<n&&await tm(ve.join(this.directory(),`${i.eventId}.json`),{force:!0})}async registerSourceMap(t){if(!Qc.test(t.releaseId)||!Qc.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(A(t.map)),n=v(r),i=ve.join(this.releases(),t.releaseId);await Xc(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 Ja(`${o}.tmp`,"w",384);try{await c.writeFile(`${A({registration:s,map:t.map})}
|
|
42
|
+
`),await c.sync()}finally{await c.close()}return await Wa(`${o}.tmp`,o),await this.resymbolicate(t.releaseId),s}async resymbolicate(t){let r=await em(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(f=>new URL(l.file,"http://local").pathname.endsWith(`/${f.registration.asset}`));if(!p||l.line===void 0||l.column===void 0)return l;try{let f=Qf(new Xf(p.map),{line:l.line,column:Math.max(0,l.column-1)});return f.source===null||f.line===null||f.column===null?l:(a=!0,{...l,source:f.source.replace(/^file:\/\//,""),sourceLine:f.line,sourceColumn:f.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 Ja(`${c}.tmp`,"w",384);try{await d.writeFile(`${A(s)}
|
|
43
|
+
`),await d.sync()}finally{await d.close()}await Wa(`${c}.tmp`,c)}}};var Fe=(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[Fe("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 nm(el.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[Fe("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[Fe("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[Fe("EVIDENCE_VALID","info","evidence",`\u5DF2\u6838\u9A8C ${e.lock.capabilities.length} \u9879\u80FD\u529B\u7684 ${t} \u6761\u91C7\u7528\u8BC1\u636E\u3002`)]}function tl(e){return e==="adopted"?[]:e==="planned"?[Fe("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"?[Fe("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"?[Fe("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"?[Fe("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")]:[Fe("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 im(e){try{let r=JSON.parse(await nm(el.join(e.workspaceRoot,".dyyto","observability","config.json"),"utf8"));if(!Array.isArray(r.applications)||!r.applications.includes(e.applicationId))return[Fe("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[Fe("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 EE(el.join(e.workspaceRoot,".dyyto","observability","quarantine")).catch(()=>[])).length;return t>0?[Fe("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")]:[Fe("OBSERVABILITY_CONFIGURED","info","repository","\u8FD0\u884C\u65F6\u9519\u8BEF\u91C7\u96C6\u914D\u7F6E\u4E0E\u672C\u5730\u5B58\u50A8\u53EF\u8BFB\u53D6\u3002")]}function am(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 om}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 sm(e){let t=await om(vr.resolve(e.projectRoot)),r=B(e.manifest),n=e.release.release,i=e.currentLock.capabilities.find(f=>f.capabilityId===n.capabilityId&&f.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=B({...r,capabilities:r.capabilities.filter(f=>f.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(f=>({path:f.path,kind:"remove",ownership:f.ownership??"owned-file",baseDigest:f.digest}))],d=await Promise.all(c.map(f=>ci(t,f.path))),l={schemaVersion:1,capabilityId:n.capabilityId,version:n.version,integrity:n.integrity,assets:i.assets.map(f=>({path:f.path,ownership:f.ownership??"owned-file",desiredDigest:f.digest})),verifiers:n.verifiers.map(f=>({id:f.id,kind:"file-digest"}))};return{plan:Se({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 rl(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 om(vr.resolve(e.projectRoot)),r=B(e.manifest),n=e.release.release,i=e.packageSource?.topology,a=i?.transactionRoot??t,o=_=>i?.mode==="pnpm-shared-lockfile"?`${i.unitRelativeRoot}/${_}`:_;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(_=>_.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(_=>_.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(_=>!r.capabilities.some(S=>S.capabilityId===_)||!e.currentLock.capabilities.some(S=>S.capabilityId===_)))throw new ae("CAPABILITY_DEPENDENCY_UNSATISFIED","A required project capability is not adopted and verified");let f=B({...r,capabilities:[...r.capabilities,{capabilityId:n.capabilityId,version:n.version}]}),u=o("project-capabilities.json"),m=Buffer.from(`${JSON.stringify(f,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(m)}],y=new Map([[u,m]]),k;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 _;try{_=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}:{}},R={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 Y=se?(e.packageChannel==="development"?$a:ja)({release:n,...R,consumerProfile:c,packageJson:_,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,...R,lockResolution:e.packageSource.lockResolution,consumerProfile:c,packageJson:_,...S===void 0?{}:{currentLockfile:S},generatedAt:e.generatedAt,expiresAt:e.expiresAt});k=Ra(Y),h.push({path:o("package.json"),kind:"replace",ownership:"owned-file",baseDigest:Y.packageJsonPreimageDigest,desiredDigest:Y.desiredPackageJsonDigest}),y.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}),y.set(O.lockfilePath,Y.desiredLockfile)}catch(S){throw S instanceof Z?new ae("CAPABILITY_PACKAGE_SOURCE_INVALID",S.code):S}}for(let _ of n.assets){let S=e.release.contents.get(_.path);if(S===void 0)throw new ae("CAPABILITY_KIND_UNSUPPORTED","Capability asset content is unavailable");let O=_.renderer==="application-config-contract-v1"?Ta(r):_.renderer==="application-config-contract-v2"?Ca(r):_.renderer==="application-config-binding-v1"?Va(r):S;if(_.ownership==="managed-region"){if(_.regionId===void 0)throw new ae("CAPABILITY_KIND_UNSUPPORTED","Managed region identity is unavailable");let se;try{se=await si(vr.join(t,..._.path.split("/")))}catch{throw new ae("CAPABILITY_DEPENDENCY_UNSATISFIED","The managed shared file is unavailable")}let $=Buffer.from(bu({source:se.toString("utf8"),regionId:_.regionId,content:Buffer.from(O).toString("utf8")}));h.push({path:o(_.path),kind:"merge",ownership:"managed-region",regionId:_.regionId,baseDigest:v(se),desiredDigest:v($)}),y.set(o(_.path),$)}else{let se=await ci(t,_.path);if(_.ownership==="seed-file"&&se.exists){let $=await si(vr.join(t,..._.path.split("/")));h.push({path:o(_.path),kind:"create",ownership:"seed-file",desiredDigest:v($)}),y.set(o(_.path),$)}else h.push({path:o(_.path),kind:"create",ownership:_.ownership,desiredDigest:v(O)}),y.set(o(_.path),O)}}let b=await Promise.all(h.map(_=>ci(a,_.path))),E={schemaVersion:1,capabilityId:n.capabilityId,version:n.version,integrity:n.integrity,assets:h.filter(_=>_.path!==u&&_.path!==i?.lockfilePath).map(_=>({path:i?.mode==="pnpm-shared-lockfile"?_.path.slice(i.unitRelativeRoot.length+1):_.path,ownership:_.ownership,desiredDigest:_.desiredDigest})),verifiers:n.verifiers.map(_=>({id:_.id,kind:"file-digest"}))};return{plan:Se({action:"adopt",capability:E,changes:h,observedAssets:b,generatedAt:e.generatedAt,expiresAt:e.expiresAt,...k===void 0?{}:{packageAdoption:k}}),manifest:f,desiredContents:y,transactionRoot:a,dependency:{profile:c,satisfied:!0}}}var cm=br(nr(),1);var AE={$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:Q},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:Q},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}}}}},pD=new cm.Ajv2020({allErrors:!0,strict:!0}).compile(AE);var fm=br(nr(),1);import{readFile as RE,realpath as PE}from"node:fs/promises";import lm from"node:path";var dm="^[a-z0-9]+(?:[.-][a-z0-9]+)*$",pm="^(?!/)(?!.*(?:^|/)\\.\\.(?:/|$))(?!.*\\\\)[^\\u0000]+$",NE={$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:dm},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:Q},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:Q},version:{type:"string",minLength:1,maxLength:128},channel:{const:"development"}}}},expectedEntrypoint:{type:"string",pattern:pm,maxLength:240},verifiers:{type:"array",minItems:1,maxItems:16,uniqueItems:!0,items:{type:"string",pattern:dm}},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:pm,maxLength:240}}}}}},um=new fm.Ajv2020({allErrors:!0,strict:!0}).compile(NE),Ir=class extends Error{code;issues;constructor(t,r=[]){super(t),this.code=t,this.issues=r}};function DE(e){return v(A(e))}function SE(e){if(!um(e))throw new Ir("EXAMPLE_RECIPE_INVALID",um.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 mm(e){let t=await PE(lm.resolve(e)),r;try{r=SE(JSON.parse(await RE(lm.join(t,"recipe.json"),"utf8")))}catch(a){throw a instanceof Ir?a:new Ir("EXAMPLE_RECIPE_INVALID")}let{integrity:n,...i}=r;if(DE(i)!==n)throw new Ir("EXAMPLE_RECIPE_INTEGRITY_MISMATCH");return r}var ym=br(nr(),1);import{readFile as jE,realpath as $E}from"node:fs/promises";import gm from"node:path";var OE={$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:Q},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:Q},capability:{type:"string",pattern:`${Q.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:Q},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:Q},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"]}}}},hm=new ym.Ajv2020({allErrors:!0,strict:!0,formats:{date:/^\d{4}-\d{2}-\d{2}$/}}).compile(OE),Rt=class extends Error{code;issues;constructor(t,r=[]){super(t),this.code=t,this.issues=r}};function CE(e){return v(A(e))}function TE(e){if(!hm(e))throw new Rt("TEMPLATE_INVALID",hm.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 $E(gm.resolve(e)),n;try{n=TE(JSON.parse(await jE(gm.join(r,"template.json"),"utf8")))}catch(o){throw o instanceof Rt?o:new Rt("TEMPLATE_INVALID")}let{integrity:i,...a}=n;if(CE(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 wm}from"node:fs/promises";import vm from"node:path";var xE=/^[A-Z][A-Z0-9_]*$/u,LE=/(?:API_KEY|ACCESS_KEY|SECRET|TOKEN|PASSWORD|PRIVATE_KEY|DATABASE_URL|POSTGRES_URL)$/u;function VE(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||!xE.test(n[1]))continue;let i=n[1],a=n[2].trim();t.set(i,{name:i,requirement:a.length===0?"conditional":"optional",secret:LE.test(i),configured:!1,source:".env.example",configuredSource:null})}return[...t.values()]}async function Im(e){let t=await wm(vm.join(e.projectRoot,".env.example"),"utf8").then(()=>".env.example").catch(()=>null),r=t?await wm(vm.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}:{}})):VE(r),environmentExample:t,productionValidation:{contract:!0,live:["provider-read","oss-write-read-delete"]}}}var bm={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"])},km=new Set(["queued","running","succeeded","failed","outcome-unknown","cancelled"]);function _m(e,t){if(!bm[t.plane]||t.state&&!km.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=bm[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([...km]),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}},il=/^sha256:[a-f0-9]{64}$/u,ME=/^sha512-[A-Za-z0-9+/]{86}==$/u,qE=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u,FE=/^(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)(?:-[0-9A-Za-z.-]+)?$/u,UE=/[\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&&!UE.test(e)}function nl(e){return Pt(e,500)&&!e.startsWith("/")&&!e.startsWith("../")&&!e.includes("/../")&&!e.includes("\\")}function Em(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 zE(e){return e===null?!0:!Xr(e)||!Qr(e,["fileName","digest","integrity","fileCount","unpackedBytes"])?!1:nl(e.fileName)&&il.test(String(e.digest))&&ME.test(String(e.integrity))&&Number.isSafeInteger(e.fileCount)&&Number(e.fileCount)>0&&Number.isSafeInteger(e.unpackedBytes)&&Number(e.unpackedBytes)>0}function BE(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"||!qE.test(e.packageName)||!FE.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)||!nl(e.source.path)||!Pt(e.source.revision,200)||!il.test(String(e.source.treeDigest))||!zE(e.artifact)||!Xr(e.compatibility)||!Qr(e.compatibility,["node","packageManager"])||!Pt(e.compatibility.node,100)||!Pt(e.compatibility.packageManager,100)||!Em(e.exports)||!Em(e.consumerEvidence)||!Xr(e.documentation))return!1;let t=e.documentation.knowledgeRef===void 0?["readme"]:["readme","knowledgeRef"];return!Qr(e.documentation,t)||!nl(e.documentation.readme)||e.documentation.knowledgeRef!==void 0&&!Pt(e.documentation.knowledgeRef,500)?!1:e.artifact!==null||e.maturity!=="stable"}function GE(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(!BE(t))throw new di("PACKAGE_RELEASE_INVALID","PackageRelease \u5185\u5BB9\u65E0\u6548");return Object.freeze({...t,releaseDigest:v(A(t))})}function Am(e){if(!Xr(e)||!Qr(e,["schemaVersion","kind","packageName","version","title","summary","maturity","source","artifact","compatibility","exports","documentation","consumerEvidence","releaseDigest"])||!il.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=GE(i);if(a.releaseDigest!==t)throw new di("PACKAGE_RELEASE_MODIFIED","PackageRelease \u5DF2\u88AB\u4FEE\u6539");return a}import{lstat as JE,readFile as WE,realpath as KE}from"node:fs/promises";import Rm from"node:path";async function Pm(e){let t=await KE(Rm.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=Rm.join(t,...o.path.split("/")),d=await JE(s).then(async l=>{if(!l.isFile()||l.isSymbolicLink())return;let p=await WE(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 al="0.1.48",pi={DEPENDENCIES_NOT_INSTALLED:4,VERIFIER_RUNTIME_INVALID:4},YE=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/u;function Nm(e,t){return typeof e=="string"&&e.length>0&&e.length<=t&&!YE.test(e)}function HE(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=ZE(t);if(r===null)throw new TypeError("CLI domain error input is invalid");return r}function ZE(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]||!Nm(i("message"),500))return null;let o=i("nextStep");return o!==void 0&&!Nm(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 Oe=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]?HE({code:t.code,message:t.message,...t.nextStep===void 0?{}:{nextStep:t.nextStep}}):void 0}};var Dm=`Dyyto Engineering Platform CLI
|
|
46
46
|
|
|
47
47
|
Usage:
|
|
48
48
|
dyyto <command> [options]
|
|
@@ -105,86 +105,86 @@ Options:
|
|
|
105
105
|
--json Emit one machine-readable JSON object
|
|
106
106
|
--help Show help
|
|
107
107
|
--version Show version
|
|
108
|
-
`;import{lstat as
|
|
109
|
-
`,{flag:"wx",mode:384}).catch(async c=>{if(c.code!=="EEXIST"||await
|
|
110
|
-
`)throw new ze("SCAFFOLD_PLAN_INVALID")}),a}async function
|
|
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.
|
|
108
|
+
`;import{lstat as WS,readFile as XE,readdir as QE}from"node:fs/promises";import jm from"node:path";var Sm={"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 $m(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 Om(e,t,r){if(!(t in Sm))return"Add application requires a supported --profile.";let n=Sm[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 Ya(e,t,r){for(let n of await QE(jm.join(e,t),{withFileTypes:!0}).catch(()=>[]))if(!(!n.isDirectory()||n.isSymbolicLink()))try{if(JSON.parse(await XE(jm.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 Cm(e,t){return await Ya(e,"apps",t)||await Ya(e,"services",t)}import{lstat as Tm,mkdir as sl,readFile as xm,realpath as ol,rm as eA,writeFile as Lm}from"node:fs/promises";import Ue from"node:path";var ze=class extends Error{constructor(r,n){super(r,n===void 0?void 0:{cause:n});this.code=r}code},tA=e=>A(e),Vm=e=>v(tA(e));async function Mm(e,t){let r=await ol(Ue.resolve(e)),n=Ue.join(r,".examples");await sl(n,{recursive:!0});let i=await ol(n),a=Ue.resolve(r,t);if(Ue.dirname(a)!==i||Ue.basename(a).startsWith(".")||Ue.basename(a).length<1)throw new ze("SCAFFOLD_ARGUMENT_INVALID");if(await Tm(a).then(()=>!0).catch(o=>o.code==="ENOENT"?!1:Promise.reject(o)))throw new ze("SCAFFOLD_TARGET_CONFLICT");return{workspaceRoot:r,output:a,outputRelativePath:Ue.relative(r,a)}}async function qm(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 Mm(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:Vm(i)},o=Ue.join(r.workspaceRoot,".dyyto","scaffold-plans");await sl(o,{recursive:!0});let s=Ue.join(o,`${a.planId}.json`);return await Lm(s,`${A(a)}
|
|
109
|
+
`,{flag:"wx",mode:384}).catch(async c=>{if(c.code!=="EEXIST"||await xm(s,"utf8")!==`${A(a)}
|
|
110
|
+
`)throw new ze("SCAFFOLD_PLAN_INVALID")}),a}async function rA(e,t){if(!/^sha256:[a-f0-9]{64}$/u.test(t))throw new ze("SCAFFOLD_PLAN_INVALID");let r=await ol(Ue.resolve(e)),n;try{n=JSON.parse(await xm(Ue.join(r,".dyyto","scaffold-plans",`${t}.json`),"utf8"))}catch{throw new ze("SCAFFOLD_PLAN_NOT_FOUND")}let{planId:i,...a}=n;if(i!==t||Vm(a)!==t||n.workspaceRoot!==r||Date.parse(n.expiresAt)<=Date.now())throw new ze("SCAFFOLD_PLAN_INVALID");return n}async function Fm(e){let t=await rA(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 Mm(t.workspaceRoot,t.outputRelativePath),n;try{n=await e.execute(r.output,t)}catch(s){throw await Tm(r.output).then(()=>!0).catch(()=>!1)&&await eA(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(A(i)),o=Ue.join(t.workspaceRoot,".dyyto","scaffold-evidence");return await sl(o,{recursive:!0}),await Lm(Ue.join(o,`${a}.json`),`${A({...i,evidenceId:a})}
|
|
111
|
+
`,{flag:"wx",mode:384}),{evidenceId:a,output:r.output,receipts:n}}import{lstat as ui,readFile as cl,readdir as nA,realpath as ll}from"node:fs/promises";import ue from"node:path";var Um={capabilities:ue.resolve(import.meta.dirname,"catalog"),packages:ue.resolve(import.meta.dirname,"package-releases")};function iA(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 zm(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 Ha(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 ll(e)}async function aA(e){let t=e;for(;;){if(await ui(ue.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=ue.dirname(t);if(r===t)return;t=r}}async function oA(e){if(!ue.isAbsolute(e))throw new Error("IDP_CONFIG_DIR \u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");let t=await Ha(e,"IDP_CONFIG_DIR");await aA(t);let r=await Ha(ue.join(t,"components"),"components"),n=await Ha(ue.join(r,"dyyto"),"Dyyto \u914D\u7F6E\u76EE\u5F55"),i=ue.relative(t,n);if(i.startsWith("..")||ue.isAbsolute(i))throw new Error("Dyyto \u914D\u7F6E\u76EE\u5F55\u8D8A\u8FC7 IDP_CONFIG_DIR");let a=ue.join(n,".env");await zm(a,"Dyyto \u7EC4\u4EF6 .env");let o=iA(await cl(a,"utf8")).get("DYYTO_PACKAGE_CATALOG_DIRS_FILE");if(o===void 0||o==="")return[];if(ue.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=ue.resolve(n,o),c=ue.relative(n,s);if(c===""||c.startsWith("..")||ue.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(ue.sep).slice(0,-1))d=await Ha(ue.join(d,u),"Package Catalog Binding \u7236\u76EE\u5F55");let l=await ll(ue.dirname(s)),p=ue.relative(n,l);if(p.startsWith("..")||ue.isAbsolute(p))throw new Error("Package Catalog Binding \u89E3\u6790\u540E\u8D8A\u8FC7\u7EC4\u4EF6\u914D\u7F6E\u76EE\u5F55");await zm(s,"Package Catalog Binding");let f=[];for(let u of(await cl(s,"utf8")).split(/\r?\n/u)){let m=u.trim();if(m===""||m.startsWith("#"))continue;if(!ue.isAbsolute(m))throw new Error("Package Catalog Binding \u4E2D\u7684\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");let g=await ui(m);if(!g.isDirectory()||g.isSymbolicLink())throw new Error("Package Catalog Binding \u5FC5\u987B\u6307\u5411\u666E\u901A\u76EE\u5F55");let h=await ll(m),y=await ui(h);if(!y.isDirectory()||y.isSymbolicLink())throw new Error("Package Catalog Binding \u5FC5\u987B\u6307\u5411\u666E\u901A\u76EE\u5F55");f.includes(h)||f.push(h)}return f.sort()}async function sA(){let e=process.env.IDP_CONFIG_DIR,t=e===void 0?[]:await oA(e);return{capabilities:Um.capabilities,packages:[Um.packages,...t]}}async function Za(e){return(await nA(e,{withFileTypes:!0})).filter(t=>t.isDirectory()&&!t.isSymbolicLink()).map(t=>t.name).sort()}function cA(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 lA(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 dA(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 pA(e){let t=[];for(let r of await Za(e))for(let n of await Za(ue.join(e,r))){let i=`capability:${r}@${n}`;t.push(ge(ue.join(e,r,n)).then(a=>({entry:{item:lA(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 uA(e){let t=[];for(let r of await Za(e))for(let n of await Za(ue.join(e,r))){let i=ue.join(e,r,n,"release.json"),a=`package:${r}@${n}`;t.push(cl(i,"utf8").then(o=>{let s=Am(JSON.parse(o));return{entry:{item:dA(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 Bm(e){let t=e??await sA(),r=typeof t.packages=="string"?[t.packages]:[...t.packages],[n,...i]=await Promise.all([pA(t.capabilities),...r.map(uA)]),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 Gm(e){let t=(e.query??"").trim().toLocaleLowerCase("zh-CN"),r=await Bm(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||cA(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 Jm(e){let t=e.ref.startsWith("package:")||e.ref.startsWith("capability:")?e.ref:`${e.ref.startsWith("@")?"package":"capability"}:${e.ref}`,r=await Bm(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"},Hm=hA(mA),yA=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"]),Zm=(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,Xa={"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 Xm(e){return e.capabilities.flatMap(t=>t.assets).filter(t=>t.ownership!=="seed-file")}async function Qa(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 X(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 X(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}),f=new Date,u=new Date(f.getTime()+1800*1e3).toISOString(),m=await r.resolutionWorkerProvider.resolveWorkspace({topology:s,desiredPackageJson:p,currentLockfile:c,sources:t.release.packageSources,registryConfigs:a.registryConfigs,endpointBindings:a.endpointBindings,generatedAt:f.toISOString(),expiresAt:u});return{...a,lockResolution:{lockfile:m.evidence.desiredLockfile,packages:m.evidence.packageFacts.filter(g=>g.managed).map(({registryId:g,packageName:h,version:y,integrity:k})=>({registryId:g,packageName:h,version:y,integrity:k}))},resolutionEvidence:m.evidence,resolutionWorkerReleaseId:m.workerReleaseId,topology:s,currentLockfile:c,preservedImporterDigests:m.preservedImporterDigests}}let d=qc({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 Qm(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 X(N.join(e,"project-capabilities.json"),"utf8")),E=new Date;return sm({projectRoot:e,manifest:b,release:t,currentLock:r,generatedAt:E.toISOString(),expiresAt:new Date(E.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 X(N.join(e,"package.json")),s=await X(N.join(e,"project-capabilities.json")),c=await Kr(e),d=await X(N.join(c.transactionRoot,c.lockfilePath)),l=new Set(r.capabilities.filter(b=>b!==i).flatMap(b=>b.packageAdoption?.sources.map(E=>E.packageName)??[])),p=i.packageAdoption.sources.filter(b=>!l.has(b.packageName)),f=c.mode==="pnpm-shared-lockfile"?Uc({packageJson:o,remove:p}):Fc({packageJson:o,remove:p}),u=r.capabilities.filter(b=>b!==i).flatMap(b=>b.packageAdoption?.sources??[]),m=new Date,g=new Date(m.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:f,currentLockfile:d,sources:u,registryConfigs:a.registryConfigs,endpointBindings:a.endpointBindings,generatedAt:m.toISOString(),expiresAt:g}),E=[`${c.unitRelativeRoot}/project-capabilities.json`,`${c.unitRelativeRoot}/package.json`,c.lockfilePath,...i.assets.map(_=>`${c.unitRelativeRoot}/${_.path}`)],w=await Promise.all(E.map(async _=>X(N.join(c.transactionRoot,..._.split("/"))).then(S=>({path:_,exists:!0,digest:v(S)})).catch(S=>S.code==="ENOENT"?{path:_,exists:!1}:Promise.reject(S))));return{...ff({release:t.release,currentLock:r,projectManifest:s,packageJson:o,currentLockfile:d,endpointBindings:a.endpointBindings,observedAssets:w,topology:c,transactionRoot:c.transactionRoot,preservedImporterDigests:b.preservedImporterDigests,resolutionEvidence:b.evidence,resolutionWorkerReleaseId:b.workerReleaseId,remainingSources:u,generatedAt:m.toISOString(),expiresAt:g}),registryConfigs:a.registryConfigs,endpointBindings:a.endpointBindings}}let{resolvePnpmLock:h}=await import("./optional-runtime.js"),y=await h({desiredPackageJson:f,currentLockfile:d,sources:u,registrySources:[...u,...i.packageAdoption.sources],registries:a.registryConfigs,endpointBindings:a.endpointBindings}),k=await Promise.all(["project-capabilities.json","package.json","pnpm-lock.yaml",...i.assets.map(b=>b.path)].map(async b=>X(N.join(e,...b.split("/"))).then(E=>({path:b,exists:!0,digest:v(E)})).catch(E=>E.code==="ENOENT"?{path:b,exists:!1}:Promise.reject(E))));return{...uf({release:t.release,currentLock:r,projectManifest:s,packageJson:o,currentLockfile:d,desiredLockfile:y.lockfile,endpointBindings:a.endpointBindings,observedAssets:k,generatedAt:m.toISOString(),expiresAt:g}),registryConfigs:a.registryConfigs,endpointBindings:a.endpointBindings}}function U(e){return e.includes("--json")?"json":"human"}function I(e){throw new Oe({code:"CLI_ARGUMENT_INVALID",message:e,exitCode:2,nextStep:"Run dyyto --help."})}function Re(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 eo(e,t){return yA.has(`${e}@${t}`)?N.resolve(import.meta.dirname,"templates",e,t):I("The selected template release is not bundled with this CLI.")}function wA(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 K(e){let t=N.relative(process.cwd(),e);return t.length>0&&t!==".."&&!t.startsWith(`..${N.sep}`)?t:N.basename(e)}async function to(e){let t=JSON.parse(await X(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(Re(r.capabilityId,r.version)),i=await je(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 eg(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(eo(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,y=t.values.license,k=t.values["publish-access"],b=t.values.repository;if([g,h,y,k].some(E=>typeof E!="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(y),publishAccess:String(k),...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")&&Ut(B(p),i),i==="nextjs-full-stack-application"&&fr(B(p));let f=await va({projectRoot:t.positionals[0],manifest:p}),u=await to(f.projectRoot),m=K(f.projectRoot);return{outputMode:U(e),human:`Project '${m}' initialized.
|
|
112
112
|
Plan: ${u.planId}
|
|
113
113
|
State: ${u.state}
|
|
114
|
-
Next: dyyto apply --project ${
|
|
115
|
-
Plan: ${
|
|
116
|
-
State: ${
|
|
114
|
+
Next: dyyto apply --project ${m} --approve ${u.planId}`,value:{schemaVersion:1,ok:!0,command:"create",result:{project:m,profile:i,...n===void 0?{}:{template:`${n.templateId}@${n.version}`},capability:s,plan:u}}}}async function vA(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(Re(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 Fu({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 qu({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=K(d.projectRoot);if(t==="plan"){if(n.values.approve!==void 0)return I("Retrofit plan does not accept --approve.");let m=await pr({projectRoot:d.projectRoot,plan:d.plan,now:c.toISOString()});return{outputMode:U(e),human:`Project: ${l}
|
|
115
|
+
Plan: ${m.planId}
|
|
116
|
+
State: ${m.state}
|
|
117
117
|
Files: project-capabilities.json
|
|
118
|
-
Next: dyyto retrofit apply --project ${l} --approve ${
|
|
118
|
+
Next: dyyto retrofit apply --project ${l} --approve ${m.planId}${n.values["documentation-only"]===!0?" --documentation-only":""}`,value:{schemaVersion:1,ok:!0,command:"retrofit-plan",result:{project:l,plan:m}}}}if(typeof n.values.approve!="string")return I("Retrofit apply requires --approve <planId>.");let p=await Un({projectRoot:d.projectRoot,planId:n.values.approve}),f=await Gr({projectRoot:d.projectRoot,plan:p,approvedPlanId:n.values.approve,desiredContents:d.desiredContents,now:c.toISOString()}),u=await Jr(f);return{outputMode:U(e),human:`Project: ${l}
|
|
119
119
|
Plan: ${p.planId}
|
|
120
120
|
State: ${u.state}
|
|
121
|
-
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 IA(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=B(JSON.parse(await X(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(eo(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,m)=>{let g=gA("corepack",s,{cwd:n,env:{...process.env,NO_COLOR:"1"},stdio:"inherit"}),h=()=>g.kill("SIGINT"),y=()=>g.kill("SIGTERM");process.once("SIGINT",h),process.once("SIGTERM",y),g.once("error",m),g.once("close",k=>{process.off("SIGINT",h),process.off("SIGTERM",y),u(k??1)})})!==0)throw new Oe({code:"CLI_INTERNAL_ERROR",message:"The development server stopped with an error.",exitCode:1});let f={template:`${a.templateId}@${a.version}`,command:o,durationMs:Date.now()-c,stdout:""};return{outputMode:U(t),human:`dev completed for '${K(n)}'.`,value:{schemaVersion:1,ok:!0,command:e,result:f}}}let d=await Hm("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:U(t),human:`${e} completed for '${K(n)}'.`,value:{schemaVersion:1,ok:!0,command:e,result:l}}}async function bA(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(k=>typeof k!="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=$m(o,a);if(s!==void 0)return I(s);let c=await pt(N.resolve(String(t.values.workspace))),d=JSON.parse(await X(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 je(c);if(p===null){let k=await ge(Re(l.capabilityId,l.version)),b=new Date;if((await na({projectRoot:c,release:k,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:Xm(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 Ya(c,a==="fixture"?"fixtures":"packages",String(t.values.name)))return I("A workspace package already uses this npm name.");let[f,u]=i.split("@"),m={schemaVersion:1,...Xa[n]===void 0?{}:{template:Xa[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:f,version:u}]};Ut(B(m),n);let g=await va({projectRoot:N.join(c,...o.split("/")),manifest:m}),h=await to(g.projectRoot),y=K(g.projectRoot);return{outputMode:U(e),human:`Workspace package '${o}' initialized.
|
|
122
122
|
Plan: ${h.planId}
|
|
123
123
|
State: ${h.state}
|
|
124
|
-
Next: dyyto apply --project ${
|
|
124
|
+
Next: dyyto apply --project ${y} --approve ${h.planId}`,value:{schemaVersion:1,ok:!0,command:"add-package",result:{project:y,workspace:K(c),path:o,plan:h}}}}async function kA(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(y=>typeof y!="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=Om(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 X(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 je(s);if(l===null){let y=await ge(Re(d.capabilityId,d.version)),k=new Date;if((await na({projectRoot:s,release:y,generatedAt:k.toISOString(),expiresAt:new Date(k.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:Xm(l)})}catch{return I("Workspace root locked assets have drifted; adding an application is blocked.")}if((await oi({projectRoot:s,lock:l})).some(k=>k.code!=="EVIDENCE_VALID"))return I("Workspace root adoption evidence is invalid; adding an application is blocked.")}if(await Cm(s,String(t.values.name)))return I("A workspace application already uses this name.");let[p,f]=i.split("@"),u={schemaVersion:1,...Xa[n]===void 0?{}:{template:Xa[n]},profile:{id:n,parameters:{name:String(t.values.name)}},capabilities:[{capabilityId:p,version:f}]};fr(B(u));let m=await va({projectRoot:N.join(s,...a.split("/")),manifest:u}),g=await to(m.projectRoot),h=K(m.projectRoot);return{outputMode:U(e),human:`Workspace application '${a}' initialized.
|
|
125
125
|
Plan: ${g.planId}
|
|
126
126
|
State: ${g.state}
|
|
127
|
-
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:K(s),path:a,plan:g}}}}async function tg(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 X(N.join(n,"project-capabilities.json"),"utf8")),a=await je(n);if(a===null)return I("Add feature requires an adopted project with a verified Profile Lock.");let[o,s]=ro(r.values.capability),c=await ge(Re(o,s)),d=new Date,l;try{let u=await Qa(n,c,t);l=await rl({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 Oe({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}),f=K(n);return{outputMode:U(e),human:`Project: ${f}
|
|
128
128
|
Feature: ${o}@${s}
|
|
129
129
|
Dependency: ${l.dependency.profile} satisfied
|
|
130
130
|
Plan: ${p.planId}
|
|
131
131
|
State: ${p.state}
|
|
132
|
-
Next: dyyto apply --project ${
|
|
132
|
+
Next: dyyto apply --project ${f} --approve ${p.planId}`,value:{schemaVersion:1,ok:!0,command:"add-feature",result:{project:f,capability:r.values.capability,dependency:l.dependency,plan:p}}}}async function _A(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 je(n);if(i===null)return I("Remove feature requires a verified Lock.");let[a,o]=ro(r.values.capability),s=await ge(Re(a,o)),c=await Qm(n,s,i,t),d=await pr({projectRoot:n,plan:c.plan,now:new Date().toISOString(),..."transactionRoot"in c?{transactionRoot:c.transactionRoot}:{}}),l=K(n);return{outputMode:U(e),human:`Project: ${l}
|
|
133
133
|
\u79FB\u9664\u80FD\u529B\uFF1A${a}@${o}
|
|
134
134
|
\u72EC\u5360\u5305\uFF1A${c.removedSources.map(p=>`${p.packageName}@${p.version}`).join("\u3001")||"\u65E0\uFF08\u5171\u4EAB\u5305\u5C06\u4FDD\u7559\uFF09"}
|
|
135
135
|
Plan: ${d.planId}
|
|
136
136
|
State: ${d.state}
|
|
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
|
|
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 EA(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 to(r),i=K(r),a=n.state==="reviewable"?`Next: dyyto apply --project ${i} --approve ${n.planId}`:"Resolve the reported conflicts before applying.";return{outputMode:U(e),human:`Project: ${i}
|
|
138
138
|
Plan: ${n.planId}
|
|
139
139
|
State: ${n.state}
|
|
140
|
-
${a}`,value:{schemaVersion:1,ok:!0,command:"plan",result:{project:i,plan:n}}}}function
|
|
140
|
+
${a}`,value:{schemaVersion:1,ok:!0,command:"plan",result:{project:i,plan:n}}}}function ro(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 AA(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 je(r)!==null)return I("Baseline is only for a historical project without a Lock.");let[n,i]=ro(t.values.capability),a=await ge(Re(n,i)),o=JSON.parse(await X(N.join(r,"project-capabilities.json"),"utf8")),s=new Date,c=await Tc({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=K(r);return{outputMode:U(e),human:`Project: ${l}
|
|
141
141
|
Baseline: ${n}@${i}
|
|
142
142
|
Plan: ${d.planId}
|
|
143
143
|
State: ${d.state}
|
|
144
144
|
Preserved seed files: ${d.operations.filter(p=>p.ownership==="seed-file"&&p.disposition==="noop").length}
|
|
145
|
-
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 RA(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 X(N.join(n,"project-capabilities.json"),"utf8")),[a,o]=ro(r.values.to),s=i.capabilities?.find(_=>_.capabilityId===a);if(s===void 0)return I(`Upgrade requires ${a} to be adopted by the project.`);let c=await je(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(Re(s.capabilityId,s.version)),p=await ge(Re(a,o)),f={...i,capabilities:i.capabilities.map(_=>_.capabilityId===a?{capabilityId:a,version:o}:_)},u=p.release.schemaVersion===2&&p.release.availability.maturity!=="withdrawn"&&p.release.packageSources.length>0,m=u?qa(f,p):void 0,g=u?await Qa(n,p,t,m):void 0,h=Zm(a,o),y=new Date,k=await Gc({projectRoot:n,manifest:i,currentLock:c,sourceRelease:l,targetRelease:p,...h===void 0?{}:{targetTemplate:h},generatedAt:y.toISOString(),expiresAt:new Date(y.getTime()+1800*1e3).toISOString(),...r.values.channel==="development"?{packageChannel:"development"}:{},...g===void 0?{}:{packageSource:g}}),b=await pr({projectRoot:n,plan:k.plan,now:y.toISOString(),transactionRoot:k.transactionRoot}),E=K(n),w=b.state==="reviewable"?`Next: dyyto apply --project ${E} --approve ${b.planId}${d?` --repository ${r.values.repository}`:""}`:"Resolve the reported conflicts before applying.";return{outputMode:U(e),human:`Project: ${E}
|
|
146
146
|
Upgrade: ${s.version} -> ${o}
|
|
147
147
|
Plan: ${b.planId}
|
|
148
148
|
State: ${b.state}
|
|
149
|
-
${
|
|
149
|
+
${w}`,value:{schemaVersion:1,ok:!0,command:"upgrade",result:{project:E,source:`${s.capabilityId}@${s.version}`,target:r.values.to,plan:b}}}}async function dl(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 X(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 Un({projectRoot:n,planId:r.values.approve}),s=new Date,c,d,l;if(o.action==="remove"){let u=await je(n);if(u===null)return I("Remove apply requires the verified Lock.");let m=await Qm(n,await ge(Re(o.capability.capabilityId,o.capability.version)),u,t);c=m,d="registryConfigs"in m?m.registryConfigs:void 0,l="endpointBindings"in m?m.endpointBindings:void 0}else if(o.action==="upgrade"){let u=await je(n),m=u?.capabilities.find(w=>w.capabilityId===o.capability.capabilityId);if(u===null||m===void 0)return I("Upgrade apply requires the verified source Lock.");if((m.consumerProfile==="standalone-npm-package"||m.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(Re(o.capability.capabilityId,o.capability.version)),h={...i,capabilities:i.capabilities.map(w=>w.capabilityId===o.capability.capabilityId?{capabilityId:o.capability.capabilityId,version:o.capability.version}:w)},y=g.release.schemaVersion===2&&g.release.availability.maturity!=="withdrawn"&&g.release.packageSources.length>0,k=y?qa(h,g):void 0,b=y?await Qa(n,g,t,k):void 0;d=b?.registryConfigs,l=b?.endpointBindings;let E=Zm(o.capability.capabilityId,o.capability.version);c=await Gc({projectRoot:n,manifest:i,currentLock:u,sourceRelease:await ge(Re(m.capabilityId,m.version)),targetRelease:g,...E===void 0?{}:{targetTemplate:E},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 Tc({projectRoot:n,manifest:i,release:await ge(Re(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(Re(a.capabilityId,a.version)),m=await je(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,...m===null?{}:{currentLock:m},generatedAt:s.toISOString(),expiresAt:new Date(s.getTime()+1800*1e3).toISOString()})}else{let u=await je(n);if(u===null)return I("Feature apply requires the verified Profile Lock.");let m=await ge(Re(o.capability.capabilityId,o.capability.version)),g=await Qa(n,m,t);d=g?.registryConfigs,l=g?.endpointBindings,c=await rl({projectRoot:n,manifest:i,release:m,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 mf({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 f=K(n);return{outputMode:U(e),human:`Project: ${f}
|
|
150
150
|
Plan: ${o.planId}
|
|
151
151
|
State: ${p.state}
|
|
152
152
|
Files applied: ${p.operations.length}
|
|
153
|
-
`+(o.packageAdoption===void 0?`Next: cd ${
|
|
153
|
+
`+(o.packageAdoption===void 0?`Next: cd ${f} && corepack pnpm install`:`Next: dyyto verify --project ${f}`),value:{schemaVersion:1,ok:!0,command:"apply",result:{project:f,planId:o.planId,transaction:p}}}}async function PA(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 mm(wA(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 qm({workspaceRoot:o,output:r.values.output,recipe:i,artifactBundle:s,artifactFallbackBundles:d,artifactPort:a});return{outputMode:U(e),human:`\u793A\u4F8B\uFF1A${i.title}
|
|
154
154
|
Plan\uFF1A${u.planId}
|
|
155
155
|
\u72B6\u6001\uFF1A\u7B49\u5F85\u9636\u6BB5\u6279\u51C6
|
|
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)],
|
|
157
|
-
Evidence\uFF1A${
|
|
158
|
-
\u72B6\u6001\uFF1Aadopted`,value:{schemaVersion:1,ok:!0,command:"scaffold-example-apply",result:
|
|
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)],f;try{f=await Fm({workspaceRoot:o,approvedPlanId:l,recipe:i,execute:async(u,m)=>{if(m.artifactBundle!==s||JSON.stringify(m.artifactFallbackBundles)!==JSON.stringify(d)||m.artifactPort!==a)throw new Error("SCAFFOLD_SOURCE_PLAN_MISMATCH");let g=[],y=(await eg([u,"--profile","nextjs-full-stack-application","--capability",`${i.rootProfile.capabilityId}@${i.rootProfile.version}`,"--name",i.recipeId])).value.result.plan.planId;await dl(["--project",u,"--approve",y],t),g.push(y),await Hm("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 pl(["--project",u]);for(let k of i.capabilities){let b=`${k.capabilityId}@${k.version}`;try{let w=(await tg(["--project",u,"--capability",b,"--channel",k.channel,...p],t)).value.result.plan.planId;await dl(["--project",u,"--approve",w,...p],t),await pl(["--project",u]),g.push(w)}catch(E){throw new Error(`SCAFFOLD_CAPABILITY_FAILED:${b}:${E instanceof Error?E.message:"UNKNOWN"}`,{cause:E})}}return g}})}catch(u){let m=u instanceof ze&&u.cause instanceof Error?u.cause.message:"SCAFFOLD_APPLY_FAILED";throw new Oe({code:"SCAFFOLD_APPLY_FAILED",message:`\u793A\u4F8B\u811A\u624B\u67B6\u6267\u884C\u5931\u8D25\uFF1A${m}`,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:U(e),human:`\u793A\u4F8B\u5DF2\u751F\u6210\uFF1A${N.relative(process.cwd(),f.output)}
|
|
157
|
+
Evidence\uFF1A${f.evidenceId}
|
|
158
|
+
\u72B6\u6001\uFF1Aadopted`,value:{schemaVersion:1,ok:!0,command:"scaffold-example-apply",result:f}}}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:U(e)}}async function pl(e){let{projectRoot:t,outputMode:r}=mi(e,"Verify"),n=JSON.parse(await X(N.join(t,"project-capabilities.json"),"utf8")),i=await je(t),a=await Kr(t).catch(()=>{}),o;try{let h=i?.capabilities.map(k=>k.appliedPlanId)??[],y=i?.capabilities.map(k=>k.capabilityId)??[];try{o=await Ia(t,h,t,y)}catch(k){if(!(k instanceof he)||k.code!=="PLAN_NOT_FOUND"||a===void 0)throw k;o=await Ia(t,h,a.transactionRoot,y)}}catch(h){if(!(h instanceof he)||h.code!=="PLAN_NOT_FOUND"||i===null)throw h;let k=(await ul(["--project",t,"--json"])).value.result,b=await oi({projectRoot:t,lock:i});if(k.state!=="adopted"||b.some(w=>w.code!=="EVIDENCE_VALID"))throw new Oe({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 E=K(t);return{outputMode:r,human:`Project: ${E}
|
|
159
159
|
State: adopted
|
|
160
|
-
Verification: already committed`,value:{schemaVersion:1,ok:!0,command:"verify",result:{project:
|
|
160
|
+
Verification: already committed`,value:{schemaVersion:1,ok:!0,command:"verify",result:{project:E,state:"adopted",reused:!0,lock:i}}}}let s=await ge(Re(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=K(t);return{outputMode:r,human:`Project: ${h}
|
|
161
161
|
State: adopted
|
|
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 $=
|
|
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 $=K(t);return{outputMode:r,human:`Project: ${$}
|
|
163
163
|
State: removed
|
|
164
|
-
Verification: already committed`,value:{schemaVersion:1,ok:!0,command:"verify",result:{project:$,state:"removed",reused:!0,lock:i}}}}let
|
|
164
|
+
Verification: already committed`,value:{schemaVersion:1,ok:!0,command:"verify",result:{project:$,state:"removed",reused:!0,lock:i}}}}let y=o.packageAdoption?.schemaVersion===2&&o.packageAdoption.topology.mode==="pnpm-shared-lockfile"?`${o.packageAdoption.topology.unitRelativeRoot}/`:"",k=new Map(o.operations.flatMap($=>$.desiredDigest===void 0||!$.path.startsWith(y)?[]:[[$.path.slice(y.length),$.desiredDigest]])),b=i.capabilities.filter($=>$!==h),E=[...b].filter($=>$.packageAdoption!==void 0).sort(($,R)=>$.committedAt.localeCompare(R.committedAt)).at(-1)?.packageAdoption,w=b.flatMap($=>$.assets).map($=>({...$,digest:k.get($.path)??($.path==="package.json"?E?.packageJsonDigest:void 0)??$.digest})),{executeRemovalVerification:_}=await import("./optional-runtime.js"),S=await _({projectRoot:t,release:s,remainingAssets:w,removedPaths:h.assets.map($=>$.path)}),O=await Rc({projectRoot:t,...c===void 0?{}:{transactionRoot:c},plan:o,release:s.release,verificationResults:S.results,committedAt:new Date().toISOString(),previousLock:i,expectedAssets:w}),se=K(t);return{outputMode:r,human:`Project: ${se}
|
|
165
165
|
State: removed
|
|
166
166
|
${S.summaries.map($=>`${$.verifierId}: ${$.result}`).join(`
|
|
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(
|
|
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(y=>y.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(y=>y.path===`${d}${h.path}`)?.desiredDigest,ownership:h.ownership,regionId:h.regionId})):o.operations).map(({path:h,desiredDigest:y,ownership:k,regionId:b})=>y===void 0?I("Applied plan is missing a desired asset digest."):{path:h,digest:y,ownership:k==="managed-region"?"managed-region":k==="seed-file"?"seed-file":"owned-file",...b===void 0?{}:{regionId:b}}),{executeVerification:p}=await import("./optional-runtime.js"),f=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,m=await Ac({projectRoot:t,...c===void 0?{}:{transactionRoot:c},plan:o,release:s.release,verificationResults:f.results,committedAt:new Date().toISOString(),expectedAssets:l,...(o.action==="upgrade"||s.release.kind==="engineering-feature"||u)&&i!==null?{previousLock:i}:{}}),g=K(t);return{outputMode:r,human:`Project: ${g}
|
|
168
168
|
State: adopted
|
|
169
|
-
`+
|
|
170
|
-
`),value:{schemaVersion:1,ok:!0,command:"verify",result:{project:g,state:"adopted",verifiers:
|
|
169
|
+
`+f.summaries.map(h=>`${h.verifierId}: ${h.result}`).join(`
|
|
170
|
+
`),value:{schemaVersion:1,ok:!0,command:"verify",result:{project:g,state:"adopted",verifiers:f.summaries,lock:m}}}}async function ul(e){let{projectRoot:t,outputMode:r}=mi(e,"Inspect"),n=await jc(t),i=K(t);if(n.required)return{outputMode:r,human:`Project: ${i}
|
|
171
171
|
State: recovery-required
|
|
172
172
|
Transaction: ${n.kind}
|
|
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
|
|
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 X(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(Re(o.capabilityId,o.version)),c=await je(t);try{let E=await Ia(t,c?.capabilities.map(w=>w.appliedPlanId)??[],t,c?.capabilities.map(w=>w.capabilityId)??[]);if(E.action==="upgrade"||E.action==="adopt")return{outputMode:r,human:`Project: ${i}
|
|
174
174
|
State: applied-unverified
|
|
175
|
-
Plan: ${
|
|
176
|
-
Next: dyyto verify --project ${i}`,value:{schemaVersion:1,ok:!0,command:"inspect",result:{project:i,state:"applied-unverified",operations:
|
|
177
|
-
State: ${
|
|
178
|
-
`+
|
|
175
|
+
Plan: ${E.planId}
|
|
176
|
+
Next: dyyto verify --project ${i}`,value:{schemaVersion:1,ok:!0,command:"inspect",result:{project:i,state:"applied-unverified",operations:E.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 Xu({...l,manifest:a}):a.profile?.id==="react-component-library"?await Qu({...l,manifest:a}):a.profile?.id==="nextjs-full-stack-application"?await ef({...l,manifest:a}):a.profile?.id==="workspace-npm-package"?await tf({...l,manifest:a}):a.profile?.id==="workspace-node-application"?await rf({...l,manifest:a}):a.profile?.id==="workspace-web-application"?await nf({...l,manifest:a}):a.profile?.id==="workspace-expo-application"?await af({...l,manifest:a}):await na(l),f=c===null?void 0:[...c.capabilities].filter(E=>E.packageAdoption!==void 0).sort((E,w)=>E.committedAt.localeCompare(w.committedAt)).at(-1)?.packageAdoption?.packageJsonDigest,u=f===void 0?void 0:await X(N.join(t,"package.json")).then(v).catch(()=>{}),m=p.operations.map(E=>E.path==="package.json"&&u===f?{...E,desiredDigest:f,disposition:"noop",conflictCode:void 0}:E),g=c===null?[]:await Pm({projectRoot:t,lock:c,excludeCapabilityIds:[o.capabilityId]}),h=g.some(E=>E.disposition==="conflict"),y=f!==void 0&&m.every(E=>E.disposition==="noop")?{...p,state:"adopted"}:p,k={...y,state:h?"drifted":y.state,operations:[...m,...g]},b=c?.capabilities.flatMap(E=>E.packageAdoption?.sources.map(w=>({capabilityId:E.capabilityId,registryId:w.registryId,packageName:w.packageName,version:w.version,integrity:w.integrity}))??[])??[];return{outputMode:r,human:`Project: ${i}
|
|
177
|
+
State: ${k.state}
|
|
178
|
+
`+k.operations.map(E=>`${E.path}: ${E.disposition}`).join(`
|
|
179
179
|
`)+(b.length===0?"":`
|
|
180
180
|
\u5305\u6765\u6E90\uFF1A
|
|
181
|
-
${b.map(
|
|
182
|
-
`)}`),value:{schemaVersion:1,ok:!0,command:"inspect",result:{project:i,...
|
|
181
|
+
${b.map(E=>`- ${E.packageName}@${E.version}\uFF08Registry: ${E.registryId}\uFF0C\u5B8C\u6574\u6027\u5DF2\u9501\u5B9A\uFF09`).join(`
|
|
182
|
+
`)}`),value:{schemaVersion:1,ok:!0,command:"inspect",result:{project:i,...k,lock:c,packageSources:b}}}}async function NA(e){let{projectRoot:t,outputMode:r}=mi(e,"Recover"),n=await Yu({projectRoot:t,now:new Date().toISOString()}),i=K(t);return{outputMode:r,human:n.kind==="none"?`Project: ${i}
|
|
183
183
|
Recovery: not-required`:`Project: ${i}
|
|
184
184
|
Recovery: ${n.kind}
|
|
185
|
-
State: ${n.state}`,value:{schemaVersion:1,ok:!0,command:"recover",result:{project:i,recovery:n}}}}function
|
|
185
|
+
State: ${n.state}`,value:{schemaVersion:1,ok:!0,command:"recover",result:{project:i,recovery:n}}}}function rg(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:U(e)}}async function DA(e,t){let{parsed:r,projectRoot:n,outputMode:i}=rg(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 f=r.values.after===void 0?0:Number(r.values.after);if(!Number.isSafeInteger(f)||f<0)return I("Lifecycle logs --after must be a non-negative integer cursor.");l=await o(n,f)}else if(e==="start")await Wm(n,"dev"),l=await c(n,"dev");else if(e==="stop")l=await d(n);else if(e==="restart")await Wm(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=K(n);return{outputMode:i,human:`Project: ${p}
|
|
186
186
|
Lifecycle: ${e}
|
|
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
|
|
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 Oe({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 Wm(e,t){let r=B(JSON.parse(await X(N.join(e,"project-capabilities.json"),"utf8")));if(r.template===void 0)throw new Oe({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(eo(r.template.id,r.template.version))).commands[t]!==t)throw new Oe({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 SA(e){let{projectRoot:t,outputMode:r}=rg(e,"Integrations"),{projectIntegrations:n}=await import("./optional-runtime.js"),i=await n(t),a=K(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}
|
|
188
188
|
Declared: ${i.declared.length}
|
|
189
189
|
Locked: ${i.locked.length}
|
|
190
190
|
Verified: ${i.verified.length}
|
|
@@ -192,7 +192,7 @@ Findings: ${i.findings.length}
|
|
|
192
192
|
Unmanaged platform dependencies: ${i.platformDependencies.length} (workspace ${s("workspace")} / registry ${s("registry")} / other ${s("other")})
|
|
193
193
|
|
|
194
194
|
${[...o,...c].join(`
|
|
195
|
-
`)}`,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 jA(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(m=>typeof m=="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(m=>{throw m instanceof s?new Oe({code:m.code,message:m.message,exitCode:4,nextStep:"Run dyyto packages switch --help."}):m}),p=K(l.projectRoot),f=l.changes.map(m=>` ${m.field} ${m.packageName}: ${m.from} -> ${m.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:U(e),human:`\u9879\u76EE\uFF1A${p}
|
|
196
196
|
\u6765\u6E90\uFF1A${l.source}
|
|
197
197
|
Registry\uFF1A${l.registry??"workspace protocol"}
|
|
198
198
|
\u72B6\u6001\uFF1A${l.state}
|
|
@@ -201,40 +201,40 @@ Packages\uFF1A${l.packages.length}
|
|
|
201
201
|
\u53D8\u66F4\uFF1A${l.changes.length}
|
|
202
202
|
\u5DF2\u5199\u5165\uFF1A${l.written?"\u662F":"\u5426"}
|
|
203
203
|
|
|
204
|
-
${
|
|
205
|
-
`)}${
|
|
204
|
+
${f.join(`
|
|
205
|
+
`)}${f.length>0?`
|
|
206
206
|
|
|
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
|
|
208
|
-
Environment: ${
|
|
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 $A(e){let{projectRoot:t,outputMode:r}=mi(e,"Inspect"),n=B(JSON.parse(await X(N.join(t,"project-capabilities.json"),"utf8")));if(n.profile?.id==="workspace-root"){let s=await Bc({workspaceRoot:t}),c=s.environment.map(y=>({name:y.name,...y.runtimeEnvironmentVariable?{runtimeEnvironmentVariable:y.runtimeEnvironmentVariable}:{},requirement:y.required?"conditional":"optional",kind:y.kind,secret:y.kind!=="value",configured:y.configured,source:"application-config-contract",configuredSource:"APP_CONFIG_DIR",display:y.display,consumers:y.consumers,configuredConsumers:y.configuredConsumers,conflict:y.conflict,consistent:y.consistent,targetScope:"applications"})),d=n.profile.parameters?.name;if(typeof d!="string"||!/^[a-z0-9][a-z0-9._-]{0,127}$/u.test(d))throw new Oe({code:"APPLICATION_CONFIG_WORKSPACE_IDENTITY_REQUIRED",message:"Workspace Manifest\u5FC5\u987B\u58F0\u660E\u7A33\u5B9Aprofile.parameters.name\u3002",exitCode:4,nextStep:"\u4FEE\u6B63project-capabilities.json\u540E\u91CD\u8BD5\u3002"});let l=N.join(t,"config/workspace-environment.json"),p=await X(l,"utf8").then(y=>JSON.parse(y)).catch(y=>y.code==="ENOENT"?null:Promise.reject(y)),f=process.env.APP_CONFIG_DIR,u=f&&N.isAbsolute(f)?N.join(f,d,process.env.DYYTO_APPLICATION_ENVIRONMENT??"local"):null,m=u?await X(N.join(u,".env"),"utf8").then(y=>Object.fromEntries(y.split(/\r?\n/u).map(k=>/^([A-Z][A-Z0-9_]*)=(.*)$/u.exec(k)).filter(k=>k!==null).map(k=>[k[1],k[2].trim()])),()=>({})):{},h=[...await Promise.all((p?.bindings??[]).map(async y=>{let k=m[y.name]??y.default??"",b=y.kind==="value"?k.length>0:!!(u&&k&&await fA(N.resolve(u,k)).then(E=>E.isFile()&&!E.isSymbolicLink()&&E.size>0,()=>!1));return{name:y.name,...y.runtimeEnvironmentVariable?{runtimeEnvironmentVariable:y.runtimeEnvironmentVariable}:{},requirement:y.required?"conditional":"optional",kind:y.kind,secret:y.kind!=="value",configured:b,source:"application-config-contract",configuredSource:"APP_CONFIG_DIR",display:y.kind==="value"?k:b?"\u5DF2\u914D\u7F6E":"\u672A\u914D\u7F6E",consumers:["workspace"],configuredConsumers:b?["workspace"]:[],conflict:!1,consistent:!0,targetScope:"workspace"}})),...c];return{outputMode:r,human:`Workspace: ${K(t)}
|
|
208
|
+
Environment: ${h.filter(y=>y.configured).length}/${h.length} configured`,value:{schemaVersion:1,ok:!0,command:"maintenance",result:{project:K(t),template:"workspace-aggregate",commands:[],environment:h,environmentExample:null,productionValidation:{contract:!0,live:[]},applications:s.applications,summary:s.summary}}}}if(n.template===void 0)throw new Oe({code:"PROJECT_MAINTENANCE_UNAVAILABLE",message:"Project maintenance requires a formal Template Release.",exitCode:4,nextStep:"Adopt a supported engineering template."});let i=await li(eo(n.template.id,n.template.version)),a=await Im({projectRoot:t,commands:i.commands}),o=K(t);return{outputMode:r,human:`Project: ${o}
|
|
209
209
|
Commands: ${a.commands.map(s=>s.id).join(", ")}
|
|
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
|
|
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 OA(e){let{projectRoot:t,outputMode:r}=mi(e,"Inspect"),n=await Qn({projectRoot:t}).catch(i=>{throw new Oe({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}
|
|
211
211
|
\u73AF\u5883\uFF1A${n.environment}
|
|
212
212
|
Config Dir\uFF1A${n.configDirectory}
|
|
213
213
|
\u5DF2\u914D\u7F6E\uFF1A${n.entries.filter(i=>i.configured).length}/${n.entries.length}
|
|
214
214
|
${n.entries.map(i=>`${i.name}: ${i.display}`).join(`
|
|
215
|
-
`)}`,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 CA(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=U(e);if(typeof n=="string"){let c=await Bc({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${K(c.workspaceRoot)}
|
|
216
216
|
\u5E94\u7528\uFF1A${c.summary.total}
|
|
217
217
|
\u5C31\u7EEA\uFF1A${c.summary.ready}
|
|
218
218
|
\u5F85\u521D\u59CB\u5316\uFF1A${c.summary.needsConfigInit}
|
|
219
219
|
\u65E0\u6548\uFF1A${c.summary.invalid}
|
|
220
220
|
|
|
221
221
|
${d.join(`
|
|
222
|
-
`)}`,value:{schemaVersion:1,ok:!0,command:"config-readiness",result:c},...l?{exitCode:l}:{}}}if(typeof r!="string")return I("Config readiness requires --project or --workspace.");let a=await
|
|
222
|
+
`)}`,value:{schemaVersion:1,ok:!0,command:"config-readiness",result:c},...l?{exitCode:l}:{}}}if(typeof r!="string")return I("Config readiness requires --project or --workspace.");let a=await zc({projectRoot:N.resolve(r)}),o=a.missingBindings.length?`
|
|
223
223
|
\u7F3A\u5931\uFF1A${a.missingBindings.join(", ")}`:"",s=t.values.check===!0?a.state==="invalid"?4:a.state==="ready"?0:3:0;return{outputMode:i,human:`\u5E94\u7528\uFF1A${a.application??"\u672A\u58F0\u660E"}
|
|
224
224
|
\u73AF\u5883\uFF1A${a.environment}
|
|
225
225
|
\u72B6\u6001\uFF1A${a.state}
|
|
226
226
|
Config Dir\uFF1A${a.configDirectory??"\u672A\u7269\u5316"}${o}${a.issueCode?`
|
|
227
|
-
\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 TA(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=K(r),i=[];for(let o of await Ym(N.join(r,".dyyto","workbench","tasks")).catch(()=>[]))if(o.endsWith(".json"))try{let s=JSON.parse(await X(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=_m(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:U(e),human:`Project: ${n}
|
|
228
228
|
Operations: ${a.plane}
|
|
229
229
|
Total: ${a.summary.total}
|
|
230
|
-
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 xA(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(B(JSON.parse(await X(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 Ym(N.join(r,s),{withFileTypes:!0}).catch(()=>[])){if(!c.isDirectory()||c.isSymbolicLink())continue;let d=N.join(r,s,c.name);try{await X(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 ul(["--project",s.projectRoot,"--json"])).value.result;c=p.state??"invalid",d=tl(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=tl("invalid")}try{let l=B(JSON.parse(await X(N.join(s.projectRoot,"project-capabilities.json"),"utf8")));l.profile?.id==="workspace-web-application"&&d.push(...await im({workspaceRoot:r,applicationId:String(l.profile.parameters.name)}))}catch{}a.push({unit:s.unit,kind:s.kind,state:c,findings:d})}let o=am({workspace:N.basename(r),generatedAt:new Date().toISOString(),units:a});return{outputMode:U(e),human:`Workspace: ${o.workspace}
|
|
231
231
|
Status: ${o.status}
|
|
232
232
|
Units: ${o.summary.total}
|
|
233
233
|
Healthy: ${o.summary.healthy}
|
|
234
234
|
Attention: ${o.summary.attention}
|
|
235
235
|
Blocked: ${o.summary.blocked}
|
|
236
236
|
`+o.units.map(s=>`${s.unit}: ${s.status} (${s.findings.map(c=>c.code).join(", ")})`).join(`
|
|
237
|
-
`),value:{schemaVersion:1,ok:!0,command:"doctor",result:o}}}async function
|
|
237
|
+
`),value:{schemaVersion:1,ok:!0,command:"doctor",result:o}}}async function fl(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 Km(e){return e.length<=16?e:`${e.slice(0,12)}\u2026`}async function ng(e){let t=B(JSON.parse(await X(N.join(e,"project-capabilities.json"),"utf8"))),r=await je(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(A(r))}}async function LA(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 ng(r),a=await(await fl(t.values.kind)).prepare({projectRoot:r,profile:n.manifest.profile.id,parameters:n.manifest.profile.parameters});if(t.values.kind==="npm-publish"&&await xf({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,f=t.values.workflow,u=t.values.ref;if(l!=="github-actions"&&l!=="gitlab-ci"||typeof p!="string"||typeof f!="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:f,ref:u,...typeof t.values.environment=="string"?{environment:t.values.environment}:{}}}})():void 0;if(o!==void 0){let l=JSON.parse(await X(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,f=`https://${o.execution.provider==="github-actions"?"github.com":"gitlab.com"}/${o.execution.repository}`;if(p!==f)throw new j("NPM_PROVENANCE_REQUIRED","package.json repository does not match the trusted publishing repository identity")}let s=new Date,c=Hc({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 Of({projectRoot:r,plan:c});let d=K(r);return{outputMode:U(e),human:`Project: ${d}
|
|
238
238
|
Delivery: ${c.kind}
|
|
239
239
|
Artifact: ${c.artifact.identity}
|
|
240
240
|
Target: ${c.target.location}
|
|
@@ -246,38 +246,38 @@ Execution: ${c.publication.execution.provider}:${c.publication.execution.reposit
|
|
|
246
246
|
Approval: maintainer 2FA required outside Dyyto`}
|
|
247
247
|
Plan: ${c.planId}
|
|
248
248
|
State: reviewable
|
|
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
|
|
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 VA(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=K(r);if(i!==null)return{outputMode:U(e),human:`Project: ${a}
|
|
250
250
|
Delivery: verified
|
|
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:
|
|
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:U(e),human:`Project: ${a}
|
|
252
252
|
Delivery: staged
|
|
253
|
-
Stage: ${
|
|
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
|
|
253
|
+
Stage: ${Km(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 Tf({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 ng(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 fl(n.kind),l=await d.prepare({projectRoot:r,profile:c.manifest.profile.id,parameters:c.manifest.profile.parameters});if(A(l.artifact)!==A(n.artifact)||A(l.target)!==A(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 Cf({projectRoot:r,record:jf({planId:n.planId,artifactDigest:n.artifact.digest,startedAt:new Date().toISOString()})})}}:{}});if(n.kind==="npm-publish"){let u=Sf({planId:n.planId,stageId:p.externalIdentity,artifactDigest:n.artifact.digest,createdAt:new Date().toISOString()});return await Lf({projectRoot:r,record:u}),{outputMode:U(e),human:`Project: ${a}
|
|
255
255
|
Delivery: staged
|
|
256
|
-
Stage: ${
|
|
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
|
|
256
|
+
Stage: ${Km(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 f=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 Zc({projectRoot:r,receipt:f}),{outputMode:U(e),human:`Project: ${a}
|
|
258
258
|
Delivery: verified
|
|
259
|
-
Receipt: ${
|
|
260
|
-
External: ${
|
|
259
|
+
Receipt: ${f.receiptId}
|
|
260
|
+
External: ${f.externalIdentity}`,value:{schemaVersion:1,ok:!0,command:"delivery-apply",result:{project:a,receipt:f}}}}async function MA(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=K(r);if(i!==null)return{outputMode:U(e),human:`Project: ${a}
|
|
261
261
|
Delivery: verified
|
|
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
|
|
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 Mf({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 X(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=$f({planId:n.planId,stageId:o.stageId,artifactDigest:d,reviewedAt:new Date().toISOString()}),await Vf({projectRoot:r,record:s})}let c=await(await fl(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 Zc({projectRoot:r,receipt:d}),{outputMode:U(e),human:`Project: ${a}
|
|
263
263
|
Delivery: verified
|
|
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:
|
|
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:U(e),human:`Project: ${a}
|
|
265
265
|
Delivery: staged
|
|
266
266
|
Plan: ${n.planId}
|
|
267
267
|
Artifact review: ${s===null?"pending":"verified"}
|
|
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:
|
|
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:U(e),human:`Project: ${a}
|
|
269
269
|
Delivery: ${c.state}
|
|
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
|
|
271
|
-
`),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 qA(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:U(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 FA(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 Oe({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:U(e),human:`${r.error.type}: ${r.error.message}
|
|
272
272
|
State: ${r.state}
|
|
273
273
|
Correlation: ${r.correlation}
|
|
274
274
|
Release: ${r.releaseId??"unknown"}
|
|
275
|
-
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 UA(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:U(e),human:`Release: ${a.releaseId}
|
|
276
276
|
Source Maps: ${a.registrations.length}
|
|
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
|
|
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 zA(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 Gm({...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}
|
|
278
278
|
${o.summary}
|
|
279
279
|
\u6210\u719F\u5EA6\uFF1A${o.maturity}`).join(`
|
|
280
|
-
`);return{outputMode:
|
|
280
|
+
`);return{outputMode:U(e),human:a,value:{schemaVersion:1,ok:!0,command:"catalog-search",result:i}}}async function BA(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 Jm({ref:t.values.ref});return{outputMode:U(e),human:`${r.item.ref}
|
|
281
281
|
${r.item.summary}
|
|
282
282
|
\u6210\u719F\u5EA6\uFF1A${r.item.maturity}
|
|
283
|
-
\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 gj(e,t={}){let r=e[0]==="--"?e.slice(1):e,n=U(r);if(r[0]==="--version"&&r.every(o=>o==="--version"||o==="--json"))return{outputMode:n,human:al,value:{schemaVersion:1,ok:!0,command:"version",result:{version:al}}};if(r.length===0||r[0]==="--help"||r[0]==="-h")return{outputMode:n,human:Dm,value:{schemaVersion:1,ok:!0,command:"help",result:{usage:"dyyto <command> [options]"}}};let[i,...a]=r;return i==="catalog"&&a[0]==="search"?zA(a.slice(1)):i==="catalog"&&a[0]==="show"?BA(a.slice(1)):i==="create"?eg(a):i==="scaffold"&&a[0]==="example"?PA(a.slice(1),t):i==="retrofit"?vA(a):i==="dev"||i==="build"||i==="test"||i==="package"?IA(i,a):i==="add"&&a[0]==="package"?bA(a.slice(1)):i==="add"&&a[0]==="application"?kA(a.slice(1)):i==="add"&&a[0]==="feature"?tg(a.slice(1),t):i==="remove"&&a[0]==="feature"?_A(a.slice(1),t):i==="plan"?EA(a):i==="upgrade"?RA(a,t):i==="apply"?dl(a,t):i==="verify"?pl(a):i==="inspect"?ul(a):i==="doctor"?xA(a):i==="recover"?NA(a):i==="lifecycle"&&typeof a[0]=="string"?DA(a[0],a.slice(1)):i==="packages"&&a[0]==="switch"?jA(a.slice(1)):i==="integrations"?SA(a):i==="maintenance"?$A(a):i==="config"&&a[0]==="inspect"?OA(a.slice(1)):i==="config"&&a[0]==="readiness"?CA(a.slice(1)):i==="operations"?TA(a):i==="baseline"?AA(a):i==="delivery"&&a[0]==="plan"?LA(a.slice(1)):i==="delivery"&&a[0]==="apply"?VA(a.slice(1)):i==="delivery"&&a[0]==="inspect"?MA(a.slice(1)):i==="observe"&&a[0]==="errors"?qA(a.slice(1)):i==="observe"&&a[0]==="error"?FA(a.slice(1)):i==="observe"&&a[0]==="release"&&a[1]==="register"?UA(a.slice(2)):I(`Unknown command '${i}'.`)}export{gj as runApplication};
|