zion-mcp 2.7.14 → 2.8.0
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 +4 -4
- package/dist/{chunk-UTNJOYOL.js → chunk-3KE7DBBZ.js} +1 -1
- package/dist/chunk-4RMPLI2R.js +3 -0
- package/dist/chunk-CAF64CO7.js +1492 -0
- package/dist/chunk-OHILD5KP.js +3 -0
- package/dist/{chunk-QPWH6HFY.js → chunk-U2LHS4U2.js} +1 -1
- package/dist/chunk-UNPVTOSR.js +5 -0
- package/dist/cli-BJFYETZJ.js +1593 -0
- package/dist/{corpus-4KLVM7U2.js → corpus-XVQ4ZV2V.js} +440 -246
- package/dist/{index.cjs-VXTJAAU2.js → index.cjs-JL7FJKD6.js} +1 -1
- package/dist/{json-crdt-RZN2Q6JT.js → json-crdt-322RBKNB.js} +1 -1
- package/dist/{json-crdt-patch-AIX55EJV.js → json-crdt-patch-X2W6V7VS.js} +1 -1
- package/dist/server.js +1 -3136
- package/dist/surface-S5OGOVQV.js +3 -0
- package/dist/{ztype-QQQP6HMK.js → ztype-BFQK2PDI.js} +104 -104
- package/package.json +1 -1
- package/dist/chunk-GVWWJW5X.js +0 -3
|
@@ -0,0 +1,1492 @@
|
|
|
1
|
+
import { createRequire as __nodeCreateRequire } from 'node:module';
|
|
2
|
+
const require = __nodeCreateRequire(import.meta.url);
|
|
3
|
+
import{d as Lr,e as zn,i as Ou,j as Su}from"./chunk-4RMPLI2R.js";import{c as N,d as ks,e as vu,g as u}from"./chunk-OHILD5KP.js";var tr=N(te=>{"use strict";u();Object.defineProperty(te,"__esModule",{value:!0});te.regexpCode=te.getEsmExportName=te.getProperty=te.safeStringify=te.stringify=te.strConcat=te.addCodeArg=te.str=te._=te.nil=te._Code=te.Name=te.IDENTIFIER=te._CodeOrName=void 0;var Qa=class{};te._CodeOrName=Qa;te.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var In=class extends Qa{constructor(e){if(super(),!te.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};te.Name=In;var tt=class extends Qa{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((n,a)=>`${n}${a}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((n,a)=>(a instanceof In&&(n[a.str]=(n[a.str]||0)+1),n),{})}};te._Code=tt;te.nil=new tt("");function Sm(t,...e){let n=[t[0]],a=0;for(;a<e.length;)bl(n,e[a]),n.push(t[++a]);return new tt(n)}te._=Sm;var Tl=new tt("+");function Nm(t,...e){let n=[er(t[0])],a=0;for(;a<e.length;)n.push(Tl),bl(n,e[a]),n.push(Tl,er(t[++a]));return TA(n),new tt(n)}te.str=Nm;function bl(t,e){e instanceof tt?t.push(...e._items):e instanceof In?t.push(e):t.push(AA(e))}te.addCodeArg=bl;function TA(t){let e=1;for(;e<t.length-1;){if(t[e]===Tl){let n=bA(t[e-1],t[e+1]);if(n!==void 0){t.splice(e-1,3,n);continue}t[e++]="+"}e++}}function bA(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof In||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof In))return`"${t}${e.slice(1)}`}function wA(t,e){return e.emptyStr()?t:t.emptyStr()?e:Nm`${t}${e}`}te.strConcat=wA;function AA(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:er(Array.isArray(t)?t.join(","):t)}function IA(t){return new tt(er(t))}te.stringify=IA;function er(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}te.safeStringify=er;function vA(t){return typeof t=="string"&&te.IDENTIFIER.test(t)?new tt(`.${t}`):Sm`[${t}]`}te.getProperty=vA;function OA(t){if(typeof t=="string"&&te.IDENTIFIER.test(t))return new tt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}te.getEsmExportName=OA;function SA(t){return new tt(t.toString())}te.regexpCode=SA});var Il=N(Be=>{"use strict";u();Object.defineProperty(Be,"__esModule",{value:!0});Be.ValueScope=Be.ValueScopeName=Be.Scope=Be.varKinds=Be.UsedValueState=void 0;var je=tr(),wl=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Mo;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Mo||(Be.UsedValueState=Mo={}));Be.varKinds={const:new je.Name("const"),let:new je.Name("let"),var:new je.Name("var")};var zo=class{constructor({prefixes:e,parent:n}={}){this._names={},this._prefixes=e,this._parent=n}toName(e){return e instanceof je.Name?e:this.name(e)}name(e){return new je.Name(this._newName(e))}_newName(e){let n=this._names[e]||this._nameGroup(e);return`${e}${n.index++}`}_nameGroup(e){var n,a;if(!((a=(n=this._parent)===null||n===void 0?void 0:n._prefixes)===null||a===void 0)&&a.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Be.Scope=zo;var Fo=class extends je.Name{constructor(e,n){super(n),this.prefix=e}setValue(e,{property:n,itemIndex:a}){this.value=e,this.scopePath=(0,je._)`.${new je.Name(n)}[${a}]`}};Be.ValueScopeName=Fo;var NA=(0,je._)`\n`,Al=class extends zo{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?NA:je.nil}}get(){return this._scope}name(e){return new Fo(e,this._newName(e))}value(e,n){var a;if(n.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let r=this.toName(e),{prefix:o}=r,s=(a=n.key)!==null&&a!==void 0?a:n.ref,i=this._values[o];if(i){let h=i.get(s);if(h)return h}else i=this._values[o]=new Map;i.set(s,r);let l=this._scope[o]||(this._scope[o]=[]),d=l.length;return l[d]=n.ref,r.setValue(n,{property:o,itemIndex:d}),r}getValue(e,n){let a=this._values[e];if(a)return a.get(n)}scopeRefs(e,n=this._values){return this._reduceValues(n,a=>{if(a.scopePath===void 0)throw new Error(`CodeGen: name "${a}" has no value`);return(0,je._)`${e}${a.scopePath}`})}scopeCode(e=this._values,n,a){return this._reduceValues(e,r=>{if(r.value===void 0)throw new Error(`CodeGen: name "${r}" has no value`);return r.value.code},n,a)}_reduceValues(e,n,a={},r){let o=je.nil;for(let s in e){let i=e[s];if(!i)continue;let l=a[s]=a[s]||new Map;i.forEach(d=>{if(l.has(d))return;l.set(d,Mo.Started);let h=n(d);if(h){let p=this.opts.es5?Be.varKinds.var:Be.varKinds.const;o=(0,je._)`${o}${p} ${d} = ${h};${this.opts._n}`}else if(h=r?.(d))o=(0,je._)`${o}${h}${this.opts._n}`;else throw new wl(d);l.set(d,Mo.Completed)})}return o}};Be.ValueScope=Al});var q=N(V=>{"use strict";u();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 X=tr(),lt=Il(),Zt=tr();Object.defineProperty(V,"_",{enumerable:!0,get:function(){return Zt._}});Object.defineProperty(V,"str",{enumerable:!0,get:function(){return Zt.str}});Object.defineProperty(V,"strConcat",{enumerable:!0,get:function(){return Zt.strConcat}});Object.defineProperty(V,"nil",{enumerable:!0,get:function(){return Zt.nil}});Object.defineProperty(V,"getProperty",{enumerable:!0,get:function(){return Zt.getProperty}});Object.defineProperty(V,"stringify",{enumerable:!0,get:function(){return Zt.stringify}});Object.defineProperty(V,"regexpCode",{enumerable:!0,get:function(){return Zt.regexpCode}});Object.defineProperty(V,"Name",{enumerable:!0,get:function(){return Zt.Name}});var Zo=Il();Object.defineProperty(V,"Scope",{enumerable:!0,get:function(){return Zo.Scope}});Object.defineProperty(V,"ValueScope",{enumerable:!0,get:function(){return Zo.ValueScope}});Object.defineProperty(V,"ValueScopeName",{enumerable:!0,get:function(){return Zo.ValueScopeName}});Object.defineProperty(V,"varKinds",{enumerable:!0,get:function(){return Zo.varKinds}});V.operators={GT:new X._Code(">"),GTE:new X._Code(">="),LT:new X._Code("<"),LTE:new X._Code("<="),EQ:new X._Code("==="),NEQ:new X._Code("!=="),NOT:new X._Code("!"),OR:new X._Code("||"),AND:new X._Code("&&"),ADD:new X._Code("+")};var Nt=class{optimizeNodes(){return this}optimizeNames(e,n){return this}},vl=class extends Nt{constructor(e,n,a){super(),this.varKind=e,this.name=n,this.rhs=a}render({es5:e,_n:n}){let a=e?lt.varKinds.var:this.varKind,r=this.rhs===void 0?"":` = ${this.rhs}`;return`${a} ${this.name}${r};`+n}optimizeNames(e,n){if(e[this.name.str])return this.rhs&&(this.rhs=oa(this.rhs,e,n)),this}get names(){return this.rhs instanceof X._CodeOrName?this.rhs.names:{}}},Go=class extends Nt{constructor(e,n,a){super(),this.lhs=e,this.rhs=n,this.sideEffects=a}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof X.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=oa(this.rhs,e,n),this}get names(){let e=this.lhs instanceof X.Name?{}:{...this.lhs.names};return Bo(e,this.rhs)}},Ol=class extends Go{constructor(e,n,a,r){super(e,a,r),this.op=n}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Sl=class extends Nt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Nl=class extends Nt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Pl=class extends Nt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Cl=class extends Nt{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,n){return this.code=oa(this.code,e,n),this}get names(){return this.code instanceof X._CodeOrName?this.code.names:{}}},nr=class extends Nt{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((n,a)=>n+a.render(e),"")}optimizeNodes(){let{nodes:e}=this,n=e.length;for(;n--;){let a=e[n].optimizeNodes();Array.isArray(a)?e.splice(n,1,...a):a?e[n]=a:e.splice(n,1)}return e.length>0?this:void 0}optimizeNames(e,n){let{nodes:a}=this,r=a.length;for(;r--;){let o=a[r];o.optimizeNames(e,n)||(PA(e,o.names),a.splice(r,1))}return a.length>0?this:void 0}get names(){return this.nodes.reduce((e,n)=>Sn(e,n.names),{})}},Pt=class extends nr{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Dl=class extends nr{},ra=class extends Pt{};ra.kind="else";var vn=class t extends Pt{constructor(e,n){super(n),this.condition=e}render(e){let n=`if(${this.condition})`+super.render(e);return this.else&&(n+="else "+this.else.render(e)),n}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let n=this.else;if(n){let a=n.optimizeNodes();n=this.else=Array.isArray(a)?new ra(a):a}if(n)return e===!1?n instanceof t?n:n.nodes:this.nodes.length?this:new t(Pm(e),n instanceof t?[n]:n.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,n){var a;if(this.else=(a=this.else)===null||a===void 0?void 0:a.optimizeNames(e,n),!!(super.optimizeNames(e,n)||this.else))return this.condition=oa(this.condition,e,n),this}get names(){let e=super.names;return Bo(e,this.condition),this.else&&Sn(e,this.else.names),e}};vn.kind="if";var On=class extends Pt{};On.kind="for";var Rl=class extends On{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iteration=oa(this.iteration,e,n),this}get names(){return Sn(super.names,this.iteration.names)}},Ll=class extends On{constructor(e,n,a,r){super(),this.varKind=e,this.name=n,this.from=a,this.to=r}render(e){let n=e.es5?lt.varKinds.var:this.varKind,{name:a,from:r,to:o}=this;return`for(${n} ${a}=${r}; ${a}<${o}; ${a}++)`+super.render(e)}get names(){let e=Bo(super.names,this.from);return Bo(e,this.to)}},jo=class extends On{constructor(e,n,a,r){super(),this.loop=e,this.varKind=n,this.name=a,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iterable=oa(this.iterable,e,n),this}get names(){return Sn(super.names,this.iterable.names)}},ar=class extends Pt{constructor(e,n,a){super(),this.name=e,this.args=n,this.async=a}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};ar.kind="func";var rr=class extends nr{render(e){return"return "+super.render(e)}};rr.kind="return";var kl=class extends Pt{render(e){let n="try"+super.render(e);return this.catch&&(n+=this.catch.render(e)),this.finally&&(n+=this.finally.render(e)),n}optimizeNodes(){var e,n;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(n=this.finally)===null||n===void 0||n.optimizeNodes(),this}optimizeNames(e,n){var a,r;return super.optimizeNames(e,n),(a=this.catch)===null||a===void 0||a.optimizeNames(e,n),(r=this.finally)===null||r===void 0||r.optimizeNames(e,n),this}get names(){let e=super.names;return this.catch&&Sn(e,this.catch.names),this.finally&&Sn(e,this.finally.names),e}},or=class extends Pt{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};or.kind="catch";var sr=class extends Pt{render(e){return"finally"+super.render(e)}};sr.kind="finally";var xl=class{constructor(e,n={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...n,_n:n.lines?`
|
|
4
|
+
`:""},this._extScope=e,this._scope=new lt.Scope({parent:e}),this._nodes=[new Dl]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,n){let a=this._extScope.value(e,n);return(this._values[a.prefix]||(this._values[a.prefix]=new Set)).add(a),a}getScopeValue(e,n){return this._extScope.getValue(e,n)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,n,a,r){let o=this._scope.toName(n);return a!==void 0&&r&&(this._constants[o.str]=a),this._leafNode(new vl(e,o,a)),o}const(e,n,a){return this._def(lt.varKinds.const,e,n,a)}let(e,n,a){return this._def(lt.varKinds.let,e,n,a)}var(e,n,a){return this._def(lt.varKinds.var,e,n,a)}assign(e,n,a){return this._leafNode(new Go(e,n,a))}add(e,n){return this._leafNode(new Ol(e,V.operators.ADD,n))}code(e){return typeof e=="function"?e():e!==X.nil&&this._leafNode(new Cl(e)),this}object(...e){let n=["{"];for(let[a,r]of e)n.length>1&&n.push(","),n.push(a),(a!==r||this.opts.es5)&&(n.push(":"),(0,X.addCodeArg)(n,r));return n.push("}"),new X._Code(n)}if(e,n,a){if(this._blockNode(new vn(e)),n&&a)this.code(n).else().code(a).endIf();else if(n)this.code(n).endIf();else if(a)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new vn(e))}else(){return this._elseNode(new ra)}endIf(){return this._endBlockNode(vn,ra)}_for(e,n){return this._blockNode(e),n&&this.code(n).endFor(),this}for(e,n){return this._for(new Rl(e),n)}forRange(e,n,a,r,o=this.opts.es5?lt.varKinds.var:lt.varKinds.let){let s=this._scope.toName(e);return this._for(new Ll(o,s,n,a),()=>r(s))}forOf(e,n,a,r=lt.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let s=n instanceof X.Name?n:this.var("_arr",n);return this.forRange("_i",0,(0,X._)`${s}.length`,i=>{this.var(o,(0,X._)`${s}[${i}]`),a(o)})}return this._for(new jo("of",r,o,n),()=>a(o))}forIn(e,n,a,r=this.opts.es5?lt.varKinds.var:lt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,X._)`Object.keys(${n})`,a);let o=this._scope.toName(e);return this._for(new jo("in",r,o,n),()=>a(o))}endFor(){return this._endBlockNode(On)}label(e){return this._leafNode(new Sl(e))}break(e){return this._leafNode(new Nl(e))}return(e){let n=new rr;if(this._blockNode(n),this.code(e),n.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(rr)}try(e,n,a){if(!n&&!a)throw new Error('CodeGen: "try" without "catch" and "finally"');let r=new kl;if(this._blockNode(r),this.code(e),n){let o=this.name("e");this._currNode=r.catch=new or(o),n(o)}return a&&(this._currNode=r.finally=new sr,this.code(a)),this._endBlockNode(or,sr)}throw(e){return this._leafNode(new Pl(e))}block(e,n){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(n),this}endBlock(e){let n=this._blockStarts.pop();if(n===void 0)throw new Error("CodeGen: not in self-balancing block");let a=this._nodes.length-n;if(a<0||e!==void 0&&a!==e)throw new Error(`CodeGen: wrong number of nodes: ${a} vs ${e} expected`);return this._nodes.length=n,this}func(e,n=X.nil,a,r){return this._blockNode(new ar(e,n,a)),r&&this.code(r).endFunc(),this}endFunc(){return this._endBlockNode(ar)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,n){let a=this._currNode;if(a instanceof e||n&&a instanceof n)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${n?`${e.kind}/${n.kind}`:e.kind}"`)}_elseNode(e){let n=this._currNode;if(!(n instanceof vn))throw new Error('CodeGen: "else" without "if"');return this._currNode=n.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let n=this._nodes;n[n.length-1]=e}};V.CodeGen=xl;function Sn(t,e){for(let n in e)t[n]=(t[n]||0)+(e[n]||0);return t}function Bo(t,e){return e instanceof X._CodeOrName?Sn(t,e.names):t}function oa(t,e,n){if(t instanceof X.Name)return a(t);if(!r(t))return t;return new X._Code(t._items.reduce((o,s)=>(s instanceof X.Name&&(s=a(s)),s instanceof X._Code?o.push(...s._items):o.push(s),o),[]));function a(o){let s=n[o.str];return s===void 0||e[o.str]!==1?o:(delete e[o.str],s)}function r(o){return o instanceof X._Code&&o._items.some(s=>s instanceof X.Name&&e[s.str]===1&&n[s.str]!==void 0)}}function PA(t,e){for(let n in e)t[n]=(t[n]||0)-(e[n]||0)}function Pm(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,X._)`!${$l(t)}`}V.not=Pm;var CA=Cm(V.operators.AND);function DA(...t){return t.reduce(CA)}V.and=DA;var RA=Cm(V.operators.OR);function LA(...t){return t.reduce(RA)}V.or=LA;function Cm(t){return(e,n)=>e===X.nil?n:n===X.nil?e:(0,X._)`${$l(e)} ${t} ${$l(n)}`}function $l(t){return t instanceof X.Name?t:(0,X._)`(${t})`}});var Q=N(W=>{"use strict";u();Object.defineProperty(W,"__esModule",{value:!0});W.checkStrictMode=W.getErrorPath=W.Type=W.useFunc=W.setEvaluated=W.evaluatedPropsToName=W.mergeEvaluated=W.eachItem=W.unescapeJsonPointer=W.escapeJsonPointer=W.escapeFragment=W.unescapeFragment=W.schemaRefOrVal=W.schemaHasRulesButRef=W.schemaHasRules=W.checkUnknownRules=W.alwaysValidSchema=W.toHash=void 0;var oe=q(),kA=tr();function xA(t){let e={};for(let n of t)e[n]=!0;return e}W.toHash=xA;function $A(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Lm(t,e),!km(e,t.self.RULES.all))}W.alwaysValidSchema=$A;function Lm(t,e=t.schema){let{opts:n,self:a}=t;if(!n.strictSchema||typeof e=="boolean")return;let r=a.RULES.keywords;for(let o in e)r[o]||Um(t,`unknown keyword: "${o}"`)}W.checkUnknownRules=Lm;function km(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(e[n])return!0;return!1}W.schemaHasRules=km;function UA(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(n!=="$ref"&&e.all[n])return!0;return!1}W.schemaHasRulesButRef=UA;function MA({topSchemaRef:t,schemaPath:e},n,a,r){if(!r){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,oe._)`${n}`}return(0,oe._)`${t}${e}${(0,oe.getProperty)(a)}`}W.schemaRefOrVal=MA;function zA(t){return xm(decodeURIComponent(t))}W.unescapeFragment=zA;function FA(t){return encodeURIComponent(Ml(t))}W.escapeFragment=FA;function Ml(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}W.escapeJsonPointer=Ml;function xm(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}W.unescapeJsonPointer=xm;function GA(t,e){if(Array.isArray(t))for(let n of t)e(n);else e(t)}W.eachItem=GA;function Dm({mergeNames:t,mergeToName:e,mergeValues:n,resultToName:a}){return(r,o,s,i)=>{let l=s===void 0?o:s instanceof oe.Name?(o instanceof oe.Name?t(r,o,s):e(r,o,s),s):o instanceof oe.Name?(e(r,s,o),o):n(o,s);return i===oe.Name&&!(l instanceof oe.Name)?a(r,l):l}}W.mergeEvaluated={props:Dm({mergeNames:(t,e,n)=>t.if((0,oe._)`${n} !== true && ${e} !== undefined`,()=>{t.if((0,oe._)`${e} === true`,()=>t.assign(n,!0),()=>t.assign(n,(0,oe._)`${n} || {}`).code((0,oe._)`Object.assign(${n}, ${e})`))}),mergeToName:(t,e,n)=>t.if((0,oe._)`${n} !== true`,()=>{e===!0?t.assign(n,!0):(t.assign(n,(0,oe._)`${n} || {}`),zl(t,n,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:$m}),items:Dm({mergeNames:(t,e,n)=>t.if((0,oe._)`${n} !== true && ${e} !== undefined`,()=>t.assign(n,(0,oe._)`${e} === true ? true : ${n} > ${e} ? ${n} : ${e}`)),mergeToName:(t,e,n)=>t.if((0,oe._)`${n} !== true`,()=>t.assign(n,e===!0?!0:(0,oe._)`${n} > ${e} ? ${n} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function $m(t,e){if(e===!0)return t.var("props",!0);let n=t.var("props",(0,oe._)`{}`);return e!==void 0&&zl(t,n,e),n}W.evaluatedPropsToName=$m;function zl(t,e,n){Object.keys(n).forEach(a=>t.assign((0,oe._)`${e}${(0,oe.getProperty)(a)}`,!0))}W.setEvaluated=zl;var Rm={};function jA(t,e){return t.scopeValue("func",{ref:e,code:Rm[e.code]||(Rm[e.code]=new kA._Code(e.code))})}W.useFunc=jA;var Ul;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Ul||(W.Type=Ul={}));function BA(t,e,n){if(t instanceof oe.Name){let a=e===Ul.Num;return n?a?(0,oe._)`"[" + ${t} + "]"`:(0,oe._)`"['" + ${t} + "']"`:a?(0,oe._)`"/" + ${t}`:(0,oe._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,oe.getProperty)(t).toString():"/"+Ml(t)}W.getErrorPath=BA;function Um(t,e,n=t.opts.strictSchema){if(n){if(e=`strict mode: ${e}`,n===!0)throw new Error(e);t.self.logger.warn(e)}}W.checkStrictMode=Um});var Ct=N(Fl=>{"use strict";u();Object.defineProperty(Fl,"__esModule",{value:!0});var Ce=q(),ZA={data:new Ce.Name("data"),valCxt:new Ce.Name("valCxt"),instancePath:new Ce.Name("instancePath"),parentData:new Ce.Name("parentData"),parentDataProperty:new Ce.Name("parentDataProperty"),rootData:new Ce.Name("rootData"),dynamicAnchors:new Ce.Name("dynamicAnchors"),vErrors:new Ce.Name("vErrors"),errors:new Ce.Name("errors"),this:new Ce.Name("this"),self:new Ce.Name("self"),scope:new Ce.Name("scope"),json:new Ce.Name("json"),jsonPos:new Ce.Name("jsonPos"),jsonLen:new Ce.Name("jsonLen"),jsonPart:new Ce.Name("jsonPart")};Fl.default=ZA});var ir=N(De=>{"use strict";u();Object.defineProperty(De,"__esModule",{value:!0});De.extendErrors=De.resetErrorsCount=De.reportExtraError=De.reportError=De.keyword$DataError=De.keywordError=void 0;var ee=q(),qo=Q(),$e=Ct();De.keywordError={message:({keyword:t})=>(0,ee.str)`must pass "${t}" keyword validation`};De.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,ee.str)`"${t}" keyword must be ${e} ($data)`:(0,ee.str)`"${t}" keyword is invalid ($data)`};function qA(t,e=De.keywordError,n,a){let{it:r}=t,{gen:o,compositeRule:s,allErrors:i}=r,l=Fm(t,e,n);a??(s||i)?Mm(o,l):zm(r,(0,ee._)`[${l}]`)}De.reportError=qA;function VA(t,e=De.keywordError,n){let{it:a}=t,{gen:r,compositeRule:o,allErrors:s}=a,i=Fm(t,e,n);Mm(r,i),o||s||zm(a,$e.default.vErrors)}De.reportExtraError=VA;function WA(t,e){t.assign($e.default.errors,e),t.if((0,ee._)`${$e.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,ee._)`${$e.default.vErrors}.length`,e),()=>t.assign($e.default.vErrors,null)))}De.resetErrorsCount=WA;function HA({gen:t,keyword:e,schemaValue:n,data:a,errsCount:r,it:o}){if(r===void 0)throw new Error("ajv implementation error");let s=t.name("err");t.forRange("i",r,$e.default.errors,i=>{t.const(s,(0,ee._)`${$e.default.vErrors}[${i}]`),t.if((0,ee._)`${s}.instancePath === undefined`,()=>t.assign((0,ee._)`${s}.instancePath`,(0,ee.strConcat)($e.default.instancePath,o.errorPath))),t.assign((0,ee._)`${s}.schemaPath`,(0,ee.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(t.assign((0,ee._)`${s}.schema`,n),t.assign((0,ee._)`${s}.data`,a))})}De.extendErrors=HA;function Mm(t,e){let n=t.const("err",e);t.if((0,ee._)`${$e.default.vErrors} === null`,()=>t.assign($e.default.vErrors,(0,ee._)`[${n}]`),(0,ee._)`${$e.default.vErrors}.push(${n})`),t.code((0,ee._)`${$e.default.errors}++`)}function zm(t,e){let{gen:n,validateName:a,schemaEnv:r}=t;r.$async?n.throw((0,ee._)`new ${t.ValidationError}(${e})`):(n.assign((0,ee._)`${a}.errors`,e),n.return(!1))}var Nn={keyword:new ee.Name("keyword"),schemaPath:new ee.Name("schemaPath"),params:new ee.Name("params"),propertyName:new ee.Name("propertyName"),message:new ee.Name("message"),schema:new ee.Name("schema"),parentSchema:new ee.Name("parentSchema")};function Fm(t,e,n){let{createErrors:a}=t.it;return a===!1?(0,ee._)`{}`:YA(t,e,n)}function YA(t,e,n={}){let{gen:a,it:r}=t,o=[KA(r,n),JA(t,n)];return XA(t,e,o),a.object(...o)}function KA({errorPath:t},{instancePath:e}){let n=e?(0,ee.str)`${t}${(0,qo.getErrorPath)(e,qo.Type.Str)}`:t;return[$e.default.instancePath,(0,ee.strConcat)($e.default.instancePath,n)]}function JA({keyword:t,it:{errSchemaPath:e}},{schemaPath:n,parentSchema:a}){let r=a?e:(0,ee.str)`${e}/${t}`;return n&&(r=(0,ee.str)`${r}${(0,qo.getErrorPath)(n,qo.Type.Str)}`),[Nn.schemaPath,r]}function XA(t,{params:e,message:n},a){let{keyword:r,data:o,schemaValue:s,it:i}=t,{opts:l,propertyName:d,topSchemaRef:h,schemaPath:p}=i;a.push([Nn.keyword,r],[Nn.params,typeof e=="function"?e(t):e||(0,ee._)`{}`]),l.messages&&a.push([Nn.message,typeof n=="function"?n(t):n]),l.verbose&&a.push([Nn.schema,s],[Nn.parentSchema,(0,ee._)`${h}${p}`],[$e.default.data,o]),d&&a.push([Nn.propertyName,d])}});var jm=N(sa=>{"use strict";u();Object.defineProperty(sa,"__esModule",{value:!0});sa.boolOrEmptySchema=sa.topBoolOrEmptySchema=void 0;var QA=ir(),eI=q(),tI=Ct(),nI={message:"boolean schema is false"};function aI(t){let{gen:e,schema:n,validateName:a}=t;n===!1?Gm(t,!1):typeof n=="object"&&n.$async===!0?e.return(tI.default.data):(e.assign((0,eI._)`${a}.errors`,null),e.return(!0))}sa.topBoolOrEmptySchema=aI;function rI(t,e){let{gen:n,schema:a}=t;a===!1?(n.var(e,!1),Gm(t)):n.var(e,!0)}sa.boolOrEmptySchema=rI;function Gm(t,e){let{gen:n,data:a}=t,r={gen:n,keyword:"false schema",data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,QA.reportError)(r,nI,void 0,e)}});var Gl=N(ia=>{"use strict";u();Object.defineProperty(ia,"__esModule",{value:!0});ia.getRules=ia.isJSONType=void 0;var oI=["string","number","integer","boolean","null","object","array"],sI=new Set(oI);function iI(t){return typeof t=="string"&&sI.has(t)}ia.isJSONType=iI;function cI(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}ia.getRules=cI});var jl=N(qt=>{"use strict";u();Object.defineProperty(qt,"__esModule",{value:!0});qt.shouldUseRule=qt.shouldUseGroup=qt.schemaHasRulesForType=void 0;function lI({schema:t,self:e},n){let a=e.RULES.types[n];return a&&a!==!0&&Bm(t,a)}qt.schemaHasRulesForType=lI;function Bm(t,e){return e.rules.some(n=>Zm(t,n))}qt.shouldUseGroup=Bm;function Zm(t,e){var n;return t[e.keyword]!==void 0||((n=e.definition.implements)===null||n===void 0?void 0:n.some(a=>t[a]!==void 0))}qt.shouldUseRule=Zm});var cr=N(Re=>{"use strict";u();Object.defineProperty(Re,"__esModule",{value:!0});Re.reportTypeError=Re.checkDataTypes=Re.checkDataType=Re.coerceAndCheckDataType=Re.getJSONTypes=Re.getSchemaTypes=Re.DataType=void 0;var dI=Gl(),uI=jl(),hI=ir(),B=q(),qm=Q(),ca;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(ca||(Re.DataType=ca={}));function pI(t){let e=Vm(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}Re.getSchemaTypes=pI;function Vm(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(dI.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Re.getJSONTypes=Vm;function mI(t,e){let{gen:n,data:a,opts:r}=t,o=fI(e,r.coerceTypes),s=e.length>0&&!(o.length===0&&e.length===1&&(0,uI.schemaHasRulesForType)(t,e[0]));if(s){let i=Zl(e,a,r.strictNumbers,ca.Wrong);n.if(i,()=>{o.length?_I(t,e,o):ql(t)})}return s}Re.coerceAndCheckDataType=mI;var Wm=new Set(["string","number","integer","boolean","null"]);function fI(t,e){return e?t.filter(n=>Wm.has(n)||e==="array"&&n==="array"):[]}function _I(t,e,n){let{gen:a,data:r,opts:o}=t,s=a.let("dataType",(0,B._)`typeof ${r}`),i=a.let("coerced",(0,B._)`undefined`);o.coerceTypes==="array"&&a.if((0,B._)`${s} == 'object' && Array.isArray(${r}) && ${r}.length == 1`,()=>a.assign(r,(0,B._)`${r}[0]`).assign(s,(0,B._)`typeof ${r}`).if(Zl(e,r,o.strictNumbers),()=>a.assign(i,r))),a.if((0,B._)`${i} !== undefined`);for(let d of n)(Wm.has(d)||d==="array"&&o.coerceTypes==="array")&&l(d);a.else(),ql(t),a.endIf(),a.if((0,B._)`${i} !== undefined`,()=>{a.assign(r,i),gI(t,i)});function l(d){switch(d){case"string":a.elseIf((0,B._)`${s} == "number" || ${s} == "boolean"`).assign(i,(0,B._)`"" + ${r}`).elseIf((0,B._)`${r} === null`).assign(i,(0,B._)`""`);return;case"number":a.elseIf((0,B._)`${s} == "boolean" || ${r} === null
|
|
5
|
+
|| (${s} == "string" && ${r} && ${r} == +${r})`).assign(i,(0,B._)`+${r}`);return;case"integer":a.elseIf((0,B._)`${s} === "boolean" || ${r} === null
|
|
6
|
+
|| (${s} === "string" && ${r} && ${r} == +${r} && !(${r} % 1))`).assign(i,(0,B._)`+${r}`);return;case"boolean":a.elseIf((0,B._)`${r} === "false" || ${r} === 0 || ${r} === null`).assign(i,!1).elseIf((0,B._)`${r} === "true" || ${r} === 1`).assign(i,!0);return;case"null":a.elseIf((0,B._)`${r} === "" || ${r} === 0 || ${r} === false`),a.assign(i,null);return;case"array":a.elseIf((0,B._)`${s} === "string" || ${s} === "number"
|
|
7
|
+
|| ${s} === "boolean" || ${r} === null`).assign(i,(0,B._)`[${r}]`)}}}function gI({gen:t,parentData:e,parentDataProperty:n},a){t.if((0,B._)`${e} !== undefined`,()=>t.assign((0,B._)`${e}[${n}]`,a))}function Bl(t,e,n,a=ca.Correct){let r=a===ca.Correct?B.operators.EQ:B.operators.NEQ,o;switch(t){case"null":return(0,B._)`${e} ${r} null`;case"array":o=(0,B._)`Array.isArray(${e})`;break;case"object":o=(0,B._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":o=s((0,B._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":o=s();break;default:return(0,B._)`typeof ${e} ${r} ${t}`}return a===ca.Correct?o:(0,B.not)(o);function s(i=B.nil){return(0,B.and)((0,B._)`typeof ${e} == "number"`,i,n?(0,B._)`isFinite(${e})`:B.nil)}}Re.checkDataType=Bl;function Zl(t,e,n,a){if(t.length===1)return Bl(t[0],e,n,a);let r,o=(0,qm.toHash)(t);if(o.array&&o.object){let s=(0,B._)`typeof ${e} != "object"`;r=o.null?s:(0,B._)`!${e} || ${s}`,delete o.null,delete o.array,delete o.object}else r=B.nil;o.number&&delete o.integer;for(let s in o)r=(0,B.and)(r,Bl(s,e,n,a));return r}Re.checkDataTypes=Zl;var yI={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,B._)`{type: ${t}}`:(0,B._)`{type: ${e}}`};function ql(t){let e=EI(t);(0,hI.reportError)(e,yI)}Re.reportTypeError=ql;function EI(t){let{gen:e,data:n,schema:a}=t,r=(0,qm.schemaRefOrVal)(t,a,"type");return{gen:e,keyword:"type",data:n,schema:a.type,schemaCode:r,schemaValue:r,parentSchema:a,params:{},it:t}}});var Ym=N(Vo=>{"use strict";u();Object.defineProperty(Vo,"__esModule",{value:!0});Vo.assignDefaults=void 0;var la=q(),TI=Q();function bI(t,e){let{properties:n,items:a}=t.schema;if(e==="object"&&n)for(let r in n)Hm(t,r,n[r].default);else e==="array"&&Array.isArray(a)&&a.forEach((r,o)=>Hm(t,o,r.default))}Vo.assignDefaults=bI;function Hm(t,e,n){let{gen:a,compositeRule:r,data:o,opts:s}=t;if(n===void 0)return;let i=(0,la._)`${o}${(0,la.getProperty)(e)}`;if(r){(0,TI.checkStrictMode)(t,`default is ignored for: ${i}`);return}let l=(0,la._)`${i} === undefined`;s.useDefaults==="empty"&&(l=(0,la._)`${l} || ${i} === null || ${i} === ""`),a.if(l,(0,la._)`${i} = ${(0,la.stringify)(n)}`)}});var nt=N(re=>{"use strict";u();Object.defineProperty(re,"__esModule",{value:!0});re.validateUnion=re.validateArray=re.usePattern=re.callValidateCode=re.schemaProperties=re.allSchemaProperties=re.noPropertyInData=re.propertyInData=re.isOwnProperty=re.hasPropFunc=re.reportMissingProp=re.checkMissingProp=re.checkReportMissingProp=void 0;var de=q(),Vl=Q(),Vt=Ct(),wI=Q();function AI(t,e){let{gen:n,data:a,it:r}=t;n.if(Hl(n,a,e,r.opts.ownProperties),()=>{t.setParams({missingProperty:(0,de._)`${e}`},!0),t.error()})}re.checkReportMissingProp=AI;function II({gen:t,data:e,it:{opts:n}},a,r){return(0,de.or)(...a.map(o=>(0,de.and)(Hl(t,e,o,n.ownProperties),(0,de._)`${r} = ${o}`)))}re.checkMissingProp=II;function vI(t,e){t.setParams({missingProperty:e},!0),t.error()}re.reportMissingProp=vI;function Km(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,de._)`Object.prototype.hasOwnProperty`})}re.hasPropFunc=Km;function Wl(t,e,n){return(0,de._)`${Km(t)}.call(${e}, ${n})`}re.isOwnProperty=Wl;function OI(t,e,n,a){let r=(0,de._)`${e}${(0,de.getProperty)(n)} !== undefined`;return a?(0,de._)`${r} && ${Wl(t,e,n)}`:r}re.propertyInData=OI;function Hl(t,e,n,a){let r=(0,de._)`${e}${(0,de.getProperty)(n)} === undefined`;return a?(0,de.or)(r,(0,de.not)(Wl(t,e,n))):r}re.noPropertyInData=Hl;function Jm(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}re.allSchemaProperties=Jm;function SI(t,e){return Jm(e).filter(n=>!(0,Vl.alwaysValidSchema)(t,e[n]))}re.schemaProperties=SI;function NI({schemaCode:t,data:e,it:{gen:n,topSchemaRef:a,schemaPath:r,errorPath:o},it:s},i,l,d){let h=d?(0,de._)`${t}, ${e}, ${a}${r}`:e,p=[[Vt.default.instancePath,(0,de.strConcat)(Vt.default.instancePath,o)],[Vt.default.parentData,s.parentData],[Vt.default.parentDataProperty,s.parentDataProperty],[Vt.default.rootData,Vt.default.rootData]];s.opts.dynamicRef&&p.push([Vt.default.dynamicAnchors,Vt.default.dynamicAnchors]);let g=(0,de._)`${h}, ${n.object(...p)}`;return l!==de.nil?(0,de._)`${i}.call(${l}, ${g})`:(0,de._)`${i}(${g})`}re.callValidateCode=NI;var PI=(0,de._)`new RegExp`;function CI({gen:t,it:{opts:e}},n){let a=e.unicodeRegExp?"u":"",{regExp:r}=e.code,o=r(n,a);return t.scopeValue("pattern",{key:o.toString(),ref:o,code:(0,de._)`${r.code==="new RegExp"?PI:(0,wI.useFunc)(t,r)}(${n}, ${a})`})}re.usePattern=CI;function DI(t){let{gen:e,data:n,keyword:a,it:r}=t,o=e.name("valid");if(r.allErrors){let i=e.let("valid",!0);return s(()=>e.assign(i,!1)),i}return e.var(o,!0),s(()=>e.break()),o;function s(i){let l=e.const("len",(0,de._)`${n}.length`);e.forRange("i",0,l,d=>{t.subschema({keyword:a,dataProp:d,dataPropType:Vl.Type.Num},o),e.if((0,de.not)(o),i)})}}re.validateArray=DI;function RI(t){let{gen:e,schema:n,keyword:a,it:r}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(l=>(0,Vl.alwaysValidSchema)(r,l))&&!r.opts.unevaluated)return;let s=e.let("valid",!1),i=e.name("_valid");e.block(()=>n.forEach((l,d)=>{let h=t.subschema({keyword:a,schemaProp:d,compositeRule:!0},i);e.assign(s,(0,de._)`${s} || ${i}`),t.mergeValidEvaluated(h,i)||e.if((0,de.not)(s))})),t.result(s,()=>t.reset(),()=>t.error(!0))}re.validateUnion=RI});var ef=N(yt=>{"use strict";u();Object.defineProperty(yt,"__esModule",{value:!0});yt.validateKeywordUsage=yt.validSchemaType=yt.funcKeywordCode=yt.macroKeywordCode=void 0;var Ue=q(),Pn=Ct(),LI=nt(),kI=ir();function xI(t,e){let{gen:n,keyword:a,schema:r,parentSchema:o,it:s}=t,i=e.macro.call(s.self,r,o,s),l=Qm(n,a,i);s.opts.validateSchema!==!1&&s.self.validateSchema(i,!0);let d=n.name("valid");t.subschema({schema:i,schemaPath:Ue.nil,errSchemaPath:`${s.errSchemaPath}/${a}`,topSchemaRef:l,compositeRule:!0},d),t.pass(d,()=>t.error(!0))}yt.macroKeywordCode=xI;function $I(t,e){var n;let{gen:a,keyword:r,schema:o,parentSchema:s,$data:i,it:l}=t;MI(l,e);let d=!i&&e.compile?e.compile.call(l.self,o,s,l):e.validate,h=Qm(a,r,d),p=a.let("valid");t.block$data(p,g),t.ok((n=e.valid)!==null&&n!==void 0?n:p);function g(){if(e.errors===!1)y(),e.modifying&&Xm(t),T(()=>t.error());else{let w=e.async?f():m();e.modifying&&Xm(t),T(()=>UI(t,w))}}function f(){let w=a.let("ruleErrs",null);return a.try(()=>y((0,Ue._)`await `),I=>a.assign(p,!1).if((0,Ue._)`${I} instanceof ${l.ValidationError}`,()=>a.assign(w,(0,Ue._)`${I}.errors`),()=>a.throw(I))),w}function m(){let w=(0,Ue._)`${h}.errors`;return a.assign(w,null),y(Ue.nil),w}function y(w=e.async?(0,Ue._)`await `:Ue.nil){let I=l.opts.passContext?Pn.default.this:Pn.default.self,O=!("compile"in e&&!i||e.schema===!1);a.assign(p,(0,Ue._)`${w}${(0,LI.callValidateCode)(t,h,I,O)}`,e.modifying)}function T(w){var I;a.if((0,Ue.not)((I=e.valid)!==null&&I!==void 0?I:p),w)}}yt.funcKeywordCode=$I;function Xm(t){let{gen:e,data:n,it:a}=t;e.if(a.parentData,()=>e.assign(n,(0,Ue._)`${a.parentData}[${a.parentDataProperty}]`))}function UI(t,e){let{gen:n}=t;n.if((0,Ue._)`Array.isArray(${e})`,()=>{n.assign(Pn.default.vErrors,(0,Ue._)`${Pn.default.vErrors} === null ? ${e} : ${Pn.default.vErrors}.concat(${e})`).assign(Pn.default.errors,(0,Ue._)`${Pn.default.vErrors}.length`),(0,kI.extendErrors)(t)},()=>t.error())}function MI({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Qm(t,e,n){if(n===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof n=="function"?{ref:n}:{ref:n,code:(0,Ue.stringify)(n)})}function zI(t,e,n=!1){return!e.length||e.some(a=>a==="array"?Array.isArray(t):a==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==a||n&&typeof t>"u")}yt.validSchemaType=zI;function FI({schema:t,opts:e,self:n,errSchemaPath:a},r,o){if(Array.isArray(r.keyword)?!r.keyword.includes(o):r.keyword!==o)throw new Error("ajv implementation error");let s=r.dependencies;if(s?.some(i=>!Object.prototype.hasOwnProperty.call(t,i)))throw new Error(`parent schema must have dependencies of ${o}: ${s.join(",")}`);if(r.validateSchema&&!r.validateSchema(t[o])){let l=`keyword "${o}" value is invalid at path "${a}": `+n.errorsText(r.validateSchema.errors);if(e.validateSchema==="log")n.logger.error(l);else throw new Error(l)}}yt.validateKeywordUsage=FI});var nf=N(Wt=>{"use strict";u();Object.defineProperty(Wt,"__esModule",{value:!0});Wt.extendSubschemaMode=Wt.extendSubschemaData=Wt.getSubschema=void 0;var Et=q(),tf=Q();function GI(t,{keyword:e,schemaProp:n,schema:a,schemaPath:r,errSchemaPath:o,topSchemaRef:s}){if(e!==void 0&&a!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let i=t.schema[e];return n===void 0?{schema:i,schemaPath:(0,Et._)`${t.schemaPath}${(0,Et.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:i[n],schemaPath:(0,Et._)`${t.schemaPath}${(0,Et.getProperty)(e)}${(0,Et.getProperty)(n)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,tf.escapeFragment)(n)}`}}if(a!==void 0){if(r===void 0||o===void 0||s===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:a,schemaPath:r,topSchemaRef:s,errSchemaPath:o}}throw new Error('either "keyword" or "schema" must be passed')}Wt.getSubschema=GI;function jI(t,e,{dataProp:n,dataPropType:a,data:r,dataTypes:o,propertyName:s}){if(r!==void 0&&n!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:i}=e;if(n!==void 0){let{errorPath:d,dataPathArr:h,opts:p}=e,g=i.let("data",(0,Et._)`${e.data}${(0,Et.getProperty)(n)}`,!0);l(g),t.errorPath=(0,Et.str)`${d}${(0,tf.getErrorPath)(n,a,p.jsPropertySyntax)}`,t.parentDataProperty=(0,Et._)`${n}`,t.dataPathArr=[...h,t.parentDataProperty]}if(r!==void 0){let d=r instanceof Et.Name?r:i.let("data",r,!0);l(d),s!==void 0&&(t.propertyName=s)}o&&(t.dataTypes=o);function l(d){t.data=d,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,d]}}Wt.extendSubschemaData=jI;function BI(t,{jtdDiscriminator:e,jtdMetadata:n,compositeRule:a,createErrors:r,allErrors:o}){a!==void 0&&(t.compositeRule=a),r!==void 0&&(t.createErrors=r),o!==void 0&&(t.allErrors=o),t.jtdDiscriminator=e,t.jtdMetadata=n}Wt.extendSubschemaMode=BI});var Yl=N((u$,af)=>{"use strict";u();af.exports=function t(e,n){if(e===n)return!0;if(e&&n&&typeof e=="object"&&typeof n=="object"){if(e.constructor!==n.constructor)return!1;var a,r,o;if(Array.isArray(e)){if(a=e.length,a!=n.length)return!1;for(r=a;r--!==0;)if(!t(e[r],n[r]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if(o=Object.keys(e),a=o.length,a!==Object.keys(n).length)return!1;for(r=a;r--!==0;)if(!Object.prototype.hasOwnProperty.call(n,o[r]))return!1;for(r=a;r--!==0;){var s=o[r];if(!t(e[s],n[s]))return!1}return!0}return e!==e&&n!==n}});var of=N((p$,rf)=>{"use strict";u();var Ht=rf.exports=function(t,e,n){typeof e=="function"&&(n=e,e={}),n=e.cb||n;var a=typeof n=="function"?n:n.pre||function(){},r=n.post||function(){};Wo(e,a,r,t,"",t)};Ht.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Ht.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Ht.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Ht.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 Wo(t,e,n,a,r,o,s,i,l,d){if(a&&typeof a=="object"&&!Array.isArray(a)){e(a,r,o,s,i,l,d);for(var h in a){var p=a[h];if(Array.isArray(p)){if(h in Ht.arrayKeywords)for(var g=0;g<p.length;g++)Wo(t,e,n,p[g],r+"/"+h+"/"+g,o,r,h,a,g)}else if(h in Ht.propsKeywords){if(p&&typeof p=="object")for(var f in p)Wo(t,e,n,p[f],r+"/"+h+"/"+ZI(f),o,r,h,a,f)}else(h in Ht.keywords||t.allKeys&&!(h in Ht.skipKeywords))&&Wo(t,e,n,p,r+"/"+h,o,r,h,a)}n(a,r,o,s,i,l,d)}}function ZI(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var lr=N(Ze=>{"use strict";u();Object.defineProperty(Ze,"__esModule",{value:!0});Ze.getSchemaRefs=Ze.resolveUrl=Ze.normalizeId=Ze._getFullPath=Ze.getFullPath=Ze.inlineRef=void 0;var qI=Q(),VI=Yl(),WI=of(),HI=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function YI(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Kl(t):e?sf(t)<=e:!1}Ze.inlineRef=YI;var KI=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Kl(t){for(let e in t){if(KI.has(e))return!0;let n=t[e];if(Array.isArray(n)&&n.some(Kl)||typeof n=="object"&&Kl(n))return!0}return!1}function sf(t){let e=0;for(let n in t){if(n==="$ref")return 1/0;if(e++,!HI.has(n)&&(typeof t[n]=="object"&&(0,qI.eachItem)(t[n],a=>e+=sf(a)),e===1/0))return 1/0}return e}function cf(t,e="",n){n!==!1&&(e=da(e));let a=t.parse(e);return lf(t,a)}Ze.getFullPath=cf;function lf(t,e){return t.serialize(e).split("#")[0]+"#"}Ze._getFullPath=lf;var JI=/#\/?$/;function da(t){return t?t.replace(JI,""):""}Ze.normalizeId=da;function XI(t,e,n){return n=da(n),t.resolve(e,n)}Ze.resolveUrl=XI;var QI=/^[a-z_][-a-z0-9._]*$/i;function ev(t,e){if(typeof t=="boolean")return{};let{schemaId:n,uriResolver:a}=this.opts,r=da(t[n]||e),o={"":r},s=cf(a,r,!1),i={},l=new Set;return WI(t,{allKeys:!0},(p,g,f,m)=>{if(m===void 0)return;let y=s+g,T=o[m];typeof p[n]=="string"&&(T=w.call(this,p[n])),I.call(this,p.$anchor),I.call(this,p.$dynamicAnchor),o[g]=T;function w(O){let D=this.opts.uriResolver.resolve;if(O=da(T?D(T,O):O),l.has(O))throw h(O);l.add(O);let U=this.refs[O];return typeof U=="string"&&(U=this.refs[U]),typeof U=="object"?d(p,U.schema,O):O!==da(y)&&(O[0]==="#"?(d(p,i[O],O),i[O]=p):this.refs[O]=y),O}function I(O){if(typeof O=="string"){if(!QI.test(O))throw new Error(`invalid anchor "${O}"`);w.call(this,`#${O}`)}}}),i;function d(p,g,f){if(g!==void 0&&!VI(p,g))throw h(f)}function h(p){return new Error(`reference "${p}" resolves to more than one schema`)}}Ze.getSchemaRefs=ev});var hr=N(Yt=>{"use strict";u();Object.defineProperty(Yt,"__esModule",{value:!0});Yt.getData=Yt.KeywordCxt=Yt.validateFunctionCode=void 0;var mf=jm(),df=cr(),Xl=jl(),Ho=cr(),tv=Ym(),ur=ef(),Jl=nf(),x=q(),G=Ct(),nv=lr(),Dt=Q(),dr=ir();function av(t){if(gf(t)&&(yf(t),_f(t))){sv(t);return}ff(t,()=>(0,mf.topBoolOrEmptySchema)(t))}Yt.validateFunctionCode=av;function ff({gen:t,validateName:e,schema:n,schemaEnv:a,opts:r},o){r.code.es5?t.func(e,(0,x._)`${G.default.data}, ${G.default.valCxt}`,a.$async,()=>{t.code((0,x._)`"use strict"; ${uf(n,r)}`),ov(t,r),t.code(o)}):t.func(e,(0,x._)`${G.default.data}, ${rv(r)}`,a.$async,()=>t.code(uf(n,r)).code(o))}function rv(t){return(0,x._)`{${G.default.instancePath}="", ${G.default.parentData}, ${G.default.parentDataProperty}, ${G.default.rootData}=${G.default.data}${t.dynamicRef?(0,x._)`, ${G.default.dynamicAnchors}={}`:x.nil}}={}`}function ov(t,e){t.if(G.default.valCxt,()=>{t.var(G.default.instancePath,(0,x._)`${G.default.valCxt}.${G.default.instancePath}`),t.var(G.default.parentData,(0,x._)`${G.default.valCxt}.${G.default.parentData}`),t.var(G.default.parentDataProperty,(0,x._)`${G.default.valCxt}.${G.default.parentDataProperty}`),t.var(G.default.rootData,(0,x._)`${G.default.valCxt}.${G.default.rootData}`),e.dynamicRef&&t.var(G.default.dynamicAnchors,(0,x._)`${G.default.valCxt}.${G.default.dynamicAnchors}`)},()=>{t.var(G.default.instancePath,(0,x._)`""`),t.var(G.default.parentData,(0,x._)`undefined`),t.var(G.default.parentDataProperty,(0,x._)`undefined`),t.var(G.default.rootData,G.default.data),e.dynamicRef&&t.var(G.default.dynamicAnchors,(0,x._)`{}`)})}function sv(t){let{schema:e,opts:n,gen:a}=t;ff(t,()=>{n.$comment&&e.$comment&&Tf(t),uv(t),a.let(G.default.vErrors,null),a.let(G.default.errors,0),n.unevaluated&&iv(t),Ef(t),mv(t)})}function iv(t){let{gen:e,validateName:n}=t;t.evaluated=e.const("evaluated",(0,x._)`${n}.evaluated`),e.if((0,x._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,x._)`${t.evaluated}.props`,(0,x._)`undefined`)),e.if((0,x._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,x._)`${t.evaluated}.items`,(0,x._)`undefined`))}function uf(t,e){let n=typeof t=="object"&&t[e.schemaId];return n&&(e.code.source||e.code.process)?(0,x._)`/*# sourceURL=${n} */`:x.nil}function cv(t,e){if(gf(t)&&(yf(t),_f(t))){lv(t,e);return}(0,mf.boolOrEmptySchema)(t,e)}function _f({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let n in t)if(e.RULES.all[n])return!0;return!1}function gf(t){return typeof t.schema!="boolean"}function lv(t,e){let{schema:n,gen:a,opts:r}=t;r.$comment&&n.$comment&&Tf(t),hv(t),pv(t);let o=a.const("_errs",G.default.errors);Ef(t,o),a.var(e,(0,x._)`${o} === ${G.default.errors}`)}function yf(t){(0,Dt.checkUnknownRules)(t),dv(t)}function Ef(t,e){if(t.opts.jtd)return hf(t,[],!1,e);let n=(0,df.getSchemaTypes)(t.schema),a=(0,df.coerceAndCheckDataType)(t,n);hf(t,n,!a,e)}function dv(t){let{schema:e,errSchemaPath:n,opts:a,self:r}=t;e.$ref&&a.ignoreKeywordsWithRef&&(0,Dt.schemaHasRulesButRef)(e,r.RULES)&&r.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function uv(t){let{schema:e,opts:n}=t;e.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,Dt.checkStrictMode)(t,"default is ignored in the schema root")}function hv(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,nv.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function pv(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Tf({gen:t,schemaEnv:e,schema:n,errSchemaPath:a,opts:r}){let o=n.$comment;if(r.$comment===!0)t.code((0,x._)`${G.default.self}.logger.log(${o})`);else if(typeof r.$comment=="function"){let s=(0,x.str)`${a}/$comment`,i=t.scopeValue("root",{ref:e.root});t.code((0,x._)`${G.default.self}.opts.$comment(${o}, ${s}, ${i}.schema)`)}}function mv(t){let{gen:e,schemaEnv:n,validateName:a,ValidationError:r,opts:o}=t;n.$async?e.if((0,x._)`${G.default.errors} === 0`,()=>e.return(G.default.data),()=>e.throw((0,x._)`new ${r}(${G.default.vErrors})`)):(e.assign((0,x._)`${a}.errors`,G.default.vErrors),o.unevaluated&&fv(t),e.return((0,x._)`${G.default.errors} === 0`))}function fv({gen:t,evaluated:e,props:n,items:a}){n instanceof x.Name&&t.assign((0,x._)`${e}.props`,n),a instanceof x.Name&&t.assign((0,x._)`${e}.items`,a)}function hf(t,e,n,a){let{gen:r,schema:o,data:s,allErrors:i,opts:l,self:d}=t,{RULES:h}=d;if(o.$ref&&(l.ignoreKeywordsWithRef||!(0,Dt.schemaHasRulesButRef)(o,h))){r.block(()=>wf(t,"$ref",h.all.$ref.definition));return}l.jtd||_v(t,e),r.block(()=>{for(let g of h.rules)p(g);p(h.post)});function p(g){(0,Xl.shouldUseGroup)(o,g)&&(g.type?(r.if((0,Ho.checkDataType)(g.type,s,l.strictNumbers)),pf(t,g),e.length===1&&e[0]===g.type&&n&&(r.else(),(0,Ho.reportTypeError)(t)),r.endIf()):pf(t,g),i||r.if((0,x._)`${G.default.errors} === ${a||0}`))}}function pf(t,e){let{gen:n,schema:a,opts:{useDefaults:r}}=t;r&&(0,tv.assignDefaults)(t,e.type),n.block(()=>{for(let o of e.rules)(0,Xl.shouldUseRule)(a,o)&&wf(t,o.keyword,o.definition,e.type)})}function _v(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(gv(t,e),t.opts.allowUnionTypes||yv(t,e),Ev(t,t.dataTypes))}function gv(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(n=>{bf(t.dataTypes,n)||Ql(t,`type "${n}" not allowed by context "${t.dataTypes.join(",")}"`)}),bv(t,e)}}function yv(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Ql(t,"use allowUnionTypes to allow union type keyword")}function Ev(t,e){let n=t.self.RULES.all;for(let a in n){let r=n[a];if(typeof r=="object"&&(0,Xl.shouldUseRule)(t.schema,r)){let{type:o}=r.definition;o.length&&!o.some(s=>Tv(e,s))&&Ql(t,`missing type "${o.join(",")}" for keyword "${a}"`)}}}function Tv(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function bf(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function bv(t,e){let n=[];for(let a of t.dataTypes)bf(e,a)?n.push(a):e.includes("integer")&&a==="number"&&n.push("integer");t.dataTypes=n}function Ql(t,e){let n=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${n}" (strictTypes)`,(0,Dt.checkStrictMode)(t,e,t.opts.strictTypes)}var Yo=class{constructor(e,n,a){if((0,ur.validateKeywordUsage)(e,n,a),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=a,this.data=e.data,this.schema=e.schema[a],this.$data=n.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Dt.schemaRefOrVal)(e,this.schema,a,this.$data),this.schemaType=n.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=n,this.$data)this.schemaCode=e.gen.const("vSchema",Af(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,ur.validSchemaType)(this.schema,n.schemaType,n.allowUndefined))throw new Error(`${a} value must be ${JSON.stringify(n.schemaType)}`);("code"in n?n.trackErrors:n.errors!==!1)&&(this.errsCount=e.gen.const("_errs",G.default.errors))}result(e,n,a){this.failResult((0,x.not)(e),n,a)}failResult(e,n,a){this.gen.if(e),a?a():this.error(),n?(this.gen.else(),n(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,n){this.failResult((0,x.not)(e),void 0,n)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:n}=this;this.fail((0,x._)`${n} !== undefined && (${(0,x.or)(this.invalid$data(),e)})`)}error(e,n,a){if(n){this.setParams(n),this._error(e,a),this.setParams({});return}this._error(e,a)}_error(e,n){(e?dr.reportExtraError:dr.reportError)(this,this.def.error,n)}$dataError(){(0,dr.reportError)(this,this.def.$dataError||dr.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,dr.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,n){n?Object.assign(this.params,e):this.params=e}block$data(e,n,a=x.nil){this.gen.block(()=>{this.check$data(e,a),n()})}check$data(e=x.nil,n=x.nil){if(!this.$data)return;let{gen:a,schemaCode:r,schemaType:o,def:s}=this;a.if((0,x.or)((0,x._)`${r} === undefined`,n)),e!==x.nil&&a.assign(e,!0),(o.length||s.validateSchema)&&(a.elseIf(this.invalid$data()),this.$dataError(),e!==x.nil&&a.assign(e,!1)),a.else()}invalid$data(){let{gen:e,schemaCode:n,schemaType:a,def:r,it:o}=this;return(0,x.or)(s(),i());function s(){if(a.length){if(!(n instanceof x.Name))throw new Error("ajv implementation error");let l=Array.isArray(a)?a:[a];return(0,x._)`${(0,Ho.checkDataTypes)(l,n,o.opts.strictNumbers,Ho.DataType.Wrong)}`}return x.nil}function i(){if(r.validateSchema){let l=e.scopeValue("validate$data",{ref:r.validateSchema});return(0,x._)`!${l}(${n})`}return x.nil}}subschema(e,n){let a=(0,Jl.getSubschema)(this.it,e);(0,Jl.extendSubschemaData)(a,this.it,e),(0,Jl.extendSubschemaMode)(a,e);let r={...this.it,...a,items:void 0,props:void 0};return cv(r,n),r}mergeEvaluated(e,n){let{it:a,gen:r}=this;a.opts.unevaluated&&(a.props!==!0&&e.props!==void 0&&(a.props=Dt.mergeEvaluated.props(r,e.props,a.props,n)),a.items!==!0&&e.items!==void 0&&(a.items=Dt.mergeEvaluated.items(r,e.items,a.items,n)))}mergeValidEvaluated(e,n){let{it:a,gen:r}=this;if(a.opts.unevaluated&&(a.props!==!0||a.items!==!0))return r.if(n,()=>this.mergeEvaluated(e,x.Name)),!0}};Yt.KeywordCxt=Yo;function wf(t,e,n,a){let r=new Yo(t,n,e);"code"in n?n.code(r,a):r.$data&&n.validate?(0,ur.funcKeywordCode)(r,n):"macro"in n?(0,ur.macroKeywordCode)(r,n):(n.compile||n.validate)&&(0,ur.funcKeywordCode)(r,n)}var wv=/^\/(?:[^~]|~0|~1)*$/,Av=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Af(t,{dataLevel:e,dataNames:n,dataPathArr:a}){let r,o;if(t==="")return G.default.rootData;if(t[0]==="/"){if(!wv.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);r=t,o=G.default.rootData}else{let d=Av.exec(t);if(!d)throw new Error(`Invalid JSON-pointer: ${t}`);let h=+d[1];if(r=d[2],r==="#"){if(h>=e)throw new Error(l("property/index",h));return a[e-h]}if(h>e)throw new Error(l("data",h));if(o=n[e-h],!r)return o}let s=o,i=r.split("/");for(let d of i)d&&(o=(0,x._)`${o}${(0,x.getProperty)((0,Dt.unescapeJsonPointer)(d))}`,s=(0,x._)`${s} && ${o}`);return s;function l(d,h){return`Cannot access ${d} ${h} levels up, current level is ${e}`}}Yt.getData=Af});var Ko=N(td=>{"use strict";u();Object.defineProperty(td,"__esModule",{value:!0});var ed=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};td.default=ed});var pr=N(rd=>{"use strict";u();Object.defineProperty(rd,"__esModule",{value:!0});var nd=lr(),ad=class extends Error{constructor(e,n,a,r){super(r||`can't resolve reference ${a} from id ${n}`),this.missingRef=(0,nd.resolveUrl)(e,n,a),this.missingSchema=(0,nd.normalizeId)((0,nd.getFullPath)(e,this.missingRef))}};rd.default=ad});var Xo=N(at=>{"use strict";u();Object.defineProperty(at,"__esModule",{value:!0});at.resolveSchema=at.getCompilingSchema=at.resolveRef=at.compileSchema=at.SchemaEnv=void 0;var dt=q(),Iv=Ko(),Cn=Ct(),ut=lr(),If=Q(),vv=hr(),ua=class{constructor(e){var n;this.refs={},this.dynamicAnchors={};let a;typeof e.schema=="object"&&(a=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(n=e.baseId)!==null&&n!==void 0?n:(0,ut.normalizeId)(a?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=a?.$async,this.refs={}}};at.SchemaEnv=ua;function sd(t){let e=vf.call(this,t);if(e)return e;let n=(0,ut.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:a,lines:r}=this.opts.code,{ownProperties:o}=this.opts,s=new dt.CodeGen(this.scope,{es5:a,lines:r,ownProperties:o}),i;t.$async&&(i=s.scopeValue("Error",{ref:Iv.default,code:(0,dt._)`require("ajv/dist/runtime/validation_error").default`}));let l=s.scopeName("validate");t.validateName=l;let d={gen:s,allErrors:this.opts.allErrors,data:Cn.default.data,parentData:Cn.default.parentData,parentDataProperty:Cn.default.parentDataProperty,dataNames:[Cn.default.data],dataPathArr:[dt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,dt.stringify)(t.schema)}:{ref:t.schema}),validateName:l,ValidationError:i,schema:t.schema,schemaEnv:t,rootId:n,baseId:t.baseId||n,schemaPath:dt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,dt._)`""`,opts:this.opts,self:this},h;try{this._compilations.add(t),(0,vv.validateFunctionCode)(d),s.optimize(this.opts.code.optimize);let p=s.toString();h=`${s.scopeRefs(Cn.default.scope)}return ${p}`,this.opts.code.process&&(h=this.opts.code.process(h,t));let f=new Function(`${Cn.default.self}`,`${Cn.default.scope}`,h)(this,this.scope.get());if(this.scope.value(l,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:l,validateCode:p,scopeValues:s._values}),this.opts.unevaluated){let{props:m,items:y}=d;f.evaluated={props:m instanceof dt.Name?void 0:m,items:y instanceof dt.Name?void 0:y,dynamicProps:m instanceof dt.Name,dynamicItems:y instanceof dt.Name},f.source&&(f.source.evaluated=(0,dt.stringify)(f.evaluated))}return t.validate=f,t}catch(p){throw delete t.validate,delete t.validateName,h&&this.logger.error("Error compiling schema, function code:",h),p}finally{this._compilations.delete(t)}}at.compileSchema=sd;function Ov(t,e,n){var a;n=(0,ut.resolveUrl)(this.opts.uriResolver,e,n);let r=t.refs[n];if(r)return r;let o=Pv.call(this,t,n);if(o===void 0){let s=(a=t.localRefs)===null||a===void 0?void 0:a[n],{schemaId:i}=this.opts;s&&(o=new ua({schema:s,schemaId:i,root:t,baseId:e}))}if(o!==void 0)return t.refs[n]=Sv.call(this,o)}at.resolveRef=Ov;function Sv(t){return(0,ut.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:sd.call(this,t)}function vf(t){for(let e of this._compilations)if(Nv(e,t))return e}at.getCompilingSchema=vf;function Nv(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function Pv(t,e){let n;for(;typeof(n=this.refs[e])=="string";)e=n;return n||this.schemas[e]||Jo.call(this,t,e)}function Jo(t,e){let n=this.opts.uriResolver.parse(e),a=(0,ut._getFullPath)(this.opts.uriResolver,n),r=(0,ut.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&a===r)return od.call(this,n,t);let o=(0,ut.normalizeId)(a),s=this.refs[o]||this.schemas[o];if(typeof s=="string"){let i=Jo.call(this,t,s);return typeof i?.schema!="object"?void 0:od.call(this,n,i)}if(typeof s?.schema=="object"){if(s.validate||sd.call(this,s),o===(0,ut.normalizeId)(e)){let{schema:i}=s,{schemaId:l}=this.opts,d=i[l];return d&&(r=(0,ut.resolveUrl)(this.opts.uriResolver,r,d)),new ua({schema:i,schemaId:l,root:t,baseId:r})}return od.call(this,n,s)}}at.resolveSchema=Jo;var Cv=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function od(t,{baseId:e,schema:n,root:a}){var r;if(((r=t.fragment)===null||r===void 0?void 0:r[0])!=="/")return;for(let i of t.fragment.slice(1).split("/")){if(typeof n=="boolean")return;let l=n[(0,If.unescapeFragment)(i)];if(l===void 0)return;n=l;let d=typeof n=="object"&&n[this.opts.schemaId];!Cv.has(i)&&d&&(e=(0,ut.resolveUrl)(this.opts.uriResolver,e,d))}let o;if(typeof n!="boolean"&&n.$ref&&!(0,If.schemaHasRulesButRef)(n,this.RULES)){let i=(0,ut.resolveUrl)(this.opts.uriResolver,e,n.$ref);o=Jo.call(this,a,i)}let{schemaId:s}=this.opts;if(o=o||new ua({schema:n,schemaId:s,root:a,baseId:e}),o.schema!==o.root.schema)return o}});var Of=N((v$,Dv)=>{Dv.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 ld=N((O$,Rf)=>{"use strict";u();var Rv=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Nf=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),id=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Pf=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),Lv=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function cd(t){let e="",n=0,a=0;for(a=0;a<t.length;a++)if(n=t[a].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[a];break}for(a+=1;a<t.length;a++){if(n=t[a].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[a]}return e}var kv=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Sf(t){return t.length=0,!0}function xv(t,e,n){if(t.length){let a=cd(t);if(a!=="")e.push(a);else return n.error=!0,!1;t.length=0}return!0}function $v(t){let e=0,n={error:!1,address:"",zone:""},a=[],r=[],o=!1,s=!1,i=xv;for(let l=0;l<t.length;l++){let d=t[l];if(!(d==="["||d==="]"))if(d===":"){if(o===!0&&(s=!0),!i(r,a,n))break;if(++e>7){n.error=!0;break}l>0&&t[l-1]===":"&&(o=!0),a.push(":");continue}else if(d==="%"){if(!i(r,a,n))break;i=Sf}else{r.push(d);continue}}return r.length&&(i===Sf?n.zone=r.join(""):s?a.push(r.join("")):a.push(cd(r))),n.address=a.join(""),n}function Cf(t){if(Uv(t,":")<2)return{host:t,isIPV6:!1};let e=$v(t);if(e.error)return{host:t,isIPV6:!1};{let n=e.address,a=e.address;return e.zone&&(n+="%"+e.zone,a+="%25"+e.zone),{host:n,isIPV6:!0,escapedHost:a}}}function Uv(t,e){let n=0;for(let a=0;a<t.length;a++)t[a]===e&&n++;return n}function Mv(t){let e=t,n=[],a=-1,r=0;for(;r=e.length;){if(r===1){if(e===".")break;if(e==="/"){n.push("/");break}else{n.push(e);break}}else if(r===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){n.push("/");break}}else if(r===3&&e==="/.."){n.length!==0&&n.pop(),n.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),n.length!==0&&n.pop();continue}}if((a=e.indexOf("/",1))===-1){n.push(e);break}else n.push(e.slice(0,a)),e=e.slice(a)}return n.join("")}var zv={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},Fv=/[@/?#:]/g,Gv=/[@/?#]/g;function Df(t,e){let n=e?Gv:Fv;return n.lastIndex=0,t.replace(n,a=>zv[a])}function jv(t,e=!1){if(t.indexOf("%")===-1)return t;let n="";for(let a=0;a<t.length;a++){if(t[a]==="%"&&a+2<t.length){let r=t.slice(a+1,a+3);if(id(r)){let o=r.toUpperCase(),s=String.fromCharCode(parseInt(o,16));e&&Pf(s)?n+=s:n+="%"+o,a+=2;continue}}n+=t[a]}return n}function Bv(t){let e="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let a=t.slice(n+1,n+3);if(id(a)){let r=a.toUpperCase(),o=String.fromCharCode(parseInt(r,16));o!=="."&&Pf(o)?e+=o:e+="%"+r,n+=2;continue}}Lv(t[n])?e+=t[n]:e+=escape(t[n])}return e}function Zv(t){let e="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let a=t.slice(n+1,n+3);if(id(a)){e+="%"+a.toUpperCase(),n+=2;continue}}e+=escape(t[n])}return e}function qv(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let n=unescape(t.host);if(!Nf(n)){let a=Cf(n);a.isIPV6===!0?n=`[${a.escapedHost}]`:n=Df(n,!1)}e.push(n)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}Rf.exports={nonSimpleDomain:kv,recomposeAuthority:qv,reescapeHostDelimiters:Df,normalizePercentEncoding:jv,normalizePathEncoding:Bv,escapePreservingEscapes:Zv,removeDotSegments:Mv,isIPv4:Nf,isUUID:Rv,normalizeIPv6:Cf,stringArrayToHexStripped:cd}});var Uf=N((N$,$f)=>{"use strict";u();var{isUUID:Vv}=ld(),Wv=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,Hv=["http","https","ws","wss","urn","urn:uuid"];function Yv(t){return Hv.indexOf(t)!==-1}function dd(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function Lf(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function kf(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function Kv(t){return t.secure=dd(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function Jv(t){if((t.port===(dd(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,n]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=n,t.resourceName=void 0}return t.fragment=void 0,t}function Xv(t,e){if(!t.path)return t.error="URN can not be parsed",t;let n=t.path.match(Wv);if(n){let a=e.scheme||t.scheme||"urn";t.nid=n[1].toLowerCase(),t.nss=n[2];let r=`${a}:${e.nid||t.nid}`,o=ud(r);t.path=void 0,o&&(t=o.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function Qv(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let n=e.scheme||t.scheme||"urn",a=t.nid.toLowerCase(),r=`${n}:${e.nid||a}`,o=ud(r);o&&(t=o.serialize(t,e));let s=t,i=t.nss;return s.path=`${a||e.nid}:${i}`,e.skipEscape=!0,s}function eO(t,e){let n=t;return n.uuid=n.nss,n.nss=void 0,!e.tolerant&&(!n.uuid||!Vv(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function tO(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var xf={scheme:"http",domainHost:!0,parse:Lf,serialize:kf},nO={scheme:"https",domainHost:xf.domainHost,parse:Lf,serialize:kf},Qo={scheme:"ws",domainHost:!0,parse:Kv,serialize:Jv},aO={scheme:"wss",domainHost:Qo.domainHost,parse:Qo.parse,serialize:Qo.serialize},rO={scheme:"urn",parse:Xv,serialize:Qv,skipNormalize:!0},oO={scheme:"urn:uuid",parse:eO,serialize:tO,skipNormalize:!0},es={http:xf,https:nO,ws:Qo,wss:aO,urn:rO,"urn:uuid":oO};Object.setPrototypeOf(es,null);function ud(t){return t&&(es[t]||es[t.toLowerCase()])||void 0}$f.exports={wsIsSecure:dd,SCHEMES:es,isValidSchemeName:Yv,getSchemeHandler:ud}});var Bf=N((C$,ts)=>{"use strict";u();var{normalizeIPv6:sO,removeDotSegments:mr,recomposeAuthority:iO,normalizePercentEncoding:cO,normalizePathEncoding:lO,escapePreservingEscapes:dO,reescapeHostDelimiters:uO,isIPv4:hO,nonSimpleDomain:pO}=ld(),{SCHEMES:mO,getSchemeHandler:zf}=Uf();function fO(t,e){return typeof t=="string"?t=TO(t,e):typeof t=="object"&&(t=ha(Dn(t,e),e)),t}function _O(t,e,n){let a=n?Object.assign({scheme:"null"},n):{scheme:"null"},r=Ff(ha(t,a),ha(e,a),a,!0);return a.skipEscape=!0,Dn(r,a)}function Ff(t,e,n,a){let r={};return a||(t=ha(Dn(t,n),n),e=ha(Dn(e,n),n)),n=n||{},!n.tolerant&&e.scheme?(r.scheme=e.scheme,r.userinfo=e.userinfo,r.host=e.host,r.port=e.port,r.path=mr(e.path||""),r.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(r.userinfo=e.userinfo,r.host=e.host,r.port=e.port,r.path=mr(e.path||""),r.query=e.query):(e.path?(e.path[0]==="/"?r.path=mr(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?r.path="/"+e.path:t.path?r.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:r.path=e.path,r.path=mr(r.path)),r.query=e.query):(r.path=t.path,e.query!==void 0?r.query=e.query:r.query=t.query),r.userinfo=t.userinfo,r.host=t.host,r.port=t.port),r.scheme=t.scheme),r.fragment=e.fragment,r}function gO(t,e,n){let a=Mf(t,n),r=Mf(e,n);return a!==void 0&&r!==void 0&&a.toLowerCase()===r.toLowerCase()}function Dn(t,e){let n={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},a=Object.assign({},e),r=[],o=zf(a.scheme||n.scheme);o&&o.serialize&&o.serialize(n,a),n.path!==void 0&&(a.skipEscape?n.path=cO(n.path):(n.path=dO(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),a.reference!=="suffix"&&n.scheme&&r.push(n.scheme,":");let s=iO(n);if(s!==void 0&&(a.reference!=="suffix"&&r.push("//"),r.push(s),n.path&&n.path[0]!=="/"&&r.push("/")),n.path!==void 0){let i=n.path;!a.absolutePath&&(!o||!o.absolutePath)&&(i=mr(i)),s===void 0&&i[0]==="/"&&i[1]==="/"&&(i="/%2F"+i.slice(2)),r.push(i)}return n.query!==void 0&&r.push("?",n.query),n.fragment!==void 0&&r.push("#",n.fragment),r.join("")}var yO=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function EO(t,e){if(e[2]!==void 0&&t.path&&t.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof t.port=="number"&&(t.port<0||t.port>65535))return"URI port is malformed."}function Gf(t,e){let n=Object.assign({},e),a={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},r=!1,o=!1;n.reference==="suffix"&&(n.scheme?t=n.scheme+":"+t:t="//"+t);let s=t.match(yO);if(s){a.scheme=s[1],a.userinfo=s[3],a.host=s[4],a.port=parseInt(s[5],10),a.path=s[6]||"",a.query=s[7],a.fragment=s[8],isNaN(a.port)&&(a.port=s[5]);let i=EO(a,s);if(i!==void 0&&(a.error=a.error||i,r=!0),a.host)if(hO(a.host)===!1){let h=sO(a.host);a.host=h.host.toLowerCase(),o=h.isIPV6}else o=!0;a.scheme===void 0&&a.userinfo===void 0&&a.host===void 0&&a.port===void 0&&a.query===void 0&&!a.path?a.reference="same-document":a.scheme===void 0?a.reference="relative":a.fragment===void 0?a.reference="absolute":a.reference="uri",n.reference&&n.reference!=="suffix"&&n.reference!==a.reference&&(a.error=a.error||"URI is not a "+n.reference+" reference.");let l=zf(n.scheme||a.scheme);if(!n.unicodeSupport&&(!l||!l.unicodeSupport)&&a.host&&(n.domainHost||l&&l.domainHost)&&o===!1&&pO(a.host))try{a.host=URL.domainToASCII(a.host.toLowerCase())}catch(d){a.error=a.error||"Host's domain name can not be converted to ASCII: "+d}if((!l||l&&!l.skipNormalize)&&(t.indexOf("%")!==-1&&(a.scheme!==void 0&&(a.scheme=unescape(a.scheme)),a.host!==void 0&&(a.host=uO(unescape(a.host),o))),a.path&&(a.path=lO(a.path)),a.fragment))try{a.fragment=encodeURI(decodeURIComponent(a.fragment))}catch{a.error=a.error||"URI malformed"}l&&l.parse&&l.parse(a,n)}else a.error=a.error||"URI can not be parsed.";return{parsed:a,malformedAuthorityOrPort:r}}function ha(t,e){return Gf(t,e).parsed}function TO(t,e){return jf(t,e).normalized}function jf(t,e){let{parsed:n,malformedAuthorityOrPort:a}=Gf(t,e);return{normalized:a?t:Dn(n,e),malformedAuthorityOrPort:a}}function Mf(t,e){if(typeof t=="string"){let{normalized:n,malformedAuthorityOrPort:a}=jf(t,e);return a?void 0:n}if(typeof t=="object")return Dn(t,e)}var hd={SCHEMES:mO,normalize:fO,resolve:_O,resolveComponent:Ff,equal:gO,serialize:Dn,parse:ha};ts.exports=hd;ts.exports.default=hd;ts.exports.fastUri=hd});var qf=N(pd=>{"use strict";u();Object.defineProperty(pd,"__esModule",{value:!0});var Zf=Bf();Zf.code='require("ajv/dist/runtime/uri").default';pd.default=Zf});var Qf=N(Se=>{"use strict";u();Object.defineProperty(Se,"__esModule",{value:!0});Se.CodeGen=Se.Name=Se.nil=Se.stringify=Se.str=Se._=Se.KeywordCxt=void 0;var bO=hr();Object.defineProperty(Se,"KeywordCxt",{enumerable:!0,get:function(){return bO.KeywordCxt}});var pa=q();Object.defineProperty(Se,"_",{enumerable:!0,get:function(){return pa._}});Object.defineProperty(Se,"str",{enumerable:!0,get:function(){return pa.str}});Object.defineProperty(Se,"stringify",{enumerable:!0,get:function(){return pa.stringify}});Object.defineProperty(Se,"nil",{enumerable:!0,get:function(){return pa.nil}});Object.defineProperty(Se,"Name",{enumerable:!0,get:function(){return pa.Name}});Object.defineProperty(Se,"CodeGen",{enumerable:!0,get:function(){return pa.CodeGen}});var wO=Ko(),Kf=pr(),AO=Gl(),fr=Xo(),IO=q(),_r=lr(),ns=cr(),fd=Q(),Vf=Of(),vO=qf(),Jf=(t,e)=>new RegExp(t,e);Jf.code="new RegExp";var OO=["removeAdditional","useDefaults","coerceTypes"],SO=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),NO={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."},PO={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Wf=200;function CO(t){var e,n,a,r,o,s,i,l,d,h,p,g,f,m,y,T,w,I,O,D,U,Le,Ye,Mn,Rs;let Aa=t.strict,Ls=(e=t.code)===null||e===void 0?void 0:e.optimize,Au=Ls===!0||Ls===void 0?1:Ls||0,Iu=(a=(n=t.code)===null||n===void 0?void 0:n.regExp)!==null&&a!==void 0?a:Jf,ry=(r=t.uriResolver)!==null&&r!==void 0?r:vO.default;return{strictSchema:(s=(o=t.strictSchema)!==null&&o!==void 0?o:Aa)!==null&&s!==void 0?s:!0,strictNumbers:(l=(i=t.strictNumbers)!==null&&i!==void 0?i:Aa)!==null&&l!==void 0?l:!0,strictTypes:(h=(d=t.strictTypes)!==null&&d!==void 0?d:Aa)!==null&&h!==void 0?h:"log",strictTuples:(g=(p=t.strictTuples)!==null&&p!==void 0?p:Aa)!==null&&g!==void 0?g:"log",strictRequired:(m=(f=t.strictRequired)!==null&&f!==void 0?f:Aa)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:Au,regExp:Iu}:{optimize:Au,regExp:Iu},loopRequired:(y=t.loopRequired)!==null&&y!==void 0?y:Wf,loopEnum:(T=t.loopEnum)!==null&&T!==void 0?T:Wf,meta:(w=t.meta)!==null&&w!==void 0?w:!0,messages:(I=t.messages)!==null&&I!==void 0?I:!0,inlineRefs:(O=t.inlineRefs)!==null&&O!==void 0?O:!0,schemaId:(D=t.schemaId)!==null&&D!==void 0?D:"$id",addUsedSchema:(U=t.addUsedSchema)!==null&&U!==void 0?U:!0,validateSchema:(Le=t.validateSchema)!==null&&Le!==void 0?Le:!0,validateFormats:(Ye=t.validateFormats)!==null&&Ye!==void 0?Ye:!0,unicodeRegExp:(Mn=t.unicodeRegExp)!==null&&Mn!==void 0?Mn:!0,int32range:(Rs=t.int32range)!==null&&Rs!==void 0?Rs:!0,uriResolver:ry}}var gr=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...CO(e)};let{es5:n,lines:a}=this.opts.code;this.scope=new IO.ValueScope({scope:{},prefixes:SO,es5:n,lines:a}),this.logger=$O(e.logger);let r=e.validateFormats;e.validateFormats=!1,this.RULES=(0,AO.getRules)(),Hf.call(this,NO,e,"NOT SUPPORTED"),Hf.call(this,PO,e,"DEPRECATED","warn"),this._metaOpts=kO.call(this),e.formats&&RO.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&LO.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),DO.call(this),e.validateFormats=r}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:n,schemaId:a}=this.opts,r=Vf;a==="id"&&(r={...Vf},r.id=r.$id,delete r.$id),n&&e&&this.addMetaSchema(r,r[a],!1)}defaultMeta(){let{meta:e,schemaId:n}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[n]||e:void 0}validate(e,n){let a;if(typeof e=="string"){if(a=this.getSchema(e),!a)throw new Error(`no schema with key or ref "${e}"`)}else a=this.compile(e);let r=a(n);return"$async"in a||(this.errors=a.errors),r}compile(e,n){let a=this._addSchema(e,n);return a.validate||this._compileSchemaEnv(a)}compileAsync(e,n){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:a}=this.opts;return r.call(this,e,n);async function r(h,p){await o.call(this,h.$schema);let g=this._addSchema(h,p);return g.validate||s.call(this,g)}async function o(h){h&&!this.getSchema(h)&&await r.call(this,{$ref:h},!0)}async function s(h){try{return this._compileSchemaEnv(h)}catch(p){if(!(p instanceof Kf.default))throw p;return i.call(this,p),await l.call(this,p.missingSchema),s.call(this,h)}}function i({missingSchema:h,missingRef:p}){if(this.refs[h])throw new Error(`AnySchema ${h} is loaded but ${p} cannot be resolved`)}async function l(h){let p=await d.call(this,h);this.refs[h]||await o.call(this,p.$schema),this.refs[h]||this.addSchema(p,h,n)}async function d(h){let p=this._loading[h];if(p)return p;try{return await(this._loading[h]=a(h))}finally{delete this._loading[h]}}}addSchema(e,n,a,r=this.opts.validateSchema){if(Array.isArray(e)){for(let s of e)this.addSchema(s,void 0,a,r);return this}let o;if(typeof e=="object"){let{schemaId:s}=this.opts;if(o=e[s],o!==void 0&&typeof o!="string")throw new Error(`schema ${s} must be string`)}return n=(0,_r.normalizeId)(n||o),this._checkUnique(n),this.schemas[n]=this._addSchema(e,a,n,r,!0),this}addMetaSchema(e,n,a=this.opts.validateSchema){return this.addSchema(e,n,!0,a),this}validateSchema(e,n){if(typeof e=="boolean")return!0;let a;if(a=e.$schema,a!==void 0&&typeof a!="string")throw new Error("$schema must be a string");if(a=a||this.opts.defaultMeta||this.defaultMeta(),!a)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let r=this.validate(a,e);if(!r&&n){let o="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(o);else throw new Error(o)}return r}getSchema(e){let n;for(;typeof(n=Yf.call(this,e))=="string";)e=n;if(n===void 0){let{schemaId:a}=this.opts,r=new fr.SchemaEnv({schema:{},schemaId:a});if(n=fr.resolveSchema.call(this,r,e),!n)return;this.refs[e]=n}return n.validate||this._compileSchemaEnv(n)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let n=Yf.call(this,e);return typeof n=="object"&&this._cache.delete(n.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let n=e;this._cache.delete(n);let a=e[this.opts.schemaId];return a&&(a=(0,_r.normalizeId)(a),delete this.schemas[a],delete this.refs[a]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let n of e)this.addKeyword(n);return this}addKeyword(e,n){let a;if(typeof e=="string")a=e,typeof n=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),n.keyword=a);else if(typeof e=="object"&&n===void 0){if(n=e,a=n.keyword,Array.isArray(a)&&!a.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(MO.call(this,a,n),!n)return(0,fd.eachItem)(a,o=>md.call(this,o)),this;FO.call(this,n);let r={...n,type:(0,ns.getJSONTypes)(n.type),schemaType:(0,ns.getJSONTypes)(n.schemaType)};return(0,fd.eachItem)(a,r.type.length===0?o=>md.call(this,o,r):o=>r.type.forEach(s=>md.call(this,o,r,s))),this}getKeyword(e){let n=this.RULES.all[e];return typeof n=="object"?n.definition:!!n}removeKeyword(e){let{RULES:n}=this;delete n.keywords[e],delete n.all[e];for(let a of n.rules){let r=a.rules.findIndex(o=>o.keyword===e);r>=0&&a.rules.splice(r,1)}return this}addFormat(e,n){return typeof n=="string"&&(n=new RegExp(n)),this.formats[e]=n,this}errorsText(e=this.errors,{separator:n=", ",dataVar:a="data"}={}){return!e||e.length===0?"No errors":e.map(r=>`${a}${r.instancePath} ${r.message}`).reduce((r,o)=>r+n+o)}$dataMetaSchema(e,n){let a=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let r of n){let o=r.split("/").slice(1),s=e;for(let i of o)s=s[i];for(let i in a){let l=a[i];if(typeof l!="object")continue;let{$data:d}=l.definition,h=s[i];d&&h&&(s[i]=Xf(h))}}return e}_removeAllSchemas(e,n){for(let a in e){let r=e[a];(!n||n.test(a))&&(typeof r=="string"?delete e[a]:r&&!r.meta&&(this._cache.delete(r.schema),delete e[a]))}}_addSchema(e,n,a,r=this.opts.validateSchema,o=this.opts.addUsedSchema){let s,{schemaId:i}=this.opts;if(typeof e=="object")s=e[i];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let l=this._cache.get(e);if(l!==void 0)return l;a=(0,_r.normalizeId)(s||a);let d=_r.getSchemaRefs.call(this,e,a);return l=new fr.SchemaEnv({schema:e,schemaId:i,meta:n,baseId:a,localRefs:d}),this._cache.set(l.schema,l),o&&!a.startsWith("#")&&(a&&this._checkUnique(a),this.refs[a]=l),r&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):fr.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let n=this.opts;this.opts=this._metaOpts;try{fr.compileSchema.call(this,e)}finally{this.opts=n}}};gr.ValidationError=wO.default;gr.MissingRefError=Kf.default;Se.default=gr;function Hf(t,e,n,a="error"){for(let r in t){let o=r;o in e&&this.logger[a](`${n}: option ${r}. ${t[o]}`)}}function Yf(t){return t=(0,_r.normalizeId)(t),this.schemas[t]||this.refs[t]}function DO(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function RO(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function LO(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let n=t[e];n.keyword||(n.keyword=e),this.addKeyword(n)}}function kO(){let t={...this.opts};for(let e of OO)delete t[e];return t}var xO={log(){},warn(){},error(){}};function $O(t){if(t===!1)return xO;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var UO=/^[a-z_$][a-z0-9_$:-]*$/i;function MO(t,e){let{RULES:n}=this;if((0,fd.eachItem)(t,a=>{if(n.keywords[a])throw new Error(`Keyword ${a} is already defined`);if(!UO.test(a))throw new Error(`Keyword ${a} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function md(t,e,n){var a;let r=e?.post;if(n&&r)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:o}=this,s=r?o.post:o.rules.find(({type:l})=>l===n);if(s||(s={type:n,rules:[]},o.rules.push(s)),o.keywords[t]=!0,!e)return;let i={keyword:t,definition:{...e,type:(0,ns.getJSONTypes)(e.type),schemaType:(0,ns.getJSONTypes)(e.schemaType)}};e.before?zO.call(this,s,i,e.before):s.rules.push(i),o.all[t]=i,(a=e.implements)===null||a===void 0||a.forEach(l=>this.addKeyword(l))}function zO(t,e,n){let a=t.rules.findIndex(r=>r.keyword===n);a>=0?t.rules.splice(a,0,e):(t.rules.push(e),this.logger.warn(`rule ${n} is not defined`))}function FO(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Xf(e)),t.validateSchema=this.compile(e,!0))}var GO={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Xf(t){return{anyOf:[t,GO]}}});var e_=N(_d=>{"use strict";u();Object.defineProperty(_d,"__esModule",{value:!0});var jO={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};_d.default=jO});var r_=N(Rn=>{"use strict";u();Object.defineProperty(Rn,"__esModule",{value:!0});Rn.callRef=Rn.getValidate=void 0;var BO=pr(),t_=nt(),qe=q(),ma=Ct(),n_=Xo(),as=Q(),ZO={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:n,it:a}=t,{baseId:r,schemaEnv:o,validateName:s,opts:i,self:l}=a,{root:d}=o;if((n==="#"||n==="#/")&&r===d.baseId)return p();let h=n_.resolveRef.call(l,d,r,n);if(h===void 0)throw new BO.default(a.opts.uriResolver,r,n);if(h instanceof n_.SchemaEnv)return g(h);return f(h);function p(){if(o===d)return rs(t,s,o,o.$async);let m=e.scopeValue("root",{ref:d});return rs(t,(0,qe._)`${m}.validate`,d,d.$async)}function g(m){let y=a_(t,m);rs(t,y,m,m.$async)}function f(m){let y=e.scopeValue("schema",i.code.source===!0?{ref:m,code:(0,qe.stringify)(m)}:{ref:m}),T=e.name("valid"),w=t.subschema({schema:m,dataTypes:[],schemaPath:qe.nil,topSchemaRef:y,errSchemaPath:n},T);t.mergeEvaluated(w),t.ok(T)}}};function a_(t,e){let{gen:n}=t;return e.validate?n.scopeValue("validate",{ref:e.validate}):(0,qe._)`${n.scopeValue("wrapper",{ref:e})}.validate`}Rn.getValidate=a_;function rs(t,e,n,a){let{gen:r,it:o}=t,{allErrors:s,schemaEnv:i,opts:l}=o,d=l.passContext?ma.default.this:qe.nil;a?h():p();function h(){if(!i.$async)throw new Error("async schema referenced by sync schema");let m=r.let("valid");r.try(()=>{r.code((0,qe._)`await ${(0,t_.callValidateCode)(t,e,d)}`),f(e),s||r.assign(m,!0)},y=>{r.if((0,qe._)`!(${y} instanceof ${o.ValidationError})`,()=>r.throw(y)),g(y),s||r.assign(m,!1)}),t.ok(m)}function p(){t.result((0,t_.callValidateCode)(t,e,d),()=>f(e),()=>g(e))}function g(m){let y=(0,qe._)`${m}.errors`;r.assign(ma.default.vErrors,(0,qe._)`${ma.default.vErrors} === null ? ${y} : ${ma.default.vErrors}.concat(${y})`),r.assign(ma.default.errors,(0,qe._)`${ma.default.vErrors}.length`)}function f(m){var y;if(!o.opts.unevaluated)return;let T=(y=n?.validate)===null||y===void 0?void 0:y.evaluated;if(o.props!==!0)if(T&&!T.dynamicProps)T.props!==void 0&&(o.props=as.mergeEvaluated.props(r,T.props,o.props));else{let w=r.var("props",(0,qe._)`${m}.evaluated.props`);o.props=as.mergeEvaluated.props(r,w,o.props,qe.Name)}if(o.items!==!0)if(T&&!T.dynamicItems)T.items!==void 0&&(o.items=as.mergeEvaluated.items(r,T.items,o.items));else{let w=r.var("items",(0,qe._)`${m}.evaluated.items`);o.items=as.mergeEvaluated.items(r,w,o.items,qe.Name)}}}Rn.callRef=rs;Rn.default=ZO});var o_=N(gd=>{"use strict";u();Object.defineProperty(gd,"__esModule",{value:!0});var qO=e_(),VO=r_(),WO=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",qO.default,VO.default];gd.default=WO});var s_=N(yd=>{"use strict";u();Object.defineProperty(yd,"__esModule",{value:!0});var os=q(),Kt=os.operators,ss={maximum:{okStr:"<=",ok:Kt.LTE,fail:Kt.GT},minimum:{okStr:">=",ok:Kt.GTE,fail:Kt.LT},exclusiveMaximum:{okStr:"<",ok:Kt.LT,fail:Kt.GTE},exclusiveMinimum:{okStr:">",ok:Kt.GT,fail:Kt.LTE}},HO={message:({keyword:t,schemaCode:e})=>(0,os.str)`must be ${ss[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,os._)`{comparison: ${ss[t].okStr}, limit: ${e}}`},YO={keyword:Object.keys(ss),type:"number",schemaType:"number",$data:!0,error:HO,code(t){let{keyword:e,data:n,schemaCode:a}=t;t.fail$data((0,os._)`${n} ${ss[e].fail} ${a} || isNaN(${n})`)}};yd.default=YO});var i_=N(Ed=>{"use strict";u();Object.defineProperty(Ed,"__esModule",{value:!0});var yr=q(),KO={message:({schemaCode:t})=>(0,yr.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,yr._)`{multipleOf: ${t}}`},JO={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:KO,code(t){let{gen:e,data:n,schemaCode:a,it:r}=t,o=r.opts.multipleOfPrecision,s=e.let("res"),i=o?(0,yr._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${o}`:(0,yr._)`${s} !== parseInt(${s})`;t.fail$data((0,yr._)`(${a} === 0 || (${s} = ${n}/${a}, ${i}))`)}};Ed.default=JO});var l_=N(Td=>{"use strict";u();Object.defineProperty(Td,"__esModule",{value:!0});function c_(t){let e=t.length,n=0,a=0,r;for(;a<e;)n++,r=t.charCodeAt(a++),r>=55296&&r<=56319&&a<e&&(r=t.charCodeAt(a),(r&64512)===56320&&a++);return n}Td.default=c_;c_.code='require("ajv/dist/runtime/ucs2length").default'});var d_=N(bd=>{"use strict";u();Object.defineProperty(bd,"__esModule",{value:!0});var Ln=q(),XO=Q(),QO=l_(),eS={message({keyword:t,schemaCode:e}){let n=t==="maxLength"?"more":"fewer";return(0,Ln.str)`must NOT have ${n} than ${e} characters`},params:({schemaCode:t})=>(0,Ln._)`{limit: ${t}}`},tS={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:eS,code(t){let{keyword:e,data:n,schemaCode:a,it:r}=t,o=e==="maxLength"?Ln.operators.GT:Ln.operators.LT,s=r.opts.unicode===!1?(0,Ln._)`${n}.length`:(0,Ln._)`${(0,XO.useFunc)(t.gen,QO.default)}(${n})`;t.fail$data((0,Ln._)`${s} ${o} ${a}`)}};bd.default=tS});var u_=N(wd=>{"use strict";u();Object.defineProperty(wd,"__esModule",{value:!0});var nS=nt(),aS=Q(),fa=q(),rS={message:({schemaCode:t})=>(0,fa.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,fa._)`{pattern: ${t}}`},oS={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:rS,code(t){let{gen:e,data:n,$data:a,schema:r,schemaCode:o,it:s}=t,i=s.opts.unicodeRegExp?"u":"";if(a){let{regExp:l}=s.opts.code,d=l.code==="new RegExp"?(0,fa._)`new RegExp`:(0,aS.useFunc)(e,l),h=e.let("valid");e.try(()=>e.assign(h,(0,fa._)`${d}(${o}, ${i}).test(${n})`),()=>e.assign(h,!1)),t.fail$data((0,fa._)`!${h}`)}else{let l=(0,nS.usePattern)(t,r);t.fail$data((0,fa._)`!${l}.test(${n})`)}}};wd.default=oS});var h_=N(Ad=>{"use strict";u();Object.defineProperty(Ad,"__esModule",{value:!0});var Er=q(),sS={message({keyword:t,schemaCode:e}){let n=t==="maxProperties"?"more":"fewer";return(0,Er.str)`must NOT have ${n} than ${e} properties`},params:({schemaCode:t})=>(0,Er._)`{limit: ${t}}`},iS={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:sS,code(t){let{keyword:e,data:n,schemaCode:a}=t,r=e==="maxProperties"?Er.operators.GT:Er.operators.LT;t.fail$data((0,Er._)`Object.keys(${n}).length ${r} ${a}`)}};Ad.default=iS});var p_=N(Id=>{"use strict";u();Object.defineProperty(Id,"__esModule",{value:!0});var Tr=nt(),br=q(),cS=Q(),lS={message:({params:{missingProperty:t}})=>(0,br.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,br._)`{missingProperty: ${t}}`},dS={keyword:"required",type:"object",schemaType:"array",$data:!0,error:lS,code(t){let{gen:e,schema:n,schemaCode:a,data:r,$data:o,it:s}=t,{opts:i}=s;if(!o&&n.length===0)return;let l=n.length>=i.loopRequired;if(s.allErrors?d():h(),i.strictRequired){let f=t.parentSchema.properties,{definedProperties:m}=t.it;for(let y of n)if(f?.[y]===void 0&&!m.has(y)){let T=s.schemaEnv.baseId+s.errSchemaPath,w=`required property "${y}" is not defined at "${T}" (strictRequired)`;(0,cS.checkStrictMode)(s,w,s.opts.strictRequired)}}function d(){if(l||o)t.block$data(br.nil,p);else for(let f of n)(0,Tr.checkReportMissingProp)(t,f)}function h(){let f=e.let("missing");if(l||o){let m=e.let("valid",!0);t.block$data(m,()=>g(f,m)),t.ok(m)}else e.if((0,Tr.checkMissingProp)(t,n,f)),(0,Tr.reportMissingProp)(t,f),e.else()}function p(){e.forOf("prop",a,f=>{t.setParams({missingProperty:f}),e.if((0,Tr.noPropertyInData)(e,r,f,i.ownProperties),()=>t.error())})}function g(f,m){t.setParams({missingProperty:f}),e.forOf(f,a,()=>{e.assign(m,(0,Tr.propertyInData)(e,r,f,i.ownProperties)),e.if((0,br.not)(m),()=>{t.error(),e.break()})},br.nil)}}};Id.default=dS});var m_=N(vd=>{"use strict";u();Object.defineProperty(vd,"__esModule",{value:!0});var wr=q(),uS={message({keyword:t,schemaCode:e}){let n=t==="maxItems"?"more":"fewer";return(0,wr.str)`must NOT have ${n} than ${e} items`},params:({schemaCode:t})=>(0,wr._)`{limit: ${t}}`},hS={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:uS,code(t){let{keyword:e,data:n,schemaCode:a}=t,r=e==="maxItems"?wr.operators.GT:wr.operators.LT;t.fail$data((0,wr._)`${n}.length ${r} ${a}`)}};vd.default=hS});var is=N(Od=>{"use strict";u();Object.defineProperty(Od,"__esModule",{value:!0});var f_=Yl();f_.code='require("ajv/dist/runtime/equal").default';Od.default=f_});var __=N(Nd=>{"use strict";u();Object.defineProperty(Nd,"__esModule",{value:!0});var Sd=cr(),Ne=q(),pS=Q(),mS=is(),fS={message:({params:{i:t,j:e}})=>(0,Ne.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Ne._)`{i: ${t}, j: ${e}}`},_S={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:fS,code(t){let{gen:e,data:n,$data:a,schema:r,parentSchema:o,schemaCode:s,it:i}=t;if(!a&&!r)return;let l=e.let("valid"),d=o.items?(0,Sd.getSchemaTypes)(o.items):[];t.block$data(l,h,(0,Ne._)`${s} === false`),t.ok(l);function h(){let m=e.let("i",(0,Ne._)`${n}.length`),y=e.let("j");t.setParams({i:m,j:y}),e.assign(l,!0),e.if((0,Ne._)`${m} > 1`,()=>(p()?g:f)(m,y))}function p(){return d.length>0&&!d.some(m=>m==="object"||m==="array")}function g(m,y){let T=e.name("item"),w=(0,Sd.checkDataTypes)(d,T,i.opts.strictNumbers,Sd.DataType.Wrong),I=e.const("indices",(0,Ne._)`{}`);e.for((0,Ne._)`;${m}--;`,()=>{e.let(T,(0,Ne._)`${n}[${m}]`),e.if(w,(0,Ne._)`continue`),d.length>1&&e.if((0,Ne._)`typeof ${T} == "string"`,(0,Ne._)`${T} += "_"`),e.if((0,Ne._)`typeof ${I}[${T}] == "number"`,()=>{e.assign(y,(0,Ne._)`${I}[${T}]`),t.error(),e.assign(l,!1).break()}).code((0,Ne._)`${I}[${T}] = ${m}`)})}function f(m,y){let T=(0,pS.useFunc)(e,mS.default),w=e.name("outer");e.label(w).for((0,Ne._)`;${m}--;`,()=>e.for((0,Ne._)`${y} = ${m}; ${y}--;`,()=>e.if((0,Ne._)`${T}(${n}[${m}], ${n}[${y}])`,()=>{t.error(),e.assign(l,!1).break(w)})))}}};Nd.default=_S});var g_=N(Cd=>{"use strict";u();Object.defineProperty(Cd,"__esModule",{value:!0});var Pd=q(),gS=Q(),yS=is(),ES={message:"must be equal to constant",params:({schemaCode:t})=>(0,Pd._)`{allowedValue: ${t}}`},TS={keyword:"const",$data:!0,error:ES,code(t){let{gen:e,data:n,$data:a,schemaCode:r,schema:o}=t;a||o&&typeof o=="object"?t.fail$data((0,Pd._)`!${(0,gS.useFunc)(e,yS.default)}(${n}, ${r})`):t.fail((0,Pd._)`${o} !== ${n}`)}};Cd.default=TS});var y_=N(Dd=>{"use strict";u();Object.defineProperty(Dd,"__esModule",{value:!0});var Ar=q(),bS=Q(),wS=is(),AS={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Ar._)`{allowedValues: ${t}}`},IS={keyword:"enum",schemaType:"array",$data:!0,error:AS,code(t){let{gen:e,data:n,$data:a,schema:r,schemaCode:o,it:s}=t;if(!a&&r.length===0)throw new Error("enum must have non-empty array");let i=r.length>=s.opts.loopEnum,l,d=()=>l??(l=(0,bS.useFunc)(e,wS.default)),h;if(i||a)h=e.let("valid"),t.block$data(h,p);else{if(!Array.isArray(r))throw new Error("ajv implementation error");let f=e.const("vSchema",o);h=(0,Ar.or)(...r.map((m,y)=>g(f,y)))}t.pass(h);function p(){e.assign(h,!1),e.forOf("v",o,f=>e.if((0,Ar._)`${d()}(${n}, ${f})`,()=>e.assign(h,!0).break()))}function g(f,m){let y=r[m];return typeof y=="object"&&y!==null?(0,Ar._)`${d()}(${n}, ${f}[${m}])`:(0,Ar._)`${n} === ${y}`}}};Dd.default=IS});var E_=N(Rd=>{"use strict";u();Object.defineProperty(Rd,"__esModule",{value:!0});var vS=s_(),OS=i_(),SS=d_(),NS=u_(),PS=h_(),CS=p_(),DS=m_(),RS=__(),LS=g_(),kS=y_(),xS=[vS.default,OS.default,SS.default,NS.default,PS.default,CS.default,DS.default,RS.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},LS.default,kS.default];Rd.default=xS});var kd=N(Ir=>{"use strict";u();Object.defineProperty(Ir,"__esModule",{value:!0});Ir.validateAdditionalItems=void 0;var kn=q(),Ld=Q(),$S={message:({params:{len:t}})=>(0,kn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,kn._)`{limit: ${t}}`},US={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:$S,code(t){let{parentSchema:e,it:n}=t,{items:a}=e;if(!Array.isArray(a)){(0,Ld.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}T_(t,a)}};function T_(t,e){let{gen:n,schema:a,data:r,keyword:o,it:s}=t;s.items=!0;let i=n.const("len",(0,kn._)`${r}.length`);if(a===!1)t.setParams({len:e.length}),t.pass((0,kn._)`${i} <= ${e.length}`);else if(typeof a=="object"&&!(0,Ld.alwaysValidSchema)(s,a)){let d=n.var("valid",(0,kn._)`${i} <= ${e.length}`);n.if((0,kn.not)(d),()=>l(d)),t.ok(d)}function l(d){n.forRange("i",e.length,i,h=>{t.subschema({keyword:o,dataProp:h,dataPropType:Ld.Type.Num},d),s.allErrors||n.if((0,kn.not)(d),()=>n.break())})}}Ir.validateAdditionalItems=T_;Ir.default=US});var xd=N(vr=>{"use strict";u();Object.defineProperty(vr,"__esModule",{value:!0});vr.validateTuple=void 0;var b_=q(),cs=Q(),MS=nt(),zS={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:n}=t;if(Array.isArray(e))return w_(t,"additionalItems",e);n.items=!0,!(0,cs.alwaysValidSchema)(n,e)&&t.ok((0,MS.validateArray)(t))}};function w_(t,e,n=t.schema){let{gen:a,parentSchema:r,data:o,keyword:s,it:i}=t;h(r),i.opts.unevaluated&&n.length&&i.items!==!0&&(i.items=cs.mergeEvaluated.items(a,n.length,i.items));let l=a.name("valid"),d=a.const("len",(0,b_._)`${o}.length`);n.forEach((p,g)=>{(0,cs.alwaysValidSchema)(i,p)||(a.if((0,b_._)`${d} > ${g}`,()=>t.subschema({keyword:s,schemaProp:g,dataProp:g},l)),t.ok(l))});function h(p){let{opts:g,errSchemaPath:f}=i,m=n.length,y=m===p.minItems&&(m===p.maxItems||p[e]===!1);if(g.strictTuples&&!y){let T=`"${s}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,cs.checkStrictMode)(i,T,g.strictTuples)}}}vr.validateTuple=w_;vr.default=zS});var A_=N($d=>{"use strict";u();Object.defineProperty($d,"__esModule",{value:!0});var FS=xd(),GS={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,FS.validateTuple)(t,"items")};$d.default=GS});var v_=N(Ud=>{"use strict";u();Object.defineProperty(Ud,"__esModule",{value:!0});var I_=q(),jS=Q(),BS=nt(),ZS=kd(),qS={message:({params:{len:t}})=>(0,I_.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,I_._)`{limit: ${t}}`},VS={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:qS,code(t){let{schema:e,parentSchema:n,it:a}=t,{prefixItems:r}=n;a.items=!0,!(0,jS.alwaysValidSchema)(a,e)&&(r?(0,ZS.validateAdditionalItems)(t,r):t.ok((0,BS.validateArray)(t)))}};Ud.default=VS});var O_=N(Md=>{"use strict";u();Object.defineProperty(Md,"__esModule",{value:!0});var rt=q(),ls=Q(),WS={message:({params:{min:t,max:e}})=>e===void 0?(0,rt.str)`must contain at least ${t} valid item(s)`:(0,rt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,rt._)`{minContains: ${t}}`:(0,rt._)`{minContains: ${t}, maxContains: ${e}}`},HS={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:WS,code(t){let{gen:e,schema:n,parentSchema:a,data:r,it:o}=t,s,i,{minContains:l,maxContains:d}=a;o.opts.next?(s=l===void 0?1:l,i=d):s=1;let h=e.const("len",(0,rt._)`${r}.length`);if(t.setParams({min:s,max:i}),i===void 0&&s===0){(0,ls.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(i!==void 0&&s>i){(0,ls.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,ls.alwaysValidSchema)(o,n)){let y=(0,rt._)`${h} >= ${s}`;i!==void 0&&(y=(0,rt._)`${y} && ${h} <= ${i}`),t.pass(y);return}o.items=!0;let p=e.name("valid");i===void 0&&s===1?f(p,()=>e.if(p,()=>e.break())):s===0?(e.let(p,!0),i!==void 0&&e.if((0,rt._)`${r}.length > 0`,g)):(e.let(p,!1),g()),t.result(p,()=>t.reset());function g(){let y=e.name("_valid"),T=e.let("count",0);f(y,()=>e.if(y,()=>m(T)))}function f(y,T){e.forRange("i",0,h,w=>{t.subschema({keyword:"contains",dataProp:w,dataPropType:ls.Type.Num,compositeRule:!0},y),T()})}function m(y){e.code((0,rt._)`${y}++`),i===void 0?e.if((0,rt._)`${y} >= ${s}`,()=>e.assign(p,!0).break()):(e.if((0,rt._)`${y} > ${i}`,()=>e.assign(p,!1).break()),s===1?e.assign(p,!0):e.if((0,rt._)`${y} >= ${s}`,()=>e.assign(p,!0)))}}};Md.default=HS});var P_=N(Tt=>{"use strict";u();Object.defineProperty(Tt,"__esModule",{value:!0});Tt.validateSchemaDeps=Tt.validatePropertyDeps=Tt.error=void 0;var zd=q(),YS=Q(),Or=nt();Tt.error={message:({params:{property:t,depsCount:e,deps:n}})=>{let a=e===1?"property":"properties";return(0,zd.str)`must have ${a} ${n} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:n,missingProperty:a}})=>(0,zd._)`{property: ${t},
|
|
8
|
+
missingProperty: ${a},
|
|
9
|
+
depsCount: ${e},
|
|
10
|
+
deps: ${n}}`};var KS={keyword:"dependencies",type:"object",schemaType:"object",error:Tt.error,code(t){let[e,n]=JS(t);S_(t,e),N_(t,n)}};function JS({schema:t}){let e={},n={};for(let a in t){if(a==="__proto__")continue;let r=Array.isArray(t[a])?e:n;r[a]=t[a]}return[e,n]}function S_(t,e=t.schema){let{gen:n,data:a,it:r}=t;if(Object.keys(e).length===0)return;let o=n.let("missing");for(let s in e){let i=e[s];if(i.length===0)continue;let l=(0,Or.propertyInData)(n,a,s,r.opts.ownProperties);t.setParams({property:s,depsCount:i.length,deps:i.join(", ")}),r.allErrors?n.if(l,()=>{for(let d of i)(0,Or.checkReportMissingProp)(t,d)}):(n.if((0,zd._)`${l} && (${(0,Or.checkMissingProp)(t,i,o)})`),(0,Or.reportMissingProp)(t,o),n.else())}}Tt.validatePropertyDeps=S_;function N_(t,e=t.schema){let{gen:n,data:a,keyword:r,it:o}=t,s=n.name("valid");for(let i in e)(0,YS.alwaysValidSchema)(o,e[i])||(n.if((0,Or.propertyInData)(n,a,i,o.opts.ownProperties),()=>{let l=t.subschema({keyword:r,schemaProp:i},s);t.mergeValidEvaluated(l,s)},()=>n.var(s,!0)),t.ok(s))}Tt.validateSchemaDeps=N_;Tt.default=KS});var D_=N(Fd=>{"use strict";u();Object.defineProperty(Fd,"__esModule",{value:!0});var C_=q(),XS=Q(),QS={message:"property name must be valid",params:({params:t})=>(0,C_._)`{propertyName: ${t.propertyName}}`},eN={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:QS,code(t){let{gen:e,schema:n,data:a,it:r}=t;if((0,XS.alwaysValidSchema)(r,n))return;let o=e.name("valid");e.forIn("key",a,s=>{t.setParams({propertyName:s}),t.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},o),e.if((0,C_.not)(o),()=>{t.error(!0),r.allErrors||e.break()})}),t.ok(o)}};Fd.default=eN});var jd=N(Gd=>{"use strict";u();Object.defineProperty(Gd,"__esModule",{value:!0});var ds=nt(),ht=q(),tN=Ct(),us=Q(),nN={message:"must NOT have additional properties",params:({params:t})=>(0,ht._)`{additionalProperty: ${t.additionalProperty}}`},aN={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:nN,code(t){let{gen:e,schema:n,parentSchema:a,data:r,errsCount:o,it:s}=t;if(!o)throw new Error("ajv implementation error");let{allErrors:i,opts:l}=s;if(s.props=!0,l.removeAdditional!=="all"&&(0,us.alwaysValidSchema)(s,n))return;let d=(0,ds.allSchemaProperties)(a.properties),h=(0,ds.allSchemaProperties)(a.patternProperties);p(),t.ok((0,ht._)`${o} === ${tN.default.errors}`);function p(){e.forIn("key",r,T=>{!d.length&&!h.length?m(T):e.if(g(T),()=>m(T))})}function g(T){let w;if(d.length>8){let I=(0,us.schemaRefOrVal)(s,a.properties,"properties");w=(0,ds.isOwnProperty)(e,I,T)}else d.length?w=(0,ht.or)(...d.map(I=>(0,ht._)`${T} === ${I}`)):w=ht.nil;return h.length&&(w=(0,ht.or)(w,...h.map(I=>(0,ht._)`${(0,ds.usePattern)(t,I)}.test(${T})`))),(0,ht.not)(w)}function f(T){e.code((0,ht._)`delete ${r}[${T}]`)}function m(T){if(l.removeAdditional==="all"||l.removeAdditional&&n===!1){f(T);return}if(n===!1){t.setParams({additionalProperty:T}),t.error(),i||e.break();return}if(typeof n=="object"&&!(0,us.alwaysValidSchema)(s,n)){let w=e.name("valid");l.removeAdditional==="failing"?(y(T,w,!1),e.if((0,ht.not)(w),()=>{t.reset(),f(T)})):(y(T,w),i||e.if((0,ht.not)(w),()=>e.break()))}}function y(T,w,I){let O={keyword:"additionalProperties",dataProp:T,dataPropType:us.Type.Str};I===!1&&Object.assign(O,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(O,w)}}};Gd.default=aN});var k_=N(Zd=>{"use strict";u();Object.defineProperty(Zd,"__esModule",{value:!0});var rN=hr(),R_=nt(),Bd=Q(),L_=jd(),oN={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,parentSchema:a,data:r,it:o}=t;o.opts.removeAdditional==="all"&&a.additionalProperties===void 0&&L_.default.code(new rN.KeywordCxt(o,L_.default,"additionalProperties"));let s=(0,R_.allSchemaProperties)(n);for(let p of s)o.definedProperties.add(p);o.opts.unevaluated&&s.length&&o.props!==!0&&(o.props=Bd.mergeEvaluated.props(e,(0,Bd.toHash)(s),o.props));let i=s.filter(p=>!(0,Bd.alwaysValidSchema)(o,n[p]));if(i.length===0)return;let l=e.name("valid");for(let p of i)d(p)?h(p):(e.if((0,R_.propertyInData)(e,r,p,o.opts.ownProperties)),h(p),o.allErrors||e.else().var(l,!0),e.endIf()),t.it.definedProperties.add(p),t.ok(l);function d(p){return o.opts.useDefaults&&!o.compositeRule&&n[p].default!==void 0}function h(p){t.subschema({keyword:"properties",schemaProp:p,dataProp:p},l)}}};Zd.default=oN});var M_=N(qd=>{"use strict";u();Object.defineProperty(qd,"__esModule",{value:!0});var x_=nt(),hs=q(),$_=Q(),U_=Q(),sN={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,data:a,parentSchema:r,it:o}=t,{opts:s}=o,i=(0,x_.allSchemaProperties)(n),l=i.filter(y=>(0,$_.alwaysValidSchema)(o,n[y]));if(i.length===0||l.length===i.length&&(!o.opts.unevaluated||o.props===!0))return;let d=s.strictSchema&&!s.allowMatchingProperties&&r.properties,h=e.name("valid");o.props!==!0&&!(o.props instanceof hs.Name)&&(o.props=(0,U_.evaluatedPropsToName)(e,o.props));let{props:p}=o;g();function g(){for(let y of i)d&&f(y),o.allErrors?m(y):(e.var(h,!0),m(y),e.if(h))}function f(y){for(let T in d)new RegExp(y).test(T)&&(0,$_.checkStrictMode)(o,`property ${T} matches pattern ${y} (use allowMatchingProperties)`)}function m(y){e.forIn("key",a,T=>{e.if((0,hs._)`${(0,x_.usePattern)(t,y)}.test(${T})`,()=>{let w=l.includes(y);w||t.subschema({keyword:"patternProperties",schemaProp:y,dataProp:T,dataPropType:U_.Type.Str},h),o.opts.unevaluated&&p!==!0?e.assign((0,hs._)`${p}[${T}]`,!0):!w&&!o.allErrors&&e.if((0,hs.not)(h),()=>e.break())})})}}};qd.default=sN});var z_=N(Vd=>{"use strict";u();Object.defineProperty(Vd,"__esModule",{value:!0});var iN=Q(),cN={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:n,it:a}=t;if((0,iN.alwaysValidSchema)(a,n)){t.fail();return}let r=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},r),t.failResult(r,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Vd.default=cN});var F_=N(Wd=>{"use strict";u();Object.defineProperty(Wd,"__esModule",{value:!0});var lN=nt(),dN={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:lN.validateUnion,error:{message:"must match a schema in anyOf"}};Wd.default=dN});var G_=N(Hd=>{"use strict";u();Object.defineProperty(Hd,"__esModule",{value:!0});var ps=q(),uN=Q(),hN={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,ps._)`{passingSchemas: ${t.passing}}`},pN={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:hN,code(t){let{gen:e,schema:n,parentSchema:a,it:r}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(r.opts.discriminator&&a.discriminator)return;let o=n,s=e.let("valid",!1),i=e.let("passing",null),l=e.name("_valid");t.setParams({passing:i}),e.block(d),t.result(s,()=>t.reset(),()=>t.error(!0));function d(){o.forEach((h,p)=>{let g;(0,uN.alwaysValidSchema)(r,h)?e.var(l,!0):g=t.subschema({keyword:"oneOf",schemaProp:p,compositeRule:!0},l),p>0&&e.if((0,ps._)`${l} && ${s}`).assign(s,!1).assign(i,(0,ps._)`[${i}, ${p}]`).else(),e.if(l,()=>{e.assign(s,!0),e.assign(i,p),g&&t.mergeEvaluated(g,ps.Name)})})}}};Hd.default=pN});var j_=N(Yd=>{"use strict";u();Object.defineProperty(Yd,"__esModule",{value:!0});var mN=Q(),fN={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:n,it:a}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");let r=e.name("valid");n.forEach((o,s)=>{if((0,mN.alwaysValidSchema)(a,o))return;let i=t.subschema({keyword:"allOf",schemaProp:s},r);t.ok(r),t.mergeEvaluated(i)})}};Yd.default=fN});var q_=N(Kd=>{"use strict";u();Object.defineProperty(Kd,"__esModule",{value:!0});var ms=q(),Z_=Q(),_N={message:({params:t})=>(0,ms.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,ms._)`{failingKeyword: ${t.ifClause}}`},gN={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:_N,code(t){let{gen:e,parentSchema:n,it:a}=t;n.then===void 0&&n.else===void 0&&(0,Z_.checkStrictMode)(a,'"if" without "then" and "else" is ignored');let r=B_(a,"then"),o=B_(a,"else");if(!r&&!o)return;let s=e.let("valid",!0),i=e.name("_valid");if(l(),t.reset(),r&&o){let h=e.let("ifClause");t.setParams({ifClause:h}),e.if(i,d("then",h),d("else",h))}else r?e.if(i,d("then")):e.if((0,ms.not)(i),d("else"));t.pass(s,()=>t.error(!0));function l(){let h=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},i);t.mergeEvaluated(h)}function d(h,p){return()=>{let g=t.subschema({keyword:h},i);e.assign(s,i),t.mergeValidEvaluated(g,s),p?e.assign(p,(0,ms._)`${h}`):t.setParams({ifClause:h})}}}};function B_(t,e){let n=t.schema[e];return n!==void 0&&!(0,Z_.alwaysValidSchema)(t,n)}Kd.default=gN});var V_=N(Jd=>{"use strict";u();Object.defineProperty(Jd,"__esModule",{value:!0});var yN=Q(),EN={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:n}){e.if===void 0&&(0,yN.checkStrictMode)(n,`"${t}" without "if" is ignored`)}};Jd.default=EN});var W_=N(Xd=>{"use strict";u();Object.defineProperty(Xd,"__esModule",{value:!0});var TN=kd(),bN=A_(),wN=xd(),AN=v_(),IN=O_(),vN=P_(),ON=D_(),SN=jd(),NN=k_(),PN=M_(),CN=z_(),DN=F_(),RN=G_(),LN=j_(),kN=q_(),xN=V_();function $N(t=!1){let e=[CN.default,DN.default,RN.default,LN.default,kN.default,xN.default,ON.default,SN.default,vN.default,NN.default,PN.default];return t?e.push(bN.default,AN.default):e.push(TN.default,wN.default),e.push(IN.default),e}Xd.default=$N});var H_=N(Qd=>{"use strict";u();Object.defineProperty(Qd,"__esModule",{value:!0});var ge=q(),UN={message:({schemaCode:t})=>(0,ge.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,ge._)`{format: ${t}}`},MN={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:UN,code(t,e){let{gen:n,data:a,$data:r,schema:o,schemaCode:s,it:i}=t,{opts:l,errSchemaPath:d,schemaEnv:h,self:p}=i;if(!l.validateFormats)return;r?g():f();function g(){let m=n.scopeValue("formats",{ref:p.formats,code:l.code.formats}),y=n.const("fDef",(0,ge._)`${m}[${s}]`),T=n.let("fType"),w=n.let("format");n.if((0,ge._)`typeof ${y} == "object" && !(${y} instanceof RegExp)`,()=>n.assign(T,(0,ge._)`${y}.type || "string"`).assign(w,(0,ge._)`${y}.validate`),()=>n.assign(T,(0,ge._)`"string"`).assign(w,y)),t.fail$data((0,ge.or)(I(),O()));function I(){return l.strictSchema===!1?ge.nil:(0,ge._)`${s} && !${w}`}function O(){let D=h.$async?(0,ge._)`(${y}.async ? await ${w}(${a}) : ${w}(${a}))`:(0,ge._)`${w}(${a})`,U=(0,ge._)`(typeof ${w} == "function" ? ${D} : ${w}.test(${a}))`;return(0,ge._)`${w} && ${w} !== true && ${T} === ${e} && !${U}`}}function f(){let m=p.formats[o];if(!m){I();return}if(m===!0)return;let[y,T,w]=O(m);y===e&&t.pass(D());function I(){if(l.strictSchema===!1){p.logger.warn(U());return}throw new Error(U());function U(){return`unknown format "${o}" ignored in schema at path "${d}"`}}function O(U){let Le=U instanceof RegExp?(0,ge.regexpCode)(U):l.code.formats?(0,ge._)`${l.code.formats}${(0,ge.getProperty)(o)}`:void 0,Ye=n.scopeValue("formats",{key:o,ref:U,code:Le});return typeof U=="object"&&!(U instanceof RegExp)?[U.type||"string",U.validate,(0,ge._)`${Ye}.validate`]:["string",U,Ye]}function D(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!h.$async)throw new Error("async format in sync schema");return(0,ge._)`await ${w}(${a})`}return typeof T=="function"?(0,ge._)`${w}(${a})`:(0,ge._)`${w}.test(${a})`}}}};Qd.default=MN});var Y_=N(eu=>{"use strict";u();Object.defineProperty(eu,"__esModule",{value:!0});var zN=H_(),FN=[zN.default];eu.default=FN});var K_=N(_a=>{"use strict";u();Object.defineProperty(_a,"__esModule",{value:!0});_a.contentVocabulary=_a.metadataVocabulary=void 0;_a.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];_a.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var X_=N(tu=>{"use strict";u();Object.defineProperty(tu,"__esModule",{value:!0});var GN=o_(),jN=E_(),BN=W_(),ZN=Y_(),J_=K_(),qN=[GN.default,jN.default,(0,BN.default)(),ZN.default,J_.metadataVocabulary,J_.contentVocabulary];tu.default=qN});var eg=N(fs=>{"use strict";u();Object.defineProperty(fs,"__esModule",{value:!0});fs.DiscrError=void 0;var Q_;(function(t){t.Tag="tag",t.Mapping="mapping"})(Q_||(fs.DiscrError=Q_={}))});var ng=N(au=>{"use strict";u();Object.defineProperty(au,"__esModule",{value:!0});var ga=q(),nu=eg(),tg=Xo(),VN=pr(),WN=Q(),HN={message:({params:{discrError:t,tagName:e}})=>t===nu.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:n}})=>(0,ga._)`{error: ${t}, tag: ${n}, tagValue: ${e}}`},YN={keyword:"discriminator",type:"object",schemaType:"object",error:HN,code(t){let{gen:e,data:n,schema:a,parentSchema:r,it:o}=t,{oneOf:s}=r;if(!o.opts.discriminator)throw new Error("discriminator: requires discriminator option");let i=a.propertyName;if(typeof i!="string")throw new Error("discriminator: requires propertyName");if(a.mapping)throw new Error("discriminator: mapping is not supported");if(!s)throw new Error("discriminator: requires oneOf keyword");let l=e.let("valid",!1),d=e.const("tag",(0,ga._)`${n}${(0,ga.getProperty)(i)}`);e.if((0,ga._)`typeof ${d} == "string"`,()=>h(),()=>t.error(!1,{discrError:nu.DiscrError.Tag,tag:d,tagName:i})),t.ok(l);function h(){let f=g();e.if(!1);for(let m in f)e.elseIf((0,ga._)`${d} === ${m}`),e.assign(l,p(f[m]));e.else(),t.error(!1,{discrError:nu.DiscrError.Mapping,tag:d,tagName:i}),e.endIf()}function p(f){let m=e.name("valid"),y=t.subschema({keyword:"oneOf",schemaProp:f},m);return t.mergeEvaluated(y,ga.Name),m}function g(){var f;let m={},y=w(r),T=!0;for(let D=0;D<s.length;D++){let U=s[D];if(U?.$ref&&!(0,WN.schemaHasRulesButRef)(U,o.self.RULES)){let Ye=U.$ref;if(U=tg.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,Ye),U instanceof tg.SchemaEnv&&(U=U.schema),U===void 0)throw new VN.default(o.opts.uriResolver,o.baseId,Ye)}let Le=(f=U?.properties)===null||f===void 0?void 0:f[i];if(typeof Le!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${i}"`);T=T&&(y||w(U)),I(Le,D)}if(!T)throw new Error(`discriminator: "${i}" must be required`);return m;function w({required:D}){return Array.isArray(D)&&D.includes(i)}function I(D,U){if(D.const)O(D.const,U);else if(D.enum)for(let Le of D.enum)O(Le,U);else throw new Error(`discriminator: "properties/${i}" must have "const" or "enum"`)}function O(D,U){if(typeof D!="string"||D in m)throw new Error(`discriminator: "${i}" values must be unique strings`);m[D]=U}}}};au.default=YN});var ag=N((sM,KN)=>{KN.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var ou=N((ue,ru)=>{"use strict";u();Object.defineProperty(ue,"__esModule",{value:!0});ue.MissingRefError=ue.ValidationError=ue.CodeGen=ue.Name=ue.nil=ue.stringify=ue.str=ue._=ue.KeywordCxt=ue.Ajv=void 0;var JN=Qf(),XN=X_(),QN=ng(),rg=ag(),eP=["/properties"],_s="http://json-schema.org/draft-07/schema",ya=class extends JN.default{_addVocabularies(){super._addVocabularies(),XN.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(QN.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(rg,eP):rg;this.addMetaSchema(e,_s,!1),this.refs["http://json-schema.org/schema"]=_s}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(_s)?_s:void 0)}};ue.Ajv=ya;ru.exports=ue=ya;ru.exports.Ajv=ya;Object.defineProperty(ue,"__esModule",{value:!0});ue.default=ya;var tP=hr();Object.defineProperty(ue,"KeywordCxt",{enumerable:!0,get:function(){return tP.KeywordCxt}});var Ea=q();Object.defineProperty(ue,"_",{enumerable:!0,get:function(){return Ea._}});Object.defineProperty(ue,"str",{enumerable:!0,get:function(){return Ea.str}});Object.defineProperty(ue,"stringify",{enumerable:!0,get:function(){return Ea.stringify}});Object.defineProperty(ue,"nil",{enumerable:!0,get:function(){return Ea.nil}});Object.defineProperty(ue,"Name",{enumerable:!0,get:function(){return Ea.Name}});Object.defineProperty(ue,"CodeGen",{enumerable:!0,get:function(){return Ea.CodeGen}});var nP=Ko();Object.defineProperty(ue,"ValidationError",{enumerable:!0,get:function(){return nP.default}});var aP=pr();Object.defineProperty(ue,"MissingRefError",{enumerable:!0,get:function(){return aP.default}})});var hg=N(wt=>{"use strict";u();Object.defineProperty(wt,"__esModule",{value:!0});wt.formatNames=wt.fastFormats=wt.fullFormats=void 0;function bt(t,e){return{validate:t,compare:e}}wt.fullFormats={date:bt(cg,lu),time:bt(iu(!0),du),"date-time":bt(og(!0),dg),"iso-time":bt(iu(),lg),"iso-date-time":bt(og(),ug),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:lP,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:_P,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:dP,int32:{type:"number",validate:pP},int64:{type:"number",validate:mP},float:{type:"number",validate:ig},double:{type:"number",validate:ig},password:!0,binary:!0};wt.fastFormats={...wt.fullFormats,date:bt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,lu),time:bt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,du),"date-time":bt(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,dg),"iso-time":bt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,lg),"iso-date-time":bt(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,ug),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};wt.formatNames=Object.keys(wt.fullFormats);function rP(t){return t%4===0&&(t%100!==0||t%400===0)}var oP=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,sP=[0,31,28,31,30,31,30,31,31,30,31,30,31];function cg(t){let e=oP.exec(t);if(!e)return!1;let n=+e[1],a=+e[2],r=+e[3];return a>=1&&a<=12&&r>=1&&r<=(a===2&&rP(n)?29:sP[a])}function lu(t,e){if(t&&e)return t>e?1:t<e?-1:0}var su=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function iu(t){return function(n){let a=su.exec(n);if(!a)return!1;let r=+a[1],o=+a[2],s=+a[3],i=a[4],l=a[5]==="-"?-1:1,d=+(a[6]||0),h=+(a[7]||0);if(d>23||h>59||t&&!i)return!1;if(r<=23&&o<=59&&s<60)return!0;let p=o-h*l,g=r-d*l-(p<0?1:0);return(g===23||g===-1)&&(p===59||p===-1)&&s<61}}function du(t,e){if(!(t&&e))return;let n=new Date("2020-01-01T"+t).valueOf(),a=new Date("2020-01-01T"+e).valueOf();if(n&&a)return n-a}function lg(t,e){if(!(t&&e))return;let n=su.exec(t),a=su.exec(e);if(n&&a)return t=n[1]+n[2]+n[3],e=a[1]+a[2]+a[3],t>e?1:t<e?-1:0}var cu=/t|\s/i;function og(t){let e=iu(t);return function(a){let r=a.split(cu);return r.length===2&&cg(r[0])&&e(r[1])}}function dg(t,e){if(!(t&&e))return;let n=new Date(t).valueOf(),a=new Date(e).valueOf();if(n&&a)return n-a}function ug(t,e){if(!(t&&e))return;let[n,a]=t.split(cu),[r,o]=e.split(cu),s=lu(n,r);if(s!==void 0)return s||du(a,o)}var iP=/\/|:/,cP=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function lP(t){return iP.test(t)&&cP.test(t)}var sg=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function dP(t){return sg.lastIndex=0,sg.test(t)}var uP=-(2**31),hP=2**31-1;function pP(t){return Number.isInteger(t)&&t<=hP&&t>=uP}function mP(t){return Number.isInteger(t)}function ig(){return!0}var fP=/[^\\]\\Z/;function _P(t){if(fP.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var pg=N(Ta=>{"use strict";u();Object.defineProperty(Ta,"__esModule",{value:!0});Ta.formatLimitDefinition=void 0;var gP=ou(),pt=q(),Jt=pt.operators,gs={formatMaximum:{okStr:"<=",ok:Jt.LTE,fail:Jt.GT},formatMinimum:{okStr:">=",ok:Jt.GTE,fail:Jt.LT},formatExclusiveMaximum:{okStr:"<",ok:Jt.LT,fail:Jt.GTE},formatExclusiveMinimum:{okStr:">",ok:Jt.GT,fail:Jt.LTE}},yP={message:({keyword:t,schemaCode:e})=>(0,pt.str)`should be ${gs[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,pt._)`{comparison: ${gs[t].okStr}, limit: ${e}}`};Ta.formatLimitDefinition={keyword:Object.keys(gs),type:"string",schemaType:"string",$data:!0,error:yP,code(t){let{gen:e,data:n,schemaCode:a,keyword:r,it:o}=t,{opts:s,self:i}=o;if(!s.validateFormats)return;let l=new gP.KeywordCxt(o,i.RULES.all.format.definition,"format");l.$data?d():h();function d(){let g=e.scopeValue("formats",{ref:i.formats,code:s.code.formats}),f=e.const("fmt",(0,pt._)`${g}[${l.schemaCode}]`);t.fail$data((0,pt.or)((0,pt._)`typeof ${f} != "object"`,(0,pt._)`${f} instanceof RegExp`,(0,pt._)`typeof ${f}.compare != "function"`,p(f)))}function h(){let g=l.schema,f=i.formats[g];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${r}": format "${g}" does not define "compare" function`);let m=e.scopeValue("formats",{key:g,ref:f,code:s.code.formats?(0,pt._)`${s.code.formats}${(0,pt.getProperty)(g)}`:void 0});t.fail$data(p(m))}function p(g){return(0,pt._)`${g}.compare(${n}, ${a}) ${gs[r].fail} 0`}},dependencies:["format"]};var EP=t=>(t.addKeyword(Ta.formatLimitDefinition),t);Ta.default=EP});var gg=N((Sr,_g)=>{"use strict";u();Object.defineProperty(Sr,"__esModule",{value:!0});var ba=hg(),TP=pg(),uu=q(),mg=new uu.Name("fullFormats"),bP=new uu.Name("fastFormats"),hu=(t,e={keywords:!0})=>{if(Array.isArray(e))return fg(t,e,ba.fullFormats,mg),t;let[n,a]=e.mode==="fast"?[ba.fastFormats,bP]:[ba.fullFormats,mg],r=e.formats||ba.formatNames;return fg(t,r,n,a),e.keywords&&(0,TP.default)(t),t};hu.get=(t,e="full")=>{let a=(e==="fast"?ba.fastFormats:ba.fullFormats)[t];if(!a)throw new Error(`Unknown format "${t}"`);return a};function fg(t,e,n,a){var r,o;(r=(o=t.opts.code).formats)!==null&&r!==void 0||(o.formats=(0,uu._)`require("ajv-formats/dist/formats").${a}`);for(let s of e)t.addFormat(s,n[s])}_g.exports=Sr=hu;Object.defineProperty(Sr,"__esModule",{value:!0});Sr.default=hu});u();import{appendFileSync as oy,existsSync as kr,mkdirSync as sy,renameSync as Nu,statSync as xs,unlinkSync as $s}from"fs";import xr from"path";var Us=null;function sC(t){Us=t}var Ia={debug:0,info:1,notice:2,warning:3,error:4,critical:5,alert:6,emergency:7},iy=t=>t!==void 0&&["1","true","on","yes"].includes(t.trim().toLowerCase()),cy=()=>(process.env.MCP_LOG_LEVEL??"").trim().toLowerCase()==="verbose",ly=()=>cy()||iy(process.env.MCP_LOG_GQL),dy=()=>{if(ly())return Ia.debug;let t=process.env.MCP_LOG_LEVEL?.trim().toLowerCase();return t&&t in Ia?Ia[t]:Ia.info},uy=50*1024*1024,hy=5,Pu=1,py=6e4,Cu=(t,e)=>{let n=t?parseInt(t,10):NaN;return Number.isFinite(n)&&n>0?n:e},my=()=>{let t=process.env.MCP_LOG_MAX_AGE_DAYS;if(t===void 0)return Pu*864e5;let e=Number(t);return Number.isFinite(e)&&e>=0?e*864e5:Pu*864e5};function fy(){if(process.env.MCP_LOG_DIR)return xr.resolve(process.env.MCP_LOG_DIR);let t=process.env.WORKSPACE_ROOT||process.cwd();return xr.join(t,`.${Lr}`,"logs")}function _y(){return xr.join(fy(),`${Lr}.log`)}var Du=!1,Ms=0;function gy(t,e){try{let n=`${t}.${e}`;kr(n)&&$s(n);for(let a=e-1;a>=1;a--){let r=`${t}.${a}`;kr(r)&&Nu(r,`${t}.${a+1}`)}Nu(t,`${t}.1`)}catch{}}function yy(t,e){Ms=Date.now();let n=my();if(n<=0)return;let a=Ms-n;for(let r=1;r<=e;r++){let o=`${t}.${r}`;try{kr(o)&&xs(o).mtimeMs<a&&$s(o)}catch{}}try{kr(t)&&xs(t).mtimeMs<a&&$s(t)}catch{}}function Ey(t){let e=Cu(process.env.MCP_LOG_MAX_FILES,hy);Date.now()-Ms>=py&&yy(t,e);let n;try{n=xs(t).size}catch{return}n>=Cu(process.env.MCP_LOG_MAX_BYTES,uy)&&gy(t,e)}function Ty(t,e){if(!(Du||process.env.MCP_LOG_FILE==="off"))try{let n=_y();sy(xr.dirname(n),{recursive:!0}),Ey(n),oy(n,`${new Date().toISOString()} [${t.toUpperCase()}] ${e}
|
|
11
|
+
`)}catch{Du=!0}}function Lt(t,e,...n){if(Ia[t]<dy())return;let a=`[${Lr}] ${e} ${n.length>0?JSON.stringify(n):""}`;if(Ty(t,a),Us)try{Us.server.sendLoggingMessage({level:t,data:a}).catch(r=>{console.error(`[${t.toUpperCase()}] ${a}`)});return}catch{}console.error(`[${t.toUpperCase()}] ${a}`)}var iC={debug:(t,...e)=>Lt("debug",t,...e),info:(t,...e)=>Lt("info",t,...e),notice:(t,...e)=>Lt("notice",t,...e),warn:(t,...e)=>Lt("warning",t,...e),error:(t,...e)=>Lt("error",t,...e),critical:(t,...e)=>Lt("critical",t,...e)};u();var zs=Su,$r=null;function Fn(){if($r)return $r;let t=(process.env.ZION_ENV??process.env.MCP_ENV)?.trim().toLowerCase(),e=Ou;if(t){if(!zs[t])throw new Error(`Unknown environment "${t}". Known: ${Object.keys(zs).join(", ")}.`);e=t}let n=zs[e];return $r={name:e,authEndpoint:process.env.BACKEND_AUTH_ENDPOINT||n.authEndpoint,apiBaseUrl:process.env.BACKEND_API_BASE||n.apiBaseUrl,zeroApiUrlTemplate:process.env.ZERO_API_URL_TEMPLATE||n.zeroApiUrlTemplate,logApiUrlTemplate:process.env.LOG_API_URL_TEMPLATE||n.logApiUrlTemplate,editorBaseUrl:process.env.EDITOR_BASE_URL||n.editorBaseUrl},$r}var Ru=!1;function hC(){if(Ru)return;Ru=!0;let t=Fn();Lt("info",`Backend environment: ${t.name} (api=${t.apiBaseUrl})`)}u();u();u();u();var c={};ks(c,{BRAND:()=>Vy,DIRTY:()=>en,EMPTY_PATH:()=>Iy,INVALID:()=>M,NEVER:()=>PE,OK:()=>Pe,ParseStatus:()=>Ae,Schema:()=>Z,ZodAny:()=>$t,ZodArray:()=>Ot,ZodBigInt:()=>nn,ZodBoolean:()=>an,ZodBranded:()=>Oa,ZodCatch:()=>fn,ZodDate:()=>rn,ZodDefault:()=>mn,ZodDiscriminatedUnion:()=>zr,ZodEffects:()=>Je,ZodEnum:()=>hn,ZodError:()=>Me,ZodFirstPartyTypeKind:()=>v,ZodFunction:()=>Gr,ZodIntersection:()=>ln,ZodIssueCode:()=>A,ZodLazy:()=>dn,ZodLiteral:()=>un,ZodMap:()=>Vn,ZodNaN:()=>Hn,ZodNativeEnum:()=>pn,ZodNever:()=>ot,ZodNull:()=>sn,ZodNullable:()=>_t,ZodNumber:()=>tn,ZodObject:()=>Fe,ZodOptional:()=>ze,ZodParsedType:()=>P,ZodPipeline:()=>Sa,ZodPromise:()=>Ut,ZodReadonly:()=>_n,ZodRecord:()=>Fr,ZodSchema:()=>Z,ZodSet:()=>Wn,ZodString:()=>xt,ZodSymbol:()=>Zn,ZodTransformer:()=>Je,ZodTuple:()=>ft,ZodType:()=>Z,ZodUndefined:()=>on,ZodUnion:()=>cn,ZodUnknown:()=>vt,ZodVoid:()=>qn,addIssueToContext:()=>S,any:()=>tE,array:()=>oE,bigint:()=>Ky,boolean:()=>Bu,coerce:()=>NE,custom:()=>Fu,date:()=>Jy,datetimeRegex:()=>Mu,defaultErrorMap:()=>At,discriminatedUnion:()=>cE,effect:()=>TE,enum:()=>gE,function:()=>mE,getErrorMap:()=>Gn,getParsedType:()=>mt,instanceof:()=>Hy,intersection:()=>lE,isAborted:()=>Ur,isAsync:()=>jn,isDirty:()=>Mr,isValid:()=>kt,late:()=>Wy,lazy:()=>fE,literal:()=>_E,makeIssue:()=>va,map:()=>hE,nan:()=>Yy,nativeEnum:()=>yE,never:()=>aE,null:()=>eE,nullable:()=>wE,number:()=>ju,object:()=>Bs,objectUtil:()=>Fs,oboolean:()=>SE,onumber:()=>OE,optional:()=>bE,ostring:()=>vE,pipeline:()=>IE,preprocess:()=>AE,promise:()=>EE,quotelessJson:()=>by,record:()=>uE,set:()=>pE,setErrorMap:()=>Ay,strictObject:()=>sE,string:()=>Gu,symbol:()=>Xy,transformer:()=>TE,tuple:()=>dE,undefined:()=>Qy,union:()=>iE,unknown:()=>nE,util:()=>H,void:()=>rE});u();u();u();u();u();var H;(function(t){t.assertEqual=r=>{};function e(r){}t.assertIs=e;function n(r){throw new Error}t.assertNever=n,t.arrayToEnum=r=>{let o={};for(let s of r)o[s]=s;return o},t.getValidEnumValues=r=>{let o=t.objectKeys(r).filter(i=>typeof r[r[i]]!="number"),s={};for(let i of o)s[i]=r[i];return t.objectValues(s)},t.objectValues=r=>t.objectKeys(r).map(function(o){return r[o]}),t.objectKeys=typeof Object.keys=="function"?r=>Object.keys(r):r=>{let o=[];for(let s in r)Object.prototype.hasOwnProperty.call(r,s)&&o.push(s);return o},t.find=(r,o)=>{for(let s of r)if(o(s))return s},t.isInteger=typeof Number.isInteger=="function"?r=>Number.isInteger(r):r=>typeof r=="number"&&Number.isFinite(r)&&Math.floor(r)===r;function a(r,o=" | "){return r.map(s=>typeof s=="string"?`'${s}'`:s).join(o)}t.joinValues=a,t.jsonStringifyReplacer=(r,o)=>typeof o=="bigint"?o.toString():o})(H||(H={}));var Fs;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Fs||(Fs={}));var P=H.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),mt=t=>{switch(typeof t){case"undefined":return P.undefined;case"string":return P.string;case"number":return Number.isNaN(t)?P.nan:P.number;case"boolean":return P.boolean;case"function":return P.function;case"bigint":return P.bigint;case"symbol":return P.symbol;case"object":return Array.isArray(t)?P.array:t===null?P.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?P.promise:typeof Map<"u"&&t instanceof Map?P.map:typeof Set<"u"&&t instanceof Set?P.set:typeof Date<"u"&&t instanceof Date?P.date:P.object;default:return P.unknown}};var A=H.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),by=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Me=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=a=>{this.issues=[...this.issues,a]},this.addIssues=(a=[])=>{this.issues=[...this.issues,...a]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=e||function(o){return o.message},a={_errors:[]},r=o=>{for(let s of o.issues)if(s.code==="invalid_union")s.unionErrors.map(r);else if(s.code==="invalid_return_type")r(s.returnTypeError);else if(s.code==="invalid_arguments")r(s.argumentsError);else if(s.path.length===0)a._errors.push(n(s));else{let i=a,l=0;for(;l<s.path.length;){let d=s.path[l];l===s.path.length-1?(i[d]=i[d]||{_errors:[]},i[d]._errors.push(n(s))):i[d]=i[d]||{_errors:[]},i=i[d],l++}}};return r(this),a}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,H.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n={},a=[];for(let r of this.issues)if(r.path.length>0){let o=r.path[0];n[o]=n[o]||[],n[o].push(e(r))}else a.push(e(r));return{formErrors:a,fieldErrors:n}}get formErrors(){return this.flatten()}};Me.create=t=>new Me(t);var wy=(t,e)=>{let n;switch(t.code){case A.invalid_type:t.received===P.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case A.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,H.jsonStringifyReplacer)}`;break;case A.unrecognized_keys:n=`Unrecognized key(s) in object: ${H.joinValues(t.keys,", ")}`;break;case A.invalid_union:n="Invalid input";break;case A.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${H.joinValues(t.options)}`;break;case A.invalid_enum_value:n=`Invalid enum value. Expected ${H.joinValues(t.options)}, received '${t.received}'`;break;case A.invalid_arguments:n="Invalid function arguments";break;case A.invalid_return_type:n="Invalid function return type";break;case A.invalid_date:n="Invalid date";break;case A.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:H.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case A.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case A.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case A.custom:n="Invalid input";break;case A.invalid_intersection_types:n="Intersection results could not be merged";break;case A.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case A.not_finite:n="Number must be finite";break;default:n=e.defaultError,H.assertNever(t)}return{message:n}},At=wy;var Lu=At;function Ay(t){Lu=t}function Gn(){return Lu}u();var va=t=>{let{data:e,path:n,errorMaps:a,issueData:r}=t,o=[...n,...r.path||[]],s={...r,path:o};if(r.message!==void 0)return{...r,path:o,message:r.message};let i="",l=a.filter(d=>!!d).slice().reverse();for(let d of l)i=d(s,{data:e,defaultError:i}).message;return{...r,path:o,message:i}},Iy=[];function S(t,e){let n=Gn(),a=va({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===At?void 0:At].filter(r=>!!r)});t.common.issues.push(a)}var Ae=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let a=[];for(let r of n){if(r.status==="aborted")return M;r.status==="dirty"&&e.dirty(),a.push(r.value)}return{status:e.value,value:a}}static async mergeObjectAsync(e,n){let a=[];for(let r of n){let o=await r.key,s=await r.value;a.push({key:o,value:s})}return t.mergeObjectSync(e,a)}static mergeObjectSync(e,n){let a={};for(let r of n){let{key:o,value:s}=r;if(o.status==="aborted"||s.status==="aborted")return M;o.status==="dirty"&&e.dirty(),s.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof s.value<"u"||r.alwaysSet)&&(a[o.value]=s.value)}return{status:e.value,value:a}}},M=Object.freeze({status:"aborted"}),en=t=>({status:"dirty",value:t}),Pe=t=>({status:"valid",value:t}),Ur=t=>t.status==="aborted",Mr=t=>t.status==="dirty",kt=t=>t.status==="valid",jn=t=>typeof Promise<"u"&&t instanceof Promise;u();u();var R;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(R||(R={}));var Ke=class{constructor(e,n,a,r){this._cachedPath=[],this.parent=e,this.data=n,this._path=a,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},ku=(t,e)=>{if(kt(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new Me(t.common.issues);return this._error=n,this._error}}};function j(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:a,description:r}=t;if(e&&(n||a))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:r}:{errorMap:(s,i)=>{let{message:l}=t;return s.code==="invalid_enum_value"?{message:l??i.defaultError}:typeof i.data>"u"?{message:l??a??i.defaultError}:s.code!=="invalid_type"?{message:i.defaultError}:{message:l??n??i.defaultError}},description:r}}var Z=class{get description(){return this._def.description}_getType(e){return mt(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:mt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ae,ctx:{common:e.parent.common,data:e.data,parsedType:mt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(jn(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let a=this.safeParse(e,n);if(a.success)return a.data;throw a.error}safeParse(e,n){let a={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:mt(e)},r=this._parseSync({data:e,path:a.path,parent:a});return ku(a,r)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:mt(e)};if(!this["~standard"].async)try{let a=this._parseSync({data:e,path:[],parent:n});return kt(a)?{value:a.value}:{issues:n.common.issues}}catch(a){a?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(a=>kt(a)?{value:a.value}:{issues:n.common.issues})}async parseAsync(e,n){let a=await this.safeParseAsync(e,n);if(a.success)return a.data;throw a.error}async safeParseAsync(e,n){let a={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:mt(e)},r=this._parse({data:e,path:a.path,parent:a}),o=await(jn(r)?r:Promise.resolve(r));return ku(a,o)}refine(e,n){let a=r=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(r):n;return this._refinement((r,o)=>{let s=e(r),i=()=>o.addIssue({code:A.custom,...a(r)});return typeof Promise<"u"&&s instanceof Promise?s.then(l=>l?!0:(i(),!1)):s?!0:(i(),!1)})}refinement(e,n){return this._refinement((a,r)=>e(a)?!0:(r.addIssue(typeof n=="function"?n(a,r):n),!1))}_refinement(e){return new Je({schema:this,typeName:v.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return ze.create(this,this._def)}nullable(){return _t.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ot.create(this)}promise(){return Ut.create(this,this._def)}or(e){return cn.create([this,e],this._def)}and(e){return ln.create(this,e,this._def)}transform(e){return new Je({...j(this._def),schema:this,typeName:v.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new mn({...j(this._def),innerType:this,defaultValue:n,typeName:v.ZodDefault})}brand(){return new Oa({typeName:v.ZodBranded,type:this,...j(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new fn({...j(this._def),innerType:this,catchValue:n,typeName:v.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Sa.create(this,e)}readonly(){return _n.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},vy=/^c[^\s-]{8,}$/i,Oy=/^[0-9a-z]+$/,Sy=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ny=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Py=/^[a-z0-9_-]{21}$/i,Cy=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Dy=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Ry=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ly="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Gs,ky=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,xy=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,$y=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Uy=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,My=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,zy=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,$u="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Fy=new RegExp(`^${$u}$`);function Uu(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function Gy(t){return new RegExp(`^${Uu(t)}$`)}function Mu(t){let e=`${$u}T${Uu(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function jy(t,e){return!!((e==="v4"||!e)&&ky.test(t)||(e==="v6"||!e)&&$y.test(t))}function By(t,e){if(!Cy.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let a=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),r=JSON.parse(atob(a));return!(typeof r!="object"||r===null||"typ"in r&&r?.typ!=="JWT"||!r.alg||e&&r.alg!==e)}catch{return!1}}function Zy(t,e){return!!((e==="v4"||!e)&&xy.test(t)||(e==="v6"||!e)&&Uy.test(t))}var xt=class t extends Z{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==P.string){let o=this._getOrReturnCtx(e);return S(o,{code:A.invalid_type,expected:P.string,received:o.parsedType}),M}let a=new Ae,r;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(r=this._getOrReturnCtx(e,r),S(r,{code:A.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),a.dirty());else if(o.kind==="max")e.data.length>o.value&&(r=this._getOrReturnCtx(e,r),S(r,{code:A.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),a.dirty());else if(o.kind==="length"){let s=e.data.length>o.value,i=e.data.length<o.value;(s||i)&&(r=this._getOrReturnCtx(e,r),s?S(r,{code:A.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):i&&S(r,{code:A.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),a.dirty())}else if(o.kind==="email")Ry.test(e.data)||(r=this._getOrReturnCtx(e,r),S(r,{validation:"email",code:A.invalid_string,message:o.message}),a.dirty());else if(o.kind==="emoji")Gs||(Gs=new RegExp(Ly,"u")),Gs.test(e.data)||(r=this._getOrReturnCtx(e,r),S(r,{validation:"emoji",code:A.invalid_string,message:o.message}),a.dirty());else if(o.kind==="uuid")Ny.test(e.data)||(r=this._getOrReturnCtx(e,r),S(r,{validation:"uuid",code:A.invalid_string,message:o.message}),a.dirty());else if(o.kind==="nanoid")Py.test(e.data)||(r=this._getOrReturnCtx(e,r),S(r,{validation:"nanoid",code:A.invalid_string,message:o.message}),a.dirty());else if(o.kind==="cuid")vy.test(e.data)||(r=this._getOrReturnCtx(e,r),S(r,{validation:"cuid",code:A.invalid_string,message:o.message}),a.dirty());else if(o.kind==="cuid2")Oy.test(e.data)||(r=this._getOrReturnCtx(e,r),S(r,{validation:"cuid2",code:A.invalid_string,message:o.message}),a.dirty());else if(o.kind==="ulid")Sy.test(e.data)||(r=this._getOrReturnCtx(e,r),S(r,{validation:"ulid",code:A.invalid_string,message:o.message}),a.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),S(r,{validation:"url",code:A.invalid_string,message:o.message}),a.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),S(r,{validation:"regex",code:A.invalid_string,message:o.message}),a.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(r=this._getOrReturnCtx(e,r),S(r,{code:A.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),a.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(r=this._getOrReturnCtx(e,r),S(r,{code:A.invalid_string,validation:{startsWith:o.value},message:o.message}),a.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(r=this._getOrReturnCtx(e,r),S(r,{code:A.invalid_string,validation:{endsWith:o.value},message:o.message}),a.dirty()):o.kind==="datetime"?Mu(o).test(e.data)||(r=this._getOrReturnCtx(e,r),S(r,{code:A.invalid_string,validation:"datetime",message:o.message}),a.dirty()):o.kind==="date"?Fy.test(e.data)||(r=this._getOrReturnCtx(e,r),S(r,{code:A.invalid_string,validation:"date",message:o.message}),a.dirty()):o.kind==="time"?Gy(o).test(e.data)||(r=this._getOrReturnCtx(e,r),S(r,{code:A.invalid_string,validation:"time",message:o.message}),a.dirty()):o.kind==="duration"?Dy.test(e.data)||(r=this._getOrReturnCtx(e,r),S(r,{validation:"duration",code:A.invalid_string,message:o.message}),a.dirty()):o.kind==="ip"?jy(e.data,o.version)||(r=this._getOrReturnCtx(e,r),S(r,{validation:"ip",code:A.invalid_string,message:o.message}),a.dirty()):o.kind==="jwt"?By(e.data,o.alg)||(r=this._getOrReturnCtx(e,r),S(r,{validation:"jwt",code:A.invalid_string,message:o.message}),a.dirty()):o.kind==="cidr"?Zy(e.data,o.version)||(r=this._getOrReturnCtx(e,r),S(r,{validation:"cidr",code:A.invalid_string,message:o.message}),a.dirty()):o.kind==="base64"?My.test(e.data)||(r=this._getOrReturnCtx(e,r),S(r,{validation:"base64",code:A.invalid_string,message:o.message}),a.dirty()):o.kind==="base64url"?zy.test(e.data)||(r=this._getOrReturnCtx(e,r),S(r,{validation:"base64url",code:A.invalid_string,message:o.message}),a.dirty()):H.assertNever(o);return{status:a.value,value:e.data}}_regex(e,n,a){return this.refinement(r=>e.test(r),{validation:n,code:A.invalid_string,...R.errToObj(a)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...R.errToObj(e)})}url(e){return this._addCheck({kind:"url",...R.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...R.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...R.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...R.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...R.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...R.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...R.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...R.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...R.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...R.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...R.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...R.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...R.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...R.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...R.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...R.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...R.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...R.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...R.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...R.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...R.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...R.errToObj(n)})}nonempty(e){return this.min(1,R.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};xt.create=t=>new xt({checks:[],typeName:v.ZodString,coerce:t?.coerce??!1,...j(t)});function qy(t,e){let n=(t.toString().split(".")[1]||"").length,a=(e.toString().split(".")[1]||"").length,r=n>a?n:a,o=Number.parseInt(t.toFixed(r).replace(".","")),s=Number.parseInt(e.toFixed(r).replace(".",""));return o%s/10**r}var tn=class t extends Z{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==P.number){let o=this._getOrReturnCtx(e);return S(o,{code:A.invalid_type,expected:P.number,received:o.parsedType}),M}let a,r=new Ae;for(let o of this._def.checks)o.kind==="int"?H.isInteger(e.data)||(a=this._getOrReturnCtx(e,a),S(a,{code:A.invalid_type,expected:"integer",received:"float",message:o.message}),r.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(a=this._getOrReturnCtx(e,a),S(a,{code:A.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),r.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(a=this._getOrReturnCtx(e,a),S(a,{code:A.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),r.dirty()):o.kind==="multipleOf"?qy(e.data,o.value)!==0&&(a=this._getOrReturnCtx(e,a),S(a,{code:A.not_multiple_of,multipleOf:o.value,message:o.message}),r.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(a=this._getOrReturnCtx(e,a),S(a,{code:A.not_finite,message:o.message}),r.dirty()):H.assertNever(o);return{status:r.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,R.toString(n))}gt(e,n){return this.setLimit("min",e,!1,R.toString(n))}lte(e,n){return this.setLimit("max",e,!0,R.toString(n))}lt(e,n){return this.setLimit("max",e,!1,R.toString(n))}setLimit(e,n,a,r){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:a,message:R.toString(r)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:R.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:R.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:R.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:R.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:R.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:R.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:R.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:R.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:R.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&H.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let a of this._def.checks){if(a.kind==="finite"||a.kind==="int"||a.kind==="multipleOf")return!0;a.kind==="min"?(n===null||a.value>n)&&(n=a.value):a.kind==="max"&&(e===null||a.value<e)&&(e=a.value)}return Number.isFinite(n)&&Number.isFinite(e)}};tn.create=t=>new tn({checks:[],typeName:v.ZodNumber,coerce:t?.coerce||!1,...j(t)});var nn=class t extends Z{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==P.bigint)return this._getInvalidInput(e);let a,r=new Ae;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(a=this._getOrReturnCtx(e,a),S(a,{code:A.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),r.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(a=this._getOrReturnCtx(e,a),S(a,{code:A.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),r.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(a=this._getOrReturnCtx(e,a),S(a,{code:A.not_multiple_of,multipleOf:o.value,message:o.message}),r.dirty()):H.assertNever(o);return{status:r.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return S(n,{code:A.invalid_type,expected:P.bigint,received:n.parsedType}),M}gte(e,n){return this.setLimit("min",e,!0,R.toString(n))}gt(e,n){return this.setLimit("min",e,!1,R.toString(n))}lte(e,n){return this.setLimit("max",e,!0,R.toString(n))}lt(e,n){return this.setLimit("max",e,!1,R.toString(n))}setLimit(e,n,a,r){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:a,message:R.toString(r)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:R.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:R.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:R.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:R.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:R.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};nn.create=t=>new nn({checks:[],typeName:v.ZodBigInt,coerce:t?.coerce??!1,...j(t)});var an=class extends Z{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==P.boolean){let a=this._getOrReturnCtx(e);return S(a,{code:A.invalid_type,expected:P.boolean,received:a.parsedType}),M}return Pe(e.data)}};an.create=t=>new an({typeName:v.ZodBoolean,coerce:t?.coerce||!1,...j(t)});var rn=class t extends Z{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==P.date){let o=this._getOrReturnCtx(e);return S(o,{code:A.invalid_type,expected:P.date,received:o.parsedType}),M}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return S(o,{code:A.invalid_date}),M}let a=new Ae,r;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(r=this._getOrReturnCtx(e,r),S(r,{code:A.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),a.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(r=this._getOrReturnCtx(e,r),S(r,{code:A.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),a.dirty()):H.assertNever(o);return{status:a.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:R.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:R.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};rn.create=t=>new rn({checks:[],coerce:t?.coerce||!1,typeName:v.ZodDate,...j(t)});var Zn=class extends Z{_parse(e){if(this._getType(e)!==P.symbol){let a=this._getOrReturnCtx(e);return S(a,{code:A.invalid_type,expected:P.symbol,received:a.parsedType}),M}return Pe(e.data)}};Zn.create=t=>new Zn({typeName:v.ZodSymbol,...j(t)});var on=class extends Z{_parse(e){if(this._getType(e)!==P.undefined){let a=this._getOrReturnCtx(e);return S(a,{code:A.invalid_type,expected:P.undefined,received:a.parsedType}),M}return Pe(e.data)}};on.create=t=>new on({typeName:v.ZodUndefined,...j(t)});var sn=class extends Z{_parse(e){if(this._getType(e)!==P.null){let a=this._getOrReturnCtx(e);return S(a,{code:A.invalid_type,expected:P.null,received:a.parsedType}),M}return Pe(e.data)}};sn.create=t=>new sn({typeName:v.ZodNull,...j(t)});var $t=class extends Z{constructor(){super(...arguments),this._any=!0}_parse(e){return Pe(e.data)}};$t.create=t=>new $t({typeName:v.ZodAny,...j(t)});var vt=class extends Z{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Pe(e.data)}};vt.create=t=>new vt({typeName:v.ZodUnknown,...j(t)});var ot=class extends Z{_parse(e){let n=this._getOrReturnCtx(e);return S(n,{code:A.invalid_type,expected:P.never,received:n.parsedType}),M}};ot.create=t=>new ot({typeName:v.ZodNever,...j(t)});var qn=class extends Z{_parse(e){if(this._getType(e)!==P.undefined){let a=this._getOrReturnCtx(e);return S(a,{code:A.invalid_type,expected:P.void,received:a.parsedType}),M}return Pe(e.data)}};qn.create=t=>new qn({typeName:v.ZodVoid,...j(t)});var Ot=class t extends Z{_parse(e){let{ctx:n,status:a}=this._processInputParams(e),r=this._def;if(n.parsedType!==P.array)return S(n,{code:A.invalid_type,expected:P.array,received:n.parsedType}),M;if(r.exactLength!==null){let s=n.data.length>r.exactLength.value,i=n.data.length<r.exactLength.value;(s||i)&&(S(n,{code:s?A.too_big:A.too_small,minimum:i?r.exactLength.value:void 0,maximum:s?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),a.dirty())}if(r.minLength!==null&&n.data.length<r.minLength.value&&(S(n,{code:A.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),a.dirty()),r.maxLength!==null&&n.data.length>r.maxLength.value&&(S(n,{code:A.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),a.dirty()),n.common.async)return Promise.all([...n.data].map((s,i)=>r.type._parseAsync(new Ke(n,s,n.path,i)))).then(s=>Ae.mergeArray(a,s));let o=[...n.data].map((s,i)=>r.type._parseSync(new Ke(n,s,n.path,i)));return Ae.mergeArray(a,o)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:R.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:R.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:R.toString(n)}})}nonempty(e){return this.min(1,e)}};Ot.create=(t,e)=>new Ot({type:t,minLength:null,maxLength:null,exactLength:null,typeName:v.ZodArray,...j(e)});function Bn(t){if(t instanceof Fe){let e={};for(let n in t.shape){let a=t.shape[n];e[n]=ze.create(Bn(a))}return new Fe({...t._def,shape:()=>e})}else return t instanceof Ot?new Ot({...t._def,type:Bn(t.element)}):t instanceof ze?ze.create(Bn(t.unwrap())):t instanceof _t?_t.create(Bn(t.unwrap())):t instanceof ft?ft.create(t.items.map(e=>Bn(e))):t}var Fe=class t extends Z{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),n=H.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==P.object){let d=this._getOrReturnCtx(e);return S(d,{code:A.invalid_type,expected:P.object,received:d.parsedType}),M}let{status:a,ctx:r}=this._processInputParams(e),{shape:o,keys:s}=this._getCached(),i=[];if(!(this._def.catchall instanceof ot&&this._def.unknownKeys==="strip"))for(let d in r.data)s.includes(d)||i.push(d);let l=[];for(let d of s){let h=o[d],p=r.data[d];l.push({key:{status:"valid",value:d},value:h._parse(new Ke(r,p,r.path,d)),alwaysSet:d in r.data})}if(this._def.catchall instanceof ot){let d=this._def.unknownKeys;if(d==="passthrough")for(let h of i)l.push({key:{status:"valid",value:h},value:{status:"valid",value:r.data[h]}});else if(d==="strict")i.length>0&&(S(r,{code:A.unrecognized_keys,keys:i}),a.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let d=this._def.catchall;for(let h of i){let p=r.data[h];l.push({key:{status:"valid",value:h},value:d._parse(new Ke(r,p,r.path,h)),alwaysSet:h in r.data})}}return r.common.async?Promise.resolve().then(async()=>{let d=[];for(let h of l){let p=await h.key,g=await h.value;d.push({key:p,value:g,alwaysSet:h.alwaysSet})}return d}).then(d=>Ae.mergeObjectSync(a,d)):Ae.mergeObjectSync(a,l)}get shape(){return this._def.shape()}strict(e){return R.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,a)=>{let r=this._def.errorMap?.(n,a).message??a.defaultError;return n.code==="unrecognized_keys"?{message:R.errToObj(e).message??r}:{message:r}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:v.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let a of H.objectKeys(e))e[a]&&this.shape[a]&&(n[a]=this.shape[a]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let a of H.objectKeys(this.shape))e[a]||(n[a]=this.shape[a]);return new t({...this._def,shape:()=>n})}deepPartial(){return Bn(this)}partial(e){let n={};for(let a of H.objectKeys(this.shape)){let r=this.shape[a];e&&!e[a]?n[a]=r:n[a]=r.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let a of H.objectKeys(this.shape))if(e&&!e[a])n[a]=this.shape[a];else{let o=this.shape[a];for(;o instanceof ze;)o=o._def.innerType;n[a]=o}return new t({...this._def,shape:()=>n})}keyof(){return zu(H.objectKeys(this.shape))}};Fe.create=(t,e)=>new Fe({shape:()=>t,unknownKeys:"strip",catchall:ot.create(),typeName:v.ZodObject,...j(e)});Fe.strictCreate=(t,e)=>new Fe({shape:()=>t,unknownKeys:"strict",catchall:ot.create(),typeName:v.ZodObject,...j(e)});Fe.lazycreate=(t,e)=>new Fe({shape:t,unknownKeys:"strip",catchall:ot.create(),typeName:v.ZodObject,...j(e)});var cn=class extends Z{_parse(e){let{ctx:n}=this._processInputParams(e),a=this._def.options;function r(o){for(let i of o)if(i.result.status==="valid")return i.result;for(let i of o)if(i.result.status==="dirty")return n.common.issues.push(...i.ctx.common.issues),i.result;let s=o.map(i=>new Me(i.ctx.common.issues));return S(n,{code:A.invalid_union,unionErrors:s}),M}if(n.common.async)return Promise.all(a.map(async o=>{let s={...n,common:{...n.common,issues:[]},parent:null};return{result:await o._parseAsync({data:n.data,path:n.path,parent:s}),ctx:s}})).then(r);{let o,s=[];for(let l of a){let d={...n,common:{...n.common,issues:[]},parent:null},h=l._parseSync({data:n.data,path:n.path,parent:d});if(h.status==="valid")return h;h.status==="dirty"&&!o&&(o={result:h,ctx:d}),d.common.issues.length&&s.push(d.common.issues)}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;let i=s.map(l=>new Me(l));return S(n,{code:A.invalid_union,unionErrors:i}),M}}get options(){return this._def.options}};cn.create=(t,e)=>new cn({options:t,typeName:v.ZodUnion,...j(e)});var It=t=>t instanceof dn?It(t.schema):t instanceof Je?It(t.innerType()):t instanceof un?[t.value]:t instanceof hn?t.options:t instanceof pn?H.objectValues(t.enum):t instanceof mn?It(t._def.innerType):t instanceof on?[void 0]:t instanceof sn?[null]:t instanceof ze?[void 0,...It(t.unwrap())]:t instanceof _t?[null,...It(t.unwrap())]:t instanceof Oa||t instanceof _n?It(t.unwrap()):t instanceof fn?It(t._def.innerType):[],zr=class t extends Z{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==P.object)return S(n,{code:A.invalid_type,expected:P.object,received:n.parsedType}),M;let a=this.discriminator,r=n.data[a],o=this.optionsMap.get(r);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._parseSync({data:n.data,path:n.path,parent:n}):(S(n,{code:A.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[a]}),M)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,a){let r=new Map;for(let o of n){let s=It(o.shape[e]);if(!s.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let i of s){if(r.has(i))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);r.set(i,o)}}return new t({typeName:v.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:r,...j(a)})}};function js(t,e){let n=mt(t),a=mt(e);if(t===e)return{valid:!0,data:t};if(n===P.object&&a===P.object){let r=H.objectKeys(e),o=H.objectKeys(t).filter(i=>r.indexOf(i)!==-1),s={...t,...e};for(let i of o){let l=js(t[i],e[i]);if(!l.valid)return{valid:!1};s[i]=l.data}return{valid:!0,data:s}}else if(n===P.array&&a===P.array){if(t.length!==e.length)return{valid:!1};let r=[];for(let o=0;o<t.length;o++){let s=t[o],i=e[o],l=js(s,i);if(!l.valid)return{valid:!1};r.push(l.data)}return{valid:!0,data:r}}else return n===P.date&&a===P.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var ln=class extends Z{_parse(e){let{status:n,ctx:a}=this._processInputParams(e),r=(o,s)=>{if(Ur(o)||Ur(s))return M;let i=js(o.value,s.value);return i.valid?((Mr(o)||Mr(s))&&n.dirty(),{status:n.value,value:i.data}):(S(a,{code:A.invalid_intersection_types}),M)};return a.common.async?Promise.all([this._def.left._parseAsync({data:a.data,path:a.path,parent:a}),this._def.right._parseAsync({data:a.data,path:a.path,parent:a})]).then(([o,s])=>r(o,s)):r(this._def.left._parseSync({data:a.data,path:a.path,parent:a}),this._def.right._parseSync({data:a.data,path:a.path,parent:a}))}};ln.create=(t,e,n)=>new ln({left:t,right:e,typeName:v.ZodIntersection,...j(n)});var ft=class t extends Z{_parse(e){let{status:n,ctx:a}=this._processInputParams(e);if(a.parsedType!==P.array)return S(a,{code:A.invalid_type,expected:P.array,received:a.parsedType}),M;if(a.data.length<this._def.items.length)return S(a,{code:A.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),M;!this._def.rest&&a.data.length>this._def.items.length&&(S(a,{code:A.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let o=[...a.data].map((s,i)=>{let l=this._def.items[i]||this._def.rest;return l?l._parse(new Ke(a,s,a.path,i)):null}).filter(s=>!!s);return a.common.async?Promise.all(o).then(s=>Ae.mergeArray(n,s)):Ae.mergeArray(n,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};ft.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ft({items:t,typeName:v.ZodTuple,rest:null,...j(e)})};var Fr=class t extends Z{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:a}=this._processInputParams(e);if(a.parsedType!==P.object)return S(a,{code:A.invalid_type,expected:P.object,received:a.parsedType}),M;let r=[],o=this._def.keyType,s=this._def.valueType;for(let i in a.data)r.push({key:o._parse(new Ke(a,i,a.path,i)),value:s._parse(new Ke(a,a.data[i],a.path,i)),alwaysSet:i in a.data});return a.common.async?Ae.mergeObjectAsync(n,r):Ae.mergeObjectSync(n,r)}get element(){return this._def.valueType}static create(e,n,a){return n instanceof Z?new t({keyType:e,valueType:n,typeName:v.ZodRecord,...j(a)}):new t({keyType:xt.create(),valueType:e,typeName:v.ZodRecord,...j(n)})}},Vn=class extends Z{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:a}=this._processInputParams(e);if(a.parsedType!==P.map)return S(a,{code:A.invalid_type,expected:P.map,received:a.parsedType}),M;let r=this._def.keyType,o=this._def.valueType,s=[...a.data.entries()].map(([i,l],d)=>({key:r._parse(new Ke(a,i,a.path,[d,"key"])),value:o._parse(new Ke(a,l,a.path,[d,"value"]))}));if(a.common.async){let i=new Map;return Promise.resolve().then(async()=>{for(let l of s){let d=await l.key,h=await l.value;if(d.status==="aborted"||h.status==="aborted")return M;(d.status==="dirty"||h.status==="dirty")&&n.dirty(),i.set(d.value,h.value)}return{status:n.value,value:i}})}else{let i=new Map;for(let l of s){let d=l.key,h=l.value;if(d.status==="aborted"||h.status==="aborted")return M;(d.status==="dirty"||h.status==="dirty")&&n.dirty(),i.set(d.value,h.value)}return{status:n.value,value:i}}}};Vn.create=(t,e,n)=>new Vn({valueType:e,keyType:t,typeName:v.ZodMap,...j(n)});var Wn=class t extends Z{_parse(e){let{status:n,ctx:a}=this._processInputParams(e);if(a.parsedType!==P.set)return S(a,{code:A.invalid_type,expected:P.set,received:a.parsedType}),M;let r=this._def;r.minSize!==null&&a.data.size<r.minSize.value&&(S(a,{code:A.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),n.dirty()),r.maxSize!==null&&a.data.size>r.maxSize.value&&(S(a,{code:A.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),n.dirty());let o=this._def.valueType;function s(l){let d=new Set;for(let h of l){if(h.status==="aborted")return M;h.status==="dirty"&&n.dirty(),d.add(h.value)}return{status:n.value,value:d}}let i=[...a.data.values()].map((l,d)=>o._parse(new Ke(a,l,a.path,d)));return a.common.async?Promise.all(i).then(l=>s(l)):s(i)}min(e,n){return new t({...this._def,minSize:{value:e,message:R.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:R.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};Wn.create=(t,e)=>new Wn({valueType:t,minSize:null,maxSize:null,typeName:v.ZodSet,...j(e)});var Gr=class t extends Z{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==P.function)return S(n,{code:A.invalid_type,expected:P.function,received:n.parsedType}),M;function a(i,l){return va({data:i,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Gn(),At].filter(d=>!!d),issueData:{code:A.invalid_arguments,argumentsError:l}})}function r(i,l){return va({data:i,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Gn(),At].filter(d=>!!d),issueData:{code:A.invalid_return_type,returnTypeError:l}})}let o={errorMap:n.common.contextualErrorMap},s=n.data;if(this._def.returns instanceof Ut){let i=this;return Pe(async function(...l){let d=new Me([]),h=await i._def.args.parseAsync(l,o).catch(f=>{throw d.addIssue(a(l,f)),d}),p=await Reflect.apply(s,this,h);return await i._def.returns._def.type.parseAsync(p,o).catch(f=>{throw d.addIssue(r(p,f)),d})})}else{let i=this;return Pe(function(...l){let d=i._def.args.safeParse(l,o);if(!d.success)throw new Me([a(l,d.error)]);let h=Reflect.apply(s,this,d.data),p=i._def.returns.safeParse(h,o);if(!p.success)throw new Me([r(h,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:ft.create(e).rest(vt.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,a){return new t({args:e||ft.create([]).rest(vt.create()),returns:n||vt.create(),typeName:v.ZodFunction,...j(a)})}},dn=class extends Z{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};dn.create=(t,e)=>new dn({getter:t,typeName:v.ZodLazy,...j(e)});var un=class extends Z{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return S(n,{received:n.data,code:A.invalid_literal,expected:this._def.value}),M}return{status:"valid",value:e.data}}get value(){return this._def.value}};un.create=(t,e)=>new un({value:t,typeName:v.ZodLiteral,...j(e)});function zu(t,e){return new hn({values:t,typeName:v.ZodEnum,...j(e)})}var hn=class t extends Z{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),a=this._def.values;return S(n,{expected:H.joinValues(a),received:n.parsedType,code:A.invalid_type}),M}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),a=this._def.values;return S(n,{received:n.data,code:A.invalid_enum_value,options:a}),M}return Pe(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(a=>!e.includes(a)),{...this._def,...n})}};hn.create=zu;var pn=class extends Z{_parse(e){let n=H.getValidEnumValues(this._def.values),a=this._getOrReturnCtx(e);if(a.parsedType!==P.string&&a.parsedType!==P.number){let r=H.objectValues(n);return S(a,{expected:H.joinValues(r),received:a.parsedType,code:A.invalid_type}),M}if(this._cache||(this._cache=new Set(H.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let r=H.objectValues(n);return S(a,{received:a.data,code:A.invalid_enum_value,options:r}),M}return Pe(e.data)}get enum(){return this._def.values}};pn.create=(t,e)=>new pn({values:t,typeName:v.ZodNativeEnum,...j(e)});var Ut=class extends Z{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==P.promise&&n.common.async===!1)return S(n,{code:A.invalid_type,expected:P.promise,received:n.parsedType}),M;let a=n.parsedType===P.promise?n.data:Promise.resolve(n.data);return Pe(a.then(r=>this._def.type.parseAsync(r,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Ut.create=(t,e)=>new Ut({type:t,typeName:v.ZodPromise,...j(e)});var Je=class extends Z{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===v.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:a}=this._processInputParams(e),r=this._def.effect||null,o={addIssue:s=>{S(a,s),s.fatal?n.abort():n.dirty()},get path(){return a.path}};if(o.addIssue=o.addIssue.bind(o),r.type==="preprocess"){let s=r.transform(a.data,o);if(a.common.async)return Promise.resolve(s).then(async i=>{if(n.value==="aborted")return M;let l=await this._def.schema._parseAsync({data:i,path:a.path,parent:a});return l.status==="aborted"?M:l.status==="dirty"?en(l.value):n.value==="dirty"?en(l.value):l});{if(n.value==="aborted")return M;let i=this._def.schema._parseSync({data:s,path:a.path,parent:a});return i.status==="aborted"?M:i.status==="dirty"?en(i.value):n.value==="dirty"?en(i.value):i}}if(r.type==="refinement"){let s=i=>{let l=r.refinement(i,o);if(a.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return i};if(a.common.async===!1){let i=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});return i.status==="aborted"?M:(i.status==="dirty"&&n.dirty(),s(i.value),{status:n.value,value:i.value})}else return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then(i=>i.status==="aborted"?M:(i.status==="dirty"&&n.dirty(),s(i.value).then(()=>({status:n.value,value:i.value}))))}if(r.type==="transform")if(a.common.async===!1){let s=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});if(!kt(s))return M;let i=r.transform(s.value,o);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:i}}else return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then(s=>kt(s)?Promise.resolve(r.transform(s.value,o)).then(i=>({status:n.value,value:i})):M);H.assertNever(r)}};Je.create=(t,e,n)=>new Je({schema:t,typeName:v.ZodEffects,effect:e,...j(n)});Je.createWithPreprocess=(t,e,n)=>new Je({schema:e,effect:{type:"preprocess",transform:t},typeName:v.ZodEffects,...j(n)});var ze=class extends Z{_parse(e){return this._getType(e)===P.undefined?Pe(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ze.create=(t,e)=>new ze({innerType:t,typeName:v.ZodOptional,...j(e)});var _t=class extends Z{_parse(e){return this._getType(e)===P.null?Pe(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};_t.create=(t,e)=>new _t({innerType:t,typeName:v.ZodNullable,...j(e)});var mn=class extends Z{_parse(e){let{ctx:n}=this._processInputParams(e),a=n.data;return n.parsedType===P.undefined&&(a=this._def.defaultValue()),this._def.innerType._parse({data:a,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};mn.create=(t,e)=>new mn({innerType:t,typeName:v.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...j(e)});var fn=class extends Z{_parse(e){let{ctx:n}=this._processInputParams(e),a={...n,common:{...n.common,issues:[]}},r=this._def.innerType._parse({data:a.data,path:a.path,parent:{...a}});return jn(r)?r.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Me(a.common.issues)},input:a.data})})):{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new Me(a.common.issues)},input:a.data})}}removeCatch(){return this._def.innerType}};fn.create=(t,e)=>new fn({innerType:t,typeName:v.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...j(e)});var Hn=class extends Z{_parse(e){if(this._getType(e)!==P.nan){let a=this._getOrReturnCtx(e);return S(a,{code:A.invalid_type,expected:P.nan,received:a.parsedType}),M}return{status:"valid",value:e.data}}};Hn.create=t=>new Hn({typeName:v.ZodNaN,...j(t)});var Vy=Symbol("zod_brand"),Oa=class extends Z{_parse(e){let{ctx:n}=this._processInputParams(e),a=n.data;return this._def.type._parse({data:a,path:n.path,parent:n})}unwrap(){return this._def.type}},Sa=class t extends Z{_parse(e){let{status:n,ctx:a}=this._processInputParams(e);if(a.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:a.data,path:a.path,parent:a});return o.status==="aborted"?M:o.status==="dirty"?(n.dirty(),en(o.value)):this._def.out._parseAsync({data:o.value,path:a.path,parent:a})})();{let r=this._def.in._parseSync({data:a.data,path:a.path,parent:a});return r.status==="aborted"?M:r.status==="dirty"?(n.dirty(),{status:"dirty",value:r.value}):this._def.out._parseSync({data:r.value,path:a.path,parent:a})}}static create(e,n){return new t({in:e,out:n,typeName:v.ZodPipeline})}},_n=class extends Z{_parse(e){let n=this._def.innerType._parse(e),a=r=>(kt(r)&&(r.value=Object.freeze(r.value)),r);return jn(n)?n.then(r=>a(r)):a(n)}unwrap(){return this._def.innerType}};_n.create=(t,e)=>new _n({innerType:t,typeName:v.ZodReadonly,...j(e)});function xu(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function Fu(t,e={},n){return t?$t.create().superRefine((a,r)=>{let o=t(a);if(o instanceof Promise)return o.then(s=>{if(!s){let i=xu(e,a),l=i.fatal??n??!0;r.addIssue({code:"custom",...i,fatal:l})}});if(!o){let s=xu(e,a),i=s.fatal??n??!0;r.addIssue({code:"custom",...s,fatal:i})}}):$t.create()}var Wy={object:Fe.lazycreate},v;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(v||(v={}));var Hy=(t,e={message:`Input not instance of ${t.name}`})=>Fu(n=>n instanceof t,e),Gu=xt.create,ju=tn.create,Yy=Hn.create,Ky=nn.create,Bu=an.create,Jy=rn.create,Xy=Zn.create,Qy=on.create,eE=sn.create,tE=$t.create,nE=vt.create,aE=ot.create,rE=qn.create,oE=Ot.create,Bs=Fe.create,sE=Fe.strictCreate,iE=cn.create,cE=zr.create,lE=ln.create,dE=ft.create,uE=Fr.create,hE=Vn.create,pE=Wn.create,mE=Gr.create,fE=dn.create,_E=un.create,gE=hn.create,yE=pn.create,EE=Ut.create,TE=Je.create,bE=ze.create,wE=_t.create,AE=Je.createWithPreprocess,IE=Sa.create,vE=()=>Gu().optional(),OE=()=>ju().optional(),SE=()=>Bu().optional(),NE={string:(t=>xt.create({...t,coerce:!0})),number:(t=>tn.create({...t,coerce:!0})),boolean:(t=>an.create({...t,coerce:!0})),bigint:(t=>nn.create({...t,coerce:!0})),date:(t=>rn.create({...t,coerce:!0}))};var PE=M;u();u();u();var CE=Object.freeze({status:"aborted"});function b(t,e,n){function a(i,l){var d;Object.defineProperty(i,"_zod",{value:i._zod??{},enumerable:!1}),(d=i._zod).traits??(d.traits=new Set),i._zod.traits.add(t),e(i,l);for(let h in s.prototype)h in i||Object.defineProperty(i,h,{value:s.prototype[h].bind(i)});i._zod.constr=s,i._zod.def=l}let r=n?.Parent??Object;class o extends r{}Object.defineProperty(o,"name",{value:t});function s(i){var l;let d=n?.Parent?new o:this;a(d,i),(l=d._zod).deferred??(l.deferred=[]);for(let h of d._zod.deferred)h();return d}return Object.defineProperty(s,"init",{value:a}),Object.defineProperty(s,Symbol.hasInstance,{value:i=>n?.Parent&&i instanceof n.Parent?!0:i?._zod?.traits?.has(t)}),Object.defineProperty(s,"name",{value:t}),s}var DE=Symbol("zod_brand"),St=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},jr={};function Ve(t){return t&&Object.assign(jr,t),jr}u();u();var Y={};ks(Y,{BIGINT_FORMAT_RANGES:()=>qu,Class:()=>qs,NUMBER_FORMAT_RANGES:()=>Xs,aborted:()=>yn,allowsEval:()=>Ys,assert:()=>$E,assertEqual:()=>RE,assertIs:()=>kE,assertNever:()=>xE,assertNotEqual:()=>LE,assignProp:()=>Hs,cached:()=>Ca,captureStackTrace:()=>Zr,cleanEnum:()=>YE,cleanRegex:()=>Ra,clone:()=>We,createTransparentProxy:()=>jE,defineLazy:()=>se,esc:()=>gn,escapeRegex:()=>Mt,extend:()=>qE,finalizeIssue:()=>st,floatSafeRemainder:()=>Ws,getElementAtPath:()=>UE,getEnumValues:()=>Pa,getLengthableOrigin:()=>La,getParsedType:()=>GE,getSizableOrigin:()=>Vu,isObject:()=>Yn,isPlainObject:()=>Kn,issue:()=>Qs,joinValues:()=>Br,jsonStringifyReplacer:()=>Vs,merge:()=>VE,normalizeParams:()=>z,nullish:()=>Da,numKeys:()=>FE,omit:()=>ZE,optionalKeys:()=>Js,partial:()=>WE,pick:()=>BE,prefixIssues:()=>gt,primitiveTypes:()=>Zu,promiseAllObject:()=>ME,propertyKeyTypes:()=>Ks,randomString:()=>zE,required:()=>HE,stringifyPrimitive:()=>qr,unwrapMessage:()=>Na});u();function RE(t){return t}function LE(t){return t}function kE(t){}function xE(t){throw new Error}function $E(t){}function Pa(t){let e=Object.values(t).filter(a=>typeof a=="number");return Object.entries(t).filter(([a,r])=>e.indexOf(+a)===-1).map(([a,r])=>r)}function Br(t,e="|"){return t.map(n=>qr(n)).join(e)}function Vs(t,e){return typeof e=="bigint"?e.toString():e}function Ca(t){return{get value(){{let n=t();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function Da(t){return t==null}function Ra(t){let e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function Ws(t,e){let n=(t.toString().split(".")[1]||"").length,a=(e.toString().split(".")[1]||"").length,r=n>a?n:a,o=Number.parseInt(t.toFixed(r).replace(".","")),s=Number.parseInt(e.toFixed(r).replace(".",""));return o%s/10**r}function se(t,e,n){Object.defineProperty(t,e,{get(){{let r=n();return t[e]=r,r}throw new Error("cached value already set")},set(r){Object.defineProperty(t,e,{value:r})},configurable:!0})}function Hs(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function UE(t,e){return e?e.reduce((n,a)=>n?.[a],t):t}function ME(t){let e=Object.keys(t),n=e.map(a=>t[a]);return Promise.all(n).then(a=>{let r={};for(let o=0;o<e.length;o++)r[e[o]]=a[o];return r})}function zE(t=10){let e="abcdefghijklmnopqrstuvwxyz",n="";for(let a=0;a<t;a++)n+=e[Math.floor(Math.random()*e.length)];return n}function gn(t){return JSON.stringify(t)}var Zr=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function Yn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Ys=Ca(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function Kn(t){if(Yn(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let n=e.prototype;return!(Yn(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function FE(t){let e=0;for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&e++;return e}var GE=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},Ks=new Set(["string","number","symbol"]),Zu=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Mt(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function We(t,e,n){let a=new t._zod.constr(e??t._zod.def);return(!e||n?.parent)&&(a._zod.parent=t),a}function z(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function jE(t){let e;return new Proxy({},{get(n,a,r){return e??(e=t()),Reflect.get(e,a,r)},set(n,a,r,o){return e??(e=t()),Reflect.set(e,a,r,o)},has(n,a){return e??(e=t()),Reflect.has(e,a)},deleteProperty(n,a){return e??(e=t()),Reflect.deleteProperty(e,a)},ownKeys(n){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(n,a){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,a)},defineProperty(n,a,r){return e??(e=t()),Reflect.defineProperty(e,a,r)}})}function qr(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Js(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var Xs={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},qu={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function BE(t,e){let n={},a=t._zod.def;for(let r in e){if(!(r in a.shape))throw new Error(`Unrecognized key: "${r}"`);e[r]&&(n[r]=a.shape[r])}return We(t,{...t._zod.def,shape:n,checks:[]})}function ZE(t,e){let n={...t._zod.def.shape},a=t._zod.def;for(let r in e){if(!(r in a.shape))throw new Error(`Unrecognized key: "${r}"`);e[r]&&delete n[r]}return We(t,{...t._zod.def,shape:n,checks:[]})}function qE(t,e){if(!Kn(e))throw new Error("Invalid input to extend: expected a plain object");let n={...t._zod.def,get shape(){let a={...t._zod.def.shape,...e};return Hs(this,"shape",a),a},checks:[]};return We(t,n)}function VE(t,e){return We(t,{...t._zod.def,get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return Hs(this,"shape",n),n},catchall:e._zod.def.catchall,checks:[]})}function WE(t,e,n){let a=e._zod.def.shape,r={...a};if(n)for(let o in n){if(!(o in a))throw new Error(`Unrecognized key: "${o}"`);n[o]&&(r[o]=t?new t({type:"optional",innerType:a[o]}):a[o])}else for(let o in a)r[o]=t?new t({type:"optional",innerType:a[o]}):a[o];return We(e,{...e._zod.def,shape:r,checks:[]})}function HE(t,e,n){let a=e._zod.def.shape,r={...a};if(n)for(let o in n){if(!(o in r))throw new Error(`Unrecognized key: "${o}"`);n[o]&&(r[o]=new t({type:"nonoptional",innerType:a[o]}))}else for(let o in a)r[o]=new t({type:"nonoptional",innerType:a[o]});return We(e,{...e._zod.def,shape:r,checks:[]})}function yn(t,e=0){for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue!==!0)return!0;return!1}function gt(t,e){return e.map(n=>{var a;return(a=n).path??(a.path=[]),n.path.unshift(t),n})}function Na(t){return typeof t=="string"?t:t?.message}function st(t,e,n){let a={...t,path:t.path??[]};if(!t.message){let r=Na(t.inst?._zod.def?.error?.(t))??Na(e?.error?.(t))??Na(n.customError?.(t))??Na(n.localeError?.(t))??"Invalid input";a.message=r}return delete a.inst,delete a.continue,e?.reportInput||delete a.input,a}function Vu(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function La(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Qs(...t){let[e,n,a]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:a}:{...e}}function YE(t){return Object.entries(t).filter(([e,n])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var qs=class{constructor(...e){}};var Wu=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,Vs,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Vr=b("$ZodError",Wu),ka=b("$ZodError",Wu,{Parent:Error});function ei(t,e=n=>n.message){let n={},a=[];for(let r of t.issues)r.path.length>0?(n[r.path[0]]=n[r.path[0]]||[],n[r.path[0]].push(e(r))):a.push(e(r));return{formErrors:a,fieldErrors:n}}function ti(t,e){let n=e||function(o){return o.message},a={_errors:[]},r=o=>{for(let s of o.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(i=>r({issues:i}));else if(s.code==="invalid_key")r({issues:s.issues});else if(s.code==="invalid_element")r({issues:s.issues});else if(s.path.length===0)a._errors.push(n(s));else{let i=a,l=0;for(;l<s.path.length;){let d=s.path[l];l===s.path.length-1?(i[d]=i[d]||{_errors:[]},i[d]._errors.push(n(s))):i[d]=i[d]||{_errors:[]},i=i[d],l++}}};return r(t),a}var ni=t=>(e,n,a,r)=>{let o=a?Object.assign(a,{async:!1}):{async:!1},s=e._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new St;if(s.issues.length){let i=new(r?.Err??t)(s.issues.map(l=>st(l,o,Ve())));throw Zr(i,r?.callee),i}return s.value},ai=ni(ka),ri=t=>async(e,n,a,r)=>{let o=a?Object.assign(a,{async:!0}):{async:!0},s=e._zod.run({value:n,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){let i=new(r?.Err??t)(s.issues.map(l=>st(l,o,Ve())));throw Zr(i,r?.callee),i}return s.value},oi=ri(ka),si=t=>(e,n,a)=>{let r=a?{...a,async:!1}:{async:!1},o=e._zod.run({value:n,issues:[]},r);if(o instanceof Promise)throw new St;return o.issues.length?{success:!1,error:new(t??Vr)(o.issues.map(s=>st(s,r,Ve())))}:{success:!0,data:o.value}},En=si(ka),ii=t=>async(e,n,a)=>{let r=a?Object.assign(a,{async:!0}):{async:!0},o=e._zod.run({value:n,issues:[]},r);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new t(o.issues.map(s=>st(s,r,Ve())))}:{success:!0,data:o.value}},Tn=ii(ka);u();u();u();var Hu=/^[cC][^\s-]{8,}$/,Yu=/^[0-9a-z]+$/,Ku=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Ju=/^[0-9a-vA-V]{20}$/,Xu=/^[A-Za-z0-9]{27}$/,Qu=/^[a-zA-Z0-9_-]{21}$/,eh=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var th=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,ci=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;var nh=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var JE="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function ah(){return new RegExp(JE,"u")}var rh=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,oh=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,sh=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,ih=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,ch=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,li=/^[A-Za-z0-9_-]*$/,lh=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var dh=/^\+(?:[0-9]){6,14}[0-9]$/,uh="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",hh=new RegExp(`^${uh}$`);function ph(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function mh(t){return new RegExp(`^${ph(t)}$`)}function fh(t){let e=ph({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-]\\d{2}:\\d{2})");let a=`${e}(?:${n.join("|")})`;return new RegExp(`^${uh}T(?:${a})$`)}var _h=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var gh=/^\d+$/,yh=/^-?\d+(?:\.\d+)?/i,Eh=/true|false/i,Th=/null/i;var bh=/^[^A-Z]*$/,wh=/^[^a-z]*$/;var Ie=b("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),Ah={number:"number",bigint:"bigint",object:"date"},di=b("$ZodCheckLessThan",(t,e)=>{Ie.init(t,e);let n=Ah[typeof e.value];t._zod.onattach.push(a=>{let r=a._zod.bag,o=(e.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<o&&(e.inclusive?r.maximum=e.value:r.exclusiveMaximum=e.value)}),t._zod.check=a=>{(e.inclusive?a.value<=e.value:a.value<e.value)||a.issues.push({origin:n,code:"too_big",maximum:e.value,input:a.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),ui=b("$ZodCheckGreaterThan",(t,e)=>{Ie.init(t,e);let n=Ah[typeof e.value];t._zod.onattach.push(a=>{let r=a._zod.bag,o=(e.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>o&&(e.inclusive?r.minimum=e.value:r.exclusiveMinimum=e.value)}),t._zod.check=a=>{(e.inclusive?a.value>=e.value:a.value>e.value)||a.issues.push({origin:n,code:"too_small",minimum:e.value,input:a.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Ih=b("$ZodCheckMultipleOf",(t,e)=>{Ie.init(t,e),t._zod.onattach.push(n=>{var a;(a=n._zod.bag).multipleOf??(a.multipleOf=e.value)}),t._zod.check=n=>{if(typeof n.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):Ws(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:t,continue:!e.abort})}}),vh=b("$ZodCheckNumberFormat",(t,e)=>{Ie.init(t,e),e.format=e.format||"float64";let n=e.format?.includes("int"),a=n?"int":"number",[r,o]=Xs[e.format];t._zod.onattach.push(s=>{let i=s._zod.bag;i.format=e.format,i.minimum=r,i.maximum=o,n&&(i.pattern=gh)}),t._zod.check=s=>{let i=s.value;if(n){if(!Number.isInteger(i)){s.issues.push({expected:a,format:e.format,code:"invalid_type",input:i,inst:t});return}if(!Number.isSafeInteger(i)){i>0?s.issues.push({input:i,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:a,continue:!e.abort}):s.issues.push({input:i,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:a,continue:!e.abort});return}}i<r&&s.issues.push({origin:"number",input:i,code:"too_small",minimum:r,inclusive:!0,inst:t,continue:!e.abort}),i>o&&s.issues.push({origin:"number",input:i,code:"too_big",maximum:o,inst:t})}});var Oh=b("$ZodCheckMaxLength",(t,e)=>{var n;Ie.init(t,e),(n=t._zod.def).when??(n.when=a=>{let r=a.value;return!Da(r)&&r.length!==void 0}),t._zod.onattach.push(a=>{let r=a._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<r&&(a._zod.bag.maximum=e.maximum)}),t._zod.check=a=>{let r=a.value;if(r.length<=e.maximum)return;let s=La(r);a.issues.push({origin:s,code:"too_big",maximum:e.maximum,inclusive:!0,input:r,inst:t,continue:!e.abort})}}),Sh=b("$ZodCheckMinLength",(t,e)=>{var n;Ie.init(t,e),(n=t._zod.def).when??(n.when=a=>{let r=a.value;return!Da(r)&&r.length!==void 0}),t._zod.onattach.push(a=>{let r=a._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>r&&(a._zod.bag.minimum=e.minimum)}),t._zod.check=a=>{let r=a.value;if(r.length>=e.minimum)return;let s=La(r);a.issues.push({origin:s,code:"too_small",minimum:e.minimum,inclusive:!0,input:r,inst:t,continue:!e.abort})}}),Nh=b("$ZodCheckLengthEquals",(t,e)=>{var n;Ie.init(t,e),(n=t._zod.def).when??(n.when=a=>{let r=a.value;return!Da(r)&&r.length!==void 0}),t._zod.onattach.push(a=>{let r=a._zod.bag;r.minimum=e.length,r.maximum=e.length,r.length=e.length}),t._zod.check=a=>{let r=a.value,o=r.length;if(o===e.length)return;let s=La(r),i=o>e.length;a.issues.push({origin:s,...i?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:a.value,inst:t,continue:!e.abort})}}),xa=b("$ZodCheckStringFormat",(t,e)=>{var n,a;Ie.init(t,e),t._zod.onattach.push(r=>{let o=r._zod.bag;o.format=e.format,e.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(e.pattern))}),e.pattern?(n=t._zod).check??(n.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:e.format,input:r.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(a=t._zod).check??(a.check=()=>{})}),Ph=b("$ZodCheckRegex",(t,e)=>{xa.init(t,e),t._zod.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Ch=b("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=bh),xa.init(t,e)}),Dh=b("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=wh),xa.init(t,e)}),Rh=b("$ZodCheckIncludes",(t,e)=>{Ie.init(t,e);let n=Mt(e.includes),a=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=a,t._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(a)}),t._zod.check=r=>{r.value.includes(e.includes,e.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:r.value,inst:t,continue:!e.abort})}}),Lh=b("$ZodCheckStartsWith",(t,e)=>{Ie.init(t,e);let n=new RegExp(`^${Mt(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(a=>{let r=a._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),t._zod.check=a=>{a.value.startsWith(e.prefix)||a.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:a.value,inst:t,continue:!e.abort})}}),kh=b("$ZodCheckEndsWith",(t,e)=>{Ie.init(t,e);let n=new RegExp(`.*${Mt(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(a=>{let r=a._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),t._zod.check=a=>{a.value.endsWith(e.suffix)||a.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:a.value,inst:t,continue:!e.abort})}});var xh=b("$ZodCheckOverwrite",(t,e)=>{Ie.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});u();var Hr=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let a=e.split(`
|
|
12
|
+
`).filter(s=>s),r=Math.min(...a.map(s=>s.length-s.trimStart().length)),o=a.map(s=>s.slice(r)).map(s=>" ".repeat(this.indent*2)+s);for(let s of o)this.content.push(s)}compile(){let e=Function,n=this?.args,r=[...(this?.content??[""]).map(o=>` ${o}`)];return new e(...n,r.join(`
|
|
13
|
+
`))}};u();var Uh={major:4,minor:0,patch:0};var ae=b("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Uh;let a=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&a.unshift(t);for(let r of a)for(let o of r._zod.onattach)o(t);if(a.length===0)(n=t._zod).deferred??(n.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let r=(o,s,i)=>{let l=yn(o),d;for(let h of s){if(h._zod.def.when){if(!h._zod.def.when(o))continue}else if(l)continue;let p=o.issues.length,g=h._zod.check(o);if(g instanceof Promise&&i?.async===!1)throw new St;if(d||g instanceof Promise)d=(d??Promise.resolve()).then(async()=>{await g,o.issues.length!==p&&(l||(l=yn(o,p)))});else{if(o.issues.length===p)continue;l||(l=yn(o,p))}}return d?d.then(()=>o):o};t._zod.run=(o,s)=>{let i=t._zod.parse(o,s);if(i instanceof Promise){if(s.async===!1)throw new St;return i.then(l=>r(l,a,s))}return r(i,a,s)}}t["~standard"]={validate:r=>{try{let o=En(t,r);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return Tn(t,r).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}}),$a=b("$ZodString",(t,e)=>{ae.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??_h(t._zod.bag),t._zod.parse=(n,a)=>{if(e.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:t}),n}}),ie=b("$ZodStringFormat",(t,e)=>{xa.init(t,e),$a.init(t,e)}),pi=b("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=th),ie.init(t,e)}),mi=b("$ZodUUID",(t,e)=>{if(e.version){let a={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(a===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=ci(a))}else e.pattern??(e.pattern=ci());ie.init(t,e)}),fi=b("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=nh),ie.init(t,e)}),_i=b("$ZodURL",(t,e)=>{ie.init(t,e),t._zod.check=n=>{try{let a=n.value,r=new URL(a),o=r.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(r.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:lh.source,input:n.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(r.protocol.endsWith(":")?r.protocol.slice(0,-1):r.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:n.value,inst:t,continue:!e.abort})),!a.endsWith("/")&&o.endsWith("/")?n.value=o.slice(0,-1):n.value=o;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!e.abort})}}}),gi=b("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=ah()),ie.init(t,e)}),yi=b("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Qu),ie.init(t,e)}),Ei=b("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Hu),ie.init(t,e)}),Ti=b("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Yu),ie.init(t,e)}),bi=b("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Ku),ie.init(t,e)}),wi=b("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Ju),ie.init(t,e)}),Ai=b("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Xu),ie.init(t,e)}),Wh=b("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=fh(e)),ie.init(t,e)}),Hh=b("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=hh),ie.init(t,e)}),Yh=b("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=mh(e)),ie.init(t,e)}),Kh=b("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=eh),ie.init(t,e)}),Ii=b("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=rh),ie.init(t,e),t._zod.onattach.push(n=>{let a=n._zod.bag;a.format="ipv4"})}),vi=b("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=oh),ie.init(t,e),t._zod.onattach.push(n=>{let a=n._zod.bag;a.format="ipv6"}),t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!e.abort})}}}),Oi=b("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=sh),ie.init(t,e)}),Si=b("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=ih),ie.init(t,e),t._zod.check=n=>{let[a,r]=n.value.split("/");try{if(!r)throw new Error;let o=Number(r);if(`${o}`!==r)throw new Error;if(o<0||o>128)throw new Error;new URL(`http://[${a}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:t,continue:!e.abort})}}});function Jh(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var Ni=b("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=ch),ie.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),t._zod.check=n=>{Jh(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function XE(t){if(!li.test(t))return!1;let e=t.replace(/[-_]/g,a=>a==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return Jh(n)}var Pi=b("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=li),ie.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),t._zod.check=n=>{XE(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),Ci=b("$ZodE164",(t,e)=>{e.pattern??(e.pattern=dh),ie.init(t,e)});function QE(t,e=null){try{let n=t.split(".");if(n.length!==3)return!1;let[a]=n;if(!a)return!1;let r=JSON.parse(atob(a));return!("typ"in r&&r?.typ!=="JWT"||!r.alg||e&&(!("alg"in r)||r.alg!==e))}catch{return!1}}var Di=b("$ZodJWT",(t,e)=>{ie.init(t,e),t._zod.check=n=>{QE(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}});var Kr=b("$ZodNumber",(t,e)=>{ae.init(t,e),t._zod.pattern=t._zod.bag.pattern??yh,t._zod.parse=(n,a)=>{if(e.coerce)try{n.value=Number(n.value)}catch{}let r=n.value;if(typeof r=="number"&&!Number.isNaN(r)&&Number.isFinite(r))return n;let o=typeof r=="number"?Number.isNaN(r)?"NaN":Number.isFinite(r)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:r,inst:t,...o?{received:o}:{}}),n}}),Ri=b("$ZodNumber",(t,e)=>{vh.init(t,e),Kr.init(t,e)}),Li=b("$ZodBoolean",(t,e)=>{ae.init(t,e),t._zod.pattern=Eh,t._zod.parse=(n,a)=>{if(e.coerce)try{n.value=!!n.value}catch{}let r=n.value;return typeof r=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:r,inst:t}),n}});var ki=b("$ZodNull",(t,e)=>{ae.init(t,e),t._zod.pattern=Th,t._zod.values=new Set([null]),t._zod.parse=(n,a)=>{let r=n.value;return r===null||n.issues.push({expected:"null",code:"invalid_type",input:r,inst:t}),n}});var xi=b("$ZodUnknown",(t,e)=>{ae.init(t,e),t._zod.parse=n=>n}),$i=b("$ZodNever",(t,e)=>{ae.init(t,e),t._zod.parse=(n,a)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)});function Mh(t,e,n){t.issues.length&&e.issues.push(...gt(n,t.issues)),e.value[n]=t.value}var Ui=b("$ZodArray",(t,e)=>{ae.init(t,e),t._zod.parse=(n,a)=>{let r=n.value;if(!Array.isArray(r))return n.issues.push({expected:"array",code:"invalid_type",input:r,inst:t}),n;n.value=Array(r.length);let o=[];for(let s=0;s<r.length;s++){let i=r[s],l=e.element._zod.run({value:i,issues:[]},a);l instanceof Promise?o.push(l.then(d=>Mh(d,n,s))):Mh(l,n,s)}return o.length?Promise.all(o).then(()=>n):n}});function Yr(t,e,n){t.issues.length&&e.issues.push(...gt(n,t.issues)),e.value[n]=t.value}function zh(t,e,n,a){t.issues.length?a[n]===void 0?n in a?e.value[n]=void 0:e.value[n]=t.value:e.issues.push(...gt(n,t.issues)):t.value===void 0?n in a&&(e.value[n]=void 0):e.value[n]=t.value}var Jr=b("$ZodObject",(t,e)=>{ae.init(t,e);let n=Ca(()=>{let p=Object.keys(e.shape);for(let f of p)if(!(e.shape[f]instanceof ae))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);let g=Js(e.shape);return{shape:e.shape,keys:p,keySet:new Set(p),numKeys:p.length,optionalKeys:new Set(g)}});se(t._zod,"propValues",()=>{let p=e.shape,g={};for(let f in p){let m=p[f]._zod;if(m.values){g[f]??(g[f]=new Set);for(let y of m.values)g[f].add(y)}}return g});let a=p=>{let g=new Hr(["shape","payload","ctx"]),f=n.value,m=I=>{let O=gn(I);return`shape[${O}]._zod.run({ value: input[${O}], issues: [] }, ctx)`};g.write("const input = payload.value;");let y=Object.create(null),T=0;for(let I of f.keys)y[I]=`key_${T++}`;g.write("const newResult = {}");for(let I of f.keys)if(f.optionalKeys.has(I)){let O=y[I];g.write(`const ${O} = ${m(I)};`);let D=gn(I);g.write(`
|
|
14
|
+
if (${O}.issues.length) {
|
|
15
|
+
if (input[${D}] === undefined) {
|
|
16
|
+
if (${D} in input) {
|
|
17
|
+
newResult[${D}] = undefined;
|
|
18
|
+
}
|
|
19
|
+
} else {
|
|
20
|
+
payload.issues = payload.issues.concat(
|
|
21
|
+
${O}.issues.map((iss) => ({
|
|
22
|
+
...iss,
|
|
23
|
+
path: iss.path ? [${D}, ...iss.path] : [${D}],
|
|
24
|
+
}))
|
|
25
|
+
);
|
|
26
|
+
}
|
|
27
|
+
} else if (${O}.value === undefined) {
|
|
28
|
+
if (${D} in input) newResult[${D}] = undefined;
|
|
29
|
+
} else {
|
|
30
|
+
newResult[${D}] = ${O}.value;
|
|
31
|
+
}
|
|
32
|
+
`)}else{let O=y[I];g.write(`const ${O} = ${m(I)};`),g.write(`
|
|
33
|
+
if (${O}.issues.length) payload.issues = payload.issues.concat(${O}.issues.map(iss => ({
|
|
34
|
+
...iss,
|
|
35
|
+
path: iss.path ? [${gn(I)}, ...iss.path] : [${gn(I)}]
|
|
36
|
+
})));`),g.write(`newResult[${gn(I)}] = ${O}.value`)}g.write("payload.value = newResult;"),g.write("return payload;");let w=g.compile();return(I,O)=>w(p,I,O)},r,o=Yn,s=!jr.jitless,l=s&&Ys.value,d=e.catchall,h;t._zod.parse=(p,g)=>{h??(h=n.value);let f=p.value;if(!o(f))return p.issues.push({expected:"object",code:"invalid_type",input:f,inst:t}),p;let m=[];if(s&&l&&g?.async===!1&&g.jitless!==!0)r||(r=a(e.shape)),p=r(p,g);else{p.value={};let O=h.shape;for(let D of h.keys){let U=O[D],Le=U._zod.run({value:f[D],issues:[]},g),Ye=U._zod.optin==="optional"&&U._zod.optout==="optional";Le instanceof Promise?m.push(Le.then(Mn=>Ye?zh(Mn,p,D,f):Yr(Mn,p,D))):Ye?zh(Le,p,D,f):Yr(Le,p,D)}}if(!d)return m.length?Promise.all(m).then(()=>p):p;let y=[],T=h.keySet,w=d._zod,I=w.def.type;for(let O of Object.keys(f)){if(T.has(O))continue;if(I==="never"){y.push(O);continue}let D=w.run({value:f[O],issues:[]},g);D instanceof Promise?m.push(D.then(U=>Yr(U,p,O))):Yr(D,p,O)}return y.length&&p.issues.push({code:"unrecognized_keys",keys:y,input:f,inst:t}),m.length?Promise.all(m).then(()=>p):p}});function Fh(t,e,n,a){for(let r of t)if(r.issues.length===0)return e.value=r.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:t.map(r=>r.issues.map(o=>st(o,a,Ve())))}),e}var Xr=b("$ZodUnion",(t,e)=>{ae.init(t,e),se(t._zod,"optin",()=>e.options.some(n=>n._zod.optin==="optional")?"optional":void 0),se(t._zod,"optout",()=>e.options.some(n=>n._zod.optout==="optional")?"optional":void 0),se(t._zod,"values",()=>{if(e.options.every(n=>n._zod.values))return new Set(e.options.flatMap(n=>Array.from(n._zod.values)))}),se(t._zod,"pattern",()=>{if(e.options.every(n=>n._zod.pattern)){let n=e.options.map(a=>a._zod.pattern);return new RegExp(`^(${n.map(a=>Ra(a.source)).join("|")})$`)}}),t._zod.parse=(n,a)=>{let r=!1,o=[];for(let s of e.options){let i=s._zod.run({value:n.value,issues:[]},a);if(i instanceof Promise)o.push(i),r=!0;else{if(i.issues.length===0)return i;o.push(i)}}return r?Promise.all(o).then(s=>Fh(s,n,t,a)):Fh(o,n,t,a)}}),Mi=b("$ZodDiscriminatedUnion",(t,e)=>{Xr.init(t,e);let n=t._zod.parse;se(t._zod,"propValues",()=>{let r={};for(let o of e.options){let s=o._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(let[i,l]of Object.entries(s)){r[i]||(r[i]=new Set);for(let d of l)r[i].add(d)}}return r});let a=Ca(()=>{let r=e.options,o=new Map;for(let s of r){let i=s._zod.propValues[e.discriminator];if(!i||i.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let l of i){if(o.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);o.set(l,s)}}return o});t._zod.parse=(r,o)=>{let s=r.value;if(!Yn(s))return r.issues.push({code:"invalid_type",expected:"object",input:s,inst:t}),r;let i=a.value.get(s?.[e.discriminator]);return i?i._zod.run(r,o):e.unionFallback?n(r,o):(r.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:s,path:[e.discriminator],inst:t}),r)}}),zi=b("$ZodIntersection",(t,e)=>{ae.init(t,e),t._zod.parse=(n,a)=>{let r=n.value,o=e.left._zod.run({value:r,issues:[]},a),s=e.right._zod.run({value:r,issues:[]},a);return o instanceof Promise||s instanceof Promise?Promise.all([o,s]).then(([l,d])=>Gh(n,l,d)):Gh(n,o,s)}});function hi(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Kn(t)&&Kn(e)){let n=Object.keys(e),a=Object.keys(t).filter(o=>n.indexOf(o)!==-1),r={...t,...e};for(let o of a){let s=hi(t[o],e[o]);if(!s.valid)return{valid:!1,mergeErrorPath:[o,...s.mergeErrorPath]};r[o]=s.data}return{valid:!0,data:r}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let a=0;a<t.length;a++){let r=t[a],o=e[a],s=hi(r,o);if(!s.valid)return{valid:!1,mergeErrorPath:[a,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Gh(t,e,n){if(e.issues.length&&t.issues.push(...e.issues),n.issues.length&&t.issues.push(...n.issues),yn(t))return t;let a=hi(e.value,n.value);if(!a.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return t.value=a.data,t}var Fi=b("$ZodRecord",(t,e)=>{ae.init(t,e),t._zod.parse=(n,a)=>{let r=n.value;if(!Kn(r))return n.issues.push({expected:"record",code:"invalid_type",input:r,inst:t}),n;let o=[];if(e.keyType._zod.values){let s=e.keyType._zod.values;n.value={};for(let l of s)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){let d=e.valueType._zod.run({value:r[l],issues:[]},a);d instanceof Promise?o.push(d.then(h=>{h.issues.length&&n.issues.push(...gt(l,h.issues)),n.value[l]=h.value})):(d.issues.length&&n.issues.push(...gt(l,d.issues)),n.value[l]=d.value)}let i;for(let l in r)s.has(l)||(i=i??[],i.push(l));i&&i.length>0&&n.issues.push({code:"unrecognized_keys",input:r,inst:t,keys:i})}else{n.value={};for(let s of Reflect.ownKeys(r)){if(s==="__proto__")continue;let i=e.keyType._zod.run({value:s,issues:[]},a);if(i instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(i.issues.length){n.issues.push({origin:"record",code:"invalid_key",issues:i.issues.map(d=>st(d,a,Ve())),input:s,path:[s],inst:t}),n.value[i.value]=i.value;continue}let l=e.valueType._zod.run({value:r[s],issues:[]},a);l instanceof Promise?o.push(l.then(d=>{d.issues.length&&n.issues.push(...gt(s,d.issues)),n.value[i.value]=d.value})):(l.issues.length&&n.issues.push(...gt(s,l.issues)),n.value[i.value]=l.value)}}return o.length?Promise.all(o).then(()=>n):n}});var Gi=b("$ZodEnum",(t,e)=>{ae.init(t,e);let n=Pa(e.entries);t._zod.values=new Set(n),t._zod.pattern=new RegExp(`^(${n.filter(a=>Ks.has(typeof a)).map(a=>typeof a=="string"?Mt(a):a.toString()).join("|")})$`),t._zod.parse=(a,r)=>{let o=a.value;return t._zod.values.has(o)||a.issues.push({code:"invalid_value",values:n,input:o,inst:t}),a}}),ji=b("$ZodLiteral",(t,e)=>{ae.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(n=>typeof n=="string"?Mt(n):n?n.toString():String(n)).join("|")})$`),t._zod.parse=(n,a)=>{let r=n.value;return t._zod.values.has(r)||n.issues.push({code:"invalid_value",values:e.values,input:r,inst:t}),n}});var Bi=b("$ZodTransform",(t,e)=>{ae.init(t,e),t._zod.parse=(n,a)=>{let r=e.transform(n.value,n);if(a.async)return(r instanceof Promise?r:Promise.resolve(r)).then(s=>(n.value=s,n));if(r instanceof Promise)throw new St;return n.value=r,n}}),Zi=b("$ZodOptional",(t,e)=>{ae.init(t,e),t._zod.optin="optional",t._zod.optout="optional",se(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),se(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${Ra(n.source)})?$`):void 0}),t._zod.parse=(n,a)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(n,a):n.value===void 0?n:e.innerType._zod.run(n,a)}),qi=b("$ZodNullable",(t,e)=>{ae.init(t,e),se(t._zod,"optin",()=>e.innerType._zod.optin),se(t._zod,"optout",()=>e.innerType._zod.optout),se(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${Ra(n.source)}|null)$`):void 0}),se(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(n,a)=>n.value===null?n:e.innerType._zod.run(n,a)}),Vi=b("$ZodDefault",(t,e)=>{ae.init(t,e),t._zod.optin="optional",se(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,a)=>{if(n.value===void 0)return n.value=e.defaultValue,n;let r=e.innerType._zod.run(n,a);return r instanceof Promise?r.then(o=>jh(o,e)):jh(r,e)}});function jh(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var Wi=b("$ZodPrefault",(t,e)=>{ae.init(t,e),t._zod.optin="optional",se(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,a)=>(n.value===void 0&&(n.value=e.defaultValue),e.innerType._zod.run(n,a))}),Hi=b("$ZodNonOptional",(t,e)=>{ae.init(t,e),se(t._zod,"values",()=>{let n=e.innerType._zod.values;return n?new Set([...n].filter(a=>a!==void 0)):void 0}),t._zod.parse=(n,a)=>{let r=e.innerType._zod.run(n,a);return r instanceof Promise?r.then(o=>Bh(o,t)):Bh(r,t)}});function Bh(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}var Yi=b("$ZodCatch",(t,e)=>{ae.init(t,e),t._zod.optin="optional",se(t._zod,"optout",()=>e.innerType._zod.optout),se(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,a)=>{let r=e.innerType._zod.run(n,a);return r instanceof Promise?r.then(o=>(n.value=o.value,o.issues.length&&(n.value=e.catchValue({...n,error:{issues:o.issues.map(s=>st(s,a,Ve()))},input:n.value}),n.issues=[]),n)):(n.value=r.value,r.issues.length&&(n.value=e.catchValue({...n,error:{issues:r.issues.map(o=>st(o,a,Ve()))},input:n.value}),n.issues=[]),n)}});var Ki=b("$ZodPipe",(t,e)=>{ae.init(t,e),se(t._zod,"values",()=>e.in._zod.values),se(t._zod,"optin",()=>e.in._zod.optin),se(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(n,a)=>{let r=e.in._zod.run(n,a);return r instanceof Promise?r.then(o=>Zh(o,e,a)):Zh(r,e,a)}});function Zh(t,e,n){return yn(t)?t:e.out._zod.run({value:t.value,issues:t.issues},n)}var Ji=b("$ZodReadonly",(t,e)=>{ae.init(t,e),se(t._zod,"propValues",()=>e.innerType._zod.propValues),se(t._zod,"values",()=>e.innerType._zod.values),se(t._zod,"optin",()=>e.innerType._zod.optin),se(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(n,a)=>{let r=e.innerType._zod.run(n,a);return r instanceof Promise?r.then(qh):qh(r)}});function qh(t){return t.value=Object.freeze(t.value),t}var Xi=b("$ZodCustom",(t,e)=>{Ie.init(t,e),ae.init(t,e),t._zod.parse=(n,a)=>n,t._zod.check=n=>{let a=n.value,r=e.fn(a);if(r instanceof Promise)return r.then(o=>Vh(o,n,a,t));Vh(r,n,a,t)}});function Vh(t,e,n,a){if(!t){let r={code:"custom",input:n,inst:a,path:[...a._zod.def.path??[]],continue:!a._zod.def.abort};a._zod.def.params&&(r.params=a._zod.def.params),e.issues.push(Qs(r))}}u();var eT=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},tT=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(a){return t[a]??null}let n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return a=>{switch(a.code){case"invalid_type":return`Invalid input: expected ${a.expected}, received ${eT(a.input)}`;case"invalid_value":return a.values.length===1?`Invalid input: expected ${qr(a.values[0])}`:`Invalid option: expected one of ${Br(a.values,"|")}`;case"too_big":{let r=a.inclusive?"<=":"<",o=e(a.origin);return o?`Too big: expected ${a.origin??"value"} to have ${r}${a.maximum.toString()} ${o.unit??"elements"}`:`Too big: expected ${a.origin??"value"} to be ${r}${a.maximum.toString()}`}case"too_small":{let r=a.inclusive?">=":">",o=e(a.origin);return o?`Too small: expected ${a.origin} to have ${r}${a.minimum.toString()} ${o.unit}`:`Too small: expected ${a.origin} to be ${r}${a.minimum.toString()}`}case"invalid_format":{let r=a;return r.format==="starts_with"?`Invalid string: must start with "${r.prefix}"`:r.format==="ends_with"?`Invalid string: must end with "${r.suffix}"`:r.format==="includes"?`Invalid string: must include "${r.includes}"`:r.format==="regex"?`Invalid string: must match pattern ${r.pattern}`:`Invalid ${n[r.format]??a.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${a.divisor}`;case"unrecognized_keys":return`Unrecognized key${a.keys.length>1?"s":""}: ${Br(a.keys,", ")}`;case"invalid_key":return`Invalid key in ${a.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${a.origin}`;default:return"Invalid input"}}};function Xh(){return{localeError:tT()}}u();var nT=Symbol("ZodOutput"),aT=Symbol("ZodInput"),Ua=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...n){let a=n[0];if(this._map.set(e,a),a&&typeof a=="object"&&"id"in a){if(this._idmap.has(a.id))throw new Error(`ID ${a.id} already exists in the registry`);this._idmap.set(a.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let n=this._map.get(e);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(e),this}get(e){let n=e._zod.parent;if(n){let a={...this.get(n)??{}};return delete a.id,{...a,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};function Qh(){return new Ua}var zt=Qh();u();function Qi(t,e){return new t({type:"string",...z(e)})}function ec(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...z(e)})}function Qr(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...z(e)})}function tc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...z(e)})}function nc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...z(e)})}function ac(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...z(e)})}function rc(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...z(e)})}function oc(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...z(e)})}function sc(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...z(e)})}function ic(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...z(e)})}function cc(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...z(e)})}function lc(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...z(e)})}function dc(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...z(e)})}function uc(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...z(e)})}function hc(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...z(e)})}function pc(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...z(e)})}function mc(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...z(e)})}function fc(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...z(e)})}function _c(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...z(e)})}function gc(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...z(e)})}function yc(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...z(e)})}function Ec(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...z(e)})}function Tc(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...z(e)})}function ep(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...z(e)})}function tp(t,e){return new t({type:"string",format:"date",check:"string_format",...z(e)})}function np(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...z(e)})}function ap(t,e){return new t({type:"string",format:"duration",check:"string_format",...z(e)})}function bc(t,e){return new t({type:"number",checks:[],...z(e)})}function wc(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...z(e)})}function Ac(t,e){return new t({type:"boolean",...z(e)})}function Ic(t,e){return new t({type:"null",...z(e)})}function vc(t){return new t({type:"unknown"})}function Oc(t,e){return new t({type:"never",...z(e)})}function eo(t,e){return new di({check:"less_than",...z(e),value:t,inclusive:!1})}function Ma(t,e){return new di({check:"less_than",...z(e),value:t,inclusive:!0})}function to(t,e){return new ui({check:"greater_than",...z(e),value:t,inclusive:!1})}function za(t,e){return new ui({check:"greater_than",...z(e),value:t,inclusive:!0})}function no(t,e){return new Ih({check:"multiple_of",...z(e),value:t})}function ao(t,e){return new Oh({check:"max_length",...z(e),maximum:t})}function Jn(t,e){return new Sh({check:"min_length",...z(e),minimum:t})}function ro(t,e){return new Nh({check:"length_equals",...z(e),length:t})}function Sc(t,e){return new Ph({check:"string_format",format:"regex",...z(e),pattern:t})}function Nc(t){return new Ch({check:"string_format",format:"lowercase",...z(t)})}function Pc(t){return new Dh({check:"string_format",format:"uppercase",...z(t)})}function Cc(t,e){return new Rh({check:"string_format",format:"includes",...z(e),includes:t})}function Dc(t,e){return new Lh({check:"string_format",format:"starts_with",...z(e),prefix:t})}function Rc(t,e){return new kh({check:"string_format",format:"ends_with",...z(e),suffix:t})}function bn(t){return new xh({check:"overwrite",tx:t})}function Lc(t){return bn(e=>e.normalize(t))}function kc(){return bn(t=>t.trim())}function xc(){return bn(t=>t.toLowerCase())}function $c(){return bn(t=>t.toUpperCase())}function rp(t,e,n){return new t({type:"array",element:e,...z(n)})}function Uc(t,e,n){let a=z(n);return a.abort??(a.abort=!0),new t({type:"custom",check:"custom",fn:e,...a})}function Mc(t,e,n){return new t({type:"custom",check:"custom",fn:e,...z(n)})}u();var oo=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??zt,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,n={path:[],schemaPath:[]}){var a;let r=e._zod.def,o={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},s=this.seen.get(e);if(s)return s.count++,n.schemaPath.includes(e)&&(s.cycle=n.path),s.schema;let i={schema:{},count:1,cycle:void 0,path:n.path};this.seen.set(e,i);let l=e._zod.toJSONSchema?.();if(l)i.schema=l;else{let p={...n,schemaPath:[...n.schemaPath,e],path:n.path},g=e._zod.parent;if(g)i.ref=g,this.process(g,p),this.seen.get(g).isParent=!0;else{let f=i.schema;switch(r.type){case"string":{let m=f;m.type="string";let{minimum:y,maximum:T,format:w,patterns:I,contentEncoding:O}=e._zod.bag;if(typeof y=="number"&&(m.minLength=y),typeof T=="number"&&(m.maxLength=T),w&&(m.format=o[w]??w,m.format===""&&delete m.format),O&&(m.contentEncoding=O),I&&I.size>0){let D=[...I];D.length===1?m.pattern=D[0].source:D.length>1&&(i.schema.allOf=[...D.map(U=>({...this.target==="draft-7"?{type:"string"}:{},pattern:U.source}))])}break}case"number":{let m=f,{minimum:y,maximum:T,format:w,multipleOf:I,exclusiveMaximum:O,exclusiveMinimum:D}=e._zod.bag;typeof w=="string"&&w.includes("int")?m.type="integer":m.type="number",typeof D=="number"&&(m.exclusiveMinimum=D),typeof y=="number"&&(m.minimum=y,typeof D=="number"&&(D>=y?delete m.minimum:delete m.exclusiveMinimum)),typeof O=="number"&&(m.exclusiveMaximum=O),typeof T=="number"&&(m.maximum=T,typeof O=="number"&&(O<=T?delete m.maximum:delete m.exclusiveMaximum)),typeof I=="number"&&(m.multipleOf=I);break}case"boolean":{let m=f;m.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{f.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{f.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let m=f,{minimum:y,maximum:T}=e._zod.bag;typeof y=="number"&&(m.minItems=y),typeof T=="number"&&(m.maxItems=T),m.type="array",m.items=this.process(r.element,{...p,path:[...p.path,"items"]});break}case"object":{let m=f;m.type="object",m.properties={};let y=r.shape;for(let I in y)m.properties[I]=this.process(y[I],{...p,path:[...p.path,"properties",I]});let T=new Set(Object.keys(y)),w=new Set([...T].filter(I=>{let O=r.shape[I]._zod;return this.io==="input"?O.optin===void 0:O.optout===void 0}));w.size>0&&(m.required=Array.from(w)),r.catchall?._zod.def.type==="never"?m.additionalProperties=!1:r.catchall?r.catchall&&(m.additionalProperties=this.process(r.catchall,{...p,path:[...p.path,"additionalProperties"]})):this.io==="output"&&(m.additionalProperties=!1);break}case"union":{let m=f;m.anyOf=r.options.map((y,T)=>this.process(y,{...p,path:[...p.path,"anyOf",T]}));break}case"intersection":{let m=f,y=this.process(r.left,{...p,path:[...p.path,"allOf",0]}),T=this.process(r.right,{...p,path:[...p.path,"allOf",1]}),w=O=>"allOf"in O&&Object.keys(O).length===1,I=[...w(y)?y.allOf:[y],...w(T)?T.allOf:[T]];m.allOf=I;break}case"tuple":{let m=f;m.type="array";let y=r.items.map((I,O)=>this.process(I,{...p,path:[...p.path,"prefixItems",O]}));if(this.target==="draft-2020-12"?m.prefixItems=y:m.items=y,r.rest){let I=this.process(r.rest,{...p,path:[...p.path,"items"]});this.target==="draft-2020-12"?m.items=I:m.additionalItems=I}r.rest&&(m.items=this.process(r.rest,{...p,path:[...p.path,"items"]}));let{minimum:T,maximum:w}=e._zod.bag;typeof T=="number"&&(m.minItems=T),typeof w=="number"&&(m.maxItems=w);break}case"record":{let m=f;m.type="object",m.propertyNames=this.process(r.keyType,{...p,path:[...p.path,"propertyNames"]}),m.additionalProperties=this.process(r.valueType,{...p,path:[...p.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let m=f,y=Pa(r.entries);y.every(T=>typeof T=="number")&&(m.type="number"),y.every(T=>typeof T=="string")&&(m.type="string"),m.enum=y;break}case"literal":{let m=f,y=[];for(let T of r.values)if(T===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof T=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");y.push(Number(T))}else y.push(T);if(y.length!==0)if(y.length===1){let T=y[0];m.type=T===null?"null":typeof T,m.const=T}else y.every(T=>typeof T=="number")&&(m.type="number"),y.every(T=>typeof T=="string")&&(m.type="string"),y.every(T=>typeof T=="boolean")&&(m.type="string"),y.every(T=>T===null)&&(m.type="null"),m.enum=y;break}case"file":{let m=f,y={type:"string",format:"binary",contentEncoding:"binary"},{minimum:T,maximum:w,mime:I}=e._zod.bag;T!==void 0&&(y.minLength=T),w!==void 0&&(y.maxLength=w),I?I.length===1?(y.contentMediaType=I[0],Object.assign(m,y)):m.anyOf=I.map(O=>({...y,contentMediaType:O})):Object.assign(m,y);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let m=this.process(r.innerType,p);f.anyOf=[m,{type:"null"}];break}case"nonoptional":{this.process(r.innerType,p),i.ref=r.innerType;break}case"success":{let m=f;m.type="boolean";break}case"default":{this.process(r.innerType,p),i.ref=r.innerType,f.default=JSON.parse(JSON.stringify(r.defaultValue));break}case"prefault":{this.process(r.innerType,p),i.ref=r.innerType,this.io==="input"&&(f._prefault=JSON.parse(JSON.stringify(r.defaultValue)));break}case"catch":{this.process(r.innerType,p),i.ref=r.innerType;let m;try{m=r.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}f.default=m;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let m=f,y=e._zod.pattern;if(!y)throw new Error("Pattern not found in template literal");m.type="string",m.pattern=y.source;break}case"pipe":{let m=this.io==="input"?r.in._zod.def.type==="transform"?r.out:r.in:r.out;this.process(m,p),i.ref=m;break}case"readonly":{this.process(r.innerType,p),i.ref=r.innerType,f.readOnly=!0;break}case"promise":{this.process(r.innerType,p),i.ref=r.innerType;break}case"optional":{this.process(r.innerType,p),i.ref=r.innerType;break}case"lazy":{let m=e._zod.innerType;this.process(m,p),i.ref=m;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let d=this.metadataRegistry.get(e);return d&&Object.assign(i.schema,d),this.io==="input"&&Ee(e)&&(delete i.schema.examples,delete i.schema.default),this.io==="input"&&i.schema._prefault&&((a=i.schema).default??(a.default=i.schema._prefault)),delete i.schema._prefault,this.seen.get(e).schema}emit(e,n){let a={cycles:n?.cycles??"ref",reused:n?.reused??"inline",external:n?.external??void 0},r=this.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=h=>{let p=this.target==="draft-2020-12"?"$defs":"definitions";if(a.external){let y=a.external.registry.get(h[0])?.id,T=a.external.uri??(I=>I);if(y)return{ref:T(y)};let w=h[1].defId??h[1].schema.id??`schema${this.counter++}`;return h[1].defId=w,{defId:w,ref:`${T("__shared")}#/${p}/${w}`}}if(h[1]===r)return{ref:"#"};let f=`#/${p}/`,m=h[1].schema.id??`__schema${this.counter++}`;return{defId:m,ref:f+m}},s=h=>{if(h[1].schema.$ref)return;let p=h[1],{ref:g,defId:f}=o(h);p.def={...p.schema},f&&(p.defId=f);let m=p.schema;for(let y in m)delete m[y];m.$ref=g};if(a.cycles==="throw")for(let h of this.seen.entries()){let p=h[1];if(p.cycle)throw new Error(`Cycle detected: #/${p.cycle?.join("/")}/<root>
|
|
37
|
+
|
|
38
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let h of this.seen.entries()){let p=h[1];if(e===h[0]){s(h);continue}if(a.external){let f=a.external.registry.get(h[0])?.id;if(e!==h[0]&&f){s(h);continue}}if(this.metadataRegistry.get(h[0])?.id){s(h);continue}if(p.cycle){s(h);continue}if(p.count>1&&a.reused==="ref"){s(h);continue}}let i=(h,p)=>{let g=this.seen.get(h),f=g.def??g.schema,m={...f};if(g.ref===null)return;let y=g.ref;if(g.ref=null,y){i(y,p);let T=this.seen.get(y).schema;T.$ref&&p.target==="draft-7"?(f.allOf=f.allOf??[],f.allOf.push(T)):(Object.assign(f,T),Object.assign(f,m))}g.isParent||this.override({zodSchema:h,jsonSchema:f,path:g.path??[]})};for(let h of[...this.seen.entries()].reverse())i(h[0],{target:this.target});let l={};if(this.target==="draft-2020-12"?l.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?l.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),a.external?.uri){let h=a.external.registry.get(e)?.id;if(!h)throw new Error("Schema is missing an `id` property");l.$id=a.external.uri(h)}Object.assign(l,r.def);let d=a.external?.defs??{};for(let h of this.seen.entries()){let p=h[1];p.def&&p.defId&&(d[p.defId]=p.def)}a.external||Object.keys(d).length>0&&(this.target==="draft-2020-12"?l.$defs=d:l.definitions=d);try{return JSON.parse(JSON.stringify(l))}catch{throw new Error("Error converting schema to JSON.")}}};function zc(t,e){if(t instanceof Ua){let a=new oo(e),r={};for(let i of t._idmap.entries()){let[l,d]=i;a.process(d)}let o={},s={registry:t,uri:e?.uri,defs:r};for(let i of t._idmap.entries()){let[l,d]=i;o[l]=a.emit(d,{...e,external:s})}if(Object.keys(r).length>0){let i=a.target==="draft-2020-12"?"$defs":"definitions";o.__shared={[i]:r}}return{schemas:o}}let n=new oo(e);return n.process(t),n.emit(t,e)}function Ee(t,e){let n=e??{seen:new Set};if(n.seen.has(t))return!1;n.seen.add(t);let r=t._zod.def;switch(r.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return Ee(r.element,n);case"object":{for(let o in r.shape)if(Ee(r.shape[o],n))return!0;return!1}case"union":{for(let o of r.options)if(Ee(o,n))return!0;return!1}case"intersection":return Ee(r.left,n)||Ee(r.right,n);case"tuple":{for(let o of r.items)if(Ee(o,n))return!0;return!!(r.rest&&Ee(r.rest,n))}case"record":return Ee(r.keyType,n)||Ee(r.valueType,n);case"map":return Ee(r.keyType,n)||Ee(r.valueType,n);case"set":return Ee(r.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Ee(r.innerType,n);case"lazy":return Ee(r.getter(),n);case"default":return Ee(r.innerType,n);case"prefault":return Ee(r.innerType,n);case"custom":return!1;case"transform":return!0;case"pipe":return Ee(r.in,n)||Ee(r.out,n);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${r.type}`)}u();u();var MT=b("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");ae.init(t,e),t.def=e,t.parse=(n,a)=>ai(t,n,a,{callee:t.parse}),t.safeParse=(n,a)=>En(t,n,a),t.parseAsync=async(n,a)=>oi(t,n,a,{callee:t.parseAsync}),t.safeParseAsync=async(n,a)=>Tn(t,n,a),t.check=(...n)=>t.clone({...e,checks:[...e.checks??[],...n.map(a=>typeof a=="function"?{_zod:{check:a,def:{check:"custom"},onattach:[]}}:a)]}),t.clone=(n,a)=>We(t,n,a),t.brand=()=>t,t.register=((n,a)=>(n.add(t,a),t))});var zT=b("ZodMiniObject",(t,e)=>{Jr.init(t,e),MT.init(t,e),Y.defineLazy(t,"shape",()=>e.shape)});function Fc(t,e){let n={type:"object",get shape(){return Y.assignProp(this,"shape",{...t}),this.shape},...Y.normalizeParams(e)};return new zT(n)}function Xe(t){return!!t._zod}function An(t){let e=Object.values(t);if(e.length===0)return Fc({});let n=e.every(Xe),a=e.every(r=>!Xe(r));if(n)return Fc(t);if(a)return Bs(t);throw new Error("Mixed Zod versions detected in object shape.")}function Ft(t,e){return Xe(t)?En(t,e):t.safeParse(e)}async function so(t,e){return Xe(t)?await Tn(t,e):await t.safeParseAsync(e)}function Gt(t){if(!t)return;let e;if(Xe(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Xn(t){if(t){if(typeof t=="object"){let e=t,n=t;if(!e._def&&!n._zod){let a=Object.values(t);if(a.length>0&&a.every(r=>typeof r=="object"&&r!==null&&(r._def!==void 0||r._zod!==void 0||typeof r.parse=="function")))return An(t)}}if(Xe(t)){let n=t._zod?.def;if(n&&(n.type==="object"||n.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function io(t){if(t&&typeof t=="object"){if("message"in t&&typeof t.message=="string")return t.message;if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0){let e=t.issues[0];if(e&&typeof e=="object"&&"message"in e)return String(e.message)}try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function sp(t){return t.description}function ip(t){if(Xe(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function co(t){if(Xe(t)){let o=t._zod?.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.values[0]}}let n=t._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}let a=t.value;if(a!==void 0)return a}u();u();u();u();var Fa={};ks(Fa,{ZodISODate:()=>lp,ZodISODateTime:()=>cp,ZodISODuration:()=>up,ZodISOTime:()=>dp,date:()=>jc,datetime:()=>Gc,duration:()=>Zc,time:()=>Bc});u();var cp=b("ZodISODateTime",(t,e)=>{Wh.init(t,e),he.init(t,e)});function Gc(t){return ep(cp,t)}var lp=b("ZodISODate",(t,e)=>{Hh.init(t,e),he.init(t,e)});function jc(t){return tp(lp,t)}var dp=b("ZodISOTime",(t,e)=>{Yh.init(t,e),he.init(t,e)});function Bc(t){return np(dp,t)}var up=b("ZodISODuration",(t,e)=>{Kh.init(t,e),he.init(t,e)});function Zc(t){return ap(up,t)}u();u();var hp=(t,e)=>{Vr.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>ti(t,n)},flatten:{value:n=>ei(t,n)},addIssue:{value:n=>t.issues.push(n)},addIssues:{value:n=>t.issues.push(...n)},isEmpty:{get(){return t.issues.length===0}}})},gR=b("ZodError",hp),Ga=b("ZodError",hp,{Parent:Error});var pp=ni(Ga),mp=ri(Ga),fp=si(Ga),_p=ii(Ga);var _e=b("ZodType",(t,e)=>(ae.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...n)=>t.clone({...e,checks:[...e.checks??[],...n.map(a=>typeof a=="function"?{_zod:{check:a,def:{check:"custom"},onattach:[]}}:a)]}),t.clone=(n,a)=>We(t,n,a),t.brand=()=>t,t.register=((n,a)=>(n.add(t,a),t)),t.parse=(n,a)=>pp(t,n,a,{callee:t.parse}),t.safeParse=(n,a)=>fp(t,n,a),t.parseAsync=async(n,a)=>mp(t,n,a,{callee:t.parseAsync}),t.safeParseAsync=async(n,a)=>_p(t,n,a),t.spa=t.safeParseAsync,t.refine=(n,a)=>t.check($b(n,a)),t.superRefine=n=>t.check(Ub(n)),t.overwrite=n=>t.check(bn(n)),t.optional=()=>me(t),t.nullable=()=>Ep(t),t.nullish=()=>me(Ep(t)),t.nonoptional=n=>Pb(t,n),t.array=()=>K(t),t.or=n=>le([t,n]),t.and=n=>uo(t,n),t.transform=n=>Vc(t,vp(n)),t.default=n=>Ob(t,n),t.prefault=n=>Nb(t,n),t.catch=n=>Db(t,n),t.pipe=n=>Vc(t,n),t.readonly=()=>kb(t),t.describe=n=>{let a=t.clone();return zt.add(a,{description:n}),a},Object.defineProperty(t,"description",{get(){return zt.get(t)?.description},configurable:!0}),t.meta=(...n)=>{if(n.length===0)return zt.get(t);let a=t.clone();return zt.add(a,n[0]),a},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Tp=b("_ZodString",(t,e)=>{$a.init(t,e),_e.init(t,e);let n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,t.regex=(...a)=>t.check(Sc(...a)),t.includes=(...a)=>t.check(Cc(...a)),t.startsWith=(...a)=>t.check(Dc(...a)),t.endsWith=(...a)=>t.check(Rc(...a)),t.min=(...a)=>t.check(Jn(...a)),t.max=(...a)=>t.check(ao(...a)),t.length=(...a)=>t.check(ro(...a)),t.nonempty=(...a)=>t.check(Jn(1,...a)),t.lowercase=a=>t.check(Nc(a)),t.uppercase=a=>t.check(Pc(a)),t.trim=()=>t.check(kc()),t.normalize=(...a)=>t.check(Lc(...a)),t.toLowerCase=()=>t.check(xc()),t.toUpperCase=()=>t.check($c())}),HT=b("ZodString",(t,e)=>{$a.init(t,e),Tp.init(t,e),t.email=n=>t.check(ec(YT,n)),t.url=n=>t.check(oc(KT,n)),t.jwt=n=>t.check(Tc(ub,n)),t.emoji=n=>t.check(sc(JT,n)),t.guid=n=>t.check(Qr(gp,n)),t.uuid=n=>t.check(tc(lo,n)),t.uuidv4=n=>t.check(nc(lo,n)),t.uuidv6=n=>t.check(ac(lo,n)),t.uuidv7=n=>t.check(rc(lo,n)),t.nanoid=n=>t.check(ic(XT,n)),t.guid=n=>t.check(Qr(gp,n)),t.cuid=n=>t.check(cc(QT,n)),t.cuid2=n=>t.check(lc(eb,n)),t.ulid=n=>t.check(dc(tb,n)),t.base64=n=>t.check(gc(cb,n)),t.base64url=n=>t.check(yc(lb,n)),t.xid=n=>t.check(uc(nb,n)),t.ksuid=n=>t.check(hc(ab,n)),t.ipv4=n=>t.check(pc(rb,n)),t.ipv6=n=>t.check(mc(ob,n)),t.cidrv4=n=>t.check(fc(sb,n)),t.cidrv6=n=>t.check(_c(ib,n)),t.e164=n=>t.check(Ec(db,n)),t.datetime=n=>t.check(Gc(n)),t.date=n=>t.check(jc(n)),t.time=n=>t.check(Bc(n)),t.duration=n=>t.check(Zc(n))});function E(t){return Qi(HT,t)}var he=b("ZodStringFormat",(t,e)=>{ie.init(t,e),Tp.init(t,e)}),YT=b("ZodEmail",(t,e)=>{fi.init(t,e),he.init(t,e)});var gp=b("ZodGUID",(t,e)=>{pi.init(t,e),he.init(t,e)});var lo=b("ZodUUID",(t,e)=>{mi.init(t,e),he.init(t,e)});var KT=b("ZodURL",(t,e)=>{_i.init(t,e),he.init(t,e)});var JT=b("ZodEmoji",(t,e)=>{gi.init(t,e),he.init(t,e)});var XT=b("ZodNanoID",(t,e)=>{yi.init(t,e),he.init(t,e)});var QT=b("ZodCUID",(t,e)=>{Ei.init(t,e),he.init(t,e)});var eb=b("ZodCUID2",(t,e)=>{Ti.init(t,e),he.init(t,e)});var tb=b("ZodULID",(t,e)=>{bi.init(t,e),he.init(t,e)});var nb=b("ZodXID",(t,e)=>{wi.init(t,e),he.init(t,e)});var ab=b("ZodKSUID",(t,e)=>{Ai.init(t,e),he.init(t,e)});var rb=b("ZodIPv4",(t,e)=>{Ii.init(t,e),he.init(t,e)});var ob=b("ZodIPv6",(t,e)=>{vi.init(t,e),he.init(t,e)});var sb=b("ZodCIDRv4",(t,e)=>{Oi.init(t,e),he.init(t,e)});var ib=b("ZodCIDRv6",(t,e)=>{Si.init(t,e),he.init(t,e)});var cb=b("ZodBase64",(t,e)=>{Ni.init(t,e),he.init(t,e)});var lb=b("ZodBase64URL",(t,e)=>{Pi.init(t,e),he.init(t,e)});var db=b("ZodE164",(t,e)=>{Ci.init(t,e),he.init(t,e)});var ub=b("ZodJWT",(t,e)=>{Di.init(t,e),he.init(t,e)});var bp=b("ZodNumber",(t,e)=>{Kr.init(t,e),_e.init(t,e),t.gt=(a,r)=>t.check(to(a,r)),t.gte=(a,r)=>t.check(za(a,r)),t.min=(a,r)=>t.check(za(a,r)),t.lt=(a,r)=>t.check(eo(a,r)),t.lte=(a,r)=>t.check(Ma(a,r)),t.max=(a,r)=>t.check(Ma(a,r)),t.int=a=>t.check(yp(a)),t.safe=a=>t.check(yp(a)),t.positive=a=>t.check(to(0,a)),t.nonnegative=a=>t.check(za(0,a)),t.negative=a=>t.check(eo(0,a)),t.nonpositive=a=>t.check(Ma(0,a)),t.multipleOf=(a,r)=>t.check(no(a,r)),t.step=(a,r)=>t.check(no(a,r)),t.finite=()=>t;let n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null});function ne(t){return bc(bp,t)}var hb=b("ZodNumberFormat",(t,e)=>{Ri.init(t,e),bp.init(t,e)});function yp(t){return wc(hb,t)}var pb=b("ZodBoolean",(t,e)=>{Li.init(t,e),_e.init(t,e)});function we(t){return Ac(pb,t)}var mb=b("ZodNull",(t,e)=>{ki.init(t,e),_e.init(t,e)});function wp(t){return Ic(mb,t)}var fb=b("ZodUnknown",(t,e)=>{xi.init(t,e),_e.init(t,e)});function pe(){return vc(fb)}var _b=b("ZodNever",(t,e)=>{$i.init(t,e),_e.init(t,e)});function gb(t){return Oc(_b,t)}var yb=b("ZodArray",(t,e)=>{Ui.init(t,e),_e.init(t,e),t.element=e.element,t.min=(n,a)=>t.check(Jn(n,a)),t.nonempty=n=>t.check(Jn(1,n)),t.max=(n,a)=>t.check(ao(n,a)),t.length=(n,a)=>t.check(ro(n,a)),t.unwrap=()=>t.element});function K(t,e){return rp(yb,t,e)}var Ap=b("ZodObject",(t,e)=>{Jr.init(t,e),_e.init(t,e),Y.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Ge(Object.keys(t._zod.def.shape)),t.catchall=n=>t.clone({...t._zod.def,catchall:n}),t.passthrough=()=>t.clone({...t._zod.def,catchall:pe()}),t.loose=()=>t.clone({...t._zod.def,catchall:pe()}),t.strict=()=>t.clone({...t._zod.def,catchall:gb()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>Y.extend(t,n),t.merge=n=>Y.merge(t,n),t.pick=n=>Y.pick(t,n),t.omit=n=>Y.omit(t,n),t.partial=(...n)=>Y.partial(Op,t,n[0]),t.required=(...n)=>Y.required(Sp,t,n[0])});function C(t,e){let n={type:"object",get shape(){return Y.assignProp(this,"shape",{...t}),this.shape},...Y.normalizeParams(e)};return new Ap(n)}function ke(t,e){return new Ap({type:"object",get shape(){return Y.assignProp(this,"shape",{...t}),this.shape},catchall:pe(),...Y.normalizeParams(e)})}var Ip=b("ZodUnion",(t,e)=>{Xr.init(t,e),_e.init(t,e),t.options=e.options});function le(t,e){return new Ip({type:"union",options:t,...Y.normalizeParams(e)})}var Eb=b("ZodDiscriminatedUnion",(t,e)=>{Ip.init(t,e),Mi.init(t,e)});function Wc(t,e,n){return new Eb({type:"union",options:e,discriminator:t,...Y.normalizeParams(n)})}var Tb=b("ZodIntersection",(t,e)=>{zi.init(t,e),_e.init(t,e)});function uo(t,e){return new Tb({type:"intersection",left:t,right:e})}var bb=b("ZodRecord",(t,e)=>{Fi.init(t,e),_e.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function ce(t,e,n){return new bb({type:"record",keyType:t,valueType:e,...Y.normalizeParams(n)})}var qc=b("ZodEnum",(t,e)=>{Gi.init(t,e),_e.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let n=new Set(Object.keys(e.entries));t.extract=(a,r)=>{let o={};for(let s of a)if(n.has(s))o[s]=e.entries[s];else throw new Error(`Key ${s} not found in enum`);return new qc({...e,checks:[],...Y.normalizeParams(r),entries:o})},t.exclude=(a,r)=>{let o={...e.entries};for(let s of a)if(n.has(s))delete o[s];else throw new Error(`Key ${s} not found in enum`);return new qc({...e,checks:[],...Y.normalizeParams(r),entries:o})}});function Ge(t,e){let n=Array.isArray(t)?Object.fromEntries(t.map(a=>[a,a])):t;return new qc({type:"enum",entries:n,...Y.normalizeParams(e)})}var wb=b("ZodLiteral",(t,e)=>{ji.init(t,e),_e.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function k(t,e){return new wb({type:"literal",values:Array.isArray(t)?t:[t],...Y.normalizeParams(e)})}var Ab=b("ZodTransform",(t,e)=>{Bi.init(t,e),_e.init(t,e),t._zod.parse=(n,a)=>{n.addIssue=o=>{if(typeof o=="string")n.issues.push(Y.issue(o,n.value,e));else{let s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=t),s.continue??(s.continue=!0),n.issues.push(Y.issue(s))}};let r=e.transform(n.value,n);return r instanceof Promise?r.then(o=>(n.value=o,n)):(n.value=r,n)}});function vp(t){return new Ab({type:"transform",transform:t})}var Op=b("ZodOptional",(t,e)=>{Zi.init(t,e),_e.init(t,e),t.unwrap=()=>t._zod.def.innerType});function me(t){return new Op({type:"optional",innerType:t})}var Ib=b("ZodNullable",(t,e)=>{qi.init(t,e),_e.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Ep(t){return new Ib({type:"nullable",innerType:t})}var vb=b("ZodDefault",(t,e)=>{Vi.init(t,e),_e.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function Ob(t,e){return new vb({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var Sb=b("ZodPrefault",(t,e)=>{Wi.init(t,e),_e.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Nb(t,e){return new Sb({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var Sp=b("ZodNonOptional",(t,e)=>{Hi.init(t,e),_e.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Pb(t,e){return new Sp({type:"nonoptional",innerType:t,...Y.normalizeParams(e)})}var Cb=b("ZodCatch",(t,e)=>{Yi.init(t,e),_e.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function Db(t,e){return new Cb({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var Rb=b("ZodPipe",(t,e)=>{Ki.init(t,e),_e.init(t,e),t.in=e.in,t.out=e.out});function Vc(t,e){return new Rb({type:"pipe",in:t,out:e})}var Lb=b("ZodReadonly",(t,e)=>{Ji.init(t,e),_e.init(t,e)});function kb(t){return new Lb({type:"readonly",innerType:t})}var Np=b("ZodCustom",(t,e)=>{Xi.init(t,e),_e.init(t,e)});function xb(t){let e=new Ie({check:"custom"});return e._zod.check=t,e}function Pp(t,e){return Uc(Np,t??(()=>!0),e)}function $b(t,e={}){return Mc(Np,t,e)}function Ub(t){let e=xb(n=>(n.addIssue=a=>{if(typeof a=="string")n.issues.push(Y.issue(a,n.value,e._zod.def));else{let r=a;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=n.value),r.inst??(r.inst=e),r.continue??(r.continue=!e._zod.def.abort),n.issues.push(Y.issue(r))}},t(n.value,n)));return e}function Hc(t,e){return Vc(vp(t),e)}Ve(Xh());var Kc="2025-11-25";var Cp=[Kc,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],jt="io.modelcontextprotocol/related-task",po="2.0",Te=Pp(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Dp=le([E(),ne().int()]),Rp=E(),xR=ke({ttl:ne().optional(),pollInterval:ne().optional()}),Mb=C({ttl:ne().optional()}),zb=C({taskId:E()}),Jc=ke({progressToken:Dp.optional(),[jt]:zb.optional()}),He=C({_meta:Jc.optional()}),ja=He.extend({task:Mb.optional()}),Lp=t=>ja.safeParse(t).success,ve=C({method:E(),params:He.loose().optional()}),Qe=C({_meta:Jc.optional()}),et=C({method:E(),params:Qe.loose().optional()}),Oe=ke({_meta:Jc.optional()}),mo=le([E(),ne().int()]),kp=C({jsonrpc:k(po),id:mo,...ve.shape}).strict(),Xc=t=>kp.safeParse(t).success,xp=C({jsonrpc:k(po),...et.shape}).strict(),$p=t=>xp.safeParse(t).success,Qc=C({jsonrpc:k(po),id:mo,result:Oe}).strict(),Ba=t=>Qc.safeParse(t).success;var $;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})($||($={}));var el=C({jsonrpc:k(po),id:mo.optional(),error:C({code:ne().int(),message:E(),data:pe().optional()})}).strict();var Up=t=>el.safeParse(t).success;var $R=le([kp,xp,Qc,el]),UR=le([Qc,el]),fo=Oe.strict(),Fb=Qe.extend({requestId:mo.optional(),reason:E().optional()}),_o=et.extend({method:k("notifications/cancelled"),params:Fb}),Gb=C({src:E(),mimeType:E().optional(),sizes:K(E()).optional(),theme:Ge(["light","dark"]).optional()}),Za=C({icons:K(Gb).optional()}),Qn=C({name:E(),title:E().optional()}),Mp=Qn.extend({...Qn.shape,...Za.shape,version:E(),websiteUrl:E().optional(),description:E().optional()}),jb=uo(C({applyDefaults:we().optional()}),ce(E(),pe())),Bb=Hc(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,uo(C({form:jb.optional(),url:Te.optional()}),ce(E(),pe()).optional())),Zb=ke({list:Te.optional(),cancel:Te.optional(),requests:ke({sampling:ke({createMessage:Te.optional()}).optional(),elicitation:ke({create:Te.optional()}).optional()}).optional()}),qb=ke({list:Te.optional(),cancel:Te.optional(),requests:ke({tools:ke({call:Te.optional()}).optional()}).optional()}),Vb=C({experimental:ce(E(),Te).optional(),sampling:C({context:Te.optional(),tools:Te.optional()}).optional(),elicitation:Bb.optional(),roots:C({listChanged:we().optional()}).optional(),tasks:Zb.optional(),extensions:ce(E(),Te).optional()}),Wb=He.extend({protocolVersion:E(),capabilities:Vb,clientInfo:Mp}),tl=ve.extend({method:k("initialize"),params:Wb});var Hb=C({experimental:ce(E(),Te).optional(),logging:Te.optional(),completions:Te.optional(),prompts:C({listChanged:we().optional()}).optional(),resources:C({subscribe:we().optional(),listChanged:we().optional()}).optional(),tools:C({listChanged:we().optional()}).optional(),tasks:qb.optional(),extensions:ce(E(),Te).optional()}),Yb=Oe.extend({protocolVersion:E(),capabilities:Hb,serverInfo:Mp,instructions:E().optional()}),nl=et.extend({method:k("notifications/initialized"),params:Qe.optional()});var go=ve.extend({method:k("ping"),params:He.optional()}),Kb=C({progress:ne(),total:me(ne()),message:me(E())}),Jb=C({...Qe.shape,...Kb.shape,progressToken:Dp}),yo=et.extend({method:k("notifications/progress"),params:Jb}),Xb=He.extend({cursor:Rp.optional()}),qa=ve.extend({params:Xb.optional()}),Va=Oe.extend({nextCursor:Rp.optional()}),Qb=Ge(["working","input_required","completed","failed","cancelled"]),Wa=C({taskId:E(),status:Qb,ttl:le([ne(),wp()]),createdAt:E(),lastUpdatedAt:E(),pollInterval:me(ne()),statusMessage:me(E())}),ea=Oe.extend({task:Wa}),ew=Qe.merge(Wa),Ha=et.extend({method:k("notifications/tasks/status"),params:ew}),Eo=ve.extend({method:k("tasks/get"),params:He.extend({taskId:E()})}),To=Oe.merge(Wa),bo=ve.extend({method:k("tasks/result"),params:He.extend({taskId:E()})}),MR=Oe.loose(),wo=qa.extend({method:k("tasks/list")}),Ao=Va.extend({tasks:K(Wa)}),Io=ve.extend({method:k("tasks/cancel"),params:He.extend({taskId:E()})}),zp=Oe.merge(Wa),Fp=C({uri:E(),mimeType:me(E()),_meta:ce(E(),pe()).optional()}),Gp=Fp.extend({text:E()}),al=E().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),jp=Fp.extend({blob:al}),Ya=Ge(["user","assistant"]),ta=C({audience:K(Ya).optional(),priority:ne().min(0).max(1).optional(),lastModified:Fa.datetime({offset:!0}).optional()}),Bp=C({...Qn.shape,...Za.shape,uri:E(),description:me(E()),mimeType:me(E()),size:me(ne()),annotations:ta.optional(),_meta:me(ke({}))}),tw=C({...Qn.shape,...Za.shape,uriTemplate:E(),description:me(E()),mimeType:me(E()),annotations:ta.optional(),_meta:me(ke({}))}),vo=qa.extend({method:k("resources/list")}),nw=Va.extend({resources:K(Bp)}),Oo=qa.extend({method:k("resources/templates/list")}),aw=Va.extend({resourceTemplates:K(tw)}),rl=He.extend({uri:E()}),rw=rl,So=ve.extend({method:k("resources/read"),params:rw}),ow=Oe.extend({contents:K(le([Gp,jp]))}),sw=et.extend({method:k("notifications/resources/list_changed"),params:Qe.optional()}),iw=rl,cw=ve.extend({method:k("resources/subscribe"),params:iw}),lw=rl,dw=ve.extend({method:k("resources/unsubscribe"),params:lw}),uw=Qe.extend({uri:E()}),hw=et.extend({method:k("notifications/resources/updated"),params:uw}),pw=C({name:E(),description:me(E()),required:me(we())}),mw=C({...Qn.shape,...Za.shape,description:me(E()),arguments:me(K(pw)),_meta:me(ke({}))}),No=qa.extend({method:k("prompts/list")}),fw=Va.extend({prompts:K(mw)}),_w=He.extend({name:E(),arguments:ce(E(),E()).optional()}),Po=ve.extend({method:k("prompts/get"),params:_w}),ol=C({type:k("text"),text:E(),annotations:ta.optional(),_meta:ce(E(),pe()).optional()}),sl=C({type:k("image"),data:al,mimeType:E(),annotations:ta.optional(),_meta:ce(E(),pe()).optional()}),il=C({type:k("audio"),data:al,mimeType:E(),annotations:ta.optional(),_meta:ce(E(),pe()).optional()}),gw=C({type:k("tool_use"),name:E(),id:E(),input:ce(E(),pe()),_meta:ce(E(),pe()).optional()}),yw=C({type:k("resource"),resource:le([Gp,jp]),annotations:ta.optional(),_meta:ce(E(),pe()).optional()}),Ew=Bp.extend({type:k("resource_link")}),cl=le([ol,sl,il,Ew,yw]),Tw=C({role:Ya,content:cl}),bw=Oe.extend({description:E().optional(),messages:K(Tw)}),ww=et.extend({method:k("notifications/prompts/list_changed"),params:Qe.optional()}),Aw=C({title:E().optional(),readOnlyHint:we().optional(),destructiveHint:we().optional(),idempotentHint:we().optional(),openWorldHint:we().optional()}),Iw=C({taskSupport:Ge(["required","optional","forbidden"]).optional()}),Zp=C({...Qn.shape,...Za.shape,description:E().optional(),inputSchema:C({type:k("object"),properties:ce(E(),Te).optional(),required:K(E()).optional()}).catchall(pe()),outputSchema:C({type:k("object"),properties:ce(E(),Te).optional(),required:K(E()).optional()}).catchall(pe()).optional(),annotations:Aw.optional(),execution:Iw.optional(),_meta:ce(E(),pe()).optional()}),Co=qa.extend({method:k("tools/list")}),vw=Va.extend({tools:K(Zp)}),Do=Oe.extend({content:K(cl).default([]),structuredContent:ce(E(),pe()).optional(),isError:we().optional()}),zR=Do.or(Oe.extend({toolResult:pe()})),Ow=ja.extend({name:E(),arguments:ce(E(),pe()).optional()}),na=ve.extend({method:k("tools/call"),params:Ow}),Sw=et.extend({method:k("notifications/tools/list_changed"),params:Qe.optional()}),FR=C({autoRefresh:we().default(!0),debounceMs:ne().int().nonnegative().default(300)}),Ka=Ge(["debug","info","notice","warning","error","critical","alert","emergency"]),Nw=He.extend({level:Ka}),ll=ve.extend({method:k("logging/setLevel"),params:Nw}),Pw=Qe.extend({level:Ka,logger:E().optional(),data:pe()}),Cw=et.extend({method:k("notifications/message"),params:Pw}),Dw=C({name:E().optional()}),Rw=C({hints:K(Dw).optional(),costPriority:ne().min(0).max(1).optional(),speedPriority:ne().min(0).max(1).optional(),intelligencePriority:ne().min(0).max(1).optional()}),Lw=C({mode:Ge(["auto","required","none"]).optional()}),kw=C({type:k("tool_result"),toolUseId:E().describe("The unique identifier for the corresponding tool call."),content:K(cl).default([]),structuredContent:C({}).loose().optional(),isError:we().optional(),_meta:ce(E(),pe()).optional()}),xw=Wc("type",[ol,sl,il]),ho=Wc("type",[ol,sl,il,gw,kw]),$w=C({role:Ya,content:le([ho,K(ho)]),_meta:ce(E(),pe()).optional()}),Uw=ja.extend({messages:K($w),modelPreferences:Rw.optional(),systemPrompt:E().optional(),includeContext:Ge(["none","thisServer","allServers"]).optional(),temperature:ne().optional(),maxTokens:ne().int(),stopSequences:K(E()).optional(),metadata:Te.optional(),tools:K(Zp).optional(),toolChoice:Lw.optional()}),Mw=ve.extend({method:k("sampling/createMessage"),params:Uw}),Ja=Oe.extend({model:E(),stopReason:me(Ge(["endTurn","stopSequence","maxTokens"]).or(E())),role:Ya,content:xw}),dl=Oe.extend({model:E(),stopReason:me(Ge(["endTurn","stopSequence","maxTokens","toolUse"]).or(E())),role:Ya,content:le([ho,K(ho)])}),zw=C({type:k("boolean"),title:E().optional(),description:E().optional(),default:we().optional()}),Fw=C({type:k("string"),title:E().optional(),description:E().optional(),minLength:ne().optional(),maxLength:ne().optional(),format:Ge(["email","uri","date","date-time"]).optional(),default:E().optional()}),Gw=C({type:Ge(["number","integer"]),title:E().optional(),description:E().optional(),minimum:ne().optional(),maximum:ne().optional(),default:ne().optional()}),jw=C({type:k("string"),title:E().optional(),description:E().optional(),enum:K(E()),default:E().optional()}),Bw=C({type:k("string"),title:E().optional(),description:E().optional(),oneOf:K(C({const:E(),title:E()})),default:E().optional()}),Zw=C({type:k("string"),title:E().optional(),description:E().optional(),enum:K(E()),enumNames:K(E()).optional(),default:E().optional()}),qw=le([jw,Bw]),Vw=C({type:k("array"),title:E().optional(),description:E().optional(),minItems:ne().optional(),maxItems:ne().optional(),items:C({type:k("string"),enum:K(E())}),default:K(E()).optional()}),Ww=C({type:k("array"),title:E().optional(),description:E().optional(),minItems:ne().optional(),maxItems:ne().optional(),items:C({anyOf:K(C({const:E(),title:E()}))}),default:K(E()).optional()}),Hw=le([Vw,Ww]),Yw=le([Zw,qw,Hw]),Kw=le([Yw,zw,Fw,Gw]),Jw=ja.extend({mode:k("form").optional(),message:E(),requestedSchema:C({type:k("object"),properties:ce(E(),Kw),required:K(E()).optional()})}),Xw=ja.extend({mode:k("url"),message:E(),elicitationId:E(),url:E().url()}),Qw=le([Jw,Xw]),eA=ve.extend({method:k("elicitation/create"),params:Qw}),tA=Qe.extend({elicitationId:E()}),nA=et.extend({method:k("notifications/elicitation/complete"),params:tA}),aa=Oe.extend({action:Ge(["accept","decline","cancel"]),content:Hc(t=>t===null?void 0:t,ce(E(),le([E(),ne(),we(),K(E())])).optional())}),aA=C({type:k("ref/resource"),uri:E()});var rA=C({type:k("ref/prompt"),name:E()}),oA=He.extend({ref:le([rA,aA]),argument:C({name:E(),value:E()}),context:C({arguments:ce(E(),E()).optional()}).optional()}),Ro=ve.extend({method:k("completion/complete"),params:oA});function qp(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function Vp(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var sA=Oe.extend({completion:ke({values:K(E()).max(100),total:me(ne().int()),hasMore:me(we())})}),iA=C({uri:E().startsWith("file://"),name:E().optional(),_meta:ce(E(),pe()).optional()}),cA=ve.extend({method:k("roots/list"),params:He.optional()}),ul=Oe.extend({roots:K(iA)}),lA=et.extend({method:k("notifications/roots/list_changed"),params:Qe.optional()}),GR=le([go,tl,Ro,ll,Po,No,vo,Oo,So,cw,dw,na,Co,Eo,bo,wo,Io]),jR=le([_o,yo,nl,lA,Ha]),BR=le([fo,Ja,dl,aa,ul,To,Ao,ea]),ZR=le([go,Mw,eA,cA,Eo,bo,wo,Io]),qR=le([_o,yo,Cw,hw,sw,Sw,ww,Ha,nA]),VR=le([fo,Yb,sA,bw,fw,nw,aw,ow,Do,vw,To,Ao,ea]),L=class t extends Error{constructor(e,n,a){super(`MCP error ${e}: ${n}`),this.code=e,this.data=a,this.name="McpError"}static fromError(e,n,a){if(e===$.UrlElicitationRequired&&a){let r=a;if(r.elicitations)return new Yc(r.elicitations,n)}return new t(e,n,a)}},Yc=class extends L{constructor(e,n=`URL elicitation${e.length>1?"s":""} required`){super($.UrlElicitationRequired,n,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};u();function Bt(t){return t==="completed"||t==="failed"||t==="cancelled"}u();u();u();var Hp=Symbol("Let zodToJsonSchema decide on which parser to use");var Wp={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},Yp=t=>typeof t=="string"?{...Wp,name:t}:{...Wp,...t};u();var Kp=t=>{let e=Yp(t),n=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([a,r])=>[r._def,{def:r._def,path:[...e.basePath,e.definitionPath,a],jsonSchema:void 0}]))}};u();function hl(t,e,n,a){a?.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function J(t,e,n,a,r){t[e]=n,hl(t,e,a,r)}u();var Lo=(t,e)=>{let n=0;for(;n<t.length&&n<e.length&&t[n]===e[n];n++);return[(t.length-n).toString(),...e.slice(n)].join("/")};u();u();u();function fe(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Lo(e,t.currentPath):e.join("/")}}u();function Jp(t,e){let n={type:"array"};return t.type?._def&&t.type?._def?.typeName!==v.ZodAny&&(n.items=F(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&J(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&J(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(J(n,"minItems",t.exactLength.value,t.exactLength.message,e),J(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}u();function Xp(t,e){let n={type:"integer",format:"int64"};if(!t.checks)return n;for(let a of t.checks)switch(a.kind){case"min":e.target==="jsonSchema7"?a.inclusive?J(n,"minimum",a.value,a.message,e):J(n,"exclusiveMinimum",a.value,a.message,e):(a.inclusive||(n.exclusiveMinimum=!0),J(n,"minimum",a.value,a.message,e));break;case"max":e.target==="jsonSchema7"?a.inclusive?J(n,"maximum",a.value,a.message,e):J(n,"exclusiveMaximum",a.value,a.message,e):(a.inclusive||(n.exclusiveMaximum=!0),J(n,"maximum",a.value,a.message,e));break;case"multipleOf":J(n,"multipleOf",a.value,a.message,e);break}return n}u();function Qp(){return{type:"boolean"}}u();function ko(t,e){return F(t.type._def,e)}u();var em=(t,e)=>F(t.innerType._def,e);u();function pl(t,e,n){let a=n??e.dateStrategy;if(Array.isArray(a))return{anyOf:a.map((r,o)=>pl(t,e,r))};switch(a){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return dA(t,e)}}var dA=(t,e)=>{let n={type:"integer",format:"unix-time"};if(e.target==="openApi3")return n;for(let a of t.checks)switch(a.kind){case"min":J(n,"minimum",a.value,a.message,e);break;case"max":J(n,"maximum",a.value,a.message,e);break}return n};u();function tm(t,e){return{...F(t.innerType._def,e),default:t.defaultValue()}}u();function nm(t,e){return e.effectStrategy==="input"?F(t.schema._def,e):fe(e)}u();function am(t){return{type:"string",enum:Array.from(t.values)}}u();var uA=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function rm(t,e){let n=[F(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),F(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(o=>!!o),a=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,r=[];return n.forEach(o=>{if(uA(o))r.push(...o.allOf),o.unevaluatedProperties===void 0&&(a=void 0);else{let s=o;if("additionalProperties"in o&&o.additionalProperties===!1){let{additionalProperties:i,...l}=o;s=l}else a=void 0;r.push(s)}}),r.length?{allOf:r,...a}:void 0}u();function om(t,e){let n=typeof t.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[t.value]}:{type:n==="bigint"?"integer":n,const:t.value}}u();u();u();var ml,it={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(ml===void 0&&(ml=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ml),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function xo(t,e){let n={type:"string"};if(t.checks)for(let a of t.checks)switch(a.kind){case"min":J(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,a.value):a.value,a.message,e);break;case"max":J(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,a.value):a.value,a.message,e);break;case"email":switch(e.emailStrategy){case"format:email":ct(n,"email",a.message,e);break;case"format:idn-email":ct(n,"idn-email",a.message,e);break;case"pattern:zod":xe(n,it.email,a.message,e);break}break;case"url":ct(n,"uri",a.message,e);break;case"uuid":ct(n,"uuid",a.message,e);break;case"regex":xe(n,a.regex,a.message,e);break;case"cuid":xe(n,it.cuid,a.message,e);break;case"cuid2":xe(n,it.cuid2,a.message,e);break;case"startsWith":xe(n,RegExp(`^${fl(a.value,e)}`),a.message,e);break;case"endsWith":xe(n,RegExp(`${fl(a.value,e)}$`),a.message,e);break;case"datetime":ct(n,"date-time",a.message,e);break;case"date":ct(n,"date",a.message,e);break;case"time":ct(n,"time",a.message,e);break;case"duration":ct(n,"duration",a.message,e);break;case"length":J(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,a.value):a.value,a.message,e),J(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,a.value):a.value,a.message,e);break;case"includes":{xe(n,RegExp(fl(a.value,e)),a.message,e);break}case"ip":{a.version!=="v6"&&ct(n,"ipv4",a.message,e),a.version!=="v4"&&ct(n,"ipv6",a.message,e);break}case"base64url":xe(n,it.base64url,a.message,e);break;case"jwt":xe(n,it.jwt,a.message,e);break;case"cidr":{a.version!=="v6"&&xe(n,it.ipv4Cidr,a.message,e),a.version!=="v4"&&xe(n,it.ipv6Cidr,a.message,e);break}case"emoji":xe(n,it.emoji(),a.message,e);break;case"ulid":{xe(n,it.ulid,a.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{ct(n,"binary",a.message,e);break}case"contentEncoding:base64":{J(n,"contentEncoding","base64",a.message,e);break}case"pattern:zod":{xe(n,it.base64,a.message,e);break}}break}case"nanoid":xe(n,it.nanoid,a.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return n}function fl(t,e){return e.patternStrategy==="escape"?pA(t):t}var hA=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function pA(t){let e="";for(let n=0;n<t.length;n++)hA.has(t[n])||(e+="\\"),e+=t[n];return e}function ct(t,e,n,a){t.format||t.anyOf?.some(r=>r.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&a.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...n&&a.errorMessages&&{errorMessage:{format:n}}})):J(t,"format",e,n,a)}function xe(t,e,n,a){t.pattern||t.allOf?.some(r=>r.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&a.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:sm(e,a),...n&&a.errorMessages&&{errorMessage:{pattern:n}}})):J(t,"pattern",sm(e,a),n,a)}function sm(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let n={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},a=n.i?t.source.toLowerCase():t.source,r="",o=!1,s=!1,i=!1;for(let l=0;l<a.length;l++){if(o){r+=a[l],o=!1;continue}if(n.i){if(s){if(a[l].match(/[a-z]/)){i?(r+=a[l],r+=`${a[l-2]}-${a[l]}`.toUpperCase(),i=!1):a[l+1]==="-"&&a[l+2]?.match(/[a-z]/)?(r+=a[l],i=!0):r+=`${a[l]}${a[l].toUpperCase()}`;continue}}else if(a[l].match(/[a-z]/)){r+=`[${a[l]}${a[l].toUpperCase()}]`;continue}}if(n.m){if(a[l]==="^"){r+=`(^|(?<=[\r
|
|
39
|
+
]))`;continue}else if(a[l]==="$"){r+=`($|(?=[\r
|
|
40
|
+
]))`;continue}}if(n.s&&a[l]==="."){r+=s?`${a[l]}\r
|
|
41
|
+
`:`[${a[l]}\r
|
|
42
|
+
]`;continue}r+=a[l],a[l]==="\\"?o=!0:s&&a[l]==="]"?s=!1:!s&&a[l]==="["&&(s=!0)}try{new RegExp(r)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return r}function $o(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===v.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((a,r)=>({...a,[r]:F(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",r]})??fe(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let n={type:"object",additionalProperties:F(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return n;if(t.keyType?._def.typeName===v.ZodString&&t.keyType._def.checks?.length){let{type:a,...r}=xo(t.keyType._def,e);return{...n,propertyNames:r}}else{if(t.keyType?._def.typeName===v.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===v.ZodBranded&&t.keyType._def.type._def.typeName===v.ZodString&&t.keyType._def.type._def.checks?.length){let{type:a,...r}=ko(t.keyType._def,e);return{...n,propertyNames:r}}}return n}function im(t,e){if(e.mapStrategy==="record")return $o(t,e);let n=F(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||fe(e),a=F(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||fe(e);return{type:"array",maxItems:125,items:{type:"array",items:[n,a],minItems:2,maxItems:2}}}u();function cm(t){let e=t.values,a=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),r=Array.from(new Set(a.map(o=>typeof o)));return{type:r.length===1?r[0]==="string"?"string":"number":["string","number"],enum:a}}u();function lm(t){return t.target==="openAi"?void 0:{not:fe({...t,currentPath:[...t.currentPath,"not"]})}}u();function dm(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}u();u();var Xa={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function hm(t,e){if(e.target==="openApi3")return um(t,e);let n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(a=>a._def.typeName in Xa&&(!a._def.checks||!a._def.checks.length))){let a=n.reduce((r,o)=>{let s=Xa[o._def.typeName];return s&&!r.includes(s)?[...r,s]:r},[]);return{type:a.length>1?a:a[0]}}else if(n.every(a=>a._def.typeName==="ZodLiteral"&&!a.description)){let a=n.reduce((r,o)=>{let s=typeof o._def.value;switch(s){case"string":case"number":case"boolean":return[...r,s];case"bigint":return[...r,"integer"];case"object":if(o._def.value===null)return[...r,"null"];case"symbol":case"undefined":case"function":default:return r}},[]);if(a.length===n.length){let r=a.filter((o,s,i)=>i.indexOf(o)===s);return{type:r.length>1?r:r[0],enum:n.reduce((o,s)=>o.includes(s._def.value)?o:[...o,s._def.value],[])}}}else if(n.every(a=>a._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((a,r)=>[...a,...r._def.values.filter(o=>!a.includes(o))],[])};return um(t,e)}var um=(t,e)=>{let n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((a,r)=>F(a._def,{...e,currentPath:[...e.currentPath,"anyOf",`${r}`]})).filter(a=>!!a&&(!e.strictUnions||typeof a=="object"&&Object.keys(a).length>0));return n.length?{anyOf:n}:void 0};function pm(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:Xa[t.innerType._def.typeName],nullable:!0}:{type:[Xa[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let a=F(t.innerType._def,{...e,currentPath:[...e.currentPath]});return a&&"$ref"in a?{allOf:[a],nullable:!0}:a&&{...a,nullable:!0}}let n=F(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}u();function mm(t,e){let n={type:"number"};if(!t.checks)return n;for(let a of t.checks)switch(a.kind){case"int":n.type="integer",hl(n,"type",a.message,e);break;case"min":e.target==="jsonSchema7"?a.inclusive?J(n,"minimum",a.value,a.message,e):J(n,"exclusiveMinimum",a.value,a.message,e):(a.inclusive||(n.exclusiveMinimum=!0),J(n,"minimum",a.value,a.message,e));break;case"max":e.target==="jsonSchema7"?a.inclusive?J(n,"maximum",a.value,a.message,e):J(n,"exclusiveMaximum",a.value,a.message,e):(a.inclusive||(n.exclusiveMaximum=!0),J(n,"maximum",a.value,a.message,e));break;case"multipleOf":J(n,"multipleOf",a.value,a.message,e);break}return n}u();function fm(t,e){let n=e.target==="openAi",a={type:"object",properties:{}},r=[],o=t.shape();for(let i in o){let l=o[i];if(l===void 0||l._def===void 0)continue;let d=fA(l);d&&n&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),d=!1);let h=F(l._def,{...e,currentPath:[...e.currentPath,"properties",i],propertyPath:[...e.currentPath,"properties",i]});h!==void 0&&(a.properties[i]=h,d||r.push(i))}r.length&&(a.required=r);let s=mA(t,e);return s!==void 0&&(a.additionalProperties=s),a}function mA(t,e){if(t.catchall._def.typeName!=="ZodNever")return F(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function fA(t){try{return t.isOptional()}catch{return!0}}u();var _m=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return F(t.innerType._def,e);let n=F(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:fe(e)},n]}:fe(e)};u();var gm=(t,e)=>{if(e.pipeStrategy==="input")return F(t.in._def,e);if(e.pipeStrategy==="output")return F(t.out._def,e);let n=F(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),a=F(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,a].filter(r=>r!==void 0)}};u();function ym(t,e){return F(t.type._def,e)}u();function Em(t,e){let a={type:"array",uniqueItems:!0,items:F(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&J(a,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&J(a,"maxItems",t.maxSize.value,t.maxSize.message,e),a}u();function Tm(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,a)=>F(n._def,{...e,currentPath:[...e.currentPath,"items",`${a}`]})).reduce((n,a)=>a===void 0?n:[...n,a],[]),additionalItems:F(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,a)=>F(n._def,{...e,currentPath:[...e.currentPath,"items",`${a}`]})).reduce((n,a)=>a===void 0?n:[...n,a],[])}}u();function bm(t){return{not:fe(t)}}u();function wm(t){return fe(t)}u();var Am=(t,e)=>F(t.innerType._def,e);var Im=(t,e,n)=>{switch(e){case v.ZodString:return xo(t,n);case v.ZodNumber:return mm(t,n);case v.ZodObject:return fm(t,n);case v.ZodBigInt:return Xp(t,n);case v.ZodBoolean:return Qp();case v.ZodDate:return pl(t,n);case v.ZodUndefined:return bm(n);case v.ZodNull:return dm(n);case v.ZodArray:return Jp(t,n);case v.ZodUnion:case v.ZodDiscriminatedUnion:return hm(t,n);case v.ZodIntersection:return rm(t,n);case v.ZodTuple:return Tm(t,n);case v.ZodRecord:return $o(t,n);case v.ZodLiteral:return om(t,n);case v.ZodEnum:return am(t);case v.ZodNativeEnum:return cm(t);case v.ZodNullable:return pm(t,n);case v.ZodOptional:return _m(t,n);case v.ZodMap:return im(t,n);case v.ZodSet:return Em(t,n);case v.ZodLazy:return()=>t.getter()._def;case v.ZodPromise:return ym(t,n);case v.ZodNaN:case v.ZodNever:return lm(n);case v.ZodEffects:return nm(t,n);case v.ZodAny:return fe(n);case v.ZodUnknown:return wm(n);case v.ZodDefault:return tm(t,n);case v.ZodBranded:return ko(t,n);case v.ZodReadonly:return Am(t,n);case v.ZodCatch:return em(t,n);case v.ZodPipeline:return gm(t,n);case v.ZodFunction:case v.ZodVoid:case v.ZodSymbol:return;default:return(a=>{})(e)}};function F(t,e,n=!1){let a=e.seen.get(t);if(e.override){let i=e.override?.(t,e,a,n);if(i!==Hp)return i}if(a&&!n){let i=_A(a,e);if(i!==void 0)return i}let r={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,r);let o=Im(t,t.typeName,e),s=typeof o=="function"?F(o(),e):o;if(s&&gA(t,e,s),e.postProcess){let i=e.postProcess(s,t,e);return r.jsonSchema=s,i}return r.jsonSchema=s,s}var _A=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Lo(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,a)=>e.currentPath[a]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),fe(e)):e.$refStrategy==="seen"?fe(e):void 0}},gA=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n);u();u();var _l=(t,e)=>{let n=Kp(e),a=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[d,h])=>({...l,[d]:F(h._def,{...n,currentPath:[...n.basePath,n.definitionPath,d]},!0)??fe(n)}),{}):void 0,r=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=F(t._def,r===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,r]},!1)??fe(n),s=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;s!==void 0&&(o.title=s),n.flags.hasReferencedOpenAiAnyType&&(a||(a={}),a[n.openAiAnyTypeName]||(a[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));let i=r===void 0?a?{...o,[n.definitionPath]:a}:o:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,r].join("/"),[n.definitionPath]:{...a,[r]:o}};return n.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),n.target==="openAi"&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i};function yA(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function gl(t,e){return Xe(t)?zc(t,{target:yA(e?.target),io:e?.pipeStrategy??"input"}):_l(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function yl(t){let n=Gt(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let a=co(n);if(typeof a!="string")throw new Error("Schema method literal must be a string");return a}function El(t,e){let n=Ft(t,e);if(!n.success)throw n.error;return n.data}var EA=6e4,Uo=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(_o,n=>{this._oncancel(n)}),this.setNotificationHandler(yo,n=>{this._onprogress(n)}),this.setRequestHandler(go,n=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Eo,async(n,a)=>{let r=await this._taskStore.getTask(n.params.taskId,a.sessionId);if(!r)throw new L($.InvalidParams,"Failed to retrieve task: Task not found");return{...r}}),this.setRequestHandler(bo,async(n,a)=>{let r=async()=>{let o=n.params.taskId;if(this._taskMessageQueue){let i;for(;i=await this._taskMessageQueue.dequeue(o,a.sessionId);){if(i.type==="response"||i.type==="error"){let l=i.message,d=l.id,h=this._requestResolvers.get(d);if(h)if(this._requestResolvers.delete(d),i.type==="response")h(l);else{let p=l,g=new L(p.error.code,p.error.message,p.error.data);h(g)}else{let p=i.type==="response"?"Response":"Error";this._onerror(new Error(`${p} handler missing for request ${d}`))}continue}await this._transport?.send(i.message,{relatedRequestId:a.requestId})}}let s=await this._taskStore.getTask(o,a.sessionId);if(!s)throw new L($.InvalidParams,`Task not found: ${o}`);if(!Bt(s.status))return await this._waitForTaskUpdate(o,a.signal),await r();if(Bt(s.status)){let i=await this._taskStore.getTaskResult(o,a.sessionId);return this._clearTaskQueue(o),{...i,_meta:{...i._meta,[jt]:{taskId:o}}}}return await r()};return await r()}),this.setRequestHandler(wo,async(n,a)=>{try{let{tasks:r,nextCursor:o}=await this._taskStore.listTasks(n.params?.cursor,a.sessionId);return{tasks:r,nextCursor:o,_meta:{}}}catch(r){throw new L($.InvalidParams,`Failed to list tasks: ${r instanceof Error?r.message:String(r)}`)}}),this.setRequestHandler(Io,async(n,a)=>{try{let r=await this._taskStore.getTask(n.params.taskId,a.sessionId);if(!r)throw new L($.InvalidParams,`Task not found: ${n.params.taskId}`);if(Bt(r.status))throw new L($.InvalidParams,`Cannot cancel task in terminal status: ${r.status}`);await this._taskStore.updateTaskStatus(n.params.taskId,"cancelled","Client cancelled task execution.",a.sessionId),this._clearTaskQueue(n.params.taskId);let o=await this._taskStore.getTask(n.params.taskId,a.sessionId);if(!o)throw new L($.InvalidParams,`Task not found after cancellation: ${n.params.taskId}`);return{_meta:{},...o}}catch(r){throw r instanceof L?r:new L($.InvalidRequest,`Failed to cancel task: ${r instanceof Error?r.message:String(r)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,n,a,r,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,n),startTime:Date.now(),timeout:n,maxTotalTimeout:a,resetTimeoutOnProgress:o,onTimeout:r})}_resetTimeout(e){let n=this._timeoutInfo.get(e);if(!n)return!1;let a=Date.now()-n.startTime;if(n.maxTotalTimeout&&a>=n.maxTotalTimeout)throw this._timeoutInfo.delete(e),L.fromError($.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:a});return clearTimeout(n.timeoutId),n.timeoutId=setTimeout(n.onTimeout,n.timeout),!0}_cleanupTimeout(e){let n=this._timeoutInfo.get(e);n&&(clearTimeout(n.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let n=this.transport?.onclose;this._transport.onclose=()=>{n?.(),this._onclose()};let a=this.transport?.onerror;this._transport.onerror=o=>{a?.(o),this._onerror(o)};let r=this._transport?.onmessage;this._transport.onmessage=(o,s)=>{r?.(o,s),Ba(o)||Up(o)?this._onresponse(o):Xc(o)?this._onrequest(o,s):$p(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let a of this._timeoutInfo.values())clearTimeout(a.timeoutId);this._timeoutInfo.clear();for(let a of this._requestHandlerAbortControllers.values())a.abort();this._requestHandlerAbortControllers.clear();let n=L.fromError($.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let a of e.values())a(n)}_onerror(e){this.onerror?.(e)}_onnotification(e){let n=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(a=>this._onerror(new Error(`Uncaught error in notification handler: ${a}`)))}_onrequest(e,n){let a=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,o=e.params?._meta?.[jt]?.taskId;if(a===void 0){let h={jsonrpc:"2.0",id:e.id,error:{code:$.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:h,timestamp:Date.now()},r?.sessionId).catch(p=>this._onerror(new Error(`Failed to enqueue error response: ${p}`))):r?.send(h).catch(p=>this._onerror(new Error(`Failed to send an error response: ${p}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(e.id,s);let i=Lp(e.params)?e.params.task:void 0,l=this._taskStore?this.requestTaskStore(e,r?.sessionId):void 0,d={signal:s.signal,sessionId:r?.sessionId,_meta:e.params?._meta,sendNotification:async h=>{if(s.signal.aborted)return;let p={relatedRequestId:e.id};o&&(p.relatedTask={taskId:o}),await this.notification(h,p)},sendRequest:async(h,p,g)=>{if(s.signal.aborted)throw new L($.ConnectionClosed,"Request was cancelled");let f={...g,relatedRequestId:e.id};o&&!f.relatedTask&&(f.relatedTask={taskId:o});let m=f.relatedTask?.taskId??o;return m&&l&&await l.updateTaskStatus(m,"input_required"),await this.request(h,p,f)},authInfo:n?.authInfo,requestId:e.id,requestInfo:n?.requestInfo,taskId:o,taskStore:l,taskRequestedTtl:i?.ttl,closeSSEStream:n?.closeSSEStream,closeStandaloneSSEStream:n?.closeStandaloneSSEStream};Promise.resolve().then(()=>{i&&this.assertTaskHandlerCapability(e.method)}).then(()=>a(e,d)).then(async h=>{if(s.signal.aborted)return;let p={result:h,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:p,timestamp:Date.now()},r?.sessionId):await r?.send(p)},async h=>{if(s.signal.aborted)return;let p={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(h.code)?h.code:$.InternalError,message:h.message??"Internal error",...h.data!==void 0&&{data:h.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:p,timestamp:Date.now()},r?.sessionId):await r?.send(p)}).catch(h=>this._onerror(new Error(`Failed to send response: ${h}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===s&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:n,...a}=e.params,r=Number(n),o=this._progressHandlers.get(r);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let s=this._responseHandlers.get(r),i=this._timeoutInfo.get(r);if(i&&s&&i.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(l){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),s(l);return}o(a)}_onresponse(e){let n=Number(e.id),a=this._requestResolvers.get(n);if(a){if(this._requestResolvers.delete(n),Ba(e))a(e);else{let s=new L(e.error.code,e.error.message,e.error.data);a(s)}return}let r=this._responseHandlers.get(n);if(r===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(n),this._cleanupTimeout(n);let o=!1;if(Ba(e)&&e.result&&typeof e.result=="object"){let s=e.result;if(s.task&&typeof s.task=="object"){let i=s.task;typeof i.taskId=="string"&&(o=!0,this._taskProgressTokens.set(i.taskId,n))}}if(o||this._progressHandlers.delete(n),Ba(e))r(e);else{let s=L.fromError(e.error.code,e.error.message,e.error.data);r(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,n,a){let{task:r}=a??{};if(!r){try{yield{type:"result",result:await this.request(e,n,a)}}catch(s){yield{type:"error",error:s instanceof L?s:new L($.InternalError,String(s))}}return}let o;try{let s=await this.request(e,ea,a);if(s.task)o=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new L($.InternalError,"Task creation did not return a task");for(;;){let i=await this.getTask({taskId:o},a);if(yield{type:"taskStatus",task:i},Bt(i.status)){i.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},n,a)}:i.status==="failed"?yield{type:"error",error:new L($.InternalError,`Task ${o} failed`)}:i.status==="cancelled"&&(yield{type:"error",error:new L($.InternalError,`Task ${o} was cancelled`)});return}if(i.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},n,a)};return}let l=i.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(d=>setTimeout(d,l)),a?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof L?s:new L($.InternalError,String(s))}}}request(e,n,a){let{relatedRequestId:r,resumptionToken:o,onresumptiontoken:s,task:i,relatedTask:l}=a??{};return new Promise((d,h)=>{let p=I=>{h(I)};if(!this._transport){p(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),i&&this.assertTaskCapability(e.method)}catch(I){p(I);return}a?.signal?.throwIfAborted();let g=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:g};a?.onprogress&&(this._progressHandlers.set(g,a.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:g}}),i&&(f.params={...f.params,task:i}),l&&(f.params={...f.params,_meta:{...f.params?._meta||{},[jt]:l}});let m=I=>{this._responseHandlers.delete(g),this._progressHandlers.delete(g),this._cleanupTimeout(g),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:g,reason:String(I)}},{relatedRequestId:r,resumptionToken:o,onresumptiontoken:s}).catch(D=>this._onerror(new Error(`Failed to send cancellation: ${D}`)));let O=I instanceof L?I:new L($.RequestTimeout,String(I));h(O)};this._responseHandlers.set(g,I=>{if(!a?.signal?.aborted){if(I instanceof Error)return h(I);try{let O=Ft(n,I.result);O.success?d(O.data):h(O.error)}catch(O){h(O)}}}),a?.signal?.addEventListener("abort",()=>{m(a?.signal?.reason)});let y=a?.timeout??EA,T=()=>m(L.fromError($.RequestTimeout,"Request timed out",{timeout:y}));this._setupTimeout(g,y,a?.maxTotalTimeout,T,a?.resetTimeoutOnProgress??!1);let w=l?.taskId;if(w){let I=O=>{let D=this._responseHandlers.get(g);D?D(O):this._onerror(new Error(`Response handler missing for side-channeled request ${g}`))};this._requestResolvers.set(g,I),this._enqueueTaskMessage(w,{type:"request",message:f,timestamp:Date.now()}).catch(O=>{this._cleanupTimeout(g),h(O)})}else this._transport.send(f,{relatedRequestId:r,resumptionToken:o,onresumptiontoken:s}).catch(I=>{this._cleanupTimeout(g),h(I)})})}async getTask(e,n){return this.request({method:"tasks/get",params:e},To,n)}async getTaskResult(e,n,a){return this.request({method:"tasks/result",params:e},n,a)}async listTasks(e,n){return this.request({method:"tasks/list",params:e},Ao,n)}async cancelTask(e,n){return this.request({method:"tasks/cancel",params:e},zp,n)}async notification(e,n){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let a=n?.relatedTask?.taskId;if(a){let i={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[jt]:n.relatedTask}}};await this._enqueueTaskMessage(a,{type:"notification",message:i,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!n?.relatedRequestId&&!n?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let i={...e,jsonrpc:"2.0"};n?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[jt]:n.relatedTask}}}),this._transport?.send(i,n).catch(l=>this._onerror(l))});return}let s={...e,jsonrpc:"2.0"};n?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[jt]:n.relatedTask}}}),await this._transport.send(s,n)}setRequestHandler(e,n){let a=yl(e);this.assertRequestHandlerCapability(a),this._requestHandlers.set(a,(r,o)=>{let s=El(e,r);return Promise.resolve(n(s,o))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,n){let a=yl(e);this._notificationHandlers.set(a,r=>{let o=El(e,r);return Promise.resolve(n(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let n=this._taskProgressTokens.get(e);n!==void 0&&(this._progressHandlers.delete(n),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,n,a){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,n,a,r)}async _clearTaskQueue(e,n){if(this._taskMessageQueue){let a=await this._taskMessageQueue.dequeueAll(e,n);for(let r of a)if(r.type==="request"&&Xc(r.message)){let o=r.message.id,s=this._requestResolvers.get(o);s?(s(new L($.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,n){let a=this._options?.defaultTaskPollInterval??1e3;try{let r=await this._taskStore?.getTask(e);r?.pollInterval&&(a=r.pollInterval)}catch{}return new Promise((r,o)=>{if(n.aborted){o(new L($.InvalidRequest,"Request cancelled"));return}let s=setTimeout(r,a);n.addEventListener("abort",()=>{clearTimeout(s),o(new L($.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,n){let a=this._taskStore;if(!a)throw new Error("No task store configured");return{createTask:async r=>{if(!e)throw new Error("No request provided");return await a.createTask(r,e.id,{method:e.method,params:e.params},n)},getTask:async r=>{let o=await a.getTask(r,n);if(!o)throw new L($.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(r,o,s)=>{await a.storeTaskResult(r,o,s,n);let i=await a.getTask(r,n);if(i){let l=Ha.parse({method:"notifications/tasks/status",params:i});await this.notification(l),Bt(i.status)&&this._cleanupTaskProgressHandler(r)}},getTaskResult:r=>a.getTaskResult(r,n),updateTaskStatus:async(r,o,s)=>{let i=await a.getTask(r,n);if(!i)throw new L($.InvalidParams,`Task "${r}" not found - it may have been cleaned up`);if(Bt(i.status))throw new L($.InvalidParams,`Cannot update task "${r}" from terminal status "${i.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await a.updateTaskStatus(r,o,s,n);let l=await a.getTask(r,n);if(l){let d=Ha.parse({method:"notifications/tasks/status",params:l});await this.notification(d),Bt(l.status)&&this._cleanupTaskProgressHandler(r)}},listTasks:r=>a.listTasks(r,n)}}};function vm(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Om(t,e){let n={...t};for(let a in e){let r=a,o=e[r];if(o===void 0)continue;let s=n[r];vm(s)&&vm(o)?n[r]={...s,...o}:n[r]=o}return n}u();var yg=vu(ou(),1),Eg=vu(gg(),1);function wP(){let t=new yg.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Eg.default)(t),t}var ys=class{constructor(e){this._ajv=e??wP()}getValidator(e){let n="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return a=>n(a)?{valid:!0,data:a,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}};u();var Es=class{constructor(e){this._server=e}requestStream(e,n,a){return this._server.requestStream(e,n,a)}createMessageStream(e,n){let a=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!a?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let r=e.messages[e.messages.length-1],o=Array.isArray(r.content)?r.content:[r.content],s=o.some(h=>h.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,l=i?Array.isArray(i.content)?i.content:[i.content]:[],d=l.some(h=>h.type==="tool_use");if(s){if(o.some(h=>h.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!d)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(d){let h=new Set(l.filter(g=>g.type==="tool_use").map(g=>g.id)),p=new Set(o.filter(g=>g.type==="tool_result").map(g=>g.toolUseId));if(h.size!==p.size||![...h].every(g=>p.has(g)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},Ja,n)}elicitInputStream(e,n){let a=this._server.getClientCapabilities(),r=e.mode??"form";switch(r){case"url":{if(!a?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!a?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let o=r==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:o},aa,n)}async getTask(e,n){return this._server.getTask({taskId:e},n)}async getTaskResult(e,n,a){return this._server.getTaskResult({taskId:e},n,a)}async listTasks(e,n){return this._server.listTasks(e?{cursor:e}:void 0,n)}async cancelTask(e,n){return this._server.cancelTask({taskId:e},n)}};u();function Tg(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${n} does not support task creation for tools/call (required for ${e})`);break;default:break}}function bg(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${n} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${n} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var Ts=class extends Uo{constructor(e,n){super(n),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Ka.options.map((a,r)=>[a,r])),this.isMessageIgnored=(a,r)=>{let o=this._loggingLevels.get(r);return o?this.LOG_LEVEL_SEVERITY.get(a)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=n?.capabilities??{},this._instructions=n?.instructions,this._jsonSchemaValidator=n?.jsonSchemaValidator??new ys,this.setRequestHandler(tl,a=>this._oninitialize(a)),this.setNotificationHandler(nl,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(ll,async(a,r)=>{let o=r.sessionId||r.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=a.params,i=Ka.safeParse(s);return i.success&&this._loggingLevels.set(o,i.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Es(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Om(this._capabilities,e)}setRequestHandler(e,n){let r=Gt(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let o;if(Xe(r)){let i=r;o=i._zod?.def?.value??i.value}else{let i=r;o=i._def?.value??i.value}if(typeof o!="string")throw new Error("Schema method literal must be a string");if(o==="tools/call"){let i=async(l,d)=>{let h=Ft(na,l);if(!h.success){let m=h.error instanceof Error?h.error.message:String(h.error);throw new L($.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:p}=h.data,g=await Promise.resolve(n(l,d));if(p.task){let m=Ft(ea,g);if(!m.success){let y=m.error instanceof Error?m.error.message:String(m.error);throw new L($.InvalidParams,`Invalid task creation result: ${y}`)}return m.data}let f=Ft(Do,g);if(!f.success){let m=f.error instanceof Error?f.error.message:String(f.error);throw new L($.InvalidParams,`Invalid tools/call result: ${m}`)}return f.data};return super.setRequestHandler(e,i)}return super.setRequestHandler(e,n)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){bg(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Tg(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let n=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Cp.includes(n)?n:Kc,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},fo)}async createMessage(e,n){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let a=e.messages[e.messages.length-1],r=Array.isArray(a.content)?a.content:[a.content],o=r.some(d=>d.type==="tool_result"),s=e.messages.length>1?e.messages[e.messages.length-2]:void 0,i=s?Array.isArray(s.content)?s.content:[s.content]:[],l=i.some(d=>d.type==="tool_use");if(o){if(r.some(d=>d.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let d=new Set(i.filter(p=>p.type==="tool_use").map(p=>p.id)),h=new Set(r.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(d.size!==h.size||![...d].every(p=>h.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},dl,n):this.request({method:"sampling/createMessage",params:e},Ja,n)}async elicitInput(e,n){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let r=e;return this.request({method:"elicitation/create",params:r},aa,n)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let r=e.mode==="form"?e:{...e,mode:"form"},o=await this.request({method:"elicitation/create",params:r},aa,n);if(o.action==="accept"&&o.content&&r.requestedSchema)try{let i=this._jsonSchemaValidator.getValidator(r.requestedSchema)(o.content);if(!i.valid)throw new L($.InvalidParams,`Elicitation response content does not match requested schema: ${i.errorMessage}`)}catch(s){throw s instanceof L?s:new L($.InternalError,`Error validating elicitation response: ${s instanceof Error?s.message:String(s)}`)}return o}}}createElicitationCompletionNotifier(e,n){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},n)}async listRoots(e,n){return this.request({method:"roots/list",params:e},ul,n)}async sendLoggingMessage(e,n){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,n))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};u();var Ag=Symbol.for("mcp.completable");function pu(t){return!!t&&typeof t=="object"&&Ag in t}function Ig(t){return t[Ag]?.complete}var wg;(function(t){t.Completable="McpCompletable"})(wg||(wg={}));u();var bs=class t{static isTemplate(e){return/\{[^}\s]+\}/.test(e)}static validateLength(e,n,a){if(e.length>n)throw new Error(`${a} exceeds maximum length of ${n} characters (got ${e.length})`)}get variableNames(){return this.parts.flatMap(e=>typeof e=="string"?[]:e.names)}constructor(e){t.validateLength(e,1e6,"Template"),this.template=e,this.parts=this.parse(e)}toString(){return this.template}parse(e){let n=[],a="",r=0,o=0;for(;r<e.length;)if(e[r]==="{"){a&&(n.push(a),a="");let s=e.indexOf("}",r);if(s===-1)throw new Error("Unclosed template expression");if(o++,o>1e4)throw new Error("Template contains too many expressions (max 10000)");let i=e.slice(r+1,s),l=this.getOperator(i),d=i.includes("*"),h=this.getNames(i),p=h[0];for(let g of h)t.validateLength(g,1e6,"Variable name");n.push({name:p,operator:l,names:h,exploded:d}),r=s+1}else a+=e[r],r++;return a&&n.push(a),n}getOperator(e){return["+","#",".","/","?","&"].find(a=>e.startsWith(a))||""}getNames(e){let n=this.getOperator(e);return e.slice(n.length).split(",").map(a=>a.replace("*","").trim()).filter(a=>a.length>0)}encodeValue(e,n){return t.validateLength(e,1e6,"Variable value"),n==="+"||n==="#"?encodeURI(e):encodeURIComponent(e)}expandPart(e,n){if(e.operator==="?"||e.operator==="&"){let s=e.names.map(l=>{let d=n[l];if(d===void 0)return"";let h=Array.isArray(d)?d.map(p=>this.encodeValue(p,e.operator)).join(","):this.encodeValue(d.toString(),e.operator);return`${l}=${h}`}).filter(l=>l.length>0);return s.length===0?"":(e.operator==="?"?"?":"&")+s.join("&")}if(e.names.length>1){let s=e.names.map(i=>n[i]).filter(i=>i!==void 0);return s.length===0?"":s.map(i=>Array.isArray(i)?i[0]:i).join(",")}let a=n[e.name];if(a===void 0)return"";let o=(Array.isArray(a)?a:[a]).map(s=>this.encodeValue(s,e.operator));switch(e.operator){case"":return o.join(",");case"+":return o.join(",");case"#":return"#"+o.join(",");case".":return"."+o.join(".");case"/":return"/"+o.join("/");default:return o.join(",")}}expand(e){let n="",a=!1;for(let r of this.parts){if(typeof r=="string"){n+=r;continue}let o=this.expandPart(r,e);o&&((r.operator==="?"||r.operator==="&")&&a?n+=o.replace("?","&"):n+=o,(r.operator==="?"||r.operator==="&")&&(a=!0))}return n}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}partToRegExp(e){let n=[];for(let o of e.names)t.validateLength(o,1e6,"Variable name");if(e.operator==="?"||e.operator==="&"){for(let o=0;o<e.names.length;o++){let s=e.names[o],i=o===0?"\\"+e.operator:"&";n.push({pattern:i+this.escapeRegExp(s)+"=([^&]+)",name:s})}return n}let a,r=e.name;switch(e.operator){case"":a=e.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)";break;case"+":case"#":a="(.+)";break;case".":a="\\.([^/,]+)";break;case"/":a="/"+(e.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)");break;default:a="([^/]+)"}return n.push({pattern:a,name:r}),n}match(e){t.validateLength(e,1e6,"URI");let n="^",a=[];for(let i of this.parts)if(typeof i=="string")n+=this.escapeRegExp(i);else{let l=this.partToRegExp(i);for(let{pattern:d,name:h}of l)n+=d,a.push({name:h,exploded:i.exploded})}n+="$",t.validateLength(n,1e6,"Generated regex pattern");let r=new RegExp(n),o=e.match(r);if(!o)return null;let s={};for(let i=0;i<a.length;i++){let{name:l,exploded:d}=a[i],h=o[i+1],p=l.replace("*","");d&&h.includes(",")?s[p]=h.split(","):s[p]=h}return s}};u();var AP=/^[A-Za-z0-9._-]{1,128}$/;function IP(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!AP.test(t)){let n=t.split("").filter(a=>!/[A-Za-z0-9._-]/.test(a)).filter((a,r,o)=>o.indexOf(a)===r);return e.push(`Tool name contains invalid characters: ${n.map(a=>`"${a}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function vP(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let n of e)console.warn(` - ${n}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function mu(t){let e=IP(t);return vP(t,e.warnings),e.isValid}u();var ws=class{constructor(e){this._mcpServer=e}registerToolTask(e,n,a){let r={taskSupport:"required",...n.execution};if(r.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,n.title,n.description,n.inputSchema,n.outputSchema,n.annotations,r,n._meta,a)}};u();var vg=class{constructor(e,n){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Ts(e,n)}get experimental(){return this._experimental||(this._experimental={tasks:new ws(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Xt(Co)),this.server.assertCanSetRequestHandler(Xt(na)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Co,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,n])=>{let a={name:e,title:n.title,description:n.description,inputSchema:(()=>{let r=Xn(n.inputSchema);return r?gl(r,{strictUnions:!0,pipeStrategy:"input"}):OP})(),annotations:n.annotations,execution:n.execution,_meta:n._meta};if(n.outputSchema){let r=Xn(n.outputSchema);r&&(a.outputSchema=gl(r,{strictUnions:!0,pipeStrategy:"output"}))}return a})})),this.server.setRequestHandler(na,async(e,n)=>{try{let a=this._registeredTools[e.params.name];if(!a)throw new L($.InvalidParams,`Tool ${e.params.name} not found`);if(!a.enabled)throw new L($.InvalidParams,`Tool ${e.params.name} disabled`);let r=!!e.params.task,o=a.execution?.taskSupport,s="createTask"in a.handler;if((o==="required"||o==="optional")&&!s)throw new L($.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!r)throw new L($.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(o==="optional"&&!r&&s)return await this.handleAutomaticTaskPolling(a,e,n);let i=await this.validateToolInput(a,e.params.arguments,e.params.name),l=await this.executeToolHandler(a,i,n);return r||await this.validateToolOutput(a,l,e.params.name),l}catch(a){if(a instanceof L&&a.code===$.UrlElicitationRequired)throw a;return this.createToolError(a instanceof Error?a.message:String(a))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,n,a){if(!e.inputSchema)return;let o=Xn(e.inputSchema)??e.inputSchema,s=await so(o,n);if(!s.success){let i="error"in s?s.error:"Unknown error",l=io(i);throw new L($.InvalidParams,`Input validation error: Invalid arguments for tool ${a}: ${l}`)}return s.data}async validateToolOutput(e,n,a){if(!e.outputSchema||!("content"in n)||n.isError)return;if(!n.structuredContent)throw new L($.InvalidParams,`Output validation error: Tool ${a} has an output schema but no structured content was provided`);let r=Xn(e.outputSchema),o=await so(r,n.structuredContent);if(!o.success){let s="error"in o?o.error:"Unknown error",i=io(s);throw new L($.InvalidParams,`Output validation error: Invalid structured content for tool ${a}: ${i}`)}}async executeToolHandler(e,n,a){let r=e.handler;if("createTask"in r){if(!a.taskStore)throw new Error("No task store provided.");let s={...a,taskStore:a.taskStore};if(e.inputSchema){let i=r;return await Promise.resolve(i.createTask(n,s))}else{let i=r;return await Promise.resolve(i.createTask(s))}}if(e.inputSchema){let s=r;return await Promise.resolve(s(n,a))}else{let s=r;return await Promise.resolve(s(a))}}async handleAutomaticTaskPolling(e,n,a){if(!a.taskStore)throw new Error("No task store provided for task-capable tool.");let r=await this.validateToolInput(e,n.params.arguments,n.params.name),o=e.handler,s={...a,taskStore:a.taskStore},i=r?await Promise.resolve(o.createTask(r,s)):await Promise.resolve(o.createTask(s)),l=i.task.taskId,d=i.task,h=d.pollInterval??5e3;for(;d.status!=="completed"&&d.status!=="failed"&&d.status!=="cancelled";){await new Promise(g=>setTimeout(g,h));let p=await a.taskStore.getTask(l);if(!p)throw new L($.InternalError,`Task ${l} not found during polling`);d=p}return await a.taskStore.getTaskResult(l)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Xt(Ro)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Ro,async e=>{switch(e.params.ref.type){case"ref/prompt":return qp(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Vp(e),this.handleResourceCompletion(e,e.params.ref);default:throw new L($.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,n){let a=this._registeredPrompts[n.name];if(!a)throw new L($.InvalidParams,`Prompt ${n.name} not found`);if(!a.enabled)throw new L($.InvalidParams,`Prompt ${n.name} disabled`);if(!a.argsSchema)return Nr;let o=Gt(a.argsSchema)?.[e.params.argument.name];if(!pu(o))return Nr;let s=Ig(o);if(!s)return Nr;let i=await s(e.params.argument.value,e.params.context);return Ng(i)}async handleResourceCompletion(e,n){let a=Object.values(this._registeredResourceTemplates).find(s=>s.resourceTemplate.uriTemplate.toString()===n.uri);if(!a){if(this._registeredResources[n.uri])return Nr;throw new L($.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=a.resourceTemplate.completeCallback(e.params.argument.name);if(!r)return Nr;let o=await r(e.params.argument.value,e.params.context);return Ng(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Xt(vo)),this.server.assertCanSetRequestHandler(Xt(Oo)),this.server.assertCanSetRequestHandler(Xt(So)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(vo,async(e,n)=>{let a=Object.entries(this._registeredResources).filter(([o,s])=>s.enabled).map(([o,s])=>({uri:o,name:s.name,...s.metadata})),r=[];for(let o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;let s=await o.resourceTemplate.listCallback(n);for(let i of s.resources)r.push({...o.metadata,...i})}return{resources:[...a,...r]}}),this.server.setRequestHandler(Oo,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([n,a])=>({name:n,uriTemplate:a.resourceTemplate.uriTemplate.toString(),...a.metadata}))})),this.server.setRequestHandler(So,async(e,n)=>{let a=new URL(e.params.uri),r=this._registeredResources[a.toString()];if(r){if(!r.enabled)throw new L($.InvalidParams,`Resource ${a} disabled`);return r.readCallback(a,n)}for(let o of Object.values(this._registeredResourceTemplates)){let s=o.resourceTemplate.uriTemplate.match(a.toString());if(s)return o.readCallback(a,s,n)}throw new L($.InvalidParams,`Resource ${a} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Xt(No)),this.server.assertCanSetRequestHandler(Xt(Po)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(No,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,n])=>({name:e,title:n.title,description:n.description,arguments:n.argsSchema?SP(n.argsSchema):void 0}))})),this.server.setRequestHandler(Po,async(e,n)=>{let a=this._registeredPrompts[e.params.name];if(!a)throw new L($.InvalidParams,`Prompt ${e.params.name} not found`);if(!a.enabled)throw new L($.InvalidParams,`Prompt ${e.params.name} disabled`);if(a.argsSchema){let r=Xn(a.argsSchema),o=await so(r,e.params.arguments);if(!o.success){let l="error"in o?o.error:"Unknown error",d=io(l);throw new L($.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${d}`)}let s=o.data,i=a.callback;return await Promise.resolve(i(s,n))}else{let r=a.callback;return await Promise.resolve(r(n))}}),this._promptHandlersInitialized=!0)}resource(e,n,...a){let r;typeof a[0]=="object"&&(r=a.shift());let o=a[0];if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);let s=this._createRegisteredResource(e,void 0,n,r,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,void 0,n,r,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}registerResource(e,n,a,r){if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);let o=this._createRegisteredResource(e,a.title,n,a,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let o=this._createRegisteredResourceTemplate(e,a.title,n,a,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,n,a,r,o){let s={name:e,title:n,metadata:r,readCallback:o,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({uri:null}),update:i=>{typeof i.uri<"u"&&i.uri!==a&&(delete this._registeredResources[a],i.uri&&(this._registeredResources[i.uri]=s)),typeof i.name<"u"&&(s.name=i.name),typeof i.title<"u"&&(s.title=i.title),typeof i.metadata<"u"&&(s.metadata=i.metadata),typeof i.callback<"u"&&(s.readCallback=i.callback),typeof i.enabled<"u"&&(s.enabled=i.enabled),this.sendResourceListChanged()}};return this._registeredResources[a]=s,s}_createRegisteredResourceTemplate(e,n,a,r,o){let s={resourceTemplate:a,title:n,metadata:r,readCallback:o,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==e&&(delete this._registeredResourceTemplates[e],d.name&&(this._registeredResourceTemplates[d.name]=s)),typeof d.title<"u"&&(s.title=d.title),typeof d.template<"u"&&(s.resourceTemplate=d.template),typeof d.metadata<"u"&&(s.metadata=d.metadata),typeof d.callback<"u"&&(s.readCallback=d.callback),typeof d.enabled<"u"&&(s.enabled=d.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=s;let i=a.uriTemplate.variableNames;return Array.isArray(i)&&i.some(d=>!!a.completeCallback(d))&&this.setCompletionRequestHandler(),s}_createRegisteredPrompt(e,n,a,r,o){let s={title:n,description:a,argsSchema:r===void 0?void 0:An(r),callback:o,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:i=>{typeof i.name<"u"&&i.name!==e&&(delete this._registeredPrompts[e],i.name&&(this._registeredPrompts[i.name]=s)),typeof i.title<"u"&&(s.title=i.title),typeof i.description<"u"&&(s.description=i.description),typeof i.argsSchema<"u"&&(s.argsSchema=An(i.argsSchema)),typeof i.callback<"u"&&(s.callback=i.callback),typeof i.enabled<"u"&&(s.enabled=i.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=s,r&&Object.values(r).some(l=>{let d=l instanceof ze?l._def?.innerType:l;return pu(d)})&&this.setCompletionRequestHandler(),s}_createRegisteredTool(e,n,a,r,o,s,i,l,d){mu(e);let h={title:n,description:a,inputSchema:Sg(r),outputSchema:Sg(o),annotations:s,execution:i,_meta:l,handler:d,enabled:!0,disable:()=>h.update({enabled:!1}),enable:()=>h.update({enabled:!0}),remove:()=>h.update({name:null}),update:p=>{typeof p.name<"u"&&p.name!==e&&(typeof p.name=="string"&&mu(p.name),delete this._registeredTools[e],p.name&&(this._registeredTools[p.name]=h)),typeof p.title<"u"&&(h.title=p.title),typeof p.description<"u"&&(h.description=p.description),typeof p.paramsSchema<"u"&&(h.inputSchema=An(p.paramsSchema)),typeof p.outputSchema<"u"&&(h.outputSchema=An(p.outputSchema)),typeof p.callback<"u"&&(h.handler=p.callback),typeof p.annotations<"u"&&(h.annotations=p.annotations),typeof p._meta<"u"&&(h._meta=p._meta),typeof p.enabled<"u"&&(h.enabled=p.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=h,this.setToolRequestHandlers(),this.sendToolListChanged(),h}tool(e,...n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let a,r,o,s;if(typeof n[0]=="string"&&(a=n.shift()),n.length>1){let l=n[0];if(fu(l))r=n.shift(),n.length>1&&typeof n[0]=="object"&&n[0]!==null&&!fu(n[0])&&(s=n.shift());else if(typeof l=="object"&&l!==null){if(Object.values(l).some(d=>typeof d=="object"&&d!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);s=n.shift()}}let i=n[0];return this._createRegisteredTool(e,void 0,a,r,o,s,{taskSupport:"forbidden"},void 0,i)}registerTool(e,n,a){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:r,description:o,inputSchema:s,outputSchema:i,annotations:l,_meta:d}=n;return this._createRegisteredTool(e,r,o,s,i,l,{taskSupport:"forbidden"},d,a)}prompt(e,...n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let a;typeof n[0]=="string"&&(a=n.shift());let r;n.length>1&&(r=n.shift());let o=n[0],s=this._createRegisteredPrompt(e,void 0,a,r,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}registerPrompt(e,n,a){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:r,description:o,argsSchema:s}=n,i=this._createRegisteredPrompt(e,r,o,s,a);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,n){return this.server.sendLoggingMessage(e,n)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},Og=class{constructor(e,n){this._callbacks=n,this._uriTemplate=typeof e=="string"?new bs(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}},OP={type:"object",properties:{}};function Pg(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function Cg(t){return"_def"in t||"_zod"in t||Pg(t)}function fu(t){return typeof t!="object"||t===null||Cg(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(Pg)}function Sg(t){if(t){if(fu(t))return An(t);if(!Cg(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function SP(t){let e=Gt(t);return e?Object.entries(e).map(([n,a])=>{let r=sp(a),o=ip(a);return{name:n,description:r,required:!o}}):[]}function Xt(t){let n=Gt(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let a=co(n);if(typeof a=="string")return a;throw new Error("Schema method literal must be a string")}function Ng(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Nr={completion:{values:[],hasMore:!1}};u();u();u();u();u();import{readFileSync as $P}from"node:fs";import{dirname as UP,join as MP}from"node:path";import{fileURLToPath as zP}from"node:url";u();var be,Pr=null;function As(){return(Pr===null||Pr.byteLength===0)&&(Pr=new Uint8Array(be.memory.buffer)),Pr}var Is=typeof TextDecoder<"u"?new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}):{decode:()=>{throw Error("TextDecoder not available")}};typeof TextDecoder<"u"&&Is.decode();var NP=2146435072,_u=0;function PP(t,e){return _u+=e,_u>=NP&&(Is=typeof TextDecoder<"u"?new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}):{decode:()=>{throw Error("TextDecoder not available")}},Is.decode(),_u=e),Is.decode(As().subarray(t,t+e))}function gu(t,e){return t=t>>>0,PP(t,e)}function yu(t){let e=typeof t;if(e=="number"||e=="boolean"||t==null)return`${t}`;if(e=="string")return`"${t}"`;if(e=="symbol"){let r=t.description;return r==null?"Symbol":`Symbol(${r})`}if(e=="function"){let r=t.name;return typeof r=="string"&&r.length>0?`Function(${r})`:"Function"}if(Array.isArray(t)){let r=t.length,o="[";r>0&&(o+=yu(t[0]));for(let s=1;s<r;s++)o+=", "+yu(t[s]);return o+="]",o}let n=/\[object ([^\]]+)\]/.exec(toString.call(t)),a;if(n&&n.length>1)a=n[1];else return toString.call(t);if(a=="Object")try{return"Object("+JSON.stringify(t)+")"}catch{return"Object"}return t instanceof Error?`${t.name}: ${t.message}
|
|
43
|
+
${t.stack}`:a}var Os=0,vs=typeof TextEncoder<"u"?new TextEncoder("utf-8"):{encode:()=>{throw Error("TextEncoder not available")}},CP=typeof vs.encodeInto=="function"?function(t,e){return vs.encodeInto(t,e)}:function(t,e){let n=vs.encode(t);return e.set(n),{read:t.length,written:n.length}};function Dg(t,e,n){if(n===void 0){let i=vs.encode(t),l=e(i.length,1)>>>0;return As().subarray(l,l+i.length).set(i),Os=i.length,l}let a=t.length,r=e(a,1)>>>0,o=As(),s=0;for(;s<a;s++){let i=t.charCodeAt(s);if(i>127)break;o[r+s]=i}if(s!==a){s!==0&&(t=t.slice(s)),r=n(r,a,a=s+t.length*3,1)>>>0;let i=As().subarray(r+s,r+a),l=CP(t,i);s+=l.written,r=n(r,a,s,1)>>>0}return Os=s,r}var xn=null;function Eu(){return(xn===null||xn.buffer.detached===!0||xn.buffer.detached===void 0&&xn.buffer!==be.memory.buffer)&&(xn=new DataView(be.memory.buffer)),xn}function DP(t){return t==null}function RP(t,e){t=t>>>0;let n=Eu(),a=[];for(let r=t;r<t+4*e;r+=4)a.push(be.__wbindgen_export_2.get(n.getUint32(r,!0)));return be.__externref_drop_slice(t,e),a}function Rg(t,e){let n=Dg(t,be.__wbindgen_malloc,be.__wbindgen_realloc),a=Os,r=be.cut(n,a,DP(e)?16777215:e?1:0);var o=RP(r[0],r[1]).slice();return be.__wbindgen_free(r[0],r[1]*4,4),o}var LP=new Set(["basic","cors","default"]);async function kP(t,e){if(typeof Response=="function"&&t instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(t,e)}catch(a){if(t.ok&&LP.has(t.type)&&t.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",a);else throw a}let n=await t.arrayBuffer();return await WebAssembly.instantiate(n,e)}else{let n=await WebAssembly.instantiate(t,e);return n instanceof WebAssembly.Instance?{instance:n,module:t}:n}}function Lg(){let t={};return t.wbg={},t.wbg.__wbg_Error_0497d5bdba9362e5=function(e,n){return Error(gu(e,n))},t.wbg.__wbg_new_07b483f72211fd66=function(){return new Object},t.wbg.__wbg_set_3f1d0b984ed272ed=function(e,n,a){e[n]=a},t.wbg.__wbindgen_bigint_from_u64=function(e){return BigInt.asUintN(64,e)},t.wbg.__wbindgen_debug_string=function(e,n){let a=yu(n),r=Dg(a,be.__wbindgen_malloc,be.__wbindgen_realloc),o=Os;Eu().setInt32(e+4,o,!0),Eu().setInt32(e+0,r,!0)},t.wbg.__wbindgen_init_externref_table=function(){let e=be.__wbindgen_export_2,n=e.grow(4);e.set(0,void 0),e.set(n+0,void 0),e.set(n+1,null),e.set(n+2,!0),e.set(n+3,!1)},t.wbg.__wbindgen_number_new=function(e){return e},t.wbg.__wbindgen_string_new=function(e,n){return gu(e,n)},t.wbg.__wbindgen_throw=function(e,n){throw new Error(gu(e,n))},t}function kg(t,e){return be=t.exports,xP.__wbindgen_wasm_module=e,xn=null,Pr=null,be.__wbindgen_start(),be}function xg(t){if(be!==void 0)return be;typeof t<"u"&&(Object.getPrototypeOf(t)===Object.prototype?{module:t}=t:console.warn("using deprecated parameters for `initSync()`; pass a single object instead"));let e=Lg();t instanceof WebAssembly.Module||(t=new WebAssembly.Module(t));let n=new WebAssembly.Instance(t,e);return kg(n,t)}async function xP(t){if(be!==void 0)return be;typeof t<"u"&&(Object.getPrototypeOf(t)===Object.prototype?{module_or_path:t}=t:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),typeof t>"u"&&(t=new URL("jieba_rs_wasm_bg.wasm",import.meta.url));let e=Lg();(typeof t=="string"||typeof Request=="function"&&t instanceof Request||typeof URL=="function"&&t instanceof URL)&&(t=fetch(t));let{instance:n,module:a}=await kP(await t,e);return kg(n,a)}var $g=!1,Ug=(t,e)=>{if(!$g){let n=MP(UP(zP(import.meta.url)),"jieba-engine.wasm");xg({module:$P(n)}),$g=!0}return Rg(t,e)};var FP=new Set(["a","an","and","are","as","at","be","but","by","for","if","in","into","is","it","no","not","of","on","or","such","that","the","their","then","there","these","they","this","to","was","will","with"]),GP=/[a-z0-9]+/g,jP=t=>{let e=t.toLowerCase().replace(/'s\b/g,""),n=[];for(let a of e.matchAll(GP)){let r=a[0];FP.has(r)||n.push(qP(r))}return n},BP=/[㐀-鿿豈--ヿ가-]|[a-z0-9]/i,ZP=t=>Ug(t.toLowerCase(),!0).filter(e=>BP.test(e)),bu=t=>{switch(zn){case"ZION":return ZP(t);case"MOMEN":return jP(t);default:throw new Error(`[analyzer] unknown PRODUCT '${zn}'`)}},$n=(t,e)=>{let n=t[e];return n==="a"||n==="e"||n==="i"||n==="o"||n==="u"?!1:n==="y"?e===0?!0:!$n(t,e-1):!0},Qt=t=>{let e=0,n=!1;for(let a=0;a<t.length;a+=1){let r=!$n(t,a);n&&!r&&(e+=1),n=r}return e},Tu=t=>{for(let e=0;e<t.length;e+=1)if(!$n(t,e))return!0;return!1},Mg=t=>{let e=t.length;return e>=2&&t[e-1]===t[e-2]&&$n(t,e-1)},zg=t=>{let e=t.length;if(e<3||!$n(t,e-1)||$n(t,e-2)||!$n(t,e-3))return!1;let n=t[e-1];return n!=="w"&&n!=="x"&&n!=="y"},Ss=(t,e,n)=>t.slice(0,t.length-e.length)+n;function qP(t){let e=t;if(e.length<=2)return e;e.endsWith("sses")?e=Ss(e,"sses","ss"):e.endsWith("ies")?e=Ss(e,"ies","i"):e.endsWith("ss")||e.endsWith("s")&&(e=e.slice(0,-1));let n=!1;e.endsWith("eed")?Qt(e.slice(0,-3))>0&&(e=e.slice(0,-1)):e.endsWith("ed")&&Tu(e.slice(0,-2))?(e=e.slice(0,-2),n=!0):e.endsWith("ing")&&Tu(e.slice(0,-3))&&(e=e.slice(0,-3),n=!0),n&&(e.endsWith("at")||e.endsWith("bl")||e.endsWith("iz")?e+="e":Mg(e)&&!/[lsz]$/.test(e)?e=e.slice(0,-1):Qt(e)===1&&zg(e)&&(e+="e")),e.endsWith("y")&&Tu(e.slice(0,-1))&&(e=`${e.slice(0,-1)}i`);let a=[["ational","ate"],["tional","tion"],["enci","ence"],["anci","ance"],["izer","ize"],["bli","ble"],["alli","al"],["entli","ent"],["eli","e"],["ousli","ous"],["ization","ize"],["ation","ate"],["ator","ate"],["alism","al"],["iveness","ive"],["fulness","ful"],["ousness","ous"],["aliti","al"],["iviti","ive"],["biliti","ble"],["logi","log"]];for(let[i,l]of a)if(e.endsWith(i)){Qt(e.slice(0,e.length-i.length))>0&&(e=Ss(e,i,l));break}let r=[["icate","ic"],["ative",""],["alize","al"],["iciti","ic"],["ical","ic"],["ful",""],["ness",""]];for(let[i,l]of r)if(e.endsWith(i)){Qt(e.slice(0,e.length-i.length))>0&&(e=Ss(e,i,l));break}let o=["al","ance","ence","er","ic","able","ible","ant","ement","ment","ent","ou","ism","ate","iti","ous","ive","ize"],s=!1;for(let i of o)if(e.endsWith(i)){let l=e.slice(0,e.length-i.length);Qt(l)>1&&(e=l),s=!0;break}if(!s&&e.endsWith("ion")){let i=e.slice(0,-3);Qt(i)>1&&/[st]$/.test(i)&&(e=i)}if(e.endsWith("e")){let i=e.slice(0,-1),l=Qt(i);(l>1||l===1&&!zg(i))&&(e=i)}return Qt(e)>1&&Mg(e)&&e.endsWith("l")&&(e=e.slice(0,-1)),e}u();var Fg=1.5,Gg=.75,VP=t=>{let e=[],n=new Map,a=0;for(let{ref:r,tokens:o}of t){let s=new Map;for(let i of o)s.set(i,(s.get(i)??0)+1);for(let i of s.keys())n.set(i,(n.get(i)??0)+1);e.push({ref:r,tf:s,length:o.length}),a+=o.length}return{docs:e,df:n,avgdl:e.length>0?a/e.length:0}},WP=(t,e)=>{let n=[...new Set(bu(e))],a=t.docs.length;return n.length===0||a===0?[]:t.docs.map(r=>{let o=0;for(let s of n){let i=r.tf.get(s);if(!i)continue;let l=t.df.get(s)??0,d=Math.log(1+(a-l+.5)/(l+.5)),h=i+Fg*(1-Gg+Gg*r.length/(t.avgdl||1));o+=d*(i*(Fg+1)/h)}return{ref:r.ref,score:o}})};u();var wa={actionflow:{pre:{available:!0,prompt:"## Actionflow Domain Knowledge\nActionflows are server-side workflows for business logic. They run entirely on the server; the frontend triggers them via \"Request \u2013 Actionflow\" component actions.\n\n### When to Use an Actionflow\nDo not create an Actionflow merely to proxy CRUD. Simple single-table CRUD should run directly from the frontend when table, column, and row permissions fully express the authorization policy. Reserve Actionflows for genuinely server-side, multi-step, transactional, or orchestrated operations: cross-table atomicity, trusted calculations or secrets, loops, AI steps, third-party calls, schedules, webhooks, and database triggers. If data permissions cannot express the authorization rule, enforce it server-side here. A condition on its own is not a reason to build a flow: a check that only decides what the UI does belongs in the frontend, and only a condition that must be guaranteed rather than merely evaluated has to run here, where the client cannot bypass it. That includes authorization checks \u2014 if the rule is already expressed in table, column, and row permissions, the frontend may hold the condition, because permissions are enforced on every request and nothing the client sends can bypass them. Wrapping such a check in a flow adds a hop and a second place for the rule to drift, without making it any harder to circumvent.\n\n### Execution Modes\nSynchronous: all nodes in one synchronous Actionflow invocation execute inside a single database transaction; the caller blocks for the result, and any node error rolls back every DB write from that invocation. Asynchronous: the caller gets a task handle instead of blocking and retrieves the result later \u2014 the flow still computes and returns its declared output; only the failing node's DB writes roll back; required for AI agents and video generation.\n\nBoth modes share a per-flow total timeout (`ACTION_FLOW_TIMEOUT_MILLISECONDS`): 15 s on free-tier servers, 10 min on paid tiers. The budget is for the entire flow, not per node. A flow can override it with its own `timeout` (`UPDATE_ACTION_FLOW`), so a run outliving the server default means the tier is paid or the flow carries an override \u2014 neither of which is readable from here. Do not infer the tier from a run that finished.\n\n### Triggers\nWhat fires a flow. Four kinds: Manual (a UI action \u2014 no config), scheduled (cron), database-change event, and webhook. Scheduled and database-change triggers are tool-managed: inspect with `GET_ALL_SCHEDULED_TRIGGERS_INFO` / `GET_ALL_DB_TRIGGERS_INFO`, create with `ADD_SCHEDULED_TRIGGERS` (a Quartz cron \u2014 set a future `endInstant` or it never fires) and `ADD_DB_TRIGGERS` (a table + INSERT/UPDATE/DELETE), each pointing at a flow id from `GET_ALL_ACTION_FLOWS_INFO` (update/delete variants too). Manual triggers need no setup; webhook triggers are managed by the separate `webhook` plugin (`ADD_CALLBACK_TRIGGERS`) \u2014 load it to add or edit an incoming HTTP webhook that fires a flow.\n\n### Node Types\nWhat can be added at a position is the add-node menu there: read it with BROWSE_ACTION_FLOW_ADD_NODE_OPTIONS at that same `afterNodeId` and pass that entry's `node` to ADD_ACTION_FLOW_NODE \u2014 the entry already carries every default for that position, and its config fields are yours to override; its `type` and `templateCodeId` name the menu entry, so never assemble those yourself, and an entry disabled there is refused with the same reason. The menu also carries the deployment's **preset integration nodes** (the `TEMPLATE_CODE` entries \u2014 the current user's ID / WeChat OpenID / Access Token, file/media conversion to Zion native types, SMS, and video/AI generation), whose set varies by deployment. There is no built-in `CURRENT_USER` / `FILES` / `SMS` node type; do not pass those to `ADD_ACTION_FLOW_NODE`.\n\n### AI Conversation Nodes\nAI conversation nodes are valid only in asynchronous Actionflows.\n\n`AI_CREATE_CONVERSATION` creates a new conversation and runs its first turn. Bind the Agent's declared inputs; Start has no free-form message field because the first user message comes from the Agent's configured prompt. When the node completes, `id` is the conversation ID and `data` is the Agent result. For plain output, `data` is text; for structured output, it has the Agent's declared output type. `id` and `data` are the stable fields. Inspect the node's data-binding options for feature-dependent reasoning and media outputs.\n\n`AI_SEND_MESSAGE` continues an existing conversation. Continue returns the same `id` and `data` shape as Start. Bind `conversationId` to the `id` returned by Start, then bind the new message. Continue uses the Agent configuration stored by Start; selecting another Agent on Continue does not switch the conversation. Use the same `configId` as Start so validation and output typing remain correct.\n\n`AI_STOP_RESPONSE` cancels only the response currently being generated. It preserves the conversation, which may later be continued. `AI_DELETE_CONVERSATION` permanently deletes the conversation and its messages. Stop and Delete have no node output.\n\nUse the target node's data-binding options to select the preceding Start or Continue node's `id`; the event's `taskId` is not a conversation ID.\n\nStart and Continue are wait points: the Actionflow does not proceed to the next node until the AI response finishes. A Stop node placed after Start or Continue therefore cannot stop that response.\n\n**Current runtime limitation:** There is currently no safe cancellation path for a response launched by an Actionflow. Do not use Stop for a response launched by an Actionflow. Stop acts only while the stored status is `IN_PROGRESS`; once it is `STREAMING`, Stop does not cancel the response. If Stop reaches an in-progress response, canceling leaves the AI child task processing, so the source Actionflow never resumes.\n\n### Choosing How to Express Logic: nodes \u2192 formulas \u2192 code\nThree tiers, in order of preference:\n1. **Visual nodes** for orchestration \u2014 query / branch / iterate / write / call (Database, Condition, Loop, Set Variable, Call API, Run Actionflow). They take part in the flow's transaction, surface individually in logs and the edit-time error collector, and stay user-editable.\n2. **Formula bindings** for value-level computation. A node value \u2014 a Set Variable value, a mutation column, a condition predicate \u2014 can be a FORMULA binding built with the bindings plugin, and formulas cover far more than people expect: text and regex (extract / match / replace, substring, split, concat), math, date/time arithmetic and formatting, array aggregation / mapping / filtering, JSON value access, and type casts. Prefer a formula over code whenever you are computing a single value.\n3. **Run Code** only for genuinely procedural logic that neither a node nor a formula operator expresses \u2014 e.g. cryptographic hashing / signature building, multi-step algorithms with intermediate state, or assembling / parsing a complex nested payload. Keep it small and fed by node inputs; never collapse a whole flow into one Run Code node.\n\n### Variables\nDeclared at flow level, accessible by all nodes, assigned with \"Set Variable\" node.\n\n### Inputs & Outputs\nInspect a flow first with `GET_ALL_ACTION_FLOWS_INFO` / `GET_ACTION_FLOW_DETAIL` (unless its detail is already provided in your context). Declare typed **input params** with `ADD_ACTION_FLOW_INPUT_PARAMS`; set each param's type to a value copied verbatim from `GET_ACTION_FLOW_SELECTABLE_TYPES` (never hand-build the type string). Every input param, variable, output field and code-node input/output name is an identifier: letters, digits and underscores only, never starting with a digit. The editor enforces the same rule on a manual rename, so a name that breaks it is one the user cannot repair in the UI; put user-facing wording in a displayName or description instead.\n\n### List Input Workaround\nInput parameters accept only scalar basic types; they cannot receive arrays. When a caller needs to supply a list of objects, persist the list before invoking the flow: create one parent/request record, save each list item as a child record related to that parent, and pass only the parent's ID as a scalar input. In the flow, query the related child records and use a Loop node to process the query result. For example, for a checkout with cart items, create one `CheckoutRequest`, create one related `CheckoutItem` per `{productId, quantity}`, invoke the flow with `checkoutRequestId`, then query and loop over those items. Validate that the parent belongs to the caller before processing it; do not encode the list as text merely to bypass the input type restriction.\n\nA flow returns a **set of named output fields**: add them with `ADD_ACTION_FLOW_OUTPUT_FIELDS`\n(one entry per field, each with its own type) and remove them with\n`DELETE_ACTION_FLOW_OUTPUT_FIELDS`.\n\n### Building & Editing a Flow\nCreate flows with `ADD_ACTION_FLOWS` (each seeds an empty FLOW_START \u2192 FLOW_END), then read node and structure ids from `GET_ACTION_FLOW_DETAIL` before editing. See what can be added after a node with `BROWSE_ACTION_FLOW_ADD_NODE_OPTIONS` at that same position, then add an entry's `node` with `ADD_ACTION_FLOW_NODE`; reorder with `MOVE_ACTION_FLOW_NODES`, remove with `DELETE_ACTION_FLOW_NODES`, and branch a Condition node with `ADD_ACTION_FLOW_BRANCH_ITEM`. Every node's displayName should state its business intent ('Insert generation request', 'Decrement like count') rather than the node-type default \u2014 it is optional, and a name left off becomes that default, so omit it only when no better name fits. Edit a node's name or type-scalar config with `UPDATE_ACTION_FLOW_NODE`, but set its data bindings (values, conditions, data sources, mutation fields) with the bindings plugin at the node's schema path \u2014 never inline. A node's schema path is NEVER hand-built: copy it from `ADD_ACTION_FLOW_NODE`'s result or `GET_ACTION_FLOW_DETAIL`'s nodeSchemaPaths (form: server/actionFlows/{i}/allNodes/{j}), then append key segments to reach a binding site inside the node. The key names vary by node type \u2014 an AI node's input arg is `.../allNodes/{j}/inputArgs/<argKey>`, a code node's is `.../allNodes/{j}/inputArgsDataBinding/<argName>`, a mutation column is `.../allNodes/{j}/mutation/object/<columnName>` \u2014 copy the exact keys from `GET_ACTION_FLOW_CONTEXT_INFO`'s currentNode structure, never guess them. Declare flow variables with `ADD_ACTION_FLOW_GLOBAL_VARIABLES` and assign them in a Set Variable node with `ADD_GLOBAL_VARIABLES_NODE_TARGETS`. A Run Code node's `args.<name>` input slots are managed with `ADD_CUSTOM_CODE_NODE_INPUT` (rename/delete variants); its named result values are declared with `ADD_CUSTOM_CODE_NODE_OUTPUT_VALUE` (update/delete variants) so downstream nodes can bind to them; fill the code body with `CREATE_CONST_BINDING`. An update or delete Database node is seeded with an always-true filter that matches **every** row \u2014 narrow it with the bindings plugin's request filters before syncing, or the write hits the whole table. A Third-Party API node's request parameters are pre-seeded on the node when the API is selected \u2014 read the node back and bind ONLY the parameter slots it shows in the legacy `event/input` tree, e.g. `.../event/input/object/{k}/value`. NEVER invent input keys the read-back does not show: the runtime and editor ignore them.\n\n### Condition Branches\nCondition branches use their left-to-right editor order. At runtime, only the first branch whose condition is true has its branch body executed; branches to its right are not entered. Put an `Always` branch last when fallback behavior is required\u2014an earlier `Always` branch shadows every branch to its right. Do not rely on the no-match behavior; provide an explicit fallback whenever the flow must choose a branch. Only `MUTUAL_EXCLUSION` is supported. `MUTUAL_TOLERANCE` may still appear in generated argument schemas, but tolerance branches are not implemented and fail at runtime. Always set a Condition node's `conditionType` to `MUTUAL_EXCLUSION`.\n\n### Node Input Visibility (Scope)\nWhat a node can bind to is not \"any earlier node\": ztype limits it to the nodes **visible** from that site \u2014 the ones on its straight path back from FLOW_START. The data binding options tree returned with every binding response (its \"Actionflow data\" branch) already applies this rule and is the authoritative list of reachable node outputs; if a node is absent there it is out of scope, so never hand-build a path to reach it.\n\nLoops and Condition branches are **one-way scopes**. From *inside* a block, a node sees the outer scope, the flow inputs, and \u2014 in a Loop \u2014 the current item; but from *outside* the block (any node after the loop's end or after a branch merge) the block's inner nodes are invisible, and sibling branches never see one another. A value produced inside one branch or one loop iteration therefore CANNOT be bound directly by a later node \u2014 it will not appear in that node's options tree.\n\nTo carry a branch- or loop-dependent value past the block, use a **flow variable** \u2014 the only output that crosses a scope boundary. Declare it once with `ADD_ACTION_FLOW_GLOBAL_VARIABLES` (type copied from `GET_ACTION_FLOW_SELECTABLE_TYPES`), assign it *inside* the branch or loop body with a Set Variable node (`ADD_GLOBAL_VARIABLES_NODE_TARGETS`), then read the variable from any later node. Idioms: choose a value by branch \u2014 assign the SAME variable in every branch, then read it after the merge; capture or accumulate across a Loop \u2014 assign the variable inside the loop body, then read it after the loop's end. A branch that never assigns the variable leaves its prior value, so set a sensible default before the branch when every path must yield one.\n\n### Concurrency\nConcurrent invocations of the same flow interleave between nodes; sync-mode ACID rolls back on error but does NOT serialize flows (read committed). Query-a-row, branch, then write based on that read is a race: concurrent calls all act on the same stale read. Where the platform can express the check inside the write, prefer that: put row-local guards in the mutation node's own filter (update where stock >= qty; delete where the key pair matches) and branch on the write's affected rows; use an update node's increment/decrement mode for counters; for insert-if-absent or toggle semantics use a unique constraint (the only DB-enforced constraint kind today) with `insert ... on_conflict do nothing` and branch on affected_rows \u2014 that idiom is only expressible in a Run Code node, which makes it a legitimate Run Code use. Invariants none of these can express (cross-row rules, aggregates) have no atomic form yet; check-then-write is the accepted fallback there.\n\n### Error Handling\nSynchronous: all DB changes roll back on error. Asynchronous: only the failing node's DB changes roll back.\n\n### Versioning\nEach save creates a new version. \"Sync Backend\" required after editing for changes to take effect in production.\n\n### JavaScript Sandbox (Run Code node)\nCustom Code Blocks run in a synchronous GraalJS server sandbox. No async/await, no require(), no browser APIs. All platform interactions go through the global `context` object: context.getArg(key) \u2014 retrieve flow input context.setReturn(key, val) \u2014 pass output to downstream nodes context.runGql(opName, gql, vars, permission) \u2014 execute DB operations context.callThirdPartyApi(apiId, params) \u2014 invoke a configured Third-Party API context.callActionFlow(flowId, ver, args) \u2014 run a sub-flow synchronously context.createActionFlowTask(flowId, ver, args) \u2014 trigger a sub-flow async context.getSsoUserInfo() \u2014 get authenticated user profile context.uploadMedia(url, headers) \u2014 stream remote image to asset server context.log(message) \u2014 emit to Log Service\n\n`runGql` takes FOUR arguments and the first one is the operation NAME, not the document: `runGql(\"GetWords\", \"query GetWords { theme_word(where: {...}) { word } }\", {}, {role: \"admin\"})`. The name must match the one declared in the document. `vars` is a JS object (not a JSON string) and `permission` is `{role: \"<role name>\"}` with an optional `sessionVariable` map. Passing the document first is the mistake that costs an afternoon: the arity error, then a String-coercion error naming a type you did not pass, then \"permission should have field role\" are all the same misalignment reported one argument at a time.\n\nIt returns the `data` object directly \u2014 `r.theme_word`, never `r.data.theme_word` \u2014 and it THROWS on a GraphQL error rather than returning an `errors` array, so there is no envelope to branch on. Do not write defensive code for a response shape you have not seen.\n\nThe list above is the methods you will reach for, not the whole API. The complete Context API reference \u2014 every method with its parameters and return shape \u2014 is the \"Develop with Run Code\" developer page: find it with `docs.search`, and read it rather than inferring a signature from an error message. Search by title; the page's path is not the same across products."},post:{available:!0,prompt:"## Actionflow Domain Knowledge\nActionflows are server-side workflows for business logic. They run entirely on the server; the frontend triggers them via \"Request \u2013 Actionflow\" component actions.\n\n### When to Use an Actionflow\nDo not create an Actionflow merely to proxy CRUD. Simple single-table CRUD should run directly from the frontend when table, column, and row permissions fully express the authorization policy. Reserve Actionflows for genuinely server-side, multi-step, transactional, or orchestrated operations: cross-table atomicity, trusted calculations or secrets, loops, AI steps, third-party calls, schedules, webhooks, and database triggers. If data permissions cannot express the authorization rule, enforce it server-side here. A condition on its own is not a reason to build a flow: a check that only decides what the UI does belongs in the frontend, and only a condition that must be guaranteed rather than merely evaluated has to run here, where the client cannot bypass it. That includes authorization checks \u2014 if the rule is already expressed in table, column, and row permissions, the frontend may hold the condition, because permissions are enforced on every request and nothing the client sends can bypass them. Wrapping such a check in a flow adds a hop and a second place for the rule to drift, without making it any harder to circumvent.\n\n### Execution Modes\nSynchronous: all nodes in one synchronous Actionflow invocation execute inside a single database transaction; the caller blocks for the result, and any node error rolls back every DB write from that invocation. Asynchronous: the caller gets a task handle instead of blocking and retrieves the result later \u2014 the flow still computes and returns its declared output; only the failing node's DB writes roll back; required for AI agents and video generation.\n\nBoth modes share a per-flow total timeout (`ACTION_FLOW_TIMEOUT_MILLISECONDS`): 15 s on free-tier servers, 10 min on paid tiers. The budget is for the entire flow, not per node. A flow can override it with its own `timeout` (`UPDATE_ACTION_FLOW`), so a run outliving the server default means the tier is paid or the flow carries an override \u2014 neither of which is readable from here. Do not infer the tier from a run that finished.\n\n### Triggers\nWhat fires a flow. Four kinds: Manual (a UI action \u2014 no config), scheduled (cron), database-change event, and webhook. Scheduled and database-change triggers are tool-managed: inspect with `GET_ALL_SCHEDULED_TRIGGERS_INFO` / `GET_ALL_DB_TRIGGERS_INFO`, create with `ADD_SCHEDULED_TRIGGERS` (a Quartz cron \u2014 set a future `endInstant` or it never fires) and `ADD_DB_TRIGGERS` (a table + INSERT/UPDATE/DELETE), each pointing at a flow id from `GET_ALL_ACTION_FLOWS_INFO` (update/delete variants too). Manual triggers need no setup; webhook triggers are managed by the separate `webhook` plugin (`ADD_CALLBACK_TRIGGERS`) \u2014 load it to add or edit an incoming HTTP webhook that fires a flow.\n\n### Node Types\nWhat can be added at a position is the add-node menu there: read it with BROWSE_ACTION_FLOW_ADD_NODE_OPTIONS at that same `afterNodeId` and pass that entry's `node` to ADD_ACTION_FLOW_NODE \u2014 the entry already carries every default for that position, and its config fields are yours to override; its `type` and `templateCodeId` name the menu entry, so never assemble those yourself, and an entry disabled there is refused with the same reason. The menu also carries the deployment's **preset integration nodes** (the `TEMPLATE_CODE` entries \u2014 the current user's ID / WeChat OpenID / Access Token, file/media conversion to Zion native types, SMS, and video/AI generation), whose set varies by deployment. There is no built-in `CURRENT_USER` / `FILES` / `SMS` node type; do not pass those to `ADD_ACTION_FLOW_NODE`.\n\n### AI Conversation Nodes\nAI conversation nodes are valid only in asynchronous Actionflows.\n\n`AI_CREATE_CONVERSATION` creates a new conversation and runs its first turn. Bind the Agent's declared inputs; Start has no free-form message field because the first user message comes from the Agent's configured prompt. When the node completes, `id` is the conversation ID and `data` is the Agent result. For plain output, `data` is text; for structured output, it has the Agent's declared output type. `id` and `data` are the stable fields. Inspect the node's data-binding options for feature-dependent reasoning and media outputs.\n\n`AI_SEND_MESSAGE` continues an existing conversation. Continue returns the same `id` and `data` shape as Start. Bind `conversationId` to the `id` returned by Start, then bind the new message. Continue uses the Agent configuration stored by Start; selecting another Agent on Continue does not switch the conversation. Use the same `configId` as Start so validation and output typing remain correct.\n\n`AI_STOP_RESPONSE` cancels only the response currently being generated. It preserves the conversation, which may later be continued. `AI_DELETE_CONVERSATION` permanently deletes the conversation and its messages. Stop and Delete have no node output.\n\nUse the target node's data-binding options to select the preceding Start or Continue node's `id`; the event's `taskId` is not a conversation ID.\n\nStart and Continue are wait points: the Actionflow does not proceed to the next node until the AI response finishes. A Stop node placed after Start or Continue therefore cannot stop that response.\n\n**Current runtime limitation:** There is currently no safe cancellation path for a response launched by an Actionflow. Do not use Stop for a response launched by an Actionflow. Stop acts only while the stored status is `IN_PROGRESS`; once it is `STREAMING`, Stop does not cancel the response. If Stop reaches an in-progress response, canceling leaves the AI child task processing, so the source Actionflow never resumes.\n\n### Choosing How to Express Logic: nodes \u2192 formulas \u2192 code\nThree tiers, in order of preference:\n1. **Visual nodes** for orchestration \u2014 query / branch / iterate / write / call (Database, Condition, Loop, Set Variable, Call API, Run Actionflow). They take part in the flow's transaction, surface individually in logs and the edit-time error collector, and stay user-editable.\n2. **Formula bindings** for value-level computation. A node value \u2014 a Set Variable value, a mutation column, a condition predicate \u2014 can be a FORMULA binding built with the bindings plugin, and formulas cover far more than people expect: text and regex (extract / match / replace, substring, split, concat), math, date/time arithmetic and formatting, array aggregation / mapping / filtering, JSON value access, and type casts. Prefer a formula over code whenever you are computing a single value.\n3. **Run Code** only for genuinely procedural logic that neither a node nor a formula operator expresses \u2014 e.g. cryptographic hashing / signature building, multi-step algorithms with intermediate state, or assembling / parsing a complex nested payload. Keep it small and fed by node inputs; never collapse a whole flow into one Run Code node.\n\n### Variables\nDeclared at flow level, accessible by all nodes, assigned with \"Set Variable\" node.\n\n### Inputs & Outputs\nInspect a flow first with `GET_ALL_ACTION_FLOWS_INFO` / `GET_ACTION_FLOW_DETAIL` (unless its detail is already provided in your context). Declare typed **input params** with `ADD_ACTION_FLOW_INPUT_PARAMS`; set each param's type to a value copied verbatim from `GET_ACTION_FLOW_SELECTABLE_TYPES` (never hand-build the type string). Every input param, variable, output field and code-node input/output name is an identifier: letters, digits and underscores only, never starting with a digit. The editor enforces the same rule on a manual rename, so a name that breaks it is one the user cannot repair in the UI; put user-facing wording in a displayName or description instead.\n\nA flow returns a **single typed output value**: set its type with `SET_ACTION_FLOW_OUTPUT`\n(type copied from `GET_ACTION_FLOW_SELECTABLE_TYPES`) and clear it with\n`CLEAR_ACTION_FLOW_OUTPUT`; bind the value afterwards at the output's schema path.\n\n### Building & Editing a Flow\nCreate flows with `ADD_ACTION_FLOWS` (each seeds an empty FLOW_START \u2192 FLOW_END), then read node and structure ids from `GET_ACTION_FLOW_DETAIL` before editing. See what can be added after a node with `BROWSE_ACTION_FLOW_ADD_NODE_OPTIONS` at that same position, then add an entry's `node` with `ADD_ACTION_FLOW_NODE`; reorder with `MOVE_ACTION_FLOW_NODES`, remove with `DELETE_ACTION_FLOW_NODES`, and branch a Condition node with `ADD_ACTION_FLOW_BRANCH_ITEM`. Every node's displayName should state its business intent ('Insert generation request', 'Decrement like count') rather than the node-type default \u2014 it is optional, and a name left off becomes that default, so omit it only when no better name fits. Edit a node's name or type-scalar config with `UPDATE_ACTION_FLOW_NODE`, but set its data bindings (values, conditions, data sources, mutation fields) with the bindings plugin at the node's schema path \u2014 never inline. A node's schema path is NEVER hand-built: copy it from `ADD_ACTION_FLOW_NODE`'s result or `GET_ACTION_FLOW_DETAIL`'s nodeSchemaPaths (form: server/actionFlows/{i}/allNodes/{j}), then append key segments to reach a binding site inside the node. The key names vary by node type \u2014 an AI node's input arg is `.../allNodes/{j}/inputArgs/<argKey>`, a code node's is `.../allNodes/{j}/inputs/{index}/value`, a mutation column is `.../allNodes/{j}/mutation/object/<columnName>` \u2014 copy the exact keys from `GET_ACTION_FLOW_CONTEXT_INFO`'s currentNode structure, never guess them. Declare flow variables with `ADD_ACTION_FLOW_GLOBAL_VARIABLES` and assign them in a Set Variable node with `ADD_GLOBAL_VARIABLES_NODE_TARGETS`. A Run Code node's `args.<name>` input slots are managed with `ADD_CUSTOM_CODE_NODE_INPUT` (rename/delete variants); its result type is declared with `SET_CUSTOM_CODE_NODE_OUTPUT_TYPE` so downstream nodes can bind to it; fill the code body with `CREATE_CONST_BINDING`. An update or delete Database node is seeded with an always-true filter that matches **every** row \u2014 narrow it with the bindings plugin's request filters before syncing, or the write hits the whole table. A workspace API node's request parameters are pre-seeded on the node when the API is selected \u2014 read the node back and bind ONLY the parameter slots it shows under `event/inputs/<param>`. NEVER invent input keys the read-back does not show: the runtime and editor ignore them.\n\n### Condition Branches\nCondition branches use their left-to-right editor order. At runtime, only the first branch whose condition is true has its branch body executed; branches to its right are not entered. Put an `Always` branch last when fallback behavior is required\u2014an earlier `Always` branch shadows every branch to its right. Do not rely on the no-match behavior; provide an explicit fallback whenever the flow must choose a branch. Only `MUTUAL_EXCLUSION` is supported. `MUTUAL_TOLERANCE` may still appear in generated argument schemas, but tolerance branches are not implemented and fail at runtime. Always set a Condition node's `conditionType` to `MUTUAL_EXCLUSION`.\n\n### Node Input Visibility (Scope)\nWhat a node can bind to is not \"any earlier node\": ztype limits it to the nodes **visible** from that site \u2014 the ones on its straight path back from FLOW_START. The data binding options tree returned with every binding response (its \"Actionflow data\" branch) already applies this rule and is the authoritative list of reachable node outputs; if a node is absent there it is out of scope, so never hand-build a path to reach it.\n\nLoops and Condition branches are **one-way scopes**. From *inside* a block, a node sees the outer scope, the flow inputs, and \u2014 in a Loop \u2014 the current item; but from *outside* the block (any node after the loop's end or after a branch merge) the block's inner nodes are invisible, and sibling branches never see one another. A value produced inside one branch or one loop iteration therefore CANNOT be bound directly by a later node \u2014 it will not appear in that node's options tree.\n\nTo carry a branch- or loop-dependent value past the block, use a **flow variable** \u2014 the only output that crosses a scope boundary. Declare it once with `ADD_ACTION_FLOW_GLOBAL_VARIABLES` (type copied from `GET_ACTION_FLOW_SELECTABLE_TYPES`), assign it *inside* the branch or loop body with a Set Variable node (`ADD_GLOBAL_VARIABLES_NODE_TARGETS`), then read the variable from any later node. Idioms: choose a value by branch \u2014 assign the SAME variable in every branch, then read it after the merge; capture or accumulate across a Loop \u2014 assign the variable inside the loop body, then read it after the loop's end. A branch that never assigns the variable leaves its prior value, so set a sensible default before the branch when every path must yield one.\n\n### Concurrency\nConcurrent invocations of the same flow interleave between nodes; sync-mode ACID rolls back on error but does NOT serialize flows (read committed). Query-a-row, branch, then write based on that read is a race: concurrent calls all act on the same stale read. Where the platform can express the check inside the write, prefer that: put row-local guards in the mutation node's own filter (update where stock >= qty; delete where the key pair matches) and branch on the write's affected rows; use an update node's increment/decrement mode for counters; for insert-if-absent or toggle semantics use a unique constraint (the only DB-enforced constraint kind today) with `insert ... on_conflict do nothing` and branch on affected_rows \u2014 that idiom is only expressible in a Run Code node, which makes it a legitimate Run Code use. Invariants none of these can express (cross-row rules, aggregates) have no atomic form yet; check-then-write is the accepted fallback there.\n\n### Error Handling\nSynchronous: all DB changes roll back on error. Asynchronous: only the failing node's DB changes roll back.\n\n### Versioning\nEach save creates a new version. \"Sync Backend\" required after editing for changes to take effect in production.\n\n### JavaScript Sandbox (Run Code node)\nCustom Code Blocks run in a synchronous GraalJS server sandbox. No async/await, no require(), no browser APIs. All platform interactions go through the global `context` object: context.getArg(key) \u2014 retrieve flow input context.setResult(val) \u2014 pass this node's single result downstream context.runGql(opName, gql, vars, permission) \u2014 execute DB operations context.callThirdPartyApi(apiId, params) \u2014 invoke a workspace API by its apiId (the method name is historical; this project has no third-party API configs) context.callActionFlow(flowId, ver, args) \u2014 run a sub-flow synchronously context.createActionFlowTask(flowId, ver, args) \u2014 trigger a sub-flow async context.getSsoUserInfo() \u2014 get authenticated user profile context.uploadMedia(url, headers) \u2014 stream remote image to asset server context.log(message) \u2014 emit to Log Service\n\n`runGql` takes FOUR arguments and the first one is the operation NAME, not the document: `runGql(\"GetWords\", \"query GetWords { theme_word(where: {...}) { word } }\", {}, {role: \"admin\"})`. The name must match the one declared in the document. `vars` is a JS object (not a JSON string) and `permission` is `{role: \"<role name>\"}` with an optional `sessionVariable` map. Passing the document first is the mistake that costs an afternoon: the arity error, then a String-coercion error naming a type you did not pass, then \"permission should have field role\" are all the same misalignment reported one argument at a time.\n\nIt returns the `data` object directly \u2014 `r.theme_word`, never `r.data.theme_word` \u2014 and it THROWS on a GraphQL error rather than returning an `errors` array, so there is no envelope to branch on. Do not write defensive code for a response shape you have not seen.\n\nThe list above is the methods you will reach for, not the whole API. The complete Context API reference \u2014 every method with its parameters and return shape \u2014 is the \"Develop with Run Code\" developer page: find it with `docs.search`, and read it rather than inferring a signature from an error message. Search by title; the page's path is not the same across products."}},agent:{pre:{available:!0,prompt:`Zion is a powerful no-code development platform that enables developers to build and deploy web, mobile, and WeChat Mini Program (\u5FAE\u4FE1\u5C0F\u7A0B\u5E8F) applications. It integrates a visual drag-and-drop design canvas, an enterprise-grade relational database engine (PostgreSQL), and an event-driven backend logic execution pipeline.
|
|
44
|
+
|
|
45
|
+
This overview details the structural design, data engines, execution pipelines, and safety requirements of the platform.
|
|
46
|
+
|
|
47
|
+
---
|
|
48
|
+
|
|
49
|
+
## 1. Architectural Philosophy (The Three Pillars)
|
|
50
|
+
|
|
51
|
+
Zion decouples application systems into three isolated yet bound layers:
|
|
52
|
+
|
|
53
|
+
1. **Design**: The presentation layer, built strictly on nested HTML components obeying the CSS Box Model and CSS Flexbox layouts.
|
|
54
|
+
2. **Data**: The persistence layer, powered by a built-in, highly-scalable relational database engine (PostgreSQL). All UI contents are dynamically populated by binding to database rows or Third-Party API schemas.
|
|
55
|
+
3. **Action**: The behavior layer, using an event-driven "Trigger -> Execution" model that connects frontend components to local client tasks or backend operations.
|
|
56
|
+
|
|
57
|
+
---
|
|
58
|
+
|
|
59
|
+
## 2. The Mental Model & Engineering Workflow
|
|
60
|
+
|
|
61
|
+
Building on Zion happens at two levels, and they are not interchangeable. Level one decides **what this release is**; level two builds it. Outlining a solution straight into an ER diagram skips the decision that sets how large that diagram should be, which is what produces a project where every part is half-finished at once instead of one part working.
|
|
62
|
+
|
|
63
|
+
### 2.1 Level One \u2014 Scope The Release
|
|
64
|
+
|
|
65
|
+
A request names a product; it does not name a first release. Deciding that is your job. When a request describes a whole product \u2014 typically the first message of a new project \u2014 cut the work into releases before you model any data; a change to an app that already exists goes straight to level two:
|
|
66
|
+
|
|
67
|
+
* **MVP**: one role, one happy path, the fewest tables that make it real. It must open and demonstrate the idea, not sketch every screen.
|
|
68
|
+
* **1.0**: the secondary flows around that path.
|
|
69
|
+
* **2.0**: admin, operations, analytics.
|
|
70
|
+
|
|
71
|
+
State the cut in one line before you build anything, in the language the user writes in \u2014 e.g. "MVP: a customer browses products and places an order; membership balance and points come in 1.0." A stated cut gets corrected in one sentence; an unstated one is discovered when the user asks where the rest went. Then carry only the MVP into level two, and name what you deferred rather than dropping it silently: work that disappears without being named reads as you having missed half the request.
|
|
72
|
+
|
|
73
|
+
### 2.2 Level Two \u2014 Build That Release Data-First
|
|
74
|
+
|
|
75
|
+
Within the release you just scoped \u2014 never across the whole product \u2014 Zion requires a rigorous **data-first** engineering approach. Outline that release in this exact order:
|
|
76
|
+
|
|
77
|
+
1. **Data Modeling**: Design the Entity-Relationship (ER) diagram, database tables, constraints, and relationships first.
|
|
78
|
+
2. **UI Layout**: Construct nested structural containers (Views) and map static display/input components onto them.
|
|
79
|
+
3. **Logic & Binding**: Link dynamic variables/fields to inputs/displays, then map actions or backend workflows to events.
|
|
80
|
+
4. **Verification**: Run diagnostic reviews using edit-time error panels and runtime log tracing before deploying.
|
|
81
|
+
|
|
82
|
+
---
|
|
83
|
+
|
|
84
|
+
## 3. Database Architecture & Data Binding
|
|
85
|
+
|
|
86
|
+
Zion runs on an enterprise-grade relational database powered by PostgreSQL.
|
|
87
|
+
|
|
88
|
+
### 3.1 Relationship Modeling
|
|
89
|
+
All table relations map directly to standard SQL constraints:
|
|
90
|
+
* **One-to-One (1:1)**: e.g., \`account\` <-> \`user_profile\`. Direct foreign key binding.
|
|
91
|
+
* **One-to-Many (1:N)**: e.g., \`account\` -> \`post\` (One author, multiple posts).
|
|
92
|
+
* **Many-to-Many (N:M)**: Must be configured using a **junction/intermediate table** with two distinct 1:N relations. e.g., \`account\` -> \`enrollment\` <- \`course\` represents a Many-to-Many relation between students and courses.
|
|
93
|
+
|
|
94
|
+
### 3.2 State and Variable Scopes
|
|
95
|
+
Zion distinguishes scopes by lifecycle and visibility:
|
|
96
|
+
|
|
97
|
+
**Application scope** (lifetime = app session):
|
|
98
|
+
* **Global Variable**: shared across all pages. Theme, feature flags, cached user state.
|
|
99
|
+
* **Current User**: the logged-in user object \u2014 id, profile fields, SSO claims.
|
|
100
|
+
|
|
101
|
+
**Page scope** (lifetime = current page):
|
|
102
|
+
* **Page Parameter**: passed from the caller. Path params (\`/product/:id\`) and query params (\`?q=abc\`) are both Page Parameters.
|
|
103
|
+
* **Page Variable**: local UI/form state \u2014 active tab, search keywords, loading flag.
|
|
104
|
+
* **Page Data**: result of the page's Page Data Source (a remote query the page binds at load).
|
|
105
|
+
* **Component State**: the value of stateful input components (Input, Select, Switch). Two-way binding writes flow back into Component State automatically.
|
|
106
|
+
|
|
107
|
+
**List-iteration scope** (lifetime = single rendered row):
|
|
108
|
+
* **Current Item**: the row object inside a List component. Child components inside the list bind to \`Current Item.field\` instead of re-querying the table.
|
|
109
|
+
|
|
110
|
+
**Action-Flow scope** (lifetime = single flow execution):
|
|
111
|
+
* **Action Input**: parameters declared on the flow's Start node.
|
|
112
|
+
* **Flow Variable**: locals declared by a "Set Variable" node; visible to subsequent nodes in the same flow.
|
|
113
|
+
* **Flow Output**: named output fields returned by the flow \u2014 visible to the caller.
|
|
114
|
+
* **Loop Item**: the current iteration value inside a Loop node.
|
|
115
|
+
|
|
116
|
+
### 3.3 Data Interaction Types
|
|
117
|
+
Zion splits operations into two non-overlapping categories to prevent infinite render loops:
|
|
118
|
+
* **Query (Read-Only)**: Idempotent operations that fetch data. Used directly as dynamic data sources for Lists, Select Views, and Pages.
|
|
119
|
+
* **Mutation (State-Changing)**: Operations that insert, update, or delete records. These **must** be explicitly triggered as actions (e.g., On Click events) and can never be used as static data sources.
|
|
120
|
+
|
|
121
|
+
### 3.4 Data Binding
|
|
122
|
+
Data binding connects data sources to component properties. A property can be set to:
|
|
123
|
+
* **OPTION**: a live value from the hierarchical data binding options tree \u2014 sources include database table fields, page variables, global variables, logged-in user, list item context ("Current Item"), and actionflow inputs/outputs. The exact \`pathInHierarchicalMenu\` must match the options tree; never fabricate a path.
|
|
124
|
+
* **CONST_VALUE**: a literal constant (string, number, boolean).
|
|
125
|
+
* **DISPLAY_NAME**: rename the component's displayed label.
|
|
126
|
+
|
|
127
|
+
Every bindable slot \u2014 a component property, an action-flow node's input, a request filter's comparison value \u2014 is addressed by a **schemaPath**: an ordered array of steps into the project's JSON schema, \`{"key":"<field>"}\` into an object or \`{"index":N}\` into an array, never both in one step. A schemaPath is read back, never composed by hand \u2014 the call that creates a slot echoes the path of what it made, and the context reads return the finer paths inside it. Build top-down (create, read back the echoed path, then drill in) and the path you need is always one you already hold.
|
|
128
|
+
|
|
129
|
+
Lists render one row per record from their data source. Children inside a list bind to the list's "Current Item" context (a scoped reference to that row's fields) rather than querying a new table \u2014 this preserves the relational link.
|
|
130
|
+
|
|
131
|
+
---
|
|
132
|
+
|
|
133
|
+
## 4. Visual Layout & Positioning Engine
|
|
134
|
+
|
|
135
|
+
Zion's canvas operates as a visual CSS rendering engine: components are nested Flexbox containers obeying the CSS box model, laid out in the natural document flow unless deliberately taken out of it. The component plugin's own guidance is authoritative for positioning, container sizing, breakpoints, and when a conditional container is the right structure rather than a conditional value or a conditional action \u2014 consult it there rather than deciding any of that from this overview.
|
|
136
|
+
|
|
137
|
+
---
|
|
138
|
+
|
|
139
|
+
## 5. Logic Engines: Frontend vs. Backend
|
|
140
|
+
|
|
141
|
+
### 5.1 Frontend Actions
|
|
142
|
+
Lightweight operations executing directly in the client browser/app. Triggered by UI events.
|
|
143
|
+
|
|
144
|
+
**Prefer direct frontend CRUD**: The frontend can insert/update/delete rows directly for simple single-table CRUD when table, column, and row permissions fully express the authorization policy. Do not create an Actionflow merely to proxy CRUD. Reserve Backend Actionflows for genuinely server-side, multi-step, transactional, or orchestrated operations: cross-table atomicity, trusted calculations or secrets, branching or loops, third-party calls, schedules, webhooks, and database triggers. If data permissions cannot express the authorization rule, enforce it server-side in an Actionflow \u2014 see \xA76.
|
|
145
|
+
|
|
146
|
+
**The authoritative list of what a frontend action can do** is the component plugin's selectable-actions read plus that tool's parameter schema \u2014 they are filtered to this project and platform and they are complete. The editor offers navigation, toasts and dialogs, local and global state writes, data refresh and list control, file upload / download / clipboard / QR, AI agent invocation, authentication, payments, animation, and platform-specific capabilities. Do not tell a user an interaction is impossible, or reach for an Actionflow to get it, before checking there.
|
|
147
|
+
|
|
148
|
+
### 5.2 Backend Actionflows
|
|
149
|
+
Server-side visual execution graphs used to perform robust operations. They are triggered by:
|
|
150
|
+
* Client requests (explicit frontend action calls).
|
|
151
|
+
* Cron schedules (scheduled background workflows).
|
|
152
|
+
* Webhooks (third-party external integrations).
|
|
153
|
+
* Database Triggers (automatically runs on \`INSERT\`/\`UPDATE\`/\`DELETE\` of target tables).
|
|
154
|
+
|
|
155
|
+
**Node types available inside an Actionflow:** the authoritative list is the flow's add-node menu at the position \u2014 read it with the actionflow plugin and pass that entry's \`node\`, rather than choosing from a fixed list; an entry it disables is refused with that reason. Its entries span database reads and writes, Call Third-Party API, Run AI (async only), calling another flow (sync cannot call async), variables, permissions, JavaScript and branching or loops. Current-user and file/media operations are preset integration nodes, not built-in node types \u2014 the menu carries the deployment's \`TEMPLATE_CODE\` entries for them (SMS, video/AI generation, \u2026), whose set changes over time. There is no built-in \`CURRENT_USER\` / \`FILES\` / \`SMS\` node type.
|
|
156
|
+
|
|
157
|
+
**Execution modes**: In synchronous flows, all nodes in one synchronous Actionflow invocation execute inside a single database transaction; any node failure rolls back every DB write from that invocation, and the caller blocks waiting for the result. Asynchronous flows are fire-and-forget; only the failing node's DB changes roll back; required for AI agents and video generation. Both modes share a **per-flow total timeout** governed by \`ACTION_FLOW_TIMEOUT_MILLISECONDS\` \u2014 15 s on free-tier servers, 10 min (600 s) on paid tiers. The budget is for the whole flow, not per node, and a flow may override it with its own \`timeout\`, so a long run that succeeded tells you nothing about which tier you are on.
|
|
158
|
+
|
|
159
|
+
---
|
|
160
|
+
|
|
161
|
+
## 6. Architectural Security Principles
|
|
162
|
+
|
|
163
|
+
LLMs must enforce the **Zero Trust Client** model when designing Zion architectures:
|
|
164
|
+
|
|
165
|
+
1. **Untrusted Client Rule**: The client browser is entirely compromiseable. Never calculate prices, validate stock counts, or verify user authorization clearance on the frontend.
|
|
166
|
+
2. **Secure Transaction Pattern**:
|
|
167
|
+
* Frontend calls a Backend Actionflow, passing only the \`product_id\`.
|
|
168
|
+
* The Actionflow queries the product table *on the server* to fetch the immutable price.
|
|
169
|
+
* The Actionflow inserts a secure \`Pending\` order in the database and returns the generated \`order_id\` and the verified price.
|
|
170
|
+
* Frontend maps the *returned* \`order_id\` and verified price to the payment action.
|
|
171
|
+
3. **Webhook Verification**: Business state mutations must **only** occur inside the backend Webhook actionflow triggered directly and securely by the Payment Gateway, never from a frontend callback.
|
|
172
|
+
|
|
173
|
+
### 6.4 Data Isolation & Access Boundaries (Relation-First Hybrid Pattern)
|
|
174
|
+
Whenever a system requires segmented data access (e.g., multi-tenant, department, region, client, or creator separation):
|
|
175
|
+
1. **Avoid Role Explosion:** Do NOT create separate roles for every individual organizational entity or group (e.g., do not make separate roles for every department or store branch).
|
|
176
|
+
2. **The Hybrid ABAC Pattern (Relation-First):**
|
|
177
|
+
- Instead of manually creating a \`group_id\` or \`tenant_id\` column (which is strictly forbidden by database conventions), **create a one-to-many (1:n) RELATION** from your context table (e.g., \`department\` or \`tenant\`) to the \`Account\` table. This auto-generates a non-editable foreign key column \`department_id\` or \`tenant_id\` on the \`Account\` table.
|
|
178
|
+
- Similarly, **create a one-to-many (1:n) RELATION** from the same context table to your business/data table (e.g., \`sales_record\`), which auto-generates the corresponding FK column on the business table.
|
|
179
|
+
- Define a single generic role representing the user's functional capability (e.g., \`Staff\`).
|
|
180
|
+
- Configure Row-Level Security (RLS) filters inside that role's table permissions to dynamically isolate rows at query time by comparing the auto-generated FK columns: Table.group_id == Account.group_id
|
|
181
|
+
|
|
182
|
+
---
|
|
183
|
+
|
|
184
|
+
## 7. Environment Lifecycle Model
|
|
185
|
+
|
|
186
|
+
* **Mirror**: Hot-reloading, local sandbox. Instantly reflects UI edits in a local window. No build compile or backend synchronization is required during rapid frontend iteration.
|
|
187
|
+
* **Preview**: Compiles and builds the current source into a staging release, providing a unique staging URL. Necessary for deep verification testing of custom components and payment simulations.
|
|
188
|
+
* **Publish**: Deploys the code to the production environment for live users. If database tables, APIs, or Actionflows were modified, they must be synchronized using **Sync Backend** to apply schema migrations to production servers.
|
|
189
|
+
|
|
190
|
+
Mirror, Preview and Publish are things the USER drives from the editor \u2014 you cannot open a preview window or ship a release. What you can drive is the backend: load the \`runtime\` plugin to run an action flow node by node against the real backend, read and write table data as admin or as a given user, and read what the deployed app actually returns. Hand the user anything that needs a browser (visual checks, custom components, a real payment flow, a mini-program audit) and say plainly that it is theirs to do.
|
|
191
|
+
|
|
192
|
+
---
|
|
193
|
+
|
|
194
|
+
## 8. Diagnostics and Troubleshooting Framework
|
|
195
|
+
|
|
196
|
+
0. **Reproduce it**:
|
|
197
|
+
* Run the thing that failed before theorizing about why. \`runtime.debug_flow\` executes the draft action flow node by node and reverts its writes, and gives you the per-node input, output and \`traceId\` the rest of this framework needs. A bug you have not reproduced is a bug you are guessing at.
|
|
198
|
+
1. **Check Edit-time Warnings (Error Collector)**:
|
|
199
|
+
* Look for unmapped input parameters, invalid expressions, or variable mismatch warnings listed under Zion's navigation bar error console.
|
|
200
|
+
2. **Retrieve execution details (Log Service)**:
|
|
201
|
+
* Query the runtime logs using the exact \`traceId\` attached to the failed request.
|
|
202
|
+
* Trace backend code block execution steps, comparing timestamp drift and evaluating input parameters.
|
|
203
|
+
3. **Database Constraints Validation**:
|
|
204
|
+
* If database actions throw \`unique_constraint_violation\` during data imports or integrations, check if the conflict resolution rule is set to \`Skip\` or \`Update\` on the unique fields.
|
|
205
|
+
|
|
206
|
+
---
|
|
207
|
+
|
|
208
|
+
## 9. Platform-Specific Features
|
|
209
|
+
|
|
210
|
+
### Deployment Targets
|
|
211
|
+
Each project can publish to three independent client app targets, all sharing the same backend:
|
|
212
|
+
* **Web**: Standard browser application with a unique URL.
|
|
213
|
+
* **Mobile**: Native iOS app. Android is not available yet.
|
|
214
|
+
* **WeChat Mini Program (\u5FAE\u4FE1\u5C0F\u7A0B\u5E8F)**: Mini program running inside the WeChat app. Requires a registered WeChat Mini Program account (AppID) linked to the project.
|
|
215
|
+
|
|
216
|
+
### WeChat Mini Program Lifecycle
|
|
217
|
+
The mini program publish flow is distinct from web/mobile:
|
|
218
|
+
1. **Mirror**: Hot-reload preview inside the editor \u2014 same as web.
|
|
219
|
+
2. **Preview**: Builds a trial version QR code scannable in WeChat DevTools. No audit needed.
|
|
220
|
+
3. **Submit for Audit**: Submits the build to WeChat platform for review (1\u20137 business days).
|
|
221
|
+
4. **Release**: After audit approval, publish the version. Backend schema changes still require "Sync Backend" separately; mini program code and backend are released independently. Mini program releases are fully independent from the web/mobile release cycle.
|
|
222
|
+
|
|
223
|
+
### Payment Gateways
|
|
224
|
+
* **WeChat Pay**: Native WeChat Pay v3 API. Requires merchant ID and API credentials.
|
|
225
|
+
* **Alipay**: Alipay payment gateway.
|
|
226
|
+
* **Airwallex**: Cards and local payment methods, one-time and subscriptions. Not available on the WeChat Mini Program, and only offered where Airwallex is enabled for the project.
|
|
227
|
+
|
|
228
|
+
### Authentication Providers
|
|
229
|
+
* WeChat (OAuth via WeChat Open Platform)
|
|
230
|
+
* QQ
|
|
231
|
+
* DingTalk (\u9489\u9489)
|
|
232
|
+
* Feishu / Lark (\u98DE\u4E66)
|
|
233
|
+
* Email/password
|
|
234
|
+
|
|
235
|
+
### Timezone & Locale
|
|
236
|
+
Product default timezone: **Asia/Shanghai** (UTC+08:00). A project can override it; the zone actually in effect is \`timezone\` in GET_PROJECT_OVERVIEW. Default UI language: Simplified Chinese (zh-CN).`},post:{available:!0,prompt:`Zion is a powerful no-code development platform that enables developers to build and deploy web, mobile, and WeChat Mini Program (\u5FAE\u4FE1\u5C0F\u7A0B\u5E8F) applications. It integrates a visual drag-and-drop design canvas, an enterprise-grade relational database engine (PostgreSQL), and an event-driven backend logic execution pipeline.
|
|
237
|
+
|
|
238
|
+
This overview details the structural design, data engines, execution pipelines, and safety requirements of the platform.
|
|
239
|
+
|
|
240
|
+
---
|
|
241
|
+
|
|
242
|
+
## 1. Architectural Philosophy (The Three Pillars)
|
|
243
|
+
|
|
244
|
+
Zion decouples application systems into three isolated yet bound layers:
|
|
245
|
+
|
|
246
|
+
1. **Design**: The presentation layer, built strictly on nested HTML components obeying the CSS Box Model and CSS Flexbox layouts.
|
|
247
|
+
2. **Data**: The persistence layer, powered by a built-in, highly-scalable relational database engine (PostgreSQL). All UI contents are dynamically populated by binding to database rows or workspace API schemas.
|
|
248
|
+
3. **Action**: The behavior layer, using an event-driven "Trigger -> Execution" model that connects frontend components to local client tasks or backend operations.
|
|
249
|
+
|
|
250
|
+
---
|
|
251
|
+
|
|
252
|
+
## 2. The Mental Model & Engineering Workflow
|
|
253
|
+
|
|
254
|
+
Building on Zion happens at two levels, and they are not interchangeable. Level one decides **what this release is**; level two builds it. Outlining a solution straight into an ER diagram skips the decision that sets how large that diagram should be, which is what produces a project where every part is half-finished at once instead of one part working.
|
|
255
|
+
|
|
256
|
+
### 2.1 Level One \u2014 Scope The Release
|
|
257
|
+
|
|
258
|
+
A request names a product; it does not name a first release. Deciding that is your job. When a request describes a whole product \u2014 typically the first message of a new project \u2014 cut the work into releases before you model any data; a change to an app that already exists goes straight to level two:
|
|
259
|
+
|
|
260
|
+
* **MVP**: one role, one happy path, the fewest tables that make it real. It must open and demonstrate the idea, not sketch every screen.
|
|
261
|
+
* **1.0**: the secondary flows around that path.
|
|
262
|
+
* **2.0**: admin, operations, analytics.
|
|
263
|
+
|
|
264
|
+
State the cut in one line before you build anything, in the language the user writes in \u2014 e.g. "MVP: a customer browses products and places an order; membership balance and points come in 1.0." A stated cut gets corrected in one sentence; an unstated one is discovered when the user asks where the rest went. Then carry only the MVP into level two, and name what you deferred rather than dropping it silently: work that disappears without being named reads as you having missed half the request.
|
|
265
|
+
|
|
266
|
+
### 2.2 Level Two \u2014 Build That Release Data-First
|
|
267
|
+
|
|
268
|
+
Within the release you just scoped \u2014 never across the whole product \u2014 Zion requires a rigorous **data-first** engineering approach. Outline that release in this exact order:
|
|
269
|
+
|
|
270
|
+
1. **Data Modeling**: Design the Entity-Relationship (ER) diagram, database tables, constraints, and relationships first.
|
|
271
|
+
2. **UI Layout**: Construct nested structural containers (Views) and map static display/input components onto them.
|
|
272
|
+
3. **Logic & Binding**: Link dynamic variables/fields to inputs/displays, then map actions or backend workflows to events.
|
|
273
|
+
4. **Verification**: Run diagnostic reviews using edit-time error panels and runtime log tracing before deploying.
|
|
274
|
+
|
|
275
|
+
---
|
|
276
|
+
|
|
277
|
+
## 3. Database Architecture & Data Binding
|
|
278
|
+
|
|
279
|
+
Zion runs on an enterprise-grade relational database powered by PostgreSQL.
|
|
280
|
+
|
|
281
|
+
### 3.1 Relationship Modeling
|
|
282
|
+
All table relations map directly to standard SQL constraints:
|
|
283
|
+
* **One-to-One (1:1)**: e.g., \`account\` <-> \`user_profile\`. Direct foreign key binding.
|
|
284
|
+
* **One-to-Many (1:N)**: e.g., \`account\` -> \`post\` (One author, multiple posts).
|
|
285
|
+
* **Many-to-Many (N:M)**: Must be configured using a **junction/intermediate table** with two distinct 1:N relations. e.g., \`account\` -> \`enrollment\` <- \`course\` represents a Many-to-Many relation between students and courses.
|
|
286
|
+
|
|
287
|
+
### 3.2 State and Variable Scopes
|
|
288
|
+
Zion distinguishes scopes by lifecycle and visibility:
|
|
289
|
+
|
|
290
|
+
**Application scope** (lifetime = app session):
|
|
291
|
+
* **Global Variable**: shared across all pages. Theme, feature flags, cached user state.
|
|
292
|
+
* **Current User**: the logged-in user object \u2014 id, profile fields, SSO claims.
|
|
293
|
+
|
|
294
|
+
**Page scope** (lifetime = current page):
|
|
295
|
+
* **Page Parameter**: passed from the caller. Path params (\`/product/:id\`) and query params (\`?q=abc\`) are both Page Parameters.
|
|
296
|
+
* **Page Variable**: local UI/form state \u2014 active tab, search keywords, loading flag.
|
|
297
|
+
* **Page Data**: result of the page's Page Data Source (a remote query the page binds at load).
|
|
298
|
+
* **Component State**: the value of stateful input components (Input, Select, Switch). Two-way binding writes flow back into Component State automatically.
|
|
299
|
+
|
|
300
|
+
**List-iteration scope** (lifetime = single rendered row):
|
|
301
|
+
* **Current Item**: the row object inside a List component. Child components inside the list bind to \`Current Item.field\` instead of re-querying the table.
|
|
302
|
+
|
|
303
|
+
**Action-Flow scope** (lifetime = single flow execution):
|
|
304
|
+
* **Action Input**: parameters declared on the flow's Start node.
|
|
305
|
+
* **Flow Variable**: locals declared by a "Set Variable" node; visible to subsequent nodes in the same flow.
|
|
306
|
+
* **Flow Output**: a single typed output value returned by the flow \u2014 visible to the caller.
|
|
307
|
+
* **Loop Item**: the current iteration value inside a Loop node.
|
|
308
|
+
|
|
309
|
+
### 3.3 Data Interaction Types
|
|
310
|
+
Zion splits operations into two non-overlapping categories to prevent infinite render loops:
|
|
311
|
+
* **Query (Read-Only)**: Idempotent operations that fetch data. Used directly as dynamic data sources for Lists, Select Views, and Pages.
|
|
312
|
+
* **Mutation (State-Changing)**: Operations that insert, update, or delete records. These **must** be explicitly triggered as actions (e.g., On Click events) and can never be used as static data sources.
|
|
313
|
+
|
|
314
|
+
### 3.4 Data Binding
|
|
315
|
+
Data binding connects data sources to component properties. A property can be set to:
|
|
316
|
+
* **OPTION**: a live value from the hierarchical data binding options tree \u2014 sources include database table fields, page variables, global variables, logged-in user, list item context ("Current Item"), and actionflow inputs/outputs. The exact \`pathInHierarchicalMenu\` must match the options tree; never fabricate a path.
|
|
317
|
+
* **CONST_VALUE**: a literal constant (string, number, boolean).
|
|
318
|
+
* **DISPLAY_NAME**: rename the component's displayed label.
|
|
319
|
+
|
|
320
|
+
Every bindable slot \u2014 a component property, an action-flow node's input, a request filter's comparison value \u2014 is addressed by a **schemaPath**: an ordered array of steps into the project's JSON schema, \`{"key":"<field>"}\` into an object or \`{"index":N}\` into an array, never both in one step. A schemaPath is read back, never composed by hand \u2014 the call that creates a slot echoes the path of what it made, and the context reads return the finer paths inside it. Build top-down (create, read back the echoed path, then drill in) and the path you need is always one you already hold.
|
|
321
|
+
|
|
322
|
+
Lists render one row per record from their data source. Children inside a list bind to the list's "Current Item" context (a scoped reference to that row's fields) rather than querying a new table \u2014 this preserves the relational link.
|
|
323
|
+
|
|
324
|
+
---
|
|
325
|
+
|
|
326
|
+
## 4. Visual Layout & Positioning Engine
|
|
327
|
+
|
|
328
|
+
Zion's canvas operates as a visual CSS rendering engine: components are nested Flexbox containers obeying the CSS box model, laid out in the natural document flow unless deliberately taken out of it. The component plugin's own guidance is authoritative for positioning, container sizing, breakpoints, and when a conditional container is the right structure rather than a conditional value or a conditional action \u2014 consult it there rather than deciding any of that from this overview.
|
|
329
|
+
|
|
330
|
+
---
|
|
331
|
+
|
|
332
|
+
## 5. Logic Engines: Frontend vs. Backend
|
|
333
|
+
|
|
334
|
+
### 5.1 Frontend Actions
|
|
335
|
+
Lightweight operations executing directly in the client browser/app. Triggered by UI events.
|
|
336
|
+
|
|
337
|
+
**Prefer direct frontend CRUD**: The frontend can insert/update/delete rows directly for simple single-table CRUD when table, column, and row permissions fully express the authorization policy. Do not create an Actionflow merely to proxy CRUD. Reserve Backend Actionflows for genuinely server-side, multi-step, transactional, or orchestrated operations: cross-table atomicity, trusted calculations or secrets, branching or loops, third-party calls, schedules, webhooks, and database triggers. If data permissions cannot express the authorization rule, enforce it server-side in an Actionflow \u2014 see \xA76.
|
|
338
|
+
|
|
339
|
+
**The authoritative list of what a frontend action can do** is the component plugin's selectable-actions read plus that tool's parameter schema \u2014 they are filtered to this project and platform and they are complete. The editor offers navigation, toasts and dialogs, local and global state writes, data refresh and list control, file upload / download / clipboard / QR, AI agent invocation, authentication, payments, animation, and platform-specific capabilities. Do not tell a user an interaction is impossible, or reach for an Actionflow to get it, before checking there.
|
|
340
|
+
|
|
341
|
+
### 5.2 Backend Actionflows
|
|
342
|
+
Server-side visual execution graphs used to perform robust operations. They are triggered by:
|
|
343
|
+
* Client requests (explicit frontend action calls).
|
|
344
|
+
* Cron schedules (scheduled background workflows).
|
|
345
|
+
* Webhooks (third-party external integrations).
|
|
346
|
+
* Database Triggers (automatically runs on \`INSERT\`/\`UPDATE\`/\`DELETE\` of target tables).
|
|
347
|
+
|
|
348
|
+
**Node types available inside an Actionflow:** the authoritative list is the flow's add-node menu at the position \u2014 read it with the actionflow plugin and pass that entry's \`node\`, rather than choosing from a fixed list; an entry it disables is refused with that reason. Its entries span database reads and writes, Call workspace API, Run AI (async only), calling another flow (sync cannot call async), variables, permissions, JavaScript and branching or loops. Current-user and file/media operations are preset integration nodes, not built-in node types \u2014 the menu carries the deployment's \`TEMPLATE_CODE\` entries for them (SMS, video/AI generation, \u2026), whose set changes over time. There is no built-in \`CURRENT_USER\` / \`FILES\` / \`SMS\` node type.
|
|
349
|
+
|
|
350
|
+
**Execution modes**: In synchronous flows, all nodes in one synchronous Actionflow invocation execute inside a single database transaction; any node failure rolls back every DB write from that invocation, and the caller blocks waiting for the result. Asynchronous flows are fire-and-forget; only the failing node's DB changes roll back; required for AI agents and video generation. Both modes share a **per-flow total timeout** governed by \`ACTION_FLOW_TIMEOUT_MILLISECONDS\` \u2014 15 s on free-tier servers, 10 min (600 s) on paid tiers. The budget is for the whole flow, not per node, and a flow may override it with its own \`timeout\`, so a long run that succeeded tells you nothing about which tier you are on.
|
|
351
|
+
|
|
352
|
+
---
|
|
353
|
+
|
|
354
|
+
## 6. Architectural Security Principles
|
|
355
|
+
|
|
356
|
+
LLMs must enforce the **Zero Trust Client** model when designing Zion architectures:
|
|
357
|
+
|
|
358
|
+
1. **Untrusted Client Rule**: The client browser is entirely compromiseable. Never calculate prices, validate stock counts, or verify user authorization clearance on the frontend.
|
|
359
|
+
2. **Secure Transaction Pattern**:
|
|
360
|
+
* Frontend calls a Backend Actionflow, passing only the \`product_id\`.
|
|
361
|
+
* The Actionflow queries the product table *on the server* to fetch the immutable price.
|
|
362
|
+
* The Actionflow inserts a secure \`Pending\` order in the database and returns the generated \`order_id\` and the verified price.
|
|
363
|
+
* Frontend maps the *returned* \`order_id\` and verified price to the payment action.
|
|
364
|
+
3. **Webhook Verification**: Business state mutations must **only** occur inside the backend Webhook actionflow triggered directly and securely by the Payment Gateway, never from a frontend callback.
|
|
365
|
+
|
|
366
|
+
### 6.4 Data Isolation & Access Boundaries (Relation-First Hybrid Pattern)
|
|
367
|
+
Whenever a system requires segmented data access (e.g., multi-tenant, department, region, client, or creator separation):
|
|
368
|
+
1. **Avoid Role Explosion:** Do NOT create separate roles for every individual organizational entity or group (e.g., do not make separate roles for every department or store branch).
|
|
369
|
+
2. **The Hybrid ABAC Pattern (Relation-First):**
|
|
370
|
+
- Instead of manually creating a \`group_id\` or \`tenant_id\` column (which is strictly forbidden by database conventions), **create a one-to-many (1:n) RELATION** from your context table (e.g., \`department\` or \`tenant\`) to the \`Account\` table. This auto-generates a non-editable foreign key column \`department_id\` or \`tenant_id\` on the \`Account\` table.
|
|
371
|
+
- Similarly, **create a one-to-many (1:n) RELATION** from the same context table to your business/data table (e.g., \`sales_record\`), which auto-generates the corresponding FK column on the business table.
|
|
372
|
+
- Define a single generic role representing the user's functional capability (e.g., \`Staff\`).
|
|
373
|
+
- Configure Row-Level Security (RLS) filters inside that role's table permissions to dynamically isolate rows at query time by comparing the auto-generated FK columns: Table.group_id == Account.group_id
|
|
374
|
+
|
|
375
|
+
---
|
|
376
|
+
|
|
377
|
+
## 7. Environment Lifecycle Model
|
|
378
|
+
|
|
379
|
+
* **Mirror**: Hot-reloading, local sandbox. Instantly reflects UI edits in a local window. No build compile or backend synchronization is required during rapid frontend iteration.
|
|
380
|
+
* **Preview**: Compiles and builds the current source into a staging release, providing a unique staging URL. Necessary for deep verification testing of custom components and payment simulations.
|
|
381
|
+
* **Publish**: Deploys the code to the production environment for live users. If database tables, APIs, or Actionflows were modified, they must be synchronized using **Sync Backend** to apply schema migrations to production servers.
|
|
382
|
+
|
|
383
|
+
Mirror, Preview and Publish are things the USER drives from the editor \u2014 you cannot open a preview window or ship a release. What you can drive is the backend: load the \`runtime\` plugin to run an action flow node by node against the real backend, read and write table data as admin or as a given user, and read what the deployed app actually returns. Hand the user anything that needs a browser (visual checks, custom components, a real payment flow, a mini-program audit) and say plainly that it is theirs to do.
|
|
384
|
+
|
|
385
|
+
---
|
|
386
|
+
|
|
387
|
+
## 8. Diagnostics and Troubleshooting Framework
|
|
388
|
+
|
|
389
|
+
0. **Reproduce it**:
|
|
390
|
+
* Run the thing that failed before theorizing about why. \`runtime.debug_flow\` executes the draft action flow node by node and reverts its writes, and gives you the per-node input, output and \`traceId\` the rest of this framework needs. A bug you have not reproduced is a bug you are guessing at.
|
|
391
|
+
1. **Check Edit-time Warnings (Error Collector)**:
|
|
392
|
+
* Look for unmapped input parameters, invalid expressions, or variable mismatch warnings listed under Zion's navigation bar error console.
|
|
393
|
+
2. **Retrieve execution details (Log Service)**:
|
|
394
|
+
* Query the runtime logs using the exact \`traceId\` attached to the failed request.
|
|
395
|
+
* Trace backend code block execution steps, comparing timestamp drift and evaluating input parameters.
|
|
396
|
+
3. **Database Constraints Validation**:
|
|
397
|
+
* If database actions throw \`unique_constraint_violation\` during data imports or integrations, check if the conflict resolution rule is set to \`Skip\` or \`Update\` on the unique fields.
|
|
398
|
+
|
|
399
|
+
---
|
|
400
|
+
|
|
401
|
+
## 9. Platform-Specific Features
|
|
402
|
+
|
|
403
|
+
### Deployment Targets
|
|
404
|
+
Each project can publish to three independent client app targets, all sharing the same backend:
|
|
405
|
+
* **Web**: Standard browser application with a unique URL.
|
|
406
|
+
* **Mobile**: Native iOS app. Android is not available yet.
|
|
407
|
+
* **WeChat Mini Program (\u5FAE\u4FE1\u5C0F\u7A0B\u5E8F)**: Mini program running inside the WeChat app. Requires a registered WeChat Mini Program account (AppID) linked to the project.
|
|
408
|
+
|
|
409
|
+
### WeChat Mini Program Lifecycle
|
|
410
|
+
The mini program publish flow is distinct from web/mobile:
|
|
411
|
+
1. **Mirror**: Hot-reload preview inside the editor \u2014 same as web.
|
|
412
|
+
2. **Preview**: Builds a trial version QR code scannable in WeChat DevTools. No audit needed.
|
|
413
|
+
3. **Submit for Audit**: Submits the build to WeChat platform for review (1\u20137 business days).
|
|
414
|
+
4. **Release**: After audit approval, publish the version. Backend schema changes still require "Sync Backend" separately; mini program code and backend are released independently. Mini program releases are fully independent from the web/mobile release cycle.
|
|
415
|
+
|
|
416
|
+
### Payment Gateways
|
|
417
|
+
* **WeChat Pay**: Native WeChat Pay v3 API. Requires merchant ID and API credentials.
|
|
418
|
+
* **Alipay**: Alipay payment gateway.
|
|
419
|
+
* **Airwallex**: Cards and local payment methods, one-time and subscriptions. Not available on the WeChat Mini Program, and only offered where Airwallex is enabled for the project.
|
|
420
|
+
|
|
421
|
+
### Authentication Providers
|
|
422
|
+
* WeChat (OAuth via WeChat Open Platform)
|
|
423
|
+
* QQ
|
|
424
|
+
* DingTalk (\u9489\u9489)
|
|
425
|
+
* Feishu / Lark (\u98DE\u4E66)
|
|
426
|
+
* Email/password
|
|
427
|
+
|
|
428
|
+
### Timezone & Locale
|
|
429
|
+
Product default timezone: **Asia/Shanghai** (UTC+08:00). A project can override it; the zone actually in effect is \`timezone\` in GET_PROJECT_OVERVIEW. Default UI language: Simplified Chinese (zh-CN).`}},api:{pre:{available:!1,prompt:null},post:{available:!0,prompt:"## API Integration Domain Knowledge\nAn API integration is a saved external HTTP endpoint the project can use as a data source. APIs are organized into **workspaces**: a workspace groups related endpoints and holds shared **constants** (e.g. a base URL or API key) the endpoints reference, so credentials live in one place. The action-flow \"Call API\" node invokes these workspace APIs.\n\n### Anatomy\n- **Workspace**: a named group with a description and a set of `constants`.\n- **API**: an HTTP `method` + URL under a workspace, with request **parameters** (path / query / header / body), typed **response configs** (the result shape downstream binds from), and declared **input variables** (the values a caller supplies).\n\n### Workflow\nList with `GET_ALL_API_WORKSPACES` / `GET_ALL_APIS_INFO`, then `GET_API_DETAIL` to read an API's `apiId`, `workspaceId`, and parameter / response `uniqueId`s before editing \u2014 never fabricate them. Build top-down: `ADD_API_WORKSPACES` \u2192 `ADD_API_WORKSPACE_CONSTANTS` (put API keys / base URLs here, never inline) \u2192 `ADD_APIS` (each under a `workspaceId`) \u2192 `ADD_API_PARAMETERS`, `ADD_API_RESPONSE_CONFIGS`, `ADD_API_INPUT_VARIABLES`. Editing creates a new version; \"Sync Backend\" is required for changes to take effect in production.\n\n### Request Bodies\nA body-carrying method needs a body FORMAT, and `SET_API_CONTENT_TYPE` is what sets it \u2014 `UPDATE_API` has no content-type argument and will reject one. `application/json` seeds an empty object type that belongs to this API; `GET_API_DETAIL` reports it as `bodyType`, and you describe it with the 'type' plugin's `ADD_TYPE_DEFINITION_FIELDS`. The two form formats take their fields from `ADD_API_PARAMETERS` instead. Every such switch DISCARDS the body that was there, so pick the format before filling it in \u2014 and never cycle the method away and back to force a reset, which throws the body parameters away with it.\n\nA media field, or an object field carried as a JSON string, cannot travel over HTTP as itself: it needs a conversion, and a media field left without one leaves the API incomplete. `GET_API_CODEC_OPTIONS` says which slots need one and what each allows; `SET_API_CODECS` applies it and `DELETE_API_CODECS` removes it.\n\n### Response Shapes\nA response config's type is what downstream reads the result through, and only an object type puts that result's fields where a binding can see and pick them. A JSON response still yields values \u2014 through the get-value-from-JSON formula \u2014 but the key path is a string you have to already know and spell by hand, nothing in the project lists what the payload holds, and a key that does not match it comes back empty rather than erroring; a text response does not even reach that formula. So whenever the endpoint documents what it returns \u2014 and it usually does \u2014 give the response a shape: `ADD_API_RESPONSE_CONFIGS` / `UPDATE_API_RESPONSE_CONFIGS` with `seedObjectType: true` mint an object type owned by this API and echo its `responseTypeId`, which you then describe with the 'type' plugin's `ADD_TYPE_DEFINITION_FIELDS`, exactly as you do a JSON request body. Add `arrayLevel: 1` where the endpoint returns a list of that shape. Reach for the JSON type only when the body's shape genuinely varies from call to call, and for text only when the response is not JSON at all (a 204 with no content, a plain-text body).\n\n### Types\nEvery `type` argument here is picked, not written: call `GET_API_SELECTABLE_TYPES` for the slot being filled and copy a returned `typeIdentifier` verbatim. A private object type belongs to the one feature that owns it and is never offered to another, so to reuse a shape some other feature owns, publish it with `COPY_PRIVATE_OBJECT_TYPE_AS_PUBLIC` and select the public copy. This API's own JSON body type is the exception \u2014 it is already this API's, so describe it in place with `ADD_TYPE_DEFINITION_FIELDS`. Lists are not enumerated \u2014 the nesting has no end \u2014 so a list response or input variable is a returned identifier plus `arrayLevel: 1`; the URL, header and form-body parameters hold one value, take no `arrayLevel`, and accept no list at all."}},bindings:{pre:{available:!0,prompt:"## Data Binding Domain Knowledge\nData binding connects data sources to UI components for display or interaction.\n\n### Concepts\nSchema path: array of keys/indices locating a bindable node in the project JSON schema. Data binding options tree: hierarchical tree of all available data for a given schema path. Never hand-build a schema path for an action-flow node: copy it from the actionflow plugin's add_node result or get_flow_detail's nodeSchemaPaths (form: server/actionFlows/{i}/allNodes/{j}), then append key segments for the binding site inside the node. The binding-site key names VARY BY NODE TYPE (an AI node's input arg lives under inputArgs/<argKey>, a code node's under inputArgsDataBinding/<argName>, a mutation column under mutation/object/<columnName>) \u2014 copy the exact keys from the currentNode structure returned by get_context_info; never guess them.\nType metadata in read results uses exact legacy ColumnType names such as `TEXT` and `BIGINT`; copy those names verbatim.\n\n### Binding Kinds\nOPTION: bind to an existing path in the data binding options tree. pathInHierarchicalMenu must be the EXACT complete path, and menu labels are locale-dependent display names (a project may render them in Chinese or English) \u2014 so a label can NEVER be guessed. Before the first option binding at a schema path whose tree you have not seen, read it with `BROWSE_DATA_BINDING_OPTIONS` (CRITICAL: Do NOT call `get_options_tree` if the tree is already provided in the context above); afterwards every binding response attaches the refreshed tree for its op's path. Copy every label verbatim from that tree \u2014 never invent, translate, or shorten a label \u2014 and include every intermediate menu level. If the tree root is a named context (e.g., \"List Context\"), include it as the first element. CONST_VALUE: set a literal constant (e.g., \"Submit\", 0, false). FORMULA: compute a value with an operator (text / math / time / array / enum / geography / json groups); discover the available operators before building one. CONDITIONAL: choose the value by branch \u2014 define the branches, then build each branch's predicate.\n\n### Priority\n1. Prefer OPTION (live data) over CONST_VALUE.\n2. No suitable option? Use CONST_VALUE with a reasonable inferred constant.\n3. Component purpose unclear? Skip binding.\n4. A list NESTED INSIDE another list binds from the ancestor's item data, not from a table, so the relational linkage survives. This is about nesting only \u2014 a top-level list binds straight to the table it shows, and prefers that over consuming someone else's page query unless the result set is genuinely shared.\n5. Bind ONLY what the task requires: in an update/insert node's object leave every other column untouched \u2014 never fill it with a Null option or a placeholder constant (Null on a required column breaks the flow at runtime).\n6. Never seed a typed site with a throwaway constant \"for now\" and upgrade later \u2014 bind the real value directly; a constant re-types nothing but still wastes a round.\n\n### Iterative Refinement\nPer-op errors are returned keyed by index. Successful bindings have already landed. On rejection, fix ONLY the failing entries by index and re-call.\n\n### Data Sources Available in Zion\nDatabase tables (with filters/sorting/limits), page data sources, page variables, global variables, page parameters, logged-in user, list/component item data, Actionflow inputs/outputs, formula results.\nThis is the product-wide catalog, NOT what is bindable at any given site \u2014 each site exposes only a subset. NEVER assume a category is available: the options tree for the site is authoritative, so read it with `BROWSE_DATA_BINDING_OPTIONS` first and bind only categories it actually lists. If one (e.g. formula data) is absent for that path, it is not valid there \u2014 do not attempt it. (Action flows run strictly on the backend, so page data sources never apply inside a flow node.)\n\n### Request Filters (where / sort)\nA database-query data source \u2014 a list/component request, or an action-flow query / update / delete node \u2014 carries **request filters**. FIRST call `GET_REQUEST_FILTER_CONTEXT` with the request's (or owning node's) schema path: it returns the table's selectable columns (with the `pathComponents` and `allowedOperators` to use) and the filter entries' `whereSchemaPath` / `sortConfigsSchemaPath`. Copy those paths and column `pathComponents` verbatim \u2014 never hand-build them. Queries and component requests carry a LIST of conditional filters (where + sort groups, each gated by its own condition, always including a system Default filter). An action-flow update/delete node instead carries ONE bare where (`supportsConditionalFilters: false` in the context result) \u2014 edit it via the single entry's `whereSchemaPath` with the where-condition tools only; the filter-group and sort tools do not apply, and insert nodes have no request filter at all.\nTo change a numeric column RELATIVE to its current value (stock, counters, balances), set the column's write mode with `SET_UPDATE_COLUMN_ARITHMETIC` and bind only the DELTA as the column's value \u2014 the database applies it atomically. Never query the current value, compute in a formula, and set it back: that read-modify-write loses concurrent updates. Idiom \u2014 decrease field_a by x: mode 'decrement' on field_a, value x, and a where guard `field_a > x` (or `>= x` when draining to zero is allowed) so the update changes nothing when the stored value is insufficient. That rule generalizes to every mutation this plugin configures \u2014 frontend component mutation events and action-flow nodes alike: when a write's correctness depends on current row state, put the check in the mutation's own where filter and let follow-ups branch on its affected rows, instead of querying first and writing on the stale read (concurrent users race it). Insert-if-absent semantics additionally need a unique constraint \u2014 the only DB-enforced constraint kind today (see the database plugin).\n- Filter groups: `ADD_REQUEST_CONDITIONAL_FILTER` / `UPDATE_REQUEST_CONDITIONAL_FILTER` / `DELETE_REQUEST_CONDITIONAL_FILTER` / `REORDER_REQUEST_CONDITIONAL_FILTERS`. The Default filter cannot be renamed or deleted.\n- Where conditions: `ADD_REQUEST_FILTER_CONDITION` (column + operator), then fill its comparison value with a binding (OPTION / CONST_VALUE) at the condition's `value` path; shape the expression with `NEST_REQUEST_FILTER_CONDITION`, `TOGGLE_REQUEST_FILTER_CONDITION_AND_OR`, `TOGGLE_REQUEST_FILTER_CONDITION_NOT`, `UPDATE_REQUEST_FILTER_CONDITION_OPERATOR`, `DELETE_REQUEST_FILTER_CONDITION`.\n- Sort: `ADD_REQUEST_SORT_CONFIG` / `UPDATE_REQUEST_SORT_CONFIG` / `DELETE_REQUEST_SORT_CONFIG` / `REORDER_REQUEST_SORT_CONFIGS`.\n\n### Composing text from fragments and variables\nFor any `TEXT` value that mixes literal fragments with variables \u2014 AI prompt templates, titles, labels, messages \u2014 do NOT build a stringConcat formula. Build the template at the same schema path with operation CONCAT: `CREATE_CONST_BINDING` for a literal fragment, `CREATE_OPTION_BINDING` for a variable. Each CONCAT appends to the end, so the final order is exactly the order you emit entries \u2014 within a call and across consecutive binding calls in the same turn. Emit them in final reading order, interleaving literals and variables \u2014 e.g. const_value \"Hello \", option user, const_value \", order \", option orderId, const_value \" total \", option amount. Never emit all literals then all variables (that puts every label before every variable), and two literal CONCATs in a row merge into one fragment. This produces the same inline template the editor's text fields produce and stays editable there. Reserve formulas for real computation (math, time, regex, arrays) \u2014 never for simple text templating.\nA number, boolean, date, time, datetime or color bound into a `TEXT` slot is converted for display automatically, so bind the option straight to the slot \u2014 never wrap it in `toText` or any other conversion operator. Only structured values (lists, objects, media) genuinely need one. `BROWSE_DATA_BINDING_OPTIONS` marks an option with `*` only when the target really cannot take it; an unmarked option needs no conversion step.\n\n### Formula & Conditional Bindings\nA FORMULA or CONDITIONAL value is built in several steps at the value's schema path, not in a single call.\n- Formula: call `GET_FORMULA_OPERATORS` at the path, then `CREATE_FORMULA_BINDING` with an operator copied verbatim (the wire token, e.g. `-` not SUBTRACT; operation REPLACE). If the operator needs scalar config (e.g. distance unit, rounding mode), read its shape with `GET_FORMULA_CONFIG_OPTIONS` and pass it or apply it later with `SET_FORMULA_CONFIG`. The create result returns `operandSchemaPaths` \u2014 fill each operand with an OPTION / CONST_VALUE binding at its returned path, copied verbatim; never derive an operand path yourself. A `timezone` operand (e.g. on FORMAT_DATE_TIME) is optional: unbound, the project's default zone applies, so bind it only when the user asks for a specific zone or the viewer's own.\n- Conditional: `CREATE_CONDITIONAL_BINDING` (seed branches with initialBranchNames; operation REPLACE), add more with `INSERT_CONDITIONAL_DATA`. For each branch, build its predicate with `INSERT_CONDITION_BOOL_EXP`, choose the comparison via `GET_EXPRESSION_CONDITION_OPERATORS` + `UPDATE_EXPRESSION_CONDITION_OPERATOR`, fill both operands with OPTION / CONST_VALUE bindings, and shape the expression with `NEST_CONDITION_BOOL_EXP`, `TOGGLE_CONDITION_BOOL_EXP_AND_OR`, `TOGGLE_CONDITION_BOOL_EXP_NOT`, `DELETE_CONDITION_BOOL_EXP`; then bind the branch's resulting value. The first branch whose predicate is true wins \u2014 order them with `REORDER_CONDITIONAL_DATA`.\n- There is no string is-empty operator (`_is_empty` accepts lists only, and `\"\"` is not null): test text emptiness as `stringLength(x) > 0` via a formula binding on the operand.\n\n### Page links\nThe global page-link option binds a getPageUrl function binding with no target page, so the link points nowhere until you call `SET_FUNCTION_BINDING_PAGE_URL_TARGET` at the same schema path with the target page's id. Fill each parameter it returns under argSchemaPaths with an OPTION / CONST_VALUE binding at that path, copied verbatim.\n\n### Lists composed item by item\nTo give a list slot a literal list, bind the Custom > Array option at its schema path, then append items with `ADD_CUSTOM_ARRAY_BINDING_ITEMS` \u2014 a binding at an item index that does not exist yet is rejected, so an empty custom array can only grow through that tool. Fill each item it returns under itemSchemaPaths with an OPTION / CONST_VALUE binding, copied verbatim. For a list of lists, each item is a custom array of its own: call `ADD_CUSTOM_ARRAY_BINDING_ITEMS` again at the item's path. Remove items with `DELETE_CUSTOM_ARRAY_BINDING_ITEMS`."},post:{available:!0,prompt:"## Data Binding Domain Knowledge\nData binding connects data sources to UI components for display or interaction.\n\n### Concepts\nSchema path: array of keys/indices locating a bindable node in the project JSON schema. Data binding options tree: hierarchical tree of all available data for a given schema path. Never hand-build a schema path for an action-flow node: copy it from the actionflow plugin's add_node result or get_flow_detail's nodeSchemaPaths (form: server/actionFlows/{i}/allNodes/{j}), then append key segments for the binding site inside the node. The binding-site key names VARY BY NODE TYPE (an AI node's input arg lives under inputArgs/<argKey>, a code node's under inputs/<index>/value, a mutation column under mutation/object/<columnName>) \u2014 copy the exact keys from the currentNode structure returned by get_context_info; never guess them.\nType metadata in read results uses exact typeIdentifier values such as `s:p:string` and `u:e:<enumId>`; copy those values verbatim.\n\n### Binding Kinds\nOPTION: bind to an existing path in the data binding options tree. pathInHierarchicalMenu must be the EXACT complete path, and menu labels are locale-dependent display names (a project may render them in Chinese or English) \u2014 so a label can NEVER be guessed. Before the first option binding at a schema path whose tree you have not seen, read it with `BROWSE_DATA_BINDING_OPTIONS` (CRITICAL: Do NOT call `get_options_tree` if the tree is already provided in the context above); afterwards every binding response attaches the refreshed tree for its op's path. Copy every label verbatim from that tree \u2014 never invent, translate, or shorten a label \u2014 and include every intermediate menu level. If the tree root is a named context (e.g., \"List Context\"), include it as the first element. CONST_VALUE: set a literal constant (e.g., \"Submit\", 0, false). FORMULA: compute a value with an operator (text / math / time / array / enum / geography / json groups); discover the available operators before building one. CONDITIONAL: choose the value by branch \u2014 define the branches, then build each branch's predicate.\n\n### Priority\n1. Prefer OPTION (live data) over CONST_VALUE.\n2. No suitable option? Use CONST_VALUE with a reasonable inferred constant.\n3. Component purpose unclear? Skip binding.\n4. A list NESTED INSIDE another list binds from the ancestor's item data, not from a table, so the relational linkage survives. This is about nesting only \u2014 a top-level list binds straight to the table it shows, and prefers that over consuming someone else's page query unless the result set is genuinely shared.\n5. Bind ONLY what the task requires: in an update/insert node's object leave every other column untouched \u2014 never fill it with a Null option or a placeholder constant (Null on a required column breaks the flow at runtime).\n6. Never seed a typed site with a throwaway constant \"for now\" and upgrade later \u2014 bind the real value directly; a constant re-types nothing but still wastes a round.\n\n### Iterative Refinement\nPer-op errors are returned keyed by index. Successful bindings have already landed. On rejection, fix ONLY the failing entries by index and re-call.\n\n### Data Sources Available in Zion\nDatabase tables (with filters/sorting/limits), page data sources, page variables, global variables, page parameters, logged-in user, list/component item data, Actionflow inputs/outputs, formula results.\nThis is the product-wide catalog, NOT what is bindable at any given site \u2014 each site exposes only a subset. NEVER assume a category is available: the options tree for the site is authoritative, so read it with `BROWSE_DATA_BINDING_OPTIONS` first and bind only categories it actually lists. If one (e.g. formula data) is absent for that path, it is not valid there \u2014 do not attempt it. (Action flows run strictly on the backend, so page data sources never apply inside a flow node.)\n\n### Request Filters (where / sort)\nA database-query data source \u2014 a list/component request, or an action-flow query / update / delete node \u2014 carries **request filters**. FIRST call `GET_REQUEST_FILTER_CONTEXT` with the request's (or owning node's) schema path: it returns the table's selectable columns (with the `pathComponents` and `allowedOperators` to use) and the filter entries' `whereSchemaPath` / `sortConfigsSchemaPath`. Copy those paths and column `pathComponents` verbatim \u2014 never hand-build them. Queries and component requests carry a LIST of conditional filters (where + sort groups, each gated by its own condition, always including a system Default filter). An action-flow update/delete node instead carries ONE bare where (`supportsConditionalFilters: false` in the context result) \u2014 edit it via the single entry's `whereSchemaPath` with the where-condition tools only; the filter-group and sort tools do not apply, and insert nodes have no request filter at all.\nTo change a numeric column RELATIVE to its current value (stock, counters, balances), set the column's write mode with `SET_UPDATE_COLUMN_ARITHMETIC` and bind only the DELTA as the column's value \u2014 the database applies it atomically. Never query the current value, compute in a formula, and set it back: that read-modify-write loses concurrent updates. Idiom \u2014 decrease field_a by x: mode 'decrement' on field_a, value x, and a where guard `field_a > x` (or `>= x` when draining to zero is allowed) so the update changes nothing when the stored value is insufficient. That rule generalizes to every mutation this plugin configures \u2014 frontend component mutation events and action-flow nodes alike: when a write's correctness depends on current row state, put the check in the mutation's own where filter and let follow-ups branch on its affected rows, instead of querying first and writing on the stale read (concurrent users race it). Insert-if-absent semantics additionally need a unique constraint \u2014 the only DB-enforced constraint kind today (see the database plugin).\n- Filter groups: `ADD_REQUEST_CONDITIONAL_FILTER` / `UPDATE_REQUEST_CONDITIONAL_FILTER` / `DELETE_REQUEST_CONDITIONAL_FILTER` / `REORDER_REQUEST_CONDITIONAL_FILTERS`. The Default filter cannot be renamed or deleted.\n- Where conditions: `ADD_REQUEST_FILTER_CONDITION` (column + operator), then fill its comparison value with a binding (OPTION / CONST_VALUE) at the condition's `value` path; shape the expression with `NEST_REQUEST_FILTER_CONDITION`, `TOGGLE_REQUEST_FILTER_CONDITION_AND_OR`, `TOGGLE_REQUEST_FILTER_CONDITION_NOT`, `UPDATE_REQUEST_FILTER_CONDITION_OPERATOR`, `DELETE_REQUEST_FILTER_CONDITION`.\n- Sort: `ADD_REQUEST_SORT_CONFIG` / `UPDATE_REQUEST_SORT_CONFIG` / `DELETE_REQUEST_SORT_CONFIG` / `REORDER_REQUEST_SORT_CONFIGS`.\n\n### Composing text from fragments and variables\nFor any `s:p:string` value that mixes literal fragments with variables \u2014 AI prompt templates, titles, labels, messages \u2014 do NOT build a stringConcat formula. Build the template at the same schema path with operation CONCAT: `CREATE_CONST_BINDING` for a literal fragment, `CREATE_OPTION_BINDING` for a variable. Each CONCAT appends to the end, so the final order is exactly the order you emit entries \u2014 within a call and across consecutive binding calls in the same turn. Emit them in final reading order, interleaving literals and variables \u2014 e.g. const_value \"Hello \", option user, const_value \", order \", option orderId, const_value \" total \", option amount. Never emit all literals then all variables (that puts every label before every variable), and two literal CONCATs in a row merge into one fragment. This produces the same inline template the editor's text fields produce and stays editable there. Reserve formulas for real computation (math, time, regex, arrays) \u2014 never for simple text templating.\nA number, boolean, date, time, datetime or color bound into a `s:p:string` slot is converted for display automatically, so bind the option straight to the slot \u2014 never wrap it in `toText` or any other conversion operator. Only structured values (lists, objects, media) genuinely need one. `BROWSE_DATA_BINDING_OPTIONS` marks an option with `*` only when the target really cannot take it; an unmarked option needs no conversion step.\n\n### Formula & Conditional Bindings\nA FORMULA or CONDITIONAL value is built in several steps at the value's schema path, not in a single call.\n- Formula: call `GET_FORMULA_OPERATORS` at the path, then `CREATE_FORMULA_BINDING` with an operator copied verbatim (the wire token, e.g. `-` not SUBTRACT; operation REPLACE). If the operator needs scalar config (e.g. distance unit, rounding mode), read its shape with `GET_FORMULA_CONFIG_OPTIONS` and pass it or apply it later with `SET_FORMULA_CONFIG`. The create result returns `operandSchemaPaths` \u2014 fill each operand with an OPTION / CONST_VALUE binding at its returned path, copied verbatim; never derive an operand path yourself. A `timezone` operand (e.g. on FORMAT_DATE_TIME) is optional: unbound, the project's default zone applies, so bind it only when the user asks for a specific zone or the viewer's own.\n- Conditional: `CREATE_CONDITIONAL_BINDING` (seed branches with initialBranchNames; operation REPLACE), add more with `INSERT_CONDITIONAL_DATA`. For each branch, build its predicate with `INSERT_CONDITION_BOOL_EXP`, choose the comparison via `GET_EXPRESSION_CONDITION_OPERATORS` + `UPDATE_EXPRESSION_CONDITION_OPERATOR`, fill both operands with OPTION / CONST_VALUE bindings, and shape the expression with `NEST_CONDITION_BOOL_EXP`, `TOGGLE_CONDITION_BOOL_EXP_AND_OR`, `TOGGLE_CONDITION_BOOL_EXP_NOT`, `DELETE_CONDITION_BOOL_EXP`; then bind the branch's resulting value. The first branch whose predicate is true wins \u2014 order them with `REORDER_CONDITIONAL_DATA`.\n- There is no string is-empty operator (`_is_empty` accepts lists only, and `\"\"` is not null): test text emptiness as `stringLength(x) > 0` via a formula binding on the operand.\n\n### Page links\nThe global page-link option binds a getPageUrl function binding with no target page, so the link points nowhere until you call `SET_FUNCTION_BINDING_PAGE_URL_TARGET` at the same schema path with the target page's id. Fill each parameter it returns under argSchemaPaths with an OPTION / CONST_VALUE binding at that path, copied verbatim.\n\n### Lists composed item by item\nTo give a list slot a literal list, bind the Custom > Array option at its schema path, then append items with `ADD_CUSTOM_ARRAY_BINDING_ITEMS` \u2014 a binding at an item index that does not exist yet is rejected, so an empty custom array can only grow through that tool. Fill each item it returns under itemSchemaPaths with an OPTION / CONST_VALUE binding, copied verbatim. For a list of lists, each item is a custom array of its own: call `ADD_CUSTOM_ARRAY_BINDING_ITEMS` again at the item's path. Remove items with `DELETE_CUSTOM_ARRAY_BINDING_ITEMS`."}},component:{pre:{available:!0,prompt:"## Component Domain Knowledge\nThe UI is a tree of components organized into pages.\n\n### Identity & Tree Rules\nEvery component has an immutable id and a displayName. Reads return both; write tools verify the {id, displayName} pair and reject a mismatch \u2014 re-read, then retry. A container's children order IS the visual order. A component can never be moved into its own subtree.\n\n### Categories\nLayout (container \u2014 can hold other components via `children`):\n- PAGE: root of each page; created without a parent and registered as a new page.\n- LAYOUT_VIEW: generic Flexbox container; the most common container.\n- MODAL: popup/dialog container; created without a parent, opened/closed via events.\n\nSpecial (complex \u2014 children live in built-in slots seeded at creation and mutated only via the slot tools, never via ADD_COMPONENT / MOVE_COMPONENTS):\n- LIST: repeating list; its \"cell\" slot renders once per data row (optional header/footer).\n- TAB_VIEW: tabbed interface; one child view per tab in tabList.\n- SELECT_VIEW: built-in normal/selected state views.\n- CONDITIONAL_VIEW: one built-in view per condition branch.\n- MAP: optional \"marker\" slot taking a MAP_MARKER.\n\nLeaf/Business (cannot have children): BUTTON, TEXT, IMAGE, VIDEO, LOTTIE, RICH_TEXT, TEXT_INPUT, NUMBER_INPUT, VIDEO_PICKER, FILE_PICKER, SWITCH, MAP_MARKER, CALENDAR, HORIZONTAL_LINE, SHEET, HTML, RICH_TEXT_EDITOR, MIX_IMAGE_PICKER, DATE_TIME_PICKER, DATA_SELECTOR, PROGRESS_BAR. MAP_MARKER can only be placed inside MAP. `GET_SELECTABLE_COMPONENT_TYPES` returns the full creatable catalog with each type's slot fields.\n\n### Hierarchy Rules\nEvery component except PAGE and MODAL must have a Layout Component as its parent. Prefer relative positioning; use absolute/fixed only when truly necessary.\n\n### Layout\nZion uses Flexbox. Layout containers configure: direction (row/column), justify-content (start, space-between, space-evenly, space-around), gap, wrap, overflow (scroll/visible/hidden).\n\n### Responsive Breakpoints\nPhone: 0\u2013767 px (375 px panel) | Tablet: 768\u20131279 px (820 px panel) | Desktop: 1280\u20131920 px (1440 px panel). Desktop is the primary breakpoint and the one every read and write defaults to. A narrower breakpoint stores only its differences from desktop, so a field it does not override renders the desktop value at that width \u2014 an app built without touching phone is not unstyled there, it is desktop-sized there, which is how a 600 px card ends up running off a 375 px screen. Nothing fails: the schema is valid, the error center stays clean, and the only symptom is what the user sees on a phone. So a page is not finished at desktop. Read what phone actually resolves to by passing `breakpoint` to `GET_COMPONENT_INFO` and `GET_CONTAINER_CHILDREN_INFO`; the read names which fields that breakpoint overrides and which it inherits. Fix one by resending that field with the `breakpoint` param to `UPDATE_COMPONENT_STYLE` \u2014 usually flexDirection 'column' on rows, and widths in % or fill rather than px \u2014 and have the user confirm the phone breakpoint in the editor. Resending a value unchanged at a breakpoint pins it there and stops it following desktop, so override only what has to differ. The closing check at the end of a turn names any component that cannot fit the narrow panel and has nothing set there; that is a defect report, not a note.\n\n### Reading the Component Tree\n- `GET_ALL_ROOTS_INFO` \u2014 every page's {id, displayName}; start here.\n- `FIND_COMPONENTS` \u2014 when the user names a component (\"the submit button\") rather than giving an id, resolve the name to its id here instead of descending the tree container by container. One call, whole client, every match tagged with the page it sits on.\n- `GET_COMPONENT_INFO` \u2014 one component's type and config, by its component id.\n- `GET_CONTAINER_CHILDREN_INFO` \u2014 the direct children of a container (or a special component's slot), by the container's id.\n- `GET_COMPONENT_CONTEXT_INFO` \u2014 a component together with its ancestor chain and siblings, so you can see where it sits in the page.\nIds are opaque: copy them verbatim from these read tools and never modify them. A page id (from `GET_ALL_ROOTS_INFO`) is not a component id, and breakpoint keys (phone/tablet/desktop) are tool parameters, never part of an id \u2014 passing something like `<pageId>-desktop` as a component target fails with \"target component not found\".\n\n### Building & Editing the Component Tree\nConstruction workflow:\n1. `GET_ALL_ROOTS_INFO` / `GET_COMPONENT_CONTEXT_INFO` to locate where to build, and read the target container (writes are rejected until their targets have been read).\n2. `GET_SELECTABLE_COMPONENT_TYPES` to pick types; `GET_COMPONENT_TEMPLATE` for a valid starter definition \u2014 always start from a template, never hand-write component JSON.\n3. Edit the template (displayName, parentComponentId, inline children / slot definitions) and submit via `ADD_COMPONENT`. Ids are minted server-side and echoed back \u2014 use them directly instead of re-reading. Set the visible copy via content fields ('title'/'text' for BUTTON and TEXT, 'placeholder' for TEXT_INPUT); styles and remaining properties are seeded with the editor's creation defaults so components render visibly; nested children may omit parentComponentId.\n4. Verify with `GET_CONTAINER_CHILDREN_INFO`.\nContainer sizing: a LAYOUT_VIEW hugs its content, so a container created WITH its children inside is sized by them and needs no height of its own; an empty one keeps a small minimum height so it stays visible and droppable, and filling it makes that minimum irrelevant. Give a container an explicit height only when you want a fixed-size box or a scroll viewport \u2014 a fixed height its content outgrows clips that content invisibly, and a fixed width crops text mid-word. `UPDATE_COMPONENT_STYLE` merges, so a size you do not name keeps its old value.\nWidth/height `fill` means \"grow along the flex main axis\", so it only makes sense on the axis the parent lays out along: `width: fill` in a row, `height: fill` in a column. On the other axis it would unset the size and let the child shrink to its content, so it is applied as '100%' instead and the result says so. There is no `stretch` alignment to fall back on \u2014 in Zion a component declares its own size rather than having its container negotiate one.\nA row of cards is sized one axis at a time. Along the row, give every child `fill`, or fr shares \u2014 `65fr` and `35fr` \u2014 when the split is deliberate; never percentages, because fr divides what is left after the gap and the padding while `65%` + `35%` claims the whole width and the gap then pushes it over, wrapping or clipping the last column. Across the row, give every child the SAME `minHeight` so they bottom out together: a real `height` would clip the card whose content grows past it, and with no `stretch` to fall back on a shared floor is as close to equal-height cards as this system gets \u2014 a card whose content clears the floor still grows alone, so pick a floor that clears the tallest copy you expect. Set `minWidth` on a child only where that column has a genuine floor: it, not `flexWrap`, is what makes a row break into 2+1 once the container is narrower than the floors plus the gaps. Size the children this way and the container needs nothing beyond `flexDirection`, `gap` and its own width \u2014 `justifyContent` and `alignItems` have no free space left to distribute, so reaching for them to fix a ragged row means the children are the wrong size.\nA TEXT holds a paragraph only because it is allowed to break: `textWrap` false pins it to one line and cuts it with an ellipsis at its box edge, however wide the sentence is. Anything longer than a label \u2014 body copy, a description, a card blurb \u2014 wants `textWrap: true`, and `lineClamp` on top of that when it must stop after N lines. When a sentence reports as clipped horizontally, this is nearly always why: widening the box, or setting `overflowX`, does not make the text reflow.\nA TEXT_INPUT collecting a password needs `password: true` via `UPDATE_COMPONENT_PROPERTIES`; a \"Password\" placeholder alone does not mask anything.\nRestructure with `MOVE_COMPONENTS` (reparent and/or reorder; the index is the position in the final children list). Restyle with `UPDATE_COMPONENT_STYLE` \u2014 merge-based: only the fields you provide change, everything else keeps its current value; flex settings (gap/direction/alignment) apply to containers only and text settings to BUTTON/TEXT/TEXT_INPUT only; target phone/tablet with the breakpoint param and the hover state with variant. Change scalar behavior properties (enums/booleans/numbers, e.g. list direction, input type) or rename a component with `UPDATE_COMPONENT_PROPERTIES` \u2014 binding-typed properties stay with the bindings tools. Remove with `DELETE_COMPONENTS` \u2014 it deletes each id's entire subtree, and references elsewhere (bindings, event targets, navigation) are NOT cleaned up automatically, so check them afterwards.\n\n### Decide The Look Before You Place The First Component\nA request that names no visual direction \u2014 \"a task tracker\", \"a booking page\" \u2014 is not a request for no styling. It is a request for you to decide, and declining to decide is what produces the grey-box build the user then has to describe their way out of. So decide first, in one line, before the first `ADD_COMPONENT` of a new project: what this app is, who opens it, the one job it does, and the palette and type roles that reading implies. A shift-handover tool for night-shift nurses and a portfolio for a ceramicist should not resolve to the same screen; the subject is where a non-generic direction comes from, and it is the only input you have that no other project shares. State that line to the user. A stated choice gets corrected; an accidental one gets discovered three screens later. Then set the theme's colour variables (through the theme plugin) and the scale (`SET_STYLE_SCALE`) from that line, and build every screen out of them. A screen styled component-by-component, deciding each colour as it comes up, drifts by the third card \u2014 and the drift is what reads as unfinished, not any single value in it. The moment the user states a direction \u2014 a brand colour, \"dark\", \"playful\", a screenshot \u2014 it overrides all of this. What fails is splitting the difference: a stated direction on the first two screens and your own default on the rest reads worse than either applied throughout, because inconsistency looks like a bug rather than a choice.\n\n### The Palette Is Named Before It Is Spent\nA colour written as a hex is pinned to the component you wrote it on. A colour written as a colour-variable reference follows the theme. Both render identically today, so the difference only shows up later \u2014 when the same surface colour has to be repeated by hand on the fifth page, or when one recolour turns into an edit per component. Read the theme first \u2014 the theme plugin lists every colour variable with the referenceValue a colour field takes. The theme ships with Primary, Secondary, Tertiary, Text_primary, Text_secondary, Background, Surface, Border, Success, Alert and Error, each following a palette. Build with those roles and add a variable only for a role the theme lacks \u2014 and give the new variable a palette level (the theme plugin explains which), not a hex, so it recolours with the rest. A working set is roughly eight roles, named by ROLE, not by colour:\n- Four neutrals, not two: the page ground, a surface lifted off it, a border a step darker again, and a hairline/divider weaker than the border. Two neutrals is the single most common cause of a flat screen \u2014 with only \"background\" and \"border\" available, every card, input, header and divider ends up drawn with the same one, and nothing separates from anything.\n- Two inks: primary for content, muted for secondary text and labels. Do NOT make muted text by dropping `opacity` on a TEXT \u2014 opacity fades the whole component including anything it contains, and it composites against whatever is behind it, so the same \"muted\" reads differently on a card than on the page. Muted is a colour.\n- One accent, and one status colour (danger) if the app writes data.\nSpend the accent only on the primary action and the active/selected state. The moment it also appears on a heading, an icon and a border, nothing on the screen is being pointed at. Name entries by role rather than by colour \u2014 \"surface\", not \"light-grey\" \u2014 because that is what lets a later recolour of one variable restyle the whole app in one call. A literal hex belongs only on a one-off that genuinely should not move with the theme.\n\n### The Scale, And The Two Things It Does Not Carry\nSpacing, corners and type work through a scale rather than references: call `GET_STYLE_SCALE`, and if the project has none, set one with `SET_STYLE_SCALE` before the first screen \u2014 six or seven spacing steps, four or five radii, five or six named text roles (page title, section heading, body, label, caption), at most two font families. Values you send afterwards are pulled onto the nearest step and the result says when that happened; a value far from every step is left as sent, so a deliberate one-off \u2014 a pill radius, a hero size \u2014 still survives. This is not decoration: a build without a scale ends up with paddings of 12 and 14 and 18 and radii of 9 and 10 and 12, each defensible alone, and the result reads as unfinished even though every screen is individually reasonable. A text role carries `fontSize`, `fontWeight` and `lineHeight` \u2014 asking for a heading gets you the whole heading, not heading size at body weight. It does NOT carry `letterSpacing` or `fontFamily`. Those two exist only as per-component fields on `UPDATE_COMPONENT_STYLE`, so if you never send them, every text in the app is at the default tracking in the default face. That default is exactly what \"looks like a wireframe\" means, and it is two extra fields to fix.\n\n### Typography Carries Most Of The Impression\nThe type is the largest coloured area on almost every screen, so it decides the character of the page before any accent does.\n- Typeface is a real choice, but the platform's faces are a fixed set and nothing validates what you send against it: `fontFamily` on `UPDATE_COMPONENT_STYLE` takes any string and stores it verbatim, so a face the platform does not ship is not rejected and not substituted \u2014 it is simply stored, and the client renders a fallback. You will not be told. (If the project's scale already declares families, sending one outside them returns a note and still stores it; if the scale declares none, nothing is checked at all.) So pick from the faces that exist.\n The default is DM Sans on web and pingFang SC on mobile, so leaving it alone is not neutral \u2014 it is the same face every other project ships with. Nine faces exist on EVERY client: pingFang SC, HarmonyOS Sans, microsoft yahei, stheiti, simsun, helvetica neue, tahoma, Montserrat, Smiley Sans. A WEB app has twenty-seven more, and they are worth picking by job rather than off a flat list:\n - CJK body: Noto Sans SC, SiYuan HeiTi, Mi Sans, OPPO Sans, Alibaba PuHuiTi.\n - CJK serif: SiYuan SongTi, Swei Spring SongTi \u2014 simsun is the system default and reads dated.\n - CJK rounded, for a friendlier brief: Resource Han Rounded, SiYuan RouHeiTi.\n - CJK display, headline only and never body: Alimama ShuHeiTi, ZhanKu WenYiTI, Tsanger YuYangTi, ZCOOL GDH, ZCOOL Kuhei, Youshe Header Heiti, Pangmenzhengdao Header, Pangmenzhengdao Light, Wendaochao Heiti.\n - Latin workhorses: DM Sans, Plus Jakarta Sans, Inter, Roboto, open sans, plus the system face -apple-system.\n - Montserrat is a geometric display voice, D-DIN-PRO a technical one, Yellowtail a script for a single display line and nothing else, and Vonwaon Bitmap a pixel face for a deliberately informal brief.\n If the copy is Chinese, the BODY face has to be a CJK one, not just the headline: a Latin family carries no Chinese glyphs at all, so every Chinese character falls back to whatever the device has and the page you designed is not the page that renders.\n One family is a complete answer; two only when clearly distinct in role (a display face and a text face), never two sans faces that differ slightly. `GET_STYLE_SCALE` reports which ones this project already committed to \u2014 follow those rather than introducing a third.\n- Hierarchy comes from weight and space as much as from size. Three text roles that differ only in `fontSize` read as one undifferentiated block; a heading at 600\u2013700 against body at 400 separates at a glance even when the sizes are close.\n- `letterSpacing` is in PIXELS, not em, and goes NEGATIVE on large display type \u2014 roughly -0.5px at a 28\u201332px page title, -1px or beyond as the size grows \u2014 because a face designed at body size is too loose when set large. Body text wants 0. A fractional value like -0.02 changes nothing visible, so sending one and then reporting the tracking as tightened is a false claim. It goes slightly POSITIVE only on small uppercase labels, which are themselves worth avoiding (see below).\n- Set `maxWidth` on any TEXT holding a paragraph. Unbounded body text stretches to the container and a 1200px-wide line is unreadable regardless of how well it is styled; hold it near 60\u201370 characters, which at body size is roughly 600\u2013680px. A capped column keeps hugging the left edge until its PARENT centres it \u2014 in a column parent (a PAGE's default) that is `alignItems: 'center'`. This is the most-skipped and most-visible typographic fix in a wide desktop layout.\n- Body text needs `textWrap: true` \u2014 false pins it to one line and ellipsises it at the box edge however wide the sentence is. `lineClamp` on top when it must stop after N lines.\n\n### Depth Is One Decision, Applied Once\n`shadow` takes `{ offsetX, offsetY, blur, spread, color, inset }`, so it can do far more than a default drop shadow, and the failure mode is using it everywhere rather than using it well.\n- A card lifts off the page with EITHER a hairline border OR a soft shadow, not both. Pick one for the whole app.\n- A real shadow is large, soft and nearly transparent, and offset downward only \u2014 light comes from above. A tight dark shadow at every corner is the tell that nothing was decided; `blur` well above `offsetY`, and a colour at low alpha, is what reads as expensive.\n- Elevation is a scale like everything else: at most two levels \u2014 resting surface, and the raised thing (modal, dropdown, the one hero card). A third level means the second is not doing its job.\n- `inset: true` is for the pressed state of a button and for a well an input sits in. It is the only correct way to make something look recessed rather than raised.\n- `backdropBlur` belongs on overlay chrome that sits over content \u2014 a sticky header, a modal scrim. On an ordinary card it costs paint and buys nothing, since there is nothing behind it to blur.\n- `borderRadiusCorners` exists for the cases a single radius cannot express: a segmented control, a sheet rounded only at the top, a cell at the end of a row. Reach for it there and nowhere else.\n- Radius is hierarchy. If the card, the input, the badge and the button all carry the same value, the screen has told the user nothing about what is what.\n\n### Space Is The Cheapest Thing That Reads As Finished\nThe common failure is far too little of it, and it is not a matter of taste \u2014 the numbers are knowable. On desktop, section padding starts at 64px vertical and goes up, not down; card padding at 20\u201324px; the page gutter at least two spacing steps above the in-card gap, so a card reads as sitting on the page rather than pasted onto it. When a screen feels cramped, the fix is almost always more space AROUND the groups, not less space inside them. Proximity is the actual signal: things that belong together sit closer to each other than to anything else, and if a label is equidistant from its own field and the next one, the layout has lost the reader regardless of how the label is styled.\n\n### The Look That Reads As Generated\nNone of these is forbidden \u2014 each is right for some brief \u2014 but they are what gets reached for when nothing has been decided, so they appear regardless of subject. Where the user asked for one, give it to them. Where they left the axis free, spend the freedom elsewhere:\n- Cream page (near #F4F1EA) with a high-contrast serif display and a terracotta/clay accent (near #D97757).\n- Near-black page with one acid-green or vermilion accent.\n- Every surface on the same radius under the same soft grey shadow, whatever its role.\n- A tracked-out ALL-CAPS eyebrow label above every heading.\n- Meta strings joined with middle dots ('A \xB7 B \xB7 C'); '\u2192' appended to button text.\n- One word in a heading coloured or bolded to add interest.\n- Numbered markers (01 / 02 / 03) on content that is not actually a sequence.\n- A gradient used as decoration on a surface that has no reason to be gradient. A gradient is legitimate as the subject of a hero, or to keep text legible over an image; as a wash behind ordinary cards it is the clearest single tell.\n\n### Every Interactive Thing Answers The Cursor\n`UPDATE_COMPONENT_STYLE` takes `variant: 'hover'`, and a build that never sends it is a build where nothing on screen responds to the mouse. That, more than any colour choice, is what makes a page feel like a mockup rather than an application. Give every BUTTON, every clickable card and every list row a hover state \u2014 a surface a step lighter or darker is enough, and it costs one extra call per component type, not per component, because you are styling the same few shapes. Set `cursor: 'pointer'` on anything clickable that is not a BUTTON: a LAYOUT_VIEW with an ON_CLICK handler still shows an arrow cursor, so the user has no way to know it is a target. Where a SELECT_VIEW or a TAB_VIEW has a selected state, style it. The default selected state is not a design decision, and \"the active tab looks like the inactive ones\" is a bug the user will report in different words.\n\n### Three Things Can Be Conditional \u2014 Pick The Smallest One\nWhen a screen has two modes, do NOT reach for a conditional container first. Ask what actually differs between the modes, and make only that conditional:\n- Conditional DATA (`CREATE_CONDITIONAL_BINDING`) when only VALUES differ \u2014 a label, a title, a placeholder, a colour. One component, one conditional binding whose branches are keyed off the deciding value. This is the default answer.\n- Conditional ACTION when only BEHAVIOR differs \u2014 one button that submits, signs in or signs up depending on the mode. One button, one handler that branches.\n- Conditional VIEW (CONDITIONAL_VIEW) only when the STRUCTURE differs \u2014 different fields, different counts of children. Branches do NOT share children, so anything you put in a branch is duplicated in every other branch. If the two modes share a form, keep the shared form OUTSIDE the CONDITIONAL_VIEW and put only the differing part inside it.\nA \"switchable signup / login\" is therefore conditional data plus a conditional action over ONE shared form \u2014 not two branches each holding a copy of the same fields. Wrapping shared UI in branches is the classic wrong answer: it looks right and silently doubles the tree.\nTAB_VIEW is a different question entirely: use it only when the tab strip itself is the affordance the user should see and click. It renders tab chrome you cannot remove.\nBoth TAB_VIEW and CONDITIONAL_VIEW take `preserveStateOnSwitch`, and it is the same mechanism in both: true keeps every case alive, so a scrolled list, a half-filled input or a loaded query survives switching away and back; false tears the inactive case down and rebuilds it from scratch. Both are created with it ON. Turn it off only when stale state would be wrong (a form that must reset), and remember the cost: every case stays mounted.\n\n### Who Owns A CONDITIONAL_VIEW's Active Branch\nBranch conditions and SWITCH_VIEW_CASE write the SAME runtime slot, so exactly one of them owns a given container \u2014 never both. A tool call that mixes them is rejected.\n- Conditions own it (the default). The mode is app state: a page variable, a query result, a login state. Narrow each branch's condition at the conditionSchemaPath `ADD_COMPONENT` / `ADD_CONDITIONAL_VIEW_BRANCHES` echoes, and change the mode with SET_VARIABLE_DATA. Only this way does the right branch show on first render, react to data, and stay readable by everything else \u2014 a title, a colour, a query filter can all condition on the same variable.\n- SWITCH_VIEW_CASE owns it only when the selection is purely visual, nothing outside the container will ever need to know which branch is active, and the first branch is the correct starting view \u2014 a carousel or an accordion. It never runs on page load and stores the choice where nothing can read it.\nLeft alone, branch conditions are always-true and the FIRST branch always shows. That is the state right after creation, so narrow them or switch to SWITCH_VIEW_CASE deliberately.\n\n### Slots of Special Components\nSlot children are mutated only with the slot tools:\n- TAB_VIEW tabs: `ADD_TAB_VIEW_TABS` creates each tab's content container (a LAYOUT_VIEW child) plus its tabList entry, echoing the content child's id and the tab title binding's schemaPath. Tabs are addressed by their content-child id everywhere: `DELETE_TAB_VIEW_TABS` (a TAB_VIEW keeps at least 2 tabs) and `REORDER_TAB_VIEW_TABS` (pass a full permutation).\n- CONDITIONAL_VIEW branches: `ADD_CONDITIONAL_VIEW_BRANCHES` inserts always-true branches \u2014 narrow each one with the bindings plugin's condition tools at the echoed conditionSchemaPath. Branch order IS evaluation order (first matching condition wins): `REORDER_CONDITIONAL_VIEW_BRANCHES`. The default case cannot be deleted (`DELETE_CONDITIONAL_VIEW_BRANCHES` takes non-default branches only) and always stays last.\n- Optional slots: `SET_COMPONENT_SLOT` fills an empty LIST 'header'/'footer' or MAP 'marker' slot with a freshly created default child; `CLEAR_COMPONENT_SLOT` empties it again, deleting the subtree. Required slots (LIST 'cell', SELECT_VIEW states) are fixed at creation \u2014 to change one, recreate the component.\n- SHEET columns: a SHEET does not take its data through a binding. `SET_SHEET_DATA_SOURCE` builds its embedded query from a table \u2014 call it immediately after creating the SHEET, because one without a data source is invalid \u2014 then add the displayed columns with `ADD_SHEET_COLUMNS`, managing them by data-field name with `DELETE_SHEET_COLUMNS` / `REORDER_SHEET_COLUMNS`. Filters and sorts go on the echoed querySchemaPath with the request tools.\n\n### Components That Display a Field of Their Data\nDATA_SELECTOR, SELECT_VIEW and LIST name one field of their data source: `displayDataField` (the value the user sees) and `cellKeyDataField` (the row identity). Binding the dataSource is not enough \u2014 a DATA_SELECTOR or SELECT_VIEW whose data source resolves to a list of objects is invalid until its displayDataField is set. Set it with `UPDATE_COMPONENT_PROPERTIES`, passing the field's plain NAME as a string; the full field reference is resolved for you, so never hand-assemble one. The candidates appear as selectableDataFields in `GET_COMPONENT_INFO` once the dataSource is bound \u2014 so the order is always: create \u2192 bind dataSource \u2192 read the component \u2192 name the field.\n\n### Page Data: Queries, Variables & Inputs\nPages have NO separate query list \u2014 a page query IS a read-only page variable whose dataSource is a database query. It is for data more than one component reads, or a filter the page owns centrally; a single list showing one filtered table binds that table itself (see Data Bindings below) and needs nothing here:\n- `ADD_COMPONENT_QUERY` attaches a table query to a PAGE or MODAL (limit 1 = single row, >1 = list). Components consume it through data bindings (bindings plugin) at the echoed dataSourceSchemaPath; narrow filters and sorting with the request-filter tools at that same path. The result also reports rolesWithoutSelect \u2014 grant SELECT with the permission plugin's table-permission tool; never assume it is granted automatically. Tune with `UPDATE_COMPONENT_QUERY`; remove queries and variables alike with `DELETE_COMPONENT_VARIABLES`.\n- Page-local mutable state: `ADD_COMPONENT_VARIABLES`, with each typeIdentifier picked from `GET_COMPONENT_VARIABLE_SELECTABLE_TYPES` \u2014 never hand-assembled. A new variable starts with no value, so give it an initial one at the `defaultValueSchemaPath` the result echoes whenever anything reads it: conditional cases, branch conditions and SET_VARIABLE_DATA values all test the variable against specific values, and none of them match an empty variable. The page then loads with every dependent case unmatched \u2014 blank labels, the fallback branch showing \u2014 and a toggle whose new value is itself conditional on the old one cannot recover, because it has nothing to match either.\n- Page parameters: `ADD_COMPONENT_INPUTS` / `UPDATE_COMPONENT_INPUT` / `DELETE_COMPONENT_INPUTS`. WEB pages take URL query/path params; WECHAT/MOBILE pages and MODALs take general inputs. Navigation and show-modal call sites pass one value per input.\n- `SET_INITIAL_PAGE_ID` sets the app's home page for the current client.\n\n### Client Variables\nThe current client's app-wide variables: every page reads and sets them, and each client (WEB / mini program / mobile) keeps its own table, so a value set on one is not the other's. State that has to survive navigation belongs here rather than in a page variable.\n- Read them with `GET_CLIENT_VARIABLES_INFO`; declare with `ADD_CLIENT_VARIABLES`, each typeIdentifier picked from `GET_CLIENT_VARIABLE_SELECTABLE_TYPES`; rename or retype with `UPDATE_CLIENT_VARIABLES`; remove with `DELETE_CLIENT_VARIABLES`.\n- A new variable starts with no value: fill it at the `defaultValueSchemaPath` the add echoes with the bindings plugin. That value is a literal \u2014 no variable, formula or expression may stand in for it.\n- A variable declared inside one action flow is that flow's own, not one of these.\n- Deleting one does not clean the bindings and set-client-variable actions that name it; the result's danglingReferences lists them, so repoint or remove them in the same turn.\n\n### Data Bindings on Components\n`GET_COMPONENT_BINDABLE_PROPERTIES` lists every place a component can be bound \u2014 always start there and copy the paths verbatim, never hand-assemble a binding path. It returns two sections: `properties`, the component's own slots, each with its ready-to-use schemaPath, expected type, current binding and scope; and `actionSlots`, the parameter slots of the actions already wired to its events, chained success/failure branches included. `ADD_COMPONENT_ACTIONS` echoes an action's slots when it creates it \u2014 bind them in the same turn when you can, and use `actionSlots` to find them again in any later turn. Fill the echoed paths with the bindings plugin's tools: `BROWSE_DATA_BINDING_OPTIONS` + `CREATE_OPTION_BINDING` for dataSource slots and other dynamic values, `CREATE_CONST_BINDING` for literals. A LIST, SELECT_VIEW or DATA_SELECTOR can take its dataSource either way, and the options tree offers both in one answer: the tables under 'Table', and any page query under 'Context > Current page > Data source'. **Prefer the table** \u2014 a component that owns its data source is filtered, sorted and retyped in one place, and `GET_REQUEST_FILTER_CONTEXT` narrows it at the component's own path. Reach for a page query (`ADD_COMPONENT_QUERY` first) only when the SAME result set is genuinely shared \u2014 two components reading one query, or a filter the page tunes centrally. One component, one filtered list is not a sharing case: adding a page variable there buys nothing and leaves a second thing to keep in step. Inside a list cell (scope \"list-cell:<listId>\") the options tree additionally offers the current list item's fields under 'item-data' \u2014 bind cell children to those instead of re-querying the table.\n\n### Editing Protocol\n- Read-before-edit: editing a component (or inserting into a container) you have not read fails with \"has not been read\" \u2014 read it first; after a conflict, re-read and retry. One read of a container covers both adding children to it and editing its own configuration, so `GET_COMPONENT_INFO` and `GET_CONTAINER_CHILDREN_INFO` on the same component is one call wasted.\n- Everything you call in a single turn applies as one atomic batch: if any call in it fails, none of them landed, so fix the offending call and resend the whole group. Calls in *different* turns are independent \u2014 a failure there leaves earlier turns' work in place.\n- Prefer one turn over many. Independent reads should always go together, and a read may sit in the same turn as an edit that depends on it. The one thing you cannot do is use an id or schema path echoed by a call in the same turn \u2014 those are only visible once the turn returns, so anything consuming them belongs in the next turn.\n- Wiring behavior is always the same three steps: `GET_COMPONENT_SELECTABLE_EVENTS` for the events this component exposes, `GET_SELECTABLE_COMPONENT_ACTIONS` for the actions that event accepts here, then `ADD_COMPONENT_ACTIONS` to attach one. Never guess a kind \u2014 the selectable list is already filtered to this client's platform and the project's configuration, so anything absent from it cannot be attached and must be built in the editor instead. Remove any handler with `DELETE_COMPONENT_EVENT_HANDLERS`.\n- Every action seeds its parameters as empty bindings and echoes them in bindableSchemaPaths; fill them with the bindings plugin's tools. Anything a specific kind returns beyond that arrives under that handler's `details`.\n- Pick the kind from `GET_SELECTABLE_COMPONENT_ACTIONS` and take its parameter shape from this tool's parameter schema, which is the only complete list of the kinds and their fields \u2014 the editor offers far more than the handful named below, including SHOW_TOAST, OPEN_EXTERNAL_LINK, SET_CLIPBOARD, DOWNLOAD_FILE, CALL_PHONE, the payment kinds and the animation kinds. Do not conclude an interaction is impossible because it is not discussed here; the selectable list and the schema decide that. What follows is only the judgment the schema cannot carry.\n- ALERT_DIALOG is the runtime's own confirm box \u2014 a title, a message and two buttons it draws itself, with no MODAL to build or lay out. Use it for \"are you sure?\"; use SHOW_MODAL when the dialog needs your own components in it. Chain what confirming does onto ALERT_DIALOG's ON_CONFIRM branch, or the buttons do nothing.\n- Building a MODAL does not make it reachable. Without a SHOW_MODAL action pointing at it, nothing opens it, and the modal you just laid out is dead UI the user cannot reach.\n- An action that produces a RESULT \u2014 GET_LOCATION, UPLOAD_FILE, GENERATE_QR_CODE and the other result-bearing kinds \u2014 can only keep it through assignToVariable, a writable page variable created with `ADD_COMPONENT_VARIABLES` on the page the component sits on. Their success branches cannot see the result, so an action without assignToVariable runs and throws its answer away. Create the variable first.\n- SIGN_UP and USER_LOGIN are separate actions, and the password slot on a SIGN_UP decides what the account can sign in with later: leave it unbound and the account has no password, so a USER_LOGIN with credentialType PASSWORD can never succeed for anyone who signed up there. Build the pair together, or sign in with VERIFICATION_CODE.\n- A WeChat mini-program signs its user in by itself. The client is created with a silent WeChat login in its own app-did-load configuration, which the editor will not let anyone delete, so whoever opens the app is already signed in, and the account is created there too. Do NOT build a sign-in or sign-up screen there and do NOT wire a login action: USER_LOGIN offers no WeChat mode at all, the silent login belongs to that configuration alone, and SIGN_IN / SIGN_UP / SIGN_OUT are absent from the mini-program's selectable actions. When the app needs the user's phone number, use OBTAIN_PHONE_NUMBER.\n- MUTATION writes the database without an action flow. rolesWithoutPermission in its result is report-only \u2014 grant the table permission with the permission plugin or the write is denied at runtime, which looks like a silent no-op to the user. rowScope CURRENT_ITEM is valid only inside a LIST cell; refreshOnSuccess is preferable to a separate REFRESH.\n- SCHEDULED_JOB_CONTROL starts or pauses a page timer; the timer itself is built with `ADD_COMPONENT_SCHEDULED_JOBS` and renamed, rescheduled or removed with `UPDATE_COMPONENT_SCHEDULED_JOB` / `DELETE_COMPONENT_SCHEDULED_JOBS`. A job is a schedule and nothing else \u2014 until it has actions it fires on its interval and does nothing \u2014 and every one of those calls takes the PAGE or MODAL itself rather than a component inside it. Its actions come from `ADD_COMPONENT_ACTIONS` and `DELETE_COMPONENT_EVENT_HANDLERS` carrying its scheduledJobId; its interval is in milliseconds.\n- CONDITIONAL is how ONE event does different things in different cases: branches in evaluation order, first match wins, each branch narrowed at the echoed conditionSchemaPath and filled by a further `ADD_COMPONENT_ACTIONS` carrying that branch's conditionalBranchId. Leave the last branch always-true as the else. Without it every action on the event fires on every click \u2014 ON_SUCCESS / ON_FAILURE branch on whether a call worked, never on a data condition. Do NOT reach for an action flow to get branching: a flow's BRANCH node runs on the server and cannot navigate, toast or open a modal, so frontend branching belongs here. This decides what HAPPENS; a CONDITIONAL_VIEW decides what is DISPLAYED.\n- There is no per-component conditional visibility \u2014 an ordinary component has no data-driven show/hide flag. To make content appear only when a condition holds, wrap it in a CONDITIONAL_VIEW container and gate the branch with the bindings plugin's condition tools (see CONDITIONAL_VIEW branches under \"Slots of Special Components\").\n\n### Motion Is One Moment, Not A Coat Of Paint\nZion has animation as ACTIONS, not style fields, so they are attached with `ADD_COMPONENT_ACTIONS` like any other handler: ANIMATION_FADE_EFFECT and ANIMATION_SLIDE_EFFECT (APPEAR / DISAPPEAR, eight directions, a distance defaulting to 150px), ANIMATION_SCALE_EFFECT, ANIMATION_COMMON_EMPHASIS (BOUNCE / PULSE / BLINK), ANIMATION_FLIP_EMPHASIS, and ANIMATION_SCROLLING_INTERACTION. Each takes delay, and the emphasis kinds take repeat or loop.\nThe rules are hard ones, and breaking them shows up as a project error rather than a subtle defect: exactly ONE animation per event, and only on onClick, onHover or onScrollIntoPage \u2014 the runtime reads the last effect it finds on the event and ignores any attached elsewhere. ANIMATION_SCROLLING_INTERACTION is the exception and goes ONLY on onPageScroll, which carries nothing else at all, because the curve is driven by scroll distance. None of them take attachTo and none take bindings, so they cannot be chained onto a success branch.\nSpend motion the way you spend the accent. Movement that answers what a person just did \u2014 a press, an open, a confirm \u2014 is worth it, because it shows what changed. Movement that merely announces that content exists is the generated-page tell: a fade-and-slide on every section as it scrolls into view reads as a template, and it reads that way precisely because it is the first thing reached for. One orchestrated moment on the screen that matters beats an effect on every card, and a screen with no animation at all is a perfectly good answer \u2014 far better than one where everything twitches. The emphasis kinds earn their place on something genuinely needing attention, never as decoration, and BLINK almost never earns it.\n\n### Reviewing The Screen You Built\nMake ALL edits first, then run `schema validate` and resolve anything your changes introduced. The editor's error center and canvas screenshots are not reachable from here, so you cannot confirm a result visually \u2014 ask the user to open the screen in the editor and read it against the following, then fix what they report:\n1. Is there one clear focal point, or is everything competing at the same weight?\n2. Do related things sit closer together than unrelated things?\n3. Are there at least three distinguishable levels of text, and do they differ in weight and not only in size?\n4. Does anything touch an edge that should have gutter, or run to a line length past ~70 characters?\n5. Does the accent appear only on the primary action and the active state, or has it leaked onto headings and borders?\n6. Does anything on the screen respond to hover?\nName what you are fixing and fix it. A screen that passes `schema validate` and fails all six is not done \u2014 validation only knows about invalid schema, and none of the above is invalid. Report only what you actually changed. Every claim about appearance \u2014 a heading looks larger, a selected state looks different, spacing was tightened \u2014 must correspond to an `UPDATE_COMPONENT_STYLE` (or creation-time style) call you made in this session. If a requested look was not achievable with the available tools, say which part you skipped and why; do not describe the component's built-in default styling as if you had applied it. A user who is told the work is done stops checking."},post:{available:!0,prompt:"## Component Domain Knowledge\nThe UI is a tree of components organized into pages.\n\n### Identity & Tree Rules\nEvery component has an immutable id and a displayName. Reads return both; write tools verify the {id, displayName} pair and reject a mismatch \u2014 re-read, then retry. A container's children order IS the visual order. A component can never be moved into its own subtree.\n\n### Categories\nLayout (container \u2014 can hold other components via `children`):\n- PAGE: root of each page; created without a parent and registered as a new page.\n- LAYOUT_VIEW: generic Flexbox container; the most common container.\n- MODAL: popup/dialog container; created without a parent, opened/closed via events.\n\nSpecial (complex \u2014 children live in built-in slots seeded at creation and mutated only via the slot tools, never via ADD_COMPONENT / MOVE_COMPONENTS):\n- LIST: repeating list; its \"cell\" slot renders once per data row (optional header/footer).\n- TAB_VIEW: tabbed interface; one child view per tab in tabList.\n- SELECT_VIEW: built-in normal/selected state views.\n- CONDITIONAL_VIEW: one built-in view per condition branch.\n- MAP: optional \"marker\" slot taking a MAP_MARKER.\n\nLeaf/Business (cannot have children): BUTTON, TEXT, IMAGE, VIDEO, LOTTIE, RICH_TEXT, TEXT_INPUT, NUMBER_INPUT, VIDEO_PICKER, FILE_PICKER, SWITCH, MAP_MARKER, CALENDAR, HORIZONTAL_LINE, SHEET, HTML, RICH_TEXT_EDITOR, MIX_IMAGE_PICKER, DATE_TIME_PICKER, DATA_SELECTOR, PROGRESS_BAR. MAP_MARKER can only be placed inside MAP. `GET_SELECTABLE_COMPONENT_TYPES` returns the full creatable catalog with each type's slot fields.\n\n### Hierarchy Rules\nEvery component except PAGE and MODAL must have a Layout Component as its parent. Prefer relative positioning; use absolute/fixed only when truly necessary.\n\n### Layout\nZion uses Flexbox. Layout containers configure: direction (row/column), justify-content (start, space-between, space-evenly, space-around), gap, wrap, overflow (scroll/visible/hidden).\n\n### Responsive Breakpoints\nPhone: 0\u2013767 px (375 px panel) | Tablet: 768\u20131279 px (820 px panel) | Desktop: 1280\u20131920 px (1440 px panel). Desktop is the primary breakpoint and the one every read and write defaults to. A narrower breakpoint stores only its differences from desktop, so a field it does not override renders the desktop value at that width \u2014 an app built without touching phone is not unstyled there, it is desktop-sized there, which is how a 600 px card ends up running off a 375 px screen. Nothing fails: the schema is valid, the error center stays clean, and the only symptom is what the user sees on a phone. So a page is not finished at desktop. Read what phone actually resolves to by passing `breakpoint` to `GET_COMPONENT_INFO` and `GET_CONTAINER_CHILDREN_INFO`; the read names which fields that breakpoint overrides and which it inherits. Fix one by resending that field with the `breakpoint` param to `UPDATE_COMPONENT_STYLE` \u2014 usually flexDirection 'column' on rows, and widths in % or fill rather than px \u2014 and have the user confirm the phone breakpoint in the editor. Resending a value unchanged at a breakpoint pins it there and stops it following desktop, so override only what has to differ. The closing check at the end of a turn names any component that cannot fit the narrow panel and has nothing set there; that is a defect report, not a note.\n\n### Reading the Component Tree\n- `GET_ALL_ROOTS_INFO` \u2014 every page's {id, displayName}; start here.\n- `FIND_COMPONENTS` \u2014 when the user names a component (\"the submit button\") rather than giving an id, resolve the name to its id here instead of descending the tree container by container. One call, whole client, every match tagged with the page it sits on.\n- `GET_COMPONENT_INFO` \u2014 one component's type and config, by its component id.\n- `GET_CONTAINER_CHILDREN_INFO` \u2014 the direct children of a container (or a special component's slot), by the container's id.\n- `GET_COMPONENT_CONTEXT_INFO` \u2014 a component together with its ancestor chain and siblings, so you can see where it sits in the page.\nIds are opaque: copy them verbatim from these read tools and never modify them. A page id (from `GET_ALL_ROOTS_INFO`) is not a component id, and breakpoint keys (phone/tablet/desktop) are tool parameters, never part of an id \u2014 passing something like `<pageId>-desktop` as a component target fails with \"target component not found\".\n\n### Building & Editing the Component Tree\nConstruction workflow:\n1. `GET_ALL_ROOTS_INFO` / `GET_COMPONENT_CONTEXT_INFO` to locate where to build, and read the target container (writes are rejected until their targets have been read).\n2. `GET_SELECTABLE_COMPONENT_TYPES` to pick types; `GET_COMPONENT_TEMPLATE` for a valid starter definition \u2014 always start from a template, never hand-write component JSON.\n3. Edit the template (displayName, parentComponentId, inline children / slot definitions) and submit via `ADD_COMPONENT`. Ids are minted server-side and echoed back \u2014 use them directly instead of re-reading. Set the visible copy via content fields ('title'/'text' for BUTTON and TEXT, 'placeholder' for TEXT_INPUT); styles and remaining properties are seeded with the editor's creation defaults so components render visibly; nested children may omit parentComponentId.\n4. Verify with `GET_CONTAINER_CHILDREN_INFO`.\nContainer sizing: a LAYOUT_VIEW hugs its content, so a container created WITH its children inside is sized by them and needs no height of its own; an empty one keeps a small minimum height so it stays visible and droppable, and filling it makes that minimum irrelevant. Give a container an explicit height only when you want a fixed-size box or a scroll viewport \u2014 a fixed height its content outgrows clips that content invisibly, and a fixed width crops text mid-word. `UPDATE_COMPONENT_STYLE` merges, so a size you do not name keeps its old value.\nWidth/height `fill` means \"grow along the flex main axis\", so it only makes sense on the axis the parent lays out along: `width: fill` in a row, `height: fill` in a column. On the other axis it would unset the size and let the child shrink to its content, so it is applied as '100%' instead and the result says so. There is no `stretch` alignment to fall back on \u2014 in Zion a component declares its own size rather than having its container negotiate one.\nA row of cards is sized one axis at a time. Along the row, give every child `fill`, or fr shares \u2014 `65fr` and `35fr` \u2014 when the split is deliberate; never percentages, because fr divides what is left after the gap and the padding while `65%` + `35%` claims the whole width and the gap then pushes it over, wrapping or clipping the last column. Across the row, give every child the SAME `minHeight` so they bottom out together: a real `height` would clip the card whose content grows past it, and with no `stretch` to fall back on a shared floor is as close to equal-height cards as this system gets \u2014 a card whose content clears the floor still grows alone, so pick a floor that clears the tallest copy you expect. Set `minWidth` on a child only where that column has a genuine floor: it, not `flexWrap`, is what makes a row break into 2+1 once the container is narrower than the floors plus the gaps. Size the children this way and the container needs nothing beyond `flexDirection`, `gap` and its own width \u2014 `justifyContent` and `alignItems` have no free space left to distribute, so reaching for them to fix a ragged row means the children are the wrong size.\nA TEXT holds a paragraph only because it is allowed to break: `textWrap` false pins it to one line and cuts it with an ellipsis at its box edge, however wide the sentence is. Anything longer than a label \u2014 body copy, a description, a card blurb \u2014 wants `textWrap: true`, and `lineClamp` on top of that when it must stop after N lines. When a sentence reports as clipped horizontally, this is nearly always why: widening the box, or setting `overflowX`, does not make the text reflow.\nA TEXT_INPUT collecting a password needs `password: true` via `UPDATE_COMPONENT_PROPERTIES`; a \"Password\" placeholder alone does not mask anything.\nRestructure with `MOVE_COMPONENTS` (reparent and/or reorder; the index is the position in the final children list). Restyle with `UPDATE_COMPONENT_STYLE` \u2014 merge-based: only the fields you provide change, everything else keeps its current value; flex settings (gap/direction/alignment) apply to containers only and text settings to BUTTON/TEXT/TEXT_INPUT only; target phone/tablet with the breakpoint param and the hover state with variant. Change scalar behavior properties (enums/booleans/numbers, e.g. list direction, input type) or rename a component with `UPDATE_COMPONENT_PROPERTIES` \u2014 binding-typed properties stay with the bindings tools. Remove with `DELETE_COMPONENTS` \u2014 it deletes each id's entire subtree, and references elsewhere (bindings, event targets, navigation) are NOT cleaned up automatically, so check them afterwards.\n\n### Decide The Look Before You Place The First Component\nA request that names no visual direction \u2014 \"a task tracker\", \"a booking page\" \u2014 is not a request for no styling. It is a request for you to decide, and declining to decide is what produces the grey-box build the user then has to describe their way out of. So decide first, in one line, before the first `ADD_COMPONENT` of a new project: what this app is, who opens it, the one job it does, and the palette and type roles that reading implies. A shift-handover tool for night-shift nurses and a portfolio for a ceramicist should not resolve to the same screen; the subject is where a non-generic direction comes from, and it is the only input you have that no other project shares. State that line to the user. A stated choice gets corrected; an accidental one gets discovered three screens later. Then set the theme's colour variables (through the theme plugin) and the scale (`SET_STYLE_SCALE`) from that line, and build every screen out of them. A screen styled component-by-component, deciding each colour as it comes up, drifts by the third card \u2014 and the drift is what reads as unfinished, not any single value in it. The moment the user states a direction \u2014 a brand colour, \"dark\", \"playful\", a screenshot \u2014 it overrides all of this. What fails is splitting the difference: a stated direction on the first two screens and your own default on the rest reads worse than either applied throughout, because inconsistency looks like a bug rather than a choice.\n\n### The Palette Is Named Before It Is Spent\nA colour written as a hex is pinned to the component you wrote it on. A colour written as a colour-variable reference follows the theme. Both render identically today, so the difference only shows up later \u2014 when the same surface colour has to be repeated by hand on the fifth page, or when one recolour turns into an edit per component. Read the theme first \u2014 the theme plugin lists every colour variable with the referenceValue a colour field takes. The theme ships with Primary, Secondary, Tertiary, Text_primary, Text_secondary, Background, Surface, Border, Success, Alert and Error, each following a palette. Build with those roles and add a variable only for a role the theme lacks \u2014 and give the new variable a palette level (the theme plugin explains which), not a hex, so it recolours with the rest. A working set is roughly eight roles, named by ROLE, not by colour:\n- Four neutrals, not two: the page ground, a surface lifted off it, a border a step darker again, and a hairline/divider weaker than the border. Two neutrals is the single most common cause of a flat screen \u2014 with only \"background\" and \"border\" available, every card, input, header and divider ends up drawn with the same one, and nothing separates from anything.\n- Two inks: primary for content, muted for secondary text and labels. Do NOT make muted text by dropping `opacity` on a TEXT \u2014 opacity fades the whole component including anything it contains, and it composites against whatever is behind it, so the same \"muted\" reads differently on a card than on the page. Muted is a colour.\n- One accent, and one status colour (danger) if the app writes data.\nSpend the accent only on the primary action and the active/selected state. The moment it also appears on a heading, an icon and a border, nothing on the screen is being pointed at. Name entries by role rather than by colour \u2014 \"surface\", not \"light-grey\" \u2014 because that is what lets a later recolour of one variable restyle the whole app in one call. A literal hex belongs only on a one-off that genuinely should not move with the theme.\n\n### The Scale, And The Two Things It Does Not Carry\nSpacing, corners and type work through a scale rather than references: call `GET_STYLE_SCALE`, and if the project has none, set one with `SET_STYLE_SCALE` before the first screen \u2014 six or seven spacing steps, four or five radii, five or six named text roles (page title, section heading, body, label, caption), at most two font families. Values you send afterwards are pulled onto the nearest step and the result says when that happened; a value far from every step is left as sent, so a deliberate one-off \u2014 a pill radius, a hero size \u2014 still survives. This is not decoration: a build without a scale ends up with paddings of 12 and 14 and 18 and radii of 9 and 10 and 12, each defensible alone, and the result reads as unfinished even though every screen is individually reasonable. A text role carries `fontSize`, `fontWeight` and `lineHeight` \u2014 asking for a heading gets you the whole heading, not heading size at body weight. It does NOT carry `letterSpacing` or `fontFamily`. Those two exist only as per-component fields on `UPDATE_COMPONENT_STYLE`, so if you never send them, every text in the app is at the default tracking in the default face. That default is exactly what \"looks like a wireframe\" means, and it is two extra fields to fix.\n\n### Typography Carries Most Of The Impression\nThe type is the largest coloured area on almost every screen, so it decides the character of the page before any accent does.\n- Typeface is a real choice, but the platform's faces are a fixed set and nothing validates what you send against it: `fontFamily` on `UPDATE_COMPONENT_STYLE` takes any string and stores it verbatim, so a face the platform does not ship is not rejected and not substituted \u2014 it is simply stored, and the client renders a fallback. You will not be told. (If the project's scale already declares families, sending one outside them returns a note and still stores it; if the scale declares none, nothing is checked at all.) So pick from the faces that exist.\n The default is DM Sans on web and pingFang SC on mobile, so leaving it alone is not neutral \u2014 it is the same face every other project ships with. Nine faces exist on EVERY client: pingFang SC, HarmonyOS Sans, microsoft yahei, stheiti, simsun, helvetica neue, tahoma, Montserrat, Smiley Sans. A WEB app has twenty-seven more, and they are worth picking by job rather than off a flat list:\n - CJK body: Noto Sans SC, SiYuan HeiTi, Mi Sans, OPPO Sans, Alibaba PuHuiTi.\n - CJK serif: SiYuan SongTi, Swei Spring SongTi \u2014 simsun is the system default and reads dated.\n - CJK rounded, for a friendlier brief: Resource Han Rounded, SiYuan RouHeiTi.\n - CJK display, headline only and never body: Alimama ShuHeiTi, ZhanKu WenYiTI, Tsanger YuYangTi, ZCOOL GDH, ZCOOL Kuhei, Youshe Header Heiti, Pangmenzhengdao Header, Pangmenzhengdao Light, Wendaochao Heiti.\n - Latin workhorses: DM Sans, Plus Jakarta Sans, Inter, Roboto, open sans, plus the system face -apple-system.\n - Montserrat is a geometric display voice, D-DIN-PRO a technical one, Yellowtail a script for a single display line and nothing else, and Vonwaon Bitmap a pixel face for a deliberately informal brief.\n If the copy is Chinese, the BODY face has to be a CJK one, not just the headline: a Latin family carries no Chinese glyphs at all, so every Chinese character falls back to whatever the device has and the page you designed is not the page that renders.\n One family is a complete answer; two only when clearly distinct in role (a display face and a text face), never two sans faces that differ slightly. `GET_STYLE_SCALE` reports which ones this project already committed to \u2014 follow those rather than introducing a third.\n- Hierarchy comes from weight and space as much as from size. Three text roles that differ only in `fontSize` read as one undifferentiated block; a heading at 600\u2013700 against body at 400 separates at a glance even when the sizes are close.\n- `letterSpacing` is in PIXELS, not em, and goes NEGATIVE on large display type \u2014 roughly -0.5px at a 28\u201332px page title, -1px or beyond as the size grows \u2014 because a face designed at body size is too loose when set large. Body text wants 0. A fractional value like -0.02 changes nothing visible, so sending one and then reporting the tracking as tightened is a false claim. It goes slightly POSITIVE only on small uppercase labels, which are themselves worth avoiding (see below).\n- Set `maxWidth` on any TEXT holding a paragraph. Unbounded body text stretches to the container and a 1200px-wide line is unreadable regardless of how well it is styled; hold it near 60\u201370 characters, which at body size is roughly 600\u2013680px. A capped column keeps hugging the left edge until its PARENT centres it \u2014 in a column parent (a PAGE's default) that is `alignItems: 'center'`. This is the most-skipped and most-visible typographic fix in a wide desktop layout.\n- Body text needs `textWrap: true` \u2014 false pins it to one line and ellipsises it at the box edge however wide the sentence is. `lineClamp` on top when it must stop after N lines.\n\n### Depth Is One Decision, Applied Once\n`shadow` takes `{ offsetX, offsetY, blur, spread, color, inset }`, so it can do far more than a default drop shadow, and the failure mode is using it everywhere rather than using it well.\n- A card lifts off the page with EITHER a hairline border OR a soft shadow, not both. Pick one for the whole app.\n- A real shadow is large, soft and nearly transparent, and offset downward only \u2014 light comes from above. A tight dark shadow at every corner is the tell that nothing was decided; `blur` well above `offsetY`, and a colour at low alpha, is what reads as expensive.\n- Elevation is a scale like everything else: at most two levels \u2014 resting surface, and the raised thing (modal, dropdown, the one hero card). A third level means the second is not doing its job.\n- `inset: true` is for the pressed state of a button and for a well an input sits in. It is the only correct way to make something look recessed rather than raised.\n- `backdropBlur` belongs on overlay chrome that sits over content \u2014 a sticky header, a modal scrim. On an ordinary card it costs paint and buys nothing, since there is nothing behind it to blur.\n- `borderRadiusCorners` exists for the cases a single radius cannot express: a segmented control, a sheet rounded only at the top, a cell at the end of a row. Reach for it there and nowhere else.\n- Radius is hierarchy. If the card, the input, the badge and the button all carry the same value, the screen has told the user nothing about what is what.\n\n### Space Is The Cheapest Thing That Reads As Finished\nThe common failure is far too little of it, and it is not a matter of taste \u2014 the numbers are knowable. On desktop, section padding starts at 64px vertical and goes up, not down; card padding at 20\u201324px; the page gutter at least two spacing steps above the in-card gap, so a card reads as sitting on the page rather than pasted onto it. When a screen feels cramped, the fix is almost always more space AROUND the groups, not less space inside them. Proximity is the actual signal: things that belong together sit closer to each other than to anything else, and if a label is equidistant from its own field and the next one, the layout has lost the reader regardless of how the label is styled.\n\n### The Look That Reads As Generated\nNone of these is forbidden \u2014 each is right for some brief \u2014 but they are what gets reached for when nothing has been decided, so they appear regardless of subject. Where the user asked for one, give it to them. Where they left the axis free, spend the freedom elsewhere:\n- Cream page (near #F4F1EA) with a high-contrast serif display and a terracotta/clay accent (near #D97757).\n- Near-black page with one acid-green or vermilion accent.\n- Every surface on the same radius under the same soft grey shadow, whatever its role.\n- A tracked-out ALL-CAPS eyebrow label above every heading.\n- Meta strings joined with middle dots ('A \xB7 B \xB7 C'); '\u2192' appended to button text.\n- One word in a heading coloured or bolded to add interest.\n- Numbered markers (01 / 02 / 03) on content that is not actually a sequence.\n- A gradient used as decoration on a surface that has no reason to be gradient. A gradient is legitimate as the subject of a hero, or to keep text legible over an image; as a wash behind ordinary cards it is the clearest single tell.\n\n### Every Interactive Thing Answers The Cursor\n`UPDATE_COMPONENT_STYLE` takes `variant: 'hover'`, and a build that never sends it is a build where nothing on screen responds to the mouse. That, more than any colour choice, is what makes a page feel like a mockup rather than an application. Give every BUTTON, every clickable card and every list row a hover state \u2014 a surface a step lighter or darker is enough, and it costs one extra call per component type, not per component, because you are styling the same few shapes. Set `cursor: 'pointer'` on anything clickable that is not a BUTTON: a LAYOUT_VIEW with an ON_CLICK handler still shows an arrow cursor, so the user has no way to know it is a target. Where a SELECT_VIEW or a TAB_VIEW has a selected state, style it. The default selected state is not a design decision, and \"the active tab looks like the inactive ones\" is a bug the user will report in different words.\n\n### Three Things Can Be Conditional \u2014 Pick The Smallest One\nWhen a screen has two modes, do NOT reach for a conditional container first. Ask what actually differs between the modes, and make only that conditional:\n- Conditional DATA (`CREATE_CONDITIONAL_BINDING`) when only VALUES differ \u2014 a label, a title, a placeholder, a colour. One component, one conditional binding whose branches are keyed off the deciding value. This is the default answer.\n- Conditional ACTION when only BEHAVIOR differs \u2014 one button that submits, signs in or signs up depending on the mode. One button, one handler that branches.\n- Conditional VIEW (CONDITIONAL_VIEW) only when the STRUCTURE differs \u2014 different fields, different counts of children. Branches do NOT share children, so anything you put in a branch is duplicated in every other branch. If the two modes share a form, keep the shared form OUTSIDE the CONDITIONAL_VIEW and put only the differing part inside it.\nA \"switchable signup / login\" is therefore conditional data plus a conditional action over ONE shared form \u2014 not two branches each holding a copy of the same fields. Wrapping shared UI in branches is the classic wrong answer: it looks right and silently doubles the tree.\nTAB_VIEW is a different question entirely: use it only when the tab strip itself is the affordance the user should see and click. It renders tab chrome you cannot remove.\nBoth TAB_VIEW and CONDITIONAL_VIEW take `preserveStateOnSwitch`, and it is the same mechanism in both: true keeps every case alive, so a scrolled list, a half-filled input or a loaded query survives switching away and back; false tears the inactive case down and rebuilds it from scratch. Both are created with it ON. Turn it off only when stale state would be wrong (a form that must reset), and remember the cost: every case stays mounted.\n\n### Who Owns A CONDITIONAL_VIEW's Active Branch\nBranch conditions and SWITCH_VIEW_CASE write the SAME runtime slot, so exactly one of them owns a given container \u2014 never both. A tool call that mixes them is rejected.\n- Conditions own it (the default). The mode is app state: a page variable, a query result, a login state. Narrow each branch's condition at the conditionSchemaPath `ADD_COMPONENT` / `ADD_CONDITIONAL_VIEW_BRANCHES` echoes, and change the mode with SET_VARIABLE_DATA. Only this way does the right branch show on first render, react to data, and stay readable by everything else \u2014 a title, a colour, a query filter can all condition on the same variable.\n- SWITCH_VIEW_CASE owns it only when the selection is purely visual, nothing outside the container will ever need to know which branch is active, and the first branch is the correct starting view \u2014 a carousel or an accordion. It never runs on page load and stores the choice where nothing can read it.\nLeft alone, branch conditions are always-true and the FIRST branch always shows. That is the state right after creation, so narrow them or switch to SWITCH_VIEW_CASE deliberately.\n\n### Slots of Special Components\nSlot children are mutated only with the slot tools:\n- TAB_VIEW tabs: `ADD_TAB_VIEW_TABS` creates each tab's content container (a LAYOUT_VIEW child) plus its tabList entry, echoing the content child's id and the tab title binding's schemaPath. Tabs are addressed by their content-child id everywhere: `DELETE_TAB_VIEW_TABS` (a TAB_VIEW keeps at least 2 tabs) and `REORDER_TAB_VIEW_TABS` (pass a full permutation).\n- CONDITIONAL_VIEW branches: `ADD_CONDITIONAL_VIEW_BRANCHES` inserts always-true branches \u2014 narrow each one with the bindings plugin's condition tools at the echoed conditionSchemaPath. Branch order IS evaluation order (first matching condition wins): `REORDER_CONDITIONAL_VIEW_BRANCHES`. The default case cannot be deleted (`DELETE_CONDITIONAL_VIEW_BRANCHES` takes non-default branches only) and always stays last.\n- Optional slots: `SET_COMPONENT_SLOT` fills an empty LIST 'header'/'footer' or MAP 'marker' slot with a freshly created default child; `CLEAR_COMPONENT_SLOT` empties it again, deleting the subtree. Required slots (LIST 'cell', SELECT_VIEW states) are fixed at creation \u2014 to change one, recreate the component.\n- SHEET columns: a SHEET does not take its data through a binding. `SET_SHEET_DATA_SOURCE` builds its embedded query from a table \u2014 call it immediately after creating the SHEET, because one without a data source is invalid \u2014 then add the displayed columns with `ADD_SHEET_COLUMNS`, managing them by data-field name with `DELETE_SHEET_COLUMNS` / `REORDER_SHEET_COLUMNS`. Filters and sorts go on the echoed querySchemaPath with the request tools.\n\n### Components That Display a Field of Their Data\nDATA_SELECTOR, SELECT_VIEW and LIST name one field of their data source: `displayDataField` (the value the user sees) and `cellKeyDataField` (the row identity). Binding the dataSource is not enough \u2014 a DATA_SELECTOR or SELECT_VIEW whose data source resolves to a list of objects is invalid until its displayDataField is set. Set it with `UPDATE_COMPONENT_PROPERTIES`, passing the field's plain NAME as a string; the full field reference is resolved for you, so never hand-assemble one. The candidates appear as selectableDataFields in `GET_COMPONENT_INFO` once the dataSource is bound \u2014 so the order is always: create \u2192 bind dataSource \u2192 read the component \u2192 name the field.\n\n### Page Data: Queries, Variables & Inputs\nPages have NO separate query list \u2014 a page query IS a read-only page variable whose dataSource is a database query. It is for data more than one component reads, or a filter the page owns centrally; a single list showing one filtered table binds that table itself (see Data Bindings below) and needs nothing here:\n- `ADD_COMPONENT_QUERY` attaches a table query to a PAGE or MODAL (limit 1 = single row, >1 = list). Components consume it through data bindings (bindings plugin) at the echoed dataSourceSchemaPath; narrow filters and sorting with the request-filter tools at that same path. The result also reports rolesWithoutSelect \u2014 grant SELECT with the permission plugin's table-permission tool; never assume it is granted automatically. Tune with `UPDATE_COMPONENT_QUERY`; remove queries and variables alike with `DELETE_COMPONENT_VARIABLES`.\n- Page-local mutable state: `ADD_COMPONENT_VARIABLES`, with each typeIdentifier picked from `GET_COMPONENT_VARIABLE_SELECTABLE_TYPES` \u2014 never hand-assembled. A new variable starts with no value, so give it an initial one at the `defaultValueSchemaPath` the result echoes whenever anything reads it: conditional cases, branch conditions and SET_VARIABLE_DATA values all test the variable against specific values, and none of them match an empty variable. The page then loads with every dependent case unmatched \u2014 blank labels, the fallback branch showing \u2014 and a toggle whose new value is itself conditional on the old one cannot recover, because it has nothing to match either.\n- Page parameters: `ADD_COMPONENT_INPUTS` / `UPDATE_COMPONENT_INPUT` / `DELETE_COMPONENT_INPUTS`. WEB pages take URL query/path params; WECHAT/MOBILE pages and MODALs take general inputs. Navigation and show-modal call sites pass one value per input.\n- `SET_INITIAL_PAGE_ID` sets the app's home page for the current client.\n\n### Client Variables\nThe current client's app-wide variables: every page reads and sets them, and each client (WEB / mini program / mobile) keeps its own table, so a value set on one is not the other's. State that has to survive navigation belongs here rather than in a page variable.\n- Read them with `GET_CLIENT_VARIABLES_INFO`; declare with `ADD_CLIENT_VARIABLES`, each typeIdentifier picked from `GET_CLIENT_VARIABLE_SELECTABLE_TYPES`; rename or retype with `UPDATE_CLIENT_VARIABLES`; remove with `DELETE_CLIENT_VARIABLES`.\n- A new variable starts with no value: fill it at the `defaultValueSchemaPath` the add echoes with the bindings plugin. That value is a literal \u2014 no variable, formula or expression may stand in for it.\n- A variable declared inside one action flow is that flow's own, not one of these.\n- Deleting one does not clean the bindings and set-client-variable actions that name it; the result's danglingReferences lists them, so repoint or remove them in the same turn.\n\n### Data Bindings on Components\n`GET_COMPONENT_BINDABLE_PROPERTIES` lists every place a component can be bound \u2014 always start there and copy the paths verbatim, never hand-assemble a binding path. It returns two sections: `properties`, the component's own slots, each with its ready-to-use schemaPath, expected type, current binding and scope; and `actionSlots`, the parameter slots of the actions already wired to its events, chained success/failure branches included. `ADD_COMPONENT_ACTIONS` echoes an action's slots when it creates it \u2014 bind them in the same turn when you can, and use `actionSlots` to find them again in any later turn. Fill the echoed paths with the bindings plugin's tools: `BROWSE_DATA_BINDING_OPTIONS` + `CREATE_OPTION_BINDING` for dataSource slots and other dynamic values, `CREATE_CONST_BINDING` for literals. A LIST, SELECT_VIEW or DATA_SELECTOR can take its dataSource either way, and the options tree offers both in one answer: the tables under 'Table', and any page query under 'Context > Current page > Data source'. **Prefer the table** \u2014 a component that owns its data source is filtered, sorted and retyped in one place, and `GET_REQUEST_FILTER_CONTEXT` narrows it at the component's own path. Reach for a page query (`ADD_COMPONENT_QUERY` first) only when the SAME result set is genuinely shared \u2014 two components reading one query, or a filter the page tunes centrally. One component, one filtered list is not a sharing case: adding a page variable there buys nothing and leaves a second thing to keep in step. Inside a list cell (scope \"list-cell:<listId>\") the options tree additionally offers the current list item's fields under 'item-data' \u2014 bind cell children to those instead of re-querying the table.\n\n### Editing Protocol\n- Read-before-edit: editing a component (or inserting into a container) you have not read fails with \"has not been read\" \u2014 read it first; after a conflict, re-read and retry. One read of a container covers both adding children to it and editing its own configuration, so `GET_COMPONENT_INFO` and `GET_CONTAINER_CHILDREN_INFO` on the same component is one call wasted.\n- Everything you call in a single turn applies as one atomic batch: if any call in it fails, none of them landed, so fix the offending call and resend the whole group. Calls in *different* turns are independent \u2014 a failure there leaves earlier turns' work in place.\n- Prefer one turn over many. Independent reads should always go together, and a read may sit in the same turn as an edit that depends on it. The one thing you cannot do is use an id or schema path echoed by a call in the same turn \u2014 those are only visible once the turn returns, so anything consuming them belongs in the next turn.\n- Wiring behavior is always the same three steps: `GET_COMPONENT_SELECTABLE_EVENTS` for the events this component exposes, `GET_SELECTABLE_COMPONENT_ACTIONS` for the actions that event accepts here, then `ADD_COMPONENT_ACTIONS` to attach one. Never guess a kind \u2014 the selectable list is already filtered to this client's platform and the project's configuration, so anything absent from it cannot be attached and must be built in the editor instead. Remove any handler with `DELETE_COMPONENT_EVENT_HANDLERS`.\n- Every action seeds its parameters as empty bindings and echoes them in bindableSchemaPaths; fill them with the bindings plugin's tools. Anything a specific kind returns beyond that arrives under that handler's `details`.\n- Pick the kind from `GET_SELECTABLE_COMPONENT_ACTIONS` and take its parameter shape from this tool's parameter schema, which is the only complete list of the kinds and their fields \u2014 the editor offers far more than the handful named below, including SHOW_TOAST, OPEN_EXTERNAL_LINK, SET_CLIPBOARD, DOWNLOAD_FILE, CALL_PHONE, the payment kinds and the animation kinds. Do not conclude an interaction is impossible because it is not discussed here; the selectable list and the schema decide that. What follows is only the judgment the schema cannot carry.\n- ALERT_DIALOG is the runtime's own confirm box \u2014 a title, a message and two buttons it draws itself, with no MODAL to build or lay out. Use it for \"are you sure?\"; use SHOW_MODAL when the dialog needs your own components in it. Chain what confirming does onto ALERT_DIALOG's ON_CONFIRM branch, or the buttons do nothing.\n- Building a MODAL does not make it reachable. Without a SHOW_MODAL action pointing at it, nothing opens it, and the modal you just laid out is dead UI the user cannot reach.\n- An action that produces a RESULT \u2014 GET_LOCATION, UPLOAD_FILE, GENERATE_QR_CODE and the other result-bearing kinds \u2014 can only keep it through assignToVariable, a writable page variable created with `ADD_COMPONENT_VARIABLES` on the page the component sits on. Their success branches cannot see the result, so an action without assignToVariable runs and throws its answer away. Create the variable first.\n- SIGN_UP and USER_LOGIN are separate actions, and the password slot on a SIGN_UP decides what the account can sign in with later: leave it unbound and the account has no password, so a USER_LOGIN with credentialType PASSWORD can never succeed for anyone who signed up there. Build the pair together, or sign in with VERIFICATION_CODE.\n- A WeChat mini-program signs its user in by itself. The client is created with a silent WeChat login in its own app-did-load configuration, which the editor will not let anyone delete, so whoever opens the app is already signed in, and the account is created there too. Do NOT build a sign-in or sign-up screen there and do NOT wire a login action: USER_LOGIN offers no WeChat mode at all, the silent login belongs to that configuration alone, and SIGN_IN / SIGN_UP / SIGN_OUT are absent from the mini-program's selectable actions. When the app needs the user's phone number, use OBTAIN_PHONE_NUMBER.\n- MUTATION writes the database without an action flow. rolesWithoutPermission in its result is report-only \u2014 grant the table permission with the permission plugin or the write is denied at runtime, which looks like a silent no-op to the user. rowScope CURRENT_ITEM is valid only inside a LIST cell; refreshOnSuccess is preferable to a separate REFRESH.\n- SCHEDULED_JOB_CONTROL starts or pauses a page timer; the timer itself is built with `ADD_COMPONENT_SCHEDULED_JOBS` and renamed, rescheduled or removed with `UPDATE_COMPONENT_SCHEDULED_JOB` / `DELETE_COMPONENT_SCHEDULED_JOBS`. A job is a schedule and nothing else \u2014 until it has actions it fires on its interval and does nothing \u2014 and every one of those calls takes the PAGE or MODAL itself rather than a component inside it. Its actions come from `ADD_COMPONENT_ACTIONS` and `DELETE_COMPONENT_EVENT_HANDLERS` carrying its scheduledJobId; its interval is in milliseconds.\n- CONDITIONAL is how ONE event does different things in different cases: branches in evaluation order, first match wins, each branch narrowed at the echoed conditionSchemaPath and filled by a further `ADD_COMPONENT_ACTIONS` carrying that branch's conditionalBranchId. Leave the last branch always-true as the else. Without it every action on the event fires on every click \u2014 ON_SUCCESS / ON_FAILURE branch on whether a call worked, never on a data condition. Do NOT reach for an action flow to get branching: a flow's BRANCH node runs on the server and cannot navigate, toast or open a modal, so frontend branching belongs here. This decides what HAPPENS; a CONDITIONAL_VIEW decides what is DISPLAYED.\n- There is no per-component conditional visibility \u2014 an ordinary component has no data-driven show/hide flag. To make content appear only when a condition holds, wrap it in a CONDITIONAL_VIEW container and gate the branch with the bindings plugin's condition tools (see CONDITIONAL_VIEW branches under \"Slots of Special Components\").\n\n### Motion Is One Moment, Not A Coat Of Paint\nZion has animation as ACTIONS, not style fields, so they are attached with `ADD_COMPONENT_ACTIONS` like any other handler: ANIMATION_FADE_EFFECT and ANIMATION_SLIDE_EFFECT (APPEAR / DISAPPEAR, eight directions, a distance defaulting to 150px), ANIMATION_SCALE_EFFECT, ANIMATION_COMMON_EMPHASIS (BOUNCE / PULSE / BLINK), ANIMATION_FLIP_EMPHASIS, and ANIMATION_SCROLLING_INTERACTION. Each takes delay, and the emphasis kinds take repeat or loop.\nThe rules are hard ones, and breaking them shows up as a project error rather than a subtle defect: exactly ONE animation per event, and only on onClick, onHover or onScrollIntoPage \u2014 the runtime reads the last effect it finds on the event and ignores any attached elsewhere. ANIMATION_SCROLLING_INTERACTION is the exception and goes ONLY on onPageScroll, which carries nothing else at all, because the curve is driven by scroll distance. None of them take attachTo and none take bindings, so they cannot be chained onto a success branch.\nSpend motion the way you spend the accent. Movement that answers what a person just did \u2014 a press, an open, a confirm \u2014 is worth it, because it shows what changed. Movement that merely announces that content exists is the generated-page tell: a fade-and-slide on every section as it scrolls into view reads as a template, and it reads that way precisely because it is the first thing reached for. One orchestrated moment on the screen that matters beats an effect on every card, and a screen with no animation at all is a perfectly good answer \u2014 far better than one where everything twitches. The emphasis kinds earn their place on something genuinely needing attention, never as decoration, and BLINK almost never earns it.\n\n### Reviewing The Screen You Built\nMake ALL edits first, then run `schema validate` and resolve anything your changes introduced. The editor's error center and canvas screenshots are not reachable from here, so you cannot confirm a result visually \u2014 ask the user to open the screen in the editor and read it against the following, then fix what they report:\n1. Is there one clear focal point, or is everything competing at the same weight?\n2. Do related things sit closer together than unrelated things?\n3. Are there at least three distinguishable levels of text, and do they differ in weight and not only in size?\n4. Does anything touch an edge that should have gutter, or run to a line length past ~70 characters?\n5. Does the accent appear only on the primary action and the active state, or has it leaked onto headings and borders?\n6. Does anything on the screen respond to hover?\nName what you are fixing and fix it. A screen that passes `schema validate` and fails all six is not done \u2014 validation only knows about invalid schema, and none of the above is invalid. Report only what you actually changed. Every claim about appearance \u2014 a heading looks larger, a selected state looks different, spacing was tightened \u2014 must correspond to an `UPDATE_COMPONENT_STYLE` (or creation-time style) call you made in this session. If a requested look was not achievable with the available tools, say which part you skipped and why; do not describe the component's built-in default styling as if you had applied it. A user who is told the work is done stops checking."}},database:{pre:{available:!0,prompt:`## Database Domain Knowledge
|
|
430
|
+
Zion uses PostgreSQL. Data model changes require "Sync Backend" to take effect online.
|
|
431
|
+
|
|
432
|
+
### Capabilities & Limitations
|
|
433
|
+
You can: create and delete tables, fields, relations, and unique constraints; change a table's displayName / description; change a field's displayName.
|
|
434
|
+
Tables and fields are addressed by their displayName in every tool on this plugin.
|
|
435
|
+
|
|
436
|
+
You CANNOT:
|
|
437
|
+
- Rename a table or a field. An apiName is fixed when the entity is created \u2014 only its displayName can change afterwards. If an apiName is genuinely wrong, delete and recreate it; recreating a field discards the data already stored in it. Choose apiNames carefully up front.
|
|
438
|
+
- Change an existing column's TYPE, or its uniqueness. To change either, delete the column and create a new one; uniqueness cannot be added later because existing rows may already hold duplicates.
|
|
439
|
+
- Update an existing relation or constraint. To change one, delete it and recreate it.
|
|
440
|
+
- Create a formula (computed) field. The data model here has none, so never send 'computed' on a field.
|
|
441
|
+
|
|
442
|
+
### Every table edit rewrites role permissions
|
|
443
|
+
Creating or deleting a table, and adding, retyping or deleting a field, rewrites the role permissions keyed to that table. Nobody asks for it, and a new table lands in every role including Anonymous User, so the grants you end up with are not the ones you chose. Each of those results names the roles it changed. Before changing one of them, read that role with GET_ROLE_DETAIL: a permission write is rejected until the role has been read in this session, and the role you would reach for is one your own table edit just moved.
|
|
444
|
+
|
|
445
|
+
### Column Types
|
|
446
|
+
A new field's 'typeIdentifier' is a bare primitive type NAME: string, decimal, bigint, boolean, timestamptz, timetz, date, jsonb, image, video, file, geo_point, timezone. Those are exactly the options GET_TABLE_FIELD_SELECTABLE_TYPES offers on this
|
|
447
|
+
project; it prints them uppercase and either case is accepted.
|
|
448
|
+
|
|
449
|
+
Pass the name on its own (for example "decimal"). Read results report a field's existing
|
|
450
|
+
type using legacy uppercase names (TEXT, BIGINT); that is the read vocabulary only \u2014 when
|
|
451
|
+
creating a field, still pass the primitive name (a column shown as TEXT is created with
|
|
452
|
+
"string"). This project has no enums, so an enum id is never a valid field type here. The
|
|
453
|
+
separate 'required' field controls nullability; never wrap a type in a null union.
|
|
454
|
+
|
|
455
|
+
### Naming
|
|
456
|
+
apiName \u2014 spelled 'tableApiName' on a table, 'apiName' on a field, 'fieldApiNameInSourceTable' / 'fieldApiNameInTargetTable' on the two sides of a relation, and reported under those names by every read: English snake_case. Tables are nouns or noun phrases, singular not plural ("order", not "orders"), concise (e.g. "user_profile"); fields are snake_case (e.g. "first_name", "is_active"). No name may contain a space \u2014 not tables, fields, relations, or constraints, and not even the displayName. An apiName is permanent once created; only the displayName can be changed later. displayName: user-visible; use the natural Chinese name as the displayName and derive the English snake_case apiName from it (e.g. displayName "\u7528\u6237\u540D" \u2192 apiName "user_name").
|
|
457
|
+
|
|
458
|
+
### System Built-ins & Product Context
|
|
459
|
+
Every table has non-deletable built-in fields: id (BIGINT), created_at (TIMESTAMPTZ), updated_at (TIMESTAMPTZ). Do NOT include these when creating a table. Any table, field, or relation where 'editable' is false is system built-in and cannot be modified or deleted. System tables and timezone configurations for Zion:
|
|
460
|
+
* UTC Offset: +08:00
|
|
461
|
+
* Protected Account Table: '\u5E10\u6237(\u8D26\u6237)' (can add/delete user-defined fields, but cannot delete table itself)
|
|
462
|
+
* Protected Payment Tables: '\u652F\u4ED8', '\u5468\u671F\u6027\u652F\u4ED8', '\u9000\u6B3E' (cannot be modified or deleted)
|
|
463
|
+
* Protected AI/Session Tables: '\u4F1A\u8BDD', '\u6D88\u606F', '\u5DE5\u5177\u4F7F\u7528\u8BB0\u5F55', '\u6D88\u606F\u5185\u5BB9' (cannot be modified or deleted) The system built-in AI tables are strictly for system AI functions. For user chat systems, always create custom user-defined tables (e.g. 'user_chat', 'chat_message').
|
|
464
|
+
|
|
465
|
+
### Required Fields
|
|
466
|
+
Fields on this project CANNOT carry a default value \u2014 the data model here predates the type system that has them. Never send 'defaultValue' or 'clearDefaultValue' to any tool on this plugin: the call is rejected whole, and on ADD_TABLES that discards every table in it.
|
|
467
|
+
|
|
468
|
+
That leaves 'required' as the one to place carefully, since a mandatory column needs something to put in the rows a table already holds:
|
|
469
|
+
- 'required = true' is free on the fields you declare inside ADD_TABLES itself \u2014 that table is created empty, so there are no rows to satisfy.
|
|
470
|
+
- A field added with ADD_FIELDS_AND_RELATIONS must be 'required = false', even on a table you created earlier in this conversation: only ADD_TABLES can tell that the table holds no rows, so declare the mandatory fields there. An existing field's 'required' cannot be changed at all here \u2014 it is fixed when the field is created, and deleting and re-creating the field does not get around it. When a value really has to be mandatory, enforce it where it is written \u2014 validate it in the action flow doing the insert \u2014 rather than in the column.
|
|
471
|
+
|
|
472
|
+
### Relations
|
|
473
|
+
Types: one_to_one, one_to_many. Defined on the source table.
|
|
474
|
+
To make one table reference another, create a RELATION \u2014 never add a manual foreign-key column (e.g. a "*_id" field) or a column whose type is another table. The FK column and the virtual reference fields are generated automatically. Add the relation on the SOURCE table only; it is reflected on the target automatically.
|
|
475
|
+
A relation is configured by seven required fields: relationType, sourceTableDisplayName, targetTableDisplayName, and both a display name and an apiName for the field it adds to each side \u2014 fieldDisplayNameInSourceTable / fieldApiNameInSourceTable and fieldDisplayNameInTargetTable / fieldApiNameInTargetTable. Reads report those seven plus 'editable'. Each of those four names a field that does not exist yet, so each must be unique among its own table's fields, relations on that table included: reusing a column name ("id"), the table's own name, or another relation's field name on that table is rejected.
|
|
476
|
+
Creating a relation auto-generates:
|
|
477
|
+
- A non-editable FK field in the target table, its display name fieldDisplayNameInTargetTable + "_id" (e.g. "user_id", "\u6D3B\u52A8_id") and its apiName fieldApiNameInTargetTable + "_id". Stores the source row's id, and is unique when the relation is one_to_one. Never write that "_id" yourself: "user_id" as the target-side name produces the field "user_id_id". Deleted when the relation is deleted.
|
|
478
|
+
- Virtual reference fields in both tables (NOT real columns), one per side: fieldDisplayNameInSourceTable lives on the source; fieldDisplayNameInTargetTable lives on the target.
|
|
479
|
+
Examples:
|
|
480
|
+
- 1:n user (source) \u2192 post (target), source field "posts", target field "user"
|
|
481
|
+
\u21D2 user has virtual list "posts"; post has virtual reference "user" and FK column "user_id".
|
|
482
|
+
- 1:n post (source) \u2192 comment (target), source field "comments", target field "post"
|
|
483
|
+
\u21D2 post has virtual list "comments"; comment has virtual reference "post" and FK column "post_id".
|
|
484
|
+
- 1:1 user (source) \u2192 profile (target), source field "profile", target field "user"
|
|
485
|
+
\u21D2 user has virtual reference "profile"; profile has virtual reference "user" and FK column "user_id".
|
|
486
|
+
Relations only between editable (user-created) tables.
|
|
487
|
+
Many-to-many: use an intermediate join table + two one-to-many relations.
|
|
488
|
+
To unique-constrain a relation field, use the FK field name ("user_id"), not the virtual name.
|
|
489
|
+
|
|
490
|
+
### Geographic Location
|
|
491
|
+
Use GEO_POINT for coordinates. Never split into separate latitude/longitude fields. A GEO_POINT field auto-generates a companion DECIMAL hack field named "fz_distance_from_<apiName>", where <apiName> is the geo_point's apiName (may differ from its displayName). At request time it returns the distance from the stored geo_point to the user-supplied location in the request. Treat it as a distance-calculation hack \u2014 future migration: this will be replaced by formula fields.
|
|
492
|
+
|
|
493
|
+
### Data Views
|
|
494
|
+
A view is a saved SELECT over this project's tables, exposed as a READ-ONLY table of its own: it has a displayName like any table, it shows up in reads and data bindings, and it is queried the same way. Reach for one when the SAME joined or aggregated result is needed in more than one place \u2014 "Number of orders and total amount per user" \u2014 so the definition lives once instead of being rebuilt in every query, component and action flow that needs it.
|
|
495
|
+
|
|
496
|
+
A view is a definition, not a copy: it holds no data of its own and is recomputed on every read, so it is never stale. It costs what the query costs, every time it is read.
|
|
497
|
+
|
|
498
|
+
Write the SQL against the API (snake_case) names, quoted and case-sensitive \u2014 the same names GET_TABLES_INFO reports. Everything else on this plugin is addressed by displayName; the SQL body is the one place that is not, because it is PostgreSQL rather than a tool argument.
|
|
499
|
+
|
|
500
|
+
Always ANALYZE_VIEW_SQL first and fix what it reports before creating or updating a view. It returns the exact columns the view would expose, so it is also how you learn what a view you are about to build on actually gives you. Creating or updating a view with SQL that does not analyse is rejected, not stored.
|
|
501
|
+
|
|
502
|
+
You CANNOT:
|
|
503
|
+
- Write through a view. There is no insert, update or delete, and no by-id lookup: a view has no primary key.
|
|
504
|
+
- Use the whole of SQL. One SELECT only: JOIN with ON, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT, UNION, CTEs, CASE, COALESCE, casts and the aggregate functions. NOT available: subqueries, window functions, query parameters, and anything that is not a single SELECT statement.
|
|
505
|
+
- Parameterise a view. It is a stored definition with no request context, so there is no "current user" inside it and no placeholder to bind. Expose the user column and filter when you QUERY the view instead.
|
|
506
|
+
- Omit a column alias. Every output column needs an explicit \`AS alias\`, and that alias is the field name the view exposes.
|
|
507
|
+
- Read an IMAGE_LIST column. Every other type works, but a media column is read under its database name \u2014 an IMAGE/VIDEO/FILE field called "avatar" is \`avatar_id\` in the SQL, and aliasing it \`AS cover_id\` exposes it as a media field named "cover". Keep the \`_id\` suffix or it comes back as a plain number.
|
|
508
|
+
- Delete a view another view still reads. Delete or rewrite the reader first.
|
|
509
|
+
|
|
510
|
+
Views take effect online only after "Sync Backend", like every other data-model change.
|
|
511
|
+
|
|
512
|
+
### Constraints
|
|
513
|
+
Only unique constraints supported. Constraint name: lowercase English snake_case, no uppercase. Reference fields by their displayName \u2014 for a relation's foreign key use the generated FK field ("user_id"). Uniqueness is fixed when a field is created and cannot be turned on afterwards (existing rows could already hold duplicates), so to make an existing field unique, add a constraint over it. Use a constraint to span multiple fields (composite unique): list the fields' displayNames. Unique constraints are also the only DB-enforced invariant writers can lean on for atomic insert-if-absent / toggle semantics (insert with on_conflict): whenever the design has "at most one row per X" semantics (a join/like/save table, an idempotency key), create the unique constraint up front \u2014 read-check-then-insert cannot be made race-safe without it.
|
|
514
|
+
|
|
515
|
+
A relation's generated FK carries two names, and which one a call wants depends on the call. The schema tools here take displayNames, so a relation named \u8F6C\u8BD1\u884C gives a FK whose displayName is \`\u8F6C\u8BD1\u884C_id\` \u2014 that is what ADD_CONSTRAINTS matches on. The runtime API takes apiNames, so the same column is \`translation_row_id\` in a \`runtime.query\` filter or a \`runtime.insert\` object. Neither side accepts the other's name, and passing the wrong one reports the field as missing rather than as misnamed. Read both off the field record instead of transliterating one into the other.`},post:{available:!0,prompt:`## Database Domain Knowledge
|
|
516
|
+
Zion uses PostgreSQL. Data model changes require "Sync Backend" to take effect online.
|
|
517
|
+
|
|
518
|
+
### Capabilities & Limitations
|
|
519
|
+
You can: create and delete tables, fields, relations, and unique constraints; change a table's displayName / description; change a field's displayName / required / default value; create formula (computed) fields.
|
|
520
|
+
Tables and fields are addressed by their displayName in every tool on this plugin.
|
|
521
|
+
(Enums are created and edited via the 'type' plugin.)
|
|
522
|
+
You CANNOT:
|
|
523
|
+
- Rename a table or a field. An apiName is fixed when the entity is created \u2014 only its displayName can change afterwards. If an apiName is genuinely wrong, delete and recreate it; recreating a field discards the data already stored in it. Choose apiNames carefully up front.
|
|
524
|
+
- Change an existing column's TYPE, or its uniqueness. To change either, delete the column and create a new one; uniqueness cannot be added later because existing rows may already hold duplicates.
|
|
525
|
+
- Update an existing relation or constraint. To change one, delete it and recreate it.
|
|
526
|
+
|
|
527
|
+
### Every table edit rewrites role permissions
|
|
528
|
+
Creating or deleting a table, and adding, retyping or deleting a field, rewrites the role permissions keyed to that table. Nobody asks for it, and a new table lands in every role including Anonymous User, so the grants you end up with are not the ones you chose. Each of those results names the roles it changed. Before changing one of them, read that role with GET_ROLE_DETAIL: a permission write is rejected until the role has been read in this session, and the role you would reach for is one your own table edit just moved.
|
|
529
|
+
|
|
530
|
+
### Column Types
|
|
531
|
+
A new field's 'typeIdentifier' is copied verbatim from GET_TABLE_FIELD_SELECTABLE_TYPES, which lists every type a field on this project accepts. Its vocabulary is the wrapped identifier: s:p:string, s:p:decimal, s:p:bigint, s:p:boolean, s:p:timestamptz, s:p:timetz, s:p:date, s:p:jsonb, s:p:image, s:p:video, s:p:file, s:p:geo_point, s:p:timezone for the primitives, and "u:e:<enumId>" for an enum.
|
|
532
|
+
|
|
533
|
+
Never assemble one by hand, and never pass a bare name or a bare enum id \u2014 "decimal" and
|
|
534
|
+
"mja44si4" are not field types here; "s:p:decimal" and "u:e:mja44si4" are. An enum the
|
|
535
|
+
picker does not list does not exist yet: create it with the 'type' plugin (same turn,
|
|
536
|
+
before the column), then call GET_TABLE_FIELD_SELECTABLE_TYPES again and copy what it returns. The
|
|
537
|
+
separate 'required' field controls nullability; never wrap a type in a null union.
|
|
538
|
+
|
|
539
|
+
Read results report a field's existing type using legacy uppercase names (TEXT, BIGINT).
|
|
540
|
+
That is the read vocabulary only \u2014 when creating a field, still pass the picker's
|
|
541
|
+
identifier (e.g. a column shown as TEXT is created with "s:p:string").
|
|
542
|
+
|
|
543
|
+
### Formula (Computed) Fields
|
|
544
|
+
A computed field's value is derived from the row's other fields every time it is read, so it never goes stale. Create one by passing \`computed: true\` on the field \u2014 it takes no default, cannot be required, and cannot be an image / video / file / JSON type. The field is created with an EMPTY formula, which is a project error until you fill it, so finish it in the same turn:
|
|
545
|
+
1. Take the field's \`formulaSchemaPath\` from the create result (GET_TABLES_INFO reports it for fields created earlier, under \`formulaFields\`).
|
|
546
|
+
2. Load the 'bindings' plugin and build the formula at that path \u2014 \`bindings.get_formula_operators\` then \`bindings.create_formula_binding\`, filling each operand at the paths that result echoes.
|
|
547
|
+
|
|
548
|
+
Never fake a computed field with a plain column written at insert time: it goes stale the moment any input changes. Reach for a write-time value only when the user wants the number frozen as of the write.
|
|
549
|
+
|
|
550
|
+
### Naming
|
|
551
|
+
apiName \u2014 spelled 'tableApiName' on a table, 'apiName' on a field, 'fieldApiNameInSourceTable' / 'fieldApiNameInTargetTable' on the two sides of a relation, and reported under those names by every read: English snake_case. Tables are nouns or noun phrases, singular not plural ("order", not "orders"), concise (e.g. "user_profile"); fields are snake_case (e.g. "first_name", "is_active"). No name may contain a space \u2014 not tables, fields, relations, or constraints, and not even the displayName. An apiName is permanent once created; only the displayName can be changed later. displayName: user-visible; use the natural Chinese name as the displayName and derive the English snake_case apiName from it (e.g. displayName "\u7528\u6237\u540D" \u2192 apiName "user_name").
|
|
552
|
+
|
|
553
|
+
### System Built-ins & Product Context
|
|
554
|
+
Every table has non-deletable built-in fields: id (s:p:bigint), created_at (s:p:timestamptz), updated_at (s:p:timestamptz). Do NOT include these when creating a table. Any table, field, or relation where 'editable' is false is system built-in and cannot be modified or deleted. System tables and timezone configurations for Zion:
|
|
555
|
+
* UTC Offset: +08:00
|
|
556
|
+
* Protected Account Table: '\u5E10\u6237(\u8D26\u6237)' (can add/delete user-defined fields, but cannot delete table itself)
|
|
557
|
+
* Protected Payment Tables: '\u652F\u4ED8', '\u5468\u671F\u6027\u652F\u4ED8', '\u9000\u6B3E' (cannot be modified or deleted)
|
|
558
|
+
* Protected AI/Session Tables: '\u4F1A\u8BDD', '\u6D88\u606F', '\u5DE5\u5177\u4F7F\u7528\u8BB0\u5F55', '\u6D88\u606F\u5185\u5BB9' (cannot be modified or deleted) The system built-in AI tables are strictly for system AI functions. For user chat systems, always create custom user-defined tables (e.g. 'user_chat', 'chat_message').
|
|
559
|
+
|
|
560
|
+
### Required Fields & Default Values
|
|
561
|
+
A field declared inside ADD_TABLES needs no default value, whatever its 'required' setting: the table is created empty, so a mandatory column has no existing rows to satisfy. Everywhere else a 'required' field needs one \u2014 ADD_FIELDS_AND_RELATIONS adding it, or UPDATE_FIELDS_AND_RELATIONS turning 'required' on for an existing field \u2014 and both are rejected without one. This holds even for a table you created earlier in this conversation: only ADD_TABLES can tell that the table holds no rows, so declare the mandatory fields there.
|
|
562
|
+
Default value formatting:
|
|
563
|
+
- s:p:bigint, s:p:decimal, and s:p:boolean: Use literal values (e.g., 10, true).
|
|
564
|
+
- s:p:timestamptz, s:p:date, and s:p:timetz: Strictly use ISO 8601 strings (e.g., '2025-12-09T16:02:03.000Z', '2025-12-09', '16:02:03+08:00').
|
|
565
|
+
- u:e:<enumId>: Use the option's id, i.e. its FULL_CAPS_SNAKE_CASE value (e.g., 'PENDING').
|
|
566
|
+
- s:p:string: Use plain strings.
|
|
567
|
+
- s:p:jsonb: Use stringified JSON objects.
|
|
568
|
+
- Unsupported: s:p:image, s:p:video, s:p:file, and s:p:geo_point do not support default values.
|
|
569
|
+
|
|
570
|
+
### Relations
|
|
571
|
+
Types: one_to_one, one_to_many. Defined on the source table.
|
|
572
|
+
To make one table reference another, create a RELATION \u2014 never add a manual foreign-key column (e.g. a "*_id" field) or a column whose type is another table. The FK column and the virtual reference fields are generated automatically. Add the relation on the SOURCE table only; it is reflected on the target automatically.
|
|
573
|
+
A relation is configured by seven required fields: relationType, sourceTableDisplayName, targetTableDisplayName, and both a display name and an apiName for the field it adds to each side \u2014 fieldDisplayNameInSourceTable / fieldApiNameInSourceTable and fieldDisplayNameInTargetTable / fieldApiNameInTargetTable. Reads report those seven plus 'editable'. Each of those four names a field that does not exist yet, so each must be unique among its own table's fields, relations on that table included: reusing a column name ("id"), the table's own name, or another relation's field name on that table is rejected.
|
|
574
|
+
Creating a relation auto-generates:
|
|
575
|
+
- A non-editable FK field in the target table, its display name fieldDisplayNameInTargetTable + "_id" (e.g. "user_id", "\u6D3B\u52A8_id") and its apiName fieldApiNameInTargetTable + "_id". Stores the source row's id, and is unique when the relation is one_to_one. Never write that "_id" yourself: "user_id" as the target-side name produces the field "user_id_id". Deleted when the relation is deleted.
|
|
576
|
+
- Virtual reference fields in both tables (NOT real columns), one per side: fieldDisplayNameInSourceTable lives on the source; fieldDisplayNameInTargetTable lives on the target.
|
|
577
|
+
Examples:
|
|
578
|
+
- 1:n user (source) \u2192 post (target), source field "posts", target field "user"
|
|
579
|
+
\u21D2 user has virtual list "posts"; post has virtual reference "user" and FK column "user_id".
|
|
580
|
+
- 1:n post (source) \u2192 comment (target), source field "comments", target field "post"
|
|
581
|
+
\u21D2 post has virtual list "comments"; comment has virtual reference "post" and FK column "post_id".
|
|
582
|
+
- 1:1 user (source) \u2192 profile (target), source field "profile", target field "user"
|
|
583
|
+
\u21D2 user has virtual reference "profile"; profile has virtual reference "user" and FK column "user_id".
|
|
584
|
+
Relations only between editable (user-created) tables.
|
|
585
|
+
Many-to-many: use an intermediate join table + two one-to-many relations.
|
|
586
|
+
To unique-constrain a relation field, use the FK field name ("user_id"), not the virtual name.
|
|
587
|
+
|
|
588
|
+
### Enums (managed by the 'type' plugin)
|
|
589
|
+
Enum types are created and edited via the 'type' plugin, not here. To use an enum as a column type, use "u:e:<enumId>" with the actual id from type.list_enums. Create the enum first via the 'type' plugin (same turn, before the column) if it does not yet exist \u2014 you supply the id there, so you can reference it immediately.
|
|
590
|
+
|
|
591
|
+
### Geographic Location
|
|
592
|
+
Use s:p:geo_point for coordinates. Never split into separate latitude/longitude fields. A s:p:geo_point field auto-generates a companion s:p:decimal hack field named "fz_distance_from_<apiName>", where <apiName> is the geo_point's apiName (may differ from its displayName). At request time it returns the distance from the stored geo_point to the user-supplied location in the request. Treat it as a distance-calculation hack \u2014 future migration: this will be replaced by formula fields.
|
|
593
|
+
|
|
594
|
+
### Data Views
|
|
595
|
+
A view is a saved SELECT over this project's tables, exposed as a READ-ONLY table of its own: it has a displayName like any table, it shows up in reads and data bindings, and it is queried the same way. Reach for one when the SAME joined or aggregated result is needed in more than one place \u2014 "Number of orders and total amount per user" \u2014 so the definition lives once instead of being rebuilt in every query, component and action flow that needs it.
|
|
596
|
+
|
|
597
|
+
A view is a definition, not a copy: it holds no data of its own and is recomputed on every read, so it is never stale. It costs what the query costs, every time it is read.
|
|
598
|
+
|
|
599
|
+
Write the SQL against the API (snake_case) names, quoted and case-sensitive \u2014 the same names GET_TABLES_INFO reports. Everything else on this plugin is addressed by displayName; the SQL body is the one place that is not, because it is PostgreSQL rather than a tool argument.
|
|
600
|
+
|
|
601
|
+
Always ANALYZE_VIEW_SQL first and fix what it reports before creating or updating a view. It returns the exact columns the view would expose, so it is also how you learn what a view you are about to build on actually gives you. Creating or updating a view with SQL that does not analyse is rejected, not stored.
|
|
602
|
+
|
|
603
|
+
You CANNOT:
|
|
604
|
+
- Write through a view. There is no insert, update or delete, and no by-id lookup: a view has no primary key.
|
|
605
|
+
- Use the whole of SQL. One SELECT only: JOIN with ON, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT, UNION, CTEs, CASE, COALESCE, casts and the aggregate functions. NOT available: subqueries, window functions, query parameters, and anything that is not a single SELECT statement.
|
|
606
|
+
- Parameterise a view. It is a stored definition with no request context, so there is no "current user" inside it and no placeholder to bind. Expose the user column and filter when you QUERY the view instead.
|
|
607
|
+
- Omit a column alias. Every output column needs an explicit \`AS alias\`, and that alias is the field name the view exposes.
|
|
608
|
+
- Read an IMAGE_LIST column. Every other type works, but a media column is read under its database name \u2014 an IMAGE/VIDEO/FILE field called "avatar" is \`avatar_id\` in the SQL, and aliasing it \`AS cover_id\` exposes it as a media field named "cover". Keep the \`_id\` suffix or it comes back as a plain number.
|
|
609
|
+
- Delete a view another view still reads. Delete or rewrite the reader first.
|
|
610
|
+
|
|
611
|
+
Views take effect online only after "Sync Backend", like every other data-model change.
|
|
612
|
+
|
|
613
|
+
### Constraints
|
|
614
|
+
Only unique constraints supported. Constraint name: lowercase English snake_case, no uppercase. Reference fields by their displayName \u2014 for a relation's foreign key use the generated FK field ("user_id"). Uniqueness is fixed when a field is created and cannot be turned on afterwards (existing rows could already hold duplicates), so to make an existing field unique, add a constraint over it. Use a constraint to span multiple fields (composite unique): list the fields' displayNames. Unique constraints are also the only DB-enforced invariant writers can lean on for atomic insert-if-absent / toggle semantics (insert with on_conflict): whenever the design has "at most one row per X" semantics (a join/like/save table, an idempotency key), create the unique constraint up front \u2014 read-check-then-insert cannot be made race-safe without it.
|
|
615
|
+
|
|
616
|
+
A relation's generated FK carries two names, and which one a call wants depends on the call. The schema tools here take displayNames, so a relation named \u8F6C\u8BD1\u884C gives a FK whose displayName is \`\u8F6C\u8BD1\u884C_id\` \u2014 that is what ADD_CONSTRAINTS matches on. The runtime API takes apiNames, so the same column is \`translation_row_id\` in a \`runtime.query\` filter or a \`runtime.insert\` object. Neither side accepts the other's name, and passing the wrong one reports the field as missing rather than as misnamed. Read both off the field record instead of transliterating one into the other.`}},deploy:{pre:{available:!0,prompt:`## Backend Sync Domain Knowledge
|
|
617
|
+
A project's running backend serves the last SYNCED schema, not the one being edited. The data model, action flows, APIs, permissions, secrets, AI agents and triggers all live there, so until a sync lands, edits to any of them do not exist for a preview, a published app, or anything queried against the runtime \u2014 the editor shows the new schema while the backend still answers with the old one.
|
|
618
|
+
|
|
619
|
+
project sync-backend saves the project, deploys that backend, waits for the pipeline, and reports what happened. It takes no arguments.
|
|
620
|
+
|
|
621
|
+
### When to call it
|
|
622
|
+
Once, after a batch of backend-affecting edits \u2014 never after each individual edit. A sync redeploys the whole backend and takes anywhere from tens of seconds to a few minutes, so finish the data model, flows, APIs and permissions the task needs, then sync once. Purely visual work (components, styles, and bindings that reference no server entity) does not need one at all.
|
|
623
|
+
|
|
624
|
+
Call it before you test anything against the runtime or tell the user their backend change is live. Do not claim a table, flow or API is working online when the only thing that happened was a schema edit.
|
|
625
|
+
|
|
626
|
+
### Reading the result
|
|
627
|
+
- SYNCED \u2014 the saved schema is live on the runtime.
|
|
628
|
+
- FAILED \u2014 the deployment pipeline rejected the schema. Something in the project is invalid; find it (the component plugin's project-error list and the logs plugin's DEPLOYMENT entries are the two places it shows up), fix it, and sync again. Repeating the sync unchanged fails the same way.
|
|
629
|
+
- IN_PROGRESS \u2014 the pipeline was still running when the wait expired. Nothing is wrong; call project sync-backend again to keep waiting for the same pipeline.
|
|
630
|
+
- NOT_STARTED \u2014 nothing was deployed. The usual cause is the user dismissing the save confirmation the editor raises when the project changed elsewhere; tell them rather than retrying in a loop.
|
|
631
|
+
|
|
632
|
+
### One backend, every client app
|
|
633
|
+
A project has ONE backend and any number of client apps on top of it. A sync redeploys that shared backend, so the data model, flows, APIs and permissions you changed take effect for every one of them at once \u2014 including apps you are not editing and cannot see from this session. Before syncing a project with more than one client app, say which change you are about to make live and that it lands for all of them; the confirmation names the apps.
|
|
634
|
+
|
|
635
|
+
### What it is not
|
|
636
|
+
Syncing is not publishing. The user's live web or mini-program app is released separately through the editor's Publish flow, which is theirs to run \u2014 a sync makes the backend match the editor, it does not push a new version of their app to end users.`},post:{available:!0,prompt:`## Backend Sync Domain Knowledge
|
|
637
|
+
A project's running backend serves the last SYNCED schema, not the one being edited. The data model, action flows, APIs, permissions, secrets, AI agents and triggers all live there, so until a sync lands, edits to any of them do not exist for a preview, a published app, or anything queried against the runtime \u2014 the editor shows the new schema while the backend still answers with the old one.
|
|
638
|
+
|
|
639
|
+
project sync-backend saves the project, deploys that backend, waits for the pipeline, and reports what happened. It takes no arguments.
|
|
640
|
+
|
|
641
|
+
### When to call it
|
|
642
|
+
Once, after a batch of backend-affecting edits \u2014 never after each individual edit. A sync redeploys the whole backend and takes anywhere from tens of seconds to a few minutes, so finish the data model, flows, APIs and permissions the task needs, then sync once. Purely visual work (components, styles, and bindings that reference no server entity) does not need one at all.
|
|
643
|
+
|
|
644
|
+
Call it before you test anything against the runtime or tell the user their backend change is live. Do not claim a table, flow or API is working online when the only thing that happened was a schema edit.
|
|
645
|
+
|
|
646
|
+
### Reading the result
|
|
647
|
+
- SYNCED \u2014 the saved schema is live on the runtime.
|
|
648
|
+
- FAILED \u2014 the deployment pipeline rejected the schema. Something in the project is invalid; find it (the component plugin's project-error list and the logs plugin's DEPLOYMENT entries are the two places it shows up), fix it, and sync again. Repeating the sync unchanged fails the same way.
|
|
649
|
+
- IN_PROGRESS \u2014 the pipeline was still running when the wait expired. Nothing is wrong; call project sync-backend again to keep waiting for the same pipeline.
|
|
650
|
+
- NOT_STARTED \u2014 nothing was deployed. The usual cause is the user dismissing the save confirmation the editor raises when the project changed elsewhere; tell them rather than retrying in a loop.
|
|
651
|
+
|
|
652
|
+
### One backend, every client app
|
|
653
|
+
A project has ONE backend and any number of client apps on top of it. A sync redeploys that shared backend, so the data model, flows, APIs and permissions you changed take effect for every one of them at once \u2014 including apps you are not editing and cannot see from this session. Before syncing a project with more than one client app, say which change you are about to make live and that it lands for all of them; the confirmation names the apps.
|
|
654
|
+
|
|
655
|
+
### What it is not
|
|
656
|
+
Syncing is not publishing. The user's live web or mini-program app is released separately through the editor's Publish flow, which is theirs to run \u2014 a sync makes the backend match the editor, it does not push a new version of their app to end users.`}},logs:{pre:{available:!0,prompt:`## Log Domain Knowledge
|
|
657
|
+
Zion provides a runtime log service showing server-side execution traces.
|
|
658
|
+
|
|
659
|
+
### Log Types
|
|
660
|
+
GATEWAY, ACTION_FLOW, ACTION_FLOW_NODE, ACTION_FLOW_CONTEXT_LOG, DEPLOYMENT, TPA, TRIGGER, SQL_GENERATION, GQL, ZAI.
|
|
661
|
+
|
|
662
|
+
### Searching
|
|
663
|
+
Every entry carries a traceId, and it is the only filter matched against a real indexed column \u2014 pass it as the traceId argument to get the whole request in causal order. types and levels are also real filters. Everything in customQueryCondition is a substring scan over the log body, so treat its matches as approximate and never as proof a field equals a value.
|
|
664
|
+
|
|
665
|
+
### Interpreting Logs
|
|
666
|
+
ACTION_FLOW / ACTION_FLOW_NODE errors: misconfigured nodes (wrong field names, type mismatches). GATEWAY errors: API or authentication issues. SQL_GENERATION: data model or query configuration problems. GQL: GraphQL schema or permission issues. Except for GATEWAY, an entry's payload sits under content.message \u2014 read nodeName, nodeType, status and errorMessage there first, then input/output only when you need them. Translate technical errors into plain language. Distinguish configuration errors from platform bugs. Never expose sensitive fields (token, account_id) in responses.
|
|
667
|
+
|
|
668
|
+
### Time Window
|
|
669
|
+
Logs fetched in a \xB15-minute window around requestCreatedAt (defaults to now).`},post:{available:!0,prompt:`## Log Domain Knowledge
|
|
670
|
+
Zion provides a runtime log service showing server-side execution traces.
|
|
671
|
+
|
|
672
|
+
### Log Types
|
|
673
|
+
GATEWAY, ACTION_FLOW, ACTION_FLOW_NODE, ACTION_FLOW_CONTEXT_LOG, DEPLOYMENT, TPA, TRIGGER, SQL_GENERATION, GQL, ZAI.
|
|
674
|
+
|
|
675
|
+
### Searching
|
|
676
|
+
Every entry carries a traceId, and it is the only filter matched against a real indexed column \u2014 pass it as the traceId argument to get the whole request in causal order. types and levels are also real filters. Everything in customQueryCondition is a substring scan over the log body, so treat its matches as approximate and never as proof a field equals a value.
|
|
677
|
+
|
|
678
|
+
### Interpreting Logs
|
|
679
|
+
ACTION_FLOW / ACTION_FLOW_NODE errors: misconfigured nodes (wrong field names, type mismatches). GATEWAY errors: API or authentication issues. SQL_GENERATION: data model or query configuration problems. GQL: GraphQL schema or permission issues. Except for GATEWAY, an entry's payload sits under content.message \u2014 read nodeName, nodeType, status and errorMessage there first, then input/output only when you need them. Translate technical errors into plain language. Distinguish configuration errors from platform bugs. Never expose sensitive fields (token, account_id) in responses.
|
|
680
|
+
|
|
681
|
+
### Time Window
|
|
682
|
+
Logs fetched in a \xB15-minute window around requestCreatedAt (defaults to now).`}},overview:{pre:{available:!0,prompt:`## Project Overview Domain Knowledge
|
|
683
|
+
Overview offers two complementary bird's-eye queries, both deliberately compact (names + ids only) so a single call orients you without flooding context.
|
|
684
|
+
|
|
685
|
+
- GET_PROJECT_OVERVIEW \u2014 the complete inventory of every top-level entity in the app
|
|
686
|
+
(tables, pages, modals, action flows, triggers, webhooks, APIs, agents, roles, types, global
|
|
687
|
+
variables, colour themes) with the ids/names the domain tools take. Call this **first** on an
|
|
688
|
+
unfamiliar project, and treat its answer as the census: the per-domain \`list_*\` tools return
|
|
689
|
+
subsets of it, so calling one after this buys nothing.
|
|
690
|
+
- GET_ENTITY_RELATION_GRAPH \u2014 the relation graph around one entity: who reads / writes / calls / governs it, expanded a bounded number of hops. Use it before changing or deleting an entity to see what depends on it.
|
|
691
|
+
|
|
692
|
+
Both are read-only; neither mutates the schema.`},post:{available:!0,prompt:`## Project Overview Domain Knowledge
|
|
693
|
+
Overview offers two complementary bird's-eye queries, both deliberately compact (names + ids only) so a single call orients you without flooding context.
|
|
694
|
+
|
|
695
|
+
- GET_PROJECT_OVERVIEW \u2014 the complete inventory of every top-level entity in the app
|
|
696
|
+
(tables, pages, modals, action flows, triggers, webhooks, APIs, agents, roles, types, global
|
|
697
|
+
variables, colour themes) with the ids/names the domain tools take. Call this **first** on an
|
|
698
|
+
unfamiliar project, and treat its answer as the census: the per-domain \`list_*\` tools return
|
|
699
|
+
subsets of it, so calling one after this buys nothing.
|
|
700
|
+
- GET_ENTITY_RELATION_GRAPH \u2014 the relation graph around one entity: who reads / writes / calls / governs it, expanded a bounded number of hops. Use it before changing or deleting an entity to see what depends on it.
|
|
701
|
+
|
|
702
|
+
Both are read-only; neither mutates the schema.`}},payments:{pre:{available:!0,prompt:"## Payment System Domain Knowledge\nZion's payment system is built around a developer-owned **order table** plus a set of platform-managed payment records and **auto-generated Actionflows** that react to gateway callbacks. On Zion the gateways are WeChat Pay (mini-program and H5/JSAPI) and Alipay (PC web; one-time plus recurring \"agreement\" subscriptions). Enabling and configuring payments splits in two: you activate the module with ACTIVATE_PAYMENT; the gateway credentials, the brand assets and the Pro-plan upgrade are the user's own, in the editor (Settings \u2192 Payment).\n\n### Prerequisites (in order)\n1. The user upgrades the project to the Pro plan or higher (payments are gated by plan; an expired plan breaks live payments and blocks publishing).\n2. Create the **order table** (see below) with its required fields.\n3. Call ACTIVATE_PAYMENT with the order table's display name. Read `overview.project` first \u2014 it reports whether payments are already enabled and which types are active, and the order table is fixed by the first activation and ignored afterwards. The call appends the type's generated flows/callbacks/jobs and grants the logged-in user role permission to pay with it; a first activation also inserts the payment tables, which every role then carries in its table permissions though only the logged-in user role can read them. It names what it created; say so in your answer, since in AUTO_ACCEPT the user was not asked.\n4. Configure the gateway credentials \u2014 WeChat Pay (merchant ID, APIv2 key, the linked Mini Program AppID, plus the apiclient_cert.p12 for refunds) and/or Alipay (app ID and an RSA2 key pair) and/or Airwallex (client ID, API key and webhook secret) \u2014 plus brand name, logo, slogan.\n5. Confirm the auto-generated payment/refund callback flows are wired.\n\n### The Order Table (you design this \u2014 follow database conventions)\nThe order table is a normal business table you create; the payment engine references one of its rows by its primary-key id (the `orderId` everywhere below). At minimum it needs:\n- an **amount/price** column \u2014 type `DECIMAL`, the authoritative price computed server-side.\n- a **status** column \u2014 model it as a `TEXT` column holding the lifecycle value (e.g.\n `pending`, `paid`, `cancelled`, `refunded`); your fulfillment flow updates it. Custom\n enums are unavailable in this project, so use TEXT here.\n- a **buyer link** \u2014 do NOT add a raw `user_id`/`account_id` column. Create a 1:n RELATION from `account` to the order table so the buyer FK is generated automatically (the same manual-foreign-key rule the database plugin enforces). Add product/quantity links as relations too. Naming follows the usual rules: `snake_case` system names, no manual `id`/`created_at` columns (the runner mints the PK).\n\n**Irreversibility warning:** once the order table is linked to the payment module it CANNOT be unlinked, replaced, or deleted. Always confirm the table design with the user and warn them of this before they bind it. Choose the table deliberately.\n\n### Platform-Managed Tables (do NOT create or model these)\nEnabling payments auto-creates three system tables \u2014 never recreate them as user tables and never write to them directly:\n- the **payment** table (`fz_payment` / `fz_payment_record`, 1:N from the order table) \u2014 one row per payment attempt, carrying `orderId`, `accountId`, `type`, `status`, `currency`, `grandTotalValue`, `transactionId`.\n- the **recurring_payment** table \u2014 Alipay agreement subscriptions and their billing cycle.\n- the **refund** table (1:N from payment) \u2014 refund transactions. The internal payment `status` is a fixed lifecycle enum: `PENDING`, `CANCELLED`, `SUCCESSFUL`, `FAILED`, `PARTIALLY_REFUNDED`, `REFUNDING`, `REFUNDED`. Your order table's own status column is separate from this \u2014 your fulfillment flow translates one into the other.\n\n### Auto-Created Callback Actionflows (WeChat Pay / Alipay)\nEnabling payments auto-generates the backend callback Actionflows the editor wires to each payment action. They have no fixed English name (they are the \"preset\" flows for the channel you enabled); don't delete or rename them. You edit their bodies to run business logic:\n- the **payment** flow \u2014 triggered automatically after a charge resolves.\n- the **refund** flow \u2014 triggered automatically after a refund resolves.\n- the Alipay **recurring-deduction** flow \u2014 a daily scheduled loop that charges due agreements.\n\n### Editing the payment flow (the one you almost always modify)\nThe flow has a built-in \"parse payment result\" code block that outputs four values:\n- `orderId` \u2014 the order-table row you passed to the payment action; use it to find and update the order.\n- `paymentFound` \u2014 whether a matching payment record was found.\n- `paymentStatus` \u2014 `SUCCESSFUL` or `FAILED`.\n- `alreadyProcessed` \u2014 boolean; `false` on the first trigger, `true` on a re-delivery. **Idempotency contract (critical):** the same payment can trigger the flow more than once. Only run fulfillment / mark the order paid when `paymentFound` is true, `paymentStatus` is the expected value, AND `alreadyProcessed == false`. Guard the fulfillment branch with Condition nodes on these, otherwise duplicate callbacks double-fulfill (double-ship, double-credit). For safety, also add a branch that re-checks the actual paid amount against the order's amount before fulfilling. The refund flow works the same way: its parser returns `orderId`, `refundFound`, `paymentStatus` (`REFUNDED` or `FAILED`), and `alreadyProcessed`.\n\n### Creating an Order (the secure-transaction pattern)\nNever let the client decide the price. Order creation must run server-side:\n1. Frontend triggers a backend Actionflow passing only identifiers (e.g. `product_id`, quantity) \u2014 never the price.\n2. The flow queries the product/price server-side, computes the authoritative amount, inserts a new order row with status `pending`, and returns the generated `orderId` and verified amount.\n3. The frontend maps the *returned* `orderId` and amount into the WeChat Pay / Alipay / Airwallex payment action. This is the Zero-Trust pattern: the price the customer is charged is the one the server computed and stored on the order, not anything the browser sent.\n\n### Amounts & Currency\nThe WeChat Pay and Alipay payment actions take the amount in **yuan (\u5143) as a `DECIMAL` with at most two decimal places, and it must be greater than 0.01** \u2014 pass the order's server-computed price directly; do NOT convert to cents/\u5206.\n\n### Airwallex (only where enabled for the project)\nAirwallex is activated like any other type and takes both one-time payments and subscriptions. It generates two backend Actionflows; don't delete or rename them:\n1. **Airwallex Payment** \u2014 receives every Airwallex webhook as `fz_payment_callback_input` and branches on the event type: payment status changed (`payment_intent.succeeded` / `payment_intent.cancelled`), refund (`refund.accepted` / `refund.failed`), subscription status changes, and `invoice.finalized`. In the payment branch the built-in \"Sync payment status\" block outputs `orderId`, `paymentStatus` (`SUCCESSFUL` or `CANCELLED`) and `alreadyProcessed`; in the refund branch \"Sync refund status\" outputs `orderId`, `status` (`REFUNDED` or `FAILED`) and `alreadyProcessed`. Put fulfillment after those blocks under the same idempotency contract: act only on the expected status AND `alreadyProcessed == false`.\n2. **Airwallex Subscription Renewal** \u2014 called by Airwallex Payment with the invoice id to create the order and payment for a subscription renewal.\nAirwallex amounts are decimals in the currency's major unit (10.00, not 1000): pass the order's server-computed decimal price directly.\n\n### Recurring Payments (Alipay)\nAlipay supports subscriptions via a signed agreement. The start action takes `orderId`, a price (Alipay caps recurring amounts at \xA5100), a product name, a deduction interval (\u2265 7 days), and an Alipay scene code (a user can subscribe to the same scene only once); the cancel action takes the recurring-payment row id. Deductions run in the auto-generated daily loop flow: for each due agreement you must create a NEW order inside the loop and bind its id to the deduction node's `orderId` input. Note: a full Alipay refund does not re-trigger the payment flow.\n\n### Scope Note\nACTIVATE_PAYMENT turns the module on one type at a time, and the actionflow plugin edits the generated flows' bodies. What you cannot do is the user's own editor work (Settings \u2192 Payment): the gateway credentials, the brand assets and the plan upgrade. Design the order table first (via the database plugin), then activate, then wire the secure order-creation flow and add the `alreadyProcessed` idempotency guard in the payment flow."},post:{available:!0,prompt:"## Payment System Domain Knowledge\nZion's payment system is built around a developer-owned **order table** plus a set of platform-managed payment records and **auto-generated Actionflows** that react to gateway callbacks. On Zion the gateways are WeChat Pay (mini-program and H5/JSAPI) and Alipay (PC web; one-time plus recurring \"agreement\" subscriptions). Enabling and configuring payments splits in two: you activate the module with ACTIVATE_PAYMENT; the gateway credentials, the brand assets and the Pro-plan upgrade are the user's own, in the editor (Action \u2192 Payment).\n\n### Prerequisites (in order)\n1. The user upgrades the project to the Pro plan or higher (payments are gated by plan; an expired plan breaks live payments and blocks publishing).\n2. Create the **order table** (see below) with its required fields.\n3. Call ACTIVATE_PAYMENT with the order table's display name. Read `overview.project` first \u2014 it reports whether payments are already enabled and which types are active, and the order table is fixed by the first activation and ignored afterwards. The call appends the type's generated flows/callbacks/jobs and grants the logged-in user role permission to pay with it; a first activation also inserts the payment tables, which every role then carries in its table permissions though only the logged-in user role can read them. It names what it created; say so in your answer, since in AUTO_ACCEPT the user was not asked.\n4. Configure the gateway credentials \u2014 WeChat Pay (merchant ID, APIv2 key, the linked Mini Program AppID, plus the apiclient_cert.p12 for refunds) and/or Alipay (app ID and an RSA2 key pair) and/or Airwallex (client ID, API key and webhook secret) \u2014 plus brand name, logo, slogan.\n5. Confirm the auto-generated payment/refund callback flows are wired.\n\n### The Order Table (you design this \u2014 follow database conventions)\nThe order table is a normal business table you create; the payment engine references one of its rows by its primary-key id (the `orderId` everywhere below). At minimum it needs:\n- an **amount/price** column \u2014 type `s:p:decimal`, the authoritative price computed server-side.\n- a **status** column \u2014 create a custom enum whose options mirror the payment lifecycle\n (e.g. `pending`, `paid`, `cancelled`, `refunded`), then use the exact\n `u:e:<enumId>` returned by the type plugin as the column type; your fulfillment flow\n updates it.\n- a **buyer link** \u2014 do NOT add a raw `user_id`/`account_id` column. Create a 1:n RELATION from `account` to the order table so the buyer FK is generated automatically (the same manual-foreign-key rule the database plugin enforces). Add product/quantity links as relations too. Naming follows the usual rules: `snake_case` system names, no manual `id`/`created_at` columns (the runner mints the PK).\n\n**Irreversibility warning:** once the order table is linked to the payment module it CANNOT be unlinked, replaced, or deleted. Always confirm the table design with the user and warn them of this before they bind it. Choose the table deliberately.\n\n### Platform-Managed Tables (do NOT create or model these)\nEnabling payments auto-creates three system tables \u2014 never recreate them as user tables and never write to them directly:\n- the **payment** table (`fz_payment` / `fz_payment_record`, 1:N from the order table) \u2014 one row per payment attempt, carrying `orderId`, `accountId`, `type`, `status`, `currency`, `grandTotalValue`, `transactionId`.\n- the **recurring_payment** table \u2014 Alipay agreement subscriptions and their billing cycle.\n- the **refund** table (1:N from payment) \u2014 refund transactions. The internal payment `status` is a fixed lifecycle enum: `PENDING`, `CANCELLED`, `SUCCESSFUL`, `FAILED`, `PARTIALLY_REFUNDED`, `REFUNDING`, `REFUNDED`. Your order table's own status column is separate from this \u2014 your fulfillment flow translates one into the other.\n\n### Auto-Created Callback Actionflows (WeChat Pay / Alipay)\nEnabling payments auto-generates the backend callback Actionflows the editor wires to each payment action. They have no fixed English name (they are the \"preset\" flows for the channel you enabled); don't delete or rename them. You edit their bodies to run business logic:\n- the **payment** flow \u2014 triggered automatically after a charge resolves.\n- the **refund** flow \u2014 triggered automatically after a refund resolves.\n- the Alipay **recurring-deduction** flow \u2014 a daily scheduled loop that charges due agreements.\n\n### Editing the payment flow (the one you almost always modify)\nThe flow has a built-in \"parse payment result\" code block that outputs four values:\n- `orderId` \u2014 the order-table row you passed to the payment action; use it to find and update the order.\n- `paymentFound` \u2014 whether a matching payment record was found.\n- `paymentStatus` \u2014 `SUCCESSFUL` or `FAILED`.\n- `alreadyProcessed` \u2014 boolean; `false` on the first trigger, `true` on a re-delivery. **Idempotency contract (critical):** the same payment can trigger the flow more than once. Only run fulfillment / mark the order paid when `paymentFound` is true, `paymentStatus` is the expected value, AND `alreadyProcessed == false`. Guard the fulfillment branch with Condition nodes on these, otherwise duplicate callbacks double-fulfill (double-ship, double-credit). For safety, also add a branch that re-checks the actual paid amount against the order's amount before fulfilling. The refund flow works the same way: its parser returns `orderId`, `refundFound`, `paymentStatus` (`REFUNDED` or `FAILED`), and `alreadyProcessed`.\n\n### Creating an Order (the secure-transaction pattern)\nNever let the client decide the price. Order creation must run server-side:\n1. Frontend triggers a backend Actionflow passing only identifiers (e.g. `product_id`, quantity) \u2014 never the price.\n2. The flow queries the product/price server-side, computes the authoritative amount, inserts a new order row with status `pending`, and returns the generated `orderId` and verified amount.\n3. The frontend maps the *returned* `orderId` and amount into the WeChat Pay / Alipay / Airwallex payment action. This is the Zero-Trust pattern: the price the customer is charged is the one the server computed and stored on the order, not anything the browser sent.\n\n### Amounts & Currency\nThe WeChat Pay and Alipay payment actions take the amount in **yuan (\u5143) as a `s:p:decimal` with at most two decimal places, and it must be greater than 0.01** \u2014 pass the order's server-computed price directly; do NOT convert to cents/\u5206.\n\n### Airwallex (only where enabled for the project)\nAirwallex is activated like any other type and takes both one-time payments and subscriptions. It generates two backend Actionflows; don't delete or rename them:\n1. **Airwallex Payment** \u2014 receives every Airwallex webhook as `fz_payment_callback_input` and branches on the event type: payment status changed (`payment_intent.succeeded` / `payment_intent.cancelled`), refund (`refund.accepted` / `refund.failed`), subscription status changes, and `invoice.finalized`. In the payment branch the built-in \"Sync payment status\" block outputs `orderId`, `paymentStatus` (`SUCCESSFUL` or `CANCELLED`) and `alreadyProcessed`; in the refund branch \"Sync refund status\" outputs `orderId`, `status` (`REFUNDED` or `FAILED`) and `alreadyProcessed`. Put fulfillment after those blocks under the same idempotency contract: act only on the expected status AND `alreadyProcessed == false`.\n2. **Airwallex Subscription Renewal** \u2014 called by Airwallex Payment with the invoice id to create the order and payment for a subscription renewal.\nAirwallex amounts are decimals in the currency's major unit (10.00, not 1000): pass the order's server-computed decimal price directly.\n\n### Recurring Payments (Alipay)\nAlipay supports subscriptions via a signed agreement. The start action takes `orderId`, a price (Alipay caps recurring amounts at \xA5100), a product name, a deduction interval (\u2265 7 days), and an Alipay scene code (a user can subscribe to the same scene only once); the cancel action takes the recurring-payment row id. Deductions run in the auto-generated daily loop flow: for each due agreement you must create a NEW order inside the loop and bind its id to the deduction node's `orderId` input. Note: a full Alipay refund does not re-trigger the payment flow.\n\n### Scope Note\nACTIVATE_PAYMENT turns the module on one type at a time, and the actionflow plugin edits the generated flows' bodies. What you cannot do is the user's own editor work (Action \u2192 Payment): the gateway credentials, the brand assets and the plan upgrade. Design the order table first (via the database plugin), then activate, then wire the secure order-creation flow and add the `alreadyProcessed` idempotency guard in the payment flow."}},permissions:{pre:{available:!0,prompt:'## Permission System Domain Knowledge\nZion secures data and actions with RBAC (roles) plus ABAC (per-row conditions). Every tool in this plugin edits the project schema only \u2014 the change reaches the deployed backend when "Sync Backend" runs, which is the last step of any permission task.\n\n### Model\n- **Role**: a named collection of users. Two are predefined and cannot be renamed or deleted: **Logged-in User** (held by every authenticated user) and **Anonymous User** (unauthenticated requests). Custom roles can then be created, renamed, and deleted, up to the project\'s role limit \u2014 but **`Admin` is a reserved name**: a role is treated as system-defined by *name*, so one created or renamed to `Admin` could never be renamed or deleted again. Both tools refuse it; pick another name.\n- **Data Permission**: what a role may read or write, at table, column and row level.\n- **Action Permission**: which Third-Party API configurations, Actionflows, AI agents and payment operations a role may invoke.\n- Each action block is allow-all or an explicit allow-list. On top of those grants, per-target conditional checks are available for Actionflows and AI agents; payments take allow-all or a payment-type/billing-method map.\n- **Roles only ever add.** A user\'s effective permissions are the union of every role they hold; a restrictive role never subtracts what a permissive one granted. To take access away, narrow or unassign the permissive role \u2014 never "add a limited role".\n\n### Activate first\nRole names come from `GET_PROJECT_OVERVIEW`\'s `roles` section, which also reports whether role permission is activated; `GET_ALL_ROLES_INFO` is the fallback when you have not run it. When either reports that role permission is not activated:\n- In BUILD or AUTO_ACCEPT mode, you MUST immediately call `ACTIVATE_ROLE_PERMISSION`, which seeds the predefined roles. BUILD uses the normal user-confirmation gate; AUTO_ACCEPT applies it immediately.\n- In RESEARCH mode, do not attempt a mutation; tell the user to look into permissions in \u8BBE\u7F6E \u2192 \u6743\u9650\u7BA1\u7406.\n\n### Grant\nData permissions are configured coarse \u2192 fine:\n1. **Table**: which operations (select / insert / update / delete / count / aggregate) the role may run.\n2. **Column**: which fields each operation covers.\n3. **Row**: a per-operation condition \u2014 a filter over existing rows for select, update and delete, a check on the incoming row for insert. Each one starts always-true, so a fresh grant is open until narrowed.\n\nRead before writing: `GET_ROLE_DETAIL`, naming every role the task will edit; the role names are already in `GET_PROJECT_OVERVIEW`. It reports each table by exception \u2014 the operations granted, the ones under `rowConditions` whose row condition has been narrowed, and `restrictedColumns` only where a grant covers less than the whole table, so an operation listed as granted and mentioned nowhere else is open on every column and every row. Tables the role cannot touch at all are named together in `tablesWithNoGrants`. Pass `blocks` when the task is about one block (the table block is nearly the whole payload). It does not carry the row conditions\' schema paths \u2014 when you are narrowing one, read `GET_TABLE_PERMISSION` instead: it names the tables you are about to change, reports each operation\'s condition path, and satisfies the same gate, so the path arrives in the call right before the one that uses it. Edit with `ADD_ROLES`, `UPDATE_ROLE`, `DELETE_ROLES` and the per-block setters `UPDATE_ROLE_TABLE_PERMISSION`, `UPDATE_ROLE_ACTION_FLOW_PERMISSION`, `UPDATE_ROLE_ZAI_PERMISSION`, `UPDATE_ROLE_PAYMENT_PERMISSION`, `UPDATE_ROLE_TPA_PERMISSION` for Third-Party API configurations. Account insert/delete is unavailable, and `id` is pinned into every table SELECT grant.\n\nViews (the read-only saved queries the database plugin manages) are granted separately with `UPDATE_ROLE_VIEW_PERMISSION`: only select / count / aggregate exist, each with its column set and row condition, and a view no role has been granted cannot be queried by anyone. `GET_VIEW_PERMISSION` reports a view\'s condition paths the way `GET_TABLE_PERMISSION` does for tables.\n\n`allowAll` on `tpaPermission`, `actionflowPermission` or `zAiPermission` also covers resources added later \u2014 prefer explicit allow-lists unless broad access is intentional.\n\n**Role, or a field on Account?** Use a role for static functional boundaries: who may run a flow, read a table, see a column. Add a field on the Account table for per-user state: VIP status, nickname, bio.\n\n**Never create one role per group.** For departments, stores, tenants or any other segmentation, use the relation-first pattern: create a `1:n` relation from the context table (e.g. `department`) to `Account`, and a second one from that same table to the business table (e.g. `sales_record`). Both foreign-key columns are generated and non-editable \u2014 never declare them as raw integer fields. Then define one generic role (`Sales_Staff`) and compare those two columns in its row conditions.\n\nSimple single-table CRUD may run directly from the frontend when table, column, and row permissions fully express the authorization policy \u2014 do not wrap it in an Actionflow. Reach for a Backend Actionflow only when the rule cannot be expressed that way at all: it needs server-held secrets, cross-table atomicity, or multi-step state transitions.\n\n### Row conditions (ABAC)\nNarrowing those conditions is a two-plugin job: this plugin has no tool that edits one \u2014 they live in the **bindings** area, whose tools are the `INSERT_CONDITION_BOOL_EXP` family, addressed by the condition path `GET_TABLE_PERMISSION` reports. The check `SET_ROLE_PERMISSION_CHECK` seeds for an Actionflow or AI agent works the same way.\n\nNever hand-build a permission schema path. It embeds the role\'s index in the schema and the table\'s internal id, neither of which any read reports on its own, so a path assembled from what a read did show resolves to nothing \u2014 copy the one a read returned.\n\nEach operation has its own condition node and its own row branch to compare against, so reusing the select recipe on another op fails:\n- `select` \u2192 path ends `/select/filter` \u2192 the branch holding the row being read\n- `insert` \u2192 path ends `/insert/check`, not `filter` \u2192 the branch holding the row being inserted\n- `update` \u2192 path ends `/update/filter` \u2192 the branch holding the row as stored, or the one holding the incoming values\n- `delete` \u2192 path ends `/delete/filter` \u2192 the branch holding the row being deleted\n- `count` / `aggregate` \u2192 no row branch exists, only the logged-in user and the current time, so they cannot be row-scoped. Whenever you narrow `select`, send `count` and `aggregate` `{enabled: false}` too, unless a whole-table count is meant to be public: a row-scoped `select` beside an open `count` still tells any user how many rows everyone else has.\n\nNarrowing one condition:\n1. `GET_TABLE_PERMISSION` for that table (or the result of `UPDATE_ROLE_TABLE_PERMISSION`, which reports the same paths for the grants it just made, or of `SET_ROLE_PERMISSION_CHECK` for a flow/agent check) \u2192 that operation\'s condition schema path. `GET_ROLE_DETAIL` does not carry them.\n2. `INSERT_CONDITION_BOOL_EXP` at that path \u2192 returns a `conditionSchemaPath`. Copy it verbatim; never hand-build one.\n3. `GET_EXPRESSION_CONDITION_OPERATORS` at that path, then `UPDATE_EXPRESSION_CONDITION_OPERATOR` with an operator copied verbatim. The `target` and `value` operand slots do not exist until the operator is set \u2014 binding first fails with "has no binding site at \u2026/target".\n4. Fill both operands at `<conditionSchemaPath>/target` and `<conditionSchemaPath>/value`, addressed by `pathInHierarchicalMenu`. Read that path \u2014 branch label included \u2014 from `BROWSE_DATA_BINDING_OPTIONS` at the operand\'s own schema path and copy it verbatim; never hand-build one. Relations traverse, so a child table can compare against its parent\'s owner \u2014 that path is four segments deep: context root, row branch, relation, column. Every segment is a label from the tree, including the root.\n5. Delete the always-true placeholder the grant started with: `DELETE_CONDITION_BOOL_EXP` at `<step 1\'s condition schema path>/_and/[0]` \u2014 the filter\'s own path, not the comparison path step 2 returned. Harmless at runtime, but the editor renders it as an empty condition row, so the user sees a half-configured rule.\n6. Shape multi-clause predicates with `NEST_CONDITION_BOOL_EXP`, `TOGGLE_CONDITION_BOOL_EXP_AND_OR`, `TOGGLE_CONDITION_BOOL_EXP_NOT`.\n7. Sync Backend.\n\nExample \u2014 "a staff member only ever touches their own department\'s sales records" \u2014 after granting `Sales_Staff` select, insert, update and delete on `sales_record`, configure four conditions, each comparing that operation\'s own row branch `department_id` against the logged-in user\'s `department_id`. Configuring only select leaves the writes unrestricted.\n\nA batch of tool calls is all-or-nothing: one bad call discards every change in that batch. Send exploratory reads on their own \u2014 especially the first `BROWSE_DATA_BINDING_OPTIONS` for an operation whose context branch you have not seen \u2014 then batch the writes.\n\n### Assign the role\nA custom role does nothing until an account holds it. Two ways:\n- Manual: assign in the editor, under \u8BBE\u7F6E \u2192 \u6743\u9650\u7BA1\u7406.\n- Automatic: the Permissions node inside an Actionflow (e.g. grant VIP after purchase). These grants and revocations take effect immediately \u2014 no backend sync required.\n\n### Definition of done\nA permission task is finished only when all of these hold. Check them before reporting:\n1. Every operation you enabled is listed under its table\'s `rowConditions` in `GET_ROLE_DETAIL`, or is deliberately open.\n2. `GET_ROLE_DETAIL` on **Anonymous User** *and* **Logged-in User** shows no unintended grant on the tables you touched. A newly created table lands in every role automatically, with select, insert, update, delete, count and aggregate all granted and unconditioned \u2014 the two predefined roles included. Observed on a deployed project: an unauthenticated request could read every row, and after only SELECT was revoked it could still INSERT. Checking Anonymous User alone leaves every logged-in user holding the same open grant.\n3. Any custom role you created is actually assigned to someone.\n4. "Sync Backend" has run.\nIf you stop short of any of these, say so explicitly and name which grants are still open. Never report the permission work as complete.\n\n### Troubleshooting 403\n403s surface in runtime logs and client responses:\n```json\n{\n "errorCode": 403,\n "extensions": { "classification": "TABLE_ACCESS" },\n "message": "User 1 has no permission for SELECT on order"\n}\n```\n"User 1" is the user whose internal id ends in 1 (1000000000000001). Then:\n1. Confirm the user holds the role you expect.\n2. Read that role with `GET_TABLE_PERMISSION` on the table the 403 names: is the operation enabled, is the column inside its grant, and does its row condition match the row the user expected?\n3. Confirm "Sync Backend" ran after the last permission change.'},post:{available:!0,prompt:'## Permission System Domain Knowledge\nZion secures data and actions with RBAC (roles) plus ABAC (per-row conditions). Every tool in this plugin edits the project schema only \u2014 the change reaches the deployed backend when "Sync Backend" runs, which is the last step of any permission task.\n\n### Model\n- **Role**: a named collection of users. Two are predefined and cannot be renamed or deleted: **Logged-in User** (held by every authenticated user) and **Anonymous User** (unauthenticated requests). Custom roles can then be created, renamed, and deleted, up to the project\'s role limit \u2014 but **`Admin` is a reserved name**: a role is treated as system-defined by *name*, so one created or renamed to `Admin` could never be renamed or deleted again. Both tools refuse it; pick another name.\n- **Data Permission**: what a role may read or write, at table, column and row level.\n- **Action Permission**: which workspace HTTP APIs, Actionflows, AI agents and payment operations a role may invoke.\n- Each action block is allow-all or an explicit allow-list. On top of those grants, per-target conditional checks are available for Actionflows and AI agents; payments take allow-all or a payment-type/billing-method map.\n- **Roles only ever add.** A user\'s effective permissions are the union of every role they hold; a restrictive role never subtracts what a permissive one granted. To take access away, narrow or unassign the permissive role \u2014 never "add a limited role".\n\n### Activate first\nRole names come from `GET_PROJECT_OVERVIEW`\'s `roles` section, which also reports whether role permission is activated; `GET_ALL_ROLES_INFO` is the fallback when you have not run it. When either reports that role permission is not activated:\n- In BUILD or AUTO_ACCEPT mode, you MUST immediately call `ACTIVATE_ROLE_PERMISSION`, which seeds the predefined roles. BUILD uses the normal user-confirmation gate; AUTO_ACCEPT applies it immediately.\n- In RESEARCH mode, do not attempt a mutation; tell the user to look into permissions in \u8BBE\u7F6E \u2192 \u6743\u9650\u7BA1\u7406.\n\n### Grant\nData permissions are configured coarse \u2192 fine:\n1. **Table**: which operations (select / insert / update / delete / count / aggregate) the role may run.\n2. **Column**: which fields each operation covers.\n3. **Row**: a per-operation condition \u2014 a filter over existing rows for select, update and delete, a check on the incoming row for insert. Each one starts always-true, so a fresh grant is open until narrowed.\n\nRead before writing: `GET_ROLE_DETAIL`, naming every role the task will edit; the role names are already in `GET_PROJECT_OVERVIEW`. It reports each table by exception \u2014 the operations granted, the ones under `rowConditions` whose row condition has been narrowed, and `restrictedColumns` only where a grant covers less than the whole table, so an operation listed as granted and mentioned nowhere else is open on every column and every row. Tables the role cannot touch at all are named together in `tablesWithNoGrants`. Pass `blocks` when the task is about one block (the table block is nearly the whole payload). It does not carry the row conditions\' schema paths \u2014 when you are narrowing one, read `GET_TABLE_PERMISSION` instead: it names the tables you are about to change, reports each operation\'s condition path, and satisfies the same gate, so the path arrives in the call right before the one that uses it. Edit with `ADD_ROLES`, `UPDATE_ROLE`, `DELETE_ROLES` and the per-block setters `UPDATE_ROLE_TABLE_PERMISSION`, `UPDATE_ROLE_ACTION_FLOW_PERMISSION`, `UPDATE_ROLE_ZAI_PERMISSION`, `UPDATE_ROLE_PAYMENT_PERMISSION`, `UPDATE_ROLE_API_PERMISSION` for workspace HTTP APIs. Account insert/delete is unavailable, and `id` is pinned into every table SELECT grant.\n\nViews (the read-only saved queries the database plugin manages) are granted separately with `UPDATE_ROLE_VIEW_PERMISSION`: only select / count / aggregate exist, each with its column set and row condition, and a view no role has been granted cannot be queried by anyone. `GET_VIEW_PERMISSION` reports a view\'s condition paths the way `GET_TABLE_PERMISSION` does for tables.\n\n`allowAll` on `apiPermission`, `actionflowPermission` or `zAiPermission` also covers resources added later \u2014 prefer explicit allow-lists unless broad access is intentional.\n\n**Role, or a field on Account?** Use a role for static functional boundaries: who may run a flow, read a table, see a column. Add a field on the Account table for per-user state: VIP status, nickname, bio.\n\n**Never create one role per group.** For departments, stores, tenants or any other segmentation, use the relation-first pattern: create a `1:n` relation from the context table (e.g. `department`) to `Account`, and a second one from that same table to the business table (e.g. `sales_record`). Both foreign-key columns are generated and non-editable \u2014 never declare them as raw integer fields. Then define one generic role (`Sales_Staff`) and compare those two columns in its row conditions.\n\nSimple single-table CRUD may run directly from the frontend when table, column, and row permissions fully express the authorization policy \u2014 do not wrap it in an Actionflow. Reach for a Backend Actionflow only when the rule cannot be expressed that way at all: it needs server-held secrets, cross-table atomicity, or multi-step state transitions.\n\n### Row conditions (ABAC)\nNarrowing those conditions is a two-plugin job: this plugin has no tool that edits one \u2014 they live in the **bindings** area, whose tools are the `INSERT_CONDITION_BOOL_EXP` family, addressed by the condition path `GET_TABLE_PERMISSION` reports. The check `SET_ROLE_PERMISSION_CHECK` seeds for an Actionflow or AI agent works the same way.\n\nNever hand-build a permission schema path. It embeds the role\'s index in the schema and the table\'s internal id, neither of which any read reports on its own, so a path assembled from what a read did show resolves to nothing \u2014 copy the one a read returned.\n\nEach operation has its own condition node and its own row branch to compare against, so reusing the select recipe on another op fails:\n- `select` \u2192 path ends `/select/filter` \u2192 the branch holding the row being read\n- `insert` \u2192 path ends `/insert/check`, not `filter` \u2192 the branch holding the row being inserted\n- `update` \u2192 path ends `/update/filter` \u2192 the branch holding the row as stored, or the one holding the incoming values\n- `delete` \u2192 path ends `/delete/filter` \u2192 the branch holding the row being deleted\n- `count` / `aggregate` \u2192 no row branch exists, only the logged-in user and the current time, so they cannot be row-scoped. Whenever you narrow `select`, send `count` and `aggregate` `{enabled: false}` too, unless a whole-table count is meant to be public: a row-scoped `select` beside an open `count` still tells any user how many rows everyone else has.\n\nNarrowing one condition:\n1. `GET_TABLE_PERMISSION` for that table (or the result of `UPDATE_ROLE_TABLE_PERMISSION`, which reports the same paths for the grants it just made, or of `SET_ROLE_PERMISSION_CHECK` for a flow/agent check) \u2192 that operation\'s condition schema path. `GET_ROLE_DETAIL` does not carry them.\n2. `INSERT_CONDITION_BOOL_EXP` at that path \u2192 returns a `conditionSchemaPath`. Copy it verbatim; never hand-build one.\n3. `GET_EXPRESSION_CONDITION_OPERATORS` at that path, then `UPDATE_EXPRESSION_CONDITION_OPERATOR` with an operator copied verbatim. The `target` and `value` operand slots do not exist until the operator is set \u2014 binding first fails with "has no binding site at \u2026/target".\n4. Fill both operands at `<conditionSchemaPath>/target` and `<conditionSchemaPath>/value`, addressed by `pathInHierarchicalMenu`. Read that path \u2014 branch label included \u2014 from `BROWSE_DATA_BINDING_OPTIONS` at the operand\'s own schema path and copy it verbatim; never hand-build one. Relations traverse, so a child table can compare against its parent\'s owner \u2014 that path is four segments deep: context root, row branch, relation, column. Every segment is a label from the tree, including the root.\n5. Delete the always-true placeholder the grant started with: `DELETE_CONDITION_BOOL_EXP` at `<step 1\'s condition schema path>/_and/[0]` \u2014 the filter\'s own path, not the comparison path step 2 returned. Harmless at runtime, but the editor renders it as an empty condition row, so the user sees a half-configured rule.\n6. Shape multi-clause predicates with `NEST_CONDITION_BOOL_EXP`, `TOGGLE_CONDITION_BOOL_EXP_AND_OR`, `TOGGLE_CONDITION_BOOL_EXP_NOT`.\n7. Sync Backend.\n\nExample \u2014 "a staff member only ever touches their own department\'s sales records" \u2014 after granting `Sales_Staff` select, insert, update and delete on `sales_record`, configure four conditions, each comparing that operation\'s own row branch `department_id` against the logged-in user\'s `department_id`. Configuring only select leaves the writes unrestricted.\n\nA batch of tool calls is all-or-nothing: one bad call discards every change in that batch. Send exploratory reads on their own \u2014 especially the first `BROWSE_DATA_BINDING_OPTIONS` for an operation whose context branch you have not seen \u2014 then batch the writes.\n\n### Assign the role\nA custom role does nothing until an account holds it. Two ways:\n- Manual: assign in the editor, under \u8BBE\u7F6E \u2192 \u6743\u9650\u7BA1\u7406.\n- Automatic: the Permissions node inside an Actionflow (e.g. grant VIP after purchase). These grants and revocations take effect immediately \u2014 no backend sync required.\n\n### Definition of done\nA permission task is finished only when all of these hold. Check them before reporting:\n1. Every operation you enabled is listed under its table\'s `rowConditions` in `GET_ROLE_DETAIL`, or is deliberately open.\n2. `GET_ROLE_DETAIL` on **Anonymous User** *and* **Logged-in User** shows no unintended grant on the tables you touched. A newly created table lands in every role automatically, with select, insert, update, delete, count and aggregate all granted and unconditioned \u2014 the two predefined roles included. Observed on a deployed project: an unauthenticated request could read every row, and after only SELECT was revoked it could still INSERT. Checking Anonymous User alone leaves every logged-in user holding the same open grant.\n3. Any custom role you created is actually assigned to someone.\n4. "Sync Backend" has run.\nIf you stop short of any of these, say so explicitly and name which grants are still open. Never report the permission work as complete.\n\n### Troubleshooting 403\n403s surface in runtime logs and client responses:\n```json\n{\n "errorCode": 403,\n "extensions": { "classification": "TABLE_ACCESS" },\n "message": "User 1 has no permission for SELECT on order"\n}\n```\n"User 1" is the user whose internal id ends in 1 (1000000000000001). Then:\n1. Confirm the user holds the role you expect.\n2. Read that role with `GET_TABLE_PERMISSION` on the table the 403 names: is the operation enabled, is the column inside its grant, and does its row condition match the row the user expected?\n3. Confirm "Sync Backend" ran after the last permission change.'}},runtime:{pre:{available:!0,prompt:'## Verifying your own work\nThese tools run against the project\'s REAL backend. There is no staging copy, so prefer the primitives that undo themselves and reach for the ones that do not only when the check genuinely requires them.\n\nDraft versus deployed, which is the distinction that decides whether a green result means anything:\n- `runtime.debug_flow` and `runtime.run_code` execute the DRAFT \u2014 what you just edited \u2014 and revert their database writes by default. This is the verification loop.\n- `runtime.invoke_flow` executes the DEPLOYED version with permissions enforced and reverts nothing. A green invoke on a project with pending changes proves nothing about your edits; the result says so when that is the case.\n\nWhat "done" means here:\n- an action flow you built or changed is not done until `runtime.debug_flow` has run it and you have read the terminal node\'s output;\n- a permission change is not done until you have watched the rule act on data whose existence you are sure of. Reading once as a user proves nothing on its own: an empty result means either "the rule hid it" or "there was nothing there", and those need different fixes. Get a second observation, in this order of preference:\n 1. `runtime.login` with credentials the user gives you \u2014 a real account with its real roles, and the only way to test a rule that keys on a named role without permission to edit the project\'s backend. Ask for them; do not guess them.\n 2. `as: "admin"` alongside `as: "<role>"`, if this session has it. `admin` bypasses row and column permissions, so the pair reads as ground-truth-versus-user over data you did not create. Cheapest when it is available, and unavailable to a session that cannot edit the project\'s backend.\nNeither is open to a session with no credentials to hand, so say which rule you could not verify and why instead of reporting it done;\n- the identity tiers are not one axis, and a rule usually keys on which tier you are in rather than on who you are. Read the same data as each tier the rule is supposed to distinguish, and compare: `as: "anonymous"` sends no credential at all \u2014 a logged-out visitor, the only identity carrying the Anonymous User role, and where public data leaks; an account from `runtime.login` is signed in, carrying Logged-in User plus the project\'s own custom roles, which is a different rung and usually a different answer. Signed-out versus signed-in is the pair most often wrong, so run it whenever a rule claims to require a login;\n- if a check cannot be run, say which one and why. Never report work as verified because it looked right.\n\nWhen a run fails, its nodes carry a `traceId`: pass it to `logs.search` as `traceId: "\u2026"` to get the server-side detail.\n\n### Two filter grammars \u2014 do not mix them\nThe operator-first grammar documented above (`{"_eq": {"bigint_operand": {\u2026}}}`) is the RAW shape, for documents you hand-write and send with `runtime.graphql`. The typed tools \u2014 `runtime.query`, `runtime.aggregate`, `runtime.update`, `runtime.delete` \u2014 take the SIMPLIFIED shape instead: `{"column": {"_op": value}}`, e.g. `{"status": {"_eq": "PAID"}}`. Feeding the raw grammar to a typed tool, or the simplified one to a hand-written document, fails validation at the runtime rather than in the tool.\n\n### Names here are API names, never display names\nThe runtime GraphQL schema is generated from **API names** \u2014 `tableName`, every column in a field list, every key in a filter or a `set`. Every editor read gives you both: `database.get_tables_info` returns each column\'s `apiName` AND its `displayName`, and only the `apiName` is valid here. They diverge the moment anyone renames a column in the editor, which is routine and leaves no trace in the runtime, so a name you read in a UI, a page binding or a conversation is the wrong one until you have checked it against `apiName`. A display name sent here comes back as `Field \'<name>\' in type \'<table>\' is undefined`.\n\n### An enum column takes the option NAME\nIn the schema an enum option has an id and a name, and a binding stores the id. The runtime stores and matches the **name**: filter with `{"status": {"_eq": "PAID"}}`, never the `o1`-style option id you would write into a schema binding. Sending the id is rejected with `Invalid option: <id>, available option: \u2026`, which lists the names \u2014 use one of those verbatim.\n\n### Binary assets are ids, on the way in and on the way out\nImages, videos and files live in object storage; a table column holds only the asset id, never a URL or a path. That changes every side of a runtime call:\n- **Reading**: the column is an object in GraphQL, not a scalar, so selecting `cover_image` bare fails with "Subselection required for type \'FZ_Image\'". Ask for `cover_image_id`, or select a subfield \u2014 `cover_image { id url }`. The typed tools do this for you when they default a field list; hand-written `runtime.graphql` selections have to get it right. The list-valued media types are deprecated; if a project still has one, it reads as a `[col]_ids` array.\n- **Writing**: `runtime.insert` and `runtime.update` take the id column too \u2014 `{"cover_image_id": 1030\u2026}`, never `{"cover_image": "https://\u2026"}`. A URL in a media column is rejected, and a plausible-looking id you invented points at someone else\'s asset or at nothing.\n- **Getting an id**: an asset does not exist until its bytes have been uploaded, which is a two-step flow \u2014 request a presigned URL (`imagePresignedUrlV2` / `videoPresignedUrlV2` / `filePresignedUrlV2`, keyed by the file\'s Base64 MD5), then HTTP PUT the bytes to it. You can do the first step through `runtime.graphql` but **not the second**: no runtime tool sends raw bytes. Three ways to get a storable id, in order of preference: `web.import_asset` with `mode: RUNTIME`, which does both steps server-side from a public URL and hands back the numeric id; `runtime.query` on `fz_images` / `fz_videos` / `fz_files`, which lists the ids the app already holds; or asking the user. Never fabricate one \u2014 a plausible number points at another project\'s asset or at nothing, and the row looks written until someone opens it.\n- **Which id, though**: a data row stores the id the RUNNING APP holds, which is what those tables list and what `mode: RUNTIME` returns. Editor-side asset ids are a different space \u2014 an id taken from the editor and written into a row, or an app id bound to a component, resolves to nothing and reports no error either way.\n- **Importing at run time is a different problem**: `web.import_asset` runs now, while you are building. An app that has to turn a URL into an asset while it runs needs the **Files** action flow node, which does the same import inside a flow. Build that node into the flow rather than importing the file yourself and writing the id in.\n- `url` is a rendering detail: read it when you want to show or check an asset, and store the id everywhere else.\n\n### What runtime.graphql can reach\n`runtime.graphql` runs against the app\'s own API \u2014 the generated table operations, `fz_invoke_action_flow*`, `fz_action_flow_result`, the ZAI conversation operations, asset upload. The debug operations behind `runtime.debug_flow`, `runtime.run_code` and `zai.debug_chat` live on a separate admin surface those tools reach for you; asking for them through `runtime.graphql` reports the field as undefined. Subscriptions are unavailable from every tool here \u2014 poll the documented query counterpart instead.\n\n### Triggers\nThere is no fire-a-trigger tool, for anyone \u2014 the editor cannot do it either. A database trigger fires when a matching row is really written **and the transaction commits**, so a rollback debug run cannot fire one: the notification the runtime listens for is rolled back with everything else. To exercise a database trigger, write a row with `runtime.insert` or `runtime.update` that matches the trigger\'s table, operation and condition, then read what it did with `runtime.query` and `logs.search`. Your write is recorded so you can report it; the rows the trigger\'s own flow wrote in response are not, so name the trigger as well when you hand the run over. `runtime.status` lists the project\'s triggers with the table and operation each one watches, and a write to a triggered table says so in its confirmation.\n\nA schedule cannot be fired on demand at all. Verify the flow it points at with `runtime.debug_flow`, check the cron expression and end date as configuration, and tell the user the schedule itself is unverified.\n\n### What you leave behind\nNothing you write here can be taken back. There is no undo tool and no cleanup tool: a row from `runtime.insert`, an account from `runtime.as_user`, an overwritten column, a deleted row, and whatever a trigger did in response are all simply in the user\'s app now. That is the reason to reach for a rollback debug run first and to write only the fixtures a check genuinely needs.\n\nWhat you do owe the user is an account of it. Rows you inserted and accounts you created are recorded with their ids, and you are reminded of them as you work \u2014 finish a verification run by saying what you created and in which table, so they can delete it from the data table if they want to. "I added some test data" is not a handover; "I added order#41 and order#42, and account 9931 with role Customer" is.\n\nThe wire protocol for each of these calls \u2014 the query language, filter grammar, aggregations, action-flow and AI invocation, third-party calls and asset upload \u2014 is documented in the `baas-*` capabilities.'},post:{available:!0,prompt:'## Verifying your own work\nThese tools run against the project\'s REAL backend. There is no staging copy, so prefer the primitives that undo themselves and reach for the ones that do not only when the check genuinely requires them.\n\nDraft versus deployed, which is the distinction that decides whether a green result means anything:\n- `runtime.debug_flow` and `runtime.run_code` execute the DRAFT \u2014 what you just edited \u2014 and revert their database writes by default. This is the verification loop.\n- `runtime.invoke_flow` executes the DEPLOYED version with permissions enforced and reverts nothing. A green invoke on a project with pending changes proves nothing about your edits; the result says so when that is the case.\n\nWhat "done" means here:\n- an action flow you built or changed is not done until `runtime.debug_flow` has run it and you have read the terminal node\'s output;\n- a permission change is not done until you have watched the rule act on data whose existence you are sure of. Reading once as a user proves nothing on its own: an empty result means either "the rule hid it" or "there was nothing there", and those need different fixes. Get a second observation, in this order of preference:\n 1. `runtime.login` with credentials the user gives you \u2014 a real account with its real roles, and the only way to test a rule that keys on a named role without permission to edit the project\'s backend. Ask for them; do not guess them.\n 2. `as: "admin"` alongside `as: "<role>"`, if this session has it. `admin` bypasses row and column permissions, so the pair reads as ground-truth-versus-user over data you did not create. Cheapest when it is available, and unavailable to a session that cannot edit the project\'s backend.\nNeither is open to a session with no credentials to hand, so say which rule you could not verify and why instead of reporting it done;\n- the identity tiers are not one axis, and a rule usually keys on which tier you are in rather than on who you are. Read the same data as each tier the rule is supposed to distinguish, and compare: `as: "anonymous"` sends no credential at all \u2014 a logged-out visitor, the only identity carrying the Anonymous User role, and where public data leaks; an account from `runtime.login` is signed in, carrying Logged-in User plus the project\'s own custom roles, which is a different rung and usually a different answer. Signed-out versus signed-in is the pair most often wrong, so run it whenever a rule claims to require a login;\n- if a check cannot be run, say which one and why. Never report work as verified because it looked right.\n\nWhen a run fails, its nodes carry a `traceId`: pass it to `logs.search` as `traceId: "\u2026"` to get the server-side detail.\n\n### Two filter grammars \u2014 do not mix them\nThe operator-first grammar documented above (`{"_eq": {"bigint_operand": {\u2026}}}`) is the RAW shape, for documents you hand-write and send with `runtime.graphql`. The typed tools \u2014 `runtime.query`, `runtime.aggregate`, `runtime.update`, `runtime.delete` \u2014 take the SIMPLIFIED shape instead: `{"column": {"_op": value}}`, e.g. `{"status": {"_eq": "PAID"}}`. Feeding the raw grammar to a typed tool, or the simplified one to a hand-written document, fails validation at the runtime rather than in the tool.\n\n### Names here are API names, never display names\nThe runtime GraphQL schema is generated from **API names** \u2014 `tableName`, every column in a field list, every key in a filter or a `set`. Every editor read gives you both: `database.get_tables_info` returns each column\'s `apiName` AND its `displayName`, and only the `apiName` is valid here. They diverge the moment anyone renames a column in the editor, which is routine and leaves no trace in the runtime, so a name you read in a UI, a page binding or a conversation is the wrong one until you have checked it against `apiName`. A display name sent here comes back as `Field \'<name>\' in type \'<table>\' is undefined`.\n\n### An enum column takes the option NAME\nIn the schema an enum option has an id and a name, and a binding stores the id. The runtime stores and matches the **name**: filter with `{"status": {"_eq": "PAID"}}`, never the `o1`-style option id you would write into a schema binding. Sending the id is rejected with `Invalid option: <id>, available option: \u2026`, which lists the names \u2014 use one of those verbatim.\n\n### Binary assets are ids, on the way in and on the way out\nImages, videos and files live in object storage; a table column holds only the asset id, never a URL or a path. That changes every side of a runtime call:\n- **Reading**: the column is an object in GraphQL, not a scalar, so selecting `cover_image` bare fails with "Subselection required for type \'FZ_Image\'". Ask for `cover_image_id`, or select a subfield \u2014 `cover_image { id url }`. The typed tools do this for you when they default a field list; hand-written `runtime.graphql` selections have to get it right. The list-valued media types are deprecated; if a project still has one, it reads as a `[col]_ids` array.\n- **Writing**: `runtime.insert` and `runtime.update` take the id column too \u2014 `{"cover_image_id": 1030\u2026}`, never `{"cover_image": "https://\u2026"}`. A URL in a media column is rejected, and a plausible-looking id you invented points at someone else\'s asset or at nothing.\n- **Getting an id**: an asset does not exist until its bytes have been uploaded, which is a two-step flow \u2014 request a presigned URL (`imagePresignedUrlV2` / `videoPresignedUrlV2` / `filePresignedUrlV2`, keyed by the file\'s Base64 MD5), then HTTP PUT the bytes to it. You can do the first step through `runtime.graphql` but **not the second**: no runtime tool sends raw bytes. Three ways to get a storable id, in order of preference: `web.import_asset` with `mode: RUNTIME`, which does both steps server-side from a public URL and hands back the numeric id; `runtime.query` on `fz_images` / `fz_videos` / `fz_files`, which lists the ids the app already holds; or asking the user. Never fabricate one \u2014 a plausible number points at another project\'s asset or at nothing, and the row looks written until someone opens it.\n- **Which id, though**: a data row stores the id the RUNNING APP holds, which is what those tables list and what `mode: RUNTIME` returns. Editor-side asset ids are a different space \u2014 an id taken from the editor and written into a row, or an app id bound to a component, resolves to nothing and reports no error either way.\n- **Importing at run time is a different problem**: `web.import_asset` runs now, while you are building. An app that has to turn a URL into an asset while it runs needs the **Files** action flow node, which does the same import inside a flow. Build that node into the flow rather than importing the file yourself and writing the id in.\n- `url` is a rendering detail: read it when you want to show or check an asset, and store the id everywhere else.\n\n### What runtime.graphql can reach\n`runtime.graphql` runs against the app\'s own API \u2014 the generated table operations, `fz_invoke_action_flow*`, `fz_action_flow_result`, the ZAI conversation operations, asset upload. The debug operations behind `runtime.debug_flow`, `runtime.run_code` and `zai.debug_chat` live on a separate admin surface those tools reach for you; asking for them through `runtime.graphql` reports the field as undefined. Subscriptions are unavailable from every tool here \u2014 poll the documented query counterpart instead.\n\n### Triggers\nThere is no fire-a-trigger tool, for anyone \u2014 the editor cannot do it either. A database trigger fires when a matching row is really written **and the transaction commits**, so a rollback debug run cannot fire one: the notification the runtime listens for is rolled back with everything else. To exercise a database trigger, write a row with `runtime.insert` or `runtime.update` that matches the trigger\'s table, operation and condition, then read what it did with `runtime.query` and `logs.search`. Your write is recorded so you can report it; the rows the trigger\'s own flow wrote in response are not, so name the trigger as well when you hand the run over. `runtime.status` lists the project\'s triggers with the table and operation each one watches, and a write to a triggered table says so in its confirmation.\n\nA schedule cannot be fired on demand at all. Verify the flow it points at with `runtime.debug_flow`, check the cron expression and end date as configuration, and tell the user the schedule itself is unverified.\n\n### What you leave behind\nNothing you write here can be taken back. There is no undo tool and no cleanup tool: a row from `runtime.insert`, an account from `runtime.as_user`, an overwritten column, a deleted row, and whatever a trigger did in response are all simply in the user\'s app now. That is the reason to reach for a rollback debug run first and to write only the fixtures a check genuinely needs.\n\nWhat you do owe the user is an account of it. Rows you inserted and accounts you created are recorded with their ids, and you are reminded of them as you work \u2014 finish a verification run by saying what you created and in which table, so they can delete it from the data table if they want to. "I added some test data" is not a handover; "I added order#41 and order#42, and account 9931 with role Customer" is.\n\nThe wire protocol for each of these calls \u2014 the query language, filter grammar, aggregations, action-flow and AI invocation, third-party calls and asset upload \u2014 is documented in the `baas-*` capabilities.'}},secret:{pre:{available:!0,prompt:`## Secret Domain Knowledge
|
|
703
|
+
A secret is a named reference to a sensitive value (an API key, token, \u2026) that action flows
|
|
704
|
+
and API/TPA configs consume by handle rather than inlining the plaintext. Changes take effect
|
|
705
|
+
online only after "Sync Backend".
|
|
706
|
+
|
|
707
|
+
Always call GET_ALL_SECRET_CONFIGS before editing \u2014 it returns each secret's id, displayName,
|
|
708
|
+
description, and \`hasValue\` (whether an actual value handle is attached yet).
|
|
709
|
+
|
|
710
|
+
### Setting the plaintext value
|
|
711
|
+
You never handle the plaintext yourself. Call secret save-value with either \`secretId\` (an
|
|
712
|
+
existing secret from GET_ALL_SECRET_CONFIGS) or \`displayName\` (to create a new one): the editor
|
|
713
|
+
prompts the user to type the value, stores it, and attaches the resulting handle, after which
|
|
714
|
+
the secret reports \`hasValue: true\`. The value is entered in the editor and never passes
|
|
715
|
+
through the chat, so never ask the user to paste a secret value to you.
|
|
716
|
+
- ADD_SECRET_CONFIGS / UPDATE_SECRET_CONFIG take only the opaque \`secretKey\` handle (never plaintext);
|
|
717
|
+
use them to register/rename/retire entries or edit metadata when you are not setting a value.`},post:{available:!0,prompt:`## Secret Domain Knowledge
|
|
718
|
+
A secret is a named reference to a sensitive value (an API key, token, \u2026) that action flows
|
|
719
|
+
and workspace API configs consume by handle rather than inlining the plaintext. Changes take effect
|
|
720
|
+
online only after "Sync Backend".
|
|
721
|
+
|
|
722
|
+
Always call GET_ALL_SECRET_CONFIGS before editing \u2014 it returns each secret's id, displayName,
|
|
723
|
+
description, and \`hasValue\` (whether an actual value handle is attached yet).
|
|
724
|
+
|
|
725
|
+
### Setting the plaintext value
|
|
726
|
+
You never handle the plaintext yourself. Call secret save-value with either \`secretId\` (an
|
|
727
|
+
existing secret from GET_ALL_SECRET_CONFIGS) or \`displayName\` (to create a new one): the editor
|
|
728
|
+
prompts the user to type the value, stores it, and attaches the resulting handle, after which
|
|
729
|
+
the secret reports \`hasValue: true\`. The value is entered in the editor and never passes
|
|
730
|
+
through the chat, so never ask the user to paste a secret value to you.
|
|
731
|
+
- ADD_SECRET_CONFIGS / UPDATE_SECRET_CONFIG take only the opaque \`secretKey\` handle (never plaintext);
|
|
732
|
+
use them to register/rename/retire entries or edit metadata when you are not setting a value.`}},tpa:{pre:{available:!0,prompt:'## Third-Party API (TPA) Domain Knowledge\nA Third-Party API config is a saved external REST endpoint the project can call \u2014 from an action flow\'s "Call API" node or from Run Code via `context.callThirdPartyApi(apiId, params)`.\n\n### Anatomy of a config\n- **Endpoint**: a `url` (absolute, with scheme and host \u2014 the runtime has no base to resolve a relative path against) plus an HTTP `method` (GET/POST/PUT/DELETE) and an `operation` (`query` = read-only, `mutation` = state-changing). Optionally a request content type and a CA certificate (PEM, base64) for mutual TLS.\n- **Request parameters**: typed inputs sent with the call. Each has a `position`: `QUERY` (query string), `PATH` (URL path segment), `HEADER`, or `BODY`. A parameter whose type is `OBJECT` or `ARRAY` holds nested **children**.\n- **Response**: three branches keyed by outcome \u2014 `SUCCESS`, `PERMANENT_FAIL`, `TEMPORARY_FAIL`. Each branch carries a typed **response-data** tree describing the JSON the endpoint returns so downstream nodes can bind to its fields. `OBJECT`/`ARRAY` response data hold nested children.\n- **Paging** (optional): pagination config for list endpoints.\n\n### Data types\nTPA fields use the TPA type set, independent of the project\'s type-system setting: TEXT, INTEGER, BIGINT, FLOAT8, DECIMAL, BOOLEAN, IMAGE, OBJECT, ARRAY. For an ARRAY give its `itemType`; for an OBJECT or ARRAY add the field shape with the `ADD_TPA_PARAMETER_CHILDREN` / `ADD_TPA_RESPONSE_DATA_CHILDREN` tools.\n\n### The request body is a single parameter\nThe body is ONE root node, so a config may hold at most one `BODY` parameter \u2014 adding several top-level `BODY` params is rejected ("API cannot have more than one body param"). To send a JSON object body with several fields, add one `BODY` parameter of type `OBJECT` and put each field under it as a **child** via `ADD_TPA_PARAMETER_CHILDREN` (for a JSON array body use one `BODY` parameter of type `ARRAY`). The same holds for QUERY/PATH/HEADER: each is its own parameter, but only the body is capped at one. That single root `BODY` parameter must be named exactly `body` (not `request_body` or any other name): the runtime resolves the outgoing request body by that name, so a mis-named root leaves the body unresolved \u2014 it is sent as null and the call fails at run time with "json instance does not match json schema: null found, object expected". If you see that error on a request that has a body, check the root `BODY` parameter is named `body`.\n\n### An OBJECT / ARRAY node must be populated\nAn `OBJECT` or `ARRAY` parameter (or response-data node) is invalid while empty \u2014 a bare `OBJECT` is rejected ("field does not have any inner fields"). Immediately after adding one, model its shape: add its fields with `ADD_TPA_PARAMETER_CHILDREN` / `ADD_TPA_RESPONSE_DATA_CHILDREN` (an `ARRAY` needs at least its element/`itemType` defined) before relying on the config.\n\n### Workflow\nList configs with `GET_ALL_TPA_CONFIGS_INFO`, then `GET_TPA_CONFIG_DETAIL` to read a config\'s parameter and response `uniqueId`s \u2014 you pass these ids to the child tools. Create endpoints with `ADD_TPA_CONFIGS`; add request inputs with `ADD_TPA_CONFIG_PARAMETERS` (and `ADD_TPA_PARAMETER_CHILDREN` for object/array fields). Describe each response branch with `ADD_TPA_RESPONSE_DATA`, then `ADD_TPA_RESPONSE_DATA_CHILDREN` for nested fields. Configure list pagination with `SET_TPA_CONFIG_PAGING`. Editing a config creates a new version; "Sync Backend" is required for changes to take effect in production.\n\n### Model the response fields you consume\nA bare root OBJECT set with `ADD_TPA_RESPONSE_DATA` is NOT a finished response: nothing can bind typed values from it \u2014 flows only get the raw payload blob, and the API page shows an endpoint with no documented shape. After setting the root, ALWAYS model the fields your flows/bindings actually consume with `ADD_TPA_RESPONSE_DATA_CHILDREN` (from the API\'s docs or a sample response; nest children for the path you need, e.g. forecast \u2192 forecastday(ARRAY of OBJECT) \u2192 day(OBJECT) \u2192 avgtemp_c(DECIMAL)). Leaving the root unmodeled is acceptable ONLY when the entire payload is deliberately passed verbatim into a code/AI node \u2014 if you do that, state it explicitly in your read-back so the user knows it was a choice, not an omission.\n\n### Importing from an OpenAPI / Swagger spec\nTo onboard an existing API, prefer `tpa import-from-openapi` over hand-building configs: pass the spec as a `url` (fetched server-side; internal/private addresses are blocked) or paste it as `specText` (JSON or YAML). It creates each operation as a full TPA endpoint \u2014 parameters, body, and success/fail response shape \u2014 in one call, capped at 25 endpoints (use `pathsFilter` to scope larger specs); a failed import is rolled back. If the spec declares no absolute server URL the imported configs get relative urls \u2014 fix each with `UPDATE_TPA_CONFIG` using the base URL from the documentation. When you only have a human-readable docs page, `tpa fetch-doc` retrieves it and lets you explore the documentation iteratively: follow the returned same-site `pageLinks`, keep reading long pages with `offset`, and watch `specLinks` for a machine-readable spec to import. If no spec exists, author the configs with the granular tools above from what you read.'},post:{available:!1,prompt:null}},type:{pre:{available:!1,prompt:null},post:{available:!0,prompt:"## Type System Domain Knowledge\nThe type system owns named, reusable types: enums and custom objects. Data model changes require \"Sync Backend\" to take effect online.\n\n### Enums\nAn enum and each of its options carry a permanent id. The platform assigns it \u2014 never send one \u2014 and every create returns the minted ids in its result. An id is never editable afterwards, which is what keeps every column and binding that references it valid. Reference an enum as a column type in the 'database' plugin by the exact canonical identifier `u:e:<enumId>` \u2014 include the `u:e:` prefix (for example, `u:e:OrderStatus`).\n- An option's id is the value a column's default and any binding stores, so it is the id you carry to the other plugins, not the name.\n- An option's `name` is the only part of an option you can edit, and it is an identifier: letters, digits and underscores only, never starting with a digit (`PENDING`, `in_progress`). It is the enum literal the live database column holds once the project is deployed, so a name carrying spaces, hyphens or non-ASCII words is rejected outright \u2014 by the editor and by these tools alike. Non-blank, \u2264200 chars.\n- An enum's displayName is where the user-facing wording goes instead; options have none of their own, only the identifier above. Use a natural Chinese phrase (e.g. enum displayName \"\u8BA2\u5355\u72B6\u6001\"). The ids and the option names stay English as above. Non-blank, \u2264200 chars. An enum also takes an optional description; options take none.\n\nOperations:\n- `GET_ALL_ENUM_DEFINITIONS`: list enums with their options. Editing an enum requires having read it first \u2014 this listing reads every enum at once.\n- `GET_ENUM_DEFINITION_DETAIL`: read one enum by id, each option with the client platforms that accept it. This satisfies that requirement for that enum alone, so an edit to a known enum needs only this call. Check an option's `platforms` before wiring it into an action: an action carrying an option is invalid on a client whose platform is missing from it.\n- `ADD_ENUM_DEFINITIONS`: create enums with their initial options inline.\n- `UPDATE_ENUM_DEFINITIONS`: change an enum's own displayName / description. Omitted fields are unchanged. Its `options` argument REPLACES the whole option list, so use the per-option tools below for single-option edits.\n- `ADD_ENUM_OPTIONS` / `UPDATE_ENUM_OPTIONS` / `DELETE_ENUM_OPTIONS`: append options, rename them, or remove them.\n\nAdding an option is always safe. Deleting an enum or an option is destructive: anything referencing it breaks, and nothing repoints it for you \u2014 check usages, delete or repoint the columns first, and tell the user. There is no way to change an id, so a \"rename\" of an id means delete + recreate with the same breakage; if the user only wants different wording, edit the enum's displayName instead and the id can stay.\n\nIf a column should use a new enum, create the enum here first, in the same turn and before the column: take the minted id out of the create result and the column can reference `u:e:<thatId>` straight away.\n\n### Custom Objects\nCustom object types are named, reusable structured types (a set of typed fields), referenced elsewhere by the identifier `u:o:<typeId>` (action-flow inputs/outputs, other types' fields, and other type slots).\n\nOperations:\n- `GET_ALL_OBJECT_DEFINITIONS`: list object types with their fields. Editing a type requires having read it first \u2014 this listing reads every type at once.\n- `GET_OBJECT_TYPE_DEFINITION_DETAIL`: read one object type by id, its fields resolved to the same readable type names as the listing. This satisfies that requirement for that type alone, so an edit to a known type needs only this call.\n- `GET_TYPE_DEFINITION_FIELD_SELECTABLE_TYPES`: the types a field of an object type accepts, with the exact `typeIdentifier` to write.\n- `ADD_OBJECT_TYPE_DEFINITIONS`: create object types, each with a displayName and its initial fields. Ids are assigned by the platform and returned in the result \u2014 do not send one.\n- `UPDATE_OBJECT_TYPE_DEFINITIONS`: update a type's own displayName / description / private flag only (omitted fields are unchanged).\n- `ADD_TYPE_DEFINITION_FIELDS` / `UPDATE_TYPE_DEFINITION_FIELDS` / `DELETE_TYPE_DEFINITION_FIELDS`: add fields, rename or retype existing ones, or remove them.\n- `REORDER_TYPE_DEFINITION_FIELDS`: set the order the type's fields are rendered and emitted in \u2014 pass every field name, in the order wanted.\n- `COPY_PRIVATE_OBJECT_TYPE_AS_PUBLIC` / `COPY_PUBLIC_OBJECT_TYPE_AS_PRIVATE`: copy a type between the shared list and a single feature (see below).\n\nA field's type is a `typeIdentifier`: `s:p:<primitive>` (string, bigint, decimal, boolean, timestamptz, timetz, date, jsonb, image, video, file, geo_point), or `u:o:<typeId>` / `u:e:<enumId>` for a nested object or enum type. Read that shape to recognise what comes back, but never assemble one \u2014 pick the identifier out of `GET_TYPE_DEFINITION_FIELD_SELECTABLE_TYPES` and copy it verbatim, since one that names nothing, or a type this slot does not take, is rejected. Arrays are not listed \u2014 the nesting has no end \u2014 so a list field is that same identifier with the field's `arrayLevel` set (1 = list, 2 = list of lists), never brackets written into the identifier.\n\nRename and retype through `UPDATE_TYPE_DEFINITION_FIELDS` rather than delete + re-add: a rename carries the field's references along with it, where a re-add breaks every one of them. Retyping away from an image / video / file or JSON type still drops the references, because nothing that pointed at the old shape can read the new one \u2014 check usages and warn the user first. Deleting a field, or a type that is still referenced, breaks those references the same way.\n\n### Shared vs feature-owned object types\nA public type is an entry in the project's shared object type list. A private one belongs to a single feature \u2014 a webhook request body, an API JSON body, an action flow's output \u2014 and is not listed. Do NOT flip `private` with `UPDATE_OBJECT_TYPE_DEFINITIONS` to share or unshare a shape: that MOVES the type the feature is already using, so the feature's contract silently becomes an editor-listed type everything else can bind to (or stops being one). Copy instead:\n- `COPY_PRIVATE_OBJECT_TYPE_AS_PUBLIC`: put a copy of a private type into the shared list, leaving the feature on the original. Read `GET_OBJECT_TYPE_DEFINITION_GROUPS` first \u2014 the copy joins that configuration.\n- `COPY_PUBLIC_OBJECT_TYPE_AS_PRIVATE`: take a feature-owned copy of a shared type, so that one feature can diverge without changing the shape for everyone else.\n\nEither way the copy is a NEW type with a new id, and nothing points at it yet: the feature keeps using the old type until you set that slot's type to the `typeIdentifier` the result echoes."}},webhook:{pre:{available:!0,prompt:`## Webhook Domain Knowledge
|
|
733
|
+
A webhook is a public HTTP endpoint that fires an action flow every time it is called; the
|
|
734
|
+
URL ends with the webhook's generated uniqueId. Only custom webhooks are authorable here \u2014
|
|
735
|
+
payment-provider callbacks (Alipay / WeChat / Stripe / \u2026) come back with \`managed: true\` and
|
|
736
|
+
cannot be edited or deleted. Changes take effect online only after "Sync Backend".
|
|
737
|
+
|
|
738
|
+
Always call GET_ALL_CALLBACKS_INFO (and GET_CALLBACK_DETAIL for one) before editing.
|
|
739
|
+
|
|
740
|
+
### Creating a webhook
|
|
741
|
+
1. Pick the action flow the webhook fires: an id from GET_ALL_ACTION_FLOWS_INFO. The bound
|
|
742
|
+
flow cannot be changed later \u2014 to re-point a webhook, delete it and create a new one.
|
|
743
|
+
2. ADD_CALLBACK_TRIGGERS with that actionFlowId (optional display name); the webhook is enabled
|
|
744
|
+
immediately.
|
|
745
|
+
3. Describe the incoming request body so the payload can feed the flow's inputs:
|
|
746
|
+
- SET_CALLBACK_REQUEST_PARAMETERS with a field tree describing the payload. Its fields become
|
|
747
|
+
binding sources for the flow's input args.
|
|
748
|
+
- CLEAR_CALLBACK_REQUEST_BODY empties it again.
|
|
749
|
+
4. The bound flow's input args start as empty bindings \u2014 fill each with the bindings plugin's
|
|
750
|
+
CREATE_*_BINDING tools at the schemaPaths echoed by GET_CALLBACK_DETAIL (bind them to the
|
|
751
|
+
request-body fields).
|
|
752
|
+
|
|
753
|
+
### The response
|
|
754
|
+
A webhook answers its caller, and GET_CALLBACK_DETAIL reports that half as \`responseBody\`.
|
|
755
|
+
SET_CALLBACK_RESPONSE_FORMAT picks the content type and REPLACES the body with an empty one of
|
|
756
|
+
that format, so set the format first:
|
|
757
|
+
- \`TEXT_PLAIN\` / \`TEXT_HTML\` answer with a single string \u2014 bind it with the bindings plugin's
|
|
758
|
+
CREATE_*_BINDING tools at the schemaPath the result echoes.
|
|
759
|
+
- \`APPLICATION_JSON\` answers with a structure \u2014 SET_CALLBACK_RESPONSE_BODY_FIELDS with a field
|
|
760
|
+
tree, then bind each field's value at the schemaPaths the result echoes.
|
|
761
|
+
- CLEAR_CALLBACK_RESPONSE_BODY empties the response body again.
|
|
762
|
+
|
|
763
|
+
### Editing
|
|
764
|
+
UPDATE_CALLBACK_TRIGGER changes only the display name and/or the enabled flag. DELETE_CALLBACK_TRIGGERS
|
|
765
|
+
removes custom webhooks by uniqueId. Both fail on managed payment-provider callbacks.
|
|
766
|
+
|
|
767
|
+
SET_CALLBACK_TYPE is a different thing entirely: it switches the endpoint from a
|
|
768
|
+
custom webhook (\`DEFAULT\`) to a payment provider's notification receiver, which RESETS both
|
|
769
|
+
bodies to that provider's fixed shape and loses whatever was configured. Only reach for it
|
|
770
|
+
when the user wants this endpoint to receive a provider's callbacks; the provider has to be
|
|
771
|
+
activated for the project first.`},post:{available:!0,prompt:`## Webhook Domain Knowledge
|
|
772
|
+
A webhook is a public HTTP endpoint that fires an action flow every time it is called; the
|
|
773
|
+
URL ends with the webhook's generated uniqueId. Only custom webhooks are authorable here \u2014
|
|
774
|
+
payment-provider callbacks (Alipay / WeChat / Stripe / \u2026) come back with \`managed: true\` and
|
|
775
|
+
cannot be edited or deleted. Changes take effect online only after "Sync Backend".
|
|
776
|
+
|
|
777
|
+
Always call GET_ALL_CALLBACKS_INFO (and GET_CALLBACK_DETAIL for one) before editing.
|
|
778
|
+
|
|
779
|
+
### Creating a webhook
|
|
780
|
+
1. Pick the action flow the webhook fires: an id from GET_ALL_ACTION_FLOWS_INFO. The bound
|
|
781
|
+
flow cannot be changed later \u2014 to re-point a webhook, delete it and create a new one.
|
|
782
|
+
2. ADD_CALLBACK_TRIGGERS with that actionFlowId (optional display name); the webhook is enabled
|
|
783
|
+
immediately.
|
|
784
|
+
3. Describe the incoming request body so the payload can feed the flow's inputs:
|
|
785
|
+
- SET_CALLBACK_REQUEST_TYPE pointing at an object type id (from GET_ALL_OBJECT_DEFINITIONS, or one
|
|
786
|
+
you just made with ADD_OBJECT_TYPE_DEFINITIONS). Its fields become binding sources for
|
|
787
|
+
the flow's input args.
|
|
788
|
+
- CLEAR_CALLBACK_REQUEST_BODY empties it again.
|
|
789
|
+
4. The bound flow's input args start as empty bindings \u2014 fill each with the bindings plugin's
|
|
790
|
+
CREATE_*_BINDING tools at the schemaPaths echoed by GET_CALLBACK_DETAIL (bind them to the
|
|
791
|
+
request-body fields).
|
|
792
|
+
|
|
793
|
+
### The response
|
|
794
|
+
A webhook answers its caller, and GET_CALLBACK_DETAIL reports that half as \`responseBody\`.
|
|
795
|
+
SET_CALLBACK_RESPONSE_FORMAT picks the content type and REPLACES the body with an empty one of
|
|
796
|
+
that format, so set the format first:
|
|
797
|
+
- \`TEXT_PLAIN\` / \`TEXT_HTML\` answer with a single string \u2014 bind it with the bindings plugin's
|
|
798
|
+
CREATE_*_BINDING tools at the schemaPath the result echoes.
|
|
799
|
+
- \`APPLICATION_JSON\` answers with a structure \u2014 SET_CALLBACK_RESPONSE_BODY_TYPE pointing at an
|
|
800
|
+
object type id (from GET_ALL_OBJECT_DEFINITIONS), then bind its value at the schemaPath the result
|
|
801
|
+
echoes.
|
|
802
|
+
- CLEAR_CALLBACK_RESPONSE_BODY empties the response body again.
|
|
803
|
+
|
|
804
|
+
### Editing
|
|
805
|
+
UPDATE_CALLBACK_TRIGGER changes only the display name and/or the enabled flag. DELETE_CALLBACK_TRIGGERS
|
|
806
|
+
removes custom webhooks by uniqueId. Both fail on managed payment-provider callbacks.
|
|
807
|
+
|
|
808
|
+
SET_CALLBACK_TYPE is a different thing entirely: it switches the endpoint from a
|
|
809
|
+
custom webhook (\`DEFAULT\`) to a payment provider's notification receiver, which RESETS both
|
|
810
|
+
bodies to that provider's fixed shape and loses whatever was configured. Only reach for it
|
|
811
|
+
when the user wants this endpoint to receive a provider's callbacks; the provider has to be
|
|
812
|
+
activated for the project first.
|
|
813
|
+
|
|
814
|
+
### Values that cannot travel as themselves
|
|
815
|
+
A media field, or an object field carried as a JSON string, needs a conversion before it can
|
|
816
|
+
go over HTTP, and a media field without one leaves the webhook incomplete.
|
|
817
|
+
GET_CALLBACK_CODEC_OPTIONS lists exactly which slots of the request and response bodies need one
|
|
818
|
+
and which conversions each allows; feed a slot's \`typeIdentifier\` / \`field\` back to
|
|
819
|
+
SET_CALLBACK_CODECS verbatim, and DELETE_CALLBACK_CODECS to remove one. A slot is a field of a type,
|
|
820
|
+
not a path \u2014 the same object type reused twice shares one conversion.`}},zai:{pre:{available:!0,prompt:'## AI Agent (ZAI) Domain Knowledge\nA ZAI config is an LLM-backed agent the app runs via a "Run AI" action / action-flow node (asynchronous only). An agent has a name + description, a model, sampling settings (temperature, maxRound, max output tokens), a system + user **prompt**, and its **output**.\n\n### Reading\n`GET_ZAI_MODEL_OPTIONS` returns the models currently selectable in this project. `GET_ALL_ZAI_CONFIGS_INFO` summarizes every agent; `GET_ZAI_CONFIG_DETAIL` returns one agent\'s full config \u2014 its input args (with their map keys), its prompt components each with the **schema path** of its text binding, its output config and structured-output fields, its database/API contexts (with the query schema paths for the request-filter tools), its knowledge base, and its callable tools.\n\n### Creating & editing\n`ADD_ZAI_CONFIGS` seeds an agent with default empty system + user prompts and plain-text output; adding the first agent also provisions the AI conversation tables/relations/permissions. Edit scalar config (name, description, temperature, maxRound) with `UPDATE_ZAI_CONFIG`. The **model** is required when creating an agent and can be changed via `UPDATE_ZAI_CONFIG`. Call `GET_ZAI_MODEL_OPTIONS` first. If the user did not name a model, choose a selectable model whose capabilities fit the request; prefer the one whose `defaultModel` is true, which matches the editor\'s default. Only models the deployment ships as SYSTEM ever carry that marker \u2014 a project whose catalog is all custom models has none, so treat it as a tie-breaker rather than the thing you look for. Copy its exact `customModelIdentifier` ({id, namespace}). Never fabricate or omit the identifier.\n\n### Verifying an agent\nAn agent you built or changed is not done until you have run it and read what it answered: a prompt that reads well is not a prompt that works, and structured output is where the difference usually shows. Inside the editor, `zai.debug_chat` runs the DRAFT agent with the input arguments you give it and returns each turn\'s output \u2014 the same debug run the editor\'s agent tester performs. It needs the editor\'s draft, so it is unavailable outside it; from elsewhere, invoke the DEPLOYED agent through the runtime API instead. Either way each run is a real model call against the project\'s AI allowance, so choose the inputs deliberately rather than looping.\n\n`structuredOutput: true` in `GET_ZAI_MODEL_OPTIONS` is what the model\'s descriptor claims, not something the platform enforces. A model advertising it can still answer with the JSON Schema envelope it was handed instead of an instance of it \u2014 `{"type":"object","properties":{\u2026}}` where you expected `{"scene":"\u2026"}` \u2014 and nothing downstream rejects that, so the agent looks configured and every consumer of its output is wrong. Read one real answer before building on the shape.\n\n### Prompts are bindings, not a ZAI tool\nA prompt\'s text is an ordinary data binding. Read its `valueSchemaPath` from `GET_ZAI_CONFIG_DETAIL` and edit it with the bindings plugin (the CREATE_*_BINDING tools) at that path \u2014 there is no ZAI prompt-edit tool.\n\nAn agent\'s own input args are not top-level options: they hang off `Input`, so the menuPath is `["Context", "Input", "<arg name>"]`, beside `Logged in user` and `Current time`. Binding `["Context", "<arg name>"]` fails with "Can not find option \u2026 in [Logged in user, Current time, Input]", which reads like the arg does not exist rather than like it is one level further down. `BROWSE_DATA_BINDING_OPTIONS` renders the arg under `Input`, but read the level off its menuPath rather than off the indentation.\n\n### System AI conversation tables\nCreating the first agent provisions four protected system tables that store agent runs. They are platform-managed (read-only \u2014 never add fields to or edit them; for a user-facing chat feature build your own tables instead). Their individual roles, in a 1:n chain:\n- `conversation` \u2014 a chat thread with an agent, owned by an account (account \u2192 conversations).\n- `message` \u2014 one turn within a conversation (conversation \u2192 messages); also linked to its account.\n- `message_content` \u2014 a single content block of a message: text or media, image / video / file (message \u2192 contents).\n- `tool_usage_record` \u2014 a record of one tool call made while producing a message, including any error (message \u2192 tool_calls).\n\n### Giving the agent context (what it can read)\nBeyond its prompt, an agent reads context \u2014 all shown by `GET_ZAI_CONFIG_DETAIL`:\n- **Database tables** \u2014 `ADD_ZAI_CONFIG_DB_CONTEXTS` (`UPDATE_ZAI_CONFIG_DB_CONTEXT` / `DELETE_ZAI_CONFIG_DB_CONTEXTS`). Each is a per-table query with column/relation selection; narrow which rows it sees by editing the query\'s `filters` with the request-filter tools at the `querySchemaPath` from `GET_ZAI_CONFIG_DETAIL`.\n- **Knowledge base** \u2014 existing knowledge-base files and retrieval settings are shown by `GET_ZAI_CONFIG_DETAIL`, but Copilot cannot mutate them. Ask the user to manage them in the editor.\n- **External APIs** \u2014 an external-API context; the tool is generation-specific (see the input-args section below).\n\n### Giving the agent tools (what it can call)\n`ADD_ZAI_CONFIG_TOOLS` lets the agent call action flows, external APIs, or other agents (`UPDATE_ZAI_CONFIG_TOOL` / `DELETE_ZAI_CONFIG_TOOLS`). The tool for tuning a callable tool\'s per-input descriptions is generation-specific (see the input-args section below).\n### Passing multiple images into an image-list input\nAn image input with `arrayLevel: 1` is the only list input in the legacy type system. Fill it where the agent is invoked: in the calling action flow\'s Run-AI node, bind the images with an **array-mapping** formula at the input\'s schema path. The agent then runs once over the complete image list.\n### Typed input args & output (legacy type system)\n\n**Input args**: each input arg\'s `type` must be one of these legacy scalar tokens (copy the\nexact `type` value from `GET_ZAI_CONFIG_SELECTABLE_TYPES`; never hand-build it):\n- `TEXT` (string)\n- `BIGINT` (integer)\n- `DECIMAL`\n- `BOOLEAN`\n- `DATE`\n- `TIMETZ` (time with timezone)\n- `TIMESTAMPTZ` (date-time with timezone)\n- `IMAGE`\n- `VIDEO`\n- `FILE`\nInput args are scalar, with ONE exception: an **image** arg may be a list by passing `arrayLevel: 1`\n(multi-image intake \u2014 the only list input a ZAI agent accepts; see "Passing a list into an input arg"\nabove). Do not pass `arrayLevel` for any other type, and do not pick a table / object / enum / union\ntype; those are rejected.\n\n**Output**: an agent returns plain text unless you make it structured \u2014 which is tool-driven here (no\neditor step needed). Call `UPDATE_ZAI_CONFIG_OUTPUT_MODE` to switch to structured output, then define the object\nshape with `ADD_ZAI_CONFIG_OUTPUT_FIELDS` (and `UPDATE_ZAI_CONFIG_OUTPUT_FIELD` / `DELETE_ZAI_CONFIG_OUTPUT_FIELDS`); each field\'s\ntype is a basic scalar, a nested object, or an array of those. Switching back to plain text with\n`UPDATE_ZAI_CONFIG_OUTPUT_MODE` drops the structured type and every field on it.\n\n**Context & tools**: external-API context here is Third-Party APIs \u2014 `ADD_ZAI_CONFIG_TPA_CONTEXTS`\n(`UPDATE_ZAI_CONFIG_TPA_CONTEXT` / `DELETE_ZAI_CONFIG_TPA_CONTEXTS`). Tune a callable tool\'s per-input descriptions with\n`UPDATE_ZAI_CONFIG_TOOL_FIELD_DESCRIPTIONS`.'},post:{available:!0,prompt:'## AI Agent (ZAI) Domain Knowledge\nA ZAI config is an LLM-backed agent the app runs via a "Run AI" action / action-flow node (asynchronous only). An agent has a name + description, a model, sampling settings (temperature, maxRound, max output tokens), a system + user **prompt**, and its **output**.\n\n### Reading\n`GET_ZAI_MODEL_OPTIONS` returns the models currently selectable in this project. `GET_ALL_ZAI_CONFIGS_INFO` summarizes every agent; `GET_ZAI_CONFIG_DETAIL` returns one agent\'s full config \u2014 its input args (with their map keys), its prompt components each with the **schema path** of its text binding, its output config and structured-output fields, its database/API contexts (with the query schema paths for the request-filter tools), its knowledge base, and its callable tools.\n\n### Creating & editing\n`ADD_ZAI_CONFIGS` seeds an agent with default empty system + user prompts and plain-text output; adding the first agent also provisions the AI conversation tables/relations/permissions. Edit scalar config (name, description, temperature, maxRound) with `UPDATE_ZAI_CONFIG`. The **model** is required when creating an agent and can be changed via `UPDATE_ZAI_CONFIG`. Call `GET_ZAI_MODEL_OPTIONS` first. If the user did not name a model, choose a selectable model whose capabilities fit the request; prefer the one whose `defaultModel` is true, which matches the editor\'s default. Only models the deployment ships as SYSTEM ever carry that marker \u2014 a project whose catalog is all custom models has none, so treat it as a tie-breaker rather than the thing you look for. Copy its exact `customModelIdentifier` ({id, namespace}). Never fabricate or omit the identifier.\n\n### Verifying an agent\nAn agent you built or changed is not done until you have run it and read what it answered: a prompt that reads well is not a prompt that works, and structured output is where the difference usually shows. Inside the editor, `zai.debug_chat` runs the DRAFT agent with the input arguments you give it and returns each turn\'s output \u2014 the same debug run the editor\'s agent tester performs. It needs the editor\'s draft, so it is unavailable outside it; from elsewhere, invoke the DEPLOYED agent through the runtime API instead. Either way each run is a real model call against the project\'s AI allowance, so choose the inputs deliberately rather than looping.\n\n`structuredOutput: true` in `GET_ZAI_MODEL_OPTIONS` is what the model\'s descriptor claims, not something the platform enforces. A model advertising it can still answer with the JSON Schema envelope it was handed instead of an instance of it \u2014 `{"type":"object","properties":{\u2026}}` where you expected `{"scene":"\u2026"}` \u2014 and nothing downstream rejects that, so the agent looks configured and every consumer of its output is wrong. Read one real answer before building on the shape.\n\n### Prompts are bindings, not a ZAI tool\nA prompt\'s text is an ordinary data binding. Read its `valueSchemaPath` from `GET_ZAI_CONFIG_DETAIL` and edit it with the bindings plugin (the CREATE_*_BINDING tools) at that path \u2014 there is no ZAI prompt-edit tool.\n\nAn agent\'s own input args are not top-level options: they hang off `Input`, so the menuPath is `["Context", "Input", "<arg name>"]`, beside `Logged in user` and `Current time`. Binding `["Context", "<arg name>"]` fails with "Can not find option \u2026 in [Logged in user, Current time, Input]", which reads like the arg does not exist rather than like it is one level further down. `BROWSE_DATA_BINDING_OPTIONS` renders the arg under `Input`, but read the level off its menuPath rather than off the indentation.\n\n### System AI conversation tables\nCreating the first agent provisions four protected system tables that store agent runs. They are platform-managed (read-only \u2014 never add fields to or edit them; for a user-facing chat feature build your own tables instead). Their individual roles, in a 1:n chain:\n- `conversation` \u2014 a chat thread with an agent, owned by an account (account \u2192 conversations).\n- `message` \u2014 one turn within a conversation (conversation \u2192 messages); also linked to its account.\n- `message_content` \u2014 a single content block of a message: text or media, image / video / file (message \u2192 contents).\n- `tool_usage_record` \u2014 a record of one tool call made while producing a message, including any error (message \u2192 tool_calls).\n\n### Giving the agent context (what it can read)\nBeyond its prompt, an agent reads context \u2014 all shown by `GET_ZAI_CONFIG_DETAIL`:\n- **Database tables** \u2014 `ADD_ZAI_CONFIG_DB_CONTEXTS` (`UPDATE_ZAI_CONFIG_DB_CONTEXT` / `DELETE_ZAI_CONFIG_DB_CONTEXTS`). Each is a per-table query with column/relation selection; narrow which rows it sees by editing the query\'s `filters` with the request-filter tools at the `querySchemaPath` from `GET_ZAI_CONFIG_DETAIL`.\n- **Knowledge base** \u2014 existing knowledge-base files and retrieval settings are shown by `GET_ZAI_CONFIG_DETAIL`, but Copilot cannot mutate them. Ask the user to manage them in the editor.\n- **External APIs** \u2014 an external-API context; the tool is generation-specific (see the input-args section below).\n\n### Giving the agent tools (what it can call)\n`ADD_ZAI_CONFIG_TOOLS` lets the agent call action flows, external APIs, or other agents (`UPDATE_ZAI_CONFIG_TOOL` / `DELETE_ZAI_CONFIG_TOOLS`). The tool for tuning a callable tool\'s per-input descriptions is generation-specific (see the input-args section below).\n### Passing a list into a list-typed input arg\nTo declare a list input, choose a base type from `GET_ZAI_CONFIG_SELECTABLE_TYPES` and set `arrayLevel: 1` (or `arrayLevel: 2` for a list of lists). Fill it where the agent is invoked. In the calling action flow\'s Run-AI node, bind it with an **array-mapping** formula at the input\'s schema path. The agent then runs once over the whole list.\n### Typed input args, output & context (refactored type system enabled)\nDeclare typed inputs with `ADD_ZAI_CONFIG_INPUT_ARGS` (and `UPDATE_ZAI_CONFIG_INPUT_ARGS` / `DELETE_ZAI_CONFIG_INPUT_ARGS`). Each\narg\'s `type` is a `typeIdentifier` copied verbatim from `GET_ZAI_CONFIG_SELECTABLE_TYPES` \u2014 primitives, tables,\nand custom object/enum types are all selectable; `arrayLevel` wraps it as a list (1) or list-of-lists\n(2), for any element type (a list of image is the common multi-image intake \u2014 see "Passing a list into\nan input arg" above). Configure output with `UPDATE_ZAI_CONFIG_OUTPUT`: `isStructured=false` for plain streamed text, or\n`isStructured=true` with an `outputType` (a `typeIdentifier` from `GET_ZAI_CONFIG_SELECTABLE_TYPES`) for a typed\nobject \u2014 for a bespoke object shape, define the object type first with the type-system tools, then\nselect its `typeIdentifier`.\nExternal-API context here is workspace HTTP APIs: `ADD_ZAI_CONFIG_API_CONTEXTS` (`UPDATE_ZAI_CONFIG_API_CONTEXT` /\n`DELETE_ZAI_CONFIG_API_CONTEXTS`). Tune a callable tool\'s per-input descriptions with\n`UPDATE_ZAI_CONFIG_TOOL_DESCRIPTION_CONFIGS`.'}}},jg={"query-language":`## Querying Zion data (auto-generated GraphQL over PostgreSQL)
|
|
821
|
+
The schema is generated from the data model \u2014 introspect the live schema before assuming exact
|
|
822
|
+
fields/enums. Each table [table] generates:
|
|
823
|
+
- Queries: [table] (list; where/order_by/distinct_on/limit/offset), [table]_by_pk (by id),
|
|
824
|
+
[table]_aggregate (count/sum/avg/min/max), [table]_group_by. A geo_point column adds
|
|
825
|
+
fz_[table]_by_[column] (proximity search); Relay pagination adds a Connection_[table] query.
|
|
826
|
+
- Mutations: insert_[table] / insert_[table]_one (nested inserts + on_conflict{constraint,
|
|
827
|
+
update_columns}); update_[table] / update_[table]_by_pk (_set replaces, _inc increments numeric;
|
|
828
|
+
where required for bulk \u2014 Hasura _append/_delete_key are NOT supported); delete_[table] /
|
|
829
|
+
delete_[table]_by_pk (where required for bulk); export_[table].
|
|
830
|
+
- Subscriptions: [table], [table]_by_pk, [table]_aggregate mirror the queries as live queries.
|
|
831
|
+
|
|
832
|
+
Column type \u2192 GraphQL: text\u2192String, integer\u2192Int, bigint/bigserial\u2192bigint, float8\u2192Float8,
|
|
833
|
+
decimal\u2192Decimal, boolean\u2192Boolean, jsonb\u2192jsonb; timestamptz/timetz/date/interval as-is;
|
|
834
|
+
geo_point\u2192geography. System columns id/created_at/updated_at are read-only \u2014 never in
|
|
835
|
+
insert/_set/_inc.
|
|
836
|
+
|
|
837
|
+
Media columns are stored as ids, never URLs/paths: single = [col]_id (image\u2192FZ_Image, file\u2192FZ_File,
|
|
838
|
+
video\u2192FZ_Video). The list forms (image_list / video_list / file_list) are DEPRECATED: read them as
|
|
839
|
+
[col]_ids arrays where an existing project still has one, but do not add new ones.
|
|
840
|
+
|
|
841
|
+
Relationships (defined by foreign keys) become nested fields: 1:1 / N:1 \u2192 a single object (e.g.
|
|
842
|
+
meta: post_meta), 1:N \u2192 an array + a [rel]_aggregate object. Filter to-one relations directly;
|
|
843
|
+
to-many use EXISTS semantics.`,"filter-grammar":`## Filtering \u2014 the strict operator-first where grammar ([table]_bool_exp)
|
|
844
|
+
This is the RAW GraphQL where shape for hand-written frontend queries and raw runtime GraphQL.
|
|
845
|
+
It is NOT the simplified where a typed table helper accepts (that one is {column:{_op:value}}).
|
|
846
|
+
|
|
847
|
+
Logical: _and:[bool_exp], _or:[bool_exp], _not:bool_exp.
|
|
848
|
+
Relation filters: navigate by the relationship field name to a nested [related]_bool_exp. To-one
|
|
849
|
+
(1:1/N:1) filters the parent by the single related row (author:{name:{_eq:\u2026}}); to-many (1:N/N:M)
|
|
850
|
+
uses EXISTS \u2014 the parent matches if ANY child does (post_tags:{tag:{name:{_eq:\u2026}}}).
|
|
851
|
+
|
|
852
|
+
A comparison predicate starts with the OPERATOR, then an operand-wrapper whose type matches the
|
|
853
|
+
FINAL evaluated type (not necessarily the column type):
|
|
854
|
+
{ "_eq": { "bigint_operand": { "left_operand": {\u2026}, "right_operand": {\u2026} } } }
|
|
855
|
+
Operands are {"literal":v} | {"column":"field"} | {"FUNCTION_NAME":{\u2026args}}. Operand-wrapper types:
|
|
856
|
+
bigint_operand, text_operand, boolean_operand, timestamptz_operand, decimal_operand, \u2026 (the final
|
|
857
|
+
type). Operators:
|
|
858
|
+
- comparison: _eq _neq _gt _lt _gte _lte
|
|
859
|
+
- array: _in _nin
|
|
860
|
+
- nullity (unary): _is_null _is_not_null
|
|
861
|
+
- text pattern: _like _nlike _ilike _nilike _similar _nsimilar
|
|
862
|
+
- jsonb: _contains _contained_in _has_key _has_keys_any _has_keys_all
|
|
863
|
+
- boolean: _is_true _is_false
|
|
864
|
+
- collection: _is_empty _is_not_empty
|
|
865
|
+
|
|
866
|
+
Example (month of created_at equals 12):
|
|
867
|
+
{ "_eq": { "bigint_operand": {
|
|
868
|
+
"left_operand": { "extract_timestamptz": { "time": {"column":"created_at"}, "unit":"MONTH" } },
|
|
869
|
+
"right_operand": { "literal": "12" } } } }`,aggregations:`## Aggregations, window functions & order_by
|
|
870
|
+
[table]_aggregate returns { nodes: [table!]! (the raw rows matching where/limit/offset/order_by),
|
|
871
|
+
aggregate: {\u2026} }. aggregate fields:
|
|
872
|
+
- count(columns:[Enum], distinct:Boolean): no columns \u2192 COUNT(*); distinct:true with 1+ columns \u2192
|
|
873
|
+
unique values/combinations; distinct:false with multiple columns \u2192 counts only the FIRST column.
|
|
874
|
+
- sum, avg: numeric columns only. max, min: comparable columns (numeric/time/text).
|
|
875
|
+
|
|
876
|
+
Window functions (ROW_NUMBER, RANK, DENSE_RANK, NTH_VALUE) are available in the relevant formula /
|
|
877
|
+
window-frame inputs.
|
|
878
|
+
|
|
879
|
+
order_by supports: direct columns ({title:asc}); related 1:1 records ({author:{name:desc}});
|
|
880
|
+
aggregates of N:1 ({post_tags_aggregate:{count:desc}}); text vector-similarity sort when the
|
|
881
|
+
TEXT_COLUMN_VECTOR_SORT extension is applied; and BM25 keyword relevance
|
|
882
|
+
({fz_content_bm25:{query:"..."}}) when that TEXT column carries a BM25 index. BM25 returns
|
|
883
|
+
only rows that match, most relevant first, so a page can be shorter than limit and a query
|
|
884
|
+
matching nothing returns no rows; an empty or whitespace query orders by id instead. Not
|
|
885
|
+
available for ordering inside window functions. The same index adds
|
|
886
|
+
fz_content_bm25_score(query) (relevance, higher is better, 0 for a non-match) and
|
|
887
|
+
fz_content_bm25_snippet(query, max_words, min_words, max_fragments, start_sel, stop_sel)
|
|
888
|
+
(an excerpt with matches wrapped in <b>\u2026</b>; selecting it on a list needs limit <= 100).`,"formula-catalog":`## Formula functions (operands)
|
|
889
|
+
Use a function as an operand by wrapping the UPPERCASE name around its args, e.g.
|
|
890
|
+
{"EXTRACT_TIMESTAMPTZ": {"time": \u2026, "unit": \u2026}}. Args nest (a function's output can feed another when
|
|
891
|
+
types match). Type legend: [TYPE] required operand of that type; [TYPE?] optional (defaults 0/null);
|
|
892
|
+
[ANY] any type; [NUMERIC] BIGINT/INTEGER/DECIMAL/FLOAT8/BIGSERIAL; [COMPARABLE] NUMERIC/TEXT/DATE/
|
|
893
|
+
TIMESTAMPTZ/TIMETZ/INTERVAL; [ANY[]] array; [Enum:NAME] an explicit enum value (see Runtime enums).
|
|
894
|
+
|
|
895
|
+
Manipulation: CONCAT(items:[TEXT[]]); SUBSTRING(source_text:[TEXT],start_index:[BIGINT],end_index:
|
|
896
|
+
[BIGINT]); LEFT(source_text,length:[BIGINT]); RIGHT(source_text,length:[BIGINT]); LOWER(source_text);
|
|
897
|
+
UPPER(source_text); TRIM(text); TRIM_TRAILING_ZERO(source_text); REPEAT(text,times:[BIGINT]);
|
|
898
|
+
ENCODE_URL(text); DECODE_URL(text); ARRAY_CONCAT(first_array:[ANY[]],second_array:[ANY[]]);
|
|
899
|
+
SLICE(array:[ANY[]],start_index:[BIGINT],length:[BIGINT]); UNIQUE(array:[ANY[]]);
|
|
900
|
+
COALESCE(array:[ANY[]]).
|
|
901
|
+
Search & replace: REPLACE_OCCURRENCES(source_text,search_text,replace_text,max_replacements:
|
|
902
|
+
[BIGINT]); REPLACE_AT_POSITION(source_text,start_index:[BIGINT],length:[BIGINT],replace_text);
|
|
903
|
+
POSITION(source_text,search_text); CONTAINS(source_text,search_text).
|
|
904
|
+
Regex: REGEX_EXTRACT(text,regex); REGEX_REPLACE(text,regex,replacement); REGEX_EXTRACT_ALL(text,
|
|
905
|
+
regex); REGEX_MATCH(text,regex).
|
|
906
|
+
Formatting & utils: TEXT_DECIMAL_FORMAT(number:[DECIMAL],fraction_digits:[BIGINT],rounding_mode:
|
|
907
|
+
[Enum:ROUNDING_MODE],clear_trailing_zeros:[BOOLEAN]); NUMBER_FORMAT(number:[DECIMAL],fraction_digits,
|
|
908
|
+
format:[Enum:NUMBER_FORMAT]); STRING_LEN(source_text); RANDOM_TEXT(min_length,max_length,
|
|
909
|
+
include_numbers,include_lower_case,include_upper_case); UUID(); JOIN(array:[TEXT[]],separator:[TEXT]);
|
|
910
|
+
SPLIT(source_text,delimiter); ARRAY_LEN(array:[ANY[]]).
|
|
911
|
+
Arithmetic: ADD(value0:[NUMERIC],value1); SUBTRACT(minuend,subtrahend); MULTIPLY(value0,value1);
|
|
912
|
+
DIVIDE(dividend:[DECIMAL],divisor:[DECIMAL]); MODULO(dividend:[NUMERIC],divisor); ABS(number);
|
|
913
|
+
POW(base,exponent); LOG(base:[DECIMAL],argument:[DECIMAL]).
|
|
914
|
+
Rounding: ROUND_UP(number:[DECIMAL]); ROUND_DOWN(number:[DECIMAL]); DECIMAL_FORMAT(number,
|
|
915
|
+
fraction_digits:[BIGINT],rounding_mode:[Enum:ROUNDING_MODE]).
|
|
916
|
+
Generators: RANDOM_BIGINT(min_length:[BIGINT],max_length:[BIGINT]); SEQUENCE(start,end,step:[BIGINT]).
|
|
917
|
+
Current time: CURRENT_DATE(); CURRENT_TIMETZ(); CURRENT_TIMESTAMPTZ().
|
|
918
|
+
Constructors: MAKE_DATE(years,months,days:[BIGINT]); MAKE_TIMETZ(hours,minutes,seconds,
|
|
919
|
+
milliseconds:[BIGINT?]); MAKE_TIMESTAMPTZ(years,months,days:[BIGINT],hours,minutes,seconds,
|
|
920
|
+
milliseconds:[BIGINT?]); MAKE_INTERVAL(years,months,weeks,days,hours,minutes,seconds,
|
|
921
|
+
milliseconds:[BIGINT]); FROM_DATE_AND_TIMETZ(date:[DATE],timetz:[TIMETZ]).
|
|
922
|
+
Extraction & formatting: EXTRACT_DATE(time:[DATE],unit:[Enum:DATE_UNIT]); EXTRACT_TIMETZ(time:[TIMETZ],
|
|
923
|
+
unit:[Enum:TIME_UNIT]); EXTRACT_TIMESTAMPTZ(time:[TIMESTAMPTZ],unit:[Enum:TIMESTAMP_UNIT]);
|
|
924
|
+
DATE_FORMAT(time:[DATE],format:[TEXT],language:[Enum:LANGUAGE]); TIMETZ_FORMAT(time,format,language);
|
|
925
|
+
TIMESTAMPTZ_FORMAT(time,format,language); DURATION_FORMAT(duration:[DECIMAL],unit:[Enum:DURATION_UNIT],
|
|
926
|
+
format:[TEXT]); RELATIVE_DATE(time:[DATE],language,hide_suffix:[BOOLEAN]); RELATIVE_TIMESTAMPTZ(time,
|
|
927
|
+
language,hide_suffix).
|
|
928
|
+
Calculations & deltas: DELTA_DATE(date:[DATE],increase:[BOOLEAN],years,months,days:[BIGINT?]);
|
|
929
|
+
DELTA_TIMETZ(timetz:[TIMETZ],increase,hours,minutes,seconds,milliseconds:[BIGINT?]);
|
|
930
|
+
DELTA_TIMESTAMPTZ(timestamptz:[TIMESTAMPTZ],increase,years,months,days,hours,minutes,seconds,
|
|
931
|
+
milliseconds:[BIGINT?]); EXTRACT_DATE_DURATION(start_time,end_time:[DATE],unit:[Enum:DATE_UNIT]);
|
|
932
|
+
EXTRACT_TIMETZ_DURATION(start_time,end_time:[TIMETZ],unit:[Enum:TIME_UNIT]);
|
|
933
|
+
EXTRACT_TIMESTAMPTZ_DURATION(start_time,end_time:[TIMESTAMPTZ],unit:[Enum:TIMESTAMP_UNIT]).
|
|
934
|
+
Conversions: FROM_TIMESTAMPTZ_TO_DATE(timestamptz); FROM_TIMESTAMPTZ_TO_TIMETZ(timestamptz).
|
|
935
|
+
Geography: FROM_COORDINATES(latitude:[DECIMAL],longitude:[DECIMAL]); GEO_DISTANCE(point0,point1:
|
|
936
|
+
[GEO_POINT],unit:[Enum:GEO_DISTANCE_UNIT]); GEO_LONGITUDE(geo:[GEO_POINT]); GEO_LATITUDE(geo).
|
|
937
|
+
Aggregates: SUM(array:[NUMERIC[]]); AVG(array:[NUMERIC[]]); MAX(value0,value1:[COMPARABLE]);
|
|
938
|
+
MIN(value0,value1); GREATEST(array:[COMPARABLE[]]); LEAST(array:[COMPARABLE[]]).
|
|
939
|
+
Element access: ITEM(array:[ANY[]],index:[BIGINT]); FIRST_ITEM(array); LAST_ITEM(array);
|
|
940
|
+
RANDOM_ITEM(array); ARRAY_POSITION(array:[ANY[]],item:[ANY]).
|
|
941
|
+
JSONB: JSON_EXTRACT_BY_DOT_NOTATION_JSONPATH(json:[JSONB],path:[TEXT]).
|
|
942
|
+
Casting: CAST_FROM_TEXT(value:[TEXT]); CAST_COLUMN_TO_TEXT(value:[ANY]); CAST_ARRAY_TO_TEXT(value:
|
|
943
|
+
[ANY[]]); CAST_TO_BIGINT(value:[ANY]); CAST_TO_DECIMAL(value:[ANY]).
|
|
944
|
+
Vector search: EMBEDDING_VECTOR_DISTANCE(embedded_text_column:[Enum:EMBEDDING_COLUMN],text:[TEXT],
|
|
945
|
+
distance_function:[Enum:VECTOR_DISTANCE]).
|
|
946
|
+
System: NULL_VALUE().`,"runtime-enums":`## Runtime enums (exact string values for [Enum:NAME] operands)
|
|
947
|
+
- DATE_UNIT: YEAR, MONTH, DAY, WEEK
|
|
948
|
+
- DURATION_UNIT: DAY, HOUR, MINUTE, SECOND, MILLISECOND
|
|
949
|
+
- EMBEDDING_COLUMN: (generated per column with the TEXT_COLUMN_VECTOR_SORT extension)
|
|
950
|
+
- GEO_DISTANCE_UNIT: METER, KILOMETER, MILE
|
|
951
|
+
- LANGUAGE: EN, ZH
|
|
952
|
+
- NUMBER_FORMAT: THOUSANDS_SEPARATOR, PERCENT
|
|
953
|
+
- ROUNDING_MODE: HALF_EVEN, HALF_UP, HALF_DOWN, UP, DOWN, CEILING, FLOOR
|
|
954
|
+
- TIMESTAMP_UNIT: YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, MILLISECOND, WEEK
|
|
955
|
+
- TIME_UNIT: HOUR, MINUTE, SECOND, MILLISECOND
|
|
956
|
+
- VECTOR_DISTANCE: EUCLIDEAN, COSINE`,"actionflow-invocation":`## Invoking actionflows from the runtime GraphQL API
|
|
957
|
+
An actionflow is a DAG of nodes (DB ops, sub-flows, conditions, loops) with input/output nodes
|
|
958
|
+
defining its args and return. Get the actionflow id, its input arg names, and (optionally) versionId
|
|
959
|
+
from the project schema first. $args keys match the input node's argument names.
|
|
960
|
+
|
|
961
|
+
Sync actionflow \u2014 single DB transaction, rolls back ALL writes on error; has a runtime limit
|
|
962
|
+
(ACTION_FLOW_TIMEOUT_MILLISECONDS: 15s free / 10min paid). Invoke with a plain mutation; the result
|
|
963
|
+
returns inline:
|
|
964
|
+
mutation ($args: Json!) { fz_invoke_action_flow(actionFlowId:"\u2026", versionId:N, args:$args) }
|
|
965
|
+
|
|
966
|
+
Async actionflow \u2014 each node in its own transaction (no global rollback); required for long tasks,
|
|
967
|
+
AI-agent nodes, and video generation. Two steps:
|
|
968
|
+
1. mutation ($args: Json!) { fz_create_action_flow_task(actionFlowId:"\u2026", versionId:N, args:$args) }
|
|
969
|
+
\u2192 returns a taskId (Long).
|
|
970
|
+
2. Read the result either by subscription \u2014 subscription ($taskId: Long!) {
|
|
971
|
+
fz_listen_action_flow_result(taskId:$taskId){ output status } } \u2014 or, without a WebSocket, by
|
|
972
|
+
polling the equivalent query: query ($taskId: Long!) { fz_action_flow_result(taskId:$taskId){
|
|
973
|
+
output status } }. Status transitions CREATED \u2192 PROCESSING \u2192 COMPLETED|FAILED; the final output
|
|
974
|
+
lives in the COMPLETED payload's output field.
|
|
975
|
+
|
|
976
|
+
fz_invoke_action_flow runs the DEPLOYED version of the flow \u2014 edits made in the editor since the
|
|
977
|
+
last backend sync are not exercised by it. It returns the Json scalar \u2014 a LEAF field: no
|
|
978
|
+
sub-selection on the result; parse it client-side. Always pass $args as one whole Json variable,
|
|
979
|
+
never assembled inline in the query string. Permission failures surface as errorCode 403 entries in
|
|
980
|
+
the GraphQL errors array (classification ACTION_FLOW) \u2014 anonymous users commonly lack invoke
|
|
981
|
+
permission.`,"ai-agent-invocation":`## Invoking Zion AI agents (ZAI) from the runtime GraphQL API
|
|
982
|
+
Agents support multi-modal in/out, prompt templating, context fetching, tool use, and structured
|
|
983
|
+
output. Get the agent id (zaiConfigId) and input names from the schema. Agents are ASYNC-only and
|
|
984
|
+
delivery depends on config: plain text may stream or not; structured output never streams and always
|
|
985
|
+
carries a JSONSchema.
|
|
986
|
+
|
|
987
|
+
1. Start \u2014 mutation returns just the conversationId:
|
|
988
|
+
mutation ($inputArgs: Map_String_ObjectScalar!, $zaiConfigId: String!) {
|
|
989
|
+
fz_zai_create_conversation(inputArgs:$inputArgs, zaiConfigId:$zaiConfigId) }
|
|
990
|
+
inputArgs keys are the agent's generated argKeys \u2014 short opaque ids like "dpmfu92py", not the
|
|
991
|
+
arg names you gave them. They are readable only from the design-time side, in
|
|
992
|
+
GET_ZAI_CONFIG_DETAIL's input args; there is no way to derive one from an arg's name, and an
|
|
993
|
+
invocation keyed by the names silently passes nothing. Binary inputs (IMAGE/VIDEO/FILE, or arrays of them)
|
|
994
|
+
use a "_id" suffix on the key and take asset id(s) as values (e.g. the_video \u2192 the_video_id:
|
|
995
|
+
1030\u2026; images \u2192 images_id: [1020\u2026, \u2026]).
|
|
996
|
+
2. Subscribe on the conversationId:
|
|
997
|
+
subscription ($conversationId: Long!) {
|
|
998
|
+
fz_zai_listen_conversation_result(conversationId:$conversationId){
|
|
999
|
+
conversationId status reasoningContent images{ id } data } }
|
|
1000
|
+
Status transitions IN_PROGRESS \u2192 (STREAMING\u2026) \u2192 COMPLETED. Streaming plain text arrives across
|
|
1001
|
+
multiple STREAMING messages; the COMPLETED message's data holds the consolidated output.
|
|
1002
|
+
reasoningContent streams the same way (partial, then whole at COMPLETED). Non-streaming text: one
|
|
1003
|
+
IN_PROGRESS then COMPLETED, no STREAMING. Image-output models fill images[] with FZ_Image ids in
|
|
1004
|
+
the COMPLETED message (see asset upload for the id system). Structured-output agents never stream:
|
|
1005
|
+
a single COMPLETED whose data is JSON matching the agent's JSONSchema.
|
|
1006
|
+
|
|
1007
|
+
Continue a COMPLETED conversation \u2014 the same subscription keeps emitting (IN_PROGRESS \u2192 \u2026 \u2192
|
|
1008
|
+
COMPLETED again): mutation ($conversationId: Long!, $text: String) {
|
|
1009
|
+
fz_zai_send_ai_message(conversationId:$conversationId, text:$text) }
|
|
1010
|
+
Stop an IN_PROGRESS/STREAMING run (returns true): fz_zai_stop_responding(conversationId:\u2026) \u2014 calling
|
|
1011
|
+
it on a COMPLETED conversation yields a 400 in the GraphQL errors field.
|
|
1012
|
+
|
|
1013
|
+
Without a WebSocket, poll the equivalent query instead of subscribing: query ($conversationId: Long!)
|
|
1014
|
+
{ fz_zai_conversation_result(conversationId:$conversationId){ conversationId status data
|
|
1015
|
+
reasoningContent } }. It reports the same state the subscription would, so a caller that cannot open
|
|
1016
|
+
a socket still sees IN_PROGRESS \u2192 COMPLETED|FAILED and the final data. Streaming deltas are the one
|
|
1017
|
+
thing polling cannot reconstruct \u2014 for a partial-token view you need the subscription.`,"third-party-invocation":`## Invoking imported third-party APIs from the runtime GraphQL API
|
|
1018
|
+
Each imported HTTP API config is { id, name, operation: 'query'|'mutation' (roughly GET vs POST),
|
|
1019
|
+
inputs: {key: TypeDefinition}, outputs: {key: TypeDefinition} }, where a TypeDefinition is a scalar
|
|
1020
|
+
('string'|'boolean'|'number'|'integer') or a nested object of them. The operation fixes the root
|
|
1021
|
+
GraphQL field: query \u2192 query operation_\${id}, mutation \u2192 mutation operation_\${id}. Get the id,
|
|
1022
|
+
inputs, and outputs from the schema; provide every input unless the user drops it.
|
|
1023
|
+
|
|
1024
|
+
Shape:
|
|
1025
|
+
mutation ($\u2026: \u2026) { operation_<id>(fz_body:{\u2026}, arg1:$\u2026, \u2026) {
|
|
1026
|
+
responseCode
|
|
1027
|
+
field_200_json { <sub-field selections> } } }
|
|
1028
|
+
|
|
1029
|
+
field_200_json is a fixed field on every TPA-derived operation \u2014 the parsed body for any 2xx
|
|
1030
|
+
response. ALWAYS check responseCode: on 4xx/5xx it is the error code and field_200_json is empty.`,"asset-upload":`## Binary asset upload (mandatory two-step)
|
|
1031
|
+
Assets (images/videos/files) live in object storage; tables reference only the asset id, never a
|
|
1032
|
+
URL/path.
|
|
1033
|
+
1. Compute the raw 128-bit MD5 of the file and encode it as standard Base64 \u2014 the server decodes
|
|
1034
|
+
with the basic decoder, so a URL-safe variant is rejected. Request a presigned URL with the
|
|
1035
|
+
QUERY field matching the type \u2014 imagePresignedUrlV2(imgMd5Base64, imageSuffix:MediaFormat,
|
|
1036
|
+
acl){ imageId uploadUrl uploadHeaders } / videoPresignedUrlV2(videoMd5Base64, videoFormat,
|
|
1037
|
+
acl){ videoId \u2026 } / filePresignedUrlV2(md5Base64, format, name, suffix, sizeBytes, acl){ fileId
|
|
1038
|
+
\u2026 }. acl defaults to PRIVATE (recommended). The same fields without the V2 suffix are
|
|
1039
|
+
deprecated mutations \u2014 do not use them in new code.
|
|
1040
|
+
2. HTTP PUT the raw bytes to uploadUrl with the returned uploadHeaders. Then use the returned id as
|
|
1041
|
+
the value of the corresponding *_id column (e.g. cover_image_id: imageId).
|
|
1042
|
+
|
|
1043
|
+
In browsers, crypto.subtle cannot compute MD5 \u2014 hash with a JS MD5 library (e.g. spark-md5)
|
|
1044
|
+
instead. When rendering an asset on the frontend, select its url subfield; when storing or passing
|
|
1045
|
+
it anywhere else, use the id.
|
|
1046
|
+
|
|
1047
|
+
MediaFormat: CSS, CSV, DOC, DOCX, GIF, HTML, ICO, JPEG, JPG, JSON, MOV, MP3, MP4, OTHER, PDF, PNG,
|
|
1048
|
+
PPT, PPTX, SVG, TXT, WAV, WEBP, XLS, XLSX, XML.
|
|
1049
|
+
CannedAccessControlList: AUTHENTICATE_READ, AWS_EXEC_READ, BUCKET_OWNER_FULL_CONTROL,
|
|
1050
|
+
BUCKET_OWNER_READ, DEFAULT, LOG_DELIVERY_WRITE, PRIVATE, PUBLIC_READ, PUBLIC_READ_WRITE.
|
|
1051
|
+
|
|
1052
|
+
## Images inside rich-text (RTF) content
|
|
1053
|
+
A rich-text column stores HTML whose <img> src is an asset placeholder, never a URL:
|
|
1054
|
+
<img src="fz_image_1020000000002458">. The suffix is either the numeric image id or its
|
|
1055
|
+
11-char base62 exId; both address the same asset. Asset URLs are presigned and expire, so a
|
|
1056
|
+
URL written into the body rots \u2014 the app's rich-text / Markdown components resolve
|
|
1057
|
+
placeholders to live URLs at render time, which is why the column read through this API (or
|
|
1058
|
+
shown in the data table) still holds the raw placeholder.
|
|
1059
|
+
|
|
1060
|
+
Reading one from outside the app means resolving them yourself: match
|
|
1061
|
+
fz_image_([0-9]+|[A-Za-z0-9]{11}) over the HTML, dedupe, batch-resolve with
|
|
1062
|
+
getImageListByIds(imageIds:_int8){ id exId url urlInfo{ urlExpireAt } } \u2014 exIds go through
|
|
1063
|
+
getImageListByExIds(imageExIds:[String]) \u2014 then rewrite each src. Cache by urlExpireAt and
|
|
1064
|
+
never write a resolved URL back into the column. Writing is the mirror image: upload through
|
|
1065
|
+
the two-step above, then emit src="fz_image_<imageId>". An external URL left in the body is
|
|
1066
|
+
stored verbatim and leaves the picture depending on a host nobody here controls.`};u();function Bg(t,e){let n=wa[t];if(!n)throw new Error(`No guide available for '${t}'.`);let a=n[e];if(!a.available||!a.prompt)throw new Error(`Plugin '${t}' is not available for ${e} projects.`);return a.prompt}u();function Tz(t){return!t||typeof t!="object"?"pre_type_system_refactor":t.editorConfiguration!=null?"post_type_system_refactor":"pre_type_system_refactor"}async function Ns(t,e,n){let r=await t({name:"schema.load",args:typeof e=="string"&&e?{projectExId:e}:{}},n);if(!r.ok)throw new Error(`schema.load failed: ${r.error??"unknown error"}`);let o=r.data?.typeSystem;if(o==="pre_type_system_refactor")return"pre";if(o==="post_type_system_refactor")return"post";throw o==null?new Error("schema.load returned missing typeSystem"):new Error(`schema.load returned unknown typeSystem: ${String(o)}`)}var ye={projectExId:c.string().optional().describe("The project to act on. Defaults to the project set by set_current_project."),appExId:c.string().nullable().optional().describe(`A front-end app INSIDE the project (web / WeChat mini program / mobile) \u2014 never the project's own exId. Leave unset to address the project itself (its backend, and the whole schema of a single-client project); a single-client project has no app to name. Take the value from project metadata \u2192 apps[], using an entry whose appExId is non-null (the BACKEND_ONLY entry carries null and means "leave this unset").`),appVersionExId:c.string().nullable().optional().describe("A specific version of the app named by appExId. Leave unset for the current version.")},Ps=t=>({content:[{type:"text",text:t.ok?t.message??JSON.stringify(t.data??{},null,2):JSON.stringify({error:t.error??"Unknown error",data:t.data},null,2)}],isError:!t.ok}),Cr=(t,e,n,a,r)=>{t.registerTool(e,{description:n,inputSchema:a},r)},Zg=(t,e,n)=>{for(let a of e)Cr(t,a.name,a.description,a.inputSchema??{},async(r,o)=>Ps(await n({name:a.command,args:r},o.signal)))},qg=(t,e,n)=>{for(let a of e){let{ops:r}=a,o={op:c.enum(Object.keys(r)),...a.inputSchema??{}};Cr(t,a.name,a.description,o,async(s,i)=>{let{op:l,...d}=s;return Ps(await n({name:r[String(l)],args:d},i.signal))})}};var HP=t=>({content:[{type:"text",text:t}],isError:!1});var Vg=(t,e,n)=>{for(let a of e){let r={...ye,op:c.enum(a.ops),args:c.record(c.any()).optional()};Cr(t,a.name,a.description,r,async(o,s)=>{let{op:i,projectExId:l,appExId:d,appVersionExId:h,args:p}=o;return Ps(await n({name:"schema.ztype_tool_calls",args:{projectExId:l,appExId:d,appVersionExId:h,toolCalls:[{toolCallId:`${a.name}-${String(i)}-${Date.now()}`,name:String(i),args:p??{}}]}},s?.signal))})}},Wg=(t,e)=>{let n=Object.keys(wa);Cr(t,"guide","Load the domain guide for a backend capability \u2014 the rules, conventions, and gotchas for a plugin area (database, type, bindings, actionflow, api, tpa, zai, component, permissions, payments, logs, agent). Returns guidance for the loaded project\u2019s type-system state. Call before editing an unfamiliar area, or when a meta-tool call is rejected.",{plugin:c.enum(n),projectExId:c.string().optional()},async(a,r)=>{let o=await Ns(e,a.projectExId,r?.signal);return HP(Bg(String(a.plugin),o))})},Hg=(t,e)=>{Cr(t,"agent_command","Advanced escape hatch for directly invoking an internal agent command.",{name:c.string(),args:c.record(c.any()).optional()},async(n,a)=>Ps(await e({name:String(n.name),args:n.args??{}},a.signal)))};u();var Cs=[{name:"schema_action_menu",tier:"catalog",description:"\nChanges apply immediately; use schema_undo to revert the last change. Ops:\n- op=GET_SELECTABLE_COMPONENT_ACTIONS \u2014 The frontend actions attachable to a component event, as the same category tree the editor's action picker shows \u2014 already filtered to this client's platform, what this product ships, the project's configured authentication, and what the event accepts. A few actions belong to one product only, so an absence can mean that rather than a missing capability. Each leaf carries the `eventType` it resolved to here (a leaf like SIGN_IN becomes whichever login the project configured) and the `path` to address it. A leaf's `kind` is what you send to ADD_COMPONENT_ACTIONS to attach it. A leaf with no `kind` cannot be attached by that tool at all \u2014 say so and let the user add it in the editor, rather than attaching some other action that looks close. `kind` is necessary but not sufficient: several leaves share one kind (SIGN_IN and SIGN_OUT are both USER_LOGIN, and each sign-in method is that same kind under a different identifier), so send the leaf's `itemArgs` verbatim in the same item alongside `kind` \u2014 a kind sent without them is a valid call for the OTHER action and is not refused. A leaf's `alternativeKinds` are further kinds the same leaf builds, as the editor's own panel switches between them (SET_VARIABLE writes a page or modal variable with SET_VARIABLE_DATA, or a client variable with SET_GLOBAL_DATA). Where a kind still cannot express the leaf you picked the write says so; follow that error instead of substituting a different action.",ops:{GET_SELECTABLE_COMPONENT_ACTIONS:"GET_SELECTABLE_COMPONENT_ACTIONS"},inputSchema:{componentId:c.string().optional(),eventType:c.string().optional()}},{name:"schema_actionflow",tier:"core",description:`Action flows \u2014 flow-level (addressed by actionFlowId). Discover types via op=SELECTABLE_TYPES and ids via op=GET_DETAIL. AI nodes require isAsync=true.
|
|
1067
|
+
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
1068
|
+
- op=ADD \u2014 Result echoes each new flow's id.
|
|
1069
|
+
- op=ADD_GLOBAL_VARS \u2014 Result echoes each new variable's minted key. These are the flow's own variables, visible inside it only; a variable the client's pages share is ADD_CLIENT_VARIABLES.
|
|
1070
|
+
- op=ADD_ACTION_FLOW_GROUPS \u2014 Result echoes each new group's minted id. [post-type-system-refactor only]
|
|
1071
|
+
- op=ADD_INPUT_PARAMS (req: actionFlowId, items)
|
|
1072
|
+
- op=ADD_OUTPUT_FIELDS (req: actionFlowId, items) [pre-type-system-refactor only]
|
|
1073
|
+
- op=ADD_CUSTOM_CODE_NODE_OUTPUT_VALUE (req: actionFlowId, name, nodeId, type) [pre-type-system-refactor only]
|
|
1074
|
+
- op=CLEAR_OUTPUT (req: actionFlowId) [post-type-system-refactor only]
|
|
1075
|
+
- op=CLEAR_CUSTOM_CODE_NODE_OUTPUT_TYPE (req: actionFlowId, nodeId) [post-type-system-refactor only]
|
|
1076
|
+
- op=DELETE \u2014 Also deletes every trigger bound to the flow (database, scheduled and webhook) and revokes it from all role permissions; the result lists the deleted triggers.
|
|
1077
|
+
- op=DELETE_GLOBAL_VARS (req: actionFlowId, variableKeys)
|
|
1078
|
+
- op=DELETE_ACTION_FLOW_GROUPS (req: groupIds) [post-type-system-refactor only]
|
|
1079
|
+
- op=DELETE_INPUT_PARAMS (req: actionFlowId, names)
|
|
1080
|
+
- op=DELETE_OUTPUT_FIELDS (req: actionFlowId, names) [pre-type-system-refactor only]
|
|
1081
|
+
- op=DELETE_CUSTOM_CODE_NODE_OUTPUT_VALUE (req: actionFlowId, name, nodeId) [pre-type-system-refactor only]
|
|
1082
|
+
- op=DUPLICATE_ACTION_FLOW \u2014 Duplicate a whole action flow, including every trigger bound to it (database, scheduled and webhook) and the type definitions private to its own input/output. The copied triggers are created DISABLED so the duplicate does not start firing on the same table; enable each one when the copy is configured. The result echoes the new flow's id. [post-type-system-refactor only]
|
|
1083
|
+
- op=GET_DETAIL (req: actionFlowId)
|
|
1084
|
+
- op=GET_ACTION_FLOW_GROUPS [post-type-system-refactor only]
|
|
1085
|
+
- op=GET_ACTION_FLOW_NODE_DETAIL (req: actionFlowId, nodeId)
|
|
1086
|
+
- op=SELECTABLE_TYPES \u2014 List the types this action-flow slot accepts. To use a type that is not listed, first create that object type or enum (leave \`private\` unset, or it stays hidden from this list) and call this again \u2014 the new type then appears with the exact \`typeIdentifier\` to copy. That identifier is not the type id and must never be assembled from it. Arrays are not listed: select the base type and set the target parameter's arrayLevel \u2014 except on the legacy type system, where every listed type is scalar-only and any arrayLevel above 0 is rejected. To pass a collection there, model it as a related table and pass the parent record's id.
|
|
1087
|
+
- op=LIST
|
|
1088
|
+
- op=MOVE_ACTION_FLOWS_TO_GROUP \u2014 Sets which group each flow belongs to. To place a brand-new flow, pass ADD_ACTION_FLOWS a \`groupId\` instead of calling this afterwards. System flows cannot be moved. [post-type-system-refactor only]
|
|
1089
|
+
- op=SET_OUTPUT (req: actionFlowId, type) [post-type-system-refactor only]
|
|
1090
|
+
- op=SET_CUSTOM_CODE_NODE_OUTPUT_TYPE (req: actionFlowId, nodeId, type) [post-type-system-refactor only]
|
|
1091
|
+
- op=UPDATE (req: actionFlowId)
|
|
1092
|
+
- op=UPDATE_GLOBAL_VARS (req: actionFlowId, items)
|
|
1093
|
+
- op=UPDATE_ACTION_FLOW_GROUPS (req: groups) [post-type-system-refactor only]
|
|
1094
|
+
- op=UPDATE_INPUT_PARAMS (req: actionFlowId, items)
|
|
1095
|
+
- op=UPDATE_CUSTOM_CODE_NODE_OUTPUT_VALUE (req: actionFlowId, name, nodeId) [pre-type-system-refactor only]`,ops:{ADD:"ADD_ACTION_FLOWS",ADD_GLOBAL_VARS:"ADD_ACTION_FLOW_GLOBAL_VARIABLES",ADD_ACTION_FLOW_GROUPS:"ADD_ACTION_FLOW_GROUPS",ADD_INPUT_PARAMS:"ADD_ACTION_FLOW_INPUT_PARAMS",ADD_OUTPUT_FIELDS:"ADD_ACTION_FLOW_OUTPUT_FIELDS",ADD_CUSTOM_CODE_NODE_OUTPUT_VALUE:"ADD_CUSTOM_CODE_NODE_OUTPUT_VALUE",CLEAR_OUTPUT:"CLEAR_ACTION_FLOW_OUTPUT",CLEAR_CUSTOM_CODE_NODE_OUTPUT_TYPE:"CLEAR_CUSTOM_CODE_NODE_OUTPUT_TYPE",DELETE:"DELETE_ACTION_FLOWS",DELETE_GLOBAL_VARS:"DELETE_ACTION_FLOW_GLOBAL_VARIABLES",DELETE_ACTION_FLOW_GROUPS:"DELETE_ACTION_FLOW_GROUPS",DELETE_INPUT_PARAMS:"DELETE_ACTION_FLOW_INPUT_PARAMS",DELETE_OUTPUT_FIELDS:"DELETE_ACTION_FLOW_OUTPUT_FIELDS",DELETE_CUSTOM_CODE_NODE_OUTPUT_VALUE:"DELETE_CUSTOM_CODE_NODE_OUTPUT_VALUE",DUPLICATE_ACTION_FLOW:"DUPLICATE_ACTION_FLOW",GET_DETAIL:"GET_ACTION_FLOW_DETAIL",GET_ACTION_FLOW_GROUPS:"GET_ACTION_FLOW_GROUPS",GET_ACTION_FLOW_NODE_DETAIL:"GET_ACTION_FLOW_NODE_DETAIL",SELECTABLE_TYPES:"GET_ACTION_FLOW_SELECTABLE_TYPES",LIST:"GET_ALL_ACTION_FLOWS_INFO",MOVE_ACTION_FLOWS_TO_GROUP:"MOVE_ACTION_FLOWS_TO_GROUP",SET_OUTPUT:"SET_ACTION_FLOW_OUTPUT",SET_CUSTOM_CODE_NODE_OUTPUT_TYPE:"SET_CUSTOM_CODE_NODE_OUTPUT_TYPE",UPDATE:"UPDATE_ACTION_FLOW",UPDATE_GLOBAL_VARS:"UPDATE_ACTION_FLOW_GLOBAL_VARIABLES",UPDATE_ACTION_FLOW_GROUPS:"UPDATE_ACTION_FLOW_GROUPS",UPDATE_INPUT_PARAMS:"UPDATE_ACTION_FLOW_INPUT_PARAMS",UPDATE_CUSTOM_CODE_NODE_OUTPUT_VALUE:"UPDATE_CUSTOM_CODE_NODE_OUTPUT_VALUE"},inputSchema:{actionFlowId:c.string().optional(),actionFlowIds:c.array(c.any()).optional(),arrayLevel:c.number().optional(),detail:c.enum(["SUMMARY","FULL"]).optional(),displayName:c.string().optional(),groupId:c.string().optional(),groupIds:c.array(c.any()).optional(),groups:c.any().optional(),isAsync:c.boolean().optional(),items:c.array(c.any()).optional(),name:c.string().optional(),names:c.array(c.any()).optional(),newName:c.string().optional(),nodeId:c.string().optional(),slot:c.enum(["GLOBAL_VARIABLE","INPUT","OUTPUT","CUSTOM_CODE_INPUT","CUSTOM_CODE_OUTPUT"]).optional(),sourceActionFlowId:c.string().optional(),timeout:c.number().optional(),type:c.any().optional(),useEventLoop:c.boolean().optional(),variableKeys:c.array(c.any()).optional()}},{name:"schema_actionflow_node",tier:"core",description:"Action-flow nodes (addressed by actionFlowId + nodeId; ids from schema_actionflow op=GET_DETAIL). Fill node value bindings with schema_create_binding and conditions with schema_condition_expr.\nChanges apply immediately; use schema_undo to revert the last change. Ops:\n- op=ADD_BRANCH_ITEM \u2014 Result echoes the new branch node's id and its condition schema path.\n- op=ADD_NODE \u2014 Add a node after `afterNodeId`, taking the `node` BROWSE_ACTION_FLOW_ADD_NODE_OPTIONS returns for that same position. Copy it; its config fields may be overridden, while its `type` and `templateCodeId` name the entry and must stay \u2014 an entry the menu does not offer here, or disables there, is refused with the menu's own message. Result echoes the new node's id; branch and while nodes also echo their condition schema paths.\n- op=ADD_CODE_INPUT (req: actionFlowId, name, nodeId)\n- op=ADD_VAR_TARGETS (req: actionFlowId, nodeId, variableKeys)\n- op=BROWSE_ACTION_FLOW_ADD_NODE_OPTIONS \u2014 Browse the nodes addable after a given node \u2014 the add-node menu at that position, as flat entries. Each entry carries the `node` to add with: copy it into ADD_ACTION_FLOW_NODE as it is, or override its config fields (the table, the limit, the code, the target flow). Its `type` and `templateCodeId` select the entry instead \u2014 a pair the menu does not offer at this position is refused there. What is addable, and what is disabled, depends on the position \u2014 re-read after the flow changes or before adding at a different `afterNodeId`. A `disabled` entry is one ADD_ACTION_FLOW_NODE refuses there, with the same `disabledMessage`; read it instead of retrying.\n- op=DELETE_NODES (req: actionFlowId, nodeIds)\n- op=DELETE_CODE_INPUT (req: actionFlowId, name, nodeId)\n- op=DELETE_VAR_TARGETS (req: actionFlowId, nodeId, variableKeys)\n- op=DUPLICATE_ACTION_FLOW_NODES \u2014 Copy a run of nodes \u2014 with their configuration and bindings \u2014 from one action flow to a position in the same or another flow, which ADD_ACTION_FLOW_NODE cannot express: it builds one node from a config, while a copied run arrives complete. To move nodes instead of copying them use MOVE_ACTION_FLOW_NODES, which keeps their ids. A reference the target flow cannot resolve (a variable of the source flow, say) is blanked rather than carried over, so re-check the new nodes' bindings. The result echoes each new node. [post-type-system-refactor only]\n- op=CONTEXT_INFO \u2014 Locate a schema path inside an action flow: returns the flow, the node owning the path, and the preceding nodes (whose outputs are bindable there).\n- op=MOVE_ACTION_FLOW_NODES \u2014 Move nodes within one action flow. Several nodes move as one contiguous chain, ordered by the flow's own execution order regardless of the order given; a block start carries its whole block. Result echoes the applied order and the resolved anchor.\n- op=REORDER_ACTION_FLOW_BRANCH_ITEMS \u2014 Reorder the branches (= evaluation order) of one BRANCH_SEPARATION. Read the current order from GET_ACTION_FLOW_DETAIL's branchItemIds.\n- op=UPDATE_NODE (req: actionFlowId, nodeId)\n- op=UPDATE_CUSTOM_CODE_NODE_INPUT (req: actionFlowId, name, nodeId)",ops:{ADD_BRANCH_ITEM:"ADD_ACTION_FLOW_BRANCH_ITEM",ADD_NODE:"ADD_ACTION_FLOW_NODE",ADD_CODE_INPUT:"ADD_CUSTOM_CODE_NODE_INPUT",ADD_VAR_TARGETS:"ADD_GLOBAL_VARIABLES_NODE_TARGETS",BROWSE_ACTION_FLOW_ADD_NODE_OPTIONS:"BROWSE_ACTION_FLOW_ADD_NODE_OPTIONS",DELETE_NODES:"DELETE_ACTION_FLOW_NODES",DELETE_CODE_INPUT:"DELETE_CUSTOM_CODE_NODE_INPUT",DELETE_VAR_TARGETS:"DELETE_GLOBAL_VARIABLES_NODE_TARGETS",DUPLICATE_ACTION_FLOW_NODES:"DUPLICATE_ACTION_FLOW_NODES",CONTEXT_INFO:"GET_ACTION_FLOW_CONTEXT_INFO",MOVE_ACTION_FLOW_NODES:"MOVE_ACTION_FLOW_NODES",REORDER_ACTION_FLOW_BRANCH_ITEMS:"REORDER_ACTION_FLOW_BRANCH_ITEMS",UPDATE_NODE:"UPDATE_ACTION_FLOW_NODE",UPDATE_CUSTOM_CODE_NODE_INPUT:"UPDATE_CUSTOM_CODE_NODE_INPUT"},inputSchema:{actionFlowId:c.string().optional(),afterNodeId:c.string().optional(),arrayLevel:c.number().optional(),branchSeparationId:c.string().optional(),config:c.any().optional(),displayName:c.string().optional(),name:c.string().optional(),newName:c.string().optional(),node:c.any().optional(),nodeId:c.string().optional(),nodeIds:c.array(c.any()).optional(),reorderedBranchItemIds:c.array(c.any()).optional(),schemaPath:c.array(c.any()).optional(),sourceActionFlowId:c.string().optional(),sourceNodeIds:c.array(c.any()).optional(),type:c.string().optional(),variableKeys:c.array(c.any()).optional()}},{name:"schema_add_tpa_config_parameters",tier:"catalog",description:`
|
|
1096
|
+
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
1097
|
+
- op=ADD_TPA_CONFIG_PARAMETERS \u2014 Result echoes each new parameter's uniqueId. [pre-type-system-refactor only]`,ops:{ADD_TPA_CONFIG_PARAMETERS:"ADD_TPA_CONFIG_PARAMETERS"},inputSchema:{items:c.record(c.any()).optional(),tpaConfigId:c.string().optional()}},{name:"schema_add_tpa_configs",tier:"catalog",description:`
|
|
1098
|
+
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
1099
|
+
- op=ADD_TPA_CONFIGS \u2014 Result echoes each new config's id. Request parameters and response bodies are described afterwards with the ADD_TPA_*_PARAMETER / ADD_TPA_RESPONSE_DATA tools. [pre-type-system-refactor only]`,ops:{ADD_TPA_CONFIGS:"ADD_TPA_CONFIGS"},inputSchema:{items:c.array(c.any()).optional()}},{name:"schema_add_tpa_parameter_children",tier:"catalog",description:`
|
|
1100
|
+
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
1101
|
+
- op=ADD_TPA_PARAMETER_CHILDREN \u2014 Result echoes each new node's uniqueId. [pre-type-system-refactor only]`,ops:{ADD_TPA_PARAMETER_CHILDREN:"ADD_TPA_PARAMETER_CHILDREN"},inputSchema:{items:c.array(c.any()).optional(),parentUniqueId:c.string().optional(),tpaConfigId:c.string().optional()}},{name:"schema_add_tpa_response_data",tier:"catalog",description:`
|
|
1102
|
+
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
1103
|
+
- op=ADD_TPA_RESPONSE_DATA \u2014 Result echoes the new root node's uniqueId. [pre-type-system-refactor only]`,ops:{ADD_TPA_RESPONSE_DATA:"ADD_TPA_RESPONSE_DATA"},inputSchema:{responseBranch:c.enum(["2xx","4xx","5xx"]).optional(),responseData:c.record(c.any()).optional(),tpaConfigId:c.string().optional()}},{name:"schema_add_tpa_response_data_children",tier:"catalog",description:`
|
|
1104
|
+
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
1105
|
+
- op=ADD_TPA_RESPONSE_DATA_CHILDREN \u2014 Result echoes each new node's uniqueId. [pre-type-system-refactor only]`,ops:{ADD_TPA_RESPONSE_DATA_CHILDREN:"ADD_TPA_RESPONSE_DATA_CHILDREN"},inputSchema:{items:c.array(c.any()).optional(),parentUniqueId:c.string().optional(),responseBranch:c.enum(["2xx","4xx","5xx"]).optional(),tpaConfigId:c.string().optional()}},{name:"schema_api",tier:"core",description:"Third-party API integrations: workspaces, APIs, parameters, input variables, response configs, and workspace constants.\nChanges apply immediately; use schema_undo to revert the last change. Ops:\n- op=ADD \u2014 Result echoes each new API's id. [post-type-system-refactor only]\n- op=ADD_INPUT_VARIABLES \u2014 Result echoes each new variable's minted key (the update/delete tools take it). [post-type-system-refactor only]\n- op=ADD_PARAMETERS \u2014 Result echoes each parameter's `schemaPath` \u2014 the value slot for the CREATE_*_BINDING tools, which is how a parameter takes a workspace constant instead of a literal. [post-type-system-refactor only]\n- op=ADD_RESPONSE_CONFIGS \u2014 Result echoes each new config's uniqueId, and the `responseTypeId` of every object type `seedObjectType` minted \u2014 pass that to ADD_TYPE_DEFINITION_FIELDS to describe the response. [post-type-system-refactor only]\n- op=ADD_WORKSPACES \u2014 Result echoes each new workspace's id. [post-type-system-refactor only]\n- op=ADD_WORKSPACE_CONSTANTS \u2014 A constant is created without a value. Result echoes each one's value `schemaPath` (read it back later from GET_API_WORKSPACE_DETAIL), and that slot takes CREATE_CONST_BINDING and nothing else \u2014 no variable, secret, formula or condition, matching the editor's constants table. To let a request use a value the project already holds, bind it on the API's parameter or URL instead. [post-type-system-refactor only]\n- op=DELETE \u2014 Also drops each API from every role's allow-list and deletes the private object types its body and responses owned. [post-type-system-refactor only]\n- op=DELETE_CODECS \u2014 Removes the value conversion from body slots. A media field left without one has no wire representation, so the editor flags it as incomplete. [post-type-system-refactor only]\n- op=DELETE_INPUT_VARIABLES (req: apiId, variableNames) [post-type-system-refactor only]\n- op=DELETE_PARAMETERS (req: apiId, items) [post-type-system-refactor only]\n- op=DELETE_RESPONSE_CONFIGS (req: apiId, uniqueIds) [post-type-system-refactor only]\n- op=DELETE_WORKSPACES \u2014 Deletes API workspaces and everything inside them: the APIs go too \u2014 dropped from every role's allow-list, along with the private object types their bodies and responses owned. Pass `transferToWorkspaceId` to move the APIs and constants into a surviving workspace instead. The result lists what was destroyed. [post-type-system-refactor only]\n- op=DELETE_WORKSPACE_CONSTANTS (req: constantNames, workspaceId) [post-type-system-refactor only]\n- op=DUPLICATE \u2014 Duplicate an API, together with the private object types it owns (its JSON request body and each response type), into the same workspace right after the source or into another one. To regroup an API without copying it use MOVE_APIS_TO_WORKSPACE. The result echoes the new API's id. [post-type-system-refactor only]\n- op=LIST [post-type-system-refactor only]\n- op=LIST_WORKSPACES [post-type-system-refactor only]\n- op=GET_CODEC_OPTIONS \u2014 Lists the request-body and response fields that can carry a value conversion, with the conversions legal at each. Feed a slot's `typeIdentifier`/`field` back to SET_API_CODECS verbatim. [post-type-system-refactor only]\n- op=GET_DETAIL (req: apiId|schemaPath) [post-type-system-refactor only]\n- op=GET_SELECTABLE_TYPES \u2014 List the types one API slot accepts. Every `type` an API tool takes must be a `typeIdentifier` copied from here verbatim. To use a type that is not listed, create it with ADD_OBJECT_TYPE_DEFINITIONS / ADD_ENUM_DEFINITIONS (leave `private` unset, or it stays out of every list) and call this again; to reuse an existing *private* type, publish it first with COPY_PRIVATE_OBJECT_TYPE_AS_PUBLIC. Lists are not enumerated \u2014 the nesting has no end \u2014 so a list is a listed identifier plus the target parameter's `arrayLevel` (1 = list, 2 = list of lists), never brackets written into the identifier; the URL, header and form-body slots carry no `arrayLevel` and take no list at all. An option is offered in its optional form (`null|\u2026`); drop the `null|` to make that slot required, and note the wrapper you pass is the one the list itself gets. [post-type-system-refactor only]\n- op=GET_WORKSPACE_DETAIL \u2014 One workspace in full: its constants \u2014 each with the value `schemaPath` CREATE_CONST_BINDING writes, the only binding that slot takes \u2014 and the APIs it holds. GET_ALL_API_WORKSPACES carries no such path, since one per constant across every workspace is replayed every turn. [post-type-system-refactor only]\n- op=MOVES_TO_WORKSPACE (req: apiIds, targetWorkspaceId) [post-type-system-refactor only]\n- op=SET_CODECS \u2014 Sets how a body slot's value is converted on the wire. Pick the slot and encoder from GET_API_CODEC_OPTIONS. A slot is a field of a type, not a path \u2014 the same object type reused twice shares one conversion. [post-type-system-refactor only]\n- op=SET_CONTENT_TYPE \u2014 Picks the request body's format, discarding the previous body. 'application/json' seeds an empty object type \u2014 describe it with ADD_TYPE_DEFINITION_FIELDS on the `bodyType` GET_API_DETAIL reports; the form formats take their fields from ADD_API_PARAMETERS. [post-type-system-refactor only]\n- op=UPDATE (req: apiId) [post-type-system-refactor only]\n- op=UPDATE_INPUT_VARIABLES (req: apiId, items) [post-type-system-refactor only]\n- op=UPDATE_PARAMETERS (req: apiId, items) [post-type-system-refactor only]\n- op=UPDATE_RESPONSE_CONFIGS \u2014 Result echoes the `responseTypeId` of every object type `seedObjectType` minted \u2014 pass that to ADD_TYPE_DEFINITION_FIELDS to describe the response. Retyping a response deletes the private object type it owned. [post-type-system-refactor only]\n- op=UPDATE_WORKSPACE (req: workspaceId) [post-type-system-refactor only]\n- op=UPDATE_WORKSPACE_CONSTANTS (req: items, workspaceId) [post-type-system-refactor only]",ops:{ADD:"ADD_APIS",ADD_INPUT_VARIABLES:"ADD_API_INPUT_VARIABLES",ADD_PARAMETERS:"ADD_API_PARAMETERS",ADD_RESPONSE_CONFIGS:"ADD_API_RESPONSE_CONFIGS",ADD_WORKSPACES:"ADD_API_WORKSPACES",ADD_WORKSPACE_CONSTANTS:"ADD_API_WORKSPACE_CONSTANTS",DELETE:"DELETE_APIS",DELETE_CODECS:"DELETE_API_CODECS",DELETE_INPUT_VARIABLES:"DELETE_API_INPUT_VARIABLES",DELETE_PARAMETERS:"DELETE_API_PARAMETERS",DELETE_RESPONSE_CONFIGS:"DELETE_API_RESPONSE_CONFIGS",DELETE_WORKSPACES:"DELETE_API_WORKSPACES",DELETE_WORKSPACE_CONSTANTS:"DELETE_API_WORKSPACE_CONSTANTS",DUPLICATE:"DUPLICATE_API",LIST:"GET_ALL_APIS_INFO",LIST_WORKSPACES:"GET_ALL_API_WORKSPACES",GET_CODEC_OPTIONS:"GET_API_CODEC_OPTIONS",GET_DETAIL:"GET_API_DETAIL",GET_SELECTABLE_TYPES:"GET_API_SELECTABLE_TYPES",GET_WORKSPACE_DETAIL:"GET_API_WORKSPACE_DETAIL",MOVES_TO_WORKSPACE:"MOVE_APIS_TO_WORKSPACE",SET_CODECS:"SET_API_CODECS",SET_CONTENT_TYPE:"SET_API_CONTENT_TYPE",UPDATE:"UPDATE_API",UPDATE_INPUT_VARIABLES:"UPDATE_API_INPUT_VARIABLES",UPDATE_PARAMETERS:"UPDATE_API_PARAMETERS",UPDATE_RESPONSE_CONFIGS:"UPDATE_API_RESPONSE_CONFIGS",UPDATE_WORKSPACE:"UPDATE_API_WORKSPACE",UPDATE_WORKSPACE_CONSTANTS:"UPDATE_API_WORKSPACE_CONSTANTS"},inputSchema:{apiId:c.string().optional(),apiIds:c.array(c.any()).optional(),clearContentType:c.boolean().optional(),constantNames:c.array(c.any()).optional(),contentType:c.enum(["application/json","application/x-www-form-urlencoded","multipart/form-data"]).optional(),description:c.string().optional(),detail:c.enum(["SUMMARY","FULL"]).optional(),displayName:c.string().optional(),items:c.array(c.any()).optional(),method:c.enum(["GET","POST","PUT","DELETE","PATCH","OPTIONS","HEAD"]).optional(),paginationEnabled:c.boolean().optional(),responseConfigId:c.string().optional(),schemaPath:c.array(c.any()).optional(),slot:c.enum(["INPUT_VARIABLE","PATH_PARAMETER","QUERY_PARAMETER","HEADER_PARAMETER","FORM_BODY_PARAMETER","JSON_BODY","RESPONSE_BODY","WORKSPACE_CONSTANT"]).optional(),sourceApiId:c.string().optional(),target:c.enum(["REQUEST_BODY","RESPONSE_BODY"]).optional(),targetWorkspaceId:c.string().optional(),transferToWorkspaceId:c.string().optional(),uniqueIds:c.array(c.any()).optional(),url:c.string().optional(),useAsData:c.boolean().optional(),variableNames:c.array(c.any()).optional(),workspaceId:c.string().optional(),workspaceIds:c.array(c.any()).optional()}},{name:"schema_binding_inspect",tier:"core",description:`Inspect a data-binding location (schemaPath: DiffPathComponents) \u2014 selectable options, expected type, and formula operators/config. Feed a returned path into schema_create_binding.
|
|
1106
|
+
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
1107
|
+
- op=BINDING_OPTIONS \u2014 Browse the data options bindable at the schema path as a size-budgeted tree. Options marked '*' exist but mismatch the slot's type \u2014 bind them via a formula/conversion (GET_FORMULA_OPERATORS + CREATE_FORMULA_BINDING), not CREATE_OPTION_BINDING. Subtrees ending in '\u2026 menuPath=[\u2026]' were omitted for size: call again with that menuPath to fetch them. CREATE_OPTION_BINDING's pathInHierarchicalMenu = the menuPath you drilled into (if any) + the option's path in this result; pick it from the tree, never hand-built.
|
|
1108
|
+
- op=BINDING_TYPE \u2014 Report the value type the binding slot at the schema path expects \u2014 check it before creating a binding there.
|
|
1109
|
+
- op=FORMULA_CONFIG_OPTIONS \u2014 List the scalar config shape and allowed values for the formula at the schema path (the \`config\` of CREATE_FORMULA_BINDING / SET_FORMULA_CONFIG).
|
|
1110
|
+
- op=FORMULA_OPERATORS \u2014 List the formula operators valid at the schema path \u2014 pass one to CREATE_FORMULA_BINDING as \`operator\`.`,ops:{BINDING_OPTIONS:"BROWSE_DATA_BINDING_OPTIONS",BINDING_TYPE:"GET_DATA_BINDING_TYPE",FORMULA_CONFIG_OPTIONS:"GET_FORMULA_CONFIG_OPTIONS",FORMULA_OPERATORS:"GET_FORMULA_OPERATORS"},inputSchema:{maxChars:c.number().optional(),menuPath:c.array(c.any()).optional(),rootLevelNameContains:c.string().optional(),schemaPath:c.array(c.any()).optional()}},{name:"schema_callback",tier:"catalog",description:`
|
|
1111
|
+
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
1112
|
+
- op=ADD_CALLBACK_TRIGGERS \u2014 Creates custom webhook endpoints, each firing an action flow when its URL is called; new webhooks are enabled immediately. The request body starts empty \u2014 describe it with the request-body tool this project's type system offers. The flow's input args are seeded as empty bindings \u2014 fill them via the CREATE_*_BINDING tools at the schema paths from GET_CALLBACK_DETAIL. Result echoes each new webhook's id.
|
|
1113
|
+
- op=CLEAR_CALLBACK_REQUEST_BODY (req: callbackId)
|
|
1114
|
+
- op=CLEAR_CALLBACK_RESPONSE_BODY (req: callbackId)
|
|
1115
|
+
- op=DELETE_CALLBACK_CODECS \u2014 Removes the value conversion from webhook body slots. A media field left without one has no wire representation, so the editor flags it as incomplete. [post-type-system-refactor only]
|
|
1116
|
+
- op=DELETE_CALLBACK_TRIGGERS \u2014 Deletes custom webhooks. Fails on managed payment callbacks.
|
|
1117
|
+
- op=GET_ALL_CALLBACKS_INFO \u2014 Lists every webhook: id, name, callbackType, enabled, bound actionFlowId, and \`managed\` (true for the payment callbacks generated when a payment provider is activated, which cannot be edited or deleted).
|
|
1118
|
+
- op=GET_CALLBACK_CODEC_OPTIONS \u2014 Lists the fields of a webhook's request and response bodies that need a value conversion to travel over HTTP, and which conversions are legal on each \u2014 media fields (whose conversion is mandatory: \`required\`) and object fields carried as a JSON string. Feed a slot's \`typeIdentifier\`/\`field\` back to SET_CALLBACK_CODECS verbatim. [post-type-system-refactor only]
|
|
1119
|
+
- op=GET_CALLBACK_DETAIL (req: callbackId|schemaPath)
|
|
1120
|
+
- op=SET_CALLBACK_CODECS \u2014 Sets how the values of a webhook body are converted on the wire, for slots picked from GET_CALLBACK_CODEC_OPTIONS. A slot is a field of a type, not a path \u2014 the same object type reused in two places shares one conversion. [post-type-system-refactor only]
|
|
1121
|
+
- op=SET_CALLBACK_REQUEST_PARAMETERS \u2014 Sets a webhook's request body from a field tree describing the incoming payload. Only DEFAULT webhooks: a payment protocol's payload is fixed by the provider. Pre-type-refactor projects only. [pre-type-system-refactor only]
|
|
1122
|
+
- op=SET_CALLBACK_REQUEST_TYPE \u2014 Sets a webhook's request body to an existing object type definition (its fields describe the incoming payload). Only DEFAULT webhooks: a payment protocol's payload is fixed by the provider. Post-type-refactor projects only. [post-type-system-refactor only]
|
|
1123
|
+
- op=SET_CALLBACK_RESPONSE_BODY_FIELDS \u2014 Sets a webhook's JSON response body from a field tree; every field starts with an empty value \u2014 fill each via the CREATE_*_BINDING tools at the schema paths the result echoes. Requires the response format to be APPLICATION_JSON. Pre-type-refactor projects only. [pre-type-system-refactor only]
|
|
1124
|
+
- op=SET_CALLBACK_RESPONSE_BODY_TYPE \u2014 Sets a webhook's JSON response body to an existing object type definition and seeds an empty value for it \u2014 fill that value via the CREATE_*_BINDING tools at the schema path the result echoes. Requires the response format to be APPLICATION_JSON. Post-type-refactor projects only. [post-type-system-refactor only]
|
|
1125
|
+
- op=SET_CALLBACK_RESPONSE_FORMAT \u2014 Sets the content type a webhook answers with, replacing the response body with an empty one of that format. Result echoes where the new body is configured. Only DEFAULT webhooks: a payment protocol's response is fixed by the provider.
|
|
1126
|
+
- op=SET_CALLBACK_TYPE \u2014 Switches which provider protocol a webhook speaks. This resets both bodies to that protocol's fixed shape \u2014 the request body is replaced by the provider's documented notification payload (generated here) and the response by the acknowledgement it expects, so any body configured before the switch is lost. Switching back to DEFAULT leaves an empty request body and a JSON response. A payment protocol only works once that provider is activated for the project (the runtime verifies signatures with its credentials), and which providers are offered depends on the project's region.
|
|
1127
|
+
- op=UPDATE_CALLBACK_TRIGGER \u2014 Updates a custom webhook's name and/or enabled flag (omitted fields are left unchanged). The bound action flow cannot be changed \u2014 delete the webhook and re-create it to re-point it. The provider protocol is changed by SET_CALLBACK_TYPE, which has to reset the bodies. Fails on managed payment callbacks.`,ops:{ADD_CALLBACK_TRIGGERS:"ADD_CALLBACK_TRIGGERS",CLEAR_CALLBACK_REQUEST_BODY:"CLEAR_CALLBACK_REQUEST_BODY",CLEAR_CALLBACK_RESPONSE_BODY:"CLEAR_CALLBACK_RESPONSE_BODY",DELETE_CALLBACK_CODECS:"DELETE_CALLBACK_CODECS",DELETE_CALLBACK_TRIGGERS:"DELETE_CALLBACK_TRIGGERS",GET_ALL_CALLBACKS_INFO:"GET_ALL_CALLBACKS_INFO",GET_CALLBACK_CODEC_OPTIONS:"GET_CALLBACK_CODEC_OPTIONS",GET_CALLBACK_DETAIL:"GET_CALLBACK_DETAIL",SET_CALLBACK_CODECS:"SET_CALLBACK_CODECS",SET_CALLBACK_REQUEST_PARAMETERS:"SET_CALLBACK_REQUEST_PARAMETERS",SET_CALLBACK_REQUEST_TYPE:"SET_CALLBACK_REQUEST_TYPE",SET_CALLBACK_RESPONSE_BODY_FIELDS:"SET_CALLBACK_RESPONSE_BODY_FIELDS",SET_CALLBACK_RESPONSE_BODY_TYPE:"SET_CALLBACK_RESPONSE_BODY_TYPE",SET_CALLBACK_RESPONSE_FORMAT:"SET_CALLBACK_RESPONSE_FORMAT",SET_CALLBACK_TYPE:"SET_CALLBACK_TYPE",UPDATE_CALLBACK_TRIGGER:"UPDATE_CALLBACK_TRIGGER"},inputSchema:{callbackId:c.string().optional(),callbackIds:c.array(c.any()).optional(),callbackType:c.enum(["DEFAULT","WECHATPAY_MINIPROGRAM","WECHATPAY_PARTNER_MINIPROGRAM","OTTPAY","ALIPAY_WEB","STRIPE_WEB","AIRWALLEX","MALL_BOOK","PAYMENT_CALLBACK"]).optional(),enabled:c.boolean().optional(),fields:c.array(c.any()).optional(),format:c.enum(["APPLICATION_JSON","TEXT_PLAIN","TEXT_HTML"]).optional(),items:c.array(c.any()).optional(),name:c.string().optional(),objectTypeId:c.string().optional(),schemaPath:c.array(c.any()).optional(),target:c.enum(["REQUEST_BODY","RESPONSE_BODY"]).optional()}},{name:"schema_client_variables",tier:"catalog",description:`The current client's app-wide variables \u2014 read by every page, one table per client, and the state that has to survive navigation. A variable inside an action flow is that flow's own and lives in the action-flow facade instead.
|
|
1128
|
+
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
1129
|
+
- op=ADD_CLIENT_VARIABLES \u2014 Declare client variables on this client. The result echoes each new variable's minted key and the schemaPath of its default value, which the binding tools write \u2014 a variable starts with no value, and reads as empty until one is set.
|
|
1130
|
+
- op=DELETE_CLIENT_VARIABLES \u2014 Remove client variables from this client. The bindings and set-client-variable actions that name them are not cleaned up \u2014 deleting a variable something still refers to leaves the project reporting an unknown client variable at each referring site, which the result lists so the caller can repoint or remove them.
|
|
1131
|
+
- op=GET_CLIENT_VARIABLES_INFO \u2014 This client's variables (the globalVariableTable that GET_PROJECT_OVERVIEW lists under globalVariables): each one's key, name, type and current default value, with the schemaPath its default value is written at. Every page of the client reads and sets them, and each client keeps its own table, so what a WEB page binds is not what the mini program binds \u2014 read this against the client you mean to change. A variable declared inside one action flow is that flow's own, not one of these.
|
|
1132
|
+
- op=GET_CLIENT_VARIABLE_SELECTABLE_TYPES \u2014 The value types a client variable can be declared as \u2014 the typeIdentifier vocabulary ADD_CLIENT_VARIABLES and UPDATE_CLIENT_VARIABLES accept.
|
|
1133
|
+
- op=UPDATE_CLIENT_VARIABLES \u2014 Rename a client variable or change its type. The key is what everything refers to, so a rename leaves the references alone; retyping does not, and a binding whose value no longer fits the new type is reported as an error until it is rewritten.`,ops:{ADD_CLIENT_VARIABLES:"ADD_CLIENT_VARIABLES",DELETE_CLIENT_VARIABLES:"DELETE_CLIENT_VARIABLES",GET_CLIENT_VARIABLES_INFO:"GET_CLIENT_VARIABLES_INFO",GET_CLIENT_VARIABLE_SELECTABLE_TYPES:"GET_CLIENT_VARIABLE_SELECTABLE_TYPES",UPDATE_CLIENT_VARIABLES:"UPDATE_CLIENT_VARIABLES"},inputSchema:{items:c.array(c.any()).optional(),variableKeys:c.array(c.any()).optional()}},{name:"schema_component",tier:"core",description:`UI component tree (pages, containers, leaf components). Layout is Flexbox; special components (LIST/TAB_VIEW/SELECT_VIEW/CONDITIONAL_VIEW) take children only in their built-in slots.
|
|
1134
|
+
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
1135
|
+
- op=ADD \u2014 Create components. One call builds a whole subtree \u2014 nest each child definition inside its parent's children/slot field and every level is created together, so build a screen region per call rather than one component per call. New components are appended after their parent's existing children; MOVE_COMPONENTS reorders them afterwards, so create them in the order you want them read. Give every component its styling in this call whenever a design system or a stated style preference applies \u2014 the creation defaults are generic, and restyling later is a second pass over work you already did. Every node takes its own 'style' \u2014 nested children and slot definitions (a LIST's cell, header, footer) alike \u2014 and only each item's outermost component gets its id echoed, so anything left unstyled inside one costs a FIND_COMPONENTS lookup to reach again. A container left without children, or a query no component consumes, is a defect the editor reports: finish a region before starting the next, since anything still unfinished is named back to you before the turn can close. Every size written here is written at the main breakpoint and inherited by all the others, so a card at width '32%' is 32% of a phone screen too \u2014 under 120px, wide enough for about four characters, and the page grows to tens of thousands of pixels tall. Percentage and fixed widths that only make sense beside their siblings in a row need a phone override the moment that row is stacked into a column; reach for 'fill' and fr shares where you can, since those re-solve at whatever width they are given. Reproducing an existing design, build what it uses: an icon in the source is an imported asset in an IMAGE component, not a '\u25C9' or an emoji in a TEXT. Result echoes each new component's minted id.
|
|
1136
|
+
- op=ADD_ACTIONS \u2014 Attach a frontend action to a component event \u2014 or, by sending \`scheduledJobId\` instead of \`eventType\`, to a page's or modal's scheduled job \u2014 or (with attachTo) chain it onto an existing handler's ON_SUCCESS / ON_FAILURE branch. This is the only tool that attaches actions \u2014 every kind goes through it. Call GET_SELECTABLE_COMPONENT_ACTIONS first: it lists what this event and client actually accept, and anything missing from that list can only be built in the editor. Each item's extra fields follow its kind (an ACTION_FLOW names a flow, a NAVIGATION a page, a MUTATION a table and operation, a REFRESH its targets, the component-targeting kinds a target component, a CONDITIONAL its branch names, a payment kind a configId and a paymentProduct, both from GET_PAYMENT_CONFIGS); the rest take no configuration. None of those fields can be changed afterwards \u2014 there is no update tool for an attached action, only delete and re-add \u2014 so get them right on this call. CONDITIONAL is how one event runs different actions for different cases: it evaluates its branches in order and runs the first whose condition holds, so putting the actions in branches is what stops them all firing at once. Its branches come back as conditionalBranchIds \u2014 fill each with a further call whose attachTo carries one, and narrow each condition at the echoed conditionSchemaPath. Every parameter is seeded empty and echoed as a bindableSchemaPath: fill each with CREATE_CONST_BINDING or BROWSE_DATA_BINDING_OPTIONS + CREATE_OPTION_BINDING. Whatever a kind returns beyond that \u2014 a mutation's requestId and column paths, a navigation's seeded page inputs, a call-flow's input args \u2014 arrives under that handler's \`details\`.
|
|
1137
|
+
- op=ADD_INPUTS \u2014 Declare input parameters on a component whose acceptsInputs is true (GET_COMPONENT_INFO reports it; today that means a page or modal, and anything else is rejected). Navigation/show-modal call sites then pass values per input (ADD_COMPONENT_ACTIONS' NAVIGATION kind seeds one binding slot per input). Result echoes each input's key and, for GENERAL inputs, the defaultValue schemaPath for the CREATE_*_BINDING tools.
|
|
1138
|
+
- op=ADD_QUERY \u2014 Attach a database query to a component whose acceptsVariables is true (GET_COMPONENT_INFO reports it; today that means a page or modal, and anything else is rejected). Creates a read-only variable (the editor labels these 'Page variable' in its right panel, on modals too) whose dataSource is a query on the given table, seeded with the mandatory always-true Default filter. Result echoes the variable key and the schema paths for narrowing the filter (GET_REQUEST_FILTER_CONTEXT) and for binding components to the data (CREATE_OPTION_BINDING), plus any roles still lacking SELECT on the table (grant via UPDATE_ROLE_TABLE_PERMISSION).
|
|
1139
|
+
- op=ADD_SCHEDULED_JOBS \u2014 Create timer jobs on a page or modal. A job is a schedule and nothing more: it runs its actions every \`interval\` milliseconds, and a new one starts with none, so follow this call with ADD_COMPONENT_ACTIONS carrying the echoed \`scheduledJobId\` to give it something to do. The result echoes each job's id, name and actionsSchemaPath.
|
|
1140
|
+
- op=ADD_VARIABLES \u2014 Declare read-write (mutable state) variables on a component whose acceptsVariables is true (GET_COMPONENT_INFO reports it; today that means a page or modal, and anything else is rejected). The editor labels them 'Page variable' in its right panel, on modals too. Result echoes each variable's defaultValue schemaPath for the CREATE_*_BINDING tools. A variable starts empty, and an empty variable matches no conditional case, so set that initial value whenever anything tests the variable \u2014 otherwise the page first renders with every dependent case unmatched. Declare one only for state nothing else already holds: a component that has an output publishes it under [Component > <name> > \u2026], so whatever depends on that output should bind to it there. Mirroring it into a variable from an on-change action instead builds a second copy that only updates when that action runs.
|
|
1141
|
+
- op=ADD_CONDITIONAL_VIEW_BRANCHES \u2014 Add branches to a CONDITIONAL_VIEW: each item creates the branch's content container and inserts an always-true branch config before the default case. Narrow each condition via the condition tools at the echoed conditionSchemaPath.
|
|
1142
|
+
- op=ADD_SHEET_COLUMNS \u2014 Add displayed columns to a SHEET, each naming one field of its data source. Result echoes each column's title and width binding schemaPaths.
|
|
1143
|
+
- op=ADD_TAB_VIEW_TABS \u2014 Add tabs to a TAB_VIEW: each item creates the tab's content container (a LAYOUT_VIEW child) and inserts a tabList entry. Result echoes each content child's id and the title binding's schemaPath.
|
|
1144
|
+
- op=CLEAR_SLOT \u2014 Empty an optional slot, deleting the slot child and its subtree.
|
|
1145
|
+
- op=DELETE \u2014 Delete components together with their descendant subtrees. References to the deleted components elsewhere (bindings, event targets) are not cleaned up automatically.
|
|
1146
|
+
- op=DELETE_EVENT_HANDLERS \u2014 Remove event handlers from a component event \u2014 or, by sending \`scheduledJobId\` instead of \`eventType\`, from a page's or modal's scheduled job \u2014 by handler id. Ids are matched at any depth, so a handler chained onto another's ON_SUCCESS / ON_FAILURE branch can be removed on its own; removing a handler also removes whatever is chained beneath it.
|
|
1147
|
+
- op=DELETE_INPUTS \u2014 Remove input parameters by key. Unlike a rename this does not fix up call sites: navigation and show-modal actions still passing a deleted key are left dangling. Result echoes deletedInputKeys.
|
|
1148
|
+
- op=DELETE_SCHEDULED_JOBS \u2014 Delete jobs by id. As in the editor, a job goes even while something still points at it: a SCHEDULED_JOB_CONTROL action that starts or pauses the job keeps its dangling id, which the project validator then reports, so the result lists every handler still referencing each deleted job.
|
|
1149
|
+
- op=DELETE_VARIABLES \u2014 Remove page variables (queries or read-write variables) by key. References elsewhere (component dataSource bindings, set-variable events) are not cleaned up automatically.
|
|
1150
|
+
- op=DELETE_CONDITIONAL_VIEW_BRANCHES \u2014 Delete non-default branches (by content-child id) with their subtrees; the default case cannot be deleted.
|
|
1151
|
+
- op=DELETE_SHEET_COLUMNS (req: componentId, dataFieldNames)
|
|
1152
|
+
- op=DELETE_TAB_VIEW_TABS \u2014 Delete tabs (addressed by their content-child ids) together with their content subtrees. A TAB_VIEW keeps at least 2 tabs.
|
|
1153
|
+
- op=DUPLICATE \u2014 Duplicate components with everything inside them. With no targetParentComponentId each one is duplicated in place, next to its source; naming a container puts the whole selection into it as one group, which is what keeps references between the copied components pointing at each other. To move a component instead of copying it use MOVE_COMPONENTS, which keeps its id so everything already pointing at it keeps working. References the destination cannot resolve \u2014 a variable of a page the copy no longer sits in, a media resource from another project \u2014 are blanked rather than carried over, so re-check the copies' bindings.
|
|
1154
|
+
- op=DUPLICATE_ACTIONS \u2014 Copy the action handlers of one component event onto another event, appending them to whatever is already there. Requests and actions inside the copies are re-minted, so a copy is independent of the original. The result echoes each copy's schema path for follow-up binding edits.
|
|
1155
|
+
- op=FIND \u2014 Resolve a component's display name to the componentId every other component tool needs, without walking the tree. Case-insensitive substring over display name and id, ranked exact-first, each match reported with the page or modal it sits on. Display names are not unique, so every match is returned \u2014 pick by rootDisplayName rather than assuming the first. Pages and modals are matched too, and are the one case where rootComponentId/rootDisplayName come back null: a root has no root above it. Read tools take a root id like any other, but a root is not a move or delete target the way a child is. Use GET_ALL_ROOTS_INFO instead when you need to enumerate what exists rather than resolve a name you already have.
|
|
1156
|
+
- op=GET_ALL_ROOTS_INFO \u2014 List this client's roots \u2014 every page AND every modal, each as {id, displayName}. A modal is a root in its own right: it has no parent and is reached only through events. The ids returned are what every component read and edit is keyed by; a display name alone cannot address one. GET_PROJECT_OVERVIEW already returns those same page and modal ids, so call this only when you have not run the overview.
|
|
1157
|
+
- op=GET_BINDABLE_PROPERTIES \u2014 Every place this component can be bound, with ready-to-use schemaPaths for BROWSE_DATA_BINDING_OPTIONS / CREATE_*_BINDING \u2014 never hand-assemble binding paths. 'properties' are the component's own property slots, each with its expected type, a summary of its current binding, the scope (inside a list cell the options tree offers the current row at [Context, List item, \u2026]) and which binding tool to use. 'actionSlots' are the parameter slots of the actions already attached to its events, chained success/failure branches included \u2014 this is how an action's parameters are found again after the ADD_COMPONENT_ACTIONS echo that first reported them is gone. Qualifies as a component read for the follow-up binding edits.
|
|
1158
|
+
- op=GET_CONTEXT_INFO (req: componentId)
|
|
1159
|
+
- op=GET_INFO \u2014 One component's configuration, plus an \`outputs\` list of what it produces for the rest of the page to read. Check that before adding state to hold a value some component already publishes. \`styles\` resolve at the main breakpoint unless \`breakpoint\` names another, and say which fields a narrower breakpoint overrides rather than inherits \u2014 a field it does not override renders the main breakpoint's value at that width. \`acceptsVariables\` and \`acceptsInputs\` say whether this component can hold variables and input parameters at all. Every variable tool \u2014 ADD_COMPONENT_VARIABLES, ADD_COMPONENT_QUERY, UPDATE_COMPONENT_QUERY, DELETE_COMPONENT_VARIABLES, and the target of a SET_VARIABLE_DATA action \u2014 is rejected where acceptsVariables is false, and the input tools likewise where acceptsInputs is false. Since a batch applies all-or-nothing, one such write throws away every other edit sent in the same call.
|
|
1160
|
+
- op=GET_SELECTABLE_EVENTS \u2014 The event fields a component exposes and whether each takes action handlers (vs visual interaction states). A PAGE or MODAL also carries timer jobs, which are not event fields: ADD_COMPONENT_SCHEDULED_JOBS creates one and ADD_COMPONENT_ACTIONS fills its run.
|
|
1161
|
+
- op=GET_TEMPLATE \u2014 A valid starter item for ADD_COMPONENT's items array for one component type, plus the edits it requires (display name, parent id, slot children).
|
|
1162
|
+
- op=GET_TYPE_CAPABILITIES \u2014 Per component type, the style fields it honours and the permitted values of every closed-set field among them. The names are the ones UPDATE_COMPONENT_STYLE takes, and ADD_COMPONENT's 'style' object takes the same set. Type-level, so it answers before the component exists \u2014 read it once for the types a screen needs, then style each component as you create it instead of restyling afterwards. GET_COMPONENT_INFO reports the same vocabulary for one component that already exists.
|
|
1163
|
+
- op=GET_VARIABLE_SELECTABLE_TYPES \u2014 The value types a variable can be declared as \u2014 the typeIdentifier vocabulary ADD_COMPONENT_VARIABLES accepts. Pass pageInputCategory when you are declaring a page INPUT instead: a URL-backed input takes less than a variable does, and the unfiltered answer offers types it cannot carry.
|
|
1164
|
+
- op=GET_CHILDREN_INFO \u2014 The direct children of one container, in visual order \u2014 children order IS the order they render in. One level only: a child's own children are not included, so walk down by calling this again with that child's id. Each entry carries {id, type, displayName} plus its events and properties, so this is how you verify a subtree you just built. Also the way to see a slotted special's slot children (a LIST's cell/header/footer, a SELECT_VIEW's normal/selected, a TAB_VIEW's tab children) \u2014 they are not in a \`children\` array and appear nowhere else. Each entry's \`flexContainer\` says whether gap, flexDirection, justifyContent and alignItems can be set on it at all: they are rejected on any child where it is false, and since a batch applies all-or-nothing, one such write throws away every other edit sent in the same call. To space out children that are not in a flex container, wrap them in a LAYOUT_VIEW and set gap on that. Direction, alignment and flexContainer are read at the main breakpoint unless \`breakpoint\` names another.
|
|
1165
|
+
- op=GET_INCOMPLETE_STRUCTURES \u2014 Containers on this client that hold no children. Every schemaops call can succeed and still leave one of these behind: a container is valid when empty, so neither the error center nor an apply-time failure reports it, and the only symptom is a box the user sees and you do not. A container you created and never filled means a step you intended was dropped. \`responsiveRisks\` is the same kind of silent failure one breakpoint over: components whose desktop width cannot fit the narrow panel and that have nothing set there, which render off the side of a phone while every call that built them reports success.
|
|
1166
|
+
- op=GET_SELECTABLE_TYPES \u2014 Catalog of the component types ADD_COMPONENT can create: category (layout container / slotted special / leaf), the children or slot fields each takes, and placement notes.
|
|
1167
|
+
- op=MOVE \u2014 Reparent and/or reorder components among PAGE / MODAL / LAYOUT_VIEW containers. Children order is the visual order.
|
|
1168
|
+
- op=REORDER_CONDITIONAL_VIEW_BRANCHES \u2014 Branch order is evaluation order (first matching condition wins); the default case stays last.
|
|
1169
|
+
- op=REORDER_SHEET_COLUMNS \u2014 Column order is left-to-right display order.
|
|
1170
|
+
- op=REORDER_TAB_VIEW_TABS (req: componentId, orderedTabChildComponentIds)
|
|
1171
|
+
- op=SET_SLOT \u2014 Fill an empty optional slot of a special component with a freshly created default child: LIST 'header'/'footer' (LAYOUT_VIEW) or MAP 'marker' (MAP_MARKER). LIST 'cell' and SELECT_VIEW states are fixed at creation; a TAB_VIEW's custom-bar slots move together, via SET_TAB_VIEW_TAB_MODE.
|
|
1172
|
+
- op=SET_INITIAL_PAGE_ID \u2014 Set the app's initial (home) page for the current client.
|
|
1173
|
+
- op=SET_SHEET_DATA_SOURCE \u2014 Point a SHEET at a table: builds the sheet's embedded database query (all selectable columns by default) and echoes the query's schemaPath so filters and sorts can be added there with the request tools. A SHEET without a data source is invalid.
|
|
1174
|
+
- op=SET_TAB_VIEW_TAB_MODE \u2014 Switch a TAB_VIEW between the built-in tab bar (NORMAL) and custom tab components (CUSTOM), after creation. CUSTOM mints two empty LAYOUT_VIEWs \u2014 one rendered for an unselected tab, one for the selected tab \u2014 and echoes their ids to fill with ADD_COMPONENT. NORMAL deletes those two and their subtrees.
|
|
1175
|
+
- op=UPDATE_INPUT \u2014 Rename an input, or change its type, array level or optionality. A rename rekeys every call site that passes it (navigation and show-modal input maps); those are listed back under cleanedDanglingReferences.
|
|
1176
|
+
- op=UPDATE_PROPERTIES \u2014 Merge-based update of a component's non-binding scalar properties (feature toggles, modes, numeric limits, plain-string fields) and/or its displayName \u2014 only provided fields change. The fields each componentType accepts, and every enum's legal values, are enumerated in this tool's own parameter schema \u2014 read them there rather than guessing. Binding-valued properties (title, dataSource, defaultValue, placeholder, \u2026) are rejected here; list and fill those via GET_COMPONENT_BINDABLE_PROPERTIES + CREATE_*_BINDING.
|
|
1177
|
+
- op=UPDATE_QUERY \u2014 Change an existing query variable's row limit or display name. A limit of 1 means a single row; crossing 1 <-> more than 1 retypes the variable between row and list, so bindings written against the old shape need re-checking.
|
|
1178
|
+
- op=UPDATE_SCHEDULED_JOB \u2014 Change a job's name, interval (milliseconds) or whether it runs at page load; a field left out keeps its current value. This never touches the job's actions \u2014 those are ADD_COMPONENT_ACTIONS and DELETE_COMPONENT_EVENT_HANDLERS with its \`scheduledJobId\`.
|
|
1179
|
+
- op=UPDATE_STYLE \u2014 Merge-based style update: only provided fields change (size, background, opacity, padding/margin, border incl. line style, shadow, cursor, flex gap/direction/alignment, text color/size/weight/align). Writes the client's main breakpoint unless a breakpoint key is given (non-main breakpoints store only deltas). Pass variant='hover' to style the hover interaction state (per breakpoint; no cross-breakpoint inheritance). Colour fields (backgroundColor/textColor/borderColor) take a hex literal or a colour variable's referenceValue ('$$<id>'). Spacing (padding/margin/gap/rowGap/columnGap), radius (borderRadius/borderRadiusCorners), fontSize, fontWeight and fontFamily take a reference to a variable of the matching class. These tools apply as an atomic batch: one reference the client cannot resolve fails everything sent with it. Bind the theme as you build \u2014 a literal is pinned where you wrote it, so a project styled in literals can only be restyled component by component. A reference resolves against the variable class the field belongs to, so the same id under padding means a spacing and under borderRadius a radius. GET_PROJECT_OVERVIEW lists the colour ids this client defines \u2014 read them there rather than from memory. Which fields a component accepts depends on its type \u2014 GET_COMPONENT_INFO lists them under style.applicableFields alongside the values already set.`,ops:{ADD:"ADD_COMPONENT",ADD_ACTIONS:"ADD_COMPONENT_ACTIONS",ADD_INPUTS:"ADD_COMPONENT_INPUTS",ADD_QUERY:"ADD_COMPONENT_QUERY",ADD_SCHEDULED_JOBS:"ADD_COMPONENT_SCHEDULED_JOBS",ADD_VARIABLES:"ADD_COMPONENT_VARIABLES",ADD_CONDITIONAL_VIEW_BRANCHES:"ADD_CONDITIONAL_VIEW_BRANCHES",ADD_SHEET_COLUMNS:"ADD_SHEET_COLUMNS",ADD_TAB_VIEW_TABS:"ADD_TAB_VIEW_TABS",CLEAR_SLOT:"CLEAR_COMPONENT_SLOT",DELETE:"DELETE_COMPONENTS",DELETE_EVENT_HANDLERS:"DELETE_COMPONENT_EVENT_HANDLERS",DELETE_INPUTS:"DELETE_COMPONENT_INPUTS",DELETE_SCHEDULED_JOBS:"DELETE_COMPONENT_SCHEDULED_JOBS",DELETE_VARIABLES:"DELETE_COMPONENT_VARIABLES",DELETE_CONDITIONAL_VIEW_BRANCHES:"DELETE_CONDITIONAL_VIEW_BRANCHES",DELETE_SHEET_COLUMNS:"DELETE_SHEET_COLUMNS",DELETE_TAB_VIEW_TABS:"DELETE_TAB_VIEW_TABS",DUPLICATE:"DUPLICATE_COMPONENTS",DUPLICATE_ACTIONS:"DUPLICATE_COMPONENT_ACTIONS",FIND:"FIND_COMPONENTS",GET_ALL_ROOTS_INFO:"GET_ALL_ROOTS_INFO",GET_BINDABLE_PROPERTIES:"GET_COMPONENT_BINDABLE_PROPERTIES",GET_CONTEXT_INFO:"GET_COMPONENT_CONTEXT_INFO",GET_INFO:"GET_COMPONENT_INFO",GET_SELECTABLE_EVENTS:"GET_COMPONENT_SELECTABLE_EVENTS",GET_TEMPLATE:"GET_COMPONENT_TEMPLATE",GET_TYPE_CAPABILITIES:"GET_COMPONENT_TYPE_CAPABILITIES",GET_VARIABLE_SELECTABLE_TYPES:"GET_COMPONENT_VARIABLE_SELECTABLE_TYPES",GET_CHILDREN_INFO:"GET_CONTAINER_CHILDREN_INFO",GET_INCOMPLETE_STRUCTURES:"GET_INCOMPLETE_STRUCTURES",GET_SELECTABLE_TYPES:"GET_SELECTABLE_COMPONENT_TYPES",MOVE:"MOVE_COMPONENTS",REORDER_CONDITIONAL_VIEW_BRANCHES:"REORDER_CONDITIONAL_VIEW_BRANCHES",REORDER_SHEET_COLUMNS:"REORDER_SHEET_COLUMNS",REORDER_TAB_VIEW_TABS:"REORDER_TAB_VIEW_TABS",SET_SLOT:"SET_COMPONENT_SLOT",SET_INITIAL_PAGE_ID:"SET_INITIAL_PAGE_ID",SET_SHEET_DATA_SOURCE:"SET_SHEET_DATA_SOURCE",SET_TAB_VIEW_TAB_MODE:"SET_TAB_VIEW_TAB_MODE",UPDATE_INPUT:"UPDATE_COMPONENT_INPUT",UPDATE_PROPERTIES:"UPDATE_COMPONENT_PROPERTIES",UPDATE_QUERY:"UPDATE_COMPONENT_QUERY",UPDATE_SCHEDULED_JOB:"UPDATE_COMPONENT_SCHEDULED_JOB",UPDATE_STYLE:"UPDATE_COMPONENT_STYLE"},inputSchema:{arrayLevel:c.number().optional(),attachTo:c.record(c.any()).optional(),branchChildComponentIds:c.array(c.any()).optional(),breakpoint:c.string().optional(),childDisplayName:c.string().optional(),columns:c.array(c.any()).optional(),componentId:c.string().optional(),componentIds:c.array(c.any()).optional(),componentType:c.enum(["PAGE","BUTTON","TEXT","LAYOUT_VIEW","LIST","IMAGE","VIDEO","LOTTIE","WECHAT_NAVIGATION_BAR","MOBILE_NAVIGATION_BAR","RICH_TEXT","TEXT_INPUT","NUMBER_INPUT","VIDEO_PICKER","TAB_VIEW","SELECT_VIEW","SWITCH","MODAL","MAP","MAP_MARKER","WECHAT_ADVERT_BANNER","LOTTIE_PROGRESS_BAR","CALENDAR","CAMERA","CONDITIONAL_VIEW","WECHAT_OFFICIAL_ACCOUNT","HORIZONTAL_LINE","CODE_COMPONENT","SHEET","HTML","RICH_TEXT_EDITOR","MIX_IMAGE_PICKER","DATE_TIME_PICKER","DATA_SELECTOR","PROGRESS_BAR"]).optional(),componentTypes:c.array(c.any()).optional(),dataFieldNames:c.array(c.any()).optional(),eventType:c.string().optional(),fullComponentConfigs:c.boolean().optional(),handlerIds:c.array(c.any()).optional(),includeSiblings:c.boolean().optional(),index:c.number().optional(),inputKey:c.string().optional(),inputKeys:c.array(c.any()).optional(),interval:c.number().optional(),items:c.array(c.any()).optional(),limit:c.number().optional(),mode:c.enum(["CUSTOM","NORMAL"]).optional(),name:c.string().optional(),newDisplayName:c.string().optional(),newName:c.string().optional(),normalTabDisplayName:c.string().optional(),optional:c.boolean().optional(),orderedBranchChildComponentIds:c.array(c.any()).optional(),orderedDataFieldNames:c.array(c.any()).optional(),orderedTabChildComponentIds:c.array(c.any()).optional(),pageId:c.string().optional(),pageInputCategory:c.enum(["GENERAL","URL_PATH","URL_QUERY"]).optional(),properties:c.record(c.any()).optional(),query:c.string().optional(),queryDisplayName:c.string().optional(),rootComponentId:c.string().optional(),scheduledJobId:c.string().optional(),scheduledJobIds:c.array(c.any()).optional(),schemaPath:c.array(c.any()).optional(),selectedTabDisplayName:c.string().optional(),slotField:c.string().optional(),sourceComponentId:c.string().optional(),sourceEventType:c.string().optional(),startImmediately:c.boolean().optional(),style:c.record(c.any()).optional(),tabChildComponentIds:c.array(c.any()).optional(),tableDisplayName:c.string().optional(),targetParentComponentId:c.string().optional(),typeIdentifier:c.string().optional(),variableKey:c.string().optional(),variableKeys:c.array(c.any()).optional(),variant:c.string().optional()}},{name:"schema_condition_expr",tier:"core",description:`Edit the boolean condition expression at a binding location (schemaPath). LIST_OPERATORS returns the comparisons available for a term; SET_OPERATOR sets one.
|
|
1180
|
+
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
1181
|
+
- op=DELETE_TERM \u2014 Remove the condition at the schema path from its AND/OR group. Deleting the root or a group's only member resets that level to always-true.
|
|
1182
|
+
- op=DUPLICATE_CONDITION \u2014 Copy a condition \u2014 the whole AND/OR tree of a slot, or one member of it \u2014 onto another condition slot, replacing what that slot held. A reference the target cannot resolve (a variable of the source's own scope, say) is blanked rather than carried over, so re-check the new condition's operands.
|
|
1183
|
+
- op=LIST_OPERATORS \u2014 List the operators (_eq, _gt, _in, \u2026) valid for the expression condition at the schema path, derived from its target/value types \u2014 apply one with UPDATE_EXPRESSION_CONDITION_OPERATOR. A condition whose target is still unbound has no types to narrow by, so that list is the full set with each operator's accepted signatures echoed: pick by signature there, and re-list once the operands are bound when the choice is not obvious.
|
|
1184
|
+
- op=INSERT_TERM \u2014 Append a new always-true condition to the AND/OR group at the schema path (a lone condition is wrapped into an AND group with the new one). Two absent/single slots are filled instead of appended: a request filter's or aggregate's whereCondition that is not written yet gets its first always-true condition (only while its column \`where\` is empty; a configured column where is rejected), and the bare always-true condition an emptied tree holds is reused in place. Either way the echoed path is the condition to configure, with no second always-true condition left behind. Turn it into a real comparison with UPDATE_EXPRESSION_CONDITION_OPERATOR, then fill its target/value bindings via the CREATE_*_BINDING tools. Result echoes the inserted condition's schema path.
|
|
1185
|
+
- op=NEST \u2014 Wrap the condition at the schema path into a new single-member AND/OR group, creating a nesting level for complex logic.
|
|
1186
|
+
- op=SET_CONSTANT \u2014 Replace the condition at the schema path with a constant one: NEVER stops whatever it gates from ever running, ALWAYS restores the neutral always-true state. Passing the condition slot's own path replaces the whole AND/OR tree; passing a member's path replaces only that member. ALWAYS is also the way back from an OS-type / WeChat-permission condition to an expression one \u2014 follow it with UPDATE_EXPRESSION_CONDITION_OPERATOR.
|
|
1187
|
+
- op=SET_OS_TYPE \u2014 Replace the condition at the schema path with one that holds only on the given operating system. Same addressing as SET_CONSTANT_CONDITION; the condition takes no operands, so there is nothing left to bind afterwards.
|
|
1188
|
+
- op=SET_WECHAT_PERMISSION \u2014 Replace the condition at the schema path with one that holds only when the user has granted the given WeChat mini-program permission. Same addressing as SET_CONSTANT_CONDITION; the condition takes no operands, so there is nothing left to bind afterwards.
|
|
1189
|
+
- op=TOGGLE_AND_OR (req: schemaPath)
|
|
1190
|
+
- op=TOGGLE_NOT (req: schemaPath)
|
|
1191
|
+
- op=SET_OPERATOR \u2014 Set the comparison operator of the condition at the schema path. This is where a condition starts, whether INSERT_CONDITION_BOOL_EXP just added it or the slot was already an always-true condition (an emptied condition tree's leaf). The condition becomes an expression condition with an empty target binding \u2014 fill its target/value via the CREATE_*_BINDING tools; unary operators (is-null / is-true / is-empty variants) drop the value.`,ops:{DELETE_TERM:"DELETE_CONDITION_BOOL_EXP",DUPLICATE_CONDITION:"DUPLICATE_CONDITION",LIST_OPERATORS:"GET_EXPRESSION_CONDITION_OPERATORS",INSERT_TERM:"INSERT_CONDITION_BOOL_EXP",NEST:"NEST_CONDITION_BOOL_EXP",SET_CONSTANT:"SET_CONSTANT_CONDITION",SET_OS_TYPE:"SET_OS_TYPE_CONDITION",SET_WECHAT_PERMISSION:"SET_WECHAT_PERMISSION_CONDITION",TOGGLE_AND_OR:"TOGGLE_CONDITION_BOOL_EXP_AND_OR",TOGGLE_NOT:"TOGGLE_CONDITION_BOOL_EXP_NOT",SET_OPERATOR:"UPDATE_EXPRESSION_CONDITION_OPERATOR"},inputSchema:{operator:c.string().optional(),osType:c.enum(["IOS","ANDROID","MAC","WINDOWS","DEVTOOLS"]).optional(),permission:c.enum(["USER_INFO","USER_LOCATION","WE_RUN","RECORD","WRITE_PHOTOS_ALBUM","CAMERA"]).optional(),schemaPath:c.array(c.any()).optional(),sourceSchemaPath:c.array(c.any()).optional(),type:c.enum(["ALWAYS","NEVER"]).optional()}},{name:"schema_conditional_branch",tier:"core",description:`Manage branches of a conditional binding (schemaPath). Build each branch predicate with schema_condition_expr.
|
|
1192
|
+
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
1193
|
+
- op=DELETE \u2014 Delete one branch of the conditional binding at the schema path.
|
|
1194
|
+
- op=INSERT \u2014 Insert a new branch into the conditional binding at the schema path. Result echoes the new branch's id.
|
|
1195
|
+
- op=REORDER \u2014 Reorder the branches (= evaluation order) of the conditional binding at the schema path.
|
|
1196
|
+
- op=UPDATE \u2014 Replace fields (condition / value / name) of one branch of the conditional binding at the schema path.`,ops:{DELETE:"DELETE_CONDITIONAL_DATA",INSERT:"INSERT_CONDITIONAL_DATA",REORDER:"REORDER_CONDITIONAL_DATA",UPDATE:"UPDATE_CONDITIONAL_DATA"},inputSchema:{afterId:c.string().optional(),conditionData:c.record(c.any()).optional(),id:c.string().optional(),reorderedIds:c.array(c.any()).optional(),schemaPath:c.array(c.any()).optional()}},{name:"schema_create_binding",tier:"core",description:`Create a data binding at a binding location (schemaPath). op=OPTION uses a pathInHierarchicalMenu from schema_binding_inspect; op=FORMULA an operator from FORMULA_OPERATORS. operation defaults to REPLACE (CONCAT to append).
|
|
1197
|
+
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
1198
|
+
- op=CONDITIONAL \u2014 Replace the binding at the schema path with a conditional binding: ordered branches of condition + value, evaluated in order \u2014 the first branch whose condition holds supplies the value. Branches start always-true with empty values: manage them with the *_CONDITIONAL_DATA tools, narrow conditions via the condition tools, fill values via the CREATE_*_BINDING tools. Result echoes the branch ids.
|
|
1199
|
+
- op=CONST \u2014 Bind a literal constant value at the schema path.
|
|
1200
|
+
- op=FORMULA \u2014 Bind a computed formula at the schema path \u2014 pick \`operator\` from GET_FORMULA_OPERATORS, then fill the formula's argument slots via further CREATE_*_BINDING calls at their paths.
|
|
1201
|
+
- op=OPTION \u2014 Bind a dynamic value (variable / column / node output \u2026) at the schema path, picked from the BROWSE_DATA_BINDING_OPTIONS tree.
|
|
1202
|
+
- op=SET_FORMULA_CONFIG (req: config, schemaPath)
|
|
1203
|
+
- op=SET_FUNCTION_BINDING_PAGE_URL_TARGET \u2014 Set the target page of a getPageUrl function binding (the global 'page url' option), which binding that option leaves unset. Re-seeds the function binding's page parameters (args) from the target page's inputs; the result echoes each parameter's schema path for the CREATE_*_BINDING tools.`,ops:{CONDITIONAL:"CREATE_CONDITIONAL_BINDING",CONST:"CREATE_CONST_BINDING",FORMULA:"CREATE_FORMULA_BINDING",OPTION:"CREATE_OPTION_BINDING",SET_FORMULA_CONFIG:"SET_FORMULA_CONFIG",SET_FUNCTION_BINDING_PAGE_URL_TARGET:"SET_FUNCTION_BINDING_PAGE_URL_TARGET"},inputSchema:{config:c.any().optional(),constantValue:c.any().optional(),initialBranchNames:c.array(c.any()).optional(),operation:c.enum(["REPLACE","CONCAT"]).optional(),operator:c.string().optional(),pageId:c.string().optional(),pathInHierarchicalMenu:c.array(c.any()).optional(),schemaPath:c.array(c.any()).optional()}},{name:"schema_custom_array_binding",tier:"core",description:`Add or delete items of a custom-array binding (schemaPath) \u2014 a list literal composed item by item, created by binding the Custom > Array option with schema_create_binding. ADD returns itemSchemaPaths to fill with schema_create_binding.
|
|
1204
|
+
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
1205
|
+
- op=ADD \u2014 Append empty items to the custom-array binding (a list literal composed item by item) at the schema path \u2014 the only way to grow one, since the binding tools write existing items only. Result echoes each new item's schema path: fill it via the CREATE_*_BINDING tools, or, when the item is itself an array, grow it with this tool at that path.
|
|
1206
|
+
- op=DELETE \u2014 Delete items from the custom-array binding at the schema path; later items shift down.`,ops:{ADD:"ADD_CUSTOM_ARRAY_BINDING_ITEMS",DELETE:"DELETE_CUSTOM_ARRAY_BINDING_ITEMS"},inputSchema:{count:c.number().optional(),indexes:c.array(c.any()).optional(),schemaPath:c.array(c.any()).optional()}},{name:"schema_delete_tpa_config_parameters",tier:"catalog",description:`
|
|
1207
|
+
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
1208
|
+
- op=DELETE_TPA_CONFIG_PARAMETERS (req: parameterUniqueIds, tpaConfigId) [pre-type-system-refactor only]`,ops:{DELETE_TPA_CONFIG_PARAMETERS:"DELETE_TPA_CONFIG_PARAMETERS"},inputSchema:{parameterUniqueIds:c.array(c.any()).optional(),tpaConfigId:c.string().optional()}},{name:"schema_delete_tpa_configs",tier:"catalog",description:`
|
|
1209
|
+
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
1210
|
+
- op=DELETE_TPA_CONFIGS (req: tpaConfigIds) [pre-type-system-refactor only]`,ops:{DELETE_TPA_CONFIGS:"DELETE_TPA_CONFIGS"},inputSchema:{tpaConfigIds:c.array(c.any()).optional()}},{name:"schema_delete_tpa_parameter_children",tier:"catalog",description:`
|
|
1211
|
+
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
1212
|
+
- op=DELETE_TPA_PARAMETER_CHILDREN (req: dataUniqueIds, tpaConfigId) [pre-type-system-refactor only]`,ops:{DELETE_TPA_PARAMETER_CHILDREN:"DELETE_TPA_PARAMETER_CHILDREN"},inputSchema:{dataUniqueIds:c.array(c.any()).optional(),tpaConfigId:c.string().optional()}},{name:"schema_delete_tpa_response_data",tier:"catalog",description:`
|
|
1213
|
+
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
1214
|
+
- op=DELETE_TPA_RESPONSE_DATA (req: responseBranch, tpaConfigId) [pre-type-system-refactor only]`,ops:{DELETE_TPA_RESPONSE_DATA:"DELETE_TPA_RESPONSE_DATA"},inputSchema:{responseBranch:c.enum(["2xx","4xx","5xx"]).optional(),tpaConfigId:c.string().optional()}},{name:"schema_delete_tpa_response_data_children",tier:"catalog",description:`
|
|
1215
|
+
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
1216
|
+
- op=DELETE_TPA_RESPONSE_DATA_CHILDREN (req: dataUniqueIds, responseBranch, tpaConfigId) [pre-type-system-refactor only]`,ops:{DELETE_TPA_RESPONSE_DATA_CHILDREN:"DELETE_TPA_RESPONSE_DATA_CHILDREN"},inputSchema:{dataUniqueIds:c.array(c.any()).optional(),responseBranch:c.enum(["2xx","4xx","5xx"]).optional(),tpaConfigId:c.string().optional()}},{name:"schema_design_system",tier:"catalog",description:`
|
|
1217
|
+
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
1218
|
+
- op=GET_STYLE_SCALE \u2014 This project's spacing steps, radius steps, named text styles (name + size/weight/line height) and font families. Take this before styling: values you send to UPDATE_COMPONENT_STYLE are pulled onto the nearest step, and a font size near a role brings that role's weight and line height with it, so the scale is how you predict what actually gets stored. A project that never defined one reads back saying which axes are undefined and carrying a starter scale ready to send to SET_STYLE_SCALE.
|
|
1219
|
+
- op=SET_STYLE_SCALE \u2014 Define this client's spacing steps, radius steps, named text styles and font families. Each axis is set as a whole: omit to keep it, send the full list to replace it, send [] to drop it. Style values are stored literally, so this restyles nothing by itself \u2014 what it does is stop the vocabulary from spreading. Left undefined, a build drifts into paddings of 12 and 14 and 18 and radii of 9 and 10 and 12, which is what reads as unfinished even when every screen is individually reasonable. Text is defined as roles rather than loose numbers (Page Title 32/700/40, Body 16/400/24): a font size near a role is stored as that whole role, so the hierarchy cannot come apart into heading size at body weight. Six or seven spacing steps and five or six roles are enough for an app.`,ops:{GET_STYLE_SCALE:"GET_STYLE_SCALE",SET_STYLE_SCALE:"SET_STYLE_SCALE"},inputSchema:{fontFamilies:c.array(c.any()).optional(),radius:c.array(c.any()).optional(),spacing:c.array(c.any()).optional(),textStyles:c.array(c.any()).optional()}},{name:"schema_get_all_tpa_configs_info",tier:"catalog",description:`
|
|
1220
|
+
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
1221
|
+
- op=GET_ALL_TPA_CONFIGS_INFO [pre-type-system-refactor only]`,ops:{GET_ALL_TPA_CONFIGS_INFO:"GET_ALL_TPA_CONFIGS_INFO"},inputSchema:{}},{name:"schema_get_tpa_config_detail",tier:"catalog",description:`
|
|
1222
|
+
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
1223
|
+
- op=GET_TPA_CONFIG_DETAIL (req: tpaConfigId) [pre-type-system-refactor only]`,ops:{GET_TPA_CONFIG_DETAIL:"GET_TPA_CONFIG_DETAIL"},inputSchema:{detail:c.enum(["SUMMARY","FULL"]).optional(),tpaConfigId:c.string().optional()}},{name:"schema_overview",tier:"catalog",description:"\nChanges apply immediately; use schema_undo to revert the last change. Ops:\n- op=GET_ENTITY_RELATION_GRAPH (req: entityId, entityType)\n- op=GET_PROJECT_OVERVIEW \u2014 One-shot compact inventory of every top-level entity (tables, flows, triggers, webhooks, APIs, agents, roles, types \u2026) with the ids/names the other tools take \u2014 the recommended first call on an unfamiliar project. It covers pages and modals too, so GET_ALL_ROOTS_INFO adds nothing after it, and it lists every table \u2014 a table carrying `systemDefined: true` (RBAC, payment, AI) can still be read and queried, only its structure is fixed. `authMethods` is the one thing here no other tool reports: which identifiers an account can be created and signed in with. A sign-up or sign-in for a method that is off is refused, and no tool can turn one on \u2014 read it before building either, rather than finding out when the write fails. `timezone.zoneId` is the zone date-time formulas and filters use wherever no timezone is bound: the project's own setting, or the product default when `setInProject` is false.",ops:{GET_ENTITY_RELATION_GRAPH:"GET_ENTITY_RELATION_GRAPH",GET_PROJECT_OVERVIEW:"GET_PROJECT_OVERVIEW"},inputSchema:{depth:c.number().optional(),entityId:c.string().optional(),entityType:c.enum(["TABLE","API","ACTION_FLOW","ZAI","ROLE","TRIGGER","COMPONENT","GLOBAL_VARIABLE"]).optional(),entityTypes:c.array(c.any()).optional(),relationTypes:c.array(c.any()).optional()}},{name:"schema_payment",tier:"catalog",description:"\nChanges apply immediately; use schema_undo to revert the last change. Ops:\n- op=ACTIVATE_PAYMENT \u2014 Activate one payment type. First activation also inserts the payment tables and relations (an existing order table must be named); every activation appends the type's generated action flows / callbacks / scheduled jobs and registers its triggers. Provider credentials are saved out of band (backend mutations), never here. On a project that uses payment configs the result carries the `paymentConfigId` it minted, which is what a payment action then charges through. This is a large generative act: tell the user what it created rather than reporting it as done.\n- op=GET_PAYMENT_CONFIGS \u2014 The project's payment configs, and for each one the checkout products a payment action on it can use. Both fields such an action carries come from here: `id` is its configId, and `usableProductsOnThisClient` \u2014 the products the merchant enabled that this client can also run \u2014 is what its paymentProduct has to be one of. An empty one means this config cannot back a payment action on this client at all, whatever it enables. `legacyPaymentModel` true means the project predates payment configs: there is nothing to point at and a payment action takes neither field.",ops:{ACTIVATE_PAYMENT:"ACTIVATE_PAYMENT",GET_PAYMENT_CONFIGS:"GET_PAYMENT_CONFIGS"},inputSchema:{orderTableDisplayName:c.string().optional(),paymentType:c.enum(["STRIPE","AIRWALLEX","ALIPAY","WECHAT"]).optional()}},{name:"schema_permission",tier:"catalog",description:`
|
|
1224
|
+
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
1225
|
+
- op=ACTIVATE_ROLE_PERMISSION \u2014 Activate RBAC by seeding the predefined Logged-in User and Anonymous User roles with their default grants. Requires Sync Backend afterward to affect the deployed backend. Result echoes the seeded roles.
|
|
1226
|
+
- op=ADD_ROLES \u2014 Create custom roles with the editor's defaults (minimal grants \u2014 extend them with the UPDATE_ROLE_*_PERMISSION tools). Call ACTIVATE_ROLE_PERMISSION first when GET_ALL_ROLES_INFO reports that RBAC is not activated. Result echoes each new role's name and predefined flag.
|
|
1227
|
+
- op=DELETE_ROLES (req: roleNames)
|
|
1228
|
+
- op=GET_ALL_ROLES_INFO
|
|
1229
|
+
- op=GET_ROLE_DETAIL \u2014 One role's grants across every permission block, reported by exception: per table, the operations granted, which of them carry a narrowed row condition, and only the column sets that cover less than the whole table \u2014 an operation listed as granted and nowhere else covers every column and every row. Tables the role cannot touch at all are named together in tablesWithNoGrants. Narrow the read with \`blocks\` when the task is about one of them. It carries no row-condition schema paths \u2014 take those from GET_TABLE_PERMISSION for the tables you are narrowing, since a whole-role read would carry one path per operation per table and almost none of them are ever used. FULL returns the raw RoleConfig.
|
|
1230
|
+
- op=GET_TABLE_PERMISSION \u2014 One role's grants on named tables, each operation with its row-condition schema path for the condition tools. The drill-in for GET_ROLE_DETAIL: name only the tables you are about to change.
|
|
1231
|
+
- op=GET_VIEW_PERMISSION \u2014 One role's grants on named views, each operation with its row-condition schema path for the condition tools. A view is read-only, so only select, count and aggregate exist.
|
|
1232
|
+
- op=SET_ROLE_PERMISSION_CHECK \u2014 Seed (or reset) a role's conditional check on one action flow / AI agent: writes an always-true condition and returns its schema path \u2014 then narrow the condition via the condition tools at that path. The check gates calls to the target on top of the allow-list.
|
|
1233
|
+
- op=UPDATE_ROLE \u2014 Edit a custom role's description. Renaming is not available here: a role's name is fixed once it has been deployed to the backend, and only the editor can tell whether it has \u2014 to use a different name, create another role with ADD_ROLES and delete the old one with DELETE_ROLES.
|
|
1234
|
+
- op=UPDATE_ROLE_ACTION_FLOW_PERMISSION (req: roleName)
|
|
1235
|
+
- op=UPDATE_ROLE_API_PERMISSION (req: roleName) [post-type-system-refactor only]
|
|
1236
|
+
- op=UPDATE_ROLE_PAYMENT_PERMISSION (req: roleName)
|
|
1237
|
+
- op=UPDATE_ROLE_TABLE_PERMISSION \u2014 Grant or revoke one role's operations across any number of tables, with per-operation column sets. Newly granted operations get an always-true row condition; the result reports every addressed table's resulting grant and the schema path of each condition, so narrowing one needs no further read.
|
|
1238
|
+
- op=UPDATE_ROLE_TPA_PERMISSION (req: roleName) [pre-type-system-refactor only]
|
|
1239
|
+
- op=UPDATE_ROLE_VIEW_PERMISSION \u2014 Grant or revoke one role's select / count / aggregate across any number of views, with per-operation column sets. A view no role was granted is not queryable by anyone. Newly granted operations get an always-true row condition; the result reports every addressed view's resulting grant and the schema path of each condition.
|
|
1240
|
+
- op=UPDATE_ROLE_ZAI_PERMISSION (req: roleName)`,ops:{ACTIVATE_ROLE_PERMISSION:"ACTIVATE_ROLE_PERMISSION",ADD_ROLES:"ADD_ROLES",DELETE_ROLES:"DELETE_ROLES",GET_ALL_ROLES_INFO:"GET_ALL_ROLES_INFO",GET_ROLE_DETAIL:"GET_ROLE_DETAIL",GET_TABLE_PERMISSION:"GET_TABLE_PERMISSION",GET_VIEW_PERMISSION:"GET_VIEW_PERMISSION",SET_ROLE_PERMISSION_CHECK:"SET_ROLE_PERMISSION_CHECK",UPDATE_ROLE:"UPDATE_ROLE",UPDATE_ROLE_ACTION_FLOW_PERMISSION:"UPDATE_ROLE_ACTION_FLOW_PERMISSION",UPDATE_ROLE_API_PERMISSION:"UPDATE_ROLE_API_PERMISSION",UPDATE_ROLE_PAYMENT_PERMISSION:"UPDATE_ROLE_PAYMENT_PERMISSION",UPDATE_ROLE_TABLE_PERMISSION:"UPDATE_ROLE_TABLE_PERMISSION",UPDATE_ROLE_TPA_PERMISSION:"UPDATE_ROLE_TPA_PERMISSION",UPDATE_ROLE_VIEW_PERMISSION:"UPDATE_ROLE_VIEW_PERMISSION",UPDATE_ROLE_ZAI_PERMISSION:"UPDATE_ROLE_ZAI_PERMISSION"},inputSchema:{allowAll:c.boolean().optional(),allowedActionFlowIds:c.array(c.any()).optional(),allowedApiIds:c.array(c.any()).optional(),allowedPaymentTypeAndMethod:c.record(c.any()).optional(),allowedTpaConfigIds:c.array(c.any()).optional(),allowedZAiIds:c.array(c.any()).optional(),blocks:c.array(c.any()).optional(),category:c.enum(["ACTION_FLOW","ZAI"]).optional(),denyAllTables:c.boolean().optional(),denyAllViews:c.boolean().optional(),description:c.string().optional(),detail:c.enum(["SUMMARY","FULL"]).optional(),items:c.array(c.any()).optional(),roleName:c.string().optional(),roleNames:c.array(c.any()).optional(),tableDisplayNames:c.array(c.any()).optional(),tables:c.array(c.any()).optional(),targetId:c.string().optional(),viewDisplayNames:c.array(c.any()).optional(),views:c.array(c.any()).optional()}},{name:"schema_request_filter",tier:"core",description:"Request filters (conditional filters / where-conditions / sort) addressed by schemaPath. Start from op=CONTEXT for selectable columns and sub-paths \u2014 never hand-build paths. Condition values are DataBindings (fill with schema_create_binding).\nChanges apply immediately; use schema_undo to revert the last change. Ops:\n- op=ADD_FILTER \u2014 Add a conditional filter to the request's list. A new filter starts empty on the column-comparison `where` by default; pass `whereTrack: WHERE_CONDITION` only when the user explicitly asks for the condition-expression (`whereCondition`) track. The echo's `whereTrack` is the track you passed. Result echoes the new filter's id and its whereSchemaPath / sortConfigsSchemaPath anchors.\n- op=ADD_CONDITION \u2014 Result echoes the new condition's schema path and its value binding's schema path (for the CREATE_*_BINDING tools).\n- op=ADD_SORT (req: field, schemaPath)\n- op=DELETE_FILTER (req: id, schemaPath)\n- op=DELETE_CONDITION (req: schemaPath)\n- op=DELETE_SORT (req: index, schemaPath)\n- op=DUPLICATE_REQUEST_CONDITIONAL_FILTER \u2014 Copy one conditional filter \u2014 its gating condition together with the where/sort it turns on \u2014 onto another query or mutation. The copy keeps the source's where track, so the echo's `whereTrack` is the source's, not the target's. Columns the target's table does not have are blanked rather than carried over, so re-check the copy's conditions when the two requests read different tables. The result echoes the copy's id and schema paths.\n- op=CONTEXT \u2014 Entry point for editing a query/mutation request's conditions and sorting. Pass the request's or owning node's schema path (e.g. from GET_ACTION_FLOW_NODE_DETAIL, or a ZAI db-context's querySchemaPath); returns the conditional filters with their whereSchemaPath / sortConfigsSchemaPath anchors, selectableColumns with allowed operators, and updateColumnArithmetic modes \u2014 everything the *_REQUEST_* tools take. `whereTrack` picks the track every reported whereSchemaPath addresses; it is a caller choice, not a read of the stored shape. COLUMN_WHERE (the default) addresses the column-comparison `where`, edited with the *_REQUEST_FILTER_CONDITION tools from the selectableColumns pathComponents. WHERE_CONDITION addresses `whereCondition`: a condition tree edited with the condition tools (a bare always-true condition, which is what an emptied tree holds, takes UPDATE_EXPRESSION_CONDITION_OPERATOR directly, and INSERT_CONDITION_BOOL_EXP seeds an absent tree or fills the bare one in place), with selectableColumns omitted because those tools reject that track. Each filter's `whereTrack` echoes the requested track. On an un-migrated request still holding a bare top-level `where`, conditionalFilters is empty and whereSchemaPath addresses that where \u2014 edit it in place; requesting WHERE_CONDITION there is rejected. An aggregate value binding (a relation's count/sum/... \u2014 its path ends in an aggregation) carries its own row filter: pass the binding's schema path to get that where the same way (no conditional filters, no sort), and the same track decides whether its whereSchemaPath addresses `where` or `whereCondition`.\n- op=NEST_CONDITION (req: schemaPath)\n- op=REORDER_FILTERS (req: reorderedIds, schemaPath)\n- op=REORDER_SORT (req: reorderedIndexes, schemaPath)\n- op=SET_UPDATE_COLUMN_ARITHMETIC (req: columnDisplayName, mode, schemaPath)\n- op=TOGGLE_CONDITION_AND_OR (req: schemaPath)\n- op=TOGGLE_CONDITION_NOT (req: schemaPath)\n- op=UPDATE_FILTER (req: id, name, schemaPath)\n- op=SET_CONDITION_OPERATOR (req: operator, schemaPath)\n- op=UPDATE_SORT (req: index, schemaPath)",ops:{ADD_FILTER:"ADD_REQUEST_CONDITIONAL_FILTER",ADD_CONDITION:"ADD_REQUEST_FILTER_CONDITION",ADD_SORT:"ADD_REQUEST_SORT_CONFIG",DELETE_FILTER:"DELETE_REQUEST_CONDITIONAL_FILTER",DELETE_CONDITION:"DELETE_REQUEST_FILTER_CONDITION",DELETE_SORT:"DELETE_REQUEST_SORT_CONFIG",DUPLICATE_REQUEST_CONDITIONAL_FILTER:"DUPLICATE_REQUEST_CONDITIONAL_FILTER",CONTEXT:"GET_REQUEST_FILTER_CONTEXT",NEST_CONDITION:"NEST_REQUEST_FILTER_CONDITION",REORDER_FILTERS:"REORDER_REQUEST_CONDITIONAL_FILTERS",REORDER_SORT:"REORDER_REQUEST_SORT_CONFIGS",SET_UPDATE_COLUMN_ARITHMETIC:"SET_UPDATE_COLUMN_ARITHMETIC",TOGGLE_CONDITION_AND_OR:"TOGGLE_REQUEST_FILTER_CONDITION_AND_OR",TOGGLE_CONDITION_NOT:"TOGGLE_REQUEST_FILTER_CONDITION_NOT",UPDATE_FILTER:"UPDATE_REQUEST_CONDITIONAL_FILTER",SET_CONDITION_OPERATOR:"UPDATE_REQUEST_FILTER_CONDITION_OPERATOR",UPDATE_SORT:"UPDATE_REQUEST_SORT_CONFIG"},inputSchema:{afterId:c.string().optional(),columnDisplayName:c.string().optional(),columnPathComponents:c.array(c.any()).optional(),field:c.array(c.any()).optional(),id:c.string().optional(),index:c.number().optional(),mode:c.enum(["set","increment","decrement"]).optional(),name:c.string().optional(),operator:c.string().optional(),reorderedIds:c.array(c.any()).optional(),reorderedIndexes:c.array(c.any()).optional(),schemaPath:c.array(c.any()).optional(),sort:c.enum(["descending","ascending"]).optional(),sourceId:c.string().optional(),sourceSchemaPath:c.array(c.any()).optional(),value:c.record(c.any()).optional(),whereTrack:c.enum(["COLUMN_WHERE","WHERE_CONDITION"]).optional()}},{name:"schema_secret",tier:"catalog",description:"\nChanges apply immediately; use schema_undo to revert the last change. Ops:\n- op=ADD_SECRET_CONFIGS \u2014 Registers secret entries in the schema. The plaintext value is NOT passed here and never stored in the schema: you must first upload the value out of band (the backend `saveSecret` mutation) to obtain its opaque `secretKey` handle, then pass that handle. A secret added without a `secretKey` has no value set and stays incomplete until one is supplied via UPDATE_SECRET_CONFIG. Result echoes each new secret's id.\n- op=DELETE_SECRET_CONFIGS (req: secretIds)\n- op=GET_ALL_SECRET_CONFIGS \u2014 Lists every secret: id, displayName, description, and `hasValue` (whether its value handle is set). The stored value handle itself is withheld.\n- op=UPDATE_SECRET_CONFIG \u2014 Updates a secret's metadata and/or value handle (incremental \u2014 omitted fields are left unchanged). You cannot set a plaintext value here: to change the value, re-upload it out of band (the backend `saveSecret` mutation) to obtain a new `secretKey` handle, then pass it as `secretKey`.",ops:{ADD_SECRET_CONFIGS:"ADD_SECRET_CONFIGS",DELETE_SECRET_CONFIGS:"DELETE_SECRET_CONFIGS",GET_ALL_SECRET_CONFIGS:"GET_ALL_SECRET_CONFIGS",UPDATE_SECRET_CONFIG:"UPDATE_SECRET_CONFIG"},inputSchema:{description:c.string().optional(),displayName:c.string().optional(),items:c.array(c.any()).optional(),secretId:c.string().optional(),secretIds:c.array(c.any()).optional(),secretKey:c.string().optional()}},{name:"schema_set_tpa_config_paging",tier:"catalog",description:`
|
|
1241
|
+
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
1242
|
+
- op=SET_TPA_CONFIG_PAGING (req: tpaConfigId) [pre-type-system-refactor only]`,ops:{SET_TPA_CONFIG_PAGING:"SET_TPA_CONFIG_PAGING"},inputSchema:{pageIndexPath:c.array(c.any()).optional(),pageIndexStartValue:c.number().optional(),pageSizePath:c.array(c.any()).optional(),tpaConfigId:c.string().optional()}},{name:"schema_tab_bar",tier:"catalog",description:`
|
|
1243
|
+
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
1244
|
+
- op=GET_TAB_BAR_INFO \u2014 The native tab bar of this client: whether it is on, its colours, and each slot with the page it opens, its label and whether it has icons. Take this before changing anything about the bottom navigation \u2014 the slot count is fixed and a page can be opened by only one tab, so the slots are what a change has to be expressed against.
|
|
1245
|
+
- op=SET_TAB_BAR_ENABLED \u2014 Show or hide this client's native tab bar \u2014 the bottom navigation the mini-program draws itself, not components on a page. Turning it on for the first time creates empty slots and shows none of them, so pair it with UPDATE_TAB_BAR_ITEMS in the same batch or the user sees no change.
|
|
1246
|
+
- op=UPDATE_TAB_BAR_ITEMS \u2014 Point a tab-bar slot at a page and give it a label and icons. A slot with no page is hidden, and emptying one hides it again, which is how a tab is removed \u2014 the slot count itself never changes. A shown slot needs both icons or the project reports an error, so take the exIds from get_tab_bar_icons first: an icon is addressed by the exId of a stored image, never by its name, and a value that cannot be an exId is rejected. A mini-program tab bar has to show between two and five tabs, so bind at least two pages.
|
|
1247
|
+
- op=UPDATE_TAB_BAR_STYLE`,ops:{GET_TAB_BAR_INFO:"GET_TAB_BAR_INFO",SET_TAB_BAR_ENABLED:"SET_TAB_BAR_ENABLED",UPDATE_TAB_BAR_ITEMS:"UPDATE_TAB_BAR_ITEMS",UPDATE_TAB_BAR_STYLE:"UPDATE_TAB_BAR_STYLE"},inputSchema:{backgroundColor:c.string().optional(),color:c.string().optional(),enabled:c.boolean().optional(),items:c.array(c.any()).optional(),selectedColor:c.string().optional()}},{name:"schema_table",tier:"core",description:`Database tables, fields, relations, and constraints in the loaded schema. A field type is copied verbatim from op=SELECTABLE_TYPES into \`typeIdentifier\`, never hand-built. A joined or aggregated result that more than one place needs is a view, not a table: see schema_view.
|
|
1248
|
+
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
1249
|
+
- op=ADD_CONSTRAINTS (req: constraints)
|
|
1250
|
+
- op=ADD_DATABASE_INDEX \u2014 Declare a database index on a table field. indexType 'BM25': keyword full-text relevance ranking over a TEXT field, exposed as the fz_<field>_bm25 order-by field of the project GraphQL API, with fz_<field>_bm25_score and fz_<field>_bm25_snippet fields reading each row's relevance and a highlighted excerpt. Only rows that actually match the query come back, most relevant first, so the result can be shorter than the limit and a query matching nothing returns nothing \u2014 no extra filter is needed. An empty query orders by id instead. An index is addressed by the field it covers; its parameters are fixed once it exists, so changing them means deleting it and declaring it again.
|
|
1251
|
+
- op=ADD_FIELDS_RELATIONS (req: tableDisplayName)
|
|
1252
|
+
- op=ADD_TABLES (req: items)
|
|
1253
|
+
- op=ADD_EXTENSION \u2014 Enable vector-embedding search on a table's TEXT field (adds hidden embedding / token-count columns maintained by the backend).
|
|
1254
|
+
- op=DELETE_CONSTRAINTS (req: constraints)
|
|
1255
|
+
- op=DELETE_DATABASE_INDEX \u2014 Drop an index declared by ADD_DATABASE_INDEX, dropping the underlying Postgres index as well.
|
|
1256
|
+
- op=DELETE_FIELDS_RELATIONS (req: tableDisplayName)
|
|
1257
|
+
- op=DELETE_TABLES (req: tableDisplayNames)
|
|
1258
|
+
- op=DELETE_EXTENSION (req: fieldDisplayName, tableDisplayName)
|
|
1259
|
+
- op=LIST_NAMES \u2014 Table display names on their own. GET_PROJECT_OVERVIEW already lists every table with its column count, so reach for this only when you want the names and nothing else.
|
|
1260
|
+
- op=LIST_EMBEDDING_MODELS \u2014 List the embedding models selectable for ADD_TABLE_EXTENSION / UPDATE_TABLE_EXTENSION.
|
|
1261
|
+
- op=GET_INFOS (req: tableDisplayNames)
|
|
1262
|
+
- op=SELECTABLE_TYPES \u2014 List the types a table field accepts, for ADD_TABLES / ADD_FIELDS_AND_RELATIONS. To use an enum that is not listed, create the enum first and call this again \u2014 the new type then appears with the exact \`typeIdentifier\` to copy, which is not the type id and must never be assembled from it. A relation is not a field type: add one through the \`relations\` parameter instead.
|
|
1263
|
+
- op=REORDER_CONSTRAINTS (req: reorderedConstraintNames, tableDisplayName)
|
|
1264
|
+
- op=REORDER_TABLES (req: reorderedTableDisplayNames)
|
|
1265
|
+
- op=REORDER_TABLE_FIELDS \u2014 Reorder the fields of one table as the editor lists them. The order is editor state kept outside the table, so it exists only after the type-system refactor. [post-type-system-refactor only]
|
|
1266
|
+
- op=UPDATE_FIELDS_AND_RELATIONS \u2014 Edit existing fields and relations in place: a field's display name, required flag and default value; a relation's display name on either side. Changing a field's type is not available here: the type is fixed once the field has been deployed to the backend, and only the editor can tell whether it has \u2014 to use a different type, delete the field with DELETE_FIELDS_AND_RELATIONS and add it again with ADD_FIELDS_AND_RELATIONS. A field's api name is minted at creation and never changes, and a relation's type or tables can only be changed by deleting it and adding a new one.
|
|
1267
|
+
- op=UPDATE_TABLES (req: items)
|
|
1268
|
+
- op=UPDATE_EXTENSION \u2014 Switch an existing embedding index to another model. The embedding model is the only part of an extension that can be reconfigured \u2014 the indexed field and the hidden columns backing it are fixed once the index exists.`,ops:{ADD_CONSTRAINTS:"ADD_CONSTRAINTS",ADD_DATABASE_INDEX:"ADD_DATABASE_INDEX",ADD_FIELDS_RELATIONS:"ADD_FIELDS_AND_RELATIONS",ADD_TABLES:"ADD_TABLES",ADD_EXTENSION:"ADD_TABLE_EXTENSION",DELETE_CONSTRAINTS:"DELETE_CONSTRAINTS",DELETE_DATABASE_INDEX:"DELETE_DATABASE_INDEX",DELETE_FIELDS_RELATIONS:"DELETE_FIELDS_AND_RELATIONS",DELETE_TABLES:"DELETE_TABLES",DELETE_EXTENSION:"DELETE_TABLE_EXTENSION",LIST_NAMES:"GET_ALL_TABLE_DISPLAY_NAMES",LIST_EMBEDDING_MODELS:"GET_AVAILABLE_EMBEDDING_MODELS",GET_INFOS:"GET_TABLES_INFO",SELECTABLE_TYPES:"GET_TABLE_FIELD_SELECTABLE_TYPES",REORDER_CONSTRAINTS:"REORDER_CONSTRAINTS",REORDER_TABLES:"REORDER_TABLES",REORDER_TABLE_FIELDS:"REORDER_TABLE_FIELDS",UPDATE_FIELDS_AND_RELATIONS:"UPDATE_FIELDS_AND_RELATIONS",UPDATE_TABLES:"UPDATE_TABLES",UPDATE_EXTENSION:"UPDATE_TABLE_EXTENSION"},inputSchema:{b:c.number().optional(),constraints:c.array(c.any()).optional(),customEmbeddingId:c.string().optional(),fieldDisplayName:c.string().optional(),fieldDisplayNames:c.array(c.any()).optional(),fields:c.array(c.any()).optional(),indexType:c.enum(["BM25"]).optional(),items:c.array(c.any()).optional(),k1:c.number().optional(),relationFieldDisplayNamesInSourceTable:c.array(c.any()).optional(),relations:c.array(c.any()).optional(),reorderedConstraintNames:c.array(c.any()).optional(),reorderedFieldDisplayNames:c.array(c.any()).optional(),reorderedTableDisplayNames:c.array(c.any()).optional(),showApiName:c.boolean().optional(),tableDisplayName:c.string().optional(),tableDisplayNames:c.array(c.any()).optional(),textConfig:c.enum(["SIMPLE","AFRIKAANS","ARABIC","ARMENIAN","BASQUE","CATALAN","DANISH","DUTCH","ENGLISH","ESTONIAN","FINNISH","FRENCH","GERMAN","GREEK","HINDI","HUNGARIAN","INDONESIAN","IRISH","ITALIAN","LITHUANIAN","NEPALI","NORWEGIAN","PORTUGUESE","ROMANIAN","RUSSIAN","SERBIAN","SPANISH","SWEDISH","TAMIL","TURKISH","YIDDISH","BULGARIAN","CROATIAN","CZECH","LATVIAN","PERSIAN","POLISH","SLOVAK","SLOVENIAN","UKRAINIAN","CHINESE","JAPANESE","KOREAN","THAI"]).optional()}},{name:"schema_trigger",tier:"catalog",description:`
|
|
1269
|
+
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
1270
|
+
- op=ADD_DB_TRIGGERS \u2014 Result echoes each new trigger's id.
|
|
1271
|
+
- op=ADD_SCHEDULED_TRIGGERS \u2014 Result echoes each new trigger's id.
|
|
1272
|
+
- op=DELETE_DB_TRIGGERS (req: triggerIds)
|
|
1273
|
+
- op=DELETE_SCHEDULED_TRIGGERS (req: triggerIds)
|
|
1274
|
+
- op=GET_ALL_DB_TRIGGERS_INFO
|
|
1275
|
+
- op=GET_ALL_SCHEDULED_TRIGGERS_INFO
|
|
1276
|
+
- op=GET_DB_TRIGGER_DETAIL (req: triggerId)
|
|
1277
|
+
- op=GET_SCHEDULED_TRIGGER_DETAIL (req: triggerId)
|
|
1278
|
+
- op=UPDATE_DB_TRIGGER (req: triggerId)
|
|
1279
|
+
- op=UPDATE_SCHEDULED_TRIGGER (req: triggerId)`,ops:{ADD_DB_TRIGGERS:"ADD_DB_TRIGGERS",ADD_SCHEDULED_TRIGGERS:"ADD_SCHEDULED_TRIGGERS",DELETE_DB_TRIGGERS:"DELETE_DB_TRIGGERS",DELETE_SCHEDULED_TRIGGERS:"DELETE_SCHEDULED_TRIGGERS",GET_ALL_DB_TRIGGERS_INFO:"GET_ALL_DB_TRIGGERS_INFO",GET_ALL_SCHEDULED_TRIGGERS_INFO:"GET_ALL_SCHEDULED_TRIGGERS_INFO",GET_DB_TRIGGER_DETAIL:"GET_DB_TRIGGER_DETAIL",GET_SCHEDULED_TRIGGER_DETAIL:"GET_SCHEDULED_TRIGGER_DETAIL",UPDATE_DB_TRIGGER:"UPDATE_DB_TRIGGER",UPDATE_SCHEDULED_TRIGGER:"UPDATE_SCHEDULED_TRIGGER"},inputSchema:{cron:c.string().optional(),cronInputType:c.enum(["CONFIGURED","CUSTOMIZED"]).optional(),dbOperationType:c.enum(["INSERT","UPDATE","INSERT_OR_UPDATE","DELETE"]).optional(),displayName:c.string().optional(),enabled:c.boolean().optional(),endInstant:c.string().optional(),items:c.array(c.any()).optional(),name:c.string().optional(),startInstant:c.string().optional(),tableDisplayName:c.string().optional(),triggerId:c.string().optional(),triggerIds:c.array(c.any()).optional()}},{name:"schema_type",tier:"core",description:`Enum and object-type definitions. Create an enum before any column that references it; editing in-use options is destructive (prefer ADDING). A field type is copied verbatim from op=SELECTABLE_TYPES into \`type\`, never hand-built.
|
|
1280
|
+
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
1281
|
+
- op=ADD_ENUMS \u2014 A new type is not usable at a typed slot until you read its \`typeIdentifier\` back from that slot's selectable-types query (GET_ACTION_FLOW_SELECTABLE_TYPES, GET_ZAI_CONFIG_SELECTABLE_TYPES, \u2026). The identifier is not the id echoed here and its exact form depends on the slot, so never build it by hand. [post-type-system-refactor only]
|
|
1282
|
+
- op=ADD_ENUM_GROUPS \u2014 Result echoes each new enum group's minted id. [post-type-system-refactor only]
|
|
1283
|
+
- op=ADD_ENUM_OPTIONS \u2014 Append options to an existing enum. Prefer this over UPDATE_ENUM_DEFINITIONS' whole-list replace, which deletes any option it does not list. [post-type-system-refactor only]
|
|
1284
|
+
- op=ADD_OBJECTS \u2014 Each created type echoes back the \`typeIdentifier\` to write at a typed slot \u2014 paste it verbatim, never build one by hand, and note it is not the bare id also echoed here. A public type additionally turns up in the selectable-types query of every slot that takes object types; a private one turns up in none, so that echo is the only way to name it. [post-type-system-refactor only]
|
|
1285
|
+
- op=ADD_OBJECT_GROUPS \u2014 Result echoes each new object-type group's minted id. [post-type-system-refactor only]
|
|
1286
|
+
- op=ADD_FIELDS (req: fields, typeId) [post-type-system-refactor only]
|
|
1287
|
+
- op=COPY_PRIVATE_OBJECT_AS_PUBLIC \u2014 Publish a private object type \u2014 a structure that belongs to one feature \u2014 as a reusable entry in the project's object type list, leaving the original in place. The copy is a new type with a new id: to make the feature use it, follow this call with the write that sets that slot's type (UPDATE_TYPE_DEFINITION_FIELDS for a field of another object, SET_ACTION_FLOW_OUTPUT for an action flow's output, \u2026) to the \`typeIdentifier\` echoed here. [post-type-system-refactor only]
|
|
1288
|
+
- op=COPY_PUBLIC_OBJECT_AS_PRIVATE \u2014 Take a private copy of a public object type, so one feature can diverge from the shared shape without changing it for every other user. The copy is referenced by nothing until you follow this call with the write that sets the slot's type (UPDATE_TYPE_DEFINITION_FIELDS, SET_ACTION_FLOW_OUTPUT, \u2026) to the \`typeIdentifier\` echoed here. [post-type-system-refactor only]
|
|
1289
|
+
- op=DELETE_ENUMS (req: enumIds) [post-type-system-refactor only]
|
|
1290
|
+
- op=DELETE_ENUM_GROUPS (req: groupIds) [post-type-system-refactor only]
|
|
1291
|
+
- op=DELETE_ENUM_OPTIONS \u2014 Delete options from an existing enum. Records and bindings still referencing a deleted option are left dangling. [post-type-system-refactor only]
|
|
1292
|
+
- op=DELETE_OBJECTS (req: typeIds) [post-type-system-refactor only]
|
|
1293
|
+
- op=DELETE_OBJECT_GROUPS (req: groupIds) [post-type-system-refactor only]
|
|
1294
|
+
- op=DELETE_FIELDS (req: fieldNames, typeId) [post-type-system-refactor only]
|
|
1295
|
+
- op=LIST_ENUMS [post-type-system-refactor only]
|
|
1296
|
+
- op=LIST_OBJECTS \u2014 Lists every object type, including the \`private\` ones, so a feature's own structure can be read. A private type belongs to the single feature that owns it (an API's request body, a webhook's payload, an agent's output): no selectable-types list offers it, and a second slot naming it is rejected. To reuse a private type's shape, publish a copy with COPY_PRIVATE_OBJECT_TYPE_AS_PUBLIC and select that copy instead. [post-type-system-refactor only]
|
|
1297
|
+
- op=GET_ENUM_DETAIL \u2014 One enum type's options, each with the client platforms that accept it. Take the id from GET_ALL_ENUM_DEFINITIONS. Read this before wiring a specific option into an action: an action that carries an option is invalid on a client whose platform is missing from that option's \`platforms\`, and the verification-code purpose enum is the one whose options differ this way today. An option listing all three platforms is unrestricted. [post-type-system-refactor only]
|
|
1298
|
+
- op=GET_ENUM_GROUPS [post-type-system-refactor only]
|
|
1299
|
+
- op=GET_OBJECT_DETAIL \u2014 One object type's fields, each stored type resolved to the same readable names GET_ALL_OBJECT_DEFINITIONS uses, plus its \`description\` and \`private\` flag. Take the id from GET_ALL_OBJECT_DEFINITIONS, a field's resolved type, or a slot that points at the type; reading one type beats listing every type to find it. [post-type-system-refactor only]
|
|
1300
|
+
- op=GET_OBJECT_GROUPS [post-type-system-refactor only]
|
|
1301
|
+
- op=SELECTABLE_TYPES \u2014 List the types a field of an object type accepts. Every \`type\` ADD_OBJECT_TYPE_DEFINITIONS / ADD_TYPE_DEFINITION_FIELDS / UPDATE_TYPE_DEFINITION_FIELDS takes must be a \`typeIdentifier\` copied from here verbatim. To use a type that is not listed, create it with ADD_OBJECT_TYPE_DEFINITIONS / ADD_ENUM_DEFINITIONS (leave \`private\` unset, or it stays out of every list) and call this again; to reuse an existing *private* type, publish it first with COPY_PRIVATE_OBJECT_TYPE_AS_PUBLIC. Lists are not enumerated \u2014 the nesting has no end \u2014 so a list field is a listed identifier with the field's \`arrayLevel\` set (1 = list, 2 = list of lists), never brackets written into the identifier. An option comes in its optional form (\`null|\u2026\`); pass it as it comes, since a field's \`required\` flag owns that wrapper. [post-type-system-refactor only]
|
|
1302
|
+
- op=MOVE_ENUM_TO_GROUP (req: items) [post-type-system-refactor only]
|
|
1303
|
+
- op=MOVE_OBJECT_TO_GROUP (req: items) [post-type-system-refactor only]
|
|
1304
|
+
- op=REORDER_FIELDS \u2014 Reorder the fields of one object type as the editor lists them \u2014 the order a structured AI-agent output, an API body or any other slot typed by it is rendered and emitted in. [post-type-system-refactor only]
|
|
1305
|
+
- op=UPDATE_ENUMS (req: enums) [post-type-system-refactor only]
|
|
1306
|
+
- op=UPDATE_ENUM_GROUPS (req: groups) [post-type-system-refactor only]
|
|
1307
|
+
- op=UPDATE_ENUM_OPTIONS \u2014 Rename options of an existing enum. An option's id is permanent, so every binding that resolves to the option survives the rename; the deployed database column stores the name, not the id, and is rewritten row by row on the next backend sync. [post-type-system-refactor only]
|
|
1308
|
+
- op=UPDATE_OBJECTS (req: types) [post-type-system-refactor only]
|
|
1309
|
+
- op=UPDATE_OBJECT_GROUPS (req: groups) [post-type-system-refactor only]
|
|
1310
|
+
- op=UPDATE_FIELDS \u2014 Rename and/or retype fields of an object type in place. Renaming carries the field's references along with it; retyping away from an image / video / file or JSON type drops them, because nothing that pointed at the old shape can read the new one. [post-type-system-refactor only]`,ops:{ADD_ENUMS:"ADD_ENUM_DEFINITIONS",ADD_ENUM_GROUPS:"ADD_ENUM_DEFINITION_GROUPS",ADD_ENUM_OPTIONS:"ADD_ENUM_OPTIONS",ADD_OBJECTS:"ADD_OBJECT_TYPE_DEFINITIONS",ADD_OBJECT_GROUPS:"ADD_OBJECT_TYPE_DEFINITION_GROUPS",ADD_FIELDS:"ADD_TYPE_DEFINITION_FIELDS",COPY_PRIVATE_OBJECT_AS_PUBLIC:"COPY_PRIVATE_OBJECT_TYPE_AS_PUBLIC",COPY_PUBLIC_OBJECT_AS_PRIVATE:"COPY_PUBLIC_OBJECT_TYPE_AS_PRIVATE",DELETE_ENUMS:"DELETE_ENUM_DEFINITIONS",DELETE_ENUM_GROUPS:"DELETE_ENUM_DEFINITION_GROUPS",DELETE_ENUM_OPTIONS:"DELETE_ENUM_OPTIONS",DELETE_OBJECTS:"DELETE_OBJECT_TYPE_DEFINITIONS",DELETE_OBJECT_GROUPS:"DELETE_OBJECT_TYPE_DEFINITION_GROUPS",DELETE_FIELDS:"DELETE_TYPE_DEFINITION_FIELDS",LIST_ENUMS:"GET_ALL_ENUM_DEFINITIONS",LIST_OBJECTS:"GET_ALL_OBJECT_DEFINITIONS",GET_ENUM_DETAIL:"GET_ENUM_DEFINITION_DETAIL",GET_ENUM_GROUPS:"GET_ENUM_DEFINITION_GROUPS",GET_OBJECT_DETAIL:"GET_OBJECT_TYPE_DEFINITION_DETAIL",GET_OBJECT_GROUPS:"GET_OBJECT_TYPE_DEFINITION_GROUPS",SELECTABLE_TYPES:"GET_TYPE_DEFINITION_FIELD_SELECTABLE_TYPES",MOVE_ENUM_TO_GROUP:"MOVE_ENUM_DEFINITIONS_TO_GROUP",MOVE_OBJECT_TO_GROUP:"MOVE_OBJECT_TYPE_DEFINITIONS_TO_GROUP",REORDER_FIELDS:"REORDER_TYPE_DEFINITION_FIELDS",UPDATE_ENUMS:"UPDATE_ENUM_DEFINITIONS",UPDATE_ENUM_GROUPS:"UPDATE_ENUM_DEFINITION_GROUPS",UPDATE_ENUM_OPTIONS:"UPDATE_ENUM_OPTIONS",UPDATE_OBJECTS:"UPDATE_OBJECT_TYPE_DEFINITIONS",UPDATE_OBJECT_GROUPS:"UPDATE_OBJECT_TYPE_DEFINITION_GROUPS",UPDATE_FIELDS:"UPDATE_TYPE_DEFINITION_FIELDS"},inputSchema:{deleteTypes:c.boolean().optional(),displayName:c.string().optional(),enumId:c.string().optional(),enumIds:c.array(c.any()).optional(),enums:c.any().optional(),fieldNames:c.array(c.any()).optional(),fields:c.array(c.any()).optional(),groupId:c.string().optional(),groupIds:c.array(c.any()).optional(),groups:c.any().optional(),items:c.array(c.any()).optional(),optionIds:c.array(c.any()).optional(),options:c.array(c.any()).optional(),orderedFieldNames:c.array(c.any()).optional(),typeId:c.string().optional(),typeIds:c.array(c.any()).optional(),types:c.any().optional()}},{name:"schema_update_tpa_config",tier:"catalog",description:`
|
|
1311
|
+
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
1312
|
+
- op=UPDATE_TPA_CONFIG (req: tpaConfigId) [pre-type-system-refactor only]`,ops:{UPDATE_TPA_CONFIG:"UPDATE_TPA_CONFIG"},inputSchema:{caX509PemBase64:c.string().optional(),description:c.string().optional(),method:c.enum(["GET","POST","PUT","DELETE"]).optional(),name:c.string().optional(),operation:c.enum(["query","mutation"]).optional(),tpaConfigId:c.string().optional(),url:c.string().optional()}},{name:"schema_update_tpa_config_parameter",tier:"catalog",description:`
|
|
1313
|
+
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
1314
|
+
- op=UPDATE_TPA_CONFIG_PARAMETER (req: parameterUniqueId, tpaConfigId) [pre-type-system-refactor only]`,ops:{UPDATE_TPA_CONFIG_PARAMETER:"UPDATE_TPA_CONFIG_PARAMETER"},inputSchema:{defaultValue:c.string().optional(),itemType:c.string().optional(),name:c.string().optional(),parameterUniqueId:c.string().optional(),required:c.boolean().optional(),tpaConfigId:c.string().optional(),type:c.string().optional()}},{name:"schema_update_tpa_parameter_child",tier:"catalog",description:`
|
|
1315
|
+
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
1316
|
+
- op=UPDATE_TPA_PARAMETER_CHILD (req: dataUniqueId, tpaConfigId) [pre-type-system-refactor only]`,ops:{UPDATE_TPA_PARAMETER_CHILD:"UPDATE_TPA_PARAMETER_CHILD"},inputSchema:{dataUniqueId:c.string().optional(),defaultValue:c.string().optional(),itemType:c.string().optional(),name:c.string().optional(),required:c.boolean().optional(),tpaConfigId:c.string().optional(),type:c.string().optional()}},{name:"schema_update_tpa_response_data",tier:"catalog",description:`
|
|
1317
|
+
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
1318
|
+
- op=UPDATE_TPA_RESPONSE_DATA (req: responseBranch, tpaConfigId) [pre-type-system-refactor only]`,ops:{UPDATE_TPA_RESPONSE_DATA:"UPDATE_TPA_RESPONSE_DATA"},inputSchema:{defaultValue:c.string().optional(),itemType:c.string().optional(),name:c.string().optional(),required:c.boolean().optional(),responseBranch:c.enum(["2xx","4xx","5xx"]).optional(),tpaConfigId:c.string().optional(),type:c.string().optional()}},{name:"schema_update_tpa_response_data_child",tier:"catalog",description:`
|
|
1319
|
+
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
1320
|
+
- op=UPDATE_TPA_RESPONSE_DATA_CHILD (req: dataUniqueId, responseBranch, tpaConfigId) [pre-type-system-refactor only]`,ops:{UPDATE_TPA_RESPONSE_DATA_CHILD:"UPDATE_TPA_RESPONSE_DATA_CHILD"},inputSchema:{dataUniqueId:c.string().optional(),defaultValue:c.string().optional(),itemType:c.string().optional(),name:c.string().optional(),required:c.boolean().optional(),responseBranch:c.enum(["2xx","4xx","5xx"]).optional(),tpaConfigId:c.string().optional(),type:c.string().optional()}},{name:"schema_view",tier:"catalog",description:`Data views \u2014 a saved SELECT over this project's tables, exposed as a read-only table of its own. Use one when the same joined or aggregated result is needed in more than one place, so the definition lives once. A view stores no data and is recomputed on every read, so it is never stale. It cannot be written through and has no primary key, so there is no insert, update, delete or by-id lookup. Its SQL is one SELECT, written against the API (snake_case) names rather than the displayNames every other op here takes, with an explicit AS alias on every output column; subqueries, window functions and query parameters are not available, and there is no request context inside a view, so filter by the current user when you QUERY it instead. Run op=ANALYZE_SQL first \u2014 it returns the columns the view would expose, and op=ADD / op=UPDATE reject SQL that does not analyse.
|
|
1321
|
+
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
1322
|
+
- op=ADD \u2014 Create read-only views: a saved SELECT exposed as a table of its own, for a joined or aggregated result that more than one place needs. A view holds no data and cannot be written through. SQL that does not analyse is rejected rather than stored.
|
|
1323
|
+
- op=ANALYZE_SQL \u2014 Dry-run a view definition: reports the columns the SQL would expose and every problem found in it, without changing anything. Call this while writing the SQL: creating or updating a view refuses a definition that does not analyse.
|
|
1324
|
+
- op=DELETE \u2014 Delete views by display name. No stored data is lost -- a view holds none -- but anything bound to its columns breaks. Refused while another view still reads one of them.
|
|
1325
|
+
- op=GET_INFOS \u2014 Each view's SQL plus the columns it exposes, derived by analysing that SQL -- a view stores a definition, not a column list, so this is the only place its shape is reported. Reading a view here is what lets you edit it.
|
|
1326
|
+
- op=UPDATE \u2014 Omitted fields keep their current value. Replacing the SQL replaces the columns the view exposes, so anything bound to a column that disappears breaks; SQL that does not analyse is rejected rather than stored.`,ops:{ADD:"ADD_VIEWS",ANALYZE_SQL:"ANALYZE_VIEW_SQL",DELETE:"DELETE_VIEWS",GET_INFOS:"GET_VIEWS_INFO",UPDATE:"UPDATE_VIEWS"},inputSchema:{items:c.array(c.any()).optional(),sql:c.string().optional(),viewDisplayName:c.string().optional(),viewDisplayNames:c.array(c.any()).optional()}},{name:"schema_zai_config",tier:"catalog",description:`
|
|
1327
|
+
Changes apply immediately; use schema_undo to revert the last change. Ops:
|
|
1328
|
+
- op=ADD_ZAI_CONFIGS \u2014 Result echoes each new agent's config id.
|
|
1329
|
+
- op=ADD_ZAI_CONFIG_API_CONTEXTS (req: apiIds, configId) [post-type-system-refactor only]
|
|
1330
|
+
- op=ADD_ZAI_CONFIG_DB_CONTEXTS \u2014 Result echoes each new entry's querySchemaPath \u2014 the anchor GET_REQUEST_FILTER_CONTEXT and the *_REQUEST_* tools take to filter/sort the context rows.
|
|
1331
|
+
- op=ADD_ZAI_CONFIG_INPUT_ARGS \u2014 Result echoes each new arg's minted key (the update/delete tools take it).
|
|
1332
|
+
- op=ADD_ZAI_CONFIG_OUTPUT_FIELDS (req: configId, items) [pre-type-system-refactor only]
|
|
1333
|
+
- op=ADD_ZAI_CONFIG_TOOLS \u2014 Result echoes each new tool's toolId.
|
|
1334
|
+
- op=ADD_ZAI_CONFIG_TPA_CONTEXTS (req: configId, tpaConfigIds) [pre-type-system-refactor only]
|
|
1335
|
+
- op=DELETE_ZAI_CONFIGS (req: configIds)
|
|
1336
|
+
- op=DELETE_ZAI_CONFIG_API_CONTEXTS (req: apiIds, configId) [post-type-system-refactor only]
|
|
1337
|
+
- op=DELETE_ZAI_CONFIG_DB_CONTEXTS (req: configId, tableDisplayNames)
|
|
1338
|
+
- op=DELETE_ZAI_CONFIG_INPUT_ARGS (req: argKeys, configId)
|
|
1339
|
+
- op=DELETE_ZAI_CONFIG_OUTPUT_FIELDS (req: configId, names) [pre-type-system-refactor only]
|
|
1340
|
+
- op=DELETE_ZAI_CONFIG_TOOLS (req: configId, toolIds)
|
|
1341
|
+
- op=DELETE_ZAI_CONFIG_TPA_CONTEXTS (req: configId, tpaConfigIds) [pre-type-system-refactor only]
|
|
1342
|
+
- op=DUPLICATE_ZAI_CONFIG \u2014 Duplicate an AI agent \u2014 prompts, model settings, context queries, tools \u2014 together with the type definitions behind its structured output. The result echoes the new agent's id. [post-type-system-refactor only]
|
|
1343
|
+
- op=GET_ALL_ZAI_CONFIGS_INFO
|
|
1344
|
+
- op=GET_ZAI_CONFIG_DETAIL (req: configId|schemaPath)
|
|
1345
|
+
- op=GET_ZAI_CONFIG_SELECTABLE_TYPES \u2014 List the types this AI-agent slot accepts. To use a type that is not listed, first create that object type or enum (leave \`private\` unset, or it stays hidden from this list) and call this again \u2014 the new type then appears with the exact \`typeIdentifier\` to copy. That identifier is not the type id and must never be assembled from it.
|
|
1346
|
+
- op=GET_ZAI_MODEL_OPTIONS \u2014 List the reasoning models available to AI agents. Use a selectable option's full customModelIdentifier verbatim when adding or updating an agent. An option's paramValueLimit is the range that model accepts for \`temperature\` and \`maxTokenSize\` plus the value it recommends; those are seeded on create and re-seeded on a model switch, so set one only to override the recommendation.
|
|
1347
|
+
- op=UPDATE_ZAI_CONFIG (req: configId)
|
|
1348
|
+
- op=UPDATE_ZAI_CONFIG_API_CONTEXT (req: apiId, configId) [post-type-system-refactor only]
|
|
1349
|
+
- op=UPDATE_ZAI_CONFIG_DB_CONTEXT (req: configId, tableDisplayName)
|
|
1350
|
+
- op=UPDATE_ZAI_CONFIG_INPUT_ARGS (req: configId, items)
|
|
1351
|
+
- op=UPDATE_ZAI_CONFIG_OUTPUT (req: configId) [post-type-system-refactor only]
|
|
1352
|
+
- op=UPDATE_ZAI_CONFIG_OUTPUT_FIELD \u2014 Edit a structured-output field's required flag or description. A field's name and type are fixed at creation \u2014 to change them, delete the field and re-add it. [pre-type-system-refactor only]
|
|
1353
|
+
- op=UPDATE_ZAI_CONFIG_OUTPUT_MODE \u2014 Switch the agent's output between plain text and structured, and set its streaming/token scalars. Switching to structured seeds an empty object output type (define its shape with ADD_/UPDATE_/DELETE_ZAI_CONFIG_OUTPUT_FIELDS); switching back to plain text deletes that type and every field on it. [pre-type-system-refactor only]
|
|
1354
|
+
- op=UPDATE_ZAI_CONFIG_TOOL (req: configId, toolId)
|
|
1355
|
+
- op=UPDATE_ZAI_CONFIG_TOOL_DESCRIPTION_CONFIGS (req: configId, toolId) [post-type-system-refactor only]
|
|
1356
|
+
- op=UPDATE_ZAI_CONFIG_TOOL_FIELD_DESCRIPTIONS (req: configId, toolId) [pre-type-system-refactor only]
|
|
1357
|
+
- op=UPDATE_ZAI_CONFIG_TPA_CONTEXT (req: configId, tpaConfigId) [pre-type-system-refactor only]`,ops:{ADD_ZAI_CONFIGS:"ADD_ZAI_CONFIGS",ADD_ZAI_CONFIG_API_CONTEXTS:"ADD_ZAI_CONFIG_API_CONTEXTS",ADD_ZAI_CONFIG_DB_CONTEXTS:"ADD_ZAI_CONFIG_DB_CONTEXTS",ADD_ZAI_CONFIG_INPUT_ARGS:"ADD_ZAI_CONFIG_INPUT_ARGS",ADD_ZAI_CONFIG_OUTPUT_FIELDS:"ADD_ZAI_CONFIG_OUTPUT_FIELDS",ADD_ZAI_CONFIG_TOOLS:"ADD_ZAI_CONFIG_TOOLS",ADD_ZAI_CONFIG_TPA_CONTEXTS:"ADD_ZAI_CONFIG_TPA_CONTEXTS",DELETE_ZAI_CONFIGS:"DELETE_ZAI_CONFIGS",DELETE_ZAI_CONFIG_API_CONTEXTS:"DELETE_ZAI_CONFIG_API_CONTEXTS",DELETE_ZAI_CONFIG_DB_CONTEXTS:"DELETE_ZAI_CONFIG_DB_CONTEXTS",DELETE_ZAI_CONFIG_INPUT_ARGS:"DELETE_ZAI_CONFIG_INPUT_ARGS",DELETE_ZAI_CONFIG_OUTPUT_FIELDS:"DELETE_ZAI_CONFIG_OUTPUT_FIELDS",DELETE_ZAI_CONFIG_TOOLS:"DELETE_ZAI_CONFIG_TOOLS",DELETE_ZAI_CONFIG_TPA_CONTEXTS:"DELETE_ZAI_CONFIG_TPA_CONTEXTS",DUPLICATE_ZAI_CONFIG:"DUPLICATE_ZAI_CONFIG",GET_ALL_ZAI_CONFIGS_INFO:"GET_ALL_ZAI_CONFIGS_INFO",GET_ZAI_CONFIG_DETAIL:"GET_ZAI_CONFIG_DETAIL",GET_ZAI_CONFIG_SELECTABLE_TYPES:"GET_ZAI_CONFIG_SELECTABLE_TYPES",GET_ZAI_MODEL_OPTIONS:"GET_ZAI_MODEL_OPTIONS",UPDATE_ZAI_CONFIG:"UPDATE_ZAI_CONFIG",UPDATE_ZAI_CONFIG_API_CONTEXT:"UPDATE_ZAI_CONFIG_API_CONTEXT",UPDATE_ZAI_CONFIG_DB_CONTEXT:"UPDATE_ZAI_CONFIG_DB_CONTEXT",UPDATE_ZAI_CONFIG_INPUT_ARGS:"UPDATE_ZAI_CONFIG_INPUT_ARGS",UPDATE_ZAI_CONFIG_OUTPUT:"UPDATE_ZAI_CONFIG_OUTPUT",UPDATE_ZAI_CONFIG_OUTPUT_FIELD:"UPDATE_ZAI_CONFIG_OUTPUT_FIELD",UPDATE_ZAI_CONFIG_OUTPUT_MODE:"UPDATE_ZAI_CONFIG_OUTPUT_MODE",UPDATE_ZAI_CONFIG_TOOL:"UPDATE_ZAI_CONFIG_TOOL",UPDATE_ZAI_CONFIG_TOOL_DESCRIPTION_CONFIGS:"UPDATE_ZAI_CONFIG_TOOL_DESCRIPTION_CONFIGS",UPDATE_ZAI_CONFIG_TOOL_FIELD_DESCRIPTIONS:"UPDATE_ZAI_CONFIG_TOOL_FIELD_DESCRIPTIONS",UPDATE_ZAI_CONFIG_TPA_CONTEXT:"UPDATE_ZAI_CONFIG_TPA_CONTEXT"},inputSchema:{addRelations:c.array(c.any()).optional(),apiId:c.string().optional(),apiIds:c.array(c.any()).optional(),argKeys:c.array(c.any()).optional(),arrayLevel:c.number().optional(),clearLimit:c.boolean().optional(),columns:c.array(c.any()).optional(),configId:c.string().optional(),configIds:c.array(c.any()).optional(),customModelIdentifier:c.record(c.any()).optional(),description:c.string().optional(),enable:c.boolean().optional(),fieldPath:c.array(c.any()).optional(),ignoreNullValuesFromContext:c.boolean().optional(),imageInputQuality:c.enum(["LOW","HIGH"]).optional(),inputDescriptionConfigs:c.record(c.any()).optional(),inputFieldDescriptions:c.array(c.any()).optional(),isStreaming:c.boolean().optional(),isStructured:c.boolean().optional(),items:c.array(c.any()).optional(),limit:c.number().optional(),maxRound:c.number().optional(),maxTokenSize:c.number().optional(),name:c.string().optional(),names:c.array(c.any()).optional(),outputDescriptionConfig:c.record(c.any()).optional(),outputFieldDescriptions:c.array(c.any()).optional(),outputType:c.string().optional(),parentFieldPath:c.array(c.any()).optional(),relationPath:c.array(c.any()).optional(),removeRelations:c.array(c.any()).optional(),required:c.boolean().optional(),schemaPath:c.array(c.any()).optional(),selectedFieldPaths:c.array(c.any()).optional(),selectedFieldsByType:c.record(c.any()).optional(),slot:c.enum(["INPUT","OUTPUT"]).optional(),sourceZAiConfigId:c.string().optional(),tableDisplayName:c.string().optional(),tableDisplayNames:c.array(c.any()).optional(),temperature:c.number().optional(),toolId:c.string().optional(),toolIds:c.array(c.any()).optional(),tpaConfigId:c.string().optional(),tpaConfigIds:c.array(c.any()).optional()}}],Lz={ADD_ACTION_FLOW_GROUPS:"post_type_system_refactor",ADD_ACTION_FLOW_OUTPUT_FIELDS:"pre_type_system_refactor",ADD_API_INPUT_VARIABLES:"post_type_system_refactor",ADD_API_PARAMETERS:"post_type_system_refactor",ADD_API_RESPONSE_CONFIGS:"post_type_system_refactor",ADD_API_WORKSPACE_CONSTANTS:"post_type_system_refactor",ADD_API_WORKSPACES:"post_type_system_refactor",ADD_APIS:"post_type_system_refactor",ADD_CUSTOM_CODE_NODE_OUTPUT_VALUE:"pre_type_system_refactor",ADD_ENUM_DEFINITION_GROUPS:"post_type_system_refactor",ADD_ENUM_DEFINITIONS:"post_type_system_refactor",ADD_ENUM_OPTIONS:"post_type_system_refactor",ADD_OBJECT_TYPE_DEFINITION_GROUPS:"post_type_system_refactor",ADD_OBJECT_TYPE_DEFINITIONS:"post_type_system_refactor",ADD_TPA_CONFIG_PARAMETERS:"pre_type_system_refactor",ADD_TPA_CONFIGS:"pre_type_system_refactor",ADD_TPA_PARAMETER_CHILDREN:"pre_type_system_refactor",ADD_TPA_RESPONSE_DATA:"pre_type_system_refactor",ADD_TPA_RESPONSE_DATA_CHILDREN:"pre_type_system_refactor",ADD_TYPE_DEFINITION_FIELDS:"post_type_system_refactor",ADD_ZAI_CONFIG_API_CONTEXTS:"post_type_system_refactor",ADD_ZAI_CONFIG_OUTPUT_FIELDS:"pre_type_system_refactor",ADD_ZAI_CONFIG_TPA_CONTEXTS:"pre_type_system_refactor",CLEAR_ACTION_FLOW_OUTPUT:"post_type_system_refactor",CLEAR_CUSTOM_CODE_NODE_OUTPUT_TYPE:"post_type_system_refactor",COPY_PRIVATE_OBJECT_TYPE_AS_PUBLIC:"post_type_system_refactor",COPY_PUBLIC_OBJECT_TYPE_AS_PRIVATE:"post_type_system_refactor",DELETE_ACTION_FLOW_GROUPS:"post_type_system_refactor",DELETE_ACTION_FLOW_OUTPUT_FIELDS:"pre_type_system_refactor",DELETE_API_CODECS:"post_type_system_refactor",DELETE_API_INPUT_VARIABLES:"post_type_system_refactor",DELETE_API_PARAMETERS:"post_type_system_refactor",DELETE_API_RESPONSE_CONFIGS:"post_type_system_refactor",DELETE_API_WORKSPACE_CONSTANTS:"post_type_system_refactor",DELETE_API_WORKSPACES:"post_type_system_refactor",DELETE_APIS:"post_type_system_refactor",DELETE_CALLBACK_CODECS:"post_type_system_refactor",DELETE_CUSTOM_CODE_NODE_OUTPUT_VALUE:"pre_type_system_refactor",DELETE_ENUM_DEFINITION_GROUPS:"post_type_system_refactor",DELETE_ENUM_DEFINITIONS:"post_type_system_refactor",DELETE_ENUM_OPTIONS:"post_type_system_refactor",DELETE_OBJECT_TYPE_DEFINITION_GROUPS:"post_type_system_refactor",DELETE_OBJECT_TYPE_DEFINITIONS:"post_type_system_refactor",DELETE_TPA_CONFIG_PARAMETERS:"pre_type_system_refactor",DELETE_TPA_CONFIGS:"pre_type_system_refactor",DELETE_TPA_PARAMETER_CHILDREN:"pre_type_system_refactor",DELETE_TPA_RESPONSE_DATA:"pre_type_system_refactor",DELETE_TPA_RESPONSE_DATA_CHILDREN:"pre_type_system_refactor",DELETE_TYPE_DEFINITION_FIELDS:"post_type_system_refactor",DELETE_ZAI_CONFIG_API_CONTEXTS:"post_type_system_refactor",DELETE_ZAI_CONFIG_OUTPUT_FIELDS:"pre_type_system_refactor",DELETE_ZAI_CONFIG_TPA_CONTEXTS:"pre_type_system_refactor",DUPLICATE_ACTION_FLOW:"post_type_system_refactor",DUPLICATE_ACTION_FLOW_NODES:"post_type_system_refactor",DUPLICATE_API:"post_type_system_refactor",DUPLICATE_ZAI_CONFIG:"post_type_system_refactor",GET_ACTION_FLOW_GROUPS:"post_type_system_refactor",GET_ALL_API_WORKSPACES:"post_type_system_refactor",GET_ALL_APIS_INFO:"post_type_system_refactor",GET_ALL_ENUM_DEFINITIONS:"post_type_system_refactor",GET_ALL_OBJECT_DEFINITIONS:"post_type_system_refactor",GET_ALL_TPA_CONFIGS_INFO:"pre_type_system_refactor",GET_API_CODEC_OPTIONS:"post_type_system_refactor",GET_API_DETAIL:"post_type_system_refactor",GET_API_SELECTABLE_TYPES:"post_type_system_refactor",GET_API_WORKSPACE_DETAIL:"post_type_system_refactor",GET_CALLBACK_CODEC_OPTIONS:"post_type_system_refactor",GET_ENUM_DEFINITION_DETAIL:"post_type_system_refactor",GET_ENUM_DEFINITION_GROUPS:"post_type_system_refactor",GET_OBJECT_TYPE_DEFINITION_DETAIL:"post_type_system_refactor",GET_OBJECT_TYPE_DEFINITION_GROUPS:"post_type_system_refactor",GET_TPA_CONFIG_DETAIL:"pre_type_system_refactor",GET_TYPE_DEFINITION_FIELD_SELECTABLE_TYPES:"post_type_system_refactor",MOVE_ACTION_FLOWS_TO_GROUP:"post_type_system_refactor",MOVE_APIS_TO_WORKSPACE:"post_type_system_refactor",MOVE_ENUM_DEFINITIONS_TO_GROUP:"post_type_system_refactor",MOVE_OBJECT_TYPE_DEFINITIONS_TO_GROUP:"post_type_system_refactor",REORDER_TABLE_FIELDS:"post_type_system_refactor",REORDER_TYPE_DEFINITION_FIELDS:"post_type_system_refactor",SET_ACTION_FLOW_OUTPUT:"post_type_system_refactor",SET_API_CODECS:"post_type_system_refactor",SET_API_CONTENT_TYPE:"post_type_system_refactor",SET_CALLBACK_CODECS:"post_type_system_refactor",SET_CALLBACK_REQUEST_PARAMETERS:"pre_type_system_refactor",SET_CALLBACK_REQUEST_TYPE:"post_type_system_refactor",SET_CALLBACK_RESPONSE_BODY_FIELDS:"pre_type_system_refactor",SET_CALLBACK_RESPONSE_BODY_TYPE:"post_type_system_refactor",SET_CUSTOM_CODE_NODE_OUTPUT_TYPE:"post_type_system_refactor",SET_TPA_CONFIG_PAGING:"pre_type_system_refactor",UPDATE_ACTION_FLOW_GROUPS:"post_type_system_refactor",UPDATE_API:"post_type_system_refactor",UPDATE_API_INPUT_VARIABLES:"post_type_system_refactor",UPDATE_API_PARAMETERS:"post_type_system_refactor",UPDATE_API_RESPONSE_CONFIGS:"post_type_system_refactor",UPDATE_API_WORKSPACE:"post_type_system_refactor",UPDATE_API_WORKSPACE_CONSTANTS:"post_type_system_refactor",UPDATE_CUSTOM_CODE_NODE_OUTPUT_VALUE:"pre_type_system_refactor",UPDATE_ENUM_DEFINITION_GROUPS:"post_type_system_refactor",UPDATE_ENUM_DEFINITIONS:"post_type_system_refactor",UPDATE_ENUM_OPTIONS:"post_type_system_refactor",UPDATE_OBJECT_TYPE_DEFINITION_GROUPS:"post_type_system_refactor",UPDATE_OBJECT_TYPE_DEFINITIONS:"post_type_system_refactor",UPDATE_ROLE_API_PERMISSION:"post_type_system_refactor",UPDATE_ROLE_TPA_PERMISSION:"pre_type_system_refactor",UPDATE_TPA_CONFIG:"pre_type_system_refactor",UPDATE_TPA_CONFIG_PARAMETER:"pre_type_system_refactor",UPDATE_TPA_PARAMETER_CHILD:"pre_type_system_refactor",UPDATE_TPA_RESPONSE_DATA:"pre_type_system_refactor",UPDATE_TPA_RESPONSE_DATA_CHILD:"pre_type_system_refactor",UPDATE_TYPE_DEFINITION_FIELDS:"post_type_system_refactor",UPDATE_ZAI_CONFIG_API_CONTEXT:"post_type_system_refactor",UPDATE_ZAI_CONFIG_OUTPUT:"post_type_system_refactor",UPDATE_ZAI_CONFIG_OUTPUT_FIELD:"pre_type_system_refactor",UPDATE_ZAI_CONFIG_OUTPUT_MODE:"pre_type_system_refactor",UPDATE_ZAI_CONFIG_TOOL_DESCRIPTION_CONFIGS:"post_type_system_refactor",UPDATE_ZAI_CONFIG_TOOL_FIELD_DESCRIPTIONS:"pre_type_system_refactor",UPDATE_ZAI_CONFIG_TPA_CONTEXT:"pre_type_system_refactor"};var YP={"actionflow.list_node_templates":{description:"List the preset action-flow integration nodes (the TEMPLATE_CODE catalog \u2014 e.g. SMS, video/AI generation) for planning: each template\u2019s templateCodeId, displayName, group, async flag, and input/output param types. To add one, read schema_actionflow_node op=BROWSE_ACTION_FLOW_ADD_NODE_OPTIONS at the position and pass that entry\u2019s `node` to op=ADD_NODE. A TEMPLATE_CODE node already in the schema carries one of these templateCodeIds; never rewrite it to an id from anywhere else.",tool:{name:"list_actionflow_node_templates"},cli:{path:"actionflow list-node-templates"}},"component.tab_bar_icons":{description:"The preset tab-bar icons this deployment ships, as name and media exId \u2014 home, cart, chat, profile and the rest. A tab that is shown needs an icon for both its normal and its selected state or the project reports an error, and the exIds are hashids of media rows that cannot be derived from an icon\u2019s name, so take them from here before schema_tab_bar op=UPDATE_TAB_BAR_ITEMS \u2014 that tool rejects a value that could not be an exId rather than letting the mini-program build fail over a file it cannot find. To use an icon that is not in the list, upload it in the editor and use the exId it is stored under.",tool:{name:"get_tab_bar_icons"},cli:{path:"component tab-bar-icons"}},"workspace.set":{description:"Set the workspace root for local credentials, daemon registry, and project context.",tool:{name:"set_current_working_directory",inputSchema:{cwd:c.string()}}},"auth.login":{description:"Start browser login and save credentials.",cli:{path:"login"}},"auth.logout":{description:"Delete local credentials and unload schema sessions.",cli:{path:"logout"}},"auth.whoami":{description:"Show the currently authenticated account token payload.",cli:{path:"whoami"}},"auth.reauth":{description:"Delete credentials and start login again.",cli:{path:"reauth"}},"account.profile":{description:"Fetch current account and organization/project-space metadata used for project creation.",tool:{name:"get_account_profile"},cli:{path:"account profile",alias:"account me"}},"projects.search":{description:"List/search projects with pagination.",tool:{name:"get_projects",inputSchema:{projectName:c.string().optional(),cursor:c.string().nullable().optional(),limit:c.number().optional()}},cli:{path:"projects search"}},"projects.list":{description:"List projects.",cli:{path:"projects list"}},"project.create":{description:"Create a new blank project. Defaults to the current account organization and waits for the project to appear in search. Creates a pre- or post-type-system-refactor project automatically based on the account rollout; pass useNewType/useRefactoredComponent to override.",tool:{name:"create_project",inputSchema:{projectName:c.string(),templateExId:c.string().nullable().optional(),platform:c.string().nullable().optional(),projectSpaceType:c.string().optional(),organizationExId:c.string().optional(),category:c.string().nullable().optional(),forBeginnerGuide:c.boolean().optional(),useRefactoredComponent:c.boolean().optional(),useNewType:c.boolean().optional(),wait:c.boolean().optional(),timeoutMs:c.number().optional()}},cli:{path:"project create"}},"project.set_current":{description:"Set the default project context by external id.",tool:{name:"set_current_project",inputSchema:{projectExId:c.string()}},cli:{path:"project set-current"}},"project.get_current":{description:"Get the current project context.",tool:{name:"get_current_project"},cli:{path:"project current",alias:"project get-current"}},"project.detail":{description:"Fetch the Zed project/app detail payload, including app list, project config, latest schema metadata, and deployment info.",cli:{path:"project detail"}},"project.metadata":{description:"Fetch a lean project summary: identity, platforms, publish/deploy state (incl. hasUndeployedChanges), configured integrations, plan, capabilities, and RPS. Pass raw=true for the full unshaped payload.",cli:{path:"project metadata",alias:"project inspect"}},"project.resources":{description:"Fetch project resource consumption, plan/capability limits, RPS stats, and optional resource history.",cli:{path:"project resources"}},"project.rename":{description:"Rename a project.",tool:{name:"rename_project",inputSchema:{...ye,projectName:c.string()}},cli:{path:"project rename"}},"project.rename_app":{description:"Rename an app inside a project.",tool:{name:"rename_project_app",inputSchema:{projectExId:c.string(),appExId:c.string(),appName:c.string()}},cli:{path:"project rename-app"}},"project.delete":{description:"Delete a project. IRREVERSIBLE: requires a human to approve a native GUI dialog by retyping the project id; the agent cannot self-approve. Set MCP_HITL=off to fall back to the confirmProjectExId/force text gate in headless automation.",tool:{name:"delete_project",inputSchema:{projectExId:c.string(),confirmProjectExId:c.string().optional(),force:c.boolean().optional()}},cli:{path:"project delete"}},"project.reset":{description:"Reset a project. IRREVERSIBLE: requires a human to approve a native GUI dialog by retyping the project id; the agent cannot self-approve. Set MCP_HITL=off to fall back to the confirmProjectExId/force text gate in headless automation.",tool:{name:"reset_project",inputSchema:{projectExId:c.string(),confirmProjectExId:c.string().optional(),force:c.boolean().optional(),languageType:c.string().optional()}},cli:{path:"project reset"}},"project.sync_backend":{description:"Save the schema and deploy/sync the project runtime backend. Returns ztype diagnostics and blocks on backend validation errors by default.",tool:{name:"sync_backend",inputSchema:{...ye,buildTarget:c.string().optional(),validateMultiClient:c.boolean().optional(),allowValidationErrors:c.boolean().optional()}},cli:{path:"project sync-backend",alias:"project deploy-backend"}},"schema.load":{description:"Load a project's CRDT schema into the daemon's in-memory headless schema session.",cli:{path:"schema load"}},"schema.reload":{description:"Force reload a project schema session from the backend CRDT model and patch log.",cli:{path:"schema reload"}},"schema.status":{description:"Show daemon schema sessions and TTL state.",tool:{name:"schema_status"},cli:{path:"schema status"}},"schema.state":{description:"Read the daemon's schema revision, stale state, and latest semantic schema-change event for a project.",cli:{path:"schema state"}},"schema.events":{description:"Read recent semantic schema-change events observed by the daemon for a project.",cli:{path:"schema events"}},"schema.sync":{description:"Catch up schema CRDT patches from the backend for the loaded project session.",cli:{path:"schema sync"}},"schema.snapshot":{description:"Return the data model of the loaded schema (tables, relations, enum types). Pass full=true for the entire raw ZSchema document (UI tree + all server configs), which is much larger.",cli:{path:"schema snapshot"}},"schema.validate":{description:"Run ztype validation/type checks against the loaded schema and return stable/beta/backend diagnostics.",cli:{path:"schema validate",alias:"schema type-check"}},"bridge.flow_definition":{description:"Resolve an action flow to the definition the debug mutation takes, plus its terminal end node. Derived from the draft CRDT, so it answers with no editor tab attached.",cli:{path:"bridge flow-definition"}},"bridge.trigger_bindings":{description:"List database and scheduled trigger bindings with their flow names, table names and enabled state, derived from the draft CRDT.",cli:{path:"bridge trigger-bindings"}},"bridge.deploy_status":{description:"Compare the draft schema against the last deployed server schema and report which of the eleven server areas differ. Unlike project.inspect this diffs content against the *draft*, so unsaved edits count as pending changes.",cli:{path:"bridge deploy-status"}},"bridge.type_system_track":{description:"Report whether the project is on the PRE or POST type-system track, from the presence of the draft schema's editorConfiguration \u2014 the same predicate the editor answers with.",cli:{path:"bridge type-system-track"}},"bridge.project_errors":{description:"List the project validation errors and warnings in the shape the editor reports them, newest ztype run, capped by limit. Same union and order as the editor panel.",cli:{path:"bridge project-errors"}},"bridge.sync_backend":{description:"Save the draft schema and start the backend deploy, reporting the outcome in the shape the editor reports it. Answers IN_PROGRESS on a started deploy rather than waiting for the pipeline; re-check with bridge deploy-status.",cli:{path:"bridge sync-backend"}},"bridge.clipped_components":{description:"Measure which components on a page render clipped (content larger than their box), in the shape the editor reports. Renders the canvas in a headless browser owned by the daemon, after it has applied the latest schema patch.",cli:{path:"bridge clipped-components"}},"bridge.capture_canvas":{description:"Screenshot a page or component as the editor canvas renders it and store it as the agent session's media. Same headless renderer and patch wait as bridge clipped-components.",cli:{path:"bridge capture-canvas"}},"schema.ztype_tool_calls":{description:"Run ztype Copilot tool calls against the loaded schema as one atomic batch: either every call lands or none does, and `applied` reports which. A batch ztype rejects, or whose patch trips validation, reports errors with errorCode/failedIndex and applies nothing \u2014 pass force to apply over a DEPENDENCY_CONFLICT. Use schema_undo to revert the last change.",tool:{name:"ztype_tool_calls",inputSchema:{...ye,toolCalls:c.array(c.record(c.any())),verbose:c.boolean().optional(),readState:c.record(c.any()).optional(),force:c.boolean().optional()}},cli:{path:"schema tool-call",alias:"schema tool-calls"}},"schema.undo":{description:"Undo the most recent schema change made in this session by applying a reverse CRDT patch. Refuses if a concurrent edit touched the same path. Pairs with schema_redo.",tool:{name:"schema_undo",inputSchema:{...ye}},cli:{path:"schema undo"}},"schema.redo":{description:"Re-apply the schema change most recently undone via schema_undo in this session.",tool:{name:"schema_redo",inputSchema:{...ye}},cli:{path:"schema redo"}},"secret.save_value":{description:"Prompt the user (native GUI dialog) to set a secret's plaintext value, store it, and attach the handle so the secret reports hasValue:true. Provide secretId (an existing secret) OR displayName (create a new one). The value is typed into the dialog and never passes through this tool call or the model. Requires a desktop session (fails on headless/SSH/CI).",tool:{name:"save_secret_value",inputSchema:{...ye,secretId:c.string().optional(),displayName:c.string().optional(),description:c.string().optional()}},cli:{path:"secret save-value"}},"runtime.graphql":{description:"Run a raw GraphQL operation against the deployed project's runtime backend (the auto-generated data/actionflow/AI/TPA API), as admin.",tool:{name:"runtime_graphql",inputSchema:{...ye,query:c.string(),variables:c.record(c.any()).optional()}},cli:{path:"runtime graphql"}},"runtime.run_code":{description:"Execute a JavaScript snippet in the deployed project's Run Code sandbox and return its result. Database writes are reverted unless updateDb is true, so this is the cheap way to check what a Run Code node will actually return before wiring it into a flow. Runs on the admin surface, as admin.",tool:{name:"runtime_run_code",inputSchema:{...ye,jsCode:c.string(),args:c.record(c.any()).optional(),updateDb:c.boolean().optional()}},cli:{path:"runtime run-code"}},"runtime.query":{description:"Query rows from a deployed project's runtime table.",cli:{path:"runtime query"}},"runtime.aggregate":{description:"Count rows matching a filter in a deployed project's runtime table \u2014 the cheapest assertion available.",cli:{path:"runtime aggregate"}},"runtime.insert":{description:"Insert one or more rows into a deployed project's runtime table.",cli:{path:"runtime insert"}},"runtime.update":{description:"Update rows in a deployed project's runtime table.",cli:{path:"runtime update"}},"runtime.delete":{description:"Delete rows from a deployed project's runtime table. Requires where unless allowDeleteAll=true.",cli:{path:"runtime delete"}},"logs.search":{description:`Fetch recent runtime logs from the project's log endpoint. Window is \xB15 minutes around requestCreatedAt (ISO-8601, defaults to now). types: GATEWAY, ACTION_FLOW, ACTION_FLOW_NODE, ACTION_FLOW_CONTEXT_LOG, DEPLOYMENT, TPA, TRIGGER, SQL_GENERATION, GQL, ZAI. levels: INFO, WARNING, ERROR. customQueryCondition is an Elasticsearch condition (e.g. 'traceId: "abc-123"').`,tool:{name:"search_logs",inputSchema:{...ye,requestCreatedAt:c.string().optional(),types:c.array(c.string()).optional(),levels:c.array(c.string()).optional(),customQueryCondition:c.string().optional(),limit:c.number().optional()}},cli:{path:"logs search"}},"docs.search":{description:"Full-text search the bundled product documentation. Returns the best-matching pages as { path, title, url }, where url is the public HTTPS docs link you can cite. Use docs.get_page with a returned path to read a page.",tool:{name:"search_docs",inputSchema:{query:c.string(),limit:c.number().optional()}},cli:{path:"docs search"}},"docs.get_page":{description:'Fetch a documentation page as markdown by its path (as returned by docs.search, e.g. "/02_design/01_layout_concepts").',tool:{name:"get_doc_page",inputSchema:{path:c.string()}},cli:{path:"docs get-page"}},"platform.graphql":{description:"Guarded raw GraphQL passthrough to the platform backend (projects, accounts, publishing \u2014 the editor/meta API, not the deployed runtime).",tool:{name:"platform_graphql",inputSchema:{query:c.string(),variables:c.record(c.any()).optional()}},cli:{path:"platform graphql"}},"tpa.import_from_openapi":{description:"Import one or more Third-Party API (TPA) configs from an OpenAPI v3 spec. Provide the spec as a `url` (fetched from this machine) or paste it as `specText` (JSON or YAML). Each operation becomes a TPA endpoint with its request parameters and success/fail response shape. Capped at 25 endpoints per call \u2014 use `pathsFilter` to scope larger specs. On any failure the whole import is rolled back. Duplicates are created (not merged) with a numbered name suffix. Works on every project generation.",tool:{name:"import_tpa_from_openapi",inputSchema:{...ye,url:c.string().optional(),specText:c.string().optional(),pathsFilter:c.array(c.string()).optional()}},cli:{path:"tpa import-from-openapi"}},"tpa.fetch_doc":{description:"Fetch a web page or spec by URL for reading. Returns the page content (HTML converted to Markdown; long pages are windowed \u2014 pass `offset` with the same url to keep reading, guided by `totalLength`/`truncated`), same-site `pageLinks` to explore the documentation further, and any OpenAPI/Swagger `specLinks` found. Explore iteratively by fetching returned links, within a budget of 15 fetches per session (`fetchesRemaining`). Prefer importing a discovered spec via tpa import-from-openapi; otherwise author configs with the granular TPA schema ops.",tool:{name:"fetch_api_doc",inputSchema:{url:c.string(),offset:c.number().optional()}},cli:{path:"tpa fetch-doc"}},"site.deploy":{description:"Deploy a built frontend directory (e.g. ./dist) to the project\u2019s hosted static site and return the live url. Scans the directory, declares the manifest, uploads every asset to object storage, and switches the site over in one call \u2014 the agent never handles checksums or upload urls itself. `target` is BETA (default) or PROD; a PROD deploy takes the site live and requires a human to approve a native GUI dialog by retyping the project id; the agent cannot self-approve, and `force` does NOT approve it. Set MCP_HITL=off to fall back to the confirmProjectExId text gate in headless automation. An interrupted run resumes automatically when the directory is unchanged; pass `force` to discard it and start over. `dryRun` reports what would be uploaded without creating a deployment. The total size must fit the project\u2019s remaining object storage, and the directory must contain an index.html.",tool:{name:"deploy_static_site",inputSchema:{...ye,dir:c.string(),target:c.string().optional(),dryRun:c.boolean().optional(),force:c.boolean().optional(),concurrency:c.number().optional(),confirmProjectExId:c.string().optional()}},cli:{path:"site deploy"}},"site.status":{description:"Report the project\u2019s static site: the currently live deployment (with its url) and any upload still in progress. Use to find the site url, or to see whether an interrupted deploy is still resumable.",tool:{name:"get_static_site_status",inputSchema:{...ye,target:c.string().optional()}},cli:{path:"site status"}},"site.abort":{description:"Abandon an in-progress static site upload and delete whatever it already uploaded. Targets the current in-progress deployment unless `deploymentExId` names one. The live site is untouched.",tool:{name:"abort_static_site_deployment",inputSchema:{...ye,target:c.string().optional(),deploymentExId:c.string().optional()}},cli:{path:"site abort"}},"wechat.deploy":{description:"Upload a locally-developed WeChat mini program source tree (the directory holding app.json) to the project and start the server-side build that commits it to WeChat as the \u4F53\u9A8C\u7248 (trial version). Scans the directory, declares the manifest, uploads every file to object storage, and hands off to the build job in one call \u2014 the agent never handles checksums or upload urls itself. By default it then WAITS for the build and returns the trial version number plus the path of the trial QR code image it saved (`wait: false` returns as soon as the build starts; `timeoutSeconds` bounds the wait). Requires the project to have granted Zion third-party platform authorization. An interrupted run resumes automatically when the directory is unchanged; pass `force` to discard it and start over. `dryRun` reports what would be uploaded without creating a deployment. This does NOT submit for audit or release \u2014 it only produces a trial version to verify; submitting it for review and releasing it are done by the user in the editor, not from here.",tool:{name:"deploy_wechat_source_code",inputSchema:{...ye,dir:c.string(),dryRun:c.boolean().optional(),force:c.boolean().optional(),wait:c.boolean().optional(),timeoutSeconds:c.number().optional(),qrOut:c.string().optional(),concurrency:c.number().optional()}},cli:{path:"wechat deploy"}},"wechat.status":{description:"Report the project\u2019s WeChat mini program source upload: any upload still in progress and any build already running (with its deploymentRecordExId and start time). Use to poll a build after `wechat deploy`, or to see whether an interrupted upload is still resumable.",tool:{name:"get_wechat_source_code_status",inputSchema:{...ye}},cli:{path:"wechat status"}},"wechat.abort":{description:"Abandon an in-progress WeChat mini program source upload and delete whatever it already uploaded. Targets the current in-progress deployment unless `deploymentExId` names one. A deployment that already reached BUILDING cannot be aborted.",tool:{name:"abort_wechat_source_code_deployment",inputSchema:{...ye,deploymentExId:c.string().optional()}},cli:{path:"wechat abort"}},"wechat.qrcode":{description:"Save the WeChat trial version (\u4F53\u9A8C\u7248) QR code of the project\u2019s mini program to a local image file and return its path, along with the trial version number and the time it was committed. The QR code is written to disk rather than returned inline because it is a JPEG. Available once a `wechat deploy` build has succeeded; scanning it opens the trial version on a phone whose WeChat id is bound as a tester.",tool:{name:"get_wechat_trial_qrcode",inputSchema:{...ye,out:c.string().optional()}},cli:{path:"wechat qrcode"}}},Yg=Object.entries(YP).map(([t,e])=>({command:t,...e})),Kg=[{name:"schema_session",description:"Schema session lifecycle for the loaded project. op: LOAD (warm the in-memory CRDT session) | RELOAD (force reload from backend) | SYNC (catch up patches) | SNAPSHOT (return the data model: tables, relations, enum types; pass full=true for the entire raw document) | VALIDATE (ztype type checks, stable/beta/backend diagnostics). Edits do not go live until sync_backend.",ops:{LOAD:"schema.load",RELOAD:"schema.reload",SYNC:"schema.sync",SNAPSHOT:"schema.snapshot",VALIDATE:"schema.validate"},inputSchema:{...ye,full:c.boolean().optional()}},{name:"schema_observe",description:"Read the daemon's schema change-state for a project. op: STATE (revision, stale flag, latest change event) | EVENTS (recent semantic schema-change events; afterEventId/limit paginate).",ops:{STATE:"schema.state",EVENTS:"schema.events"},inputSchema:{projectExId:c.string().optional(),afterEventId:c.string().nullable().optional(),limit:c.number().optional()}},{name:"auth",description:"Authentication. op: LOGIN (browser login + save credentials) | LOGOUT (delete credentials, unload sessions) | WHOAMI (show authenticated account token payload) | REAUTH (delete credentials and log in again).",ops:{LOGIN:"auth.login",LOGOUT:"auth.logout",WHOAMI:"auth.whoami",REAUTH:"auth.reauth"}},{name:"project_inspect",description:"Inspect a project. op: DETAIL (app list, project config, latest schema metadata, deployment) | METADATA (plan/capability, deployment, app list, schema metadata, RPS summary) | RESOURCES (resource consumption, plan limits, RPS, optional history). includeSecrets applies to DETAIL/METADATA; refresh/resourceType/nonRealTimeDisplayedResourceTypes apply to RESOURCES.",ops:{DETAIL:"project.detail",METADATA:"project.metadata",RESOURCES:"project.resources"},inputSchema:{...ye,includeSecrets:c.boolean().optional(),refresh:c.boolean().optional(),resourceType:c.string().optional(),nonRealTimeDisplayedResourceTypes:c.array(c.string()).optional()}}];u();u();var KP={schema_table:"database",schema_view:"database",schema_common:"database",schema_overview:"database",schema_type:"type",schema_binding_inspect:"bindings",schema_create_binding:"bindings",schema_conditional_branch:"bindings",schema_custom_array_binding:"bindings",schema_condition_expr:"bindings",schema_request_filter:"bindings",schema_actionflow:"actionflow",schema_actionflow_node:"actionflow",schema_trigger:"actionflow",schema_api:"api",schema_component:"component",schema_design_system:"component",schema_action_menu:"component",schema_theme:"component",schema_tab_bar:"component",schema_client_variables:"component",schema_permission:"permissions",schema_secret:"tpa",schema_zai_config:"zai",schema_callback:"webhook",schema_payment:"payments"},Jg=t=>KP[t]??(t.includes("tpa")?"tpa":"UNMAPPED"),JP={database:'Edit the data model \u2014 tables, columns, relations, unique constraints, display names. op is a schema ToolName from the enum; args is its payload. Call guide {plugin:"database"} first for the rules and per-op arg shapes.',type:'Edit enums and object/custom type definitions (post-type-system-refactor only). op is a schema ToolName; args is its payload. Call guide {plugin:"type"} for the rules and arg shapes.',bindings:'Create and edit data bindings \u2014 option/const/formula/conditional bindings, boolean condition expressions, and request filters (where + sort), all addressed by schemaPath. op is a schema ToolName; args is its payload. Call guide {plugin:"bindings"} for the rules and arg shapes.',actionflow:'Edit server-side action flows \u2014 flows, nodes, branches, I/O, global variables, and triggers (scheduled / database-change). op is a schema ToolName; args is its payload. Call guide {plugin:"actionflow"} for the rules and arg shapes.',api:'Edit the API-integration library \u2014 workspaces, APIs, request parameters, response configs, input variables, and workspace constants. op is a schema ToolName; args is its payload. Call guide {plugin:"api"} for the rules and arg shapes.',tpa:'Edit third-party API (TPA) configs used by the action-flow Call API node \u2014 configs, parameters, nested response trees, and paging. op is a schema ToolName; args is its payload. Call guide {plugin:"tpa"} for the rules and arg shapes.',zai:'Edit ZAI AI-agent configs \u2014 agents, input args, and model settings. op is a schema ToolName; args is its payload. Call guide {plugin:"zai"} for the rules and arg shapes.',component:`Build and edit the UI \u2014 pages, containers, components, slots, properties, styles and responsive breakpoints, plus the design system (color themes, style scale) and the client's app-wide variables. op is a schema ToolName; args is its payload. Call guide {plugin:"component"} first for the tree rules, component templates, and per-op arg shapes.`,permissions:'Edit roles and their table, API, action-flow, AI, TPA, and payment permissions. op is a schema ToolName; args is its payload. Call guide {plugin:"permissions"} for the rules and arg shapes.',webhook:'Edit incoming HTTP triggers (webhooks, called callbacks in the schema) \u2014 the bound action flow, request and response body shapes, body codecs, and the provider protocol. op is a schema ToolName; args is its payload. Call guide {plugin:"webhook"} for the rules and arg shapes.',payments:'Turn payments on and pick the order table. Provider credentials stay editor-only. op is a schema ToolName; args is its payload. Call guide {plugin:"payments"} for the rules and arg shapes.'},Xg=(()=>{let t=new Map;for(let e of Cs){let n=Jg(e.name);if(n==="UNMAPPED")continue;let a=t.get(n)??new Set;for(let r of Object.values(e.ops))a.add(r);t.set(n,a)}return[...t.entries()].map(([e,n])=>({name:e,description:JP[e]??`Edit ${e}.`,ops:[...n].sort()})).sort((e,n)=>e.name.localeCompare(n.name))})(),jz=Cs.filter(t=>Jg(t.name)==="UNMAPPED").map(t=>t.name);function XP(){let t=[];for(let e of Yg){if(!e.tool)continue;let{name:n,aliases:a,inputSchema:r}=e.tool;t.push({name:n,description:e.description,command:e.command,inputSchema:r});for(let o of a??[])t.push({name:o.name,description:o.description??e.description,command:e.command,inputSchema:r})}return t}function Hz(t,e){Zg(t,XP(),e),qg(t,Kg,e),Vg(t,Xg,e),Wg(t,e),Hg(t,e)}u();u();var QP={productName:"Zion",utcOffset:"+08:00",accountTable:"\u5E10\u6237(\u8D26\u6237)",paymentTables:"\u652F\u4ED8, \u5468\u671F\u6027\u652F\u4ED8, \u9000\u6B3E",aiTables:"\u4F1A\u8BDD, \u6D88\u606F, \u5DE5\u5177\u4F7F\u7528\u8BB0\u5F55, \u6D88\u606F\u5185\u5BB9",displayNameRule:'user-visible; use the natural Chinese name as the displayName and derive the English snake_case apiName from it (e.g. displayName "\u7528\u6237\u540D" \u2192 apiName "user_name").',enumDisplayNameRule:'use a natural Chinese phrase (enum displayName "\u8BA2\u5355\u72B6\u6001", option displayName "\u5F85\u5904\u7406"); the enum id and option values stay English.',runtimeGraphqlUrl:t=>Fn().zeroApiUrlTemplate.replace("{projectExId}",t)},eC={productName:"Momen",utcOffset:"+00:00",accountTable:"account",paymentTables:"payment_record, recurring_payment, refund",aiTables:"conversation, message, tool_usage_record, message_content",displayNameRule:'user-visible; prefer it IDENTICAL to the apiName (e.g. apiName "first_name" \u2192 displayName "first_name").',enumDisplayNameRule:'keep it close to the name/value itself (enum displayName \u2248 the enum name, e.g. "OrderStatus"; an option displayName \u2248 its value, e.g. "PENDING").',runtimeGraphqlUrl:t=>Fn().zeroApiUrlTemplate.replace("{projectExId}",t)},Ds=()=>{switch(zn){case"MOMEN":return eC;case"ZION":return QP;default:throw new Error(`[product-context] unknown PRODUCT '${zn}'`)}};u();function Qg({brand:t,zeroApiUrl:e}){let n=e.replace(/^http:/,"ws:").replace(/^https:/,"wss:").replace("/api/graphql-v2","/api/graphql-subscription");return{brand:t,zeroApiUrl:e,zeroSubscriptionUrl:n}}function ey(t){let e=t.brand==="Zion"?"Zion apps conventionally sign up / log in by phone number (SMS code); email and username work too.":"Momen apps conventionally sign up / log in by email; phone (SMS code) and username work too.";return`## App-user authentication (for the frontend you generate)
|
|
1358
|
+
The deployed app's end-users obtain a JWT by logging in / registering against the same GraphQL API;
|
|
1359
|
+
unauthenticated requests fall back to the anonymous role. Distinct from the developer \`login\` that
|
|
1360
|
+
authenticates THIS CLI to ${t.brand}. ${e}
|
|
1361
|
+
|
|
1362
|
+
mutation AuthenticateWithUsername($username:String!, $password:String!, $register:Boolean!) {
|
|
1363
|
+
authenticateWithUsername(username:$username, password:$password, register:$register) {
|
|
1364
|
+
account { id permissionRoles } jwt { token }
|
|
1365
|
+
}
|
|
1366
|
+
}
|
|
1367
|
+
|
|
1368
|
+
Email and phone flows send a verification code first (verificationEnumType: LOGIN, SIGN_UP, BIND,
|
|
1369
|
+
UNBIND, DEREGISTER, RESET_PASSWORD), then authenticate:
|
|
1370
|
+
mutation ($email:String!, $type:verificationEnumType!) {
|
|
1371
|
+
sendVerificationCodeToEmail(email:$email, verificationEnumType:$type) }
|
|
1372
|
+
mutation ($email:String!, $password:String!, $verificationCode:String, $register:Boolean!) {
|
|
1373
|
+
authenticateWithEmail(email:$email, password:$password, verificationCode:$verificationCode,
|
|
1374
|
+
register:$register) { account { id permissionRoles } jwt { token } } }
|
|
1375
|
+
Phone is the same shape: sendVerificationCodeToPhone(telephone, verificationEnumType), then
|
|
1376
|
+
authenticateWithPhoneNumber(telephone, verificationCode, password, register) with the same
|
|
1377
|
+
selection set. For email/phone, supply password or verificationCode \u2014 at least one; registration
|
|
1378
|
+
usually needs both.
|
|
1379
|
+
|
|
1380
|
+
Every variant returns jwt.token \u2014 the Bearer token for that user's subsequent requests \u2014 and
|
|
1381
|
+
FZ_Account (a subset of account: email, id, permissionRoles, phoneNumber, profileImageUrl, roles,
|
|
1382
|
+
username). A server-side admin token, when you need one, is copied from the editor's Connect
|
|
1383
|
+
Backend modal \u2014 never hardcode it in client code.`}function ty(){return`## Subscription transport (WebSocket wire protocol)
|
|
1384
|
+
The subscription endpoint speaks the LEGACY subscriptions-transport-ws protocol, NOT the newer
|
|
1385
|
+
graphql-ws \u2014 a graphql-ws client fails the handshake. After connecting send
|
|
1386
|
+
{"type":"connection_init"}, wait for {"type":"connection_ack"}, then start each operation with
|
|
1387
|
+
{"id":"<unique per socket>","type":"start","payload":{operationName, query, variables}}; results
|
|
1388
|
+
arrive as {"type":"data","id":\u2026,"payload":{\u2026}} and end with {"type":"complete"}. With Apollo
|
|
1389
|
+
Client, use a subscriptions-transport-ws WebSocketLink split against the HTTP link. Re-establish
|
|
1390
|
+
the socket whenever the user's auth state changes (login/logout) so live queries carry the new
|
|
1391
|
+
role.`}function ny(t){let e=`## Invoking payments from the runtime GraphQL API
|
|
1392
|
+
Prerequisites are design-time (payments.md): payment module enabled and bound to the order table,
|
|
1393
|
+
gateway credentials configured. Create the order SERVER-SIDE first \u2014 an actionflow takes product
|
|
1394
|
+
ids, computes the authoritative amount, inserts the order row, and returns its id; never trust a
|
|
1395
|
+
client-computed price. Fulfillment happens ONLY in the idempotent payment callback flow \u2014 never on
|
|
1396
|
+
the return/result page. The gateway's webhook is asynchronous: after payment, wait ~2s before the
|
|
1397
|
+
first order-status check, then poll briefly.`;return t.brand==="Zion"?`${e}
|
|
1398
|
+
|
|
1399
|
+
Alipay (PC web):
|
|
1400
|
+
mutation ($outTradeNo:String!, $totalAmount:Float!, $subject:String!, $productCode:String!,
|
|
1401
|
+
$returnUrl:String!) {
|
|
1402
|
+
alipayTrade(bizContent:{ out_trade_no:$outTradeNo, total_amount:$totalAmount,
|
|
1403
|
+
subject:$subject, product_code:$productCode }, returnUrl:$returnUrl) }
|
|
1404
|
+
out_trade_no is the order id; product_code is FAST_INSTANT_TRADE_PAY for PC web; total_amount is
|
|
1405
|
+
yuan as Float (> 0.01, \u2264 2 decimals \u2014 the backend stringifies it for Alipay); returnUrl MUST be the
|
|
1406
|
+
site origin (window.location.origin), not a deep path. Returns [formHtml, tradeNo]: render formHtml
|
|
1407
|
+
AS-IS (extract its <form> + <script> and document.write them) \u2014 NEVER rebuild the form; re-escaping
|
|
1408
|
+
biz_content breaks the RSA2 signature. tradeNo is informational only (the real trade no arrives via
|
|
1409
|
+
the webhook). alipayAppTrade(bizContent) is the in-app variant (no returnUrl). After payment Alipay
|
|
1410
|
+
redirects to returnUrl?out_trade_no=\u2026; check status via your order-status flow or the query
|
|
1411
|
+
getPaymentRecordsByOutTradeNo(outTradeNo:\u2026).
|
|
1412
|
+
|
|
1413
|
+
WeChat Pay (mini-program / JSAPI \u2014 requires the account's WeChat openId):
|
|
1414
|
+
createWechatPayment(type, orderId, description, amount) \u2192 SignResult (the client-side sign
|
|
1415
|
+
fields); signedPaymentInfo(type, paymentId) re-signs an existing payment record.
|
|
1416
|
+
Recurring payments (Alipay agreements) and refunds are modeled in payments.md \u2014 drive them from
|
|
1417
|
+
there.`:`${e}
|
|
1418
|
+
|
|
1419
|
+
Stripe (PaymentIntent flow \u2014 the platform creates the intent server-side; never embed your own
|
|
1420
|
+
Stripe secret keys in the frontend):
|
|
1421
|
+
mutation { stripePayV2(payDetails:{ order_id:\u2026, currency:\u2026, amount:\u2026 }) {
|
|
1422
|
+
paymentClientSecret stripeReadableAmount } }
|
|
1423
|
+
payDetails carries the order id, the ISO currency code, and the amount in major units (introspect
|
|
1424
|
+
for exact input field casing). Confirm on the frontend with Stripe.js Elements using
|
|
1425
|
+
paymentClientSecret; stripeReadableAmount is a display-ready amount string. stripePay(payDetails)
|
|
1426
|
+
is the older variant returning the bare clientSecret string. To reconcile after confirmation, query
|
|
1427
|
+
findOrderIdByPaymentIntentId(paymentIntentId:\u2026). Stripe subscriptions and refunds are modeled in
|
|
1428
|
+
payments.md \u2014 drive them from there.`}var nC=t=>({role:"user",content:{type:"text",text:t}}),Un=(t,e)=>({description:t,messages:[nC(e)]}),ay=()=>Qg({brand:Ds().productName,zeroApiUrl:Fn().zeroApiUrlTemplate}),Rt=t=>{let e=jg[t];if(!e)throw new Error(`runtime protocol section '${t}' missing from the plugin manifest`);return e},Dr=(t,e)=>{let n=wa[t]?.[e];return n?.available?n.prompt??"":""},Rr=async(t,e)=>{let n=e?{projectExId:e}:{},a=await Ns(t,e),r=null;try{let o=await t({name:"schema.ztype_tool_calls",args:{...n,apply:!1,toolCalls:[{toolCallId:"prompt-tables",name:"GET_ALL_TABLE_DISPLAY_NAMES",args:{}}]}});o.ok&&o.data!==void 0&&(r=JSON.stringify(o.data,null,2))}catch{}return{variant:a,tables:r}},wu=t=>t?`
|
|
1429
|
+
|
|
1430
|
+
Current tables in the loaded schema:
|
|
1431
|
+
${t}`:`
|
|
1432
|
+
|
|
1433
|
+
(No schema is loaded yet \u2014 call schema_session op=LOAD, then schema_table op=GET_INFOS to learn the current structure.)`;function iF(t,e){let{productName:n}=Ds(),a=t.registerPrompt.bind(t);a("inspect-project",{title:"Inspect a project",description:`Pin a ${n} project and summarize its apps, schema, and health.`,argsSchema:{projectExId:c.string().optional(),projectName:c.string().optional()}},async({projectExId:r,projectName:o})=>{let{tables:s}=await Rr(e,r),i=r?`project ${r}`:o?`the project named "${o}"`:"the current project";return Un("Project inspection workflow",`Give me a briefing on ${i}.
|
|
1434
|
+
|
|
1435
|
+
Steps:
|
|
1436
|
+
${o&&!r?`- get_projects to resolve the exId from the name.
|
|
1437
|
+
`:""}- set_current_project to pin it, then project_inspect (op DETAIL then METADATA) for apps, config, plan/capability, deployment, and RPS.
|
|
1438
|
+
- schema_session op=LOAD and schema_table op=GET_INFOS to understand the data model.
|
|
1439
|
+
- Summarize: what the app does, its core tables/relations, deployment state, and anything that looks misconfigured or risky.${wu(s)}`)}),a("edit-schema",{title:"Edit the schema safely",description:"Load, mutate, validate, save, and deploy a data-model change with the full data-model + type rules.",argsSchema:{instruction:c.string(),projectExId:c.string().optional()}},async({instruction:r,projectExId:o})=>{let{variant:s,tables:i}=await Rr(e,o);return Un("Safe schema-editing workflow",`Apply this data-model change${o?` to project ${o}`:""}: "${r}".
|
|
1440
|
+
|
|
1441
|
+
${Dr("database",s)}
|
|
1442
|
+
|
|
1443
|
+
${Dr("type",s)}
|
|
1444
|
+
|
|
1445
|
+
Order: schema_session op=LOAD \u2192 read current structure \u2192 mutate (schema_table / schema_type; each edit applies immediately, schema_undo reverts the last) \u2192 schema_session op=VALIDATE \u2192 sync_backend. Stop and report if VALIDATE or sync_backend fails \u2014 do not force past validation errors.${wu(i)}`)}),a("query-data",{title:"Query project data",description:`Answer a question against a ${n} project's data using the auto-generated GraphQL API.`,argsSchema:{question:c.string(),projectExId:c.string().optional()}},async({question:r,projectExId:o})=>{let s=ay(),{tables:i}=await Rr(e,o);return Un("Data query workflow",`Answer this question about the project's data: "${r}".
|
|
1446
|
+
|
|
1447
|
+
${Rt("query-language")}
|
|
1448
|
+
|
|
1449
|
+
${Rt("filter-grammar")}
|
|
1450
|
+
|
|
1451
|
+
${Rt("aggregations")}
|
|
1452
|
+
|
|
1453
|
+
${Rt("formula-catalog")}
|
|
1454
|
+
|
|
1455
|
+
${Rt("runtime-enums")}
|
|
1456
|
+
|
|
1457
|
+
${ey(s)}
|
|
1458
|
+
|
|
1459
|
+
${ty()}
|
|
1460
|
+
|
|
1461
|
+
Use runtime_graphql for all reads (queries and mutations). Verify table and column names from the schema before querying.${wu(i)}`)}),a("invoke-baas",{title:"Invoke an actionflow, AI agent, third-party API, or payment",description:"Trigger a server-side actionflow, ZAI agent, imported API, or payment through the runtime GraphQL API.",argsSchema:{goal:c.string(),projectExId:c.string().optional()}},async({goal:r,projectExId:o})=>{let s=ay();return Un("Actionflow / AI agent / API / payment invocation workflow",`Goal: "${r}".
|
|
1462
|
+
|
|
1463
|
+
First read the project schema (project_inspect op=DETAIL / schema_session op=LOAD) to find the
|
|
1464
|
+
actionflow / agent / API id, its version, and its input argument names. Then invoke it via
|
|
1465
|
+
runtime_graphql against the runtime endpoint${o?` (${Ds().runtimeGraphqlUrl(o)})`:""}.
|
|
1466
|
+
|
|
1467
|
+
${Rt("actionflow-invocation")}
|
|
1468
|
+
|
|
1469
|
+
${Rt("ai-agent-invocation")}
|
|
1470
|
+
|
|
1471
|
+
${Rt("third-party-invocation")}
|
|
1472
|
+
|
|
1473
|
+
${ny(s)}`)}),a("upload-asset",{title:"Upload a binary asset",description:"Upload an image/video/file via the mandatory presigned-URL flow and reference it by id.",argsSchema:{projectExId:c.string().optional()}},async()=>Un("Binary asset upload workflow",`Upload a binary asset and reference it from a row.
|
|
1474
|
+
|
|
1475
|
+
${Rt("asset-upload")}
|
|
1476
|
+
|
|
1477
|
+
Run the presigned-URL mutation through runtime_graphql, perform the PUT yourself, then
|
|
1478
|
+
store the returned id in the target table's *_id column via a runtime_graphql mutation.`)),a("audit-permissions",{title:"Audit or diagnose permissions",description:`Investigate a ${n} access-control question, 403 error, or RBAC/ABAC configuration using logs and schema state.`,argsSchema:{concern:c.string(),projectExId:c.string().optional()}},async({concern:r,projectExId:o})=>{let{variant:s}=await Rr(e,o);return Un("Permission audit / diagnosis workflow",`Investigate this permission concern: "${r}".
|
|
1479
|
+
|
|
1480
|
+
${Dr("permissions",s)}
|
|
1481
|
+
|
|
1482
|
+
${Dr("logs",s)}
|
|
1483
|
+
|
|
1484
|
+
If it is a runtime 403, pull recent activity with schema_observe op=EVENTS and search_logs${o?` for project ${o}`:""} (GQL/GATEWAY types) to find the failing role/table/op, then confirm with a targeted
|
|
1485
|
+
runtime_graphql read. State exactly which editor Settings change (and whether a
|
|
1486
|
+
sync_backend) is needed \u2014 the agent cannot apply permission changes directly.`)}),a("diagnose",{title:"Diagnose a runtime error",description:`Investigate a ${n} runtime error or permission issue using logs and schema state.`,argsSchema:{symptom:c.string(),projectExId:c.string().optional()}},async({symptom:r,projectExId:o})=>{let{variant:s}=await Rr(e,o);return Un("Runtime diagnosis workflow",`Investigate this symptom: "${r}".
|
|
1487
|
+
|
|
1488
|
+
${Dr("logs",s)}
|
|
1489
|
+
|
|
1490
|
+
Pull recent activity with schema_observe (op EVENTS and STATE)${o?` for project ${o}`:""}, and run targeted reads with runtime_graphql to confirm the hypothesis. Separate
|
|
1491
|
+
configuration mistakes from platform bugs, and state exactly which editor change or sync_backend
|
|
1492
|
+
step is needed to fix it.`)})}export{sC as a,ly as b,_y as c,Lt as d,iC as e,Fn as f,hC as g,c as h,Lz as i,Tz as j,bu as k,VP as l,WP as m,Xe as n,Ft as o,Gt as p,Kc as q,Cp as r,$ as s,$R as t,fo as u,Yb as v,ea as w,nw as x,aw as y,ow as z,sw as A,cw as B,dw as C,fw as D,bw as E,ww as F,vw as G,Do as H,Sw as I,FR as J,Mw as K,Ja as L,dl as M,eA as N,aa as O,sA as P,L as Q,Uo as R,Om as S,ys as T,Tg as U,bg as V,vg as W,Og as X,Yg as Y,Hz as Z,Ds as _,iF as $};
|