@warmhub/sdk-ts 0.163.1 → 0.164.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/CHANGELOG.md CHANGED
@@ -2,6 +2,14 @@
2
2
 
3
3
  <!-- warmhub-changelog-artifact:v1 -->
4
4
 
5
+ ## 0.164.0
6
+
7
+ No new release notes.
8
+
9
+ ## 0.163.2
10
+
11
+ No new release notes.
12
+
5
13
  ## 0.163.1
6
14
 
7
15
  No new release notes.
package/changelog.json CHANGED
@@ -330,6 +330,16 @@
330
330
  "version": "0.163.1",
331
331
  "sourceSha": "7cf96b6c2ebcf678747184fea92b28795557796a",
332
332
  "notes": []
333
+ },
334
+ {
335
+ "version": "0.163.2",
336
+ "sourceSha": "a70e2c1a8237adafbffcab2d276c2acb0900a984",
337
+ "notes": []
338
+ },
339
+ {
340
+ "version": "0.164.0",
341
+ "sourceSha": "f38a1e3a57698c339d0c56eee8de2509293a00ca",
342
+ "notes": []
333
343
  }
334
344
  ]
335
345
  }
@@ -27,11 +27,11 @@ var y=class e{static FOLD_CASE=1;static LITERAL=2;static CLASS_NL=4;static DOT_N
27
27
  `),x.CODES.get(`
28
28
  `)));let o=!0;for(;!t.more()||t.peek()!==x.CODES.get(`]`)||o;){if(t.more()&&t.lookingAt(`-`)&&(this.flags&y.PERL_X)===0&&!o){let r=t.rest();if(r===`-`||!r.startsWith(`-]`))throw t.rewindTo(n),new j(e.ERR_INVALID_CHAR_RANGE,t.rest())}o=!1;let r=t.pos();if(t.lookingAt(`[:`)){if(this.parseNamedClass(t,i))continue;t.rewindTo(r)}if(this.parseUnicodeClass(t,i)||this.parsePerlClassEscape(t,i))continue;t.rewindTo(r);let a=e.parseClassChar(t,n),s=a;if(t.more()&&t.lookingAt(`-`)){if(t.skip(1),t.more()&&t.lookingAt(`]`))t.skip(-1);else if(s=e.parseClassChar(t,n),s<a)throw new j(e.ERR_INVALID_CHAR_RANGE,t.from(r))}(this.flags&y.FOLD_CASE)===0?i.appendRange(a,s):i.appendFoldedRange(a,s)}t.skip(1),i.cleanClass(),a<0&&i.negateClass(),r.runes=i.toArray(),this.push(r)}},It=class e{static initTest(t){let n=e.compile(t),r=new e(n.expr,n.prog,n.numSubexp,n.longest);return r.cond=n.cond,r.prefix=n.prefix,r.prefixUTF8=n.prefixUTF8,r.prefixComplete=n.prefixComplete,r.prefixRune=n.prefixRune,r.prefilter=n.prefilter,r}static compile(t){return e.compileImpl(t,y.PERL,!1)}static compilePOSIX(t){return e.compileImpl(t,y.POSIX,!0)}static compileImpl(t,n,r){let i=Ft.parse(t,n),a=i.maxCap();i=mt.simplify(i);let o=ct.build(i),s=pt.compileRegexp(i),c=new e(t,s,a,r);c.prefilter=o.type===F.Type.NONE?null:o;let[l,u]=s.prefix();return c.prefixComplete=l,c.prefix=u,c.prefixUTF8=E.stringToUtf8ByteArray(c.prefix),c.prefix.length>0&&(c.prefixRune=c.prefix.codePointAt(0)),c.namedGroups=i.namedGroups,c}static match(t,n){return e.compile(t).match(n)}constructor(e,t,n=0,r=0){this.expr=e,this.prog=t,this.numSubexp=n,this.longest=r,this.cond=t.startCond(),this.prefix=null,this.prefixUTF8=null,this.prefixComplete=!1,this.prefixRune=0,this.machinePool=[],this.dfa=new Ye(this.prog),this.onepass=at.compile(this.prog),this.prefilter=null}matchPrefixComplete(e,t,n,r){if((n===y.ANCHOR_START||n===y.ANCHOR_BOTH)&&t!==0)return null;let i=-1,a=-1,o=e.prefixLength(this);if(n===y.UNANCHORED){let n=e.index(this,t);if(n<0)return null;i=t+n,a=i+o}else if(n===y.ANCHOR_BOTH){if(e.endPos()!==o||e.index(this,0)!==0)return null;i=0,a=o}else if(n===y.ANCHOR_START){if(e.index(this,0)!==0)return null;i=0,a=o}if(i<0)return null;if(r>0){let e=new Int32Array(r).fill(-1);return e[0]=i,e[1]=a,Array.from(e)}return[]}createLookbehindState(){return this.prog.numLb>0?new We(this.prog):null}executeEngine(e,t,n,r,i=null){if(this.prefixComplete&&(r===0||this.numSubexp===0))return this.matchPrefixComplete(e,t,n,r);if(this.prefilter!==null&&n===y.UNANCHORED&&!this.prefilter.eval(e,t))return null;if(this.onepass!==null)return at.execute(this,e,t,n,r);if(r>0)return this.prog.numLb===0&&e.endPos()<=Qe.maxBitStateLen(this.prog)?Qe.execute(this,e,t,n,r):this.doExecuteNFA(e,t,n,r,i);if(this.prog.numLb===0){let i=this.dfa.match(e,t,n);if(i!==null)return i?[]:null;if(e.endPos()<=Qe.maxBitStateLen(this.prog))return Qe.execute(this,e,t,n,r)}return this.doExecuteNFA(e,t,n,r,i)}numberOfCapturingGroups(){return this.numSubexp}numberOfInstructions(){return this.prog.numInst()}get(){return this.machinePool.length>0?this.machinePool.pop():null}reset(){this.machinePool.length=0}put(e){this.machinePool.push(e)}toString(){return this.expr}doExecuteNFA(e,t,n,r,i=null){let a=this.get();a||=Ge.fromRE2(this),a.init(r);let o=a.match(e,t,n,i)?a.submatches():null;return this.put(a),o}match(e){return this.executeEngine(A.fromUTF16(e),0,y.UNANCHORED,0)!==null}matchWithGroup(e,t,n,r,i,a=null){return e instanceof D||(e=E.isByteArray(e)?O.utf8(e):O.utf16(e)),this.matchMachineInput(e,t,n,r,i,a)}matchMachineInput(e,t,n,r,i,a=null){if(t>n)return[!1,null];let o=e.isUTF16Encoding()?A.fromUTF16(e.asCharSequence(),0,n):A.fromUTF8(e.asBytes(),0,n),s=this.executeEngine(o,t,r,2*i,a);return s===null?[!1,null]:[!0,s]}matchUTF8(e){return this.executeEngine(A.fromUTF8(e),0,y.UNANCHORED,0)!==null}replaceAll(e,t){return this.replaceAllFunc(e,()=>t,2*e.length+1)}replaceFirst(e,t){return this.replaceAllFunc(e,()=>t,1)}replaceAllFunc(e,t,n){let r=0,i=0,a=``,o=A.fromUTF16(e),s=this.createLookbehindState(),c=0;for(;i<=e.length;){let l=this.executeEngine(o,i,y.UNANCHORED,2,s);if(l===null||l.length===0)break;a+=e.substring(r,l[0]),(l[1]>r||l[0]===0)&&(a+=t(e.substring(l[0],l[1])),c++),r=l[1];let u=o.step(i)&7;if(i+u>l[1]?i+=u:i+1>l[1]?i++:i=l[1],c>=n)break}return a+=e.substring(r),a}pad(e){if(e===null)return null;let t=(1+this.numSubexp)*2;if(e.length<t){let n=Array(t).fill(-1);for(let t=0;t<e.length;t++)n[t]=e[t];e=n}return e}allMatches(e,t,n=e=>e){let r=[],i=e.endPos();t<0&&(t=i+1);let a=0,o=0,s=-1,c=this.createLookbehindState();for(;o<t&&a<=i;){let t=this.executeEngine(e,a,y.UNANCHORED,this.prog.numCap,c);if(t===null||t.length===0)break;let l=!0;if(t[1]===a){t[0]===s&&(l=!1);let n=e.step(a);n<0?a=i+1:a+=n&7}else a=t[1];s=t[1],l&&(r.push(n(this.pad(t))),o++)}return r}findUTF8(e){let t=this.executeEngine(A.fromUTF8(e),0,y.UNANCHORED,2);return t===null?null:e.slice(t[0],t[1])}findUTF8Index(e){let t=this.executeEngine(A.fromUTF8(e),0,y.UNANCHORED,2);return t===null?null:t.slice(0,2)}find(e){let t=this.executeEngine(A.fromUTF16(e),0,y.UNANCHORED,2);return t===null?``:e.substring(t[0],t[1])}findIndex(e){return this.executeEngine(A.fromUTF16(e),0,y.UNANCHORED,2)}findUTF8Submatch(e){let t=this.executeEngine(A.fromUTF8(e),0,y.UNANCHORED,this.prog.numCap);if(t===null)return null;let n=Array(1+this.numSubexp).fill(null);for(let r=0;r<n.length;r++)2*r<t.length&&t[2*r]>=0&&(n[r]=e.slice(t[2*r],t[2*r+1]));return n}findUTF8SubmatchIndex(e){return this.pad(this.executeEngine(A.fromUTF8(e),0,y.UNANCHORED,this.prog.numCap))}findSubmatch(e){let t=this.executeEngine(A.fromUTF16(e),0,y.UNANCHORED,this.prog.numCap);if(t===null)return null;let n=Array(1+this.numSubexp).fill(null);for(let r=0;r<n.length;r++)2*r<t.length&&t[2*r]>=0&&(n[r]=e.substring(t[2*r],t[2*r+1]));return n}findSubmatchIndex(e){return this.pad(this.executeEngine(A.fromUTF16(e),0,y.UNANCHORED,this.prog.numCap))}findAllUTF8(e,t){let n=this.allMatches(A.fromUTF8(e),t,t=>e.slice(t[0],t[1]));return n.length===0?null:n}findAllUTF8Index(e,t){let n=this.allMatches(A.fromUTF8(e),t,e=>e.slice(0,2));return n.length===0?null:n}findAll(e,t){let n=this.allMatches(A.fromUTF16(e),t,t=>e.substring(t[0],t[1]));return n.length===0?null:n}findAllIndex(e,t){let n=this.allMatches(A.fromUTF16(e),t,e=>e.slice(0,2));return n.length===0?null:n}findAllUTF8Submatch(e,t){let n=this.allMatches(A.fromUTF8(e),t,t=>{let n=Array(t.length/2|0).fill(null);for(let r=0;r<n.length;r++)t[2*r]>=0&&(n[r]=e.slice(t[2*r],t[2*r+1]));return n});return n.length===0?null:n}findAllUTF8SubmatchIndex(e,t){let n=this.allMatches(A.fromUTF8(e),t);return n.length===0?null:n}findAllSubmatch(e,t){let n=this.allMatches(A.fromUTF16(e),t,t=>{let n=Array(t.length/2|0).fill(null);for(let r=0;r<n.length;r++)t[2*r]>=0&&(n[r]=e.substring(t[2*r],t[2*r+1]));return n});return n.length===0?null:n}findAllSubmatchIndex(e,t){let n=this.allMatches(A.fromUTF16(e),t);return n.length===0?null:n}};(class e{static UNANCHORED=y.UNANCHORED;static ANCHOR_START=y.ANCHOR_START;static ANCHOR_BOTH=y.ANCHOR_BOTH;constructor(t=e.UNANCHORED,n=0,r=8388608){this.anchor=t,this.jsFlags=n,this.maxMem=r;let i=y.PERL;(n&b.DISABLE_UNICODE_GROUPS)!==0&&(i&=~y.UNICODE_GROUPS),(n&b.LOOKBEHINDS)!==0&&(i|=y.LOOKBEHIND),this.re2Flags=i,this.regexps=[],this.prog=null,this.dfa=null,this.dummyRe2=null}add(e){if(this.prog)throw new ze(`Cannot add patterns after compile`);let t=e;(this.jsFlags&b.CASE_INSENSITIVE)!==0&&(t=`(?i)${t}`),(this.jsFlags&b.DOTALL)!==0&&(t=`(?s)${t}`),(this.jsFlags&b.MULTILINE)!==0&&(t=`(?m)${t}`);let n=Ft.parse(t,this.re2Flags);return this.regexps.push(mt.simplify(n)),this.regexps.length-1}compile(){if(this.prog)return;let e=pt.compileSet(this.regexps);if(e.numInst()>Ft.MAX_SIZE)throw new ze(`${Ft.ERR_LARGE}: the set compiles to ${e.numInst()} instructions, more than ${Ft.MAX_SIZE}`);this.prog=e,this.dfa=new Ye(this.prog,this.maxMem),this.dummyRe2={prog:this.prog,cond:this.prog.startCond(),prefix:``,prefixRune:0,longest:!1}}match(t){this.prog||this.compile();let n=E.isByteArray(t)?A.fromUTF8(t):A.fromUTF16(t),r=y.UNANCHORED;this.anchor===e.ANCHOR_START?r=y.ANCHOR_START:this.anchor===e.ANCHOR_BOTH&&(r=y.ANCHOR_BOTH);let i=this.dfa.matchSet(n,0,r);if(i!==null)return i;let a=Ge.fromRE2(this.dummyRe2);return a.init(0),a.matchSet(n,0,r)}});var Lt=class e{static isHexadecimal(e){return`0`<=e&&e<=`9`||`A`<=e&&e<=`F`||`a`<=e&&e<=`f`}static translate(t){let n=``;if(t instanceof RegExp&&(t.ignoreCase&&(n+=`i`),t.multiline&&(n+=`m`),t.dotAll&&(n+=`s`),t=t.source),typeof t!=`string`)return t;let r=``,i=!1,a=t.length;a===0&&(r=`(?:)`,i=!0);let o=!1,s=0;for(;s<a;){let n=t[s];if(n===`\\`){if(s+1<a)switch(n=t[s+1],n){case`\\`:r+=`\\\\`,s+=2;continue;case`c`:if(s+2<a){let e=t[s+2].charCodeAt(0);if(e>=65&&e<=90||e>=97&&e<=122){let t=e%32;r+=`\\x`,r+=(t>>4).toString(16).toUpperCase(),r+=(t&15).toString(16).toUpperCase(),s+=3,i=!0;continue}}r+=`c`,s+=2,i=!0;continue;case`u`:if(s+2<a){if(t[s+2]===`{`){let n=s+3,o=!1,c=!1;for(;n<a;){let r=t[n];if(r===`}`){c=!0;break}if(!e.isHexadecimal(r))break;o=!0,n++}if(c&&o){r+=`\\x`,s+=2,i=!0;continue}}else if(s+5<a){let n=!0;for(let r=0;r<4;r++)if(!e.isHexadecimal(t[s+2+r])){n=!1;break}if(n){r+=`\\x{`+t.substring(s+2,s+6)+`}`,s+=6,i=!0;continue}}}r+=`u`,s+=2,i=!0;continue;case`x`:{let n=!1;if(s+2<a&&t[s+2]===`{`){let r=s+3,i=!1,o=!1;for(;r<a;){let n=t[r];if(n===`}`){o=!0;break}if(!e.isHexadecimal(n))break;i=!0,r++}o&&i&&(n=!0)}else s+3<a&&e.isHexadecimal(t[s+2])&&e.isHexadecimal(t[s+3])&&(n=!0);n?(r+=`\\x`,s+=2):(r+=`x`,s+=2,i=!0);continue}case`n`:case`r`:case`t`:case`a`:case`f`:case`v`:case`d`:case`D`:case`s`:case`S`:case`w`:case`W`:case`b`:case`B`:case`p`:case`P`:case`A`:case`z`:case`Q`:case`E`:case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:r+=`\\`+n,s+=2;continue;default:{let e=t.codePointAt(s+1);if(e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122){let n=E.charCount(e);r+=t.substring(s+1,s+1+n),s+=n+1,i=!0}else{r+=`\\`;let n=E.charCount(e);r+=t.substring(s+1,s+1+n),s+=n+1}continue}}}else if(n===`/`){r+=`\\/`,s+=1,i=!0;continue}else if(n===`[`)o=!0;else if(n===`]`)o=!1;else if(!o&&n===`(`&&s+2<a&&t[s+1]===`?`&&t[s+2]===`<`&&s+3<a&&!`=!>)`.includes(t[s+3])){r+=`(?P<`,s+=3,i=!0;continue}let c=t.codePointAt(s),l=E.charCount(c);r+=t.substring(s,s+l),s+=l}let c=i?r:t;return n.length>0?`(?${n})${c}`:c}},Rt=class e{static CASE_INSENSITIVE=b.CASE_INSENSITIVE;static DOTALL=b.DOTALL;static MULTILINE=b.MULTILINE;static DISABLE_UNICODE_GROUPS=b.DISABLE_UNICODE_GROUPS;static LONGEST_MATCH=b.LONGEST_MATCH;static LOOKBEHINDS=b.LOOKBEHINDS;static quote(e){return E.quoteMeta(e)}static quoteReplacement(e,t=!1){return He.quoteReplacement(e,t)}static translateRegExp(e){return Lt.translate(e)}static compile(t,n=0){let r=t;if((n&e.CASE_INSENSITIVE)!==0&&(r=`(?i)${r}`),(n&e.DOTALL)!==0&&(r=`(?s)${r}`),(n&e.MULTILINE)!==0&&(r=`(?m)${r}`),(n&~(e.MULTILINE|e.DOTALL|e.CASE_INSENSITIVE|e.DISABLE_UNICODE_GROUPS|e.LONGEST_MATCH|e.LOOKBEHINDS))!==0)throw new Be(`Flags should only be a combination of MULTILINE, DOTALL, CASE_INSENSITIVE, DISABLE_UNICODE_GROUPS, LONGEST_MATCH, LOOKBEHINDS`);let i=y.PERL;(n&e.DISABLE_UNICODE_GROUPS)!==0&&(i&=~y.UNICODE_GROUPS),(n&e.LOOKBEHINDS)!==0&&(i|=y.LOOKBEHIND);let a=new e(t,n);return a.re2Input=It.compileImpl(r,i,(n&e.LONGEST_MATCH)!==0),a}static matches(t,n){return e.compile(t).testExact(n)}static initTest(t,n,r){if(t==null)throw Error(`pattern is null`);if(r==null)throw Error(`re2 is null`);let i=new e(t,n);return i.re2Input=r,i}constructor(e,t){this.patternInput=e,this.flagsInput=t,this.re2Input=null}reset(){this.re2Input.reset()}flags(){return this.flagsInput}pattern(){return this.patternInput}re2(){return this.re2Input}matches(e){return this.testExact(e)}matcher(e){return E.isByteArray(e)&&(e=O.utf8(e)),new He(this,e)}test(e){return E.isByteArray(e)?this.re2Input.matchUTF8(e):this.re2Input.match(e)}testExact(e){let t=E.isByteArray(e)?A.fromUTF8(e):A.fromUTF16(e);return this.re2Input.executeEngine(t,0,y.ANCHOR_BOTH,0)!==null}exec(e){let t=this.matcher(e);if(!t.find())return null;let n=[t.group(0)];for(let e=1;e<=t.groupCount();e++){let r=t.group(e);n.push(r===null?void 0:r)}n.index=t.start(0),n.input=e;let r=this.namedGroups();if(Object.keys(r).length>0){let e=t.getNamedGroups();for(let t in e)e[t]===null&&(e[t]=void 0);n.groups=e}else n.groups=void 0;return n}split(e,t=0){let n=this.matcher(e),r=[],i=0,a=0;for(;n.find();)if(a===0&&n.end()===0)a=n.end();else{if(t>0&&r.length===t-1)break;if(a===n.start()){if(t===0){i+=1,a=n.end();continue}}else for(;i>0;)r.push(``),--i;r.push(n.substring(a,n.start())),a=n.end()}if(t===0&&a!==n.inputLength()){for(;i>0;)r.push(``),--i;r.push(n.substring(a,n.inputLength()))}return(t!==0||r.length===0&&!(a===n.inputLength()&&a>0))&&r.push(n.substring(a,n.inputLength())),r}*matchAll(e){let t=this.matcher(e);for(;t.find();){let n=[t.group(0)];for(let e=1;e<=t.groupCount();e++){let r=t.group(e);n.push(r===null?void 0:r)}n.index=t.start(0),n.input=e;let r=this.namedGroups();if(Object.keys(r).length>0){let e=t.getNamedGroups();for(let t in e)e[t]===null&&(e[t]=void 0);n.groups=e}else n.groups=void 0;yield n}}toString(){return this.patternInput}programSize(){return this.re2Input.numberOfInstructions()}groupCount(){return this.re2Input.numberOfCapturingGroups()}namedGroups(){return this.re2Input.namedGroups}equals(e){return this===e?!0:e===null||this.constructor!==e.constructor?!1:this.flagsInput===e.flagsInput&&this.patternInput===e.patternInput}};const zt=[`number`,`string`,`boolean`,`wref`,`array`],Bt=[`identity`,`versioned`,`either`],Vt=`${Bt.slice(0,-1).join(`, `)}, or ${Bt.at(-1)}`,Ht=new Set(Bt);function Ut(e){return typeof e==`string`&&Ht.has(e)}function Wt(e,t){return!(`binding`in t)||!(`type`in t)||typeof t.type!=`string`||!z.has(t.type)||typeof t.binding==`string`&&z.has(t.binding)?null:(t.type.endsWith(`?`)?t.type.slice(0,-1):t.type)===`wref`?Ut(t.binding)?null:`"binding" at "${e}" must be ${Vt}`:`Constraint "binding" at "${e}" is only valid for type "wref"`}const Gt=new Set(zt),z=/* @__PURE__ */ new Set([...zt,...zt.map(e=>`${e}?`)]);function B(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Kt=/* @__PURE__ */ new Set([`minLength`,`maxLength`,`pattern`,`enum`]),qt=/* @__PURE__ */ new Set([`minimum`,`maximum`,`integer`]),Jt=/* @__PURE__ */ new Set([`shape`,`binding`]),Yt=/* @__PURE__ */ new Set([`items`,`minItems`,`maxItems`]),Xt=/* @__PURE__ */ new Set([`type`,`description`]),Zt=/* @__PURE__ */ new Set([...Xt,...Kt,...qt,...Jt,...Yt]),Qt={string:Kt,number:qt,wref:Jt,array:Yt,boolean:/* @__PURE__ */ new Set};function V(e){if(!B(e)||!(`type`in e)||typeof e.type!=`string`||!z.has(e.type))return!1;let t=e.type.endsWith(`?`)?e.type.slice(0,-1):e.type,n=Qt[t]??/* @__PURE__ */ new Set;return!(!Object.keys(e).every(e=>Xt.has(e)||n.has(e))||`minLength`in e&&typeof e.minLength!=`number`||`maxLength`in e&&typeof e.maxLength!=`number`||`pattern`in e&&typeof e.pattern!=`string`||`pattern`in e&&typeof e.pattern==`string`&&z.has(e.pattern)&&t!==`string`||`enum`in e&&!Array.isArray(e.enum)||`minimum`in e&&typeof e.minimum!=`number`||`maximum`in e&&typeof e.maximum!=`number`||`integer`in e&&typeof e.integer!=`boolean`||`shape`in e&&typeof e.shape!=`string`||`binding`in e&&!Ut(e.binding)||`shape`in e&&typeof e.shape==`string`&&z.has(e.shape)&&t!==`wref`||`items`in e&&typeof e.items==`number`||`items`in e&&typeof e.items==`boolean`||`minItems`in e&&typeof e.minItems!=`number`||`maxItems`in e&&typeof e.maxItems!=`number`)}function $t(e){return typeof e==`string`&&z.has(e)?e:V(e)?e.type:null}function en(e){let t=$t(e);if(!t)return null;let n=t.endsWith(`?`)?t.slice(0,-1):t;return Gt.has(n)?n:null}const tn=65536,nn=`WarmHub content fields are limited to ${tn} bytes. WarmHub is not a document store; store large documents in S3, Box, Drive, or another document system and reference them from WarmHub instead.`,rn=new TextEncoder;function an(e){return rn.encode(e).byteLength}function on(e,t){if(t.length*3<=65536)return null;let n=an(t);return n<=65536?null:`Field "${e}" is ${n} bytes; ${nn}`}function sn(e,t,n){let r=on(e,t);r&&n.push(r)}function cn(e){try{return new RegExp(e),!1}catch{return!0}}function ln(e){let t=``,n=!1;for(let r=0;r<e.length;r++){let i=e[r];if(i===`\\`){let a=e[r+1];if(n&&a===`b`){t+=`\\x08`,r++;continue}t+=i,a!==void 0&&(t+=a,r++)}else i===`[`?n=!0:i===`]`&&(n=!1),t+=i}return t}function un(e){try{return Rt.compile(ln(e))}catch{return}}function dn(e){return un(e)?void 0:`uses unsupported regex syntax`}function H(e){return typeof e==`string`&&e.endsWith(`?`)?{spec:e.slice(0,-1),optionalByType:!0}:V(e)&&typeof e.type==`string`&&e.type.endsWith(`?`)?{spec:{...e,type:e.type.slice(0,-1)},optionalByType:!0}:{spec:e,optionalByType:!1}}function fn(e,t){return e?.endsWith(`?`)||H(t).optionalByType}const pn=[`Arc`,`Bond`,`Pair`,`Set`,`List`],mn=[`Triple`],hn=[`Arc`,`Bond`],gn=[`Set`,`List`],_n=[...hn,...gn],vn=[`Collection`,..._n],yn=[...pn,...mn];function bn(e){return pn.includes(e)}function xn(e){return mn.includes(e)}function Sn(e){return _n.includes(e)}function Cn(e){return vn.includes(e)}function wn(e){return yn.includes(e)}const Tn=[`Content`],En=[`Readme`,`Agents`],Dn=[`LlmsTxt`],On=e=>e===`Content`,kn=e=>En.includes(e),An=e=>Dn.includes(e),jn=[`View`],Mn=e=>jn.includes(e),Nn=[`LicenseSubject`,`LicenseDeclaration`],Pn=e=>Nn.includes(e);function Fn(e){return wn(e)||Cn(e)||Mn(e)||Pn(e)}function In(e){return pn.includes(e)||Tn.includes(e)||jn.includes(e)||Nn.includes(e)}const Ln={Arc:{fields:{from:{type:`wref`,description:`Origin of the directed relationship`},to:{type:`wref`,description:`Destination of the directed relationship`}},description:`A directed relationship between two things`},Bond:{fields:{ends:[{type:`wref`,description:`Endpoints of the relationship`}]},description:`A symmetric relationship between two things`},Pair:{fields:{first:{type:`wref`,description:`First member of the pair`},second:{type:`wref`,description:`Second member of the pair`}},composes:[`Collection`],description:`An ordered pair of two things`},Set:{fields:{members:[{type:`wref`,description:`Members of the set`}]},description:`An unordered set of things`},List:{fields:{items:[{type:`wref`,description:`Items in the list`}]},description:`An ordered list of things`}},Rn={Collection:{fields:{}},Arc:{fields:{from:{type:`wref`,binding:`either`},to:{type:`wref`,binding:`either`}},composes:[`Collection`]},Bond:{fields:{ends:{type:`array`,items:{type:`wref`,binding:`either`},minItems:2,maxItems:2}},composes:[`Collection`]},Set:{fields:{members:{type:`array`,items:{type:`wref`,binding:`either`},minItems:1}},composes:[`Collection`]},List:{fields:{items:{type:`array`,items:{type:`wref`,binding:`either`},minItems:1}},composes:[`Collection`]}},zn={Content:{fields:{content:{type:`string`,description:`Markdown content`}},description:`Built-in content shape (Readme / Agents / LlmsTxt well-known names)`}},Bn={View:{fields:{dialect:{type:`string`,description:`Query dialect stamp (warmquery/v1)`},query:{}},description:`A named, shareable WarmQuery definition bound to durable IDs`}},Vn={LicenseSubject:{fields:{scope:{type:`string`,description:`What portion of the repository is being licensed`},"note?":{type:`string`,description:`Optional clarification of the licensed scope`}},description:`A licensable body of work in this repository`},LicenseDeclaration:{fields:{"licenseWref?":{type:`wref`,description:`Canonical license reference when one license applies`},spdxIdRaw:{type:`string`,description:`Declared SPDX identifier or raw license value`},"spdxExpression?":{type:`string`,description:`Full SPDX expression for compound declarations`},"appliesTo?":{type:`string`,description:`Kind of work covered by the declaration`},"attributionText?":{type:`string`,description:`Attribution text reusers should preserve`},"declaredBy?":{type:`string`,description:`Person or organization making the declaration`},"sourceUrl?":{type:`string`,description:`Upstream source for the licensing terms`},"note?":{type:`string`,description:`Optional declaration caveats or clarification`}},composes:[`Assertion`],description:`Declares the license of a LicenseSubject`}};({...Ln,...zn,...Bn,...Vn});const Hn=`X-WarmHub-Client-Flags`,Un=`graph-wire`,Wn=/^[a-z0-9-]+$/,Gn=/* @__PURE__ */ new Set;function Kn(e){return Wn.test(e)}const qn=/(?:^|,)\s*graph-wire\s*(?:,|$)/,Jn=/* @__PURE__ */ new Set([Un]);function Yn(e){if(!e)return Gn;if(e.length>256){if(!qn.test(e))return Gn;if(e.length>267)return Jn}let t=/* @__PURE__ */ new Set;for(let n of e.split(`,`)){let e=n.trim();e&&Wn.test(e)&&t.add(e)}return t}function Xn(e){return[...new Set(e)].sort().join(`,`)}const Zn=/* @__PURE__ */ new Set([`auth.sync`,`commit.validate`,`live.issueTicket`]);function Qn(e,t){return`${e}/${t}`}const $n=1e4,er=[`add`,`revise`,`retract`,`reaffirm`,`rename`,`redact`,`remove`,`restore`,`rewrite`],tr=[`shape`,`thing`,`assertion`,`collection`];function nr(e){let t=_e(e);return t?{shapePrefix:t.shapeName,bareName:t.bareName}:null}const rr=`X-WarmHub-Install-Repo`,ir=`X-WarmHub-Signature`,ar=`X-WarmHub-Timestamp`,or=/^[A-Za-z0-9\-._~]$/;function sr(e){let t=``,n=new TextEncoder().encode(e);for(let e of n){let n=String.fromCharCode(e);or.test(n)?t+=n:t+=`%${e.toString(16).toUpperCase().padStart(2,`0`)}`}return t}function cr(e){return typeof e==`boolean`?e?`true`:`false`:typeof e==`number`?JSON.stringify(e):e}function lr(e){return e===`POST`||e===`PUT`||e===`PATCH`}function ur(e){let t=[];for(let[n,r]of Object.entries(e))r!=null&&t.push([n,cr(r)]);return t.sort(([e],[t])=>e<t?-1:+(e>t)),t.map(([e,t])=>`${sr(e)}=${sr(t)}`).join(`&`)}function dr(e){let t=``;for(let n of e)t+=n.toString(16).padStart(2,`0`);return t}async function fr(e){let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e));return dr(new Uint8Array(t))}function pr(e){return[e.method,e.path,e.canonicalQuery,e.installRepo,e.bodyHash,String(e.timestamp)].join(`
29
29
  `)}async function mr(e,t){let n=new TextEncoder,r=await crypto.subtle.importKey(`raw`,n.encode(e),{name:`HMAC`,hash:`SHA-256`},!1,[`sign`]),i=await crypto.subtle.sign(`HMAC`,r,n.encode(t));return dr(new Uint8Array(i))}const hr=/^sha256=([0-9a-f]{64})$/;async function gr(e){let t=hr.exec(e.signature);if(!t)return{ok:!1,reason:`invalid-format`};let n=t[1],r=e.toleranceSec??300;if(Math.abs(e.nowUnixSeconds-e.timestamp)>r)return{ok:!1,reason:`expired`};let i=e.body.length===0?`e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855`:await fr(e.body),a=pr({method:e.method,path:e.path,canonicalQuery:ur(e.query),installRepo:e.installRepo,bodyHash:i,timestamp:e.timestamp});return _r(n,await mr(e.secret,a))?{ok:!0}:{ok:!1,reason:`invalid-signature`}}function _r(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e.charCodeAt(r)^t.charCodeAt(r);return n===0}const vr=[`org.service_account_created`,`org.service_account_role_changed`,`org.service_account_disabled`,`org.service_account_enabled`,`org.service_account_deleted`];[...vr];const yr=[`commit`,`repo.renamed`,`org.renamed`,`org.member_added`,`org.repo_created`,`org.repo_published`,...vr,`thing.renamed`,`shape.renamed`];function br(e){return yr.includes(e)}[...vr];const xr=[`ready`,`degraded`];function Sr(e){return xr.includes(e)}const Cr=[`repo:read`,`repo:checkpoint-read`,`repo:checkpoint-generate`,`repo:write`,`repo:configure`,`repo:admin`,`repo:action-callback`];function wr(e){return Cr.includes(e)}const Tr=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;function Er(e){return Tr.test(e)?e:null}function Dr(e){let t=Tr.exec(e);return{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),prerelease:t[4]?t[4].split(`.`):[]}}const Or=/^(0|[1-9]\d*)$/;function kr(e,t){if(e.length===0&&t.length===0)return 0;if(e.length===0)return 1;if(t.length===0)return-1;let n=Math.min(e.length,t.length);for(let r=0;r<n;r++){let n=e[r],i=t[r];if(n===void 0||i===void 0)break;if(n===i)continue;let a=Or.test(n),o=Or.test(i);return a&&o?Number(n)<Number(i)?-1:1:a?-1:o?1:n<i?-1:1}return e.length===t.length?0:e.length<t.length?-1:1}function Ar(e,t){let n=Dr(e),r=Dr(t);return n.major===r.major?n.minor===r.minor?n.patch===r.patch?kr(n.prerelease,r.prerelease):n.patch<r.patch?-1:1:n.minor<r.minor?-1:1:n.major<r.major?-1:1}const jr=`com.warmhub.system`,Mr={componentId:`string`,name:`string`,version:`string`,source:`string`,"sourceKind?":`string`,"sourceRef?":`string`,"resolvedSha?":`string`,"registeredComponentRef?":`string`,manifestHash:`string`,state:`string`,manifest:`string`,installedAt:`string`,installedByUserId:`string?`,"installId?":`string`,"updatedAt?":`string`},Nr={},Pr={about:`wref`},Fr={correctionLog:{type:`array`,items:{reason:`string`},minItems:1}},Ir={},Lr={},Rr=[{name:`ComponentInstall`,fields:Mr,installInfra:!0},{name:`ComponentConfig`,fields:Nr,installInfra:!0},{name:`Collection`,...Rn.Collection},{name:`Arc`,...Rn.Arc},{name:`Bond`,...Rn.Bond},{name:`Set`,...Rn.Set},{name:`List`,...Rn.List},{name:`Assertion`,fields:Pr,priorVersions:[{fields:{}}]},{name:`CorrectedThing`,fields:Fr,onDemand:!0},{name:`RedactedThing`,fields:Ir,onDemand:!0,systemOnlyCertification:!0},{name:`File`,fields:Lr,onDemand:!0}],zr={component:{id:jr,name:`system`,version:`1.0.0`},shapes:Rr.map(({name:e,fields:t,composes:n})=>({name:e,fields:t,...n?{composes:n}:{}})),credentials:[],subscriptions:[],seeds:[],health:{requires:{shapes:Rr.map(e=>e.name)}},teardown:{},runtimeAccess:{reads:[],writes:[]}};new Set(zr.shapes.map(e=>e.name));const Br={componentId:jr,name:zr.component.name,version:zr.component.version,manifest:zr,shapes:Rr},Vr=[Br];Br.shapes.filter(e=>e.installInfra!==!0).filter(e=>e.onDemand!==!0),new Set(Vr.flatMap(e=>e.shapes.filter(e=>e.installInfra===!0).map(e=>e.name)));const Hr=new Set(zr.shapes.map(e=>e.name));new Set(Br.shapes.filter(e=>e.systemOnlyCertification===!0).map(e=>e.name));function Ur(e){return Hr.has(e)}const Wr=[`initiated`,`active`,`uninstalled`];function Gr(e){return Wr.includes(e)}const Kr=/* @__PURE__ */ new Set([8203,8204,8205,8288,8294,8295,8296,8297,8234,8235,8236,8237,8238,8232,8233]);function qr(e){return e<=31||e===127||e>=128&&e<=159}function Jr(e){return e<=65535?`\\u${e.toString(16).padStart(4,`0`)}`:`\\u{${e.toString(16)}}`}function Yr(e){for(let t of e){let e=t.codePointAt(0);if(e!==void 0&&(qr(e)||Kr.has(e)||e===34))return!0}return!1}function Xr(e){return e.length<=120?e:`${e.slice(0,120)}...<truncated>`}function Zr(e){if(!Yr(e))return e;let t=JSON.stringify(e).slice(1,-1),n=``;for(let e of t){let t=e.codePointAt(0);t!==void 0&&(n+=qr(t)||Kr.has(t)?Jr(t):e)}return n}function U(e){return Xr(Zr(e))}function Qr(e){return Zr(e)}function $r(e){if(e.length===0)return{unsafe:!0,reason:`empty field name`};if(e!==e.trim())return{unsafe:!0,reason:`leading or trailing whitespace`};for(let t of e){let e=t.codePointAt(0);if(e!==void 0){if(qr(e))return{unsafe:!0,reason:`control character (U+${e.toString(16).padStart(4,`0`).toUpperCase()})`};if(Kr.has(e))return{unsafe:!0,reason:`format or separator character (U+${e.toString(16).padStart(4,`0`).toUpperCase()})`}}}return{unsafe:!1}}function ei(e){return e.endsWith(`?`)?e.slice(0,-1):e}function ti(...e){return ri(U,e)}function ni(...e){return ri(Qr,e)}function ri(e,t){return t.map(t=>typeof t==`number`?`[${t}]`:e(t)).join(`.`).replace(/\.\[/g,`[`)}function ii(e,t){let{childContext:n,onStringValue:r,onObjectKey:i}=t,a=[{value:e,context:t.rootContext}];for(;a.length>0;){let{value:e,context:t}=a.pop();if(typeof e==`string`){r(e,t);continue}if(Array.isArray(e)){for(let r=e.length-1;r>=0;r--)a.push({value:e[r],context:n(t,r)});continue}if(!B(e))continue;let o=Object.entries(e).map(([e,r])=>[e,n(t,e),r]);if(i)for(let[e,t]of o)i(e,t);for(let e=o.length-1;e>=0;e--){let t=o[e];t&&a.push({value:t[2],context:t[1]})}}}const ai=[`org`,`repo`];function oi(e){return ai.includes(e)}const si=[`repo`,`component`];function ci(e){return si.includes(e)}const li=[`repo`,`component`,`skill`];function ui(e){return li.includes(e)}const di=[`org:read`,`org:configure`,`org:admin`,`org:action-callback`,`org:hub-curate`];function fi(e){return di.includes(e)}const pi=/^[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}$/;function mi(e){if(!pi.test(e))throw Error(`Operation-event submission ID must be a canonical UUID`);let t=e.toLowerCase().replaceAll(`-`,``);return Uint8Array.from({length:16},(e,n)=>Number.parseInt(t.slice(n*2,n*2+2),16))}function hi(e,t){return(e<<t|e>>>32-t)>>>0}function gi(e){let t=e.length*8,n=Math.ceil((e.length+9)/64)*64,r=new Uint8Array(n);r.set(e),r[e.length]=128;let i=new DataView(r.buffer);i.setUint32(n-8,Math.floor(t/4294967296)),i.setUint32(n-4,t>>>0);let a=1732584193,o=4023233417,s=2562383102,c=271733878,l=3285377520,u=/* @__PURE__ */ new Uint32Array(80);for(let e=0;e<n;e+=64){for(let t=0;t<16;t+=1)u[t]=i.getUint32(e+t*4);for(let e=16;e<80;e+=1)u[e]=hi((u[e-3]??0)^(u[e-8]??0)^(u[e-14]??0)^(u[e-16]??0),1);let t=a,n=o,r=s,d=c,f=l;for(let e=0;e<80;e+=1){let i,a;e<20?(i=n&r|~n&d,a=1518500249):e<40?(i=n^r^d,a=1859775393):e<60?(i=n&r|n&d|r&d,a=2400959708):(i=n^r^d,a=3395469782);let o=hi(t,5)+i+f+a+(u[e]??0)>>>0;f=d,d=r,r=hi(n,30),n=t,t=o}a=a+t>>>0,o=o+n>>>0,s=s+r>>>0,c=c+d>>>0,l=l+f>>>0}let d=/* @__PURE__ */ new Uint8Array(20),f=new DataView(d.buffer);for(let[e,t]of[a,o,s,c,l].entries())f.setUint32(e*4,t);return d}function _i(e){let t=Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``).slice(0,32);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function vi(e,t){if(!Number.isInteger(t)||t<0||t>2147483647)throw Error(`Stream chunk ordinal must be an integer from 0 through 2147483647`);mi(e);let n=e.toLowerCase(),r=mi(`003e7e6c-2f1e-53ea-9dfa-627edd04a8cc`),i=new TextEncoder().encode(`${n}:${t}`),a=gi(Uint8Array.from([...r,...i])).slice(0,16);return a[6]=(a[6]??0)&15|80,a[8]=(a[8]??0)&63|128,_i(a)}const yi=d.object({fieldPath:d.string(),wref:d.string(),reason:d.string()}),bi=d.object({fieldPath:d.string(),wref:d.string(),binding:d.literal(`identity`)}),xi=d.object({shape:d.string(),message:d.string(),removalMilestone:d.string()}),Si=d.object({undeclaredFields:d.array(d.string()).optional(),undeclaredFieldsTruncated:d.literal(!0).optional(),totalUndeclared:d.number().int().nonnegative().optional(),coalescedWrefs:d.array(yi).optional(),coalescedWrefsTruncated:d.literal(!0).optional(),totalCoalescedWrefs:d.number().int().nonnegative().optional(),deprecations:d.array(xi).optional(),ignoredVersionPins:d.array(bi).optional(),shapeless:d.literal(!0).optional()}),Ci=[`active`,`pending`];function wi(e){return Ci.includes(e)}const Ti=[`owner`,`admin`,`editor`,`viewer`];function Ei(e){return Ti.includes(e)}const Di=[`set`,`list`],Oi=[`add`,`revise`];function ki(e){return`Collection "type" is invalid. Use one of: ${Di.join(`, `)}. Got: "${e}".`}function Ai(e){return Di.find(t=>t===e)??null}function ji(e){return e==null?``:typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?String(e):Array.isArray(e)?`array`:typeof e}function Mi(e){return Oi.find(t=>t===e)??null}function Ni(e,t){let n=[];return n.push(...Pi(e,t)),n.push(...Ri(e,t)),n.push(...Ui(e,t)),n.push(...Wi(e,t)),n.push(...Ki(e,t)),n.push(...qi(e,t)),n.push(...Ji(e,t)),n}function Pi(e,t){let n=[],r=zi(e)&&e.name?be(e.name):void 0,i=e.operation===`rename`&&zi(e),a=e.operation===`restore`&&e.newName!==void 0&&v(e.newName),o=i||a,s=o&&e.newName?be(e.newName):void 0,c=e.operation===`add`?`created`:e.operation===`rename`?`renamed`:e.operation===`restore`?`restored`:`revised`,l=i&&r!==void 0&&Fn(r)&&s!==void 0&&!wn(s)&&!In(s);if(r&&xn(r)&&!l&&n.push({code:`RESERVED_NAME`,operationIndex:t,message:`Shape "${r}" is a retired collection shape and cannot be written manually`}),s&&xn(s))n.push({code:`RESERVED_NAME`,operationIndex:t,message:`Shape "${s}" is a retired collection shape and cannot be written manually`});else{let i=r&&(In(r)||Cn(r))&&!l?r:s&&(In(s)||Cn(s))?s:void 0;i&&(o||e.operation===`add`||e.operation===`revise`)&&n.push({code:`RESERVED_NAME`,operationIndex:t,message:`Shape "${i}" is a built-in shape and cannot be ${c} manually`})}let u=e.operation===`add`?r:o?s:void 0;u&&Ur(u)&&!In(u)&&!Cn(u)&&n.push({code:`RESERVED_NAME`,operationIndex:t,message:`Shape "${u}" is a system shape and cannot be ${c} manually`});let d=Vi(e)?.shapes.find(xn);e.operation===`add`&&d!==void 0&&n.push({code:`VALIDATION_ERROR`,operationIndex:t,message:`Cannot add under retired collection shape "${d}". Triple is read-only and retired for new collection writes.`});let f=Bi(e);if(f&&xn(f.shapePrefix))n.push({code:`VALIDATION_ERROR`,operationIndex:t,message:`Cannot add under retired collection shape "${f.shapePrefix}". Triple is read-only and retired for new collection writes.`});else if(e.kind===`thing`&&f&&(bn(f.shapePrefix)&&!Sn(f.shapePrefix)||f.shapePrefix===`Collection`)){let e=f.shapePrefix===`Collection`,r=e?`Collection is abstract: name the Thing and state a concrete collection Shape (Arc, Bond, Set, List or Pair) instead`:`Name the Thing and state the Shape instead`,i=e?`Set`:f.shapePrefix;n.push({code:`VALIDATION_ERROR`,operationIndex:t,message:`Cannot add kind="thing" under built-in shape "${f.shapePrefix}". ${r}: {"operation":"add","name":"${f.bareName}","shapes":["${i}"],"data":{…}}`})}return n}function Fi(e){return`Cannot add a Thing that declares the abstract built-in shape "Collection". State a concrete collection Shape (Arc, Bond, Set, List or Pair) instead: {"operation":"add","name":"${e}","shapes":["Set"],"data":{…}}`}function Ii(e){return`Content "${e}" is synthesized; writes are not allowed`}function Li(e){return`Content "${e}" is not a recognized well-known content name`}function Ri(e,t){return Vi(e)?.shapes.includes(`Collection`)?[{code:`VALIDATION_ERROR`,operationIndex:t,message:Fi(e.name??``)}]:[]}function zi(e){return e.kind===`shape`||e.operation!==`add`&&e.name!==void 0&&v(e.name)}function Bi(e){return e.operation!==`add`||!e.name||zi(e)||e.kind===`collection`||e.declaredShapes!==void 0?null:nr(e.name)}function Vi(e){return e.declaredShapes===void 0||!e.name||zi(e)||e.operation!==`add`&&e.operation!==`revise`?null:{shapes:e.declaredShapes.map(e=>be(e.replace(/@.*$/,``))),name:e.name}}function Hi(e,t){return{code:`RESERVED_NAME`,operationIndex:t,message:ge(e)}}function Ui(e,t){if(zi(e)){let n=e.operation===`add`?e.name:e.operation===`rename`?e.newName:void 0;return n!==void 0&&he(be(n))?[Hi(n,t)]:[]}if(e.operation===`add`&&e.name){let n=e.kind===`collection`||e.declaredShapes!==void 0?e.name:Bi(e)?.bareName;return n!==void 0&&me(n)?[Hi(n,t)]:[]}return e.operation===`rename`&&e.newName!==void 0&&me(e.newName)||e.operation===`restore`&&e.newName!==void 0&&(v(e.newName)?he(be(e.newName)):me(e.newName))?[Hi(e.newName,t)]:[]}function Wi(e,t){if(e.kind!==`thing`)return[];let n=Vi(e);if(n)return Gi(n,t);let r=Bi(e);if(!r||!On(r.shapePrefix))return[];let i=r.bareName;return An(i)?[{code:`READ_ONLY_BUILTIN_CONTENT`,operationIndex:t,message:`${r.shapePrefix} "${i}" is synthesized; writes are not allowed`}]:kn(i)?[]:[{code:`UNKNOWN_CONTENT_NAME`,operationIndex:t,message:`${r.shapePrefix} "${i}" is not a recognized well-known content name`}]}function Gi({shapes:e,name:t},n){return e.some(On)?An(t)?[{code:`READ_ONLY_BUILTIN_CONTENT`,operationIndex:n,message:Ii(t)}]:kn(t)?[]:[{code:`UNKNOWN_CONTENT_NAME`,operationIndex:n,message:Li(t)}]:[]}function Ki(e,t){let n=[],r=e.name;if(e.newName?.includes(`+`))return n.push({code:`VALIDATION_ERROR`,operationIndex:t,message:`Name "${e.newName}" contains reserved character "+". The "+" character is reserved for the historical collection auto-name namespace and is not allowed in user-supplied names.`}),n;if(r?.includes(`+`)){if(e.kind===`collection`&&e.operation===`add`)return n.push({code:`VALIDATION_ERROR`,operationIndex:t,message:`Name "${r}" contains reserved character "+". The "+" character is reserved for the historical collection auto-name namespace and is not allowed in user-supplied names.`}),n;if(e.kind===`collection`||e.operation!==`add`)return n;let i=Bi(e);if(i&&wn(i.shapePrefix)||Vi(e)?.shapes.some(wn))return n;n.push({code:`VALIDATION_ERROR`,operationIndex:t,message:`Name "${r}" contains reserved character "+". The "+" character is reserved for the historical collection auto-name namespace and is not allowed in user-supplied names.`})}return n}function qi(e,t){let n=[];return!e.about||typeof e.about==`string`||n.push({code:`VALIDATION_ERROR`,operationIndex:t,message:`about accepts a wref. Create the collection as its own named operation, then point the assertion at it. Prefer deterministic relationship names, for example: [{"operation":"add","name":"a-to-b","shapes":["Arc"],"data":{"from":"a","to":"b"}},{"operation":"add","name":"example","shapes":["Assertion"],"data":{"about":"a-to-b"}}]. For CLI usage, use wh commit submit --file with the two operations.`}),n}function Ji(e,t){let n=[];if(e.kind!==`collection`||Mi(e.operation)===null)return n;let r=Ai(e.type);e.operation===`add`&&!e.name&&n.push({code:`VALIDATION_ERROR`,operationIndex:t,message:`Collection create requires a name. Collections are ordinary named things (ADR 0004).`}),r===null&&n.push({code:`VALIDATION_ERROR`,operationIndex:t,message:ki(ji(e.type))});let i=Array.isArray(e.members)?e.members:null;if(i===null)n.push({code:`VALIDATION_ERROR`,operationIndex:t,message:`Collection requires a "members" array`});else for(let e=0;e<i.length;e++)typeof i[e]!=`string`&&n.push({code:`VALIDATION_ERROR`,operationIndex:t,message:`Collection member at index ${e} must be a string`});if(r!==null&&i!==null){let e=Yi(r,i);e&&n.push({code:`VALIDATION_ERROR`,operationIndex:t,message:e})}return n}function Yi(e,t){switch(e){case`set`:case`list`:return t.length<1?`${e===`set`?`Set`:`List`} requires at least 1 member, got 0`:null;default:return e}}function Xi(e,t){return Ni(e,t)}const Zi=[5,6],Qi=d.string().regex(/^[0-9a-f]{64}$/),$i=d.number().int().nonnegative(),ea=d.number().int().positive(),ta=[`shape`,`thing`],na=[`heads`,`ops`],ra=d.string().regex(/^[^\r\n]+@v[1-9]\d*(?![\s\S])/,`Shape certificate must be a pinned wref`),ia=d.object({wref:d.string().min(1),v:ea.optional(),durableId:d.string().min(1)}).strict();function aa(e,n,r,i){let a;e.forEach((e,o)=>{let s=n(e);a!==void 0&&t(a,s)>=0&&i.addIssue({code:`custom`,path:[o],message:r}),a=s})}const oa=d.array(ra).superRefine((e,t)=>{aa(e.slice(1),e=>e,`Shape certificates after the first must be unique and strictly increasing`,t);let n=e[0];n!==void 0&&e.indexOf(n,1)!==-1&&t.addIssue({code:`custom`,path:[e.indexOf(n,1)],message:`The first Shape certificate must not repeat in the tail`})}),sa=d.array(ia).superRefine((e,t)=>{aa(e,e=>e.wref,`Affirmed references must be unique and strictly increasing`,t)}),ca=d.array(d.object({shape:d.string().min(1),memberCount:d.number().int().nonnegative()}).strict()).min(1),la={wref:d.string().min(1),durableId:d.string().min(1),version:ea};function ua(e){let t={...la,active:d.literal(!0),data:e};return d.discriminatedUnion(`kind`,[d.object({...t,kind:d.literal(`shape`),shapes:d.array(ra).max(0),retracted:d.literal(!0).optional()}).strict(),d.object({...t,kind:d.literal(`thing`),shapes:oa,collections:ca.optional(),about:ia.optional(),affirmed:sa.optional()}).strict().refine(e=>e.about===void 0==(e.affirmed===void 0),{message:"An export row carries `about` and `affirmed` together or not at all",path:[`affirmed`]})])}function da(e){return fa(e)&&pa(e)}function fa(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&Object.getOwnPropertySymbols(e).length===0}function pa(e){if(e===null)return!0;let t=typeof e;if(t===`string`||t===`boolean`)return!0;if(t===`number`){let t=e;return Number.isFinite(t)&&(!Number.isInteger(t)||Number.isSafeInteger(t))}if(Array.isArray(e)){for(let t of e)if(!pa(t))return!1;return!0}if(!fa(e))return!1;for(let t of Object.keys(e))if(t===`__proto__`||!pa(e[t]))return!1;return!0}const ma=ua(d.record(d.string(),n)),ha=d.object({...la,kind:d.enum(ta),active:d.literal(!1)}).strict(),ga=d.union([ma,ha]);d.union([ua(d.custom(da)),ha]);const _a=d.object({kind:d.literal(`header`),formatVersion:d.literal(Zi),repo:d.string().regex(/^[^/\s]+\/[^/\s]+$/,`repo must be "<org>/<graph>"`),mode:d.enum(na),sinceRepoSeq:$i,atRepoSeq:$i}).strict().refine(e=>e.atRepoSeq>=e.sinceRepoSeq,`atRepoSeq must not precede sinceRepoSeq`),va=d.object({kind:d.literal(`trailer`),recordCount:$i,contentSha256:Qi,atRepoSeq:$i}).strict();function ya(e,n,r){let i=t(e.durableId,n.durableId);return i===0?r>=6&&e.kind===`shape`&&n.kind===`shape`&&e.version<n.version:i<0}function ba(e){return e.sinceRepoSeq>0}function xa(t){return e(t,ga,`Graph export row`)}function Sa(t){return e(t,_a,`Graph export header`)}function Ca(t){return e(t,va,`Graph export trailer`)}const wa=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ta=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);function W(e,t){return(e>>>t|e<<32-t)>>>0}var Ea=class{#e=Uint32Array.from(Ta);#t=/* @__PURE__ */ new Uint32Array(64);#n=/* @__PURE__ */ new Uint8Array(64);#r=0;#i=0;#a=!1;update(e){if(this.#a)throw Error(`SHA-256 hasher is already finalized`);if(this.#i+=e.length,!Number.isSafeInteger(this.#i))throw RangeError(`SHA-256 input length must be a safe integer`);let t=0;if(this.#r>0){let n=Math.min(64-this.#r,e.length);if(this.#n.set(e.subarray(0,n),this.#r),this.#r+=n,t=n,this.#r<64)return;this.#o(this.#n,0),this.#r=0}for(;t+64<=e.length;)this.#o(e,t),t+=64;t<e.length&&(this.#n.set(e.subarray(t),0),this.#r=e.length-t)}digestHex(){if(this.#a)throw Error(`SHA-256 hasher is already finalized`);this.#a=!0;let e=new Uint8Array(this.#r<56?64:128);e.set(this.#n.subarray(0,this.#r),0),e[this.#r]=128;let t=new DataView(e.buffer);t.setUint32(e.length-8,Math.floor(this.#i/536870912)),t.setUint32(e.length-4,this.#i<<3>>>0);for(let t=0;t<e.length;t+=64)this.#o(e,t);return Array.from(this.#e,e=>e.toString(16).padStart(8,`0`)).join(``)}#o(e,t){let n=this.#t;for(let r=0;r<16;r+=1){let i=t+r*4;n[r]=(e[i]<<24|e[i+1]<<16|e[i+2]<<8|e[i+3])>>>0}for(let e=16;e<64;e+=1){let t=n[e-15],r=n[e-2],i=(W(t,7)^W(t,18)^t>>>3)>>>0,a=(W(r,17)^W(r,19)^r>>>10)>>>0;n[e]=n[e-16]+i+n[e-7]+a>>>0}let r=this.#e,i=r[0],a=r[1],o=r[2],s=r[3],c=r[4],l=r[5],u=r[6],d=r[7];for(let e=0;e<64;e+=1){let t=(W(c,6)^W(c,11)^W(c,25))>>>0,r=(c&l^~c&u)>>>0,f=d+t+r+wa[e]+n[e]>>>0,p=((W(i,2)^W(i,13)^W(i,22))>>>0)+((i&a^i&o^a&o)>>>0)>>>0;d=u,u=l,l=c,c=s+f>>>0,s=o,o=a,a=i,i=f+p>>>0}r[0]=i+r[0]>>>0,r[1]=a+r[1]>>>0,r[2]=o+r[2]>>>0,r[3]=s+r[3]>>>0,r[4]=c+r[4]>>>0,r[5]=l+r[5]>>>0,r[6]=u+r[6]>>>0,r[7]=d+r[7]>>>0}},Da=class{#e=new Ea;#t=0;get rowCount(){return this.#t}update(e){this.#e.update(e),this.#t+=1}finalize(){return this.#e.digestHex()}};function Oa(){return new Da}function ka(e){return(e.endsWith(`?`)?e.slice(0,-1):e).toLowerCase()}function Aa(e){return e.split(`.`).map(e=>ka(e)).join(`.`)}function ja(e,t,n,r){let i=Ma(t);if(typeof e==`string`){if(i.length>0)return;sn(r??`<value>`,e,n);return}if(Array.isArray(e)){let t=i.filter(Fa);if(i.length>0&&t.length===0)return;let a=Na(t.map(Pa));for(let t=0;t<e.length;t++)ja(e[t],a,n,`${r??`<value>`}[${t}]`);return}if(!B(e))return;let a=Na(i.map(Ia));if(!(i.length>0&&a.length===0))for(let[t,i]of Object.entries(e)){let e=r?ti(r,t):U(t);sn(e,t,n),ja(i,Na(a.map(e=>e.get(t))),n,e)}}function Ma(e){return Na(e.map(e=>H(e).spec))}function Na(e){return e.filter(e=>e!==void 0)}function Pa(e){if(Array.isArray(e))return e[0];if(V(e)&&e.type===`array`)return e.items}function Fa(e){return e===`array`||Array.isArray(e)?!0:V(e)&&e.type===`array`}function Ia(e){if(!B(e)||V(e))return;let t=/* @__PURE__ */ new Map;for(let[n,r]of Object.entries(e))t.set(n.endsWith(`?`)?n.slice(0,-1):n,r);return t}function La(e,t){return e.allowUnsafeFieldNamePaths.has(t)}function Ra(e){return!(!B(e)||Array.isArray(e)||V(e)||`type`in e&&typeof e.type==`string`&&z.has(e.type)&&Object.keys(e).every(e=>Zt.has(e)))}function za(e,t,n,r,i=t){let a=/* @__PURE__ */ new Map;for(let[o,s]of Object.entries(e)){let e=$r(ei(o)),c=ti(t,o),l=ni(i,o);if(e.unsafe&&!La(r,l)){n.push(`Invalid field name at "${c}": ${e.reason}`);continue}let u=ka(o),d=a.get(u);d===void 0?(a.set(u,o),Ra(s)?za(s,c,n,r,l):Ba(c,l,s,n,r)):n.push(`${c}: duplicate field name. Shape already declares "${U(d)}" (case-insensitive match).`)}}function Ba(e,t,n,r,i){if(typeof n==`string`)z.has(n)||r.push(`Invalid type at "${e}": "${U(n)}" (expected number|string|boolean|wref|array, optionally with ? suffix)`);else if(Array.isArray(n)){if(n.length!==1){r.push(`Invalid array type at "${e}": array type spec must have exactly 1 element`);return}Ba(`${e}[]`,`${t}[]`,n[0],r,i)}else if(B(n)){let a=Wt(e,n);if(a){r.push(a);return}if(V(n)){Va(e,t,n,r,i);return}if(`type`in n&&typeof n.type==`string`&&z.has(n.type)&&Object.keys(n).every(e=>Zt.has(e))){let t=n.type.endsWith(`?`)?n.type.slice(0,-1):n.type,i=t===`string`?Kt:t===`number`?qt:t===`wref`?Jt:t===`array`?Yt:/* @__PURE__ */ new Set,a=Object.keys(n).filter(e=>e!==`type`&&e!==`description`&&!i.has(e));if(a.length>0&&a.some(e=>{let t=n[e];return typeof t!=`string`&&!Array.isArray(t)&&!B(t)})){for(let n of a)r.push(`Constraint "${U(n)}" at "${e}" is not valid for type "${t}"`);return}if(a.length===0){let t=[];for(let[r,a]of Object.entries(n))r!==`type`&&r!==`description`&&i.has(r)&&((r===`minLength`||r===`maxLength`||r===`minimum`||r===`maximum`||r===`minItems`||r===`maxItems`)&&typeof a!=`number`?t.push(`Constraint "${r}" at "${e}" must be a number, got ${typeof a}`):r===`integer`&&typeof a!=`boolean`?t.push(`Constraint "${r}" at "${e}" must be a boolean, got ${typeof a}`):r===`pattern`&&typeof a!=`string`?t.push(`Constraint "${r}" at "${e}" must be a string, got ${typeof a}`):r===`enum`&&!Array.isArray(a)?t.push(`Constraint "${r}" at "${e}" must be an array, got ${typeof a}`):r===`shape`&&typeof a!=`string`&&t.push(`Constraint "${r}" at "${e}" must be a string, got ${typeof a}`));if(t.length>0){r.push(...t);return}}if(Object.entries(n).some(([e,t])=>!(e===`type`||e===`description`||typeof t==`string`||Array.isArray(t)||B(t)))){r.push(`Object at "${e}" looks like a typed field object (type: "${U(String(n.type))}") but has constraint values with invalid types. Check that constraint values match their expected types (e.g., minLength must be a number, not a string).`);return}}za(n,e,r,i,t)}else r.push(`Invalid type at "${e}": expected string, array, or object, got ${typeof n}`)}function Va(e,t,n,r,i){let a=n.type;if(typeof a!=`string`){r.push(`Invalid typed field object at "${e}": "type" must be a string`);return}if(!z.has(a)){r.push(`Invalid type at "${e}.type": "${U(a)}" (expected number|string|boolean|wref|array, optionally with ? suffix)`);return}`description`in n&&typeof n.description!=`string`&&r.push(`Invalid typed field object at "${e}": "description" must be a string`);let o=a.endsWith(`?`)?a.slice(0,-1):a;for(let t of Object.keys(n)){if(t===`type`||t===`description`)continue;let n=U(t);o===`string`?Kt.has(t)||r.push(`Constraint "${n}" at "${e}" is not valid for type "string"`):o===`number`?qt.has(t)||r.push(`Constraint "${n}" at "${e}" is not valid for type "number"`):o===`wref`?Jt.has(t)||r.push(`Constraint "${n}" at "${e}" is not valid for type "wref"`):o===`array`?Yt.has(t)||r.push(`Constraint "${n}" at "${e}" is not valid for type "array"`):r.push(`Constraint "${n}" at "${e}" is not valid for type "${o}"`)}if(`minLength`in n&&(typeof n.minLength!=`number`||!Number.isFinite(n.minLength)||n.minLength<0||!Number.isInteger(n.minLength))&&r.push(`"minLength" at "${e}" must be a non-negative finite integer`),`maxLength`in n&&(typeof n.maxLength!=`number`||!Number.isFinite(n.maxLength)||n.maxLength<0||!Number.isInteger(n.maxLength))&&r.push(`"maxLength" at "${e}" must be a non-negative finite integer`),`minLength`in n&&`maxLength`in n&&typeof n.minLength==`number`&&typeof n.maxLength==`number`&&n.minLength>n.maxLength&&r.push(`"minLength" at "${e}" cannot exceed "maxLength"`),o===`string`&&typeof n.minLength==`number`&&Number.isFinite(n.minLength)&&Number.isInteger(n.minLength)&&n.minLength>65536&&r.push(`"minLength" at "${e}" cannot exceed ${tn}`),o===`string`&&typeof n.maxLength==`number`&&Number.isFinite(n.maxLength)&&Number.isInteger(n.maxLength)&&n.maxLength>65536&&r.push(`"maxLength" at "${e}" cannot exceed ${tn}`),`pattern`in n&&typeof n.pattern!=`string`&&r.push(`"pattern" at "${e}" must be a string`),`pattern`in n&&typeof n.pattern==`string`){if(cn(n.pattern))r.push(`"pattern" at "${e}" is not a valid regular expression`);else{let t=dn(n.pattern);t&&r.push(`"pattern" at "${e}" ${t}`)}}if(`enum`in n){if(!Array.isArray(n.enum)||n.enum.length===0||!n.enum.every(e=>typeof e==`string`))r.push(`"enum" at "${e}" must be a non-empty array of strings`);else if(o===`string`)for(let t of n.enum){let n=an(t);if(n>65536){r.push(`"enum" value at "${e}" is ${n} bytes; string enum values cannot exceed ${tn} bytes`);break}}}`minimum`in n&&(typeof n.minimum!=`number`||!Number.isFinite(n.minimum))&&r.push(`"minimum" at "${e}" must be a finite number`),`maximum`in n&&(typeof n.maximum!=`number`||!Number.isFinite(n.maximum))&&r.push(`"maximum" at "${e}" must be a finite number`),`minimum`in n&&`maximum`in n&&typeof n.minimum==`number`&&typeof n.maximum==`number`&&n.minimum>n.maximum&&r.push(`"minimum" at "${e}" cannot exceed "maximum"`),`integer`in n&&typeof n.integer!=`boolean`&&r.push(`"integer" at "${e}" must be a boolean`),`shape`in n&&(typeof n.shape==`string`?n.shape===``&&r.push(`"shape" at "${e}" must not be empty`):r.push(`"shape" at "${e}" must be a string (shape name)`)),`minItems`in n&&(typeof n.minItems!=`number`||!Number.isFinite(n.minItems)||n.minItems<0||!Number.isInteger(n.minItems))&&r.push(`"minItems" at "${e}" must be a non-negative finite integer`),`maxItems`in n&&(typeof n.maxItems!=`number`||!Number.isFinite(n.maxItems)||n.maxItems<0||!Number.isInteger(n.maxItems))&&r.push(`"maxItems" at "${e}" must be a non-negative finite integer`),`minItems`in n&&`maxItems`in n&&typeof n.minItems==`number`&&typeof n.maxItems==`number`&&n.minItems>n.maxItems&&r.push(`"minItems" at "${e}" cannot exceed "maxItems"`),o===`array`&&(`items`in n?Ba(`${e}.items`,`${t}.items`,n.items,r,i):r.push(`Typed array at "${e}" must have an "items" key specifying the element type`))}function Ha(e={}){return{allowUnsafeFieldNamePaths:new Set(e.allowUnsafeFieldNamePaths??[])}}const Ua=/* @__PURE__ */ new Set([`fields`,`description`,`composes`]);function Wa(e,t=``){let n=[];for(let[r,i]of Object.entries(e)){let e=r.endsWith(`?`)?r.slice(0,-1):r,a=t?`${t}.${e}`:e,o=en(i);o===`string`||o===`wref`||o===`number`||o===`boolean`?n.push(a):V(i)||B(i)&&n.push(...Wa(i,a))}return n}function Ga(e,t,n){if(Array.isArray(t))t.length===1&&Ga(`${e}[]`,t[0],n);else if(V(t)){let r=H(t).spec;V(r)&&typeof r.type==`string`&&r.type===`array`&&`items`in r&&Ga(`${e}.items`,r.items,n)}else Ra(t)&&Ka(t,e,n)}function Ka(e,t,n){for(let[r,i]of Object.entries(e)){let e=ni(t,r);$r(ei(r)).unsafe&&n.push(e),Ra(i)?Ka(i,e,n):Ga(e,i,n)}}function qa(e){if(typeof e!=`object`||!e||Array.isArray(e))return[];let t=e.fields;if(typeof t!=`object`||!t||Array.isArray(t))return[];let n=[];return Ka(t,`fields`,n),n}function Ja(e,t={}){if(typeof e!=`object`||!e||Array.isArray(e))return{valid:!1,errors:[`Shape definition must be a plain object`]};let n=e,r=[];for(let e of Object.keys(n))Ua.has(e)||r.push(`Unsupported shape definition key "${U(e)}"`);if(!(`fields`in n))return{valid:!1,errors:[`Shape definition must have a "fields" property`]};let i=n.fields;if(typeof i!=`object`||!i||Array.isArray(i))return{valid:!1,errors:[`"fields" must be a plain object mapping field names to types`]};za(i,`fields`,r,Ha(t));let a=Wa(i),o=a.length,s=/* @__PURE__ */ new Set,c=/* @__PURE__ */ new Set;for(let e of a){let t=an(e);t>256&&r.push(`Indexable field path "${U(e)}" is ${t} bytes; maximum is 256`);let n=Aa(e);s.has(n)?c.add(n):s.add(n)}for(let e of c)r.push(`Shape declares ambiguous indexable field path "${U(e)}"; dotted field names, optional-key suffixes, and case-insensitive folded paths must not collide with another indexable path`);return o>256&&r.push(`Shape declares ${o} indexable scalar fields; maximum is 256`),`description`in n&&typeof n.description!=`string`&&r.push(`"description" must be a string`),`composes`in n&&(Array.isArray(n.composes)&&n.composes.every(e=>typeof e==`string`&&e.length>0)||r.push(`"composes" must be an array of non-empty Shape wrefs`)),ja(n,[],r),r.length>0?{valid:!1,errors:r}:{valid:!0}}function Ya(e){let t=/* @__PURE__ */ new Set;for(let n of Object.keys(e))t.add(n.endsWith(`?`)?n.slice(0,-1):n);return t}function Xa(e,t){let n=[],r=0;for(let i of Object.keys(e))t.has(i)||(r++,n.length<500&&n.push(i));if(r!==0)return r>500?{undeclaredFields:n,undeclaredFieldsTruncated:!0,totalUndeclared:r}:{undeclaredFields:n}}function Za(e,t={}){let n=Qa(e,t.enforceContentLimits!==!1);return(e,t)=>{for(let r of n){let n=e[r.fieldName];n==null?r.isOptional||t.push(`Missing required field: "${r.displayName}"`):r.validate(r.displayName,n,t)}}}function Qa(e,t){return Object.entries(e).map(([e,n])=>{let r=e.endsWith(`?`)?e.slice(0,-1):e,i=H(n);return{fieldName:r,displayName:U(r),isOptional:fn(e,n),validate:$a(i.spec,t)}})}function $a(e,t){if(typeof e==`string`)return(n,r,i)=>no(n,r,e,i,t);if(Array.isArray(e)){let n=e.length>0?$a(H(e[0]).spec,t):void 0;return(e,t,r)=>{if(!Array.isArray(t))r.push(`Field "${e}" expected array, got ${typeof t}`);else if(n)for(let i=0;i<t.length;i++)n(`${e}[${i}]`,t[i],r)}}if(V(e)){if((e.type.endsWith(`?`)?e.type.slice(0,-1):e.type)===`array`){let n=`items`in e&&e.items!=null?$a(H(e.items).spec,t):void 0;return(t,r,i)=>{if(!Array.isArray(r))i.push(`Field "${t}" expected array, got ${typeof r}`);else if(typeof e.minItems==`number`&&r.length<e.minItems&&i.push(`Field "${t}" has ${r.length} items, minimum is ${e.minItems}`),typeof e.maxItems==`number`&&r.length>e.maxItems&&i.push(`Field "${t}" has ${r.length} items, maximum is ${e.maxItems}`),n)for(let e=0;e<r.length;e++)n(`${t}[${e}]`,r[e],i)}}let n=eo(e);return(r,i,a)=>{no(r,i,e.type,a,t),n(r,i,a)}}if(B(e)){let n=Qa(e,t);return(e,t,r)=>{if(typeof t!=`object`||!t||Array.isArray(t)){r.push(`Field "${e}" expected object, got ${typeof t}`);return}let i=t;for(let t of n){let n=i[t.fieldName],a=ti(e,t.fieldName);n==null?t.isOptional||r.push(`Missing required field: "${a}"`):t.validate(a,n,r)}}}return()=>{}}function eo(e){let t=typeof e.pattern==`string`?e.pattern:void 0,n=t===void 0?void 0:to(t);return(r,i,a)=>{if(typeof i==`string`){if(typeof e.minLength==`number`&&i.length<e.minLength&&a.push(`Field "${r}" length ${i.length} is below minimum ${e.minLength}`),typeof e.maxLength==`number`&&i.length>e.maxLength&&a.push(`Field "${r}" length ${i.length} exceeds maximum ${e.maxLength}`),t!==void 0){let e=U(t);n?.kind===`unsupported`?a.push(`Field "${r}" has unsupported pattern "${e}"`):n?.kind===`invalid`?a.push(`Field "${r}" has invalid pattern "${e}" — skipping regex check`):n?.kind===`compiled`&&!n.regex.test(i)&&a.push(`Field "${r}" does not match pattern "${e}"`)}Array.isArray(e.enum)&&!e.enum.includes(i)&&a.push(`Field "${r}" value "${U(String(i))}" is not in allowed values: ${e.enum.map(e=>U(String(e))).join(`, `)}`)}typeof i==`number`&&(typeof e.minimum==`number`&&i<e.minimum&&a.push(`Field "${r}" value ${i} is below minimum ${e.minimum}`),typeof e.maximum==`number`&&i>e.maximum&&a.push(`Field "${r}" value ${i} exceeds maximum ${e.maximum}`),e.integer===!0&&!Number.isInteger(i)&&a.push(`Field "${r}" must be an integer, got ${i}`))}}function to(e){if(cn(e))return{kind:`invalid`};let t=un(e);return t?{kind:`compiled`,regex:t}:{kind:`unsupported`}}function no(e,t,n,r,i){switch(n){case`number`:typeof t!=`number`&&r.push(`Field "${e}" expected number, got ${typeof t}`);break;case`string`:typeof t==`string`?i&&sn(e,t,r):r.push(`Field "${e}" expected string, got ${typeof t}`);break;case`wref`:typeof t!=`string`&&r.push(`Field "${e}" expected string, got ${typeof t}`);break;case`boolean`:typeof t!=`boolean`&&r.push(`Field "${e}" expected boolean, got ${typeof t}`);break;case`array`:Array.isArray(t)||r.push(`Field "${e}" expected array, got ${typeof t}`)}}function ro(e){let t=e.map(e=>Za(e.fields)),n=/* @__PURE__ */ new Set;for(let t of e)for(let e of Ya(t.fields))n.add(e);let r=e.map(e=>e.fields);return e=>{let i=e===null?{}:e;if(typeof i!=`object`||Array.isArray(i))return{valid:!1,errors:[`Data must be a plain object`]};let a=i,o=[];for(let e of t)e(a,o);ja(a,r,o);let s=Xa(a,n);return o.length>0?s?{valid:!1,errors:o,warnings:s}:{valid:!1,errors:o}:s?{valid:!0,warnings:s}:{valid:!0}}}function io(e,t){return ao(t)(e)}function ao(e){return ro([{name:``,fields:e}])}var G=class extends Error{code;status;hint;retryAfter;errorCode;backendCode;details;constructor(e,t,n,r,i,a,o){super(t),this.name=`WarmHubError`,this.code=e,this.status=n,this.hint=r,this.retryAfter=i,this.errorCode=a,this.backendCode=a,this.details=o}get kind(){return this.code}};function oo(e){return e.keepShapes===!0}const so=Symbol.for(`warmhub.sdk.queuedOperations`);function co(e){return typeof e==`object`&&!!e&&typeof e[so]==`function`}function lo(e){return ye(e)}var K=class extends G{operationIndex;constructor(e,t,n=`VALIDATION_ERROR`){super(n,e===void 0?t:`Invalid operation at index ${e}: ${t}`,n===`NOT_FOUND`?404:400),this.operationIndex=e}};const uo=`DEPENDENCY_FAILED`,fo="`shapes` takes bare Shape names; writes always certify under the Shape's head version.",po=[`expectedVersion`,`leaseId`],mo={add:/* @__PURE__ */ new Set([`operation`,`name`,`shapes`,`data`,`affirmedTargets`,`skipExisting`,`file`]),revise:/* @__PURE__ */ new Set([`operation`,`name`,`shapes`,`data`,`affirmedTargets`,`file`,...po,`keepShapes`]),retract:/* @__PURE__ */ new Set([`operation`,`name`,`reason`,...po]),reaffirm:/* @__PURE__ */ new Set([`operation`,`name`,`add`,`remove`,...po]),rename:/* @__PURE__ */ new Set([`operation`,`name`,`newName`]),restore:/* @__PURE__ */ new Set([`operation`,`name`,`newName`,...po])},ho=new Set(Object.keys(mo)),go=/@v\d+$/;function _o(e){return go.test(e)}function vo(e){return typeof e==`string`&&e.length>0&&e.trim()===e&&!e.includes(`/`)&&!fe(e)}function yo(e,t,n){if(typeof e!=`string`||e.length===0)throw new K(n,`'${t}' must be a non-empty name`);return e}function bo(e,t,n=!1){if(typeof e!=`object`||!e)throw new K(t,`an operation must be an object`);if(Object.hasOwn(e,`shapeless`))throw new K(t,`shapeless is a builder option; a raw operation states a shapeless write as shapes: []`);let r=e;if(typeof r.operation!=`string`||!ho.has(r.operation))throw new K(t,`'operation' must be one of add, revise, retract, restore, reaffirm, rename`);let i=yo(r.name,`name`,t);if(r.operation===`rename`){let e=yo(r.newName,`newName`,t);if(v(i)!==v(e))throw new K(t,`a Shape renames to a Shape: rename "${i}" to hub/shapes/<Name>, and a Thing to a Thing name`)}if((r.operation===`add`||r.operation===`revise`)&&(xo(r,i,t),r.data===void 0))throw new K(t,`${r.operation} requires 'data'`);if(r.operation===`add`&&r.expectedVersion!==void 0)throw new K(t,`expectedVersion is only valid on revise, retract, restore, or reaffirm operations`);let a=mo[r.operation],o=Object.keys(r).find(e=>r[e]!==void 0&&!a?.has(e));if(o!==void 0)throw new K(t,`unknown key "${o}" on a ${r.operation} operation`);return Co(r,i,t),n&&r.operation===`add`?{...r,skipExisting:!0}:r}function xo(e,t,n){if(e.keepShapes!==void 0){if(e.operation!==`revise`||e.keepShapes!==!0)throw new K(n,`keepShapes applies only to a revise: an add states its shapes, or shapeless`);if(e.shapes!==void 0)throw new K(n,`state Shapes one way: shapes, shapeless, or keepShapes`);return}let r=e.shapes;if(!Array.isArray(r))throw new K(n,`${String(e.operation)} "${t}" states no Shapes: pass shapes: ['Shape', ...], shapeless, or (revise only) keepShapes`);for(let e of r){if(typeof e==`string`&&_o(e))throw new K(n,fo);if(!vo(e))throw new K(n,`shapes holds bare Shape names ('Deal'); got ${JSON.stringify(e)}`)}if(v(t)&&r.length>0)throw new K(n,`"${t}" is a Shape: write it with shapes: []`);if(r.length===0&&e.affirmedTargets!==void 0)throw new K(n,`affirmedTargets needs a Shape that composes Assertion; a shapeless write has none`)}const So=e=>`Name "${e}" contains reserved character "+". The "+" character is reserved for the historical collection auto-name namespace and is not allowed in user-supplied names.`;function Co(e,t,n){let r=xe(t);if(r!==void 0){let t=typeof e.newName==`string`?xe(e.newName)??e.newName:void 0,i=Xi({operation:e.operation,kind:`shape`,name:r,...t===void 0?{}:{newName:t}},n)[0];if(i)throw new K(n,i.message,i.code);return}if(e.operation===`restore`&&typeof e.newName==`string`&&v(e.newName)){let r=Xi({operation:`restore`,name:t,newName:e.newName},n)[0];if(r)throw new K(n,r.message,r.code);return}let i=e.operation===`add`?t:(e.operation===`rename`||e.operation===`restore`)&&typeof e.newName==`string`?e.newName:void 0;if(i!==void 0){if(me(i))throw new K(n,ge(i),`RESERVED_NAME`);if(i.includes(`+`))throw new K(n,So(i))}}function wo(e,t=0){let n=/* @__PURE__ */ new Set;e.forEach((e,r)=>{if(e.operation===`add`){if(n.has(e.name))throw new K(t+r,`Cannot add "${e.name}" twice in the same commit`,`ILLEGAL_OP_SEQUENCE`);n.add(e.name)}})}function To(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Set;return async(r,i=0)=>{let a=/* @__PURE__ */ new Set,o=/* @__PURE__ */ new Set;for(let e of r){oo(e)&&!o.has(e.name)&&!n.has(e.name)&&!t.has(e.name)&&a.add(e.name);for(let t of Eo(e))o.add(t)}let s=await Do([...a],e);return r.map((e,r)=>{if(!oo(e)){if(e.operation===`revise`)t.set(e.name,e.shapes);else if(e.operation===`add`||e.operation===`rename`)for(let t of Eo(e))n.add(t);return e}if(n.has(e.name))throw new K(i+r,`keepShapes revise "${e.name}": an earlier operation in this submission adds or renames it, so its Shapes are not known until that commits; submit it in a later request, or pass \`shapes\``);let{keepShapes:a,...o}=e,c=t.get(e.name);if(c!==void 0)return{...o,shapes:c};let l=s.get(e.name);if(l===void 0)throw new K(i+r,`keepShapes revise "${e.name}": no such Thing`,`NOT_FOUND`);return t.set(e.name,l.shapes),{...o,shapes:l.shapes,expectedVersion:e.expectedVersion??l.version}})}}function Eo(e){return e.operation===`rename`?[e.name,e.newName]:e.operation===`add`||e.operation===`revise`?[e.name]:[]}async function Do(e,t){let n=/* @__PURE__ */ new Map;for(let r=0;r<e.length;r+=500){let i=e.slice(r,r+500),a=await t(i),o=new Set(a.missing),s=i.filter(e=>!o.has(e));if(s.length!==a.items.length)throw Error(`keepShapes read returned ${a.items.length} items for ${s.length} found targets`);s.forEach((e,t)=>{let r=a.items[t];r!==void 0&&n.set(e,{shapes:r.declaredShapes.map(e=>Se(e)),version:r.version})})}return n}const Oo=1e4,ko=4194304;var Ao=class extends Error{code=`VALIDATION_ERROR`;status=400;constructor(e,t){super(`Invalid operation at index ${e}: ${t}`),this.name=`WarmHubError`}};function jo(e,t){if(typeof e.name!=`string`||e.name.length===0)throw new Ao(t,`${String(e.operation)} requires 'name'`);return e.name}function Mo(e,t,n){let r=e[n];if(typeof r!=`number`||!Number.isInteger(r)||r<1)throw new Ao(t,`${String(e.operation)} requires a positive integer '${n}'`);return r}function No(e,t){let n=jo(e,t);if(e.operation===`remove`)return{operation:`remove`,name:n,expectedVersion:Mo(e,t,`expectedVersion`)};let r=e.data;if(typeof r!=`object`||!r||Array.isArray(r))throw new Ao(t,`rewrite requires 'data', the complete replacement body as an object`);let i=e.shapes;if(!Array.isArray(i)||i.some(e=>typeof e!=`string`||e.length===0))throw new Ao(t,`rewrite requires 'shapes', the version's declared Shapes plus CorrectedThing`);return{operation:`rewrite`,name:n,version:Mo(e,t,`version`),shapes:i,data:r}}const Po=e=>{let t=typeof e==`object`&&e?e.operation:void 0;return t===`remove`||t===`rewrite`},Fo=e=>!Po(e);function Io(e,t){let n=(co(e)?e[so]():e).map((e,n)=>Po(e)?No(e,n):bo(e,n,t===!0));return wo(n.filter(Fo)),n}async function Lo(e,t){let n=(await e(t.filter(Fo))).values();return t.map(e=>Fo(e)?n.next().value:e)}async function Ro(e,t,n,r,i,a){let o=Io(i,a?.skipExisting),s=To(t),c={...zo(n,r,[],a),operations:await Lo(s,o)},l=Vo(c);if(l>4194304)throw new G(`VALIDATION_ERROR`,`Commit validation request exceeds the ${ko}-byte encoded limit (${l} bytes).`,413,`Split the preview into smaller current-commit units.`);return await e.mutate(c,{signal:a?.signal})}function zo(e,t,n,r){return{orgName:e,graphName:t,...r?.committer===void 0?{}:{committer:r.committer},...r?.message===void 0?{}:{message:r.message},...r?.componentRef===void 0?{}:{componentRef:r.componentRef},operations:Io(n,r?.skipExisting),...r?.includeWouldBeBody===void 0?{}:{includeWouldBeBody:r.includeWouldBeBody}}}function Bo(e){return JSON.stringify(e)}function Vo(e){return new TextEncoder().encode(Bo(e)).byteLength}function Ho(e){let t=/* @__PURE__ */ new Set;return ii(e,{rootContext:{key:null,parentKey:null,insideData:!1},childContext:(e,t)=>({key:t,parentKey:e.key,insideData:e.insideData||t===`data`}),onStringValue:(e,n)=>{if(n.key===`durableId`&&n.parentKey===`metadata`&&!n.insideData)return;let r=oe(e);r&&t.add(r.durableId)}}),t}async function Uo(e,t){let n=[...e],r={};for(let e=0;e<n.length;e+=500){let{items:i}=await t(n.slice(e,e+500));for(let e of i)r[e.durableId]=e.canonicalWref}return r}function Wo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Go(e){if(!Wo(e))return;let t=e.decorations;return Wo(t)?t:void 0}function Ko(e){let t=e instanceof Error?e:Error(String(e));return Object.assign(t,{decorationFailure:!0})}function qo(e){return()=>({op:t,next:n})=>!e.enabled||t.type!==`query`||t.path===`thing.names`||t.path===`thing.headVersions`?n(t):u(r=>{let i=!1,o=!1,s=!1,c=()=>{!i&&o&&!s&&r.complete()},l=n(t).subscribe({next:t=>{let n=t.result?.data;if(!Wo(n)){r.next(t);return}let o=Ho(n);o.size===0?r.next(t):(s=!0,Uo(o,e.lookupNames).then(e=>{i||r.next({...t,result:{...t.result,data:{...n,decorations:e}}})}).catch(e=>{i||r.error(a.from(Ko(e)))}).finally(()=>{s=!1,c()}))},error:e=>r.error(e),complete:()=>{o=!0,c()}});return()=>{i=!0,l.unsubscribe()}})}function Jo(e,t){return{create:async(n,r,i)=>{try{return await e().grant.create.mutate({orgName:n,graphName:r,...i})}catch(e){throw t(e)}},get:async(n,r,i)=>{try{return await e().grant.get.query({orgName:n,graphName:r,grantId:i})}catch(e){throw t(e)}},list:async(n,r,i)=>{try{return await e().grant.list.query({orgName:n,graphName:r,limit:i?.limit,cursor:i?.cursor})}catch(e){throw t(e)}},revoke:async(n,r,i,a)=>{try{return await e().grant.revoke.mutate({orgName:n,graphName:r,grantId:i,reason:a?.reason})}catch(e){throw t(e)}}}}function Yo(e,t,n){let r=Ja(t,n===`revise`?{allowUnsafeFieldNamePaths:qa(t)}:void 0);return r.valid?null:`Invalid shape definition for "${e}": ${r.errors.join(`; `)}`}var Xo=class{receipts=[];operations=[];uploads=[];statusCounts={applied:0,noop:0,error:0};get allFailed(){return this.operations.length>0&&this.statusCounts.error===this.operations.length}addChunk(e){for(let t of e.receipt.operations)this.statusCounts[t.status]++,this.operations.push({...t,opIndex:e.chunkStart+t.opIndex});for(let t of e.uploads??[])this.uploads.push({...t,opIndex:e.chunkStart+t.opIndex})}addReceipt(e){this.receipts.push(e)}completedOperations(){return this.operations.filter(e=>e.status!==`error`)}completedUploads(){return[...this.uploads]}toResult(e){let t=this.statusCounts.error>0;return{...e.committer===void 0?{}:{committer:e.committer},...e.createdByEmail===void 0?{}:{createdByEmail:e.createdByEmail},message:e.message,operationCount:this.operations.length,...e.graphSeq===void 0?{}:{graphSeq:e.graphSeq},...t?{partial:t,statusCounts:{...this.statusCounts}}:{},operations:this.operations,receipts:this.receipts,...this.uploads.length>0?{uploads:this.uploads}:{}}}};function Zo(){let e=globalThis.crypto?.randomUUID?.();if(!e)throw Error(`This runtime cannot mint a cryptographically secure UUID`);return e.toLowerCase()}const Qo=Zo,$o=1e3,es=1e4;var ts=class extends Error{code=`PARTIAL_STREAM_SUBMISSION`;completedReceipts;completedOperations;uploads;submissionId;eventRequestId;chunkOrdinal;pendingOutcome;acknowledgedOperationCount;lastAcknowledgedGraphSeq;attemptedAppendOutcome;cause;constructor(e){super(e.pendingOutcome===`unknown`?`Stream submission outcome is unknown for event request ${e.eventRequestId}. Look up its immutable receipt before retrying.`:`Stream submission stopped at event request ${e.eventRequestId} after earlier chunks committed.`),this.name=`WarmHubError`,this.cause=e.cause,this.completedReceipts=e.completedReceipts,this.completedOperations=e.completedOperations??[],this.uploads=e.uploads??[],this.submissionId=e.submissionId,this.eventRequestId=e.eventRequestId,this.chunkOrdinal=e.chunkOrdinal,this.pendingOutcome=e.pendingOutcome,this.acknowledgedOperationCount=e.acknowledgedOperationCount??e.completedReceipts.length,this.attemptedAppendOutcome=e.attemptedAppendOutcome,e.lastAcknowledgedGraphSeq!==void 0&&(this.lastAcknowledgedGraphSeq=e.lastAcknowledgedGraphSeq)}},ns=class extends Error{code;receipts;result;operations;statusCounts;cause;constructor(e){let t=e.operations.find(e=>e.status===`error`)?.errors[0];super(t?`All ${e.operationCount} stream operations failed: ${t.message}`:`All ${e.operationCount} stream operations failed.`),this.name=`WarmHubError`,this.code=t&&e.operations.every(e=>e.status===`error`&&e.errors.length>0&&e.errors.every(e=>e.code===t.code))?t.code:`STREAM_ALL_OPERATIONS_FAILED`,this.cause=t,this.result=e,this.receipts=e.receipts,this.operations=e.operations,this.statusCounts=e.statusCounts??{applied:0,noop:0,error:e.operationCount}}};function rs(e){return e.status}function is(e){let t={applied:0,noop:0,error:0};for(let n of e)t[rs(n)]++;return t}const as={maxAttempts:3,baseDelayMs:250,maxDelayMs:8e3},os=6e4;function ss(e){if(e===!1)return!1;let t={};e!==void 0&&(Number.isFinite(e.maxAttempts)&&(t.maxAttempts=e.maxAttempts),Number.isFinite(e.baseDelayMs)&&(t.baseDelayMs=e.baseDelayMs),Number.isFinite(e.maxDelayMs)&&(t.maxDelayMs=e.maxDelayMs));let n={...as,...t};return{maxAttempts:Math.min(10,Math.max(1,Math.trunc(n.maxAttempts))),baseDelayMs:Math.min(os,Math.max(0,Math.trunc(n.baseDelayMs))),maxDelayMs:Math.min(os,Math.max(0,Math.trunc(n.maxDelayMs)))}}const cs=/* @__PURE__ */ new Set([`BAD_REQUEST`,`METHOD_NOT_SUPPORTED`,`PARSE_ERROR`,`PAYLOAD_TOO_LARGE`,`PRECONDITION_FAILED`,`UNAUTHORIZED`,`UNPROCESSABLE_CONTENT`,`UNSUPPORTED_MEDIA_TYPE`,`UNAUTHENTICATED`,`FORBIDDEN`,`VALIDATION_ERROR`,`SHAPE_MISMATCH`,`RESERVED_NAME`,`ILLEGAL_OP_SEQUENCE`,`NOT_FOUND`,`KIND_MISMATCH`,`CONFLICT`,`NAME_TAKEN`,`TARGET_REMOVED`,`TARGET_REDACTED`,`ALREADY_RETRACTED`,`ARCHIVED`,`RATE_LIMITED`,`TOO_MANY_REQUESTS`,`UNRESOLVED_TOKEN`]),ls=/* @__PURE__ */ new Set([`COMMIT_OUTCOME_UNKNOWN`]);function us(e){if(!e||typeof e!=`object`)return;let t=e.code;if(typeof t==`string`)return t;let n=e.data,r=n?.warmhub?.code;if(typeof r==`string`)return r;let i=n?.code;if(typeof i==`string`)return i}function ds(e){if(!e||typeof e!=`object`)return;let t=e.data?.httpStatus;if(typeof t==`number`)return t;let n=e.data?.warmhub?.status;if(typeof n==`number`)return n;let r=e.status;return typeof r==`number`?r:void 0}function fs(e){return e!==void 0&&e>=400&&e<500&&e!==408}function ps(e){let t=us(e);return t!==void 0&&ls.has(t)}function ms(e){if(ps(e))return!1;let t=us(e);return t!==void 0&&cs.has(t)||fs(ds(e))}function hs(e){if(ps(e)||ms(e))return!1;if(gs(e))return!0;if(e instanceof TypeError||e instanceof SyntaxError)return!1;let t=e?.cause;return gs(t)?!0:!(t instanceof TypeError||t instanceof SyntaxError)}function gs(e){return e instanceof TypeError&&/fetch/i.test(e.message)}function _s(e,t){let n=t.baseDelayMs*2**Math.max(0,e-1),r=Math.random()*t.baseDelayMs;return Math.min(t.maxDelayMs,n+r)}function vs(e){return new Promise(t=>setTimeout(t,e))}var ys=class extends Error{code;status=400;constructor(e,t=`VALIDATION_ERROR`){super(e),this.code=t,this.name=`WarmHubError`}},bs=class extends Error{reason;constructor(e){super(`operation source failed`),this.reason=e}};async function xs(e,t){let n=js(t.chunkSize),r=t.submissionId??Zo(),i=t.streamId??r,a=ss(t.retry),o=new Xo,s,c,l=0,u,d=0,f=To(async n=>{if(!e.thing)throw new ys(`A keepShapes revise needs the client to read its Thing: this stream client has no thing.getMany`);return await e.thing.getMany(t.orgName,t.graphName,n)}),p=e=>new ts({cause:e.cause,completedReceipts:o.receipts,completedOperations:o.completedOperations(),uploads:o.completedUploads(),acknowledgedOperationCount:l,lastAcknowledgedGraphSeq:u,attemptedAppendOutcome:e.pendingOutcome===`absent`?`not_applied`:`unknown`,submissionId:r,eventRequestId:vi(r,d),chunkOrdinal:d,pendingOutcome:e.pendingOutcome});try{for await(let m of Ss(t.operations,n,t.skipExisting===!0,f)){let n=m.operations,f=1,h=!1;for(;;)try{let a=await e.stream.append({chunkOrdinal:d,orgName:t.orgName,graphName:t.graphName,streamId:i,submissionId:r,componentRef:t.componentRef,committer:t.committer,message:t.message,...t.returnGraphSeq===void 0?{}:{returnGraphSeq:t.returnGraphSeq},operations:n});o.addReceipt(a.receipt),s=a.createdByEmail??s,c=a.graphSeq??c,o.addChunk({receipt:a.receipt,chunkStart:m.start,uploads:a.uploads}),l+=m.operations.length;let f=As(a.receipt);f!==void 0&&(u=f);break}catch(e){let t=ms(e);if(o.receipts.length===0&&!h&&t)throw e;if(a!==!1&&f<a.maxAttempts&&hs(e)){await vs(_s(f,a)),f+=1,h=!0;continue}throw p({cause:e,pendingOutcome:h||!t?`unknown`:`absent`})}d+=1}}catch(e){throw e instanceof bs?o.receipts.length===0?e.reason:p({cause:e.reason,pendingOutcome:`absent`}):e}if(d===0)throw new ys(`At least one operation is required for stream submission.`);let m=o.toResult({committer:t.committer,createdByEmail:s,message:t.message,graphSeq:c});if(o.allFailed)throw new ns(m);return m}async function*Ss(e,t,n,r){try{let i=Cs(e);if(i!==void 0){let e=i.map((e,t)=>bo(e,t,n));wo(e);let a=await r(e);for(let e=0;e<a.length;e+=t)yield{operations:a.slice(e,e+t),start:e};return}let a=0,o=[],s=async(e,t)=>await ws(e,t,r);for await(let r of Es(e,n))o.push(r),a+=1,o.length<t||(yield await s(o,a),o=[]);o.length>0&&(yield await s(o,a))}catch(e){throw new bs(e)}}function Cs(e){if(co(e))return e[so]();if(Array.isArray(e))return e}async function ws(e,t,n){let r=t-e.length;return wo(e,r),{operations:await n(e,r),start:r}}function Ts(e){let t=To(e),n=0;return async e=>{let r=n;return n+=e.length,await t(e.map((e,t)=>bo(e,r+t)),r)}}async function*Es(e,t){let n=Ds(e,t);try{for(;;){let e=await n.next();if(e.done)return;yield e.value}}finally{let e=n.returnSourceOnce();e&&await e}}function Ds(e,t){let n,r=0,i=!1,a=!1,o=()=>{if(n)return n;let t=co(e)?e[so]():e;return n=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator](),n};return{async next(){let e=await o().next();if(e.done)return a=!0,{done:!0,value:void 0};let n=bo(e.value,r,t);return r+=1,{done:!1,value:n}},returnSourceOnce(){if(i||a)i=!0;else return i=!0,n?.return?.()}}}function Os(e){return ks.encode(`${JSON.stringify(e)}\n`)}const ks=new TextEncoder;function As(e){let t=e.event?.graphSeq;if(t===void 0)return;let n=Number(t);return Number.isSafeInteger(n)?n:void 0}function js(e){return Number.isFinite(e)?Math.max(1,Math.min(es,Math.trunc(e))):$o}var Ms=class{ops=[];shapes;submitted=!1;inFlight=!1;constructor(e){this.shapes=e?.shapes}add(e,t){this.assertCanModify();let n=this.ops.length,r=this.statedShapes(t,n,`add`,e);return this.queue({operation:`add`,name:e,shapes:r??[],data:t.data,...t.affirmedTargets===void 0?{}:{affirmedTargets:[...t.affirmedTargets]},...t.skipExisting===!0?{skipExisting:!0}:{},...t.file===void 0?{}:{file:{...t.file}}},t.data),this}revise(e,t){this.assertCanModify();let n=this.ops.length,r=this.statedShapes(t,n,`revise`,e),i={data:t.data,...t.affirmedTargets===void 0?{}:{affirmedTargets:[...t.affirmedTargets]},...t.file===void 0?{}:{file:{...t.file}},...t.expectedVersion===void 0?{}:{expectedVersion:t.expectedVersion},...t.leaseId===void 0?{}:{leaseId:t.leaseId}};return this.queue(r===void 0?{operation:`revise`,name:e,keepShapes:!0,...i}:{operation:`revise`,name:e,shapes:r,...i},t.data),this}retract(e,t={}){return this.assertCanModify(),this.queue({operation:`retract`,name:e,...t.reason===void 0?{}:{reason:t.reason},...t.expectedVersion===void 0?{}:{expectedVersion:t.expectedVersion},...t.leaseId===void 0?{}:{leaseId:t.leaseId}}),this}restore(e,t={}){return this.assertCanModify(),this.queue({operation:`restore`,name:e,...t.newName===void 0?{}:{newName:t.newName},...t.expectedVersion===void 0?{}:{expectedVersion:t.expectedVersion},...t.leaseId===void 0?{}:{leaseId:t.leaseId}}),this}rename(e,t){return this.assertCanModify(),this.queue({operation:`rename`,name:e,newName:t}),this}reaffirm(e,t){return this.assertCanModify(),this.queue({operation:`reaffirm`,name:e,...t.add===void 0?{}:{add:[...t.add]},...t.remove===void 0?{}:{remove:[...t.remove]},...t.expectedVersion===void 0?{}:{expectedVersion:t.expectedVersion},...t.leaseId===void 0?{}:{leaseId:t.leaseId}}),this}get operations(){return Object.freeze([...this.ops])}get size(){return this.ops.length}has(e){return this.ops.some(t=>t.operation===`add`&&t.name===e)}[so](){return this.ops}validate(){let e=[],t=[],n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Set;return this.ops.forEach((i,a)=>{if(i.operation===`add`)n.has(i.name)&&e.push({code:`DUPLICATE_NAME`,operationIndex:a,message:`Duplicate name '${i.name}' at index ${a} (already added earlier in commit)`}),n.add(i.name);else if(i.operation===`revise`)r.has(i.name)?e.push({code:`REVISE_AFTER_RETRACT`,operationIndex:a,message:`Revise at index ${a} targets '${i.name}' which was already retracted in this commit`}):n.has(i.name)||t.push({code:`REVISE_UNKNOWN_WREF`,operationIndex:a,message:`Revise at index ${a} references '${i.name}' which was not added in this commit (assuming it exists server-side)`});else if(i.operation===`retract`){if(r.has(i.name)){t.push({code:`RETRACT_AFTER_RETRACT`,operationIndex:a,message:`Retract at index ${a} targets '${i.name}' which was already retracted in this commit`});return}n.has(i.name)||t.push({code:`RETRACT_UNKNOWN_WREF`,operationIndex:a,message:`Retract at index ${a} references '${i.name}' which was not added in this commit (assuming it exists server-side)`}),r.add(i.name)}else i.operation===`restore`&&r.clear()}),this.ops.length===0&&e.push({code:`EMPTY_COMMIT`,operationIndex:-1,message:`OperationBuilder has no operations`}),{valid:e.length===0,errors:e,warnings:t}}async commit(e){if(this.assertNotSubmitted(),this.inFlight)throw new K(void 0,`OperationBuilder: stream submission already in flight`);let t=this.validate(),[n]=t.errors;if(n!==void 0){let e=t.errors.map(e=>e.message).join(`; `);throw new K(n.operationIndex<0?void 0:n.operationIndex,`OperationBuilder validation failed: ${e}`)}this.inFlight=!0;try{let t=await xs(e.client,{orgName:e.orgName,graphName:e.graphName,committer:e.committer,message:e.message,chunkSize:e.chunkSize,streamId:e.streamId,submissionId:e.submissionId,returnGraphSeq:e.returnGraphSeq,retry:e.retry,operations:this});return this.submitted=!0,t}catch(e){throw e instanceof ts&&(this.submitted=!0),e}finally{this.inFlight=!1}}statedShapes(e,t,n,r){let i=[e.shapes!==void 0,e.shapeless!==void 0,e.keepShapes!==void 0].filter(Boolean).length;if(i!==1)throw new K(t,i===0?`${n} states no Shapes: pass shapes: ['Shape', ...], shapeless: true${n===`revise`?`, or keepShapes: true`:``}`:`state Shapes one way: shapes, shapeless, or keepShapes`);if(e.keepShapes!==void 0){if(n===`add`||e.keepShapes!==!0)throw new K(t,`keepShapes applies only to a revise: an add states its shapes, or shapeless`);return}if(e.shapeless!==void 0){if(e.shapeless!==!0)throw new K(t,`shapeless must be true`);if(v(r))throw new K(t,`"${r}" is a Shape: write it with shapes: [], not shapeless`);return[]}let a=[...e.shapes??[]];if(a.length===0&&!v(r))throw new K(t,`${n} "${r}" with shapes: [] is the raw spelling of a shapeless write; the builder takes shapeless: true`);return a}queue(e,t){let n=this.ops.length,r=bo(e,n),i=xe(r.name);if(i!==void 0&&(r.operation===`add`||r.operation===`revise`)){let e=Yo(i,r.data,r.operation);if(e)throw new K(n,e)}if(this.shapes&&t!==void 0&&(r.operation===`add`||r.operation===`revise`)&&`shapes`in r&&r.shapes!==void 0)for(let e of r.shapes){let i=this.shapes[e];if(!i)continue;let a=io(t,i);if(!a.valid)throw new K(n,`Shape validation failed for '${r.name}' (shape: ${e}): ${a.errors.join(`; `)}`)}this.ops.push(Object.freeze(r))}assertNotSubmitted(){if(this.submitted)throw new K(void 0,`OperationBuilder: already submitted, cannot modify`)}assertCanModify(){if(this.assertNotSubmitted(),this.inFlight)throw new K(void 0,`OperationBuilder: stream submission already in flight, cannot modify`)}};function Ns(e){return{...e,createdAt:new Date(e.createdAt),updatedAt:new Date(e.updatedAt),runStartedAt:new Date(e.runStartedAt),...e.state===`complete`||e.state===`failed`?{completedAt:new Date(e.completedAt)}:{}}}function Ps(e){return{...e,expiresAt:new Date(e.expiresAt)}}function Fs(e){if(typeof e.checkpointId==`string`&&typeof e.graphSeq!=`number`)return{by:`id`,checkpointId:e.checkpointId};if(typeof e.graphSeq==`number`&&typeof e.checkpointId!=`string`)return{by:`graphSeq`,graphSeq:e.graphSeq};throw TypeError(`Graph checkpoint selector must contain exactly one of checkpointId or graphSeq`)}function Is(e,t){return{status:async(n,r,i)=>{try{return Ns(await e().graph.checkpoint.status.query({orgName:n,graphName:r,selector:Fs(i)}))}catch(e){throw t(e)}},latest:async(n,r)=>{try{let t=await e().graph.checkpoint.latest.query({orgName:n,graphName:r});return t.checkpoint?Ns(t.checkpoint):null}catch(e){throw t(e)}},getAccess:async(n,r,i)=>{try{return Ps(await e().graph.checkpoint.access.query({orgName:n,graphName:r,selector:i.checkpoint===`latest`?{by:`latest`}:Fs(i.checkpoint),artifact:i.artifact===`archive`||i.artifact===`manifest`?{kind:i.artifact}:{kind:`chunk`,path:i.artifact.chunkPath}}))}catch(e){throw t(e)}}}}var q=class extends Error{reason;name=`GraphExportError`;constructor(e,t){super(t??Ls[e]),this.reason=e}};const Ls={count_mismatch:`Graph export trailer record count does not match the rows read`,digest_mismatch:`Graph export content digest does not match the trailer`,fence_mismatch:`Graph export header and trailer disagree about atRepoSeq`,format_mismatch:`Graph export delta and base use different format versions; take a fresh full export`,header_invalid:`Graph export header is invalid`,row_invalid:`Graph export row is invalid or not canonical`,row_out_of_order:`Graph export rows are not strictly increasing by durableId (and by version within one Shape)`,since_below_epoch_floor:`Graph export delta base is below the epoch floor`,trailer_invalid:`Graph export trailer is invalid`,truncated:`Graph export stream ended before its trailer`};var Rs=class{#e=Oa();#t=Oa();#n=0;#r;#i;#a;#o=!1;#s=!1;#c;get header(){return this.#r}get lastDurableId(){return this.#i?.durableId}get lastShapeVersion(){let e=this.#i;return e?.kind===`shape`&&(this.#r?.formatVersion??0)>=6?e.version:void 0}get rowCount(){return this.#e.rowCount}get segmentRowCount(){return this.#n}get contentSha256(){return this.#c}finalizeContentSha256(){return this.#c===void 0&&(this.#c=this.#e.finalize(),this.#o=!0),this.#c}beginSegment(){this.assertResumable(),this.#t=Oa(),this.#n=0}markUnverifiable(){this.#s=!0}finalizeSegment(){return this.#t.finalize()}get token(){return this.#a}set token(e){this.#a=e}get complete(){return this.#o}markComplete(){this.finalizeContentSha256()}assertResumable(){if(this.#s)throw new q(`digest_mismatch`,`Graph export session failed verification and cannot be resumed; start a new session`);if(this.#o)throw new q(`header_invalid`,`Graph export session is already complete; start a new session`)}adoptHeader(e){this.assertResumable();let t=this.#r;if(t!==void 0&&(t.repo!==e.repo||t.mode!==e.mode||t.sinceRepoSeq!==e.sinceRepoSeq||t.atRepoSeq!==e.atRepoSeq))throw new q(`header_invalid`,`Resumed graph export header does not match the opening header`);if(t!==void 0&&t.formatVersion!==e.formatVersion)throw new q(`header_invalid`,`Resumed graph export is format ${e.formatVersion}, but it opened as format ${t.formatVersion}. Restart the export; a resume must use the format it started with.`);this.#r=e}recordRow(e,t){let n=this.#r,r=this.#i;if(n?.mode===`heads`&&r!==void 0&&!ya(r,e,n.formatVersion))throw new q(`row_out_of_order`,`Graph export row '${e.durableId}' v${e.version} does not follow '${r.durableId}' v${r.version}`);this.#e.update(t),this.#t.update(t),this.#n+=1,this.#i={durableId:e.durableId,kind:e.kind,version:e.version}}};function zs(){return new Rs}function Bs(e){return typeof e.get==`function`}function Vs(e){return Bs(e)?e.values():e}function Hs(e,t){return t>=6&&e.kind===`shape`?`${e.durableId}@v${e.version}`:e.durableId}function Us(e,t,n){if(n.base>=6!=n.delta>=6)throw new q(`format_mismatch`,`Graph export delta is format ${n.delta} but its base is format ${n.base}; take a fresh full export instead of folding across formats`);let r=/* @__PURE__ */ new Map;for(let[i,a]of[[e,n.base],[t,n.delta]])for(let e of Vs(i)){if(!e.active&&a>=6&&e.kind===`shape`){let t=`${e.durableId}@v`;for(let e of r.keys())e.startsWith(t)&&r.delete(e);continue}let t=Hs(e,a);e.active?r.set(t,e):r.delete(t)}return r}const Ws=new TextDecoder;function Gs(e){let t=e.header;if(!t)throw new q(`header_invalid`,`Graph export resumed without an opening header to inherit`);return t}async function Ks(e,t,n){let r=await e.next();if(r.done)throw new q(`truncated`);let i;try{i=Sa(r.value)}catch(e){Xs(`header_invalid`,e)}if(!Zi.includes(i.formatVersion)||n!==void 0&&(i.repo!==n.repo||i.mode!==n.mode||n.sinceRepoSeq!==void 0&&i.sinceRepoSeq!==n.sinceRepoSeq||n.atRepoSeq!==void 0&&i.atRepoSeq!==n.atRepoSeq))throw new q(`header_invalid`,n===void 0?`Graph export header declares format version ${i.formatVersion}; expected one of ${Zi.join(`, `)}`:`Graph export header describes ${i.repo} (${i.mode}, ${i.sinceRepoSeq}..${i.atRepoSeq}); expected ${n.repo} (${n.mode}${n.sinceRepoSeq===void 0?``:`, since ${n.sinceRepoSeq}`}${n.atRepoSeq===void 0?``:`, at ${n.atRepoSeq}`})`);return t.adoptHeader(i),i}async function*qs(e,t){let n=/* @__PURE__ */ new Uint8Array;for await(let t of Js(e)){let e=new Uint8Array(n.length+t.length);e.set(n),e.set(t,n.length),n=e;let r=n.indexOf(10);for(;r!==-1;)yield n.subarray(0,r+1),n=n.subarray(r+1),r=n.indexOf(10)}t.unterminated=n.length>0}function Js(e){if(Symbol.asyncIterator in e)return e;let t=e;return{async*[Symbol.asyncIterator](){let e=t.getReader();try{for(;;){let{done:t,value:n}=await e.read();if(t)return;n&&(yield n)}}finally{e.releaseLock()}}}}function Ys(e){try{let t=JSON.parse(Ws.decode(e));if(typeof t==`object`&&t&&`kind`in t){let e=t.kind;if(typeof e==`string`)return e}}catch{}return``}function Xs(e,t){throw t instanceof q?t:new q(e,t instanceof Error?t.message:void 0)}async function*Zs(e,t,n,r={}){yield*$s(e,t,n,r)}async function Qs(e,t={}){let n=zs(),r=$s(e,n,void 0,t);for await(let e of r)t.onRow?.(e);return n}async function*$s(e,t,n,r){let i={unterminated:!1},a=qs(e,i);try{yield*ec(a,i,t,n,r)}finally{await a.return(void 0)}}async function*ec(e,t,n,r,i){n.assertResumable();let a=i.resumed===!0?Gs(n):await Ks(e,n,r),o=ba(a);for(n.beginSegment();;){let r=await e.next();if(r.done){if(i.partial===!0)return;throw new q(`truncated`)}let s=r.value;if(Ys(s)!==`trailer`){let e;try{e=xa(s)}catch(e){Xs(`row_invalid`,e)}if(!e.active&&!o)throw new q(`row_invalid`,`Graph export tombstone is not legal in a full export`);n.recordRow(e,s),yield e;continue}let c;try{if(c=Ca(s),c.atRepoSeq!==a.atRepoSeq)throw new q(`fence_mismatch`);if(c.recordCount!==n.segmentRowCount)throw new q(`count_mismatch`);if(c.contentSha256!==n.finalizeSegment())throw new q(`digest_mismatch`)}catch(e){if(n.markUnverifiable(),e instanceof q)throw e;Xs(`trailer_invalid`,e)}if(!(await e.next()).done||t.unterminated)throw new q(`trailer_invalid`,`Graph export stream continues past its trailer`);n.markComplete();return}}function tc(e,t,n){let r=new URLSearchParams;for(let[e,t]of Object.entries(n))t!==void 0&&r.set(e,String(t));let i=r.toString();return`/api/graphs/${encodeURIComponent(e)}/${encodeURIComponent(t)}/export${i?`?${i}`:``}`}function nc(e){let t=e?.reason;return t instanceof Error?t:/* @__PURE__ */ Error(`Graph export was aborted`)}function rc(e){return e===void 0||!Number.isFinite(e)?1e3:Math.max(e,50)}async function ic(e,t){if(t?.aborted)throw nc(t);await new Promise((n,r)=>{let i=()=>{clearTimeout(a),r(nc(t))},a=setTimeout(()=>{t?.removeEventListener(`abort`,i),n()},e);t?.addEventListener(`abort`,i,{once:!0})})}async function ac(e,t){let n;try{n=await e.clone().json()}catch{}return(n?.code??n?.error?.code)===`since-below-epoch-floor`?new q(`since_below_epoch_floor`,n?.message):n?.code!==void 0&&n.error===void 0?await t(new Response(JSON.stringify({error:n}),{status:e.status,headers:{"content-type":`application/json`}})):await t(e)}function oc(e){let t=e;return typeof t?.url==`string`&&t.url!==``&&typeof t.expiresAt==`number`&&typeof t.atGraphSeq==`number`&&typeof t.recordCount==`number`&&typeof t.contentSha256==`string`}async function sc(e){let t;try{t=await e.json()}catch{throw new q(`header_invalid`,`Graph export redemption did not return a JSON download envelope`)}if(!oc(t))throw new q(`header_invalid`,`Graph export download envelope must carry url, expiresAt, atGraphSeq, recordCount, and contentSha256`);return t}function cc(e,t){let n=e.header?.atRepoSeq;if(n!==t.atGraphSeq)throw new q(`fence_mismatch`,`Graph export download is pinned to ${n}; the redemption named ${t.atGraphSeq}`);if(e.rowCount!==t.recordCount)throw new q(`count_mismatch`,`Graph export download carried ${e.rowCount} rows; the redemption named ${t.recordCount}`);if(e.contentSha256!==t.contentSha256)throw new q(`digest_mismatch`,`Graph export download digest does not match the digest the redemption named`)}function lc(e,t,n=(e,t)=>globalThis.fetch(e,t)){let r=async(n,r)=>{let i=await e(n,{method:`GET`,headers:{accept:`application/x-ndjson`},...r?{signal:r}:{}});if(!i.ok&&i.status!==202)throw await ac(i,t);return i},i=async(e,t,n={})=>{let i=await(await r(tc(e,t,{mode:n.mode??`heads`,sinceGraphSeq:n.sinceGraphSeq,atGraphSeq:n.atGraphSeq,prefer:`async`}),n.signal)).json();if(typeof i.exportToken!=`string`||typeof i.atGraphSeq!=`number`)throw new q(`header_invalid`,`Graph export async request did not return an exportToken and atGraphSeq`);return{exportToken:i.exportToken,atGraphSeq:i.atGraphSeq}};return{prepare:i,stream:(e,t,n={})=>{let r=n.session?.lastDurableId??n.afterDurableId;if(r!==void 0&&(n.token!==void 0||n.session?.token!==void 0||n.prefer===`async`))throw new q(`header_invalid`,`Graph export token download cannot continue from '${r}': redemption returns the whole prepared object. Start a new session and redeem the token again.`);if(n.afterDurableId!==void 0&&n.session?.header===void 0)throw new q(`header_invalid`,`Graph export afterDurableId needs a session carrying the opening header; reuse the session the broken stream wrote, or rebuild one with restoreGraphExportSession`);return a(e,t,n)}};async function*a(e,t,a){let o=a.session??zs(),s=o.header,c=a.signal,l=o.lastDurableId??a.afterDurableId,u={mode:s?.mode??a.mode??`heads`,sinceGraphSeq:s?.sinceRepoSeq??a.sinceGraphSeq,atGraphSeq:s?.atRepoSeq??a.atGraphSeq,afterDurableId:l,afterVersion:o.lastDurableId===void 0?void 0:o.lastShapeVersion,formatVersion:l===void 0?void 0:s?.formatVersion},d={repo:`${e}/${t}`,mode:u.mode,...a.sinceGraphSeq===void 0?{}:{sinceRepoSeq:a.sinceGraphSeq},...a.atGraphSeq===void 0?{}:{atRepoSeq:a.atGraphSeq}};if(a.token!==void 0&&o.token!==void 0&&a.token!==o.token)throw new q(`header_invalid`,`Graph export session was redeeming token ${o.token}; resuming it with token ${a.token} would splice two exports`);let f=a.token??o.token;if(f!==void 0){o.token=f,yield*m(f);return}if(a.prefer===`async`){let n=await i(e,t,{mode:u.mode,...u.sinceGraphSeq===void 0?{}:{sinceGraphSeq:u.sinceGraphSeq},...u.atGraphSeq===void 0?{}:{atGraphSeq:u.atGraphSeq},...c?{signal:c}:{}});o.token=n.exportToken,yield*m(n.exportToken);return}let p=await r(tc(e,t,u),c);if(!p.body)throw new q(`truncated`);yield*Zs(p.body,o,d,{resumed:u.afterDurableId!==void 0});async function*m(e){for(let t=1;;t+=1){let n=await g(e);try{yield*h(n);return}catch(e){if(e instanceof q&&e.reason!==`truncated`||o.rowCount>0||t>=3||c?.aborted===!0)throw e}}}async function*h(e){let t=await n(e.url,c?{signal:c}:{});if(!t.ok||!t.body)throw await t.body?.cancel(),new q(`truncated`,`Graph export download returned HTTP ${t.status}`);yield*Zs(t.body,o,d,{resumed:!1}),cc(o,e)}async function g(n){let i=tc(e,t,{token:n});for(;;){let e=await r(i,c);if(e.status!==202)return await sc(e);await ic(rc(a.pollIntervalMs),c)}}}}const uc=`warmhub/streaming-submission-manifest/v1`,dc=new TextEncoder,fc=d.string().regex(/^sha256:[0-9a-f]{64}$/),pc={type:d.literal(`result`),chunkOrdinal:d.number().int().nonnegative(),opIndex:d.number().int().nonnegative(),submissionIndex:d.number().int().nonnegative(),name:d.string()},mc=d.enum(er),hc=d.enum([...er,`noop`]),gc=d.object({path:d.string(),message:d.string()}),_c=Si.loose().optional(),vc=d.object({added:d.array(d.string()),removed:d.array(d.string()),ignored:d.array(d.string())}),yc=d.discriminatedUnion(`reason`,[d.object({reason:d.literal(`expected_version_mismatch`),expectedVersion:d.number().int().positive(),currentVersion:d.number().int().positive()}),d.object({reason:d.literal(`lease_held`),leaseExpiresAt:d.iso.datetime()}),d.object({reason:d.literal(`validation_failed`),issues:d.array(gc)}),d.object({reason:d.literal(`rate_limit_reset`),retryAfterSeconds:d.number().int().positive(),resetAt:d.iso.datetime()}),d.object({reason:d.literal(`cursor_fence_unavailable`),cause:d.enum([`not_ready`,`below_floor`,`above_head`]),retryFromStart:d.literal(!0)})]),bc=d.discriminatedUnion(`reason`,[d.object({reason:d.literal(`expected_version_mismatch`),expectedVersion:d.number().int().nonnegative(),currentVersion:d.number().int().nonnegative()}).strict(),d.object({reason:d.literal(`lease_held`),leaseExpiresAt:d.iso.datetime()}).strict(),d.object({reason:d.literal(`validation_failed`),issues:d.array(gc.strict())}).strict(),d.object({reason:d.literal(`rate_limit_reset`),retryAfterSeconds:d.number().nonnegative(),resetAt:d.iso.datetime()}).strict(),d.object({reason:d.literal(`cursor_fence_unavailable`),cause:d.enum([`not_ready`,`below_floor`,`above_head`]),retryFromStart:d.literal(!0)}).strict(),d.object({reason:d.literal(`dependency_failed`),producerOpIndexes:d.array(d.number().int().nonnegative()).min(1)}).strict(),d.object({reason:d.literal(`name_taken`),name:d.string().min(1),takenBy:d.object({durableId:d.string().min(1)}).loose().optional()}).loose(),d.object({reason:d.literal(`target_removed`),targetDurableId:d.string().min(1),fieldPath:d.string().optional()}).loose(),d.object({reason:d.literal(`target_redacted`),targetDurableId:d.string().min(1),fieldPath:d.string().optional()}).loose(),d.object({reason:d.literal(`invalid_token`)}).loose()]),xc={...pc,operation:mc,submittedName:d.string().optional(),resolvedName:d.string().optional(),warnings:_c,affirmations:vc.optional()},Sc=d.union([d.looseObject({...pc,operation:hc.optional(),version:d.number().optional(),dataHash:d.string().optional(),status:d.enum([`success`,`noop`,`failed`]).optional(),error:d.object({code:d.string(),message:d.string(),details:yc.optional()}).optional(),resolvedName:d.string().optional(),retryable:d.boolean().optional(),warnings:_c,affirmations:vc.optional()}),d.looseObject({...xc,status:d.enum([`applied`,`noop`]),version:d.number().int().positive().optional(),dataHash:d.string().min(1).optional()}),d.looseObject({...xc,status:d.literal(`error`),errors:d.array(d.object({code:d.string().min(1),message:d.string(),path:d.string().min(1).optional(),details:bc.optional(),retryable:d.boolean().optional()}).strict()).min(1)})]),Cc=d.object({applied:d.number().int().nonnegative(),noop:d.number().int().nonnegative(),failed:d.number().int().nonnegative()}),wc=d.looseObject({type:d.literal(`group`),chunkOrdinal:d.number().int().nonnegative(),eventRequestId:d.uuid(),requestDigest:fc,outcome:d.enum([`event`,`no_event`]),graphSeq:d.number().int().nonnegative().optional(),operations:Cc,manifestDigest:fc}),Tc=d.looseObject({type:d.literal(`summary`),submissionId:d.uuid(),streamId:d.string().min(1),groupSize:d.number().int().positive(),groups:d.number().int().nonnegative(),operations:Cc.extend({total:d.number().int().nonnegative()}),graphSeq:d.object({first:d.number().int().nonnegative().nullable(),last:d.number().int().nonnegative().nullable()}),verdict:d.string().min(1),durationMs:d.number().nonnegative(),truncatedAt:d.object({lineNumber:d.number().int().positive(),message:d.string()}).optional(),manifest:d.object({groups:d.number().int().nonnegative(),digest:fc})}),Ec=d.looseObject({type:d.literal(`error`),code:d.string().min(1),message:d.string().optional()}),Dc=d.union([Sc,wc,Tc,Ec]),Oc=()=>({applied:0,noop:0,failed:0}),kc=(e,t)=>e.applied===t.applied&&e.noop===t.noop&&e.failed===t.failed,Ac=/* @__PURE__ */ new Set([`complete`,`operation-limit-reached`,`group-limit-reached`]);var J=class extends Error{rowIndex;constructor(e,t){super(`Streaming submission protocol error at row ${t}: ${e}`),this.rowIndex=t,this.name=`StreamingSubmissionProtocolError`}};async function jc(e){let t=dc.encode(e),n=await globalThis.crypto.subtle.digest(`SHA-256`,t);return`sha256:${Array.from(new Uint8Array(n),e=>e.toString(16).padStart(2,`0`)).join(``)}`}async function Mc(e,t,n){return jc(`${uc}\0${e}\0${t}\0${n}`)}function Nc(e){return e.status===`error`?`failed`:e.status===`noop`?`noop`:`applied`}var Pc=class{index=0;groupCount=0;resultCount=0;pendingCount=0;pendingCounts=Oc();totalCounts=Oc();firstGraphSeq=null;lastGraphSeq=null;manifestDigest=jc(uc);terminalSeen=!1;accept(e){let t=e=>{throw new J(e,this.index)};if(this.terminalSeen&&t(`No row may follow the terminal row`),e.type===`result`){e.chunkOrdinal!==this.groupCount&&t(`Expected result chunkOrdinal ${this.groupCount}`),e.opIndex!==this.pendingCount&&t(`Expected result opIndex ${this.pendingCount}`),e.submissionIndex!==this.resultCount&&t(`Expected submissionIndex ${this.resultCount}`);let n=Nc(e);this.pendingCounts[n]+=1,this.totalCounts[n]+=1,this.pendingCount+=1,this.resultCount+=1,this.index+=1}else{if(e.type===`group`)return e.chunkOrdinal!==this.groupCount&&t(`Expected group chunkOrdinal ${this.groupCount}`),this.pendingCount===0&&t(`A group must close result rows`),kc(this.pendingCounts,e.operations)||t(`Group operation counters do not match its result rows`),this.acceptGroup(e,t);if(this.terminalSeen=!0,this.pendingCount>0&&t(`Terminal row cannot close a partial group`),e.type===`summary`)return this.acceptSummary(e,t);this.index+=1}}async acceptGroup(e,t){this.manifestDigest=this.manifestDigest.then(t=>Mc(t,e.chunkOrdinal,e.requestDigest)),e.manifestDigest!==await this.manifestDigest&&t(`Group manifest digest does not match the receipt chain`),e.graphSeq!==void 0&&(this.firstGraphSeq??=e.graphSeq,this.lastGraphSeq=e.graphSeq),this.groupCount+=1,this.pendingCount=0,this.pendingCounts=Oc(),this.index+=1}async acceptSummary(e,t){kc(this.totalCounts,e.operations)||t(`Summary operation counters do not match result rows`),(e.groups!==this.groupCount||e.manifest.groups!==this.groupCount)&&t(`Summary group counters do not match group rows`),e.manifest.digest!==await this.manifestDigest&&t(`Summary manifest digest does not match the receipt chain`),(e.graphSeq.first!==this.firstGraphSeq||e.graphSeq.last!==this.lastGraphSeq)&&t(`Summary graph sequence does not match group rows`),(Ac.has(e.verdict)?e.operations.total!==this.resultCount:e.operations.total<this.resultCount)&&t(`Summary total is incompatible with its verdict`),e.verdict===`truncated-by-parse-error`!=(e.truncatedAt!==void 0)&&t(`truncatedAt must appear only for a parse-truncated verdict`),this.index+=1}finish(){if(!this.terminalSeen)throw new J(`Response must end with a summary or error row`,this.index)}};function Fc(e,t){let n;try{n=JSON.parse(e)}catch(e){throw new J(e instanceof Error?e.message:`Invalid JSON`,t)}let r=Dc.safeParse(n);if(!r.success)throw new J(r.error.issues[0]?.message??`Malformed row`,t);return r.data}async function*Ic(e,t){let n=e.body?.getReader();if(!n)throw new J(`Missing response body`,0);let r=new Pc,i=new TextDecoder,a=``,o=0,s=!1,c,l=e=>{if(e.endsWith(`\r`)&&(e=e.slice(0,-1)),e.length===0)throw new J(`Blank response row`,o);let t=Fc(e,o);return{pending:r.accept(t),row:t}},u=e=>{if(e.type===`summary`&&t!==void 0&&(e.submissionId!==t.submissionId||e.streamId!==t.streamId||e.groupSize!==t.groupSize))throw new J(`Summary identity does not match the submission handle`,o);o+=1};try{for(;;){let{done:e,value:t}=await n.read();if(e)break;for(a+=i.decode(t,{stream:!0});;){let e=a.indexOf(`
30
- `);if(e===-1)break;let t=a.slice(0,e);a=a.slice(e+1);let{pending:n,row:r}=l(t);n&&await n,u(r),r.type===`summary`||r.type===`error`?c=r:yield r}}if(a+=i.decode(),a.length>0){let{pending:e,row:t}=l(a);e&&await e,u(t),t.type===`summary`||t.type===`error`?c=t:yield t}r.finish(),s=!0,c&&(yield c)}finally{if(!s)try{await n.cancel()}catch{}n.releaseLock()}}var Lc=class extends Error{code=`STREAMING_SUBMISSION_OUTCOME_UNKNOWN`;outcome=`unknown`;retryable=!1;retryIdentity;cause;constructor(e,t){super(`Streaming submission outcome is unknown for ${e.submissionId}. Reconstruct the original source and copy every retryIdentity field into the next applyStreaming call.`),this.name=`StreamingSubmissionOutcomeUnknownError`,this.retryIdentity=e,this.cause=t}};function Rc(e){return e===void 0||e===``?void 0:e}function zc(){let e=globalThis;if(e.Bun!==void 0)return!0;let t=e.process?.versions?.node;if(!t)return!1;let[n=0,r=0]=t.split(`.`).map(Number);return n>22||n===22&&r>=2}function Bc(e){let t=new URLSearchParams({submissionId:e.submissionId,groupSize:String(e.groupSize)});return e.message!==void 0&&t.set(`message`,e.message),e.committer!==void 0&&t.set(`committer`,e.committer),`/api/graphs/${encodeURIComponent(e.orgName)}/${encodeURIComponent(e.graphName)}/streams/${encodeURIComponent(e.streamId)}/submissions?${t}`}function Vc(e,t,n){let r=Ds(e,!1),i=To(n),a=0,o=!1,s=async e=>{try{await e}catch{}},c=()=>{if(!o){o=!0;try{let e=r.returnSourceOnce();e&&s(e)}catch{}}};return{stream:new ReadableStream({async pull(e){try{let n=[],s=a,c=!1;for(;;){let l=await r.next();if(o)return;if(!(!l.done&&(n.push(l.value),a+=1,c||=oo(l.value),c&&a%t!==0))){for(let t of await i(n,s))e.enqueue(Os(t));l.done&&e.close();return}}}catch(t){e.error(t),c()}},cancel(){c()}}),returnSourceOnce:c}}function Hc(e,t){if(!e)return()=>void 0;let n=()=>t.abort(e.reason);return e.aborted?n():e.addEventListener(`abort`,n,{once:!0}),()=>e.removeEventListener(`abort`,n)}function Uc(e){let t=e.options?.submissionId??Zo();return{orgName:e.orgName,graphName:e.graphName,streamId:e.options.streamId,submissionId:t,groupSize:js(e.options.groupSize),...Rc(e.message)===void 0?{}:{message:Rc(e.message)},...Rc(e.options?.committer)===void 0?{}:{committer:Rc(e.options?.committer)}}}function Wc(e,t){if(!e.options.streamId)throw t.localError(`VALIDATION_ERROR`,`Streaming submissions require a non-empty streamId.`);let n=Uc(e),r=new AbortController,i=()=>void 0,a,o=!1,s=async function*(){let a=!1,s=!1,c;try{if(!(t.runtimeSupported??zc)())throw t.localError(`VALIDATION_ERROR`,`Streaming submissions require Bun or Node.js 22.2 or newer.`);if(i=Hc(e.options.signal,r),r.signal.aborted)throw t.localError(`CANCELLED`,`Streaming submission was aborted.`);let o=await t.prepare(Bc(n));if(r.signal.aborted)throw t.localError(`CANCELLED`,`Streaming submission was aborted.`);c=Vc(e.operations,n.groupSize,t.readThings),a=!0;let l=await o.dispatch(c.stream,r.signal);if(!l.ok)throw s=!0,await o.httpError(l);for await(let e of Ic(l,n))yield e}catch(e){throw e instanceof Lc?e:a&&!s?new Lc(n,e):t.normalizeLocalError(e)}finally{r.abort(),c?.returnSourceOnce(),i(),o=!0}};return{retryIdentity:n,[Symbol.asyncIterator](){return this},next(){return o?Promise.resolve({done:!0,value:void 0}):(a??=s(),a.next())},async return(e){return r.abort(),a?a.return(e):(o=!0,i(),{done:!0,value:e})},async throw(e){if(r.abort(e),!a)throw o=!0,i(),e;return a.throw(e)}}}function Gc(e){return e===`0.0.0-development`}const Kc=`0.163.1`;function qc(e){return e===`warmhub-cli`?`Run: wh update --yes`:e===`@warmhub/sdk-ts`?`Run: npm install @warmhub/sdk-ts@latest (or your package manager's equivalent).`:e===`warmhub-sdk-py`?`Run: pip install --upgrade warmhub`:`Deploy a released ${e} build that satisfies the backend compatibility contract.`}function Jc(e,t){if(typeof e?.minSupportedClients!=`object`||e.minSupportedClients===null||!Number.isSafeInteger(e.writeContractVersion)||e.writeContractVersion<1)return{message:`The backend does not advertise valid per-client write compatibility data.`,hint:`Upgrade the WarmHub backend before retrying this write.`};let n=e.minSupportedClients[t.name],r=typeof n==`string`?Er(n):null;if(!r)return{message:`The backend does not advertise a valid compatibility floor for ${t.name}.`,hint:`Upgrade the WarmHub backend or register this first-party client family before writing.`};if(!Gc(t.version)){let e=Er(t.version);if(!e)return{message:`${t.name} reported malformed version "${t.version}".`,hint:`Use a released WarmHub client with a SemVer package version.`};if(Ar(e,r)<0)return{message:`${t.name} ${t.version} is older than the backend's minimum supported version ${r}.`,hint:qc(t.name)}}if(e.writeContractVersion<5)return{message:`${t.name} requires write contract 5, but the backend provides ${e.writeContractVersion}.`,hint:`Upgrade the WarmHub backend before retrying this write.`}}function Yc(e,t){try{return new URL(e).origin===new URL(t).origin}catch{return!1}}const Xc=/* @__PURE__ */ new Set([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`]);var Y=class extends Error{reason;constructor(e,t){super(t),this.name=`CliCallVerificationError`,this.reason=e}};async function Zc(e,t,n){let r=e.method.toUpperCase();if(!Xc.has(r))throw new Y(`unsupported-method`,`Unsupported HTTP method "${e.method}" — component CLI dispatch only emits GET, POST, PUT, or PATCH`);let i=r,a=e.headers.get(rr);if(!a)throw new Y(`missing-install-repo`,`Missing ${rr} header`);let o=X(t.CLI_SIGNING_SECRET),s=X(t.CLI_BEARER_TOKEN),c=X(t.CLI_API_KEY),l=X(t.CLI_BASIC_USERNAME)&&X(t.CLI_BASIC_PASSWORD);if(!o&&!s&&!c&&!l)throw new Y(`no-scheme-configured`,`no-scheme-configured: need at least one of CLI_SIGNING_SECRET, CLI_BEARER_TOKEN, CLI_API_KEY, or CLI_BASIC_USERNAME + CLI_BASIC_PASSWORD`);if(s&&l)throw new Y(`no-scheme-configured`,`unsupported-scheme-combination: CLI_BEARER_TOKEN and CLI_BASIC_USERNAME + CLI_BASIC_PASSWORD both use the Authorization header and cannot be configured together`);let u=new URL(e.url),d=u.pathname,f,p,m;if(lr(i)?f={}:(f=Object.fromEntries(u.searchParams.entries()),p=``,m={...f}),o){let r=e.headers.get(ir);if(!r)throw new Y(`missing-signature`,`Missing ${ir} header`);let o=e.headers.get(ar);if(!o)throw new Y(`missing-timestamp`,`Missing ${ar} header`);let s=Number(o);if(!Number.isFinite(s)||!Number.isInteger(s))throw new Y(`invalid-timestamp`,`${ar} must be an integer unix seconds value; got "${o}"`);p=await Qc(e,i,p);let c=await gr({secret:t.CLI_SIGNING_SECRET,method:i,path:d,query:f,installRepo:a,body:p,signature:r,timestamp:s,nowUnixSeconds:n?.nowUnixSeconds??Math.floor(Date.now()/1e3),toleranceSec:n?.toleranceSec});if(!c.ok)throw new Y(c.reason,`HMAC verification failed: ${c.reason}`)}if(s){let n=`Bearer ${t.CLI_BEARER_TOKEN}`;if(!await tl(e.headers.get(`authorization`)??``,n))throw new Y(`invalid-bearer`,`invalid-bearer: bearer token mismatch`)}if(c){let n=X(t.CLI_API_KEY_HEADER)?t.CLI_API_KEY_HEADER:`X-API-Key`;if(!await tl(e.headers.get(n)??``,t.CLI_API_KEY))throw new Y(`invalid-api-key`,`invalid-api-key: mismatch on header "${n}"`)}if(l){let n=`Basic ${btoa(`${t.CLI_BASIC_USERNAME}:${t.CLI_BASIC_PASSWORD}`)}`;if(!await tl(e.headers.get(`authorization`)??``,n))throw new Y(`invalid-basic`,`invalid-basic: basic auth mismatch`)}return m===void 0&&(p=await Qc(e,i,p),m=$c(p)),{method:i,installRepo:a,args:m}}async function Qc(e,t,n){return lr(t)?n===void 0?e.text():n:``}function $c(e){let t;try{t=JSON.parse(e)}catch{throw new Y(`invalid-body`,`POST body is not valid JSON`)}if(!el(t))throw new Y(`invalid-body`,`POST body must be a JSON object of primitive args (string / number / boolean)`);return t}function X(e){return typeof e==`string`&&e.length>0}function el(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;for(let t of Object.values(e))if(t!==void 0&&typeof t!=`string`&&typeof t!=`number`&&typeof t!=`boolean`)return!1;return!0}async function tl(e,t){let[n,r]=await Promise.all([nl(e),nl(t)]),i=0;for(let e=0;e<n.length;e++)i|=n[e]^r[e];return i===0}async function nl(e){return new Uint8Array(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e)))}const rl=q,il=Rs,al=(...e)=>(r(`applyRepositoryExportDelta`,`applyGraphExportDelta`),Us(...e)),ol=(...e)=>(r(`createRepositoryExportSession`,`createGraphExportSession`),zs(...e)),sl=(...e)=>(r(`readRepositoryExportStream`,`readGraphExportStream`),Zs(...e)),cl=(...e)=>(r(`restoreRepositoryExportSession`,`restoreGraphExportSession`),Qs(...e));function ll(e){return Se(e)}const ul=Object.keys({apiUrl:!0,fetch:!0,accessToken:!0,auth:!0,functionLogs:!0,client:!0,clientFlags:!0,decorateResponses:!0}),dl=new Set(ul),fl=/* @__PURE__ */ new Set([`token`,`apiKey`,`bearer`]);function pl(e){if(e)for(let t of Object.keys(e)){if(dl.has(t))continue;let e=fl.has(t)?`; did you mean "accessToken"?`:`. Valid options are: ${ul.join(`, `)}.`;throw TypeError(`Unknown WarmHubClient option "${t}"${e}`)}}function ml(e){if(!e||e.length===0)return[];for(let t of e)if(!Kn(t))throw TypeError(`Invalid client flag "${t}": expected lowercase tokens matching [a-z0-9-]+.`);return[...new Set(e)].sort()}const hl=`https://api.warmhub.ai`,gl=/* @__PURE__ */ new Set([`commit.validate`,`graph.shapeInstanceCounts`,`thing.getMany`,`thing.headVersions`,`thing.names`]);function _l(e){return{...e,actionContainer:void 0,actionContainerConfig:void 0}}function vl(e){return e.map(e=>_l(e))}function yl(e,t,n){if(t===e||n.has(t))throw new G(`VALIDATION_ERROR`,`Paginated result cursor did not advance`)}function bl(e){if(e===void 0)throw new G(`VALIDATION_ERROR`,`sinceGraphSeq is required for an incremental read`)}async function*xl(e,t){let n=t,r=/* @__PURE__ */ new Set;for(;;){n&&r.add(n);let t=await e(n);if(yield t,!t.nextCursor)return;yl(n,t.nextCursor,r),n=t.nextCursor}}async function*Z(e,t,n){for await(let r of xl(e,n))yield*t(r)}async function Q(e,t,n,r){if(n!==void 0&&(!Number.isFinite(n)||Math.trunc(n)!==n||n<0))throw new G(`VALIDATION_ERROR`,`max must be a nonnegative integer`);let i=[];for await(let a of xl(e,r)){let e=t(a);if(n!==void 0&&i.length+e.length>n)throw new G(`VALIDATION_ERROR`,`Paginated result exceeded max=${n}`);i.push(...e)}return i}function Sl(e){if(e?.slugs!==void 0)throw new G(`VALIDATION_ERROR`,`graph.explore pagination helpers do not support slugs mode`)}async function Cl(e){let t=[],n,r=/* @__PURE__ */ new Set;for(;;){n&&r.add(n);let i=await e(n);if(t.push(...i.items),!i.nextCursor){if(i.graphSeq===void 0)throw new G(`VALIDATION_ERROR`,`Incremental read completed without graphSeq`);return{items:t,graphSeq:i.graphSeq}}yl(n,i.nextCursor,r),n=i.nextCursor}}function wl(e,t,n){return Number.isFinite(e)?Math.max(1,Math.min(n,Math.trunc(e))):t}function Tl(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}async function El(e,t,n){if(e.length===0)return{requested:0,items:[],missing:[]};let r=wl(t?.chunkSize,500,500),i=wl(t?.chunkConcurrency,1,8);if(e.length<=r)return await n(e);let a=Tl(e,r),o=[];for(let e=0;e<a.length;e+=i){let t=a.slice(e,e+i),r=await Promise.all(t.map(n));o.push(...r)}return{requested:e.length,items:o.flatMap(e=>e.items),missing:o.flatMap(e=>e.missing)}}function Dl(e){return e!==void 0&&tr.includes(e)?e:void 0}function Ol(e){let t=e;if(t.graphName!==void 0)return t;let{graphName:n,...r}=t;return r}function kl(e){let[t,n,r]=e;return Ol(typeof t==`string`?{orgName:t,graphName:n,name:r}:t)}function Al(e){let[t,n]=e;return Ol(typeof t==`string`?{orgName:t,graphName:n}:t)}function jl(e){let[t,n,r,i]=e;return Ol(typeof t==`string`?{orgName:t,graphName:n,subscriptionName:r,credentialSetName:i}:t)}function Ml(e){let[t,n,r]=e;return Ol(typeof t==`string`?{orgName:t,graphName:n,subscriptionName:r}:t)}function Nl(e){let{actionContainer:t,actionContainerConfig:n,...r}=e;return r}function Pl(e){let{actionContainer:t,actionContainerConfig:n,...r}=e;return r}function Fl(e){return!!e&&(!!e.shape||!!e.kind||!!e.about||!!e.match||!!e.componentRef||e.excludeComponents===!0||(e.where?.length??0)>0)}function Il(e){return!!e&&(!!e.shape||!!e.about||!!e.match||!!e.componentRef||(e.where?.length??0)>0)}function Ll(e){let t=e.members;return Array.isArray(t)&&t.length>0}function Rl(e,t){if(e!==`set`&&e!==`list`)throw new G(`VALIDATION_ERROR`,ki(String(e)));if(Fl(t.query)&&!Il(t.query))throw new G(`VALIDATION_ERROR`,`Selector-backed collection sources require shape, about, match, componentRef, or where; kind and excludeComponents only narrow an existing selector.`);if(t.sourceGraph&&!Il(t.query))throw new G(`VALIDATION_ERROR`,`sourceGraph requires a selector-backed collection query`);if(t.sourceGraph&&Ll(t))throw new G(`VALIDATION_ERROR`,`sourceGraph cannot be combined with explicit members; use canonical wh:org/graph/... member wrefs or omit sourceGraph.`);if(Fl(t.query)&&e!==`set`)throw new G(`VALIDATION_ERROR`,`Selector-backed collection sources are only supported for set collections`)}function zl(e){return e??`off`}function Bl(e){if(e!==void 0)switch(e){case`BAD_REQUEST`:case`PARSE_ERROR`:case`PAYLOAD_TOO_LARGE`:case`UNPROCESSABLE_CONTENT`:case`UNSUPPORTED_MEDIA_TYPE`:return`VALIDATION_ERROR`;case`METHOD_NOT_SUPPORTED`:return`NOT_FOUND`;case`UNAUTHORIZED`:return`UNAUTHENTICATED`;case`FORBIDDEN`:return`FORBIDDEN`;case`NOT_FOUND`:return`NOT_FOUND`;case`CONFLICT`:return`CONFLICT`;case`PRECONDITION_FAILED`:return`PRECONDITION_FAILED`;case`TOO_MANY_REQUESTS`:return`RATE_LIMITED`;default:return}}function Vl(e){if(e===void 0||e===408)return;if(e===405)return`NOT_FOUND`;if(e===412)return`PRECONDITION_FAILED`;if(e===422)return`VALIDATION_ERROR`;let t=iu(e);return t===`BACKEND`&&e>=400&&e<500?`VALIDATION_ERROR`:t}const Hl=[/\bselect\b.+?\bfrom\b/i,/\binsert\b.+?\binto\b/i,/\bupdate\b.+?\bset\b/i,/\bdelete\b.+?\bfrom\b/i,/\bparams:\s/i,/\.ts\(\d+,\d+\)/,/at\s+\S+\s+\(.*:\d+:\d+\)/,/node_modules\//,/drizzle/i];function Ul(e){for(let t of Hl)if(t.test(e))return`An internal error occurred. Please try again or contact support.`;return e}function Wl(e,t){if(typeof t!=`string`)return;let n=on(e,t);if(n)throw new G(`VALIDATION_ERROR`,n)}function $(e){if(e instanceof G)return e;if(e instanceof a){if(e.cause instanceof G)return e.cause;let t=e.data,n=t?.warmhub?.code,r=typeof t?.code==`string`?Bl(t.code):void 0,i=Vl(t?.httpStatus),a=t?.warmhub?.message??Ul(e.message);return new G(n??r??i??`BACKEND`,a,t?.warmhub?.status??t?.httpStatus,t?.warmhub?.hint,t?.warmhub?.retryAfter??t?.retryAfter,n,t?.warmhub?.details)}if(e instanceof Error){let t=e;if(e.name===`WarmHubError`&&typeof t.code==`string`){let n=new G(t.code,Ul(e.message),typeof t.status==`number`?t.status:void 0,typeof t.hint==`string`?t.hint:void 0,typeof t.retryAfter==`number`?t.retryAfter:void 0,typeof t.errorCode==`string`?t.errorCode:typeof t.backendCode==`string`?t.backendCode:void 0,t.details);return Kl(e)&&Object.defineProperty(n,Gl,{value:!0}),n}return e.name===`AbortError`?new G(`CANCELLED`,e.message):e instanceof TypeError&&/fetch/i.test(e.message)?new G(`NETWORK`,e.message):new G(`BACKEND`,Ul(e.message))}return new G(`BACKEND`,`Unknown SDK error`)}const Gl=Symbol.for(`@warmhub/sdk-ts:allStreamOperationsFailed`);function Kl(e){if(e instanceof ns)return!0;if(!(e instanceof Error))return!1;let t=e;return t[Gl]===!0||t.name===`WarmHubError`&&Array.isArray(t.receipts)&&Array.isArray(t.operations)}function ql(e){return Kl(e)}function Jl(e){return e instanceof G}function Yl(e){if(e instanceof Lc||Kl(e))return!1;let t=$(e);return t.kind===`NETWORK`||t.kind===`CANCELLED`||t.kind===`BACKEND`||t.kind===`RATE_LIMITED`}const Xl=/* @__PURE__ */ new Set([`ConnectionRefused`,`ECONNREFUSED`,`ENOTFOUND`,`ETIMEDOUT`,`EAI_AGAIN`]);function Zl(e){if(e instanceof TypeError&&/fetch/i.test(e.message))return!0;if(e&&typeof e==`object`){let t=e.code;if(typeof t==`string`&&Xl.has(t))return!0}return!1}function Ql(e){return`Unable to connect to ${e}. Is the computer able to access the url?`}function $l(e,t){if(Gc(e))return!1;let n=Er(e),r=Er(t);return!n||!r?!1:Ar(n,r)<0}function eu(e,t){return new G(`CLIENT_INCOMPATIBLE`,e,412,t)}function tu(e,t){let n=Jc(e,t);if(n)throw eu(n.message,n.hint)}function nu(e,t){if(e===`thing.rename`&&typeof t?.eventRequestId!=`string`)return new G(`VALIDATION_ERROR`,`thing.rename takes (orgName, graphName, name, newName, { eventRequestId }): name and newName are full Thing names. The v1 order (orgName, graphName, shapeName, oldName, newName, opts) is gone.`)}var ru=class e{apiUrl;fetchImpl;accessToken;clientIdentity;#e;decorateResponses;functionLogMode;getToken;compatibilityCheck;overrideNoticePrinted=!1;compatibilityNoticesPrinted=/* @__PURE__ */ new Set;graphExport=lc((e,t)=>this.fetchWithAuth(`${this.apiUrl.replace(/\/$/,``)}${e}`,t),e=>this.httpResponseError(e),(e,t)=>(this.fetchImpl??globalThis.fetch)(e,t));noteCompatibilityHeaders(e){let t=[],n=e.get(`X-WarmHub-Client-Minimum`);if(n){let{name:e,version:r}=this.clientIdentity;t.push(`${e} ${r} is older than the backend's minimum supported version ${n}. ${qc(e)}`)}let r=e.get(`X-WarmHub-Client-Flags-Honored`);if(r!==null){let e=new Set(r.split(`,`));for(let n of this.clientFlags)e.has(n)||t.push(`client flag "${n}" is not honored by this backend`)}for(let e of t)this.compatibilityNoticesPrinted.has(e)||(this.compatibilityNoticesPrinted.add(e),console.error(`warmhub: ${e}`))}noteCompatibilityOverride(){this.overrideNoticePrinted||(this.overrideNoticePrinted=!0,console.error(`warmhub: compatibility checks overridden by client flag compatibility-override; the server remains authoritative.`))}assertWriteCompatible(){return this.clientFlags.includes(`compatibility-override`)?(this.noteCompatibilityOverride(),Promise.resolve()):Gc(this.clientIdentity.version)&&Yc(this.apiUrl,`https://api.warmhub.ai`)?Promise.reject(eu(`Development client ${this.clientIdentity.name}/${this.clientIdentity.version} cannot write to production.`,`Install a released WarmHub client artifact before writing to api.warmhub.ai.`)):Gc(this.clientIdentity.version)&&this.clientIdentity.name!==`warmhub-cli`?Promise.resolve():this.diagnostics.assertCompatible()}pinnedShapeRefusal(e,t){if(e!==`stream.append`)return;let n=t?.operations;if(!Array.isArray(n))return;let r=n.findIndex(e=>Array.isArray(e?.shapes)&&e.shapes.some(e=>typeof e==`string`&&_o(e)));return r<0?void 0:new K(r,fo)}createLocalRefusalLink(){return()=>({op:e,next:t})=>{let n=nu(e.path,e.input)??this.pinnedShapeRefusal(e.path,e.input);return n?u(e=>{e.error(a.from(n))}):t(e)}}createCompatibilityLink(){return()=>({op:e,next:t})=>e.type!==`mutation`||Zn.has(e.path)?t(e):u(n=>{let r=!1,i;return(async()=>{try{await this.assertWriteCompatible()}catch(e){if(r)return;n.error(a.from(e));return}r||(i=t(e).subscribe(n))})(),()=>{r=!0,i?.unsubscribe()}})}auth={getClientId:async()=>{try{return await this.trpc.auth.getClientId.query()}catch(e){throw $(e)}},sync:async()=>{try{return await this.trpc.auth.sync.mutate()}catch(e){throw $(e)}},currentUser:async()=>{try{return await this.trpc.auth.currentUser.query()}catch(e){throw $(e)}},whoami:async()=>{try{return await this.trpc.auth.whoami.query()}catch(e){throw $(e)}}};homepage={featuredLists:async()=>{try{return await this.trpc.homepage.featuredLists.query()}catch(e){throw $(e)}}};access={resolve:async e=>{try{return await this.trpc.access.resolve.query(e)}catch(e){throw $(e)}}};diagnostics={ping:async()=>{let e=await this.fetchWithAuth(`${this.apiUrl.replace(/\/$/,``)}/health`);if(!e.ok)throw new G(`BACKEND`,`Health request failed with status ${e.status}`,e.status);return await e.json()},capabilities:async()=>{try{return await this.trpc.diagnostics.capabilities.query()}catch(e){throw $(e)}},assertCompatible:()=>{if(this.compatibilityCheck)return this.compatibilityCheck;let e=(async()=>{tu(await this.diagnostics.capabilities(),this.clientIdentity)})();return this.compatibilityCheck=e,e.catch(t=>{Jl(t)&&t.code===`CLIENT_INCOMPATIBLE`||this.compatibilityCheck===e&&(this.compatibilityCheck=void 0)}),e}};component={list:async(e,t,n)=>{try{return await this.trpc.component.list.query({orgName:e,graphName:t,limit:n?.limit,cursor:n?.cursor})}catch(e){throw $(e)}},listIter:(e,t,n)=>Z(r=>this.component.list(e,t,{...n,cursor:r}),e=>e.items,n?.cursor),listAll:async(e,t,n)=>{let{max:r,...i}=n??{};return await Q(n=>this.component.list(e,t,{...i,cursor:n}),e=>e.items,r,i.cursor)},search:async(e,t)=>{try{return await this.trpc.component.search.query({query:e,limit:t?.limit,cursor:t?.cursor})}catch(e){throw $(e)}},searchIter:(e,t)=>Z(n=>this.component.search(e,{...t,cursor:n}),e=>e.items,t?.cursor),searchAll:async(e,t)=>{let{max:n,...r}=t??{};return await Q(t=>this.component.search(e,{...r,cursor:t}),e=>e.items,n,r.cursor)},get:async(e,t,n)=>{try{return await this.trpc.component.get.query({orgName:e,graphName:t,componentRef:n})}catch(e){throw $(e)}},history:async(e,t,n)=>{try{return await this.trpc.component.history.query({orgName:e,graphName:t,componentRef:n?.componentRef,limit:n?.limit})}catch(e){throw $(e)}},install:async(e,t,n,r)=>{try{return await this.trpc.component.install.mutate({orgName:e,graphName:t,componentRef:n,submissionId:r.submissionId})}catch(e){throw $(e)}},uninstall:async(e,t,n,r)=>{try{return await this.trpc.component.uninstall.mutate({orgName:e,graphName:t,componentRef:n,submissionId:r.submissionId})}catch(e){throw $(e)}},registry:{register:async(e,t,n)=>{try{return await this.trpc.component.registry.register.mutate({orgName:e,componentName:t,...n})}catch(e){throw $(e)}},unregister:async(e,t)=>{try{return await this.trpc.component.registry.unregister.mutate({orgName:e,componentName:t})}catch(e){throw $(e)}},list:async e=>{try{return await this.trpc.component.registry.list.query({orgName:e})}catch(e){throw $(e)}},view:async(e,t)=>{try{return await this.trpc.component.registry.view.query({orgName:e,componentName:t})}catch(e){throw $(e)}},update:async(e,t,n)=>{try{return await this.trpc.component.registry.update.mutate({orgName:e,componentName:t,...n})}catch(e){throw $(e)}},resolve:async(e,t,n)=>await this.requestJson(`/api/component-registry/${encodeURIComponent(e)}/${encodeURIComponent(t)}/resolve`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({installRepo:n})}),setupCall:async(e,t,n)=>(await this.assertWriteCompatible(),await this.requestJson(`/api/component-registry/${encodeURIComponent(e)}/${encodeURIComponent(t)}/setup-call`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(n)}))},cli:{call:async(e,t,n,r)=>(await this.assertWriteCompatible(),await this.requestJson(`/api/component-registry/${encodeURIComponent(e)}/${encodeURIComponent(t)}/cli/${encodeURIComponent(n)}`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(r)}))}};ops(e){return new Ms(e)}commit={validate:async(e,t,n,r)=>{try{return await Ro(this.trpc.commit.validate,this.thingShapesReader(e,t),e,t,n,r)}catch(e){throw $(e)}},apply:async(e,t,n,r,i)=>{try{return await xs(this,{orgName:e,graphName:t,committer:i?.committer,message:n,componentRef:i?.componentRef,chunkSize:i?.chunkSize,skipExisting:i?.skipExisting,streamId:i?.streamId,submissionId:i?.submissionId,returnGraphSeq:i?.returnGraphSeq,retry:i?.retry,operations:r})}catch(e){throw e instanceof ts||e instanceof ns?e:$(e)}},applyStreaming:(e,t,n,r,i)=>Wc({orgName:e,graphName:t,message:n,operations:r,options:i},{prepare:async e=>await this.prepareStreamingSubmissionRequest(e),localError:(e,t)=>new G(e,t),normalizeLocalError:$,readThings:this.thingShapesReader(e,t)}),getReceipt:async(e,t,n)=>{try{return await this.trpc.commit.getReceipt.query({orgName:e,graphName:t,eventRequestId:n})}catch(e){throw $(e)}},getReceiptMetadata:async(e,t,n)=>{try{return await this.trpc.commit.getReceiptMetadata.query({orgName:e,graphName:t,eventRequestId:n})}catch(e){throw $(e)}}};org={get:async e=>{try{return await this.trpc.org.get.query({orgName:e})}catch(e){throw $(e)}},getCallerRole:async e=>{try{return await this.trpc.org.getCallerRole.query({orgName:e})}catch(e){throw $(e)}},list:async e=>{try{return{items:await this.trpc.org.list.query({includeArchived:e?.includeArchived})}}catch(e){throw $(e)}},create:async(e,t,n)=>{try{return await this.trpc.org.create.mutate({name:e,displayName:t,description:n})}catch(e){throw $(e)}},setDescription:async(e,t)=>{try{return await this.trpc.org.setDescription.mutate({orgName:e,description:t})}catch(e){throw $(e)}},setDisplayName:async(e,t)=>{try{return await this.trpc.org.setDisplayName.mutate({orgName:e,displayName:t})}catch(e){throw $(e)}},rename:async(e,t)=>{try{return await this.trpc.org.rename.mutate({orgName:e,newName:t})}catch(e){throw $(e)}},update:async e=>{try{return await this.trpc.org.update.mutate(e)}catch(e){throw $(e)}},addMember:async(e,t,n=`editor`)=>{try{return await this.trpc.org.addMember.mutate({orgName:e,email:t,role:n})}catch(e){throw $(e)}},removeMember:async(e,t)=>{try{await this.trpc.org.removeMember.mutate({orgName:e,email:t})}catch(e){throw $(e)}},leave:async e=>{try{await this.trpc.org.leave.mutate({orgName:e})}catch(e){throw $(e)}},changeMemberRole:async(e,t,n)=>{try{return await this.trpc.org.changeMemberRole.mutate({orgName:e,email:t,role:n})}catch(e){throw $(e)}},setMemberScopes:async(e,t,n)=>{try{await this.trpc.org.setMemberScopes.mutate({orgName:e,email:t,scopes:n})}catch(e){throw $(e)}},clearMemberScopes:async(e,t)=>{try{await this.trpc.org.clearMemberScopes.mutate({orgName:e,email:t})}catch(e){throw $(e)}},listMembers:async(e,t)=>{try{return await this.trpc.org.listMembers.query({orgName:e,pending:t?.pending})}catch(e){throw $(e)}},archive:async e=>{try{return await this.trpc.org.archive.mutate({orgName:e})}catch(e){throw $(e)}},unarchive:async e=>{try{return await this.trpc.org.unarchive.mutate({orgName:e})}catch(e){throw $(e)}},serviceAccounts:{create:async e=>{try{return await this.trpc.org.serviceAccount.create.mutate({orgName:e.orgName,name:e.name,role:e.role,description:e.description})}catch(e){throw $(e)}},list:async e=>{try{return await this.trpc.org.serviceAccount.list.query({orgName:e.orgName,includeDisabled:e.includeDisabled})}catch(e){throw $(e)}},get:async e=>{try{return await this.trpc.org.serviceAccount.get.query({orgName:e.orgName,name:e.name})}catch(e){throw $(e)}},setRole:async e=>{try{return await this.trpc.org.serviceAccount.setRole.mutate({orgName:e.orgName,name:e.name,role:e.role})}catch(e){throw $(e)}},disable:async e=>{try{return await this.trpc.org.serviceAccount.disable.mutate({orgName:e.orgName,name:e.name})}catch(e){throw $(e)}},enable:async e=>{try{return await this.trpc.org.serviceAccount.enable.mutate({orgName:e.orgName,name:e.name})}catch(e){throw $(e)}},delete:async e=>{try{await this.trpc.org.serviceAccount.delete.mutate({orgName:e.orgName,name:e.name})}catch(e){throw $(e)}}}};graph={checkpoint:Is(()=>this.trpc,$),export:(e,t,n)=>this.graphExport.stream(e,t,n),exportPrepare:(e,t,n)=>this.graphExport.prepare(e,t,n),get:async(e,t)=>{try{return await this.trpc.graph.get.query({orgName:e,graphName:t})}catch(e){throw $(e)}},getStats:async(e,t)=>{try{return await this.trpc.graph.stats.query({orgName:e,graphName:t})}catch(e){throw $(e)}},getStatsBatch:async(e,t)=>{try{return await this.trpc.graph.statsBatch.query({orgName:e,graphNames:t})}catch(e){throw $(e)}},getConfigureStats:async(e,t)=>{try{return await this.trpc.graph.configureStats.query({orgName:e,graphName:t})}catch(e){throw $(e)}},getShapeInstanceCounts:async(e,t)=>{try{return await this.trpc.graph.shapeInstanceCounts.query({orgName:e,graphName:t})}catch(e){throw $(e)}},list:async(e,t)=>{try{return await this.trpc.graph.list.query({orgName:e,limit:t?.limit,cursor:t?.cursor,includeArchived:t?.includeArchived,search:t?.search,sort:t?.sort})}catch(e){throw $(e)}},listIter:(e,t)=>Z(n=>this.graph.list(e,{...t,cursor:n}),e=>e.items,t?.cursor),listAll:async(e,t)=>{let{max:n,...r}=t??{};return await Q(t=>this.graph.list(e,{...r,cursor:t}),e=>e.items,n,r.cursor)},search:async(e,t)=>{try{return await this.trpc.graph.search.query({query:e,limit:t?.limit,cursor:t?.cursor})}catch(e){throw $(e)}},searchIter:(e,t)=>Z(n=>this.graph.search(e,{...t,cursor:n}),e=>e.items,t?.cursor),searchAll:async(e,t)=>{let{max:n,...r}=t??{};return await Q(t=>this.graph.search(e,{...r,cursor:t}),e=>e.items,n,r.cursor)},create:async(e,t,n,r,i)=>{try{return await this.trpc.graph.create.mutate({orgName:e,graphName:t,description:n,visibility:r,displayName:i})}catch(e){throw $(e)}},setDescription:async(e,t,n)=>{try{return await this.trpc.graph.setDescription.mutate({orgName:e,graphName:t,description:n})}catch(e){throw $(e)}},setDisplayName:async(e,t,n)=>{try{return await this.trpc.graph.setDisplayName.mutate({orgName:e,graphName:t,displayName:n})}catch(e){throw $(e)}},setVisibility:async(e,t,n)=>{try{return await this.trpc.graph.setVisibility.mutate({orgName:e,graphName:t,visibility:n})}catch(e){throw $(e)}},rename:async(e,t,n)=>{try{return await this.trpc.graph.rename.mutate({orgName:e,graphName:t,newName:n})}catch(e){throw $(e)}},update:async e=>{try{return await this.trpc.graph.update.mutate({orgName:e.orgName,graphName:e.graphName,displayName:e.displayName,newName:e.newName})}catch(e){throw $(e)}},archive:async(e,t)=>{try{return await this.trpc.graph.archive.mutate({orgName:e,graphName:t})}catch(e){throw $(e)}},unarchive:async(e,t)=>{try{return await this.trpc.graph.unarchive.mutate({orgName:e,graphName:t})}catch(e){throw $(e)}},delete:async(e,t)=>{try{let n=await this.trpc.graph.delete.mutate({orgName:e,graphName:t});return{graceExpiresAt:new Date(n.graceExpiresAt)}}catch(e){throw $(e)}},listPage:async(e,t)=>{try{return await this.trpc.graph.listPage.query({orgName:e,limit:t?.limit,cursor:t?.cursor,includeArchived:t?.includeArchived,search:t?.search,sort:t?.sort})}catch(e){throw $(e)}},listPageIter:(e,t)=>Z(n=>this.graph.listPage(e,{...t,cursor:n}),e=>e.items,t?.cursor),listPageAll:async(e,t)=>{let{max:n,...r}=t??{};return await Q(t=>this.graph.listPage(e,{...r,cursor:t}),e=>e.items,n,r.cursor)},listForCaller:async e=>{try{return await this.trpc.graph.listForCaller.query({limit:e?.limit,sort:e?.sort})}catch(e){throw $(e)}},explore:async e=>{try{return await this.trpc.graph.explore.query({search:e?.search,org:e?.org,activity:e?.activity,hasSubscriptions:e?.hasSubscriptions,minThings:e?.minThings,sort:e?.sort,limit:e?.limit,cursor:e?.cursor,slugs:e?.slugs})}catch(e){throw $(e)}},exploreIter:e=>(Sl(e),Z(t=>this.graph.explore({...e,cursor:t}),e=>e.items,e?.cursor)),exploreAll:async e=>{Sl(e);let{max:t,...n}=e??{};return await Q(e=>this.graph.explore({...n,cursor:e}),e=>e.items,t,n.cursor)},getReadme:async(e,t)=>{try{return await this.trpc.graph.getReadme.query({orgName:e,graphName:t})}catch(e){throw $(e)}},getAgents:async(e,t)=>{try{return await this.trpc.graph.getAgents.query({orgName:e,graphName:t})}catch(e){throw $(e)}},getLicense:async(e,t)=>{try{return await this.trpc.graph.getLicense.query({orgName:e,graphName:t})}catch(e){throw $(e)}},describe:async(e,t,n={})=>{try{return await this.trpc.graph.describe.query({orgName:e,graphName:t,includeHead:n.includeHead,includeIndexedFields:n.includeIndexedFields})}catch(e){throw $(e)}},setReadme:async(e,t,n,r)=>{try{return Wl(`Readme.content`,n),await this.trpc.graph.setReadme.mutate({orgName:e,graphName:t,eventRequestId:r.eventRequestId,content:n})}catch(e){throw $(e)}},setAgents:async(e,t,n,r)=>{try{return Wl(`Agents.content`,n),await this.trpc.graph.setAgents.mutate({orgName:e,graphName:t,eventRequestId:r.eventRequestId,content:n})}catch(e){throw $(e)}},getLlmsTxt:async(e,t)=>{try{return await this.trpc.graph.getLlmsTxt.query({orgName:e,graphName:t})}catch(e){throw $(e)}},index:{describe:async(e,t)=>{try{return await this.trpc.graph.index.describe.query({orgName:e,graphName:t})}catch(e){throw $(e)}},pin:async(e,t,n,r)=>{try{return await this.trpc.graph.index.pin.mutate({orgName:e,graphName:t,shape:n,fieldPath:r})}catch(e){throw $(e)}},unpin:async(e,t,n,r)=>{try{return await this.trpc.graph.index.unpin.mutate({orgName:e,graphName:t,shape:n,fieldPath:r})}catch(e){throw $(e)}}}};shape={list:async(e,t,n)=>{try{return await this.trpc.shape.list.query({orgName:e,graphName:t,match:n?.match,componentRef:n?.componentRef,excludeComponents:n?.excludeComponents,includeRetracted:n?.includeRetracted})}catch(e){throw $(e)}},get:async(e,t,n,r)=>{try{return await this.trpc.shape.get.query({orgName:e,graphName:t,shapeName:n,includeRetracted:r?.includeRetracted})}catch(e){throw $(e)}},create:async(e,t,n,r,i)=>{let a=Yo(n,{fields:r,...i.description===void 0?{}:{description:i.description},...i.composes===void 0?{}:{composes:i.composes}},`add`);if(a)throw new G(`VALIDATION_ERROR`,a);try{return await this.trpc.shape.create.mutate({orgName:e,graphName:t,shapeName:n,fields:r,eventRequestId:i.eventRequestId,description:i.description,composes:i.composes})}catch(e){throw $(e)}},revise:async(...e)=>{let[t,n,r]=e,i=e.length===5?e[3]:void 0,a=e.length===5?e[4]:e[3],o=i?Yo(r,{fields:i,...a.description===void 0?{}:{description:a.description},...a.composes===void 0?{}:{composes:a.composes}},`revise`):void 0;if(o)throw new G(`VALIDATION_ERROR`,o);try{return await this.trpc.shape.revise.mutate({orgName:t,graphName:n,shapeName:r,newFields:i,eventRequestId:a.eventRequestId,description:a.description,composes:a.composes})}catch(e){throw $(e)}},remove:async(e,t,n,r)=>{try{return await this.trpc.shape.remove.mutate({orgName:e,graphName:t,shapeName:n,eventRequestId:r.eventRequestId})}catch(e){throw $(e)}},rename:async(e,t,n,r,i)=>{try{return await this.trpc.shape.rename.mutate({orgName:e,graphName:t,oldName:n,newName:r,eventRequestId:i.eventRequestId})}catch(e){throw $(e)}},history:async(e,t,n,r={})=>{try{return await this.trpc.shape.history.query({orgName:e,graphName:t,name:n,includeRetracted:r.includeRetracted,limit:r.limit,cursor:r.cursor})}catch(e){throw $(e)}},historyIter:(e,t,n,r={})=>Z(i=>this.shape.history(e,t,n,{...r,cursor:i}),e=>e.versions,r.cursor),historyAll:async(e,t,n,r)=>{let{max:i,...a}=r??{};return await Q(r=>this.shape.history(e,t,n,{...a,cursor:r}),e=>e.versions,i,a.cursor)}};subscription={create:async e=>{try{return _l(await this.trpc.subscription.create.mutate(Nl(e)))}catch(e){throw $(e)}},get:async(...e)=>{try{return _l(await this.trpc.subscription.get.query(kl(e)))}catch(e){throw $(e)}},reveal:async(...e)=>{try{return await this.trpc.subscription.reveal.query(kl(e))}catch(e){throw $(e)}},list:async(...e)=>{try{return vl(await this.trpc.subscription.list.query(Al(e)))}catch(e){throw $(e)}},update:async e=>{try{return _l(await this.trpc.subscription.update.mutate(Pl(e)))}catch(e){throw $(e)}},pause:async(...e)=>{try{return await this.trpc.subscription.pause.mutate(kl(e))}catch(e){throw $(e)}},resume:async(...e)=>{try{return await this.trpc.subscription.resume.mutate(kl(e))}catch(e){throw $(e)}},remove:async(...e)=>{try{return await this.trpc.subscription.remove.mutate(kl(e))}catch(e){throw $(e)}},bindCredentials:async(...e)=>{try{return await this.trpc.subscription.bindCredentials.mutate(jl(e))}catch(e){throw $(e)}},unbindCredentials:async(...e)=>{try{return await this.trpc.subscription.unbindCredentials.mutate(Ml(e))}catch(e){throw $(e)}}};action={acquireLease:async(e,t,n,r,i,a)=>{try{return await this.trpc.action.acquireLease.mutate({orgName:e,graphName:t,subscriptionName:n,holderId:r,holderType:i,graceMs:a?.graceMs,ttlMs:a?.ttlMs})}catch(e){throw $(e)}},heartbeatLease:async(e,t,n,r,i)=>{try{return await this.trpc.action.heartbeatLease.mutate({orgName:e,graphName:t,subscriptionName:n,holderId:r,ttlMs:i})}catch(e){throw $(e)}},releaseLease:async(e,t,n,r)=>{try{return await this.trpc.action.releaseLease.mutate({orgName:e,graphName:t,subscriptionName:n,holderId:r})}catch(e){throw $(e)}},claimDelivery:async(e,t,n,r)=>{let i=typeof n==`string`?{runId:n}:n;try{return await this.trpc.action.claimDelivery.mutate({orgName:e,graphName:t,...i,holderId:r})}catch(e){throw $(e)}},completeDelivery:async(e,t,n,r)=>{let i=typeof n==`string`?{runId:n}:n;try{return await this.trpc.action.completeDelivery.mutate({orgName:e,graphName:t,...i,holderId:r})}catch(e){throw $(e)}},liveFeed:async(e,t,n,r)=>{try{return await this.trpc.action.liveFeed.query({orgName:e,graphName:t,subscriptionName:n,limit:r?.limit,cursor:r?.cursor})}catch(e){throw $(e)}},liveFeedIter:(e,t,n,r)=>Z(i=>this.action.liveFeed(e,t,n,{...r,cursor:i}),e=>e.items,r?.cursor),liveFeedAll:async(e,t,n,r)=>{let{max:i,...a}=r??{};return await Q(r=>this.action.liveFeed(e,t,n,{...a,cursor:r}),e=>e.items,i,a.cursor)},listRuns:async(e,t,n)=>{try{return await this.trpc.action.listRuns.query({orgName:e,graphName:t,runId:n?.runId,subscriptionName:n?.subscriptionName,status:n?.status,outcome:n?.outcome,since:n?.since,cursor:n?.cursor,limit:n?.limit})}catch(e){throw $(e)}},listRunsIter:(e,t,n)=>Z(r=>this.action.listRuns(e,t,{...n,since:r===void 0?n?.since:void 0,cursor:r}),e=>e.items,n?.cursor),listRunsAll:async(e,t,n)=>{let{max:r,...i}=n??{};return await Q(n=>this.action.listRuns(e,t,{...i,since:n===void 0?i.since:void 0,cursor:n}),e=>e.items,r,i.cursor)},latestRuns:async(e,t)=>{try{return await this.trpc.action.latestRuns.query({orgName:e,graphName:t})}catch(e){throw $(e)}},runStats:async(e,t,n)=>{try{return await this.trpc.action.runStats.query({orgName:e,graphName:t,subscriptionName:n?.subscriptionName,since:n?.since})}catch(e){throw $(e)}},getRunAttempts:async(e,t,n)=>{try{return await this.trpc.action.getRunAttempts.query({orgName:e,graphName:t,runId:n})}catch(e){throw $(e)}},listNotifications:async(e,t,n)=>{try{return await this.trpc.action.listNotifications.query({orgName:e,graphName:t,since:n?.since,limit:n?.limit})}catch(e){throw $(e)}}};collection={create:async(e,t,n)=>{try{return Rl(n.type,n),await this.trpc.collection.create.mutate({orgName:e,graphName:t,eventRequestId:n.eventRequestId,type:n.type,name:n.name,members:n.members,from:n.from,add:n.add,remove:n.remove,replaceMembers:n.replaceMembers,query:n.query,sourceOrgName:n.sourceGraph?.orgName,sourceGraphName:n.sourceGraph?.graphName,skipExisting:n.skipExisting,message:n.message,committer:n.committer})}catch(e){throw $(e)}},members:async(e,t,n,r)=>{try{return await this.trpc.collection.members.query({orgName:e,graphName:t,wref:n,version:r?.version,limit:r?.limit,cursor:r?.cursor,shape:r?.shape})}catch(e){throw $(e)}},membersIter:(e,t,n,r)=>{let i=r?.version;return Z(async a=>{let o=await this.collection.members(e,t,n,{...r,version:i,cursor:a});return i??=o.version,o},e=>e.items,r?.cursor)},membersAll:async(e,t,n,r)=>{let{max:i,...a}=r??{},o=a.version;return await Q(async r=>{let i=await this.collection.members(e,t,n,{...a,version:o,cursor:r});return o??=i.version,i},e=>e.items,i,a.cursor)},contains:async(e,t,n,r,i)=>{try{return await this.trpc.collection.contains.query({orgName:e,graphName:t,wref:n,version:i?.version,members:r,position:i?.position,shape:i?.shape})}catch(e){throw $(e)}},diff:async(e,t,n,r,i)=>{try{return await this.trpc.collection.diff.query({orgName:e,graphName:t,leftWref:n,rightWref:r,leftVersion:i?.leftVersion,rightVersion:i?.rightVersion,mode:i?.mode,shape:i?.shape})}catch(e){throw $(e)}},revise:async(e,t,n,r)=>{try{if(Fl(r.query)&&!Il(r.query))throw new G(`VALIDATION_ERROR`,`Selector-backed collection sources require shape, about, match, componentRef, or where; kind and excludeComponents only narrow an existing selector.`);if(r.sourceGraph&&!Il(r.query))throw new G(`VALIDATION_ERROR`,`sourceGraph requires a selector-backed collection query`);if(r.sourceGraph&&Ll(r))throw new G(`VALIDATION_ERROR`,`sourceGraph cannot be combined with explicit members; use canonical wh:org/graph/... member wrefs or omit sourceGraph.`);return await this.trpc.collection.revise.mutate({orgName:e,graphName:t,eventRequestId:r.eventRequestId,wref:n,members:r.members,add:r.add,remove:r.remove,query:r.query,sourceOrgName:r.sourceGraph?.orgName,sourceGraphName:r.sourceGraph?.graphName,message:r.message,committer:r.committer})}catch(e){throw $(e)}},stats:async(e,t,n,r)=>{try{return await this.trpc.collection.stats.query({orgName:e,graphName:t,wref:n,version:r?.version,shape:r?.shape})}catch(e){throw $(e)}}};view={evaluate:async(e,t,n,r)=>{try{return await this.trpc.view.evaluate.query({orgName:e,graphName:t,wref:n,limit:r?.limit,cursor:r?.cursor})}catch(e){throw $(e)}},evaluateIter:(e,t,n,r)=>Z(i=>this.view.evaluate(e,t,n,{...r,cursor:i}),e=>e.items,r?.cursor),evaluateAll:async(e,t,n,r)=>{let{max:i,...a}=r??{};return await Q(r=>this.view.evaluate(e,t,n,{...a,cursor:r}),e=>e.items,i,a.cursor)}};grant=Jo(()=>this.trpc,$);thing={head:async(e,t,n)=>{try{return await this.trpc.thing.head.query({orgName:e,graphName:t,shape:n?.shape,declaredShape:n?.declaredShape,shapeless:n?.shapeless,includeValidatedShapes:n?.includeValidatedShapes,kind:Dl(n?.kind),match:n?.match,dataMode:n?.dataMode,includeRetracted:n?.includeRetracted,limit:n?.limit,cursor:n?.cursor,componentRef:n?.componentRef,excludeComponents:n?.excludeComponents,excludeInfraShapes:n?.excludeInfraShapes,where:n?.where,sinceGraphSeq:n?.sinceGraphSeq})}catch(e){throw $(e)}},headIter:(e,t,n)=>Z(r=>this.thing.head(e,t,{...n,cursor:r}),e=>e.items,n?.cursor),headAll:async(e,t,n)=>{let{max:r,...i}=n??{};return await Q(n=>this.thing.head(e,t,{...i,cursor:n}),e=>e.items,r,i.cursor)},headChanges:async(e,t,n)=>(bl(n?.sinceGraphSeq),await Cl(r=>this.thing.head(e,t,{...n,includeRetracted:!0,cursor:r}))),get:async(e,t,n,r,i)=>{try{return await this.trpc.thing.get.query({orgName:e,graphName:t,wref:n,version:r,includeRetracted:i?.includeRetracted,dataMode:i?.dataMode})}catch(e){throw $(e)}},getWithLease:async(e,t,n,r)=>{try{return await this.trpc.thing.getWithLease.mutate({orgName:e,graphName:t,wref:n,ttlMs:r?.ttlMs})}catch(e){throw $(e)}},releaseLease:async(e,t,n,r)=>{try{await this.trpc.thing.releaseLease.mutate({orgName:e,graphName:t,wref:n,leaseId:r})}catch(e){throw $(e)}},graph:async(e,t,n,r)=>{try{return await this.trpc.thing.graph.query({orgName:e,graphName:t,wref:n,version:r?.version,depth:r?.depth,limit:r?.limit})}catch(e){throw $(e)}},getMany:async(e,t,n,r,i)=>{try{return await El(n,i,n=>this.trpc.thing.getMany.query({orgName:e,graphName:t,wrefs:n,version:r,includeRetracted:i?.includeRetracted,dataMode:i?.dataMode}))}catch(e){throw $(e)}},headVersions:async(e,t,n,r)=>{try{return await El(n,r,n=>this.trpc.thing.headVersions.query({orgName:e,graphName:t,wrefs:n}))}catch(e){throw $(e)}},names:async(e,t,n,r)=>{try{return await El(n,r,n=>this.trpc.thing.names.query({orgName:e,graphName:t,durableIds:n}))}catch(e){throw $(e)}},history:async(e,t,n)=>{try{return await this.trpc.thing.history.query({orgName:e,graphName:t,wref:n.wref,shape:n.shape,declaredShape:n.declaredShape,about:n.about,includeRetracted:n.includeRetracted,resolveCollections:n.resolveCollections,match:n.match,limit:n.limit,cursor:n.cursor})}catch(e){throw $(e)}},historyIter:(e,t,n)=>Z(r=>this.thing.history(e,t,{...n,cursor:r}),e=>e.versions,n.cursor),historyAll:async(e,t,n)=>{let{max:r,...i}=n;return await Q(n=>this.thing.history(e,t,{...i,cursor:n}),e=>e.versions,r,i.cursor)},rename:async(e,t,n,r,i)=>{try{return await this.trpc.thing.rename.mutate({orgName:e,graphName:t,name:n,newName:r,eventRequestId:i.eventRequestId})}catch(e){throw $(e)}},remove:async(e,t,n,r)=>{try{return await this.trpc.thing.remove.mutate({orgName:e,graphName:t,wref:n,expectedVersion:r.expectedVersion,eventRequestId:r.eventRequestId})}catch(e){throw $(e)}},redact:async(e,t,n,r)=>{try{return await this.trpc.thing.redact.mutate({orgName:e,graphName:t,durableId:n,expectedVersion:r.expectedVersion,eventRequestId:r.eventRequestId})}catch(e){throw $(e)}},rewrite:async(e,t,n,r)=>{try{return await this.trpc.thing.rewrite.mutate({orgName:e,graphName:t,wref:n,version:r.version,shapes:r.shapes,data:r.data,eventRequestId:r.eventRequestId})}catch(e){throw $(e)}},resolve:async(e,t,n)=>{try{return await this.trpc.thing.resolve.query({orgName:e,graphName:t,wref:n})}catch(e){throw $(e)}},about:async(e,t,n,r)=>{try{return await this.trpc.thing.about.query({orgName:e,graphName:t,wref:n,shape:r?.shape,match:r?.match,includeRetracted:r?.includeRetracted,depth:r?.depth,resolveCollections:r?.resolveCollections,role:r?.role,limit:r?.limit,cursor:r?.cursor,where:r?.where})}catch(e){throw $(e)}},aboutIter:(e,t,n,r)=>Z(i=>this.thing.about(e,t,n,{...r,cursor:i}),e=>e.assertions,r?.cursor),aboutAll:async(e,t,n,r)=>{let{max:i,...a}=r??{};return await Q(r=>this.thing.about(e,t,n,{...a,cursor:r}),e=>e.assertions,i,a.cursor)},query:async(e,t,n)=>{try{return await this.trpc.thing.query.query({orgName:e,graphName:t,shape:n?.shape,declaredShape:n?.declaredShape,shapeless:n?.shapeless,includeValidatedShapes:n?.includeValidatedShapes,about:n?.about,affirmedAbout:n?.affirmedAbout,kind:Dl(n?.kind),match:n?.match,includeRetracted:n?.includeRetracted,resolveCollections:n?.resolveCollections,role:n?.role,limit:n?.limit,cursor:n?.cursor,componentRef:n?.componentRef,excludeComponents:n?.excludeComponents,excludeInfraShapes:n?.excludeInfraShapes,where:n?.where,sinceGraphSeq:n?.sinceGraphSeq})}catch(e){throw $(e)}},queryIter:(e,t,n)=>Z(r=>this.thing.query(e,t,{...n,cursor:r}),e=>e.items,n?.cursor),queryAll:async(e,t,n)=>{let{max:r,...i}=n??{};return await Q(n=>this.thing.query(e,t,{...i,cursor:n}),e=>e.items,r,i.cursor)},queryChanges:async(e,t,n)=>(bl(n?.sinceGraphSeq),await Cl(r=>this.thing.query(e,t,{...n,includeRetracted:!0,cursor:r}))),search:async(e,t,n,r)=>{try{return await this.trpc.thing.search.query({orgName:e,graphName:t,query:n,shape:r?.shape,about:r?.about,affirmedAbout:r?.affirmedAbout,kind:Dl(r?.kind),match:r?.match,includeRetracted:r?.includeRetracted,resolveCollections:r?.resolveCollections,limit:r?.limit,cursor:r?.cursor,componentRef:r?.componentRef,excludeComponents:r?.excludeComponents,excludeInfraShapes:r?.excludeInfraShapes,mode:r?.mode,nameMatch:r?.nameMatch})}catch(e){throw $(e)}},searchIter:(e,t,n,r)=>Z(i=>this.thing.search(e,t,n,{...r,cursor:i}),e=>e.items,r?.cursor),searchAll:async(e,t,n,r)=>{let{max:i,...a}=r??{};return await Q(r=>this.thing.search(e,t,n,{...a,cursor:r}),e=>e.items,i,a.cursor)},count:async(e,t,n)=>{try{return await this.trpc.thing.count.query({orgName:e,graphName:t,shape:n?.shape,declaredShape:n?.declaredShape,shapeless:n?.shapeless,about:n?.about,affirmedAbout:n?.affirmedAbout,kind:Dl(n?.kind),match:n?.match,includeRetracted:n?.includeRetracted,resolveCollections:n?.resolveCollections,componentRef:n?.componentRef,excludeComponents:n?.excludeComponents,excludeInfraShapes:n?.excludeInfraShapes,where:n?.where,sinceGraphSeq:n?.sinceGraphSeq})}catch(e){throw $(e)}},refs:async(e,t,n,r)=>{try{return await this.trpc.thing.refs.query({orgName:e,graphName:t,wref:n,direction:r?.direction,fieldPath:r?.fieldPath,binding:r?.binding,limit:r?.limit,cursor:r?.cursor})}catch(e){throw $(e)}},refsIter:(e,t,n,r)=>Z(i=>this.thing.refs(e,t,n,{...r,cursor:i}),e=>e.items,r?.cursor),refsAll:async(e,t,n,r)=>{let{max:i,...a}=r??{};return await Q(r=>this.thing.refs(e,t,n,{...a,cursor:r}),e=>e.items,i,a.cursor)}};live={thingHead:async(e,t,n,r)=>this.watchRepoQuery(e,t,n?.signal,()=>this.thing.head(e,t,{shape:n?.shape,declaredShape:n?.declaredShape,shapeless:n?.shapeless,includeValidatedShapes:n?.includeValidatedShapes,kind:n?.kind,match:n?.match,dataMode:n?.dataMode,limit:n?.limit,cursor:n?.cursor,includeRetracted:n?.includeRetracted,where:n?.where}),r),thingHistory:async(e,t,n,r)=>this.watchRepoQuery(e,t,n.signal,()=>this.thing.history(e,t,{wref:n.wref,shape:n.shape,declaredShape:n.declaredShape,about:n.about,resolveCollections:n.resolveCollections,match:n.match,limit:n.limit,cursor:n.cursor,includeRetracted:n.includeRetracted}),r),subscriptionLog:async(e,t,n,r,i)=>this.watchRepoQuery(e,t,r?.signal,()=>this.action.liveFeed(e,t,n,{limit:r?.limit,cursor:r?.cursor}),i),subscribe:async(e,t,n,r)=>{let i=new AbortController,a=ou(n?.signal,i),o=0;return{close(){i.abort()},closed:this.runLiveLoop(()=>this.trpc.live.issueTicket.mutate({orgName:e,graphName:t}),a,async e=>{if(e.type!==`invalidate`)return;let t=e.data;o++,await lu(()=>r({topic:t.topic,affectedShapes:t.affectedShapes,affectedThings:t.affectedThings,affectedTargets:t.affectedTargets,hasNewCommit:t.hasNewCommit}))}).then(()=>({updates:o}))}}};token={create:async e=>{try{return await this.trpc.token.create.mutate(e)}catch(e){throw $(e)}},list:async e=>{try{return await this.trpc.token.list.query(e?.includeInactive?{includeInactive:!0}:void 0)}catch(e){throw $(e)}},listForServiceAccount:async(e,t)=>{try{return await this.trpc.token.list.query({serviceAccount:e,includeInactive:t?.includeInactive})}catch(e){throw $(e)}},get:async(e,t)=>{try{return await this.trpc.token.get.query({name:e,serviceAccount:t?.serviceAccount})}catch(e){throw $(e)}},revoke:async(e,t)=>{try{return await this.trpc.token.revoke.mutate({name:e,serviceAccount:t?.serviceAccount})}catch(e){throw $(e)}}};stream={append:async e=>{try{return await this.trpc.stream.append.mutate(e)}catch(e){throw $(e)}}};credential={createSet:async(e,t,n,r)=>{try{return await this.trpc.credential.createSet.mutate({orgName:e,graphName:t,name:n,scope:r?.scope??`repo`,description:r?.description})}catch(e){throw $(e)}},listSets:async(e,t)=>{try{return await this.trpc.credential.listSets.query({orgName:e,graphName:t})}catch(e){throw $(e)}},getSet:async(e,t,n)=>{try{return await this.trpc.credential.getSet.query({orgName:e,graphName:t,name:n})}catch(e){throw $(e)}},setKey:async(e,t,n,r,i)=>{try{return await this.trpc.credential.setKey.mutate({orgName:e,graphName:t,setName:n,keyName:r,value:i})}catch(e){throw $(e)}},setKeys:async(e,t,n,r)=>{try{return await this.trpc.credential.setKeys.mutate({orgName:e,graphName:t,setName:n,secrets:r})}catch(e){throw $(e)}},unsetKey:async(e,t,n,r)=>{try{return await this.trpc.credential.unsetKey.mutate({orgName:e,graphName:t,setName:n,keyName:r})}catch(e){throw $(e)}},deleteSet:async(e,t,n)=>{try{return await this.trpc.credential.deleteSet.mutate({orgName:e,graphName:t,setName:n})}catch(e){throw $(e)}},listAuditLog:async(e,t,n,r)=>{try{return await this.trpc.credential.listAuditLog.query({orgName:e,graphName:t,setName:n,limit:r?.limit})}catch(e){throw $(e)}},revokeSet:async(e,t,n,r)=>{try{return await this.trpc.credential.revokeSet.mutate({orgName:e,graphName:t,setName:n,reason:r?.reason})}catch(e){throw $(e)}}};credentials=this.credential;get repo(){return r(`client.repo`,`client.graph`),this.graph}constructor(e,t){let n=typeof e==`string`?t:e;pl(n);let r=typeof e==`string`?e:e?.apiUrl??`https://api.warmhub.ai`;if(this.apiUrl=r,this.fetchImpl=n?.fetch,this.accessToken=n?.accessToken??n?.auth?.getToken,this.functionLogMode=n?.functionLogs??`off`,this.clientIdentity={name:n?.client?.name??`@warmhub/sdk-ts`,version:n?.client?.version??`0.163.1`},this.#e=Object.freeze([...ml(n?.clientFlags)]),this.decorateResponses=n?.decorateResponses??!1,typeof this.accessToken==`function`){let e=this.accessToken;this.getToken=async()=>await e()}else if(this.accessToken){let e=this.accessToken;this.getToken=async()=>e}let a=`${r.replace(/\/$/,``)}/trpc`,u=((e,t)=>this.fetchWithAuth(e,t));Object.defineProperty(this,"trpc",{value:o({links:[this.createLocalRefusalLink(),this.createCompatibilityLink(),qo({enabled:this.decorateResponses,lookupNames:async e=>{try{return await this.trpc.thing.names.query({durableIds:e})}catch(e){throw $(e)}}}),l({condition:e=>gl.has(e.path),true:c({url:a,fetch:u,methodOverride:`POST`}),false:s({url:a,fetch:u,methodOverride:`POST`})})]}),enumerable:!1,writable:!1,configurable:!0}),i(this)}get clientFlags(){return this.#e}withAccessToken(t){let n={apiUrl:this.apiUrl,fetch:this.fetchImpl,accessToken:t,client:this.clientIdentity,clientFlags:this.clientFlags,decorateResponses:this.decorateResponses};return new e(n)}actions=this.action;async runLiveLoop(e,t,n,r){for(;!t.aborted;){let i=new AbortController,a=()=>i.abort();t.addEventListener(`abort`,a,{once:!0});let o;try{let a=await e(),s=await this.openSse(a.ticket,i.signal,n);if(o=s.closed,await s.ready,t.aborted)return;await r?.(),await s.closed}catch(e){if(t.aborted)return;if(e instanceof cu)throw e.cause;if(!Yl(e))throw $(e)}finally{t.removeEventListener(`abort`,a),i.abort(),o?.catch(()=>{})}await uu(su,t)}}async openSse(e,t,n){let r=await this.fetchWithAuth(`${this.apiUrl.replace(/\/$/,``)}/sse?ticket=${encodeURIComponent(e)}`,{headers:{accept:`text/event-stream`},signal:t});if(!r.ok)throw await this.httpResponseError(r);let i=r.body?.getReader();if(!i)throw new G(`BACKEND`,`SSE response body is missing`);let a=()=>{};return{ready:new Promise(e=>{a=e}),closed:(async()=>{let e=new TextDecoder,r=``;try{for(;;){let{done:t,value:o}=await i.read();if(t)break;for(r+=e.decode(o,{stream:!0}).replaceAll(`\r
30
+ `);if(e===-1)break;let t=a.slice(0,e);a=a.slice(e+1);let{pending:n,row:r}=l(t);n&&await n,u(r),r.type===`summary`||r.type===`error`?c=r:yield r}}if(a+=i.decode(),a.length>0){let{pending:e,row:t}=l(a);e&&await e,u(t),t.type===`summary`||t.type===`error`?c=t:yield t}r.finish(),s=!0,c&&(yield c)}finally{if(!s)try{await n.cancel()}catch{}n.releaseLock()}}var Lc=class extends Error{code=`STREAMING_SUBMISSION_OUTCOME_UNKNOWN`;outcome=`unknown`;retryable=!1;retryIdentity;cause;constructor(e,t){super(`Streaming submission outcome is unknown for ${e.submissionId}. Reconstruct the original source and copy every retryIdentity field into the next applyStreaming call.`),this.name=`StreamingSubmissionOutcomeUnknownError`,this.retryIdentity=e,this.cause=t}};function Rc(e){return e===void 0||e===``?void 0:e}function zc(){let e=globalThis;if(e.Bun!==void 0)return!0;let t=e.process?.versions?.node;if(!t)return!1;let[n=0,r=0]=t.split(`.`).map(Number);return n>22||n===22&&r>=2}function Bc(e){let t=new URLSearchParams({submissionId:e.submissionId,groupSize:String(e.groupSize)});return e.message!==void 0&&t.set(`message`,e.message),e.committer!==void 0&&t.set(`committer`,e.committer),`/api/graphs/${encodeURIComponent(e.orgName)}/${encodeURIComponent(e.graphName)}/streams/${encodeURIComponent(e.streamId)}/submissions?${t}`}function Vc(e,t,n){let r=Ds(e,!1),i=To(n),a=0,o=!1,s=async e=>{try{await e}catch{}},c=()=>{if(!o){o=!0;try{let e=r.returnSourceOnce();e&&s(e)}catch{}}};return{stream:new ReadableStream({async pull(e){try{let n=[],s=a,c=!1;for(;;){let l=await r.next();if(o)return;if(!(!l.done&&(n.push(l.value),a+=1,c||=oo(l.value),c&&a%t!==0))){for(let t of await i(n,s))e.enqueue(Os(t));l.done&&e.close();return}}}catch(t){e.error(t),c()}},cancel(){c()}}),returnSourceOnce:c}}function Hc(e,t){if(!e)return()=>void 0;let n=()=>t.abort(e.reason);return e.aborted?n():e.addEventListener(`abort`,n,{once:!0}),()=>e.removeEventListener(`abort`,n)}function Uc(e){let t=e.options?.submissionId??Zo();return{orgName:e.orgName,graphName:e.graphName,streamId:e.options.streamId,submissionId:t,groupSize:js(e.options.groupSize),...Rc(e.message)===void 0?{}:{message:Rc(e.message)},...Rc(e.options?.committer)===void 0?{}:{committer:Rc(e.options?.committer)}}}function Wc(e,t){if(!e.options.streamId)throw t.localError(`VALIDATION_ERROR`,`Streaming submissions require a non-empty streamId.`);let n=Uc(e),r=new AbortController,i=()=>void 0,a,o=!1,s=async function*(){let a=!1,s=!1,c;try{if(!(t.runtimeSupported??zc)())throw t.localError(`VALIDATION_ERROR`,`Streaming submissions require Bun or Node.js 22.2 or newer.`);if(i=Hc(e.options.signal,r),r.signal.aborted)throw t.localError(`CANCELLED`,`Streaming submission was aborted.`);let o=await t.prepare(Bc(n));if(r.signal.aborted)throw t.localError(`CANCELLED`,`Streaming submission was aborted.`);c=Vc(e.operations,n.groupSize,t.readThings),a=!0;let l=await o.dispatch(c.stream,r.signal);if(!l.ok)throw s=!0,await o.httpError(l);for await(let e of Ic(l,n))yield e}catch(e){throw e instanceof Lc?e:a&&!s?new Lc(n,e):t.normalizeLocalError(e)}finally{r.abort(),c?.returnSourceOnce(),i(),o=!0}};return{retryIdentity:n,[Symbol.asyncIterator](){return this},next(){return o?Promise.resolve({done:!0,value:void 0}):(a??=s(),a.next())},async return(e){return r.abort(),a?a.return(e):(o=!0,i(),{done:!0,value:e})},async throw(e){if(r.abort(e),!a)throw o=!0,i(),e;return a.throw(e)}}}function Gc(e){return e===`0.0.0-development`}const Kc=`0.164.0`;function qc(e){return e===`warmhub-cli`?`Run: wh update --yes`:e===`@warmhub/sdk-ts`?`Run: npm install @warmhub/sdk-ts@latest (or your package manager's equivalent).`:e===`warmhub-sdk-py`?`Run: pip install --upgrade warmhub`:`Deploy a released ${e} build that satisfies the backend compatibility contract.`}function Jc(e,t){if(typeof e?.minSupportedClients!=`object`||e.minSupportedClients===null||!Number.isSafeInteger(e.writeContractVersion)||e.writeContractVersion<1)return{message:`The backend does not advertise valid per-client write compatibility data.`,hint:`Upgrade the WarmHub backend before retrying this write.`};let n=e.minSupportedClients[t.name],r=typeof n==`string`?Er(n):null;if(!r)return{message:`The backend does not advertise a valid compatibility floor for ${t.name}.`,hint:`Upgrade the WarmHub backend or register this first-party client family before writing.`};if(!Gc(t.version)){let e=Er(t.version);if(!e)return{message:`${t.name} reported malformed version "${t.version}".`,hint:`Use a released WarmHub client with a SemVer package version.`};if(Ar(e,r)<0)return{message:`${t.name} ${t.version} is older than the backend's minimum supported version ${r}.`,hint:qc(t.name)}}if(e.writeContractVersion<5)return{message:`${t.name} requires write contract 5, but the backend provides ${e.writeContractVersion}.`,hint:`Upgrade the WarmHub backend before retrying this write.`}}function Yc(e,t){try{return new URL(e).origin===new URL(t).origin}catch{return!1}}const Xc=/* @__PURE__ */ new Set([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`]);var Y=class extends Error{reason;constructor(e,t){super(t),this.name=`CliCallVerificationError`,this.reason=e}};async function Zc(e,t,n){let r=e.method.toUpperCase();if(!Xc.has(r))throw new Y(`unsupported-method`,`Unsupported HTTP method "${e.method}" — component CLI dispatch only emits GET, POST, PUT, or PATCH`);let i=r,a=e.headers.get(rr);if(!a)throw new Y(`missing-install-repo`,`Missing ${rr} header`);let o=X(t.CLI_SIGNING_SECRET),s=X(t.CLI_BEARER_TOKEN),c=X(t.CLI_API_KEY),l=X(t.CLI_BASIC_USERNAME)&&X(t.CLI_BASIC_PASSWORD);if(!o&&!s&&!c&&!l)throw new Y(`no-scheme-configured`,`no-scheme-configured: need at least one of CLI_SIGNING_SECRET, CLI_BEARER_TOKEN, CLI_API_KEY, or CLI_BASIC_USERNAME + CLI_BASIC_PASSWORD`);if(s&&l)throw new Y(`no-scheme-configured`,`unsupported-scheme-combination: CLI_BEARER_TOKEN and CLI_BASIC_USERNAME + CLI_BASIC_PASSWORD both use the Authorization header and cannot be configured together`);let u=new URL(e.url),d=u.pathname,f,p,m;if(lr(i)?f={}:(f=Object.fromEntries(u.searchParams.entries()),p=``,m={...f}),o){let r=e.headers.get(ir);if(!r)throw new Y(`missing-signature`,`Missing ${ir} header`);let o=e.headers.get(ar);if(!o)throw new Y(`missing-timestamp`,`Missing ${ar} header`);let s=Number(o);if(!Number.isFinite(s)||!Number.isInteger(s))throw new Y(`invalid-timestamp`,`${ar} must be an integer unix seconds value; got "${o}"`);p=await Qc(e,i,p);let c=await gr({secret:t.CLI_SIGNING_SECRET,method:i,path:d,query:f,installRepo:a,body:p,signature:r,timestamp:s,nowUnixSeconds:n?.nowUnixSeconds??Math.floor(Date.now()/1e3),toleranceSec:n?.toleranceSec});if(!c.ok)throw new Y(c.reason,`HMAC verification failed: ${c.reason}`)}if(s){let n=`Bearer ${t.CLI_BEARER_TOKEN}`;if(!await tl(e.headers.get(`authorization`)??``,n))throw new Y(`invalid-bearer`,`invalid-bearer: bearer token mismatch`)}if(c){let n=X(t.CLI_API_KEY_HEADER)?t.CLI_API_KEY_HEADER:`X-API-Key`;if(!await tl(e.headers.get(n)??``,t.CLI_API_KEY))throw new Y(`invalid-api-key`,`invalid-api-key: mismatch on header "${n}"`)}if(l){let n=`Basic ${btoa(`${t.CLI_BASIC_USERNAME}:${t.CLI_BASIC_PASSWORD}`)}`;if(!await tl(e.headers.get(`authorization`)??``,n))throw new Y(`invalid-basic`,`invalid-basic: basic auth mismatch`)}return m===void 0&&(p=await Qc(e,i,p),m=$c(p)),{method:i,installRepo:a,args:m}}async function Qc(e,t,n){return lr(t)?n===void 0?e.text():n:``}function $c(e){let t;try{t=JSON.parse(e)}catch{throw new Y(`invalid-body`,`POST body is not valid JSON`)}if(!el(t))throw new Y(`invalid-body`,`POST body must be a JSON object of primitive args (string / number / boolean)`);return t}function X(e){return typeof e==`string`&&e.length>0}function el(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;for(let t of Object.values(e))if(t!==void 0&&typeof t!=`string`&&typeof t!=`number`&&typeof t!=`boolean`)return!1;return!0}async function tl(e,t){let[n,r]=await Promise.all([nl(e),nl(t)]),i=0;for(let e=0;e<n.length;e++)i|=n[e]^r[e];return i===0}async function nl(e){return new Uint8Array(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e)))}const rl=q,il=Rs,al=(...e)=>(r(`applyRepositoryExportDelta`,`applyGraphExportDelta`),Us(...e)),ol=(...e)=>(r(`createRepositoryExportSession`,`createGraphExportSession`),zs(...e)),sl=(...e)=>(r(`readRepositoryExportStream`,`readGraphExportStream`),Zs(...e)),cl=(...e)=>(r(`restoreRepositoryExportSession`,`restoreGraphExportSession`),Qs(...e));function ll(e){return Se(e)}const ul=Object.keys({apiUrl:!0,fetch:!0,accessToken:!0,auth:!0,functionLogs:!0,client:!0,clientFlags:!0,decorateResponses:!0}),dl=new Set(ul),fl=/* @__PURE__ */ new Set([`token`,`apiKey`,`bearer`]);function pl(e){if(e)for(let t of Object.keys(e)){if(dl.has(t))continue;let e=fl.has(t)?`; did you mean "accessToken"?`:`. Valid options are: ${ul.join(`, `)}.`;throw TypeError(`Unknown WarmHubClient option "${t}"${e}`)}}function ml(e){if(!e||e.length===0)return[];for(let t of e)if(!Kn(t))throw TypeError(`Invalid client flag "${t}": expected lowercase tokens matching [a-z0-9-]+.`);return[...new Set(e)].sort()}const hl=`https://api.warmhub.ai`,gl=/* @__PURE__ */ new Set([`commit.validate`,`graph.shapeInstanceCounts`,`thing.getMany`,`thing.headVersions`,`thing.names`]);function _l(e){return{...e,actionContainer:void 0,actionContainerConfig:void 0}}function vl(e){return e.map(e=>_l(e))}function yl(e,t,n){if(t===e||n.has(t))throw new G(`VALIDATION_ERROR`,`Paginated result cursor did not advance`)}function bl(e){if(e===void 0)throw new G(`VALIDATION_ERROR`,`sinceGraphSeq is required for an incremental read`)}async function*xl(e,t){let n=t,r=/* @__PURE__ */ new Set;for(;;){n&&r.add(n);let t=await e(n);if(yield t,!t.nextCursor)return;yl(n,t.nextCursor,r),n=t.nextCursor}}async function*Z(e,t,n){for await(let r of xl(e,n))yield*t(r)}async function Q(e,t,n,r){if(n!==void 0&&(!Number.isFinite(n)||Math.trunc(n)!==n||n<0))throw new G(`VALIDATION_ERROR`,`max must be a nonnegative integer`);let i=[];for await(let a of xl(e,r)){let e=t(a);if(n!==void 0&&i.length+e.length>n)throw new G(`VALIDATION_ERROR`,`Paginated result exceeded max=${n}`);i.push(...e)}return i}function Sl(e){if(e?.slugs!==void 0)throw new G(`VALIDATION_ERROR`,`graph.explore pagination helpers do not support slugs mode`)}async function Cl(e){let t=[],n,r=/* @__PURE__ */ new Set;for(;;){n&&r.add(n);let i=await e(n);if(t.push(...i.items),!i.nextCursor){if(i.graphSeq===void 0)throw new G(`VALIDATION_ERROR`,`Incremental read completed without graphSeq`);return{items:t,graphSeq:i.graphSeq}}yl(n,i.nextCursor,r),n=i.nextCursor}}function wl(e,t,n){return Number.isFinite(e)?Math.max(1,Math.min(n,Math.trunc(e))):t}function Tl(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}async function El(e,t,n){if(e.length===0)return{requested:0,items:[],missing:[]};let r=wl(t?.chunkSize,500,500),i=wl(t?.chunkConcurrency,1,8);if(e.length<=r)return await n(e);let a=Tl(e,r),o=[];for(let e=0;e<a.length;e+=i){let t=a.slice(e,e+i),r=await Promise.all(t.map(n));o.push(...r)}return{requested:e.length,items:o.flatMap(e=>e.items),missing:o.flatMap(e=>e.missing)}}function Dl(e){return e!==void 0&&tr.includes(e)?e:void 0}function Ol(e){let t=e;if(t.graphName!==void 0)return t;let{graphName:n,...r}=t;return r}function kl(e){let[t,n,r]=e;return Ol(typeof t==`string`?{orgName:t,graphName:n,name:r}:t)}function Al(e){let[t,n]=e;return Ol(typeof t==`string`?{orgName:t,graphName:n}:t)}function jl(e){let[t,n,r,i]=e;return Ol(typeof t==`string`?{orgName:t,graphName:n,subscriptionName:r,credentialSetName:i}:t)}function Ml(e){let[t,n,r]=e;return Ol(typeof t==`string`?{orgName:t,graphName:n,subscriptionName:r}:t)}function Nl(e){let{actionContainer:t,actionContainerConfig:n,...r}=e;return r}function Pl(e){let{actionContainer:t,actionContainerConfig:n,...r}=e;return r}function Fl(e){return!!e&&(!!e.shape||!!e.kind||!!e.about||!!e.match||!!e.componentRef||e.excludeComponents===!0||(e.where?.length??0)>0)}function Il(e){return!!e&&(!!e.shape||!!e.about||!!e.match||!!e.componentRef||(e.where?.length??0)>0)}function Ll(e){let t=e.members;return Array.isArray(t)&&t.length>0}function Rl(e,t){if(e!==`set`&&e!==`list`)throw new G(`VALIDATION_ERROR`,ki(String(e)));if(Fl(t.query)&&!Il(t.query))throw new G(`VALIDATION_ERROR`,`Selector-backed collection sources require shape, about, match, componentRef, or where; kind and excludeComponents only narrow an existing selector.`);if(t.sourceGraph&&!Il(t.query))throw new G(`VALIDATION_ERROR`,`sourceGraph requires a selector-backed collection query`);if(t.sourceGraph&&Ll(t))throw new G(`VALIDATION_ERROR`,`sourceGraph cannot be combined with explicit members; use canonical wh:org/graph/... member wrefs or omit sourceGraph.`);if(Fl(t.query)&&e!==`set`)throw new G(`VALIDATION_ERROR`,`Selector-backed collection sources are only supported for set collections`)}function zl(e){return e??`off`}function Bl(e){if(e!==void 0)switch(e){case`BAD_REQUEST`:case`PARSE_ERROR`:case`PAYLOAD_TOO_LARGE`:case`UNPROCESSABLE_CONTENT`:case`UNSUPPORTED_MEDIA_TYPE`:return`VALIDATION_ERROR`;case`METHOD_NOT_SUPPORTED`:return`NOT_FOUND`;case`UNAUTHORIZED`:return`UNAUTHENTICATED`;case`FORBIDDEN`:return`FORBIDDEN`;case`NOT_FOUND`:return`NOT_FOUND`;case`CONFLICT`:return`CONFLICT`;case`PRECONDITION_FAILED`:return`PRECONDITION_FAILED`;case`TOO_MANY_REQUESTS`:return`RATE_LIMITED`;default:return}}function Vl(e){if(e===void 0||e===408)return;if(e===405)return`NOT_FOUND`;if(e===412)return`PRECONDITION_FAILED`;if(e===422)return`VALIDATION_ERROR`;let t=iu(e);return t===`BACKEND`&&e>=400&&e<500?`VALIDATION_ERROR`:t}const Hl=[/\bselect\b.+?\bfrom\b/i,/\binsert\b.+?\binto\b/i,/\bupdate\b.+?\bset\b/i,/\bdelete\b.+?\bfrom\b/i,/\bparams:\s/i,/\.ts\(\d+,\d+\)/,/at\s+\S+\s+\(.*:\d+:\d+\)/,/node_modules\//,/drizzle/i];function Ul(e){for(let t of Hl)if(t.test(e))return`An internal error occurred. Please try again or contact support.`;return e}function Wl(e,t){if(typeof t!=`string`)return;let n=on(e,t);if(n)throw new G(`VALIDATION_ERROR`,n)}function $(e){if(e instanceof G)return e;if(e instanceof a){if(e.cause instanceof G)return e.cause;let t=e.data,n=t?.warmhub?.code,r=typeof t?.code==`string`?Bl(t.code):void 0,i=Vl(t?.httpStatus),a=t?.warmhub?.message??Ul(e.message);return new G(n??r??i??`BACKEND`,a,t?.warmhub?.status??t?.httpStatus,t?.warmhub?.hint,t?.warmhub?.retryAfter??t?.retryAfter,n,t?.warmhub?.details)}if(e instanceof Error){let t=e;if(e.name===`WarmHubError`&&typeof t.code==`string`){let n=new G(t.code,Ul(e.message),typeof t.status==`number`?t.status:void 0,typeof t.hint==`string`?t.hint:void 0,typeof t.retryAfter==`number`?t.retryAfter:void 0,typeof t.errorCode==`string`?t.errorCode:typeof t.backendCode==`string`?t.backendCode:void 0,t.details);return Kl(e)&&Object.defineProperty(n,Gl,{value:!0}),n}return e.name===`AbortError`?new G(`CANCELLED`,e.message):e instanceof TypeError&&/fetch/i.test(e.message)?new G(`NETWORK`,e.message):new G(`BACKEND`,Ul(e.message))}return new G(`BACKEND`,`Unknown SDK error`)}const Gl=Symbol.for(`@warmhub/sdk-ts:allStreamOperationsFailed`);function Kl(e){if(e instanceof ns)return!0;if(!(e instanceof Error))return!1;let t=e;return t[Gl]===!0||t.name===`WarmHubError`&&Array.isArray(t.receipts)&&Array.isArray(t.operations)}function ql(e){return Kl(e)}function Jl(e){return e instanceof G}function Yl(e){if(e instanceof Lc||Kl(e))return!1;let t=$(e);return t.kind===`NETWORK`||t.kind===`CANCELLED`||t.kind===`BACKEND`||t.kind===`RATE_LIMITED`}const Xl=/* @__PURE__ */ new Set([`ConnectionRefused`,`ECONNREFUSED`,`ENOTFOUND`,`ETIMEDOUT`,`EAI_AGAIN`]);function Zl(e){if(e instanceof TypeError&&/fetch/i.test(e.message))return!0;if(e&&typeof e==`object`){let t=e.code;if(typeof t==`string`&&Xl.has(t))return!0}return!1}function Ql(e){return`Unable to connect to ${e}. Is the computer able to access the url?`}function $l(e,t){if(Gc(e))return!1;let n=Er(e),r=Er(t);return!n||!r?!1:Ar(n,r)<0}function eu(e,t){return new G(`CLIENT_INCOMPATIBLE`,e,412,t)}function tu(e,t){let n=Jc(e,t);if(n)throw eu(n.message,n.hint)}function nu(e,t){if(e===`thing.rename`&&typeof t?.eventRequestId!=`string`)return new G(`VALIDATION_ERROR`,`thing.rename takes (orgName, graphName, name, newName, { eventRequestId }): name and newName are full Thing names. The v1 order (orgName, graphName, shapeName, oldName, newName, opts) is gone.`)}var ru=class e{apiUrl;fetchImpl;accessToken;clientIdentity;#e;decorateResponses;functionLogMode;getToken;compatibilityCheck;overrideNoticePrinted=!1;compatibilityNoticesPrinted=/* @__PURE__ */ new Set;graphExport=lc((e,t)=>this.fetchWithAuth(`${this.apiUrl.replace(/\/$/,``)}${e}`,t),e=>this.httpResponseError(e),(e,t)=>(this.fetchImpl??globalThis.fetch)(e,t));noteCompatibilityHeaders(e){let t=[],n=e.get(`X-WarmHub-Client-Minimum`);if(n){let{name:e,version:r}=this.clientIdentity;t.push(`${e} ${r} is older than the backend's minimum supported version ${n}. ${qc(e)}`)}let r=e.get(`X-WarmHub-Client-Flags-Honored`);if(r!==null){let e=new Set(r.split(`,`));for(let n of this.clientFlags)e.has(n)||t.push(`client flag "${n}" is not honored by this backend`)}for(let e of t)this.compatibilityNoticesPrinted.has(e)||(this.compatibilityNoticesPrinted.add(e),console.error(`warmhub: ${e}`))}noteCompatibilityOverride(){this.overrideNoticePrinted||(this.overrideNoticePrinted=!0,console.error(`warmhub: compatibility checks overridden by client flag compatibility-override; the server remains authoritative.`))}assertWriteCompatible(){return this.clientFlags.includes(`compatibility-override`)?(this.noteCompatibilityOverride(),Promise.resolve()):Gc(this.clientIdentity.version)&&Yc(this.apiUrl,`https://api.warmhub.ai`)?Promise.reject(eu(`Development client ${this.clientIdentity.name}/${this.clientIdentity.version} cannot write to production.`,`Install a released WarmHub client artifact before writing to api.warmhub.ai.`)):Gc(this.clientIdentity.version)&&this.clientIdentity.name!==`warmhub-cli`?Promise.resolve():this.diagnostics.assertCompatible()}pinnedShapeRefusal(e,t){if(e!==`stream.append`)return;let n=t?.operations;if(!Array.isArray(n))return;let r=n.findIndex(e=>Array.isArray(e?.shapes)&&e.shapes.some(e=>typeof e==`string`&&_o(e)));return r<0?void 0:new K(r,fo)}createLocalRefusalLink(){return()=>({op:e,next:t})=>{let n=nu(e.path,e.input)??this.pinnedShapeRefusal(e.path,e.input);return n?u(e=>{e.error(a.from(n))}):t(e)}}createCompatibilityLink(){return()=>({op:e,next:t})=>e.type!==`mutation`||Zn.has(e.path)?t(e):u(n=>{let r=!1,i;return(async()=>{try{await this.assertWriteCompatible()}catch(e){if(r)return;n.error(a.from(e));return}r||(i=t(e).subscribe(n))})(),()=>{r=!0,i?.unsubscribe()}})}auth={getClientId:async()=>{try{return await this.trpc.auth.getClientId.query()}catch(e){throw $(e)}},sync:async()=>{try{return await this.trpc.auth.sync.mutate()}catch(e){throw $(e)}},currentUser:async()=>{try{return await this.trpc.auth.currentUser.query()}catch(e){throw $(e)}},whoami:async()=>{try{return await this.trpc.auth.whoami.query()}catch(e){throw $(e)}}};homepage={featuredLists:async()=>{try{return await this.trpc.homepage.featuredLists.query()}catch(e){throw $(e)}}};access={resolve:async e=>{try{return await this.trpc.access.resolve.query(e)}catch(e){throw $(e)}}};diagnostics={ping:async()=>{let e=await this.fetchWithAuth(`${this.apiUrl.replace(/\/$/,``)}/health`);if(!e.ok)throw new G(`BACKEND`,`Health request failed with status ${e.status}`,e.status);return await e.json()},capabilities:async()=>{try{return await this.trpc.diagnostics.capabilities.query()}catch(e){throw $(e)}},assertCompatible:()=>{if(this.compatibilityCheck)return this.compatibilityCheck;let e=(async()=>{tu(await this.diagnostics.capabilities(),this.clientIdentity)})();return this.compatibilityCheck=e,e.catch(t=>{Jl(t)&&t.code===`CLIENT_INCOMPATIBLE`||this.compatibilityCheck===e&&(this.compatibilityCheck=void 0)}),e}};component={list:async(e,t,n)=>{try{return await this.trpc.component.list.query({orgName:e,graphName:t,limit:n?.limit,cursor:n?.cursor})}catch(e){throw $(e)}},listIter:(e,t,n)=>Z(r=>this.component.list(e,t,{...n,cursor:r}),e=>e.items,n?.cursor),listAll:async(e,t,n)=>{let{max:r,...i}=n??{};return await Q(n=>this.component.list(e,t,{...i,cursor:n}),e=>e.items,r,i.cursor)},search:async(e,t)=>{try{return await this.trpc.component.search.query({query:e,limit:t?.limit,cursor:t?.cursor})}catch(e){throw $(e)}},searchIter:(e,t)=>Z(n=>this.component.search(e,{...t,cursor:n}),e=>e.items,t?.cursor),searchAll:async(e,t)=>{let{max:n,...r}=t??{};return await Q(t=>this.component.search(e,{...r,cursor:t}),e=>e.items,n,r.cursor)},get:async(e,t,n)=>{try{return await this.trpc.component.get.query({orgName:e,graphName:t,componentRef:n})}catch(e){throw $(e)}},history:async(e,t,n)=>{try{return await this.trpc.component.history.query({orgName:e,graphName:t,componentRef:n?.componentRef,limit:n?.limit})}catch(e){throw $(e)}},install:async(e,t,n,r)=>{try{return await this.trpc.component.install.mutate({orgName:e,graphName:t,componentRef:n,submissionId:r.submissionId})}catch(e){throw $(e)}},uninstall:async(e,t,n,r)=>{try{return await this.trpc.component.uninstall.mutate({orgName:e,graphName:t,componentRef:n,submissionId:r.submissionId})}catch(e){throw $(e)}},registry:{register:async(e,t,n)=>{try{return await this.trpc.component.registry.register.mutate({orgName:e,componentName:t,...n})}catch(e){throw $(e)}},unregister:async(e,t)=>{try{return await this.trpc.component.registry.unregister.mutate({orgName:e,componentName:t})}catch(e){throw $(e)}},list:async e=>{try{return await this.trpc.component.registry.list.query({orgName:e})}catch(e){throw $(e)}},view:async(e,t)=>{try{return await this.trpc.component.registry.view.query({orgName:e,componentName:t})}catch(e){throw $(e)}},update:async(e,t,n)=>{try{return await this.trpc.component.registry.update.mutate({orgName:e,componentName:t,...n})}catch(e){throw $(e)}},resolve:async(e,t,n)=>await this.requestJson(`/api/component-registry/${encodeURIComponent(e)}/${encodeURIComponent(t)}/resolve`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({installRepo:n})}),setupCall:async(e,t,n)=>(await this.assertWriteCompatible(),await this.requestJson(`/api/component-registry/${encodeURIComponent(e)}/${encodeURIComponent(t)}/setup-call`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(n)}))},cli:{call:async(e,t,n,r)=>(await this.assertWriteCompatible(),await this.requestJson(`/api/component-registry/${encodeURIComponent(e)}/${encodeURIComponent(t)}/cli/${encodeURIComponent(n)}`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(r)}))}};ops(e){return new Ms(e)}commit={validate:async(e,t,n,r)=>{try{return await Ro(this.trpc.commit.validate,this.thingShapesReader(e,t),e,t,n,r)}catch(e){throw $(e)}},apply:async(e,t,n,r,i)=>{try{return await xs(this,{orgName:e,graphName:t,committer:i?.committer,message:n,componentRef:i?.componentRef,chunkSize:i?.chunkSize,skipExisting:i?.skipExisting,streamId:i?.streamId,submissionId:i?.submissionId,returnGraphSeq:i?.returnGraphSeq,retry:i?.retry,operations:r})}catch(e){throw e instanceof ts||e instanceof ns?e:$(e)}},applyStreaming:(e,t,n,r,i)=>Wc({orgName:e,graphName:t,message:n,operations:r,options:i},{prepare:async e=>await this.prepareStreamingSubmissionRequest(e),localError:(e,t)=>new G(e,t),normalizeLocalError:$,readThings:this.thingShapesReader(e,t)}),getReceipt:async(e,t,n)=>{try{return await this.trpc.commit.getReceipt.query({orgName:e,graphName:t,eventRequestId:n})}catch(e){throw $(e)}},getReceiptMetadata:async(e,t,n)=>{try{return await this.trpc.commit.getReceiptMetadata.query({orgName:e,graphName:t,eventRequestId:n})}catch(e){throw $(e)}}};org={get:async e=>{try{return await this.trpc.org.get.query({orgName:e})}catch(e){throw $(e)}},getCallerRole:async e=>{try{return await this.trpc.org.getCallerRole.query({orgName:e})}catch(e){throw $(e)}},list:async e=>{try{return{items:await this.trpc.org.list.query({includeArchived:e?.includeArchived})}}catch(e){throw $(e)}},create:async(e,t,n)=>{try{return await this.trpc.org.create.mutate({name:e,displayName:t,description:n})}catch(e){throw $(e)}},setDescription:async(e,t)=>{try{return await this.trpc.org.setDescription.mutate({orgName:e,description:t})}catch(e){throw $(e)}},setDisplayName:async(e,t)=>{try{return await this.trpc.org.setDisplayName.mutate({orgName:e,displayName:t})}catch(e){throw $(e)}},rename:async(e,t)=>{try{return await this.trpc.org.rename.mutate({orgName:e,newName:t})}catch(e){throw $(e)}},update:async e=>{try{return await this.trpc.org.update.mutate(e)}catch(e){throw $(e)}},addMember:async(e,t,n=`editor`)=>{try{return await this.trpc.org.addMember.mutate({orgName:e,email:t,role:n})}catch(e){throw $(e)}},removeMember:async(e,t)=>{try{await this.trpc.org.removeMember.mutate({orgName:e,email:t})}catch(e){throw $(e)}},leave:async e=>{try{await this.trpc.org.leave.mutate({orgName:e})}catch(e){throw $(e)}},changeMemberRole:async(e,t,n)=>{try{return await this.trpc.org.changeMemberRole.mutate({orgName:e,email:t,role:n})}catch(e){throw $(e)}},setMemberScopes:async(e,t,n)=>{try{await this.trpc.org.setMemberScopes.mutate({orgName:e,email:t,scopes:n})}catch(e){throw $(e)}},clearMemberScopes:async(e,t)=>{try{await this.trpc.org.clearMemberScopes.mutate({orgName:e,email:t})}catch(e){throw $(e)}},listMembers:async(e,t)=>{try{return await this.trpc.org.listMembers.query({orgName:e,pending:t?.pending})}catch(e){throw $(e)}},archive:async e=>{try{return await this.trpc.org.archive.mutate({orgName:e})}catch(e){throw $(e)}},unarchive:async e=>{try{return await this.trpc.org.unarchive.mutate({orgName:e})}catch(e){throw $(e)}},serviceAccounts:{create:async e=>{try{return await this.trpc.org.serviceAccount.create.mutate({orgName:e.orgName,name:e.name,role:e.role,description:e.description})}catch(e){throw $(e)}},list:async e=>{try{return await this.trpc.org.serviceAccount.list.query({orgName:e.orgName,includeDisabled:e.includeDisabled})}catch(e){throw $(e)}},get:async e=>{try{return await this.trpc.org.serviceAccount.get.query({orgName:e.orgName,name:e.name})}catch(e){throw $(e)}},setRole:async e=>{try{return await this.trpc.org.serviceAccount.setRole.mutate({orgName:e.orgName,name:e.name,role:e.role})}catch(e){throw $(e)}},disable:async e=>{try{return await this.trpc.org.serviceAccount.disable.mutate({orgName:e.orgName,name:e.name})}catch(e){throw $(e)}},enable:async e=>{try{return await this.trpc.org.serviceAccount.enable.mutate({orgName:e.orgName,name:e.name})}catch(e){throw $(e)}},delete:async e=>{try{await this.trpc.org.serviceAccount.delete.mutate({orgName:e.orgName,name:e.name})}catch(e){throw $(e)}}}};graph={checkpoint:Is(()=>this.trpc,$),export:(e,t,n)=>this.graphExport.stream(e,t,n),exportPrepare:(e,t,n)=>this.graphExport.prepare(e,t,n),get:async(e,t)=>{try{return await this.trpc.graph.get.query({orgName:e,graphName:t})}catch(e){throw $(e)}},getStats:async(e,t)=>{try{return await this.trpc.graph.stats.query({orgName:e,graphName:t})}catch(e){throw $(e)}},getStatsBatch:async(e,t)=>{try{return await this.trpc.graph.statsBatch.query({orgName:e,graphNames:t})}catch(e){throw $(e)}},getConfigureStats:async(e,t)=>{try{return await this.trpc.graph.configureStats.query({orgName:e,graphName:t})}catch(e){throw $(e)}},getShapeInstanceCounts:async(e,t)=>{try{return await this.trpc.graph.shapeInstanceCounts.query({orgName:e,graphName:t})}catch(e){throw $(e)}},list:async(e,t)=>{try{return await this.trpc.graph.list.query({orgName:e,limit:t?.limit,cursor:t?.cursor,includeArchived:t?.includeArchived,search:t?.search,sort:t?.sort})}catch(e){throw $(e)}},listIter:(e,t)=>Z(n=>this.graph.list(e,{...t,cursor:n}),e=>e.items,t?.cursor),listAll:async(e,t)=>{let{max:n,...r}=t??{};return await Q(t=>this.graph.list(e,{...r,cursor:t}),e=>e.items,n,r.cursor)},search:async(e,t)=>{try{return await this.trpc.graph.search.query({query:e,limit:t?.limit,cursor:t?.cursor})}catch(e){throw $(e)}},searchIter:(e,t)=>Z(n=>this.graph.search(e,{...t,cursor:n}),e=>e.items,t?.cursor),searchAll:async(e,t)=>{let{max:n,...r}=t??{};return await Q(t=>this.graph.search(e,{...r,cursor:t}),e=>e.items,n,r.cursor)},create:async(e,t,n,r,i)=>{try{return await this.trpc.graph.create.mutate({orgName:e,graphName:t,description:n,visibility:r,displayName:i})}catch(e){throw $(e)}},setDescription:async(e,t,n)=>{try{return await this.trpc.graph.setDescription.mutate({orgName:e,graphName:t,description:n})}catch(e){throw $(e)}},setDisplayName:async(e,t,n)=>{try{return await this.trpc.graph.setDisplayName.mutate({orgName:e,graphName:t,displayName:n})}catch(e){throw $(e)}},setVisibility:async(e,t,n)=>{try{return await this.trpc.graph.setVisibility.mutate({orgName:e,graphName:t,visibility:n})}catch(e){throw $(e)}},rename:async(e,t,n)=>{try{return await this.trpc.graph.rename.mutate({orgName:e,graphName:t,newName:n})}catch(e){throw $(e)}},update:async e=>{try{return await this.trpc.graph.update.mutate({orgName:e.orgName,graphName:e.graphName,displayName:e.displayName,newName:e.newName})}catch(e){throw $(e)}},archive:async(e,t)=>{try{return await this.trpc.graph.archive.mutate({orgName:e,graphName:t})}catch(e){throw $(e)}},unarchive:async(e,t)=>{try{return await this.trpc.graph.unarchive.mutate({orgName:e,graphName:t})}catch(e){throw $(e)}},delete:async(e,t)=>{try{let n=await this.trpc.graph.delete.mutate({orgName:e,graphName:t});return{graceExpiresAt:new Date(n.graceExpiresAt)}}catch(e){throw $(e)}},listPage:async(e,t)=>{try{return await this.trpc.graph.listPage.query({orgName:e,limit:t?.limit,cursor:t?.cursor,includeArchived:t?.includeArchived,search:t?.search,sort:t?.sort})}catch(e){throw $(e)}},listPageIter:(e,t)=>Z(n=>this.graph.listPage(e,{...t,cursor:n}),e=>e.items,t?.cursor),listPageAll:async(e,t)=>{let{max:n,...r}=t??{};return await Q(t=>this.graph.listPage(e,{...r,cursor:t}),e=>e.items,n,r.cursor)},listForCaller:async e=>{try{return await this.trpc.graph.listForCaller.query({limit:e?.limit,sort:e?.sort})}catch(e){throw $(e)}},explore:async e=>{try{return await this.trpc.graph.explore.query({search:e?.search,org:e?.org,activity:e?.activity,hasSubscriptions:e?.hasSubscriptions,minThings:e?.minThings,sort:e?.sort,limit:e?.limit,cursor:e?.cursor,slugs:e?.slugs})}catch(e){throw $(e)}},exploreIter:e=>(Sl(e),Z(t=>this.graph.explore({...e,cursor:t}),e=>e.items,e?.cursor)),exploreAll:async e=>{Sl(e);let{max:t,...n}=e??{};return await Q(e=>this.graph.explore({...n,cursor:e}),e=>e.items,t,n.cursor)},getReadme:async(e,t)=>{try{return await this.trpc.graph.getReadme.query({orgName:e,graphName:t})}catch(e){throw $(e)}},getAgents:async(e,t)=>{try{return await this.trpc.graph.getAgents.query({orgName:e,graphName:t})}catch(e){throw $(e)}},getLicense:async(e,t)=>{try{return await this.trpc.graph.getLicense.query({orgName:e,graphName:t})}catch(e){throw $(e)}},describe:async(e,t,n={})=>{try{return await this.trpc.graph.describe.query({orgName:e,graphName:t,includeHead:n.includeHead,includeIndexedFields:n.includeIndexedFields})}catch(e){throw $(e)}},setReadme:async(e,t,n,r)=>{try{return Wl(`Readme.content`,n),await this.trpc.graph.setReadme.mutate({orgName:e,graphName:t,eventRequestId:r.eventRequestId,content:n})}catch(e){throw $(e)}},setAgents:async(e,t,n,r)=>{try{return Wl(`Agents.content`,n),await this.trpc.graph.setAgents.mutate({orgName:e,graphName:t,eventRequestId:r.eventRequestId,content:n})}catch(e){throw $(e)}},getLlmsTxt:async(e,t)=>{try{return await this.trpc.graph.getLlmsTxt.query({orgName:e,graphName:t})}catch(e){throw $(e)}},index:{describe:async(e,t)=>{try{return await this.trpc.graph.index.describe.query({orgName:e,graphName:t})}catch(e){throw $(e)}},pin:async(e,t,n,r)=>{try{return await this.trpc.graph.index.pin.mutate({orgName:e,graphName:t,shape:n,fieldPath:r})}catch(e){throw $(e)}},unpin:async(e,t,n,r)=>{try{return await this.trpc.graph.index.unpin.mutate({orgName:e,graphName:t,shape:n,fieldPath:r})}catch(e){throw $(e)}}}};shape={list:async(e,t,n)=>{try{return await this.trpc.shape.list.query({orgName:e,graphName:t,match:n?.match,componentRef:n?.componentRef,excludeComponents:n?.excludeComponents,includeRetracted:n?.includeRetracted})}catch(e){throw $(e)}},get:async(e,t,n,r)=>{try{return await this.trpc.shape.get.query({orgName:e,graphName:t,shapeName:n,includeRetracted:r?.includeRetracted})}catch(e){throw $(e)}},create:async(e,t,n,r,i)=>{let a=Yo(n,{fields:r,...i.description===void 0?{}:{description:i.description},...i.composes===void 0?{}:{composes:i.composes}},`add`);if(a)throw new G(`VALIDATION_ERROR`,a);try{return await this.trpc.shape.create.mutate({orgName:e,graphName:t,shapeName:n,fields:r,eventRequestId:i.eventRequestId,description:i.description,composes:i.composes})}catch(e){throw $(e)}},revise:async(...e)=>{let[t,n,r]=e,i=e.length===5?e[3]:void 0,a=e.length===5?e[4]:e[3],o=i?Yo(r,{fields:i,...a.description===void 0?{}:{description:a.description},...a.composes===void 0?{}:{composes:a.composes}},`revise`):void 0;if(o)throw new G(`VALIDATION_ERROR`,o);try{return await this.trpc.shape.revise.mutate({orgName:t,graphName:n,shapeName:r,newFields:i,eventRequestId:a.eventRequestId,description:a.description,composes:a.composes})}catch(e){throw $(e)}},remove:async(e,t,n,r)=>{try{return await this.trpc.shape.remove.mutate({orgName:e,graphName:t,shapeName:n,eventRequestId:r.eventRequestId})}catch(e){throw $(e)}},rename:async(e,t,n,r,i)=>{try{return await this.trpc.shape.rename.mutate({orgName:e,graphName:t,oldName:n,newName:r,eventRequestId:i.eventRequestId})}catch(e){throw $(e)}},history:async(e,t,n,r={})=>{try{return await this.trpc.shape.history.query({orgName:e,graphName:t,name:n,includeRetracted:r.includeRetracted,limit:r.limit,cursor:r.cursor})}catch(e){throw $(e)}},historyIter:(e,t,n,r={})=>Z(i=>this.shape.history(e,t,n,{...r,cursor:i}),e=>e.versions,r.cursor),historyAll:async(e,t,n,r)=>{let{max:i,...a}=r??{};return await Q(r=>this.shape.history(e,t,n,{...a,cursor:r}),e=>e.versions,i,a.cursor)}};subscription={create:async e=>{try{return _l(await this.trpc.subscription.create.mutate(Nl(e)))}catch(e){throw $(e)}},get:async(...e)=>{try{return _l(await this.trpc.subscription.get.query(kl(e)))}catch(e){throw $(e)}},reveal:async(...e)=>{try{return await this.trpc.subscription.reveal.query(kl(e))}catch(e){throw $(e)}},list:async(...e)=>{try{return vl(await this.trpc.subscription.list.query(Al(e)))}catch(e){throw $(e)}},update:async e=>{try{return _l(await this.trpc.subscription.update.mutate(Pl(e)))}catch(e){throw $(e)}},pause:async(...e)=>{try{return await this.trpc.subscription.pause.mutate(kl(e))}catch(e){throw $(e)}},resume:async(...e)=>{try{return await this.trpc.subscription.resume.mutate(kl(e))}catch(e){throw $(e)}},remove:async(...e)=>{try{return await this.trpc.subscription.remove.mutate(kl(e))}catch(e){throw $(e)}},bindCredentials:async(...e)=>{try{return await this.trpc.subscription.bindCredentials.mutate(jl(e))}catch(e){throw $(e)}},unbindCredentials:async(...e)=>{try{return await this.trpc.subscription.unbindCredentials.mutate(Ml(e))}catch(e){throw $(e)}}};action={acquireLease:async(e,t,n,r,i,a)=>{try{return await this.trpc.action.acquireLease.mutate({orgName:e,graphName:t,subscriptionName:n,holderId:r,holderType:i,graceMs:a?.graceMs,ttlMs:a?.ttlMs})}catch(e){throw $(e)}},heartbeatLease:async(e,t,n,r,i)=>{try{return await this.trpc.action.heartbeatLease.mutate({orgName:e,graphName:t,subscriptionName:n,holderId:r,ttlMs:i})}catch(e){throw $(e)}},releaseLease:async(e,t,n,r)=>{try{return await this.trpc.action.releaseLease.mutate({orgName:e,graphName:t,subscriptionName:n,holderId:r})}catch(e){throw $(e)}},claimDelivery:async(e,t,n,r)=>{let i=typeof n==`string`?{runId:n}:n;try{return await this.trpc.action.claimDelivery.mutate({orgName:e,graphName:t,...i,holderId:r})}catch(e){throw $(e)}},completeDelivery:async(e,t,n,r)=>{let i=typeof n==`string`?{runId:n}:n;try{return await this.trpc.action.completeDelivery.mutate({orgName:e,graphName:t,...i,holderId:r})}catch(e){throw $(e)}},liveFeed:async(e,t,n,r)=>{try{return await this.trpc.action.liveFeed.query({orgName:e,graphName:t,subscriptionName:n,limit:r?.limit,cursor:r?.cursor})}catch(e){throw $(e)}},liveFeedIter:(e,t,n,r)=>Z(i=>this.action.liveFeed(e,t,n,{...r,cursor:i}),e=>e.items,r?.cursor),liveFeedAll:async(e,t,n,r)=>{let{max:i,...a}=r??{};return await Q(r=>this.action.liveFeed(e,t,n,{...a,cursor:r}),e=>e.items,i,a.cursor)},listRuns:async(e,t,n)=>{try{return await this.trpc.action.listRuns.query({orgName:e,graphName:t,runId:n?.runId,subscriptionName:n?.subscriptionName,status:n?.status,outcome:n?.outcome,since:n?.since,cursor:n?.cursor,limit:n?.limit})}catch(e){throw $(e)}},listRunsIter:(e,t,n)=>Z(r=>this.action.listRuns(e,t,{...n,since:r===void 0?n?.since:void 0,cursor:r}),e=>e.items,n?.cursor),listRunsAll:async(e,t,n)=>{let{max:r,...i}=n??{};return await Q(n=>this.action.listRuns(e,t,{...i,since:n===void 0?i.since:void 0,cursor:n}),e=>e.items,r,i.cursor)},latestRuns:async(e,t)=>{try{return await this.trpc.action.latestRuns.query({orgName:e,graphName:t})}catch(e){throw $(e)}},runStats:async(e,t,n)=>{try{return await this.trpc.action.runStats.query({orgName:e,graphName:t,subscriptionName:n?.subscriptionName,since:n?.since})}catch(e){throw $(e)}},getRunAttempts:async(e,t,n)=>{try{return await this.trpc.action.getRunAttempts.query({orgName:e,graphName:t,runId:n})}catch(e){throw $(e)}},listNotifications:async(e,t,n)=>{try{return await this.trpc.action.listNotifications.query({orgName:e,graphName:t,since:n?.since,limit:n?.limit})}catch(e){throw $(e)}}};collection={create:async(e,t,n)=>{try{return Rl(n.type,n),await this.trpc.collection.create.mutate({orgName:e,graphName:t,eventRequestId:n.eventRequestId,type:n.type,name:n.name,members:n.members,from:n.from,add:n.add,remove:n.remove,replaceMembers:n.replaceMembers,query:n.query,sourceOrgName:n.sourceGraph?.orgName,sourceGraphName:n.sourceGraph?.graphName,skipExisting:n.skipExisting,message:n.message,committer:n.committer})}catch(e){throw $(e)}},members:async(e,t,n,r)=>{try{return await this.trpc.collection.members.query({orgName:e,graphName:t,wref:n,version:r?.version,limit:r?.limit,cursor:r?.cursor,shape:r?.shape})}catch(e){throw $(e)}},membersIter:(e,t,n,r)=>{let i=r?.version;return Z(async a=>{let o=await this.collection.members(e,t,n,{...r,version:i,cursor:a});return i??=o.version,o},e=>e.items,r?.cursor)},membersAll:async(e,t,n,r)=>{let{max:i,...a}=r??{},o=a.version;return await Q(async r=>{let i=await this.collection.members(e,t,n,{...a,version:o,cursor:r});return o??=i.version,i},e=>e.items,i,a.cursor)},contains:async(e,t,n,r,i)=>{try{return await this.trpc.collection.contains.query({orgName:e,graphName:t,wref:n,version:i?.version,members:r,position:i?.position,shape:i?.shape})}catch(e){throw $(e)}},diff:async(e,t,n,r,i)=>{try{return await this.trpc.collection.diff.query({orgName:e,graphName:t,leftWref:n,rightWref:r,leftVersion:i?.leftVersion,rightVersion:i?.rightVersion,mode:i?.mode,shape:i?.shape})}catch(e){throw $(e)}},revise:async(e,t,n,r)=>{try{if(Fl(r.query)&&!Il(r.query))throw new G(`VALIDATION_ERROR`,`Selector-backed collection sources require shape, about, match, componentRef, or where; kind and excludeComponents only narrow an existing selector.`);if(r.sourceGraph&&!Il(r.query))throw new G(`VALIDATION_ERROR`,`sourceGraph requires a selector-backed collection query`);if(r.sourceGraph&&Ll(r))throw new G(`VALIDATION_ERROR`,`sourceGraph cannot be combined with explicit members; use canonical wh:org/graph/... member wrefs or omit sourceGraph.`);return await this.trpc.collection.revise.mutate({orgName:e,graphName:t,eventRequestId:r.eventRequestId,wref:n,members:r.members,add:r.add,remove:r.remove,query:r.query,sourceOrgName:r.sourceGraph?.orgName,sourceGraphName:r.sourceGraph?.graphName,message:r.message,committer:r.committer})}catch(e){throw $(e)}},stats:async(e,t,n,r)=>{try{return await this.trpc.collection.stats.query({orgName:e,graphName:t,wref:n,version:r?.version,shape:r?.shape})}catch(e){throw $(e)}}};view={evaluate:async(e,t,n,r)=>{try{return await this.trpc.view.evaluate.query({orgName:e,graphName:t,wref:n,limit:r?.limit,cursor:r?.cursor})}catch(e){throw $(e)}},evaluateIter:(e,t,n,r)=>Z(i=>this.view.evaluate(e,t,n,{...r,cursor:i}),e=>e.items,r?.cursor),evaluateAll:async(e,t,n,r)=>{let{max:i,...a}=r??{};return await Q(r=>this.view.evaluate(e,t,n,{...a,cursor:r}),e=>e.items,i,a.cursor)}};grant=Jo(()=>this.trpc,$);thing={head:async(e,t,n)=>{try{return await this.trpc.thing.head.query({orgName:e,graphName:t,shape:n?.shape,declaredShape:n?.declaredShape,shapeless:n?.shapeless,includeValidatedShapes:n?.includeValidatedShapes,kind:Dl(n?.kind),match:n?.match,dataMode:n?.dataMode,includeRetracted:n?.includeRetracted,limit:n?.limit,cursor:n?.cursor,componentRef:n?.componentRef,excludeComponents:n?.excludeComponents,excludeInfraShapes:n?.excludeInfraShapes,where:n?.where,sinceGraphSeq:n?.sinceGraphSeq})}catch(e){throw $(e)}},headIter:(e,t,n)=>Z(r=>this.thing.head(e,t,{...n,cursor:r}),e=>e.items,n?.cursor),headAll:async(e,t,n)=>{let{max:r,...i}=n??{};return await Q(n=>this.thing.head(e,t,{...i,cursor:n}),e=>e.items,r,i.cursor)},headChanges:async(e,t,n)=>(bl(n?.sinceGraphSeq),await Cl(r=>this.thing.head(e,t,{...n,includeRetracted:!0,cursor:r}))),get:async(e,t,n,r,i)=>{try{return await this.trpc.thing.get.query({orgName:e,graphName:t,wref:n,version:r,includeRetracted:i?.includeRetracted,dataMode:i?.dataMode})}catch(e){throw $(e)}},getWithLease:async(e,t,n,r)=>{try{return await this.trpc.thing.getWithLease.mutate({orgName:e,graphName:t,wref:n,ttlMs:r?.ttlMs})}catch(e){throw $(e)}},releaseLease:async(e,t,n,r)=>{try{await this.trpc.thing.releaseLease.mutate({orgName:e,graphName:t,wref:n,leaseId:r})}catch(e){throw $(e)}},graph:async(e,t,n,r)=>{try{return await this.trpc.thing.graph.query({orgName:e,graphName:t,wref:n,version:r?.version,depth:r?.depth,limit:r?.limit})}catch(e){throw $(e)}},getMany:async(e,t,n,r,i)=>{try{return await El(n,i,n=>this.trpc.thing.getMany.query({orgName:e,graphName:t,wrefs:n,version:r,includeRetracted:i?.includeRetracted,dataMode:i?.dataMode}))}catch(e){throw $(e)}},headVersions:async(e,t,n,r)=>{try{return await El(n,r,n=>this.trpc.thing.headVersions.query({orgName:e,graphName:t,wrefs:n}))}catch(e){throw $(e)}},names:async(e,t,n,r)=>{try{return await El(n,r,n=>this.trpc.thing.names.query({orgName:e,graphName:t,durableIds:n}))}catch(e){throw $(e)}},history:async(e,t,n)=>{try{return await this.trpc.thing.history.query({orgName:e,graphName:t,wref:n.wref,shape:n.shape,declaredShape:n.declaredShape,about:n.about,includeRetracted:n.includeRetracted,resolveCollections:n.resolveCollections,match:n.match,limit:n.limit,cursor:n.cursor})}catch(e){throw $(e)}},historyIter:(e,t,n)=>Z(r=>this.thing.history(e,t,{...n,cursor:r}),e=>e.versions,n.cursor),historyAll:async(e,t,n)=>{let{max:r,...i}=n;return await Q(n=>this.thing.history(e,t,{...i,cursor:n}),e=>e.versions,r,i.cursor)},rename:async(e,t,n,r,i)=>{try{return await this.trpc.thing.rename.mutate({orgName:e,graphName:t,name:n,newName:r,eventRequestId:i.eventRequestId})}catch(e){throw $(e)}},remove:async(e,t,n,r)=>{try{return await this.trpc.thing.remove.mutate({orgName:e,graphName:t,wref:n,expectedVersion:r.expectedVersion,eventRequestId:r.eventRequestId})}catch(e){throw $(e)}},redact:async(e,t,n,r)=>{try{return await this.trpc.thing.redact.mutate({orgName:e,graphName:t,durableId:n,expectedVersion:r.expectedVersion,eventRequestId:r.eventRequestId})}catch(e){throw $(e)}},rewrite:async(e,t,n,r)=>{try{return await this.trpc.thing.rewrite.mutate({orgName:e,graphName:t,wref:n,version:r.version,shapes:r.shapes,data:r.data,eventRequestId:r.eventRequestId})}catch(e){throw $(e)}},resolve:async(e,t,n)=>{try{return await this.trpc.thing.resolve.query({orgName:e,graphName:t,wref:n})}catch(e){throw $(e)}},about:async(e,t,n,r)=>{try{return await this.trpc.thing.about.query({orgName:e,graphName:t,wref:n,shape:r?.shape,match:r?.match,includeRetracted:r?.includeRetracted,depth:r?.depth,resolveCollections:r?.resolveCollections,role:r?.role,limit:r?.limit,cursor:r?.cursor,where:r?.where})}catch(e){throw $(e)}},aboutIter:(e,t,n,r)=>Z(i=>this.thing.about(e,t,n,{...r,cursor:i}),e=>e.assertions,r?.cursor),aboutAll:async(e,t,n,r)=>{let{max:i,...a}=r??{};return await Q(r=>this.thing.about(e,t,n,{...a,cursor:r}),e=>e.assertions,i,a.cursor)},query:async(e,t,n)=>{try{return await this.trpc.thing.query.query({orgName:e,graphName:t,shape:n?.shape,declaredShape:n?.declaredShape,shapeless:n?.shapeless,includeValidatedShapes:n?.includeValidatedShapes,about:n?.about,affirmedAbout:n?.affirmedAbout,kind:Dl(n?.kind),match:n?.match,includeRetracted:n?.includeRetracted,resolveCollections:n?.resolveCollections,role:n?.role,limit:n?.limit,cursor:n?.cursor,componentRef:n?.componentRef,excludeComponents:n?.excludeComponents,excludeInfraShapes:n?.excludeInfraShapes,where:n?.where,sinceGraphSeq:n?.sinceGraphSeq})}catch(e){throw $(e)}},queryIter:(e,t,n)=>Z(r=>this.thing.query(e,t,{...n,cursor:r}),e=>e.items,n?.cursor),queryAll:async(e,t,n)=>{let{max:r,...i}=n??{};return await Q(n=>this.thing.query(e,t,{...i,cursor:n}),e=>e.items,r,i.cursor)},queryChanges:async(e,t,n)=>(bl(n?.sinceGraphSeq),await Cl(r=>this.thing.query(e,t,{...n,includeRetracted:!0,cursor:r}))),search:async(e,t,n,r)=>{try{return await this.trpc.thing.search.query({orgName:e,graphName:t,query:n,shape:r?.shape,about:r?.about,affirmedAbout:r?.affirmedAbout,kind:Dl(r?.kind),match:r?.match,includeRetracted:r?.includeRetracted,resolveCollections:r?.resolveCollections,limit:r?.limit,cursor:r?.cursor,componentRef:r?.componentRef,excludeComponents:r?.excludeComponents,excludeInfraShapes:r?.excludeInfraShapes,mode:r?.mode,nameMatch:r?.nameMatch})}catch(e){throw $(e)}},searchIter:(e,t,n,r)=>Z(i=>this.thing.search(e,t,n,{...r,cursor:i}),e=>e.items,r?.cursor),searchAll:async(e,t,n,r)=>{let{max:i,...a}=r??{};return await Q(r=>this.thing.search(e,t,n,{...a,cursor:r}),e=>e.items,i,a.cursor)},count:async(e,t,n)=>{try{return await this.trpc.thing.count.query({orgName:e,graphName:t,shape:n?.shape,declaredShape:n?.declaredShape,shapeless:n?.shapeless,about:n?.about,affirmedAbout:n?.affirmedAbout,kind:Dl(n?.kind),match:n?.match,includeRetracted:n?.includeRetracted,resolveCollections:n?.resolveCollections,componentRef:n?.componentRef,excludeComponents:n?.excludeComponents,excludeInfraShapes:n?.excludeInfraShapes,where:n?.where,sinceGraphSeq:n?.sinceGraphSeq})}catch(e){throw $(e)}},refs:async(e,t,n,r)=>{try{return await this.trpc.thing.refs.query({orgName:e,graphName:t,wref:n,direction:r?.direction,fieldPath:r?.fieldPath,binding:r?.binding,limit:r?.limit,cursor:r?.cursor})}catch(e){throw $(e)}},refsIter:(e,t,n,r)=>Z(i=>this.thing.refs(e,t,n,{...r,cursor:i}),e=>e.items,r?.cursor),refsAll:async(e,t,n,r)=>{let{max:i,...a}=r??{};return await Q(r=>this.thing.refs(e,t,n,{...a,cursor:r}),e=>e.items,i,a.cursor)}};live={thingHead:async(e,t,n,r)=>this.watchRepoQuery(e,t,n?.signal,()=>this.thing.head(e,t,{shape:n?.shape,declaredShape:n?.declaredShape,shapeless:n?.shapeless,includeValidatedShapes:n?.includeValidatedShapes,kind:n?.kind,match:n?.match,dataMode:n?.dataMode,limit:n?.limit,cursor:n?.cursor,includeRetracted:n?.includeRetracted,where:n?.where}),r),thingHistory:async(e,t,n,r)=>this.watchRepoQuery(e,t,n.signal,()=>this.thing.history(e,t,{wref:n.wref,shape:n.shape,declaredShape:n.declaredShape,about:n.about,resolveCollections:n.resolveCollections,match:n.match,limit:n.limit,cursor:n.cursor,includeRetracted:n.includeRetracted}),r),subscriptionLog:async(e,t,n,r,i)=>this.watchRepoQuery(e,t,r?.signal,()=>this.action.liveFeed(e,t,n,{limit:r?.limit,cursor:r?.cursor}),i),subscribe:async(e,t,n,r)=>{let i=new AbortController,a=ou(n?.signal,i),o=0;return{close(){i.abort()},closed:this.runLiveLoop(()=>this.trpc.live.issueTicket.mutate({orgName:e,graphName:t}),a,async e=>{if(e.type!==`invalidate`)return;let t=e.data;o++,await lu(()=>r({topic:t.topic,affectedShapes:t.affectedShapes,affectedThings:t.affectedThings,affectedTargets:t.affectedTargets,hasNewCommit:t.hasNewCommit}))}).then(()=>({updates:o}))}}};token={create:async e=>{try{return await this.trpc.token.create.mutate(e)}catch(e){throw $(e)}},list:async e=>{try{return await this.trpc.token.list.query(e?.includeInactive?{includeInactive:!0}:void 0)}catch(e){throw $(e)}},listForServiceAccount:async(e,t)=>{try{return await this.trpc.token.list.query({serviceAccount:e,includeInactive:t?.includeInactive})}catch(e){throw $(e)}},get:async(e,t)=>{try{return await this.trpc.token.get.query({name:e,serviceAccount:t?.serviceAccount})}catch(e){throw $(e)}},revoke:async(e,t)=>{try{return await this.trpc.token.revoke.mutate({name:e,serviceAccount:t?.serviceAccount})}catch(e){throw $(e)}}};stream={append:async e=>{try{return await this.trpc.stream.append.mutate(e)}catch(e){throw $(e)}}};credential={createSet:async(e,t,n,r)=>{try{return await this.trpc.credential.createSet.mutate({orgName:e,graphName:t,name:n,scope:r?.scope??`repo`,description:r?.description})}catch(e){throw $(e)}},listSets:async(e,t)=>{try{return await this.trpc.credential.listSets.query({orgName:e,graphName:t})}catch(e){throw $(e)}},getSet:async(e,t,n)=>{try{return await this.trpc.credential.getSet.query({orgName:e,graphName:t,name:n})}catch(e){throw $(e)}},setKey:async(e,t,n,r,i)=>{try{return await this.trpc.credential.setKey.mutate({orgName:e,graphName:t,setName:n,keyName:r,value:i})}catch(e){throw $(e)}},setKeys:async(e,t,n,r)=>{try{return await this.trpc.credential.setKeys.mutate({orgName:e,graphName:t,setName:n,secrets:r})}catch(e){throw $(e)}},unsetKey:async(e,t,n,r)=>{try{return await this.trpc.credential.unsetKey.mutate({orgName:e,graphName:t,setName:n,keyName:r})}catch(e){throw $(e)}},deleteSet:async(e,t,n)=>{try{return await this.trpc.credential.deleteSet.mutate({orgName:e,graphName:t,setName:n})}catch(e){throw $(e)}},listAuditLog:async(e,t,n,r)=>{try{return await this.trpc.credential.listAuditLog.query({orgName:e,graphName:t,setName:n,limit:r?.limit})}catch(e){throw $(e)}},revokeSet:async(e,t,n,r)=>{try{return await this.trpc.credential.revokeSet.mutate({orgName:e,graphName:t,setName:n,reason:r?.reason})}catch(e){throw $(e)}}};credentials=this.credential;get repo(){return r(`client.repo`,`client.graph`),this.graph}constructor(e,t){let n=typeof e==`string`?t:e;pl(n);let r=typeof e==`string`?e:e?.apiUrl??`https://api.warmhub.ai`;if(this.apiUrl=r,this.fetchImpl=n?.fetch,this.accessToken=n?.accessToken??n?.auth?.getToken,this.functionLogMode=n?.functionLogs??`off`,this.clientIdentity={name:n?.client?.name??`@warmhub/sdk-ts`,version:n?.client?.version??`0.164.0`},this.#e=Object.freeze([...ml(n?.clientFlags)]),this.decorateResponses=n?.decorateResponses??!1,typeof this.accessToken==`function`){let e=this.accessToken;this.getToken=async()=>await e()}else if(this.accessToken){let e=this.accessToken;this.getToken=async()=>e}let a=`${r.replace(/\/$/,``)}/trpc`,u=((e,t)=>this.fetchWithAuth(e,t));Object.defineProperty(this,"trpc",{value:o({links:[this.createLocalRefusalLink(),this.createCompatibilityLink(),qo({enabled:this.decorateResponses,lookupNames:async e=>{try{return await this.trpc.thing.names.query({durableIds:e})}catch(e){throw $(e)}}}),l({condition:e=>gl.has(e.path),true:c({url:a,fetch:u,methodOverride:`POST`}),false:s({url:a,fetch:u,methodOverride:`POST`})})]}),enumerable:!1,writable:!1,configurable:!0}),i(this)}get clientFlags(){return this.#e}withAccessToken(t){let n={apiUrl:this.apiUrl,fetch:this.fetchImpl,accessToken:t,client:this.clientIdentity,clientFlags:this.clientFlags,decorateResponses:this.decorateResponses};return new e(n)}actions=this.action;async runLiveLoop(e,t,n,r){for(;!t.aborted;){let i=new AbortController,a=()=>i.abort();t.addEventListener(`abort`,a,{once:!0});let o;try{let a=await e(),s=await this.openSse(a.ticket,i.signal,n);if(o=s.closed,await s.ready,t.aborted)return;await r?.(),await s.closed}catch(e){if(t.aborted)return;if(e instanceof cu)throw e.cause;if(!Yl(e))throw $(e)}finally{t.removeEventListener(`abort`,a),i.abort(),o?.catch(()=>{})}await uu(su,t)}}async openSse(e,t,n){let r=await this.fetchWithAuth(`${this.apiUrl.replace(/\/$/,``)}/sse?ticket=${encodeURIComponent(e)}`,{headers:{accept:`text/event-stream`},signal:t});if(!r.ok)throw await this.httpResponseError(r);let i=r.body?.getReader();if(!i)throw new G(`BACKEND`,`SSE response body is missing`);let a=()=>{};return{ready:new Promise(e=>{a=e}),closed:(async()=>{let e=new TextDecoder,r=``;try{for(;;){let{done:t,value:o}=await i.read();if(t)break;for(r+=e.decode(o,{stream:!0}).replaceAll(`\r
31
31
  `,`
32
32
  `);;){let e=r.indexOf(`
33
33
 
34
34
  `);if(e===-1)break;let t=r.slice(0,e);r=r.slice(e+2);let i=du(t);i&&(i.type===`ready`?a():await n(i))}}}catch(e){if(fu(e)||t.aborted)return;throw e}finally{a(),i.releaseLock()}})()}}applyClientHeader(e){e.has(`X-WarmHub-Client`)||e.set(`X-WarmHub-Client`,Qn(this.clientIdentity.name,this.clientIdentity.version));let t=e.get(Hn);e.set(Hn,Xn([...t===null?this.clientFlags:Yn(t),Un]))}async fetchWithAuth(e,t){let n=this.fetchImpl??globalThis.fetch,r=new Headers(t?.headers),i=await au(this.accessToken);i&&r.set(`authorization`,`Bearer ${i}`),this.applyClientHeader(r);let a=async t=>{try{return await n(e,t)}catch(e){throw Zl(e)?new G(`NETWORK`,Ql(this.apiUrl)):e}},o=await a({...t,headers:r});if(o.status===401&&typeof this.accessToken==`function`){let e=await au(this.accessToken);if(e&&e!==i){let n=new Headers(t?.headers);n.set(`authorization`,`Bearer ${e}`),this.applyClientHeader(n),o=await a({...t,headers:n})}}return this.noteCompatibilityHeaders(o.headers),o}async requestResponse(e,t){let n=await this.fetchWithAuth(`${this.apiUrl.replace(/\/$/,``)}${e}`,t);if(!n.ok)throw await this.httpResponseError(n);return n}thingShapesReader(e,t){return async n=>await this.thing.getMany(e,t,n)}async prepareStreamingSubmissionRequest(e){let t=this.fetchImpl??globalThis.fetch,n=new Headers({accept:`application/x-ndjson`,"content-type":`application/x-ndjson`}),r=await au(this.accessToken);r&&n.set(`authorization`,`Bearer ${r}`),this.applyClientHeader(n);let i=`${this.apiUrl.replace(/\/$/,``)}${e}`;return{dispatch:async(e,r)=>{let a=await t(i,{method:`POST`,headers:n,body:e,signal:r,duplex:`half`});return this.noteCompatibilityHeaders(a.headers),a},httpError:async e=>await this.httpResponseError(e)}}async httpResponseError(e){let t=`Request failed with status ${e.status}`,n=iu(e.status),r,i,a;try{let o=await e.json();typeof o.error?.message==`string`&&(t=o.error.message),typeof o.error?.code==`string`&&(n=o.error.code,r=o.error.code),typeof o.error?.hint==`string`&&(i=o.error.hint),typeof o.error?.retryAfter==`number`&&(a=o.error.retryAfter)}catch{}return new G(n,t,e.status,i,a,r)}async requestJson(e,t){return await(await this.requestResponse(e,t)).json()}async watchRepoQuery(e,t,n,r,i){let a=new AbortController,o=ou(n,a),s=0,c=async()=>{let e=await r();s+=1,await lu(()=>i(e))};return{close(){a.abort()},closed:this.runLiveLoop(()=>this.trpc.live.issueTicket.mutate({orgName:e,graphName:t}),o,async e=>{e.type===`invalidate`&&await c()},c).then(()=>({updates:s}))}}};function iu(e){switch(e){case 400:return`VALIDATION_ERROR`;case 401:return`UNAUTHENTICATED`;case 403:return`FORBIDDEN`;case 404:return`NOT_FOUND`;case 409:return`CONFLICT`;case 429:return`RATE_LIMITED`;default:return`BACKEND`}}async function au(e){if(e)return typeof e==`string`?e:e()}function ou(e,t){return e?e.aborted?(t.abort(),t.signal):(e.addEventListener(`abort`,()=>t.abort(),{once:!0}),t.signal):t.signal}const su=2e3;var cu=class extends Error{constructor(e){super(`Live consumer failed`,{cause:e})}};async function lu(e){try{await e()}catch(e){throw new cu(e)}}function uu(e,t){return new Promise(n=>{if(t.aborted){n();return}let r=()=>{clearTimeout(i),n()},i=setTimeout(()=>{t.removeEventListener(`abort`,r),n()},e);t.addEventListener(`abort`,r,{once:!0})})}function du(e){let t=`message`,n=[];for(let r of e.split(`
35
35
  `))r&&!r.startsWith(`:`)&&(r.startsWith(`event:`)?t=r.slice(6).trim():r.startsWith(`data:`)&&n.push(r.slice(5).trim()));if(n.length===0)return null;let r=n.join(`
36
36
  `);return{type:t,data:JSON.parse(r)}}function fu(e){return e instanceof Error&&e.name===`AbortError`}[`org.member_added`,`org.repo_created`,`org.repo_published`].map(e=>({orgName:`o`,name:`n`,kind:`webhook`,eventType:e,webhookUrl:`https://x`}));export{G as $,Ts as A,Zo as B,Zs as C,ir as Ct,Rs as D,tn as Dt,q as E,nn as Et,ns as F,Oo as G,Go as H,$o as I,Bo as J,Vo as K,es as L,is as M,ms as N,zs as O,on as Ot,rs as P,lo as Q,ts as R,Lc as S,rr as St,Us as T,$n as Tt,Ho as U,Xo as V,ko as W,K as X,uo as Y,vo as Z,sl as _,wr as _t,Zl as a,vi as at,Zc as b,yr as bt,ll as c,li as ct,$l as d,ci as dt,io as et,$ as f,ai as ft,ol as g,Cr as gt,al as h,Gr as ht,ql as i,wi as it,xs as j,Ms as k,zl as l,ui as lt,il as m,Wr as mt,ru as n,Ei as nt,Yl as o,di as ot,rl as p,oi as pt,zo as q,Ql as r,Ci as rt,Jl as s,fi as st,hl as t,Ti as tt,Ul as u,si as ut,cl as v,xr as vt,Qs as w,ar as wt,Kc as x,br as xt,Y as y,Sr as yt,Qo as z};
37
- //# sourceMappingURL=chunk-z_DBi250.js.map
37
+ //# sourceMappingURL=chunk-syQKriG4.js.map