@roughapp/feature 0.4.0 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/README.md +207 -116
  2. package/index.js +38 -38
  3. package/package.json +2 -3
  4. package/CHANGELOG.md +0 -220
package/index.js CHANGED
@@ -1,15 +1,15 @@
1
- import{z as e}from"zod";import{errorBoundary as t,errorListBoundary as n}from"@stayradiated/error-boundary";import{z as r}from"zod/mini";import{getContext as i,mount as a,onDestroy as o,onMount as s,unmount as c}from"svelte";import"svelte/internal/disclose-version";import"svelte/internal/flags/async";import*as l from"svelte/internal/client";import{SvelteMap as u,SvelteSet as d}from"svelte/reactivity";import{newMessagePortRpcSession as f}from"capnweb";import"@andypf/json-viewer";var p=Object.create,m=Object.defineProperty,h=Object.getOwnPropertyDescriptor,g=Object.getOwnPropertyNames,_=Object.getPrototypeOf,v=Object.prototype.hasOwnProperty,y=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),b=(e,t)=>{let n={};for(var r in e)m(n,r,{get:e[r],enumerable:!0});return t||m(n,Symbol.toStringTag,{value:`Module`}),n},ee=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=g(t),a=0,o=i.length,s;a<o;a++)s=i[a],!v.call(e,s)&&s!==n&&m(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=h(t,s))||r.enumerable});return e},te=(e,t,n)=>(n=e==null?{}:p(_(e)),ee(t||!e||!e.__esModule||!v.call(e,`default`)?m(n,`default`,{value:e,enumerable:!0}):n,e)),ne=e=>Object.fromEntries(e.map(e=>{switch(e.type){case`mutation`:case`query`:return[e.id,t=>e.call(t)];case`subscription`:return[e.id,async(t,n)=>{let r=n.dup(),i=await e.subscribe(r,t);return async()=>{i(),r[Symbol.dispose]()}}];default:throw Error(`Unknown tool type: '${JSON.stringify(e)}'`)}})),re=e=>Object.fromEntries(e.map(e=>{switch(e.type){case`mutation`:case`query`:return[e.id,async t=>e.outputSample];case`subscription`:return[e.id,async(t,n)=>{let r=n.dup();return r(e.outputSample),async()=>{r[Symbol.dispose]()}}];default:throw Error(`Unknown tool type: '${JSON.stringify(e)}'`)}})),ie=e=>({type:e.type,id:e.id,name:e.name,description:e.description,inputSchema:e.inputSchema.toJSONSchema(),outputSchema:e.outputSchema.toJSONSchema(),outputSample:e.outputSample}),ae=class t{type=`mutation`;id;name;description;inputSchema;outputSchema;outputSample;implementation;static create(e){new t(e)}constructor(e){this.id=e.id,this.name=e.name,this.description=e.description,this.inputSchema=e.inputSchema,this.outputSchema=e.outputSchema,this.outputSample=e.outputSample,this.implementation=e.implementation}toJSON(){return ie(this)}async call(t){let n=this.inputSchema.safeParse(t);if(!n.success)throw Error(`Invalid input for ${this.id}: ${e.prettifyError(n.error)}`);let r=await this.implementation(n.data),i=this.outputSchema.safeParse(r);if(!i.success)throw Error(`Invalid output for ${this.id}: ${e.prettifyError(i.error)}`);return i.data}},oe=class t{type=`query`;id;name;description;inputSchema;outputSchema;outputSample;implementation;static create(e){new t(e)}constructor(e){this.id=e.id,this.name=e.name,this.description=e.description,this.inputSchema=e.inputSchema,this.outputSchema=e.outputSchema,this.outputSample=e.outputSample,this.implementation=e.implementation}toJSON(){return ie(this)}async call(t){let n=this.inputSchema.safeParse(t);if(!n.success)throw Error(`Invalid input for ${this.id}: ${e.prettifyError(n.error)}`);let r=await this.implementation(n.data),i=this.outputSchema.safeParse(r);if(!i.success)throw Error(`Invalid output for ${this.id}: ${e.prettifyError(i.error)}`);return i.data}},se=class t{type=`subscription`;id;name;description;inputSchema;outputSchema;outputSample;implementation;static create(e){new t(e)}constructor(e){this.id=e.id,this.name=e.name,this.description=e.description,this.inputSchema=e.inputSchema,this.outputSchema=e.outputSchema,this.outputSample=e.outputSample,this.implementation=e.implementation}toJSON(){return ie(this)}async subscribe(t,n){let r=this.inputSchema.safeParse(n);if(!r.success)throw Error(`Invalid input for ${this.id}: ${e.prettifyError(r.error)}`);return await this.implementation(n=>{let r=this.outputSchema.safeParse(n);if(!r.success)throw Error(`Invalid output for ${this.id}: ${e.prettifyError(r.error)}`);t(r.data)},r.data)}},ce=e=>{let t=new URL(e.path,e.baseUrl);for(let[n,r]of Object.entries(e.query??{}))r!==void 0&&t.searchParams.set(n,String(r));return t.toString()},le=async e=>{let{replicache:n,projectId:r,signal:i}=e;return i?.aborted?Error(`Ping project aborted`):t(async()=>{await n.mutate.project_ping_v1({projectPublicId:r,context:{actionedAt:Date.now()}}),await n.push({now:!0})})},ue=`/`,x=e=>{let t=`${e}${ue}`,n=t.length;return()=>({name:e,value:t=>({name:e,idA:t,idB:void 0}),trimPrefix:e=>e.substring(n),prefix:(...e)=>{switch(e.length){case 0:return t;case 1:return`${t}${e[0]}`;default:throw Error(`Unexpected number of ids: "${e}"`)}},isMatch:e=>e.startsWith(t),encode:e=>`${t}${e}`,decode:e=>{if(!e.startsWith(t))throw Error(`Expected serialized to start with prefix "${t}", received "${e}"`);return e.substring(n)},decodeWithoutPrefix:e=>e})},S=e=>{let t=`${e}${ue}`,n=t.length;return()=>({name:e,value:(t,n)=>({name:e,idA:t,idB:n}),trimPrefix:e=>e.substring(n),prefix:(...e)=>{switch(e.length){case 0:return t;case 1:return`${t}${e[0]}${ue}`;case 2:return`${t}${e[0]}${ue}${e[1]}`;default:throw Error(`Unexpected number of ids: "${e}"`)}},isMatch:e=>e.startsWith(t),encode:(e,n)=>`${t}${e}${ue}${n}`,decode:e=>{if(!e.startsWith(t))throw Error(`Expected serialized to start with prefix "${t}", received "${e}"`);return e.substring(n).split(ue)},decodeWithoutPrefix:e=>e.split(ue)})},C={internal:x(`__internal`)(),apiToken:x(`apiToken`)(),asset:x(`asset`)(),backlogTask:x(`backlogTask`)(),block:x(`block`)(),comment:x(`comment`)(),commentThread:x(`commentThread`)(),content:x(`content`)(),document:x(`document`)(),draftContent:x(`draftContent`)(),event:x(`event`)(),filter:x(`filter`)(),filterRule:x(`filterRule`)(),fizzyAccount:x(`fizzyAccount`)(),fizzyBoard:x(`fizzyBoard`)(),fizzyIntegration:x(`fizzyIntegration`)(),invitation:x(`invitation`)(),inviteLink:x(`inviteLink`)(),label:x(`label`)(),llmModel:x(`llmModel`)(),llmModelDefault:x(`llmModelDefault`)(),llmProvider:x(`llmProvider`)(),note:x(`note`)(),notification:x(`notification`)(),person:x(`person`)(),project:x(`project`)(),projectAccount:x(`projectAccount`)(),reaction:x(`reaction`)(),reference:x(`reference`)(),sequence:x(`sequence`)(),signingKey:x(`signingKey`)(),sprite:x(`sprite`)(),spriteBuild:x(`spriteBuild`)(),spriteBuildEvent:x(`spriteBuildEvent`)(),surface:x(`surface`)(),task:x(`task`)(),vcsBranch:x(`vcsBranch`)(),vcsCommit:x(`vcsCommit`)(),vcsIntegration:x(`vcsIntegration`)(),vcsRepo:x(`vcsRepo`)(),vcsUser:x(`vcsUser`)(),watch:x(`watch`)(),workspace:x(`workspace`)(),blockUser:S(`blockUser`)(),documentUser:S(`documentUser`)(),sequenceDocument:S(`sequenceDocument`)(),signingKeyProject:S(`signingKeyProject`)(),vcsCommitDocument:S(`vcsCommitDocument`)(),noteLabel:S(`noteLabel`)(),spriteProjectAccount:S(`spriteProjectAccount`)(),taskLabel:S(`taskLabel`)(),relatedDocumentNote:S(`relatedDocumentNote`)(),relatedDocumentPair:S(`relatedDocumentPair`)(),relatedNotePair:S(`relatedNotePair`)(),relatedSpritePair:S(`relatedSpritePair`)(),stackTask:S(`stackTask`)(),workspaceUser:x(`workspaceUser`)()},de=(e,t)=>{let n={};for(let r of e){let e=t(r);Object.hasOwn(n,e)?n[e]?.push(r):Object.defineProperty(n,e,{configurable:!0,enumerable:!0,value:[r],writable:!0})}return n},w=class{#e=0;#t=new Map;#n=new Map;#r;#i;#a;constructor(e){if(!(e.maxSize&&e.maxSize>0))throw TypeError("`maxSize` must be a number greater than 0");if(typeof e.maxAge==`number`&&e.maxAge===0)throw TypeError("`maxAge` must be a number greater than 0");this.#r=e.maxSize,this.#i=e.maxAge??1/0,this.#a=e.onEviction,Object.defineProperty(this,Symbol.for(`nodejs.util.inspect.custom`),{value:()=>this.toString()})}get __oldCache(){return this.#n}#o(e){if(typeof this.#a==`function`)for(let[t,n]of e)this.#a(t,n.value)}#s(e,t){return typeof t.expiry==`number`&&t.expiry<=Date.now()&&(this.#a?.(e,t.value),this.delete(e))}#c(e,t){if(!this.#s(e,t))return t.value}#l(e,t){if(t)return t.expiry?this.#c(e,t):t.value}#u(e,t){return this.#l(e,t.get(e))}#d(e,t){this.#t.set(e,t),this.#e++,this.#e>=this.#r&&(this.#e=0,this.#o(this.#n),this.#n=this.#t,this.#t=new Map)}#f(e,t){this.#n.delete(e),this.#d(e,t)}*#p(){for(let[e,t]of this.#n)!this.#t.has(e)&&!this.#s(e,t)&&(yield[e,t]);for(let[e,t]of this.#t)this.#s(e,t)||(yield[e,t])}get(e){if(this.#t.has(e))return this.#l(e,this.#t.get(e));if(this.#n.has(e)){let t=this.#n.get(e);if(t&&!this.#s(e,t))return this.#f(e,t),t.value}}set(e,t,{maxAge:n=this.#i}={}){let r={value:t,expiry:typeof n==`number`&&n!==1/0?Date.now()+n:void 0};return this.#t.has(e)?this.#t.set(e,r):this.#d(e,r),this}has(e){if(this.#t.has(e)){let t=this.#t.get(e);return t?!this.#s(e,t):!1}if(this.#n.has(e)){let t=this.#n.get(e);return t?!this.#s(e,t):!1}return!1}peek(e){if(this.#t.has(e))return this.#u(e,this.#t);if(this.#n.has(e))return this.#u(e,this.#n)}expiresIn(e){let t=this.#t.get(e)??this.#n.get(e);if(t)return t.expiry?t.expiry-Date.now():1/0}delete(e){let t=this.#t.delete(e);return t&&this.#e--,this.#n.delete(e)||t}clear(){this.#t.clear(),this.#n.clear(),this.#e=0}resize(e){if(!(e&&e>0))throw TypeError("`maxSize` must be a number greater than 0");let t=[...this.#p()],n=t.length-e;n<0?(this.#t=new Map(t),this.#n=new Map,this.#e=t.length):(n>0&&this.#o(t.slice(0,n)),this.#n=new Map(t.slice(n)),this.#t=new Map,this.#e=0),this.#r=e}evict(e=1){let t=Number(e);if(!t||t<=0)return;let n=[...this.#p()],r=Math.trunc(Math.min(t,Math.max(n.length-1,0)));r<=0||(this.#o(n.slice(0,r)),this.#n=new Map(n.slice(r)),this.#t=new Map,this.#e=0)}*keys(){for(let[e]of this)yield e}*values(){for(let[,e]of this)yield e}*[Symbol.iterator](){for(let[e,t]of this.#t)this.#s(e,t)||(yield[e,t.value]);for(let[e,t]of this.#n)!this.#t.has(e)&&!this.#s(e,t)&&(yield[e,t.value])}*entriesDescending(){let e=[...this.#t];for(let t=e.length-1;t>=0;t--){let n=e[t];if(n===void 0)continue;let[r,i]=n;this.#s(r,i)||(yield[r,i.value])}e=[...this.#n];for(let t=e.length-1;t>=0;t--){let n=e[t];if(n===void 0)continue;let[r,i]=n;!this.#t.has(r)&&!this.#s(r,i)&&(yield[r,i.value])}}*entriesAscending(){for(let[e,t]of this.#p())yield[e,t.value]}get size(){if(!this.#e)return this.#n.size;let e=0;for(let t of this.#n.keys())this.#t.has(t)||e++;return Math.min(this.#e+e,this.#r)}get maxSize(){return this.#r}get maxAge(){return this.#i}entries(){return this.entriesAscending()}forEach(e,t=this){for(let[n,r]of this.entriesAscending())e.call(t,r,n,this)}get[Symbol.toStringTag](){return`QuickLRU`}toString(){return`QuickLRU(${this.size}/${this.maxSize})`}},fe=class{arraySize=0;array=Array(8);set=null;get isEmpty(){if(this.array)return this.arraySize===0;if(this.set)return this.set.size===0;throw Error(`no set or array`)}add(e){if(this.array)return this.array.indexOf(e)===-1?this.arraySize<8?(this.array[this.arraySize]=e,this.arraySize++,!0):(this.set=new Set(this.array),this.array=null,this.set.add(e),!0):!1;if(this.set)return!this.set.has(e)&&(this.set.add(e),!0);throw Error(`no set or array`)}remove(e){if(this.array){let t=this.array.indexOf(e);return t!==-1&&(this.array[t]=void 0,this.arraySize--,t!==this.arraySize&&(this.array[t]=this.array[this.arraySize],this.array[this.arraySize]=void 0),!0)}if(this.set)return this.set.has(e)?(this.set.delete(e),!0):!1;throw Error(`no set or array`)}visit(e){if(this.array){for(let t=0;t<this.arraySize;t++){let n=this.array[t];n!==void 0&&e(n)}return}if(this.set){this.set.forEach(e);return}throw Error(`no set or array`)}};function pe(e){return e&&typeof e==`object`&&`parents`in e}function me(e){for(let t=0,n=e.parents.length;t<n;t++)if(e.parents[t].__unsafe__getWithoutCapture(),e.parents[t].lastChangedEpoch!==e.parentEpochs[t])return!0;return!1}var he=(e,t)=>{if(e.children.remove(t)&&e.children.isEmpty&&pe(e))for(let t=0,n=e.parents.length;t<n;t++)he(e.parents[t],e)},ge=(e,t)=>{if(e.children.add(t)&&pe(e))for(let t=0,n=e.parents.length;t<n;t++)ge(e.parents[t],e)};function _e(e,t){return e===t||Object.is(e,t)||!!(e&&t&&typeof e.equals==`function`&&e.equals(t))}var ve=Object.freeze([]),ye=Symbol.for(`__signia__`),be=globalThis;be[ye]?console.error(`Multiple versions of signia detected. This will cause unexpected behavior. Please add "resolutions" (yarn/pnpm) or "overrides" (npm) in your package.json to ensure only one version of signia is loaded.`):be[ye]=!0;var xe=class{constructor(e,t){this.below=e,this.child=t}offset=0;numNewParents=0;maybeRemoved},T=null;function Se(e){T=new xe(T,e)}function Ce(){let e=T;if(T=e.below,e.numNewParents>0||e.offset!==e.child.parents.length){for(let t=e.offset;t<e.child.parents.length;t++){let n=e.child.parents[t];e.child.parents.indexOf(n)>=e.offset&&he(n,e.child)}if(e.child.parents.length=e.offset,e.child.parentEpochs.length=e.offset,T?.maybeRemoved)for(let t=0;t<T.maybeRemoved.length;t++){let n=T.maybeRemoved[t];e.child.parents.indexOf(n)===-1&&he(n,e.child)}}}function we(e){if(T){let t=T.child.parents.indexOf(e);if(t<0&&(T.numNewParents++,T.child.isActivelyListening&&ge(e,T.child)),t<0||t>=T.offset){if(t!==T.offset&&t>0){let e=T.child.parents[T.offset];T.maybeRemoved?T.maybeRemoved.indexOf(e)===-1&&T.maybeRemoved.push(e):T.maybeRemoved=[e]}T.child.parents[T.offset]=e,T.child.parentEpochs[T.offset]=e.lastChangedEpoch,T.offset++}}}var Te=Symbol(`RESET_VALUE`),Ee=class{constructor(e){this.capacity=e,this.buffer=Array(e)}index=0;buffer;pushEntry(e,t,n){if(n!==void 0){if(n===Te){this.clear();return}this.buffer[this.index]=[e,t,n],this.index=(this.index+1)%this.capacity}}clear(){this.index=0,this.buffer.fill(void 0)}getChangesSince(e){let{index:t,capacity:n,buffer:r}=this;for(let i=0;i<n;i++){let a=(t-1+n-i)%n,o=r[a];if(!o)return Te;let[s,c]=o;if(i===0&&e>=c)return[];if(s<=e&&e<c){let e=i+1,t=Array(e);for(let i=0;i<e;i++)t[i]=r[(a+i)%n][2];return t}}return Te}},E=0,De=!1;function Oe(){E++}function ke(e){if(De)throw Error(`cannot change atoms during reaction cycle`);try{De=!0;let t=new Set,n=e=>{e.lastTraversedEpoch!==E&&(e.lastTraversedEpoch=E,`maybeScheduleEffect`in e?t.add(e):e.children.visit(n))};for(let t of e)t.children.visit(n);for(let e of t)e.maybeScheduleEffect()}finally{De=!1}}function Ae(e,t){je?je.initialAtomValues.has(e)||je.initialAtomValues.set(e,t):ke([e])}var je=null,Me=class{constructor(e,t,n){this.name=e,this.current=t,this.isEqual=n?.isEqual??null,n&&(n.historyLength&&(this.historyBuffer=new Ee(n.historyLength)),this.computeDiff=n.computeDiff)}isEqual;computeDiff;lastChangedEpoch=E;children=new fe;historyBuffer;__unsafe__getWithoutCapture(){return this.current}get value(){return we(this),this.current}set(e,t){if(this.isEqual?.(this.current,e)??_e(this.current,e))return this.current;Oe(),this.historyBuffer&&this.historyBuffer.pushEntry(this.lastChangedEpoch,E,t??this.computeDiff?.(this.current,e,this.lastChangedEpoch,E)??Te),this.lastChangedEpoch=E;let n=this.current;return this.current=e,Ae(this,n),e}update(e){return this.set(e(this.current))}getDiffSince(e){return we(this),e>=this.lastChangedEpoch?ve:this.historyBuffer?.getChangesSince(e)??Te}};function Ne(e,t,n){return new Me(e,t,n)}var Pe=Symbol(`UNINITIALIZED`),Fe=e=>e===Pe,Ie=class{constructor(e,t){this.value=e,this.diff=t}},Le=class{constructor(e,t,n){this.name=e,this.derive=t,n?.historyLength&&(this.historyBuffer=new Ee(n.historyLength)),this.computeDiff=n?.computeDiff,this.isEqual=n?.isEqual??_e}lastChangedEpoch=-1;lastTraversedEpoch=-1;lastCheckedEpoch=-1;parents=[];parentEpochs=[];children=new fe;get isActivelyListening(){return!this.children.isEmpty}historyBuffer;state=Pe;computeDiff;isEqual;__unsafe__getWithoutCapture(){let e=this.lastChangedEpoch===-1;if(!e&&(this.lastCheckedEpoch===E||!me(this)))return this.lastCheckedEpoch=E,this.state;try{Se(this);let t=this.derive(this.state,this.lastCheckedEpoch),n=t instanceof Ie?t.value:t;if(this.state===Pe||!this.isEqual(n,this.state)){if(this.historyBuffer&&!e){let e=t instanceof Ie?t.diff:void 0;this.historyBuffer.pushEntry(this.lastChangedEpoch,E,e??this.computeDiff?.(this.state,n,this.lastCheckedEpoch,E)??Te)}this.lastChangedEpoch=E,this.state=n}return this.lastCheckedEpoch=E,this.state}finally{Ce()}}get value(){let e=this.__unsafe__getWithoutCapture();return we(this),e}getDiffSince(e){return this.value,e>=this.lastChangedEpoch?ve:this.historyBuffer?.getChangesSince(e)??Te}};function Re(e={},t,n,r){let i=r.get,a=Symbol.for(`__signia__computed__`+n);return r.get=function(){let t=this[a];return t||(t=new Le(n,i.bind(this),e),Object.defineProperty(this,a,{enumerable:!1,configurable:!1,writable:!1,value:t})),t.value},r}function ze(){if(arguments.length===1){let e=arguments[0];return(t,n,r)=>Re(e,t,n,r)}return typeof arguments[0]==`string`?new Le(arguments[0],arguments[1],arguments[2]):Re(void 0,arguments[0],arguments[1],arguments[2])}var Be=class{constructor(e,t,n){this.name=e,this.runEffect=t,this._scheduleEffect=n?.scheduleEffect}_isActivelyListening=!1;get isActivelyListening(){return this._isActivelyListening}lastTraversedEpoch=-1;lastReactedEpoch=-1;_scheduleCount=0;get scheduleCount(){return this._scheduleCount}parentEpochs=[];parents=[];_scheduleEffect;maybeScheduleEffect(){if(this._isActivelyListening&&this.lastReactedEpoch!==E){if(this.parents.length&&!me(this)){this.lastReactedEpoch=E;return}this.scheduleEffect()}}scheduleEffect(){this._scheduleCount++,this._scheduleEffect?this._scheduleEffect(this.maybeExecute):this.execute()}maybeExecute=()=>{this._isActivelyListening&&this.execute()};attach(){this._isActivelyListening=!0;for(let e=0,t=this.parents.length;e<t;e++)ge(this.parents[e],this)}detach(){this._isActivelyListening=!1;for(let e=0,t=this.parents.length;e<t;e++)he(this.parents[e],this)}execute(){try{Se(this);let e=this.runEffect(this.lastReactedEpoch);return this.lastReactedEpoch=E,e}finally{Ce()}}};function Ve(e,t,n){let r=new Be(e,t,n);return r.attach(),r.scheduleEffect(),()=>{r.detach()}}var He=e=>{let{diffList:t,source:n,mapKey:r,mapValue:i}=e;if(t.length===0)return;let a={...n.__unsafe__getWithoutCapture()},o=[];for(let e of t)switch(e.op){case`add`:{let t=r(e.key),n=i(e.newValue,e.key);a[t]=n,o.push({op:`add`,key:t,value:n});break}case`change`:{let t=r(e.key),n=i(e.newValue,e.key);a[t]=n,o.push({op:`replace`,key:t,value:n});break}case`del`:{let t=r(e.key);delete a[t],o.push({op:`remove`,key:t});break}default:throw Error(`Unhandled diff op: ${JSON.stringify(e)}`)}n.set(a,o)},Ue=e=>{let t=new Set,n=[];for(let r=e.length-1;r>=0;r--){let i=e[r];for(let e=i.length-1;e>=0;e--){let r=i[e];t.has(r.key)||(t.add(r.key),n.push(r))}}return n.reverse(),n},We=(e,t,n)=>{let r={},i=()=>{r={};for(let[n,i]of Object.entries(e.value))t(i)&&(r[n]=i);return Object.values(r)};return ze(`${e.name}:filter`,(n,a)=>{if(Fe(n))return i();let o=e.getDiffSince(a);if(o===Te)return i();let s=Ue(o);if(s.length===0)return i();for(let e of s)switch(e.op){case`add`:t(e.value)&&(r[e.key]=e.value);break;case`remove`:delete r[e.key];break;case`replace`:t(e.value)?r[e.key]=e.value:delete r[e.key];break;default:throw Error(`Unhandled patch operation: ${JSON.stringify(e)}`)}return Object.values(r)},{...n})},Ge=(e,t,n)=>{let r=new Set,i,a=()=>{r.clear(),i=void 0;let n=!1,a;for(let[o,s]of Object.entries(e.value))n?r.add(o):t(s)&&(n=!0,a=s,i=o);return a},o=()=>{for(let n of r){r.delete(n);let a=e.value[n];if(a!==void 0&&t(a))return i=n,a}i=void 0};return ze(`${e.name}:find`,(n,s)=>{if(Fe(n))return a();let c=e.getDiffSince(s);if(c===Te)return a();let l=Ue(c);if(l.length===0)return a();for(let e of l)switch(e.op){case`add`:i===void 0?t(e.value)&&(i=e.key):r.add(e.key);break;case`remove`:e.key===i?o():r.delete(e.key);break;case`replace`:e.key===i||i===void 0?t(e.value)?i=e.key:o():r.add(e.key);break;default:throw Error(`Unhandled patch operation: ${JSON.stringify(e)}`)}return i===void 0?void 0:e.value[i]},{...n})},Ke=(e,t,n)=>ze(`${e.name}:get`,()=>e.value[t],{...n}),qe=(e,t,n)=>{let r={},i=()=>{r={};for(let[n,i]of Object.entries(e.value))r[n]=t(i);return Object.values(r)};return ze(`${e.name}:map`,(n,a)=>{if(Fe(n))return i();let o=e.getDiffSince(a);if(o===Te)return i();let s=Ue(o);if(s.length===0)return i();for(let e of s)switch(e.op){case`add`:r[e.key]=t(e.value);break;case`replace`:r[e.key]=t(e.value);break;case`remove`:delete r[e.key];break;default:throw Error(`Unhandled patch operation: ${JSON.stringify(e)}`)}return Object.values(r)},{...n})},Je=(e,t,n)=>{let r={},i=()=>{r={};for(let n of Object.keys(e.value)){let e=t(n);r[n]=e}return Object.values(r)};return ze(`${e.name}:keys`,(n,a)=>{if(Fe(n))return i();let o=e.getDiffSince(a);if(o===Te)return i();let s=Ue(o);if(s.length===0)return i();for(let e of s)switch(e.op){case`add`:r[e.key]=t(e.key);break;case`remove`:delete r[e.key];break;case`replace`:e.key in r||(r[e.key]=t(e.key));break;default:throw Error(`Unhandled patch operation: ${JSON.stringify(e)}`)}return Object.values(r)},{...n})},Ye=(e,t)=>ze(`${e.name}:values`,()=>Object.values(e.value),{...t}),Xe=(e,t,n)=>{let r=new Set,i=new Set,a=()=>{r.clear(),i.clear();let n=!1;for(let[a,o]of Object.entries(e.value))n?i.add(a):t(o)&&(r.add(a),n=!0);return n},o=()=>{for(let n of i){i.delete(n);let a=e.value[n];if(a!==void 0&&t(a))return r.add(n),!0}return!1};return ze(`${e.name}:some`,(n,s)=>{if(Fe(n))return a();let c=e.getDiffSince(s);if(c===Te)return a();let l=Ue(c);if(l.length===0)return a();for(let e of l)switch(e.op){case`add`:r.size===0?t(e.value)&&r.add(e.key):i.add(e.key);break;case`remove`:i.delete(e.key),r.delete(e.key),r.size===0&&o();break;case`replace`:r.has(e.key)||r.size===0?(i.delete(e.key),t(e.value)?r.add(e.key):(r.delete(e.key),o())):i.add(e.key);break;default:throw Error(`Unhandled patch operation: ${JSON.stringify(e)}`)}return r.size>0},{...n})},Ze=50,Qe=class e{key;mapValue;name;atom;asRecord;asList;keys;#e=new Map;#t=e.#a();#n=e.#a();#r=e.#a();#i=e.#a();static#a(){return new w({maxSize:Ze})}constructor(e){this.key=e.key,this.mapValue=e.mapValue,this.name=`ReplicacheTable(${this.key.name})`,this.atom=Ne(this.name,{},{historyLength:1}),this.asRecord=this.atom,this.asList=Ye(this.atom),this.keys=Je(this.atom,e=>this.key.decodeWithoutPrefix(e))}#o(e,t,n){let r=e.get(t);if(r!==void 0)return r;let i=n();return e.set(t,i),i}#s(e){return typeof e==`string`?e:Array.isArray(e)?`${e[0]}/${e[1]}`:(console.error(`${this.name}.get: invalid key`,e),``)}get(e){let t=this.#s(e);return this.#o(this.#e,t,()=>Ke(this.atom,t))}find(e,t){return this.#o(this.#t,e,()=>Ge(this.atom,t))}filter(e,t){return this.#o(this.#n,e,()=>We(this.atom,t))}map(e,t){return this.#o(this.#r,e,()=>qe(this.atom,t))}some(e,t){return this.#o(this.#i,e,()=>Xe(this.atom,t))}pushDiffList(e){He({diffList:e,source:this.atom,mapKey:e=>this.key.trimPrefix(e),mapValue:(e,t)=>this.mapValue(e,this.key.decode(t))})}clear(){let e=this.atom.__unsafe__getWithoutCapture(),t=Object.keys(e);if(t.length===0)return;let n=t.map(e=>({op:`remove`,key:e}));this.atom.set({},n)}},$e=`store`,et=x(`meta`)(),tt=()=>{let e={meta:new Qe({key:et,mapValue:e=>e}),person:new Qe({key:C.person,mapValue:(e,t)=>({id:t,name:e.name})}),surface:new Qe({key:C.surface,mapValue:(e,t)=>({id:t,key:e.key,name:e.name,description:e.description})}),sprite:new Qe({key:C.sprite,mapValue:(e,t)=>({id:t,name:e.name,surfaceId:e.surfaceId,ownedByPersonId:e.ownedByPersonId})}),spriteBuild:new Qe({key:C.spriteBuild,mapValue:(e,t)=>({id:t,spriteId:e.spriteId,parentSpriteBuildId:e.parentSpriteBuildId,createdByPersonId:e.createdByPersonId,prompt:e.prompt,status:e.status,cancelRequestedAt:e.cancelRequestedAt,artifactUrl:e.artifactUrl,sourceUrl:null,startedAt:e.startedAt,stoppedAt:e.stoppedAt,error:e.error,reasoningSummary:e.reasoningSummary,publishedAt:e.publishedAt})}),spriteBuildEvent:new Qe({key:C.spriteBuildEvent,mapValue:(e,t)=>({id:t,spriteBuildId:e.spriteBuildId,actionedAt:e.actionedAt,type:e.type,detail:e.detail})})},t={[C.person.name]:e.person,[C.surface.name]:e.surface,[C.spriteBuildEvent.name]:e.spriteBuildEvent,[C.spriteBuild.name]:e.spriteBuild,[C.sprite.name]:e.sprite},n=new Set,r,i=!1,a=t=>{let n=et.encode($e);t===`LOADING`?e.meta.pushDiffList([{op:`add`,key:n,newValue:{state:t}}]):e.meta.pushDiffList([{op:`change`,key:n,newValue:{state:t},oldValue:{}}])},o=()=>{e.meta.clear(),e.person.clear(),e.surface.clear(),e.sprite.clear(),e.spriteBuild.clear(),e.spriteBuildEvent.clear()},s=()=>{for(let e of n)e()},c=e=>{if(i)return;r?.(),o(),a(`LOADING`);let n=!1;r=e.experimentalWatch(e=>{let r=de(e,e=>e.key.match(/^(\w+)\//)?.[1]??``);for(let[e,n]of Object.entries(r))t[e]?.pushDiffList(n);n||(n=!0,a(`READY`)),s()},{initialValuesInFirstDiff:!0})},l=e=>(n.add(e),()=>{n.delete(e)}),u=async()=>{i=!0,r?.(),r=void 0,o(),n.clear()};return{...e,bind:c,subscribe:l,destroy:u}},nt=y(((e,t)=>{var n=self.crypto;function r(e){let t=new Uint8Array(e);return n.getRandomValues(t),t}t.exports={randomBytes:r}})),rt=y(((e,t)=>{var{randomBytes:n}=nt(),r=16;t.exports=new class{compare(e,t){let n=e.findIndex((e,n)=>e!==t[n]);return~n&&Math.sign(e[n]-t[n])}generateOneFilled(){return new Uint8Array(r).fill(255)}generateRandomFilled(){return n(r)}generateZeroFilled(){return new Uint8Array(r).fill(0)}}})),it=y(((e,t)=>{var n=class extends Error{get name(){return this.constructor.name}};t.exports={Id128Error:n,ClockSequenceOverflow:class extends n{},InvalidBytes:class extends n{},InvalidEncoding:class extends n{},InvalidEpoch:class extends n{},UnsupportedVersion:class extends n{}}})),at=y(((e,t)=>{var{InvalidEpoch:n}=it(),r=0,i=2**48;t.exports=new class{fromEpoch(e,t){return new Date(t+e)}toEpoch(e,t=null){let a=(t===null?Date.now():Number.isInteger(t)?t:t instanceof Date?t.getTime():(()=>{throw new n(`Failed to coerce time [${t}] to epoch`)})())-e;if(a<r||a>=i)throw new n(`Epoch must be between ${new Date(r+e).toISOString()} and ${new Date(i-1+e).toISOString()}`);return a}}})),ot=y(((e,t)=>{var n=rt(),r=Symbol(`bytes`);t.exports={BaseId:class{constructor(e){this[r]=e}clone(){return new this.constructor(this.bytes.slice())}get bytes(){return this[r]}get[Symbol.toStringTag](){return this.constructor.name}compare(e){return n.compare(this.bytes,e.bytes)}equal(e){return this.compare(e)===0}}}})),st=y(((e,t)=>{var n=rt(),r=at(),{BaseId:i}=ot(),a=0,o=2**32,s=255;function c(e,t){let n=e%o,r=(e-n)/o,i=-1;t[++i]=r>>>8&s,t[++i]=r>>>0&s,t[++i]=n>>>24&s,t[++i]=n>>>16&s,t[++i]=n>>>8&s,t[++i]=n>>>0&s}t.exports={Ulid:class extends i{static generate({time:e}={}){e=r.toEpoch(a,e);let t=n.generateRandomFilled();return c(e,t),new this(t)}static MIN(){return new this(n.generateZeroFilled())}static MAX(){return new this(n.generateOneFilled())}get time(){let e=-1,t=0|this.bytes[++e]<<8|this.bytes[++e]<<0,n=0|this.bytes[++e]<<24|this.bytes[++e]<<16|this.bytes[++e]<<8|this.bytes[++e]<<0,i=t*o+(n>>>0);return r.fromEpoch(a,i)}},setTime:c}})),ct=y(((e,t)=>{var{Ulid:n,setTime:r}=st(),i=rt(),a=at(),{ClockSequenceOverflow:o}=it(),s=0,c=6,l=8,u=0,d,f;function p(e){for(let t=7;t>5;--t)if(e[t]===255)e[t]=0;else{++e[t];return}throw new o(`Exhausted clock sequence`)}function m(e){e[c]&=127}function h(e){for(let t=s;t<l;++t)e[t]=d.bytes[t]}var g=class extends n{static reset(){f=-1,d=this.MIN()}static generate({time:e}={}){e=a.toEpoch(u,e);let t=i.generateRandomFilled();return e<=f?(h(t),p(t)):(r(e,t),m(t),f=e),d=new this(t)}};g.reset(),t.exports={UlidMonotonic:g}})),lt=y(((e,t)=>{var{BaseId:n}=ot(),r=rt(),i=8,a=6;function o(e,t){t[i]&=255>>>e+1,t[i]|=(7<<3-e&7)<<5}function s(e,t){t[a]&=15,t[a]|=e<<4}t.exports={Uuid:class extends n{static MIN(){let e=r.generateZeroFilled();return o(this.VARIANT,e),s(this.VERSION,e),new this(e)}static MAX(){let e=r.generateOneFilled();return o(this.VARIANT,e),s(this.VERSION,e),new this(e)}get variant(){let e=this.bytes[i]>>>5;return e===7?3:(e&6)==6?2:+((e&4)==4)}get version(){return this.bytes[a]>>>4}},setVersion:s,setVariant:o}})),ut=y(((e,t)=>{var{randomBytes:n}=nt(),r=Symbol(`mac-address`);t.exports=new class{constructor(){this.reset()}get mac_address(){let e=this[r];return e||(e=this[r]=n(6),e[0]|=1),e}reset(){this[r]=null}}})),dt=y(((e,t)=>{var n=rt(),r=at(),i=ut(),{Uuid:a,setVariant:o,setVersion:s}=lt(),c=2,l=8,u=10,d=2**14,f=Date.parse(`1582-10-15Z`),p=4096,m=2**20,h=255,g,_,v;function y(){g=(g+1)%d}function b(e,t){if(g===null){let e=n.generateRandomFilled();g=(0|e[8]<<8|e[9]<<0)%d}else e<v&&y();let r=7;t[++r]=g>>>8&h,t[++r]=g>>>0&h}function ee(e,t){for(let n=0;n<6;++n)t[u+n]=e[n]}function te(e,t){_=e>v?0:_+1,_===p&&(_=0,y());let n=e%m,r=n*p+_,i=(e-n)/m,a=-1;t[++a]=r>>>24&h,t[++a]=r>>>16&h,t[++a]=r>>>8&h,t[++a]=r>>>0&h,t[++a]=i>>>8&h,t[++a]=i>>>0&h,t[++a]=i>>>24&h,t[++a]=i>>>16&h}var ne=class extends a{static get VARIANT(){return 1}static get VERSION(){return 1}static reset(){g=null,_=-1,v=-1}static generate({node:e,time:t}={}){t=r.toEpoch(f,t);let a=n.generateZeroFilled();return te(t,a),b(t,a),ee(e||i.mac_address,a),o(this.VARIANT,a),s(this.VERSION,a),t>v&&(v=t),new this(a)}get clock_sequence(){return(0|this.bytes[l]<<8|this.bytes[9])&d-1}get hires_time(){return(0|this.bytes[c]<<8|this.bytes[3])&p-1}get node(){return this.bytes.slice(u)}get time(){let e=-1,t=0|this.bytes[++e]<<12|this.bytes[++e]<<4|this.bytes[++e]>>>4;++e;let n=(0|this.bytes[++e]<<8|this.bytes[++e]<<0|(this.bytes[++e]&15)<<24|this.bytes[++e]<<16)*m+t;return r.fromEpoch(f,n)}};ne.reset(),t.exports={Uuid1:ne}})),ft=y(((e,t)=>{var n=rt(),{Uuid:r,setVariant:i,setVersion:a}=lt();t.exports={Uuid4:class extends r{static get VARIANT(){return 1}static get VERSION(){return 4}static generate(){let e=n.generateRandomFilled();return i(this.VARIANT,e),a(this.VERSION,e),new this(e)}}}})),pt=y(((e,t)=>{var n=rt(),r=at(),i=ut(),{Uuid:a,setVariant:o,setVersion:s}=lt(),c=6,l=8,u=10,d=2**14,f=Date.parse(`1582-10-15Z`),p=4096,m=2**32,h=255,g,_,v;function y(){g=(g+1)%d}function b(e,t){if(g===null){let e=n.generateRandomFilled();g=(0|e[8]<<8|e[9]<<0)%d}else e<v&&y();let r=7;t[++r]=g>>>8&h,t[++r]=g>>>0&h}function ee(e,t){for(let n=0;n<6;++n)t[u+n]=e[n]}function te(e,t){_=e>v?0:_+1,_===p&&(_=0,y());let n=e%m,r=(e-n)/m,i=-1;t[++i]=r>>>8&h,t[++i]=r>>>0&h,t[++i]=n>>>24&h,t[++i]=n>>>16&h,t[++i]=n>>>8&h,t[++i]=n>>>0&h,t[++i]=_>>>8&h,t[++i]=_>>>0&h}var ne=class extends a{static get VARIANT(){return 1}static get VERSION(){return 6}static reset(){g=null,_=-1,v=-1}static generate({node:e,time:t}={}){t=r.toEpoch(f,t);let a=n.generateZeroFilled();return te(t,a),b(t,a),ee(e||i.mac_address,a),o(this.VARIANT,a),s(this.VERSION,a),t>v&&(v=t),new this(a)}get clock_sequence(){return(0|this.bytes[l]<<8|this.bytes[9])&d-1}get hires_time(){return(0|this.bytes[c]<<8|this.bytes[7])&p-1}get node(){return this.bytes.slice(u)}get time(){let e=-1,t=0|this.bytes[++e]<<8|this.bytes[++e]<<0,n=0|this.bytes[++e]<<24|this.bytes[++e]<<16|this.bytes[++e]<<8|this.bytes[++e]<<0,i=t*m+(n>>>0);return r.fromEpoch(f,i)}};ne.reset(),t.exports={Uuid6:ne}})),mt=y(((e,t)=>{var n=rt(),{Uuid:r,setVariant:i,setVersion:a}=lt();t.exports={UuidNil:class extends r{static get VARIANT(){return 0}static get VERSION(){return 0}static generate(){let e=n.generateZeroFilled();return i(this.VARIANT,e),a(this.VERSION,e),new this(e)}static MAX(){let e=n.generateZeroFilled();return i(this.VARIANT,e),a(this.VERSION,e),new this(e)}}}})),ht=y(((e,t)=>{var{InvalidEncoding:n,InvalidBytes:r}=it(),i=Symbol(`valid_encoding_pattern`);t.exports={BaseCoder:class{constructor({valid_encoding_pattern:e}={}){this[i]=e}decode(e){if(this.isValidEncoding(e))return this.decodeTrusted(e);throw new n(`Encoding [${e}] does not satisfy ${this[i]}`)}decodeTrusted(e){return ByteArray.generateRandomFilled()}encode(e){if(this.isValidBytes(e))return this.encodeTrusted(e);throw new r(`Requires a 16-byte Uint8Array`)}encodeTrusted(e){return``}isValidBytes(e){return e instanceof Uint8Array&&e.length===16}isValidEncoding(e){return(typeof e==`string`||e instanceof String)&&this[i].test(e)}}}})),gt=y(((e,t)=>{var{BaseCoder:n}=ht(),r=`0123456789ABCDEFGHJKMNPQRSTVWXYZ`,i=31,a=Array.from(r).reduce((e,t,n)=>(e[t]=e[t.toLowerCase()]=n,e),{I:r.indexOf(`1`),i:r.indexOf(`1`),L:r.indexOf(`1`),l:r.indexOf(`1`),O:r.indexOf(`0`),o:r.indexOf(`0`),U:r.indexOf(`V`),u:r.indexOf(`V`)}),o=Array.from(r);function s(e){return a[e]}function c(e){return o[e&i]}t.exports=new class extends n{constructor(){super({valid_encoding_pattern:/^[0-7][^\W_]{25}$/})}decodeTrusted(e){let t=new Uint8Array(16),n=[];for(let t=0,r=e.length;t<r;++t)n.push(s(e[t]));return t[0]=n[0]<<5|n[1],t[1]=n[2]<<3|n[3]>>2,t[2]=n[3]<<6|n[4]<<1|n[5]>>4,t[3]=n[5]<<4|n[6]>>1,t[4]=n[6]<<7|n[7]<<2|n[8]>>3,t[5]=n[8]<<5|n[9],t[6]=n[10]<<3|n[11]>>2,t[7]=n[11]<<6|n[12]<<1|n[13]>>4,t[8]=n[13]<<4|n[14]>>1,t[9]=n[14]<<7|n[15]<<2|n[16]>>3,t[10]=n[16]<<5|n[17],t[11]=n[18]<<3|n[19]>>2,t[12]=n[19]<<6|n[20]<<1|n[21]>>4,t[13]=n[21]<<4|n[22]>>1,t[14]=n[22]<<7|n[23]<<2|n[24]>>3,t[15]=n[24]<<5|n[25],t}encodeTrusted(e){let t=[e[0]>>5,e[0],e[1]>>3,e[1]<<2|e[2]>>6,e[2]>>1,e[2]<<4|e[3]>>4,e[3]<<1|e[4]>>7,e[4]>>2,e[4]<<3|e[5]>>5,e[5],e[6]>>3,e[6]<<2|e[7]>>6,e[7]>>1,e[7]<<4|e[8]>>4,e[8]<<1|e[9]>>7,e[9]>>2,e[9]<<3|e[10]>>5,e[10],e[11]>>3,e[11]<<2|e[12]>>6,e[12]>>1,e[12]<<4|e[13]>>4,e[13]<<1|e[14]>>7,e[14]>>2,e[14]<<3|e[15]>>5,e[15]],n=``;for(let e=0,r=t.length;e<r;++e)n+=c(t[e]);return n}}})),_t=y(((e,t)=>{var{BaseCoder:n}=ht(),r=`0123456789ABCDEF`,i=Array.from({length:256}).map((e,t)=>``+r.charAt(t/16)+r.charAt(t%16)),a=Array.from(r).reduce((e,t,n)=>Object.assign(e,{[t.toUpperCase()]:n,[t.toLowerCase()]:n}),Object.create(null));t.exports=new class extends n{constructor(){super({valid_encoding_pattern:/^[0-9A-Fa-f]{32}$/})}decodeTrusted(e){let t=new Uint8Array(16);for(let n=0,r=!0,i=0,o=e.length;i<o;++i){let o=e[i];r?t[n]=a[o]<<4:t[n++]|=a[o],r=!r}return t}encodeTrusted(e){let t=``;for(let n=0,r=e.length;n<r;++n)t+=i[e[n]];return t}}})),vt=y(((e,t)=>{var{BaseCoder:n}=ht(),r=`0123456789ABCDEF`,i=Array.from({length:256}).map((e,t)=>``+r.charAt(t/16)+r.charAt(t%16)),a=Array.from(r).reduce((e,t,n)=>Object.assign(e,{[t.toUpperCase()]:n,[t.toLowerCase()]:n}),Object.create(null));t.exports=new class extends n{constructor(){super({valid_encoding_pattern:/^[0-9A-Fa-f]{4}(?:-?[0-9A-Fa-f]{4}){7}$/})}decodeTrusted(e){let t=new Uint8Array(16);for(let n=0,r=!0,i=0,o=e.length;i<o;++i){let o=e[i];o!==`-`&&(r?t[n]=a[o]<<4:t[n++]|=a[o],r=!r)}return t}encodeTrusted(e){let t=-1;return``+i[e[++t]]+i[e[++t]]+i[e[++t]]+i[e[++t]]+`-`+i[e[++t]]+i[e[++t]]+`-`+i[e[++t]]+i[e[++t]]+`-`+i[e[++t]]+i[e[++t]]+`-`+i[e[++t]]+i[e[++t]]+i[e[++t]]+i[e[++t]]+i[e[++t]]+i[e[++t]]}}})),yt=y(((e,t)=>{var n=Symbol(`id`),r=Symbol(`canonical_coder`),i=Symbol(`raw_coder`);t.exports={IdFactory:class{constructor({id:e,canonical_coder:t,raw_coder:a}={}){this[n]=class extends e{static get name(){return e.name}static get[Symbol.species](){return e}get[Symbol.toStringTag](){return`${e.name} ${this.toRaw()}`}toCanonical(){return t.encodeTrusted(this.bytes)}toRaw(){return a.encodeTrusted(this.bytes)}},this[r]=t,this[i]=a}get name(){return this[n].name}get type(){return this[n][Symbol.species]}construct(e){return new this[n](e)}generate(){return this[n].generate(...arguments)}MIN(){return this[n].MIN(...arguments)}MAX(){return this[n].MAX(...arguments)}fromCanonical(e){return this.construct(this[r].decode(e))}fromCanonicalTrusted(e){return this.construct(this[r].decodeTrusted(e))}fromRaw(e){return this.construct(this[i].decode(e))}fromRawTrusted(e){return this.construct(this[i].decodeTrusted(e))}toCanonical(e){return this[r].encode(e.bytes)}toRaw(e){return this[i].encode(e.bytes)}compare(e,t){return console.warn(`Deprecated: use generic idCompare instead.`),e.compare(t)}equal(e,t){return console.warn(`Deprecated: use generic idEqual instead.`),e.equal(t)}isCanonical(e){return this[r].isValidEncoding(e)}isRaw(e){return this[i].isValidEncoding(e)}}}})),bt=y(((e,t)=>{var{IdFactory:n}=yt(),{UnsupportedVersion:r}=it(),i=Symbol(`id_by_version`);function a(e,{version:t}={}){return e[i][t]||(()=>{throw new r(`No support for version [${t}]`)})()}t.exports={VersionedIdFactory:class extends n{constructor({abstract_id:e,versioned_ids:t,canonical_coder:r,raw_coder:a}){super({id:e,canonical_coder:r,raw_coder:a}),this[i]=t.reduce((e,t)=>Object.assign(e,{[t.MIN().version]:new n({id:t,canonical_coder:r,raw_coder:a})}),Object.create(null))}get versioned_ids(){return Object.values(this[i])}construct(e){let t=super.construct(e),n=t.version;try{return a(this,{version:n}).construct(e)}catch(e){if(e instanceof r)return t;throw e}}generate(){return a(this,...arguments).generate(...arguments)}MIN(){return a(this,...arguments).MIN()}MAX(){return a(this,...arguments).MAX()}}}})),xt=te(y(((e,t)=>{var{Ulid:n}=st(),{UlidMonotonic:r}=ct(),{Uuid:i}=lt(),{Uuid1:a}=dt(),{Uuid4:o}=ft(),{Uuid6:s}=pt(),{UuidNil:c}=mt(),l=gt(),u=_t(),d=vt(),{IdFactory:f}=yt(),{VersionedIdFactory:p}=bt(),m={idCompare:function(e,t){return e.compare(t)},idEqual:function(e,t){return e.equal(t)},Exception:it(),Ulid:new f({id:n,canonical_coder:l,raw_coder:u}),UlidMonotonic:new f({id:r,canonical_coder:l,raw_coder:u}),Uuid:new p({abstract_id:i,versioned_ids:[a,o,s,c],canonical_coder:d,raw_coder:u})};m.Uuid.versioned_ids.reduce((e,t)=>Object.assign(e,{[t.name]:t}),m),t.exports=m}))(),1),St=e=>xt.default.UlidMonotonic.generate({time:e}).toCanonical(),Ct=async(e,t)=>e.query(async e=>{for await(let[n,r]of e.scan({prefix:C.surface.prefix()}).entries())if(r.key===t)return{id:C.surface.decode(n),...r}}),wt=async e=>{let{replicache:n,key:r,name:i,description:a,toolList:o,projectId:s,signal:c}=e;return c?.aborted?Error(`Register surface aborted`):t(async()=>{let e=St();return await n.mutate.surface_upsert_v1({surfaceId:e,projectPublicId:s,key:r,name:i,description:a,toolList:o.map(e=>e.toJSON()),context:{actionedAt:Date.now()}}),await n.push({now:!0}),await n.pull({now:!0}),await Ct(n,r)||Error(`Surface "${r}" missing from Replicache`)})},Tt=class extends Error{name=`RoughClientDestroyedError`;constructor(e=`The Rough client has been destroyed`){super(e)}},Et=class extends Error{name=`RoughReplicacheIdentityConflictError`;replicacheName;constructor(e){super(`Another Rough client is already using the local database "${e.replicacheName}". Share the existing client through your framework ownership boundary, or await its destroy() before creating a replacement.`),this.replicacheName=e.replicacheName}},Dt=class extends Error{name=`RoughSurfaceContractConflictError`;surfaceKey;constructor(e){super(`Surface "${e.surfaceKey}" is already active on this client with a different contract. Close the operations using the old definition before activating the new one.`),this.surfaceKey=e.surfaceKey}},Ot=class extends Error{name=`RoughClientDestroyError`;errors;constructor(e){super(`Rough client destruction finished with ${e.errors.length} error(s): ${e.errors.map(e=>e.message).join(`; `)}`),this.errors=e.errors}},kt=class extends Error{name=`RoughInvalidClientError`;constructor(e=`Expected a RoughClient created by createRoughClient()`){super(e)}},At=e=>e instanceof Error?e:Error(String(e)),jt=e=>e.reason instanceof Error?e.reason:new Tt,Mt=e=>new Promise((t,n)=>{if(e.aborted){n(jt(e));return}e.addEventListener(`abort`,()=>n(jt(e)),{once:!0})}),Nt=e=>new Promise(t=>{if(e.aborted){t();return}e.addEventListener(`abort`,()=>t(),{once:!0})}),Pt=Symbol(`rough.surface.definition`),Ft=(e,t)=>{if(typeof e!=`string`||e.trim()===``)throw TypeError(`defineRoughSurface: "${t}" must be a non-empty string`);return e},It=e=>{let t=Ft(e.key,`key`),n=Ft(e.name,`name`),r=Ft(e.description,`description`);if(!Array.isArray(e.tools))throw TypeError(`defineRoughSurface: "tools" must be an array`);for(let t of e.tools)if(typeof t?.toJSON!=`function`)throw TypeError(`defineRoughSurface: every entry in "tools" must be a Query, Mutation or Subscription`);let i={key:t,name:n,description:r,tools:Object.freeze([...e.tools])};return Object.defineProperty(i,Pt,{value:!0,enumerable:!1,writable:!1,configurable:!1}),Object.freeze(i)},Lt=e=>typeof e==`object`&&!!e&&Pt in e&&e[Pt]===!0,Rt=e=>{if(!Lt(e))throw TypeError(`Expected a surface created by defineRoughSurface(). Object literals are not accepted because the definition must be validated and frozen.`);return e},zt=e=>JSON.stringify({key:e.key,name:e.name,description:e.description,tools:e.tools.map(e=>e.toJSON())}),Bt=e=>{let{getRuntime:t}=e,n=new Map,r=!1,i=(e,n)=>(async()=>{let r=t();r.assertUsable();let i=await Promise.race([r.getReplicache(),Mt(n)]);r.assertUsable();let a=await wt({replicache:i,projectId:r.projectId,key:e.key,name:e.name,description:e.description,toolList:e.tools,signal:n});if(a instanceof Error)throw a;return{id:a.id}})(),a=(e,t)=>{let r=new AbortController,a={registrationFingerprint:t,activeOperationCount:0,controller:r,resolution:i(e,r.signal)};return a.resolution.catch(()=>{n.get(e.key)===a&&n.delete(e.key)}),a};return{acquire:e=>{let i=Rt(e.surface);if(t().assertUsable(),r)throw new Tt;let o=zt(i),s=n.get(i.key);if(s&&s.registrationFingerprint!==o){if(s.activeOperationCount>0)throw new Dt({surfaceKey:i.key});s.controller.abort(Error(`Surface contract replaced`)),n.delete(i.key),s=void 0}s||(s=a(i,o),n.set(i.key,s));let c=s;c.activeOperationCount+=1;let l=!1;return{surfaceKey:i.key,ready:c.resolution,release:()=>{l||(l=!0,c.activeOperationCount=Math.max(c.activeOperationCount-1,0))}}},destroy:async()=>{r=!0;let e=[...n.values()];n.clear();for(let t of e)t.controller.abort(new Tt);await Promise.allSettled(e.map(e=>e.resolution))},getActiveOperationCount:e=>n.get(e)?.activeOperationCount??0}},Vt=()=>{let e=new Set;return{register:t=>(e.add(t),()=>{e.delete(t)}),closeAll:async()=>{let t=[...e];e.clear();let n=(await Promise.allSettled(t.map(async e=>{try{await e.close()}catch(t){let n=At(t);throw n.message=`${e.label}: ${n.message}`,n}}))).flatMap(e=>e.status===`rejected`?[At(e.reason)]:[]);if(n.length>0)throw new Ot({errors:n})},size:()=>e.size}},Ht=class{#e;constructor(e){this.#e=e}log(e,t,...n){for(let r of this.#e)r.log(e,t,...n)}async flush(){await Promise.all(this.#e.map(e=>e.flush?.()))}},Ut=class{debug=void 0;info=void 0;warn=void 0;error=void 0;flush;#e;#t;constructor(e,t=`info`,n){switch(this.#e=e,this.#t=n,t){case`debug`:this.debug=this.#n;case`info`:this.info=this.#r;case`warn`:this.warn=this.#i;case`error`:this.error=this.#a}this.flush=this.#o}#n(...e){this.#e.log(`debug`,this.#t,...e)}#r(...e){this.#e.log(`info`,this.#t,...e)}#i(...e){this.#e.log(`warn`,this.#t,...e)}#a(...e){this.#e.log(`error`,this.#t,...e)}#o(){return this.#e.flush?.()??Promise.resolve()}},Wt={log(e,t,...n){console[e](...Kt(t),...n.map(qt))}},Gt=class e extends Ut{#e;#t;#n;constructor(e=`info`,t,n=Wt){super(n,e,t),this.#t=e,this.#e=n,this.#n=t}withContext(t,n){let r={...this.#n,[t]:n};return new e(this.#t,r,this.#e)}};function Kt(e){let t=[];for(let[n,r]of Object.entries(e??{})){let e=r===void 0?n:`${n}=${r}`;t.push(e)}return t}function qt(e){switch(typeof e){case`string`:case`number`:case`boolean`:case`undefined`:case`symbol`:case`bigint`:return e;case`object`:if(e===null)return null}return JSON.stringify(e,Jt)}function Jt(e,t){return t instanceof Error?{name:t.name,message:t.message,stack:t.stack,...`cause`in t?{cause:t.cause}:null}:t}function D(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}var Yt=class{_lockP=null;async lock(){let e=this._lockP,{promise:t,resolve:n}=D();return this._lockP=t,await e,n}withLock(e){return Zt(this.lock(),e)}},Xt=class{_lock=new Yt;_writeP=null;_readP=[];read(){return this._lock.withLock(async()=>{await this._writeP;let{promise:e,resolve:t}=D();return this._readP.push(e),t})}withRead(e){return Zt(this.read(),e)}async write(){return await this._lock.withLock(async()=>{await this._writeP,await Promise.all(this._readP);let{promise:e,resolve:t}=D();return this._writeP=e,this._readP=[],t})}withWrite(e){return Zt(this.write(),e)}};async function Zt(e,t){let n=await e;try{return await t()}finally{n()}}var Qt=b({ValitaError:()=>cn,array:()=>rr,bigint:()=>Jn,boolean:()=>Qn,err:()=>dn,lazy:()=>or,literal:()=>er,never:()=>Rn,null:()=>Wn,number:()=>Kn,object:()=>tr,ok:()=>un,record:()=>nr,string:()=>Xn,tuple:()=>ir,undefined:()=>Hn,union:()=>ar,unknown:()=>Bn});function $t(e,t){return e?{ok:!1,code:`join`,left:e,right:t}:t}function en(e,t){return{ok:!1,code:`prepend`,key:e,tree:t}}function tn(e,t){let n=e.code;switch(n){case`invalid_type`:return{code:n,path:t,expected:e.expected};case`invalid_literal`:return{code:n,path:t,expected:e.expected};case`missing_value`:return{code:n,path:t};case`invalid_length`:return{code:n,path:t,minLength:e.minLength,maxLength:e.maxLength};case`unrecognized_keys`:return{code:n,path:t,keys:e.keys};case`invalid_union`:return{code:n,path:t,tree:e.tree};case`custom_error`:return{code:n,path:t,error:e.error}}}function nn(e,t=[],n=[]){for(;;)if(e.code===`join`)nn(e.left,t.slice(),n),e=e.right;else if(e.code===`prepend`)t.push(e.key),e=e.tree;else return e.code===`custom_error`&&typeof e.error==`object`&&e.error.path!==void 0&&t.push(...e.error.path),n.push(tn(e,t)),n}function rn(e,t){return e.length===0?`nothing`:e.length===1?e[0]:`${e.slice(0,-1).join(`, `)} ${t} ${e[e.length-1]}`}function an(e){return typeof e==`bigint`?`${e}n`:JSON.stringify(e)}function on(e){let t=0;for(;;)if(e.code===`join`)t+=on(e.left),e=e.right;else if(e.code===`prepend`)e=e.tree;else return t+1}function sn(e){let t=``,n=0;for(;;)if(e.code===`join`)n+=on(e.right),e=e.left;else if(e.code===`prepend`)t+=`.${e.key}`,e=e.tree;else break;let r=`validation failed`;if(e.code===`invalid_type`)r=`expected ${rn(e.expected,`or`)}`;else if(e.code===`invalid_literal`)r=`expected ${rn(e.expected.map(an),`or`)}`;else if(e.code===`missing_value`)r=`missing value`;else if(e.code===`unrecognized_keys`){let t=e.keys;r=`unrecognized ${t.length===1?`key`:`keys`} ${rn(t.map(an),`and`)}`}else if(e.code===`invalid_length`){let t=e.minLength,n=e.maxLength;r=`expected an array with `,r+=t>0?n===t?`${t}`:n===void 0?`at least ${t}`:`between ${t} and ${n}`:`at most ${n??`∞`}`,r+=` item(s)`}else if(e.code===`custom_error`){let n=e.error;typeof n==`string`?r=n:n!==void 0&&(n.message!==void 0&&(r=n.message),n.path!==void 0&&(t+=`.`+n.path.join(`.`)))}let i=`${e.code} at .${t.slice(1)} (${r})`;return n===1?i+=` (+ 1 other issue)`:n>1&&(i+=` (+ ${n} other issues)`),i}var cn=class extends Error{constructor(e){super(sn(e)),this.issueTree=e,Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name,this._issues=void 0}get issues(){return this._issues===void 0&&(this._issues=nn(this.issueTree)),this._issues}},ln=class{constructor(e){this.issueTree=e,this.ok=!1,this._issues=void 0,this._message=void 0}get issues(){return this._issues===void 0&&(this._issues=nn(this.issueTree)),this._issues}get message(){return this._message===void 0&&(this._message=sn(this.issueTree)),this._message}throw(){throw new cn(this.issueTree)}};function un(e){return{ok:!0,value:e}}function dn(e){return new ln({ok:!1,code:`custom_error`,error:e})}function fn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var pn=1,mn=2,hn=4,gn=class{optional(e){let t=new vn(this);return e?new Fn(t,t=>t===void 0?{ok:!0,value:e()}:void 0):t}default(e){let t=un(e);return new Fn(this.optional(),e=>e===void 0?t:void 0)}assert(e,t){let n={ok:!1,code:`custom_error`,error:t};return new Fn(this,(t,r)=>e(t,r)?void 0:n)}map(e){return new Fn(this,(t,n)=>({ok:!0,value:e(t,n)}))}chain(e){return new Fn(this,(t,n)=>{let r=e(t,n);return r.ok?r:r.issueTree})}},O=class extends gn{nullable(){return new _n(this)}toTerminals(e){e(this)}try(e,t){let n=pn;t?.mode===`passthrough`?n=0:t?.mode===`strip`&&(n=mn);let r=this.func(e,n);return r===void 0?{ok:!0,value:e}:r.ok?{ok:!0,value:r.value}:new ln(r)}parse(e,t){let n=pn;t?.mode===`passthrough`?n=0:t?.mode===`strip`&&(n=mn);let r=this.func(e,n);if(r===void 0)return e;if(r.ok)return r.value;throw new cn(r)}},_n=class extends O{constructor(e){super(),this.type=e,this.name=`nullable`}func(e,t){return e===null?void 0:this.type.func(e,t)}toTerminals(e){e(Un),this.type.toTerminals(e)}nullable(){return this}},vn=class extends gn{constructor(e){super(),this.type=e,this.name=`optional`}func(e,t){return e===void 0||t&hn?void 0:this.type.func(e,t)}toTerminals(e){e(this),e(Vn),this.type.toTerminals(e)}optional(e){return e?new Fn(this,t=>t===void 0?{ok:!0,value:e()}:void 0):this}};function yn(e,t){if(typeof e!=`number`){let n=t>>5;for(let t=e.length;t<=n;t++)e.push(0);return e[n]|=1<<t%32,e}return t<32?e|1<<t:yn([e,0],t)}function bn(e,t){return typeof e==`number`?t<32?e>>>t&1:0:e[t>>5]>>>t%32&1}var xn=class e extends O{constructor(e,t,n){super(),this.shape=e,this.restType=t,this.checks=n,this.name=`object`,this._invalidType={ok:!1,code:`invalid_type`,expected:[`object`]}}check(t,n){let r={ok:!1,code:`custom_error`,error:n};return new e(this.shape,this.restType,[...this.checks??[],{func:t,issue:r}])}func(e,t){if(!fn(e))return this._invalidType;let n=this._func;return n===void 0&&(n=Sn(this.shape,this.restType,this.checks),this._func=n),n(e,t)}rest(t){return new e(this.shape,t)}extend(t){return new e(Object.assign(Object.assign({},this.shape),t),this.restType)}pick(...t){let n={};return t.forEach(e=>{n[e]=this.shape[e]}),new e(n,void 0)}omit(...t){let n=Object.assign({},this.shape);return t.forEach(e=>{delete n[e]}),new e(n,this.restType)}partial(){let t={};Object.keys(this.shape).forEach(e=>{t[e]=this.shape[e].optional()});let n=this.restType?.optional();return new e(t,n)}};function Sn(e,t,n){let r=[],i=[];for(let t in e){let n=!1;e[t].toTerminals(e=>{n||=e.name===`optional`}),n?i.push(t):r.push(t)}let a=[...r,...i],o=a.length;if(o===0&&t?.name===`unknown`)return function(e,t){if(n!==void 0){for(let t=0;t<n.length;t++)if(!n[t].func(e))return n[t].issue}};let s=a.map(t=>e[t]),c=r.length,l=Object.create(null);a.forEach((e,t)=>{l[e]=~t});let u=r.map(e=>en(e,{ok:!1,code:`missing_value`}));function d(e,t,n){t===`__proto__`?Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0}):e[t]=n}return function(e,r){let i=!1,f=e,p,m,h=0,g=0;if(r&pn||r&mn||t!==void 0)for(let n in e){let c=e[n],u=~l[n],_;if(u>=0)g++,h=yn(h,u),_=s[u].func(c,r);else if(t!==void 0)_=t.func(c,r);else{if(r&pn)m===void 0?m=[n]:m.push(n);else if(r&mn&&p===void 0&&!i){f={},i=!0;for(let t=0;t<o;t++)if(bn(h,t)){let n=a[t];d(f,n,e[n])}}continue}if(_===void 0)i&&p===void 0&&d(f,n,c);else if(!_.ok)p=$t(p,en(n,_));else if(p===void 0){if(!i){if(f={},i=!0,t===void 0){for(let t=0;t<o;t++)if(t!==u&&bn(h,t)){let n=a[t];d(f,n,e[n])}}else for(let t in e)d(f,t,e[t])}d(f,n,_.value)}}if(g<o)for(let n=0;n<o;n++){if(bn(h,n))continue;let l=a[n],m=e[l],g=r&-5;if(m===void 0&&!(l in e)){if(n<c){p=$t(p,u[n]);continue}g|=hn}let _=s[n].func(m,g);if(_===void 0)i&&p===void 0&&!(g&hn)&&d(f,l,m);else if(!_.ok)p=$t(p,en(l,_));else if(p===void 0){if(!i){if(f={},i=!0,t===void 0){for(let t=0;t<o;t++)if(t<n||bn(h,t)){let n=a[t];d(f,n,e[n])}}else{for(let t in e)d(f,t,e[t]);for(let t=0;t<n;t++)if(!bn(h,t)){let n=a[t];d(f,n,e[n])}}}d(f,l,_.value)}}if(m!==void 0&&(p=$t(p,{ok:!1,code:`unrecognized_keys`,keys:m})),p===void 0&&n!==void 0){for(let e=0;e<n.length;e++)if(!n[e].func(f))return n[e].issue}return p===void 0&&i?{ok:!0,value:f}:p}}var Cn=class e extends O{constructor(e,t,n){super(),this.prefix=e,this.rest=t,this.suffix=n,this.name=`array`,this.restType=t??Rn(),this.minLength=this.prefix.length+this.suffix.length,this.maxLength=t?void 0:this.minLength,this.invalidType={ok:!1,code:`invalid_type`,expected:[`array`]},this.invalidLength={ok:!1,code:`invalid_length`,minLength:this.minLength,maxLength:this.maxLength}}func(e,t){if(!Array.isArray(e))return this.invalidType;let n=e.length,r=this.minLength,i=this.maxLength??1/0;if(n<r||n>i)return this.invalidLength;let a=this.prefix.length,o=e.length-this.suffix.length,s,c=e;for(let n=0;n<e.length;n++){let r=(n<a?this.prefix[n]:n>=o?this.suffix[n-o]:this.restType).func(e[n],t);r!==void 0&&(r.ok?(c===e&&(c=e.slice()),c[n]=r.value):s=$t(s,en(n,r)))}return s||(e===c?void 0:{ok:!0,value:c})}concat(t){if(this.rest){if(t.rest)throw TypeError(`can not concatenate two variadic types`);return new e(this.prefix,this.rest,[...this.suffix,...t.prefix,...t.suffix])}return t.rest?new e([...this.prefix,...this.suffix,...t.prefix],t.rest,t.suffix):new e([...this.prefix,...this.suffix,...t.prefix,...t.suffix],t.rest,t.suffix)}};function wn(e){let t=typeof e;return t===`object`?e===null?`null`:Array.isArray(e)?`array`:t:t}function Tn(e){return Array.from(new Set(e))}function En(e){let t=new Map;e.forEach(e=>{for(let n in e)t.set(n,(t.get(n)??0)+1)});let n=[];return t.forEach((t,r)=>{t===e.length&&n.push(r)}),n}function Dn(e){let t=new Map,n=new Map,r=new Map,i=[],a=[],o=[];e.forEach(({root:e,terminal:s})=>{if(t.set(e,t.get(e)??t.size),s.name!==`never`){if(s.name===`optional`)a.push(e);else if(s.name===`unknown`)i.push(e);else if(s.name===`literal`){let t=n.get(s.value)??[];t.push(e),n.set(s.value,t),o.push(wn(s.value))}else{let t=r.get(s.name)??[];t.push(e),r.set(s.name,t),o.push(s.name)}}}),n.forEach((e,t)=>{let i=r.get(wn(t));i&&(i.push(...e),n.delete(t))});let s=(e,n)=>(t.get(e)??0)-(t.get(n)??0);return r.forEach((e,t)=>r.set(t,Tn(e.concat(i).sort(s)))),n.forEach((e,t)=>n.set(t,Tn(e.concat(i)).sort(s))),{types:r,literals:n,unknowns:Tn(i).sort(s),optionals:Tn(a).sort(s),expectedTypes:Tn(o)}}function On(e,t){let n=[];for(let{root:r,terminal:i}of e)i.shape[t].toTerminals(e=>n.push({root:r,terminal:e}));let{types:r,literals:i,optionals:a,unknowns:o,expectedTypes:s}=Dn(n);if(o.length>0||a.length>1)return;for(let e of i.values())if(e.length>1)return;for(let e of r.values())if(e.length>1)return;let c=en(t,{ok:!1,code:`missing_value`}),l=en(t,r.size===0?{ok:!1,code:`invalid_literal`,expected:Array.from(i.keys())}:{ok:!1,code:`invalid_type`,expected:s}),u=i.size>0?new Map:void 0;for(let[e,t]of i)u.set(e,t[0]);let d=r.size>0?{}:void 0;for(let[e,t]of r)d[e]=t[0];return function(e,n){let r=e,i=r[t];if(i===void 0&&!(t in r))return a.length>0?a[0].func(r,n):c;let o=d?.[wn(i)]??u?.get(i);return o?o.func(r,n):l}}function kn(e){if(e.some(({terminal:e})=>e.name===`unknown`))return;let t=e.filter(e=>e.terminal.name===`object`);if(t.length<2)return;let n=t.map(({terminal:e})=>e.shape);for(let e of En(n)){let n=On(t,e);if(n)return n}}function An(e){let{expectedTypes:t,literals:n,types:r,unknowns:i,optionals:a}=Dn(e),o=r.size===0&&i.length===0?{ok:!1,code:`invalid_literal`,expected:Array.from(n.keys())}:{ok:!1,code:`invalid_type`,expected:t},s=n.size>0?n:void 0,c=r.size>0?{}:void 0;for(let[e,t]of r)c[e]=t;return function(e,t){let n=t&hn?a:c?.[wn(e)]??s?.get(e)??i,r=0,l=o;for(let i=0;i<n.length;i++){let a=n[i].func(e,t);if(a===void 0||a.ok)return a;l=r>0?$t(l,a):a,r++}return r>1?{ok:!1,code:`invalid_union`,tree:l}:l}}var jn=class extends O{constructor(e){super(),this.options=e,this.name=`union`}toTerminals(e){this.options.forEach(t=>{t.toTerminals(e)})}func(e,t){let n=this._func;if(n===void 0){let e=[];this.options.forEach(t=>{t.toTerminals(n=>{e.push({root:t,terminal:n})})});let t=An(e),r=kn(e);n=r?function(e,n){return fn(e)?r(e,n):t(e,n)}:t,this._func=n}return n(e,t)}},Mn=Object.freeze({mode:`strict`}),Nn=Object.freeze({mode:`strip`}),Pn=Object.freeze({mode:`passthrough`}),Fn=class e extends O{constructor(e,t){super(),this.transformed=e,this.transform=t,this.name=`transform`,this.undef=un(void 0),this.transformChain=void 0,this.transformRoot=void 0}func(t,n){let r=this.transformChain;if(!r){r=[];let t=this;for(;t instanceof e;)r.push(t.transform),t=t.transformed;r.reverse(),this.transformChain=r,this.transformRoot=t}let i=this.transformRoot.func(t,n);if(i!==void 0&&!i.ok)return i;let a;i===void 0?n&hn?(a=void 0,i=this.undef):a=t:a=i.value;let o=n&pn?Mn:n&mn?Nn:Pn;for(let e=0;e<r.length;e++){let t=r[e](a,o);if(t!==void 0){if(!t.ok)return t;a=t.value,i=t}}return i}toTerminals(e){this.transformed.toTerminals(e)}},In=class extends O{constructor(e){super(),this.definer=e,this.name=`lazy`,this.recursing=!1}func(e,t){return this.type||=this.definer(),this.type.func(e,t)}toTerminals(e){if(!this.recursing)try{this.recursing=!0,this.type||=this.definer(),this.type.toTerminals(e)}finally{this.recursing=!1}}},Ln=new class extends O{constructor(){super(...arguments),this.name=`never`,this.issue={ok:!1,code:`invalid_type`,expected:[]}}func(e,t){return this.issue}};function Rn(){return Ln}var zn=new class extends O{constructor(){super(...arguments),this.name=`unknown`}func(e,t){}};function Bn(){return zn}var Vn=new class extends O{constructor(){super(...arguments),this.name=`undefined`,this.issue={ok:!1,code:`invalid_type`,expected:[`undefined`]}}func(e,t){return e===void 0?void 0:this.issue}};function Hn(){return Vn}var Un=new class extends O{constructor(){super(...arguments),this.name=`null`,this.issue={ok:!1,code:`invalid_type`,expected:[`null`]}}func(e,t){return e===null?void 0:this.issue}};function Wn(){return Un}var Gn=new class extends O{constructor(){super(...arguments),this.name=`number`,this.issue={ok:!1,code:`invalid_type`,expected:[`number`]}}func(e,t){return typeof e==`number`?void 0:this.issue}};function Kn(){return Gn}var qn=new class extends O{constructor(){super(...arguments),this.name=`bigint`,this.issue={ok:!1,code:`invalid_type`,expected:[`bigint`]}}func(e,t){return typeof e==`bigint`?void 0:this.issue}};function Jn(){return qn}var Yn=new class extends O{constructor(){super(...arguments),this.name=`string`,this.issue={ok:!1,code:`invalid_type`,expected:[`string`]}}func(e,t){return typeof e==`string`?void 0:this.issue}};function Xn(){return Yn}var Zn=new class extends O{constructor(){super(...arguments),this.name=`boolean`,this.issue={ok:!1,code:`invalid_type`,expected:[`boolean`]}}func(e,t){return typeof e==`boolean`?void 0:this.issue}};function Qn(){return Zn}var $n=class extends O{constructor(e){super(),this.value=e,this.name=`literal`,this.issue={ok:!1,code:`invalid_literal`,expected:[e]}}func(e,t){return e===this.value?void 0:this.issue}};function er(e){return new $n(e)}function tr(e){return new xn(e,void 0)}function nr(e){return new xn({},e??Bn())}function rr(e){return new Cn([],e??Bn(),[])}function ir(e){return new Cn(e,void 0,[])}function ar(...e){return new jn(e)}function or(e){return new In(e)}var sr=Object.defineProperty,cr=Object.getOwnPropertyDescriptor,lr=Object.getOwnPropertyNames,ur=Object.prototype.hasOwnProperty,dr=(e,t)=>{for(var n in t)sr(e,n,{get:t[n],enumerable:!0})},fr=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let i of lr(t))!ur.call(e,i)&&i!==n&&sr(e,i,{get:()=>t[i],enumerable:!(r=cr(t,i))||r.enumerable});return e},pr=(e,t,n)=>(fr(e,t,`default`),n&&fr(n,t,`default`)),mr=class extends Error{name=`AbortError`};function k(e,t=`Assertion failed`){if(!e)throw Error(t)}function A(e){gr(e,`string`)}function j(e){gr(e,`number`)}function hr(e){gr(e,`boolean`)}function gr(e,t){typeof e!==t&&yr(e,t)}function M(e){e===null&&yr(e,`object`),gr(e,`object`)}function _r(e){Array.isArray(e)||yr(e,`array`)}function vr(e,t){let n=`Invalid type: `;return n+=e==null?e:`${typeof e} \`${e}\``,n+`, expected ${t}`}function yr(e,t){throw Error(vr(e,t))}function br(e){if(e===null)throw Error(`Expected non-null value`)}function xr(e,t=`Expected non undefined value`){if(e===void 0)throw Error(t)}function Sr(e){throw Error(`Unreachable`)}function Cr(){return typeof document<`u`?document:void 0}function wr(e,t,n){return e?new Tr(e,t,n):new Or}var Tr=class{#e;#t;#n=0;visibilityState;#r=new Set;constructor(e,t,n){this.#e=e,this.#t=t,this.visibilityState=e.visibilityState,this.#e.addEventListener(`visibilitychange`,this.#i,{signal:n})}#i=()=>{this.#e.visibilityState===`visible`?(clearTimeout(this.#n),this.#a(`visible`)):this.#n=setTimeout(()=>{this.#a(`hidden`)},this.#t)};#a(e){if(e!==this.visibilityState){this.visibilityState=e;for(let t of this.#r){let{resolve:n,state:r}=t;r===e&&(n(),this.#r.delete(t))}}}waitForVisible(){return this.#o(`visible`)}waitForHidden(){return this.#o(`hidden`)}#o(e){if(this.visibilityState===e)return Promise.resolve();let{promise:t,resolve:n}=D();return this.#r.add({resolve:n,state:e}),t}},Er=Promise.resolve(),Dr=new Promise(()=>{}),Or=class{visibilityState=`visible`;waitForVisible(){return Er}waitForHidden(){return Dr}},kr=class{rep;invokeSend;maxConnections=1;constructor(e,t){this.rep=e,this.invokeSend=t}get maxDelayMs(){return this.rep.requestOptions.maxDelayMs}get minDelayMs(){return this.rep.requestOptions.minDelayMs}},Ar=class extends kr{debounceDelay=0;get watchdogTimer(){return this.rep.pullInterval}},jr=class extends kr{get debounceDelay(){return this.rep.pushDelay}watchdogTimer=null},Mr=Promise.resolve();new Promise(()=>{});function Nr(e,t){return e===0?Mr:new Promise((n,r)=>{let i;t&&(i=()=>{clearTimeout(a),r(new mr(`Aborted`))},t.addEventListener(`abort`,i,{once:!0}));let a=setTimeout(()=>{n(),t?.removeEventListener(`abort`,i)},e)})}var Pr=30,Fr=6e4,Ir=class{#e=D();#t=D();#n=D();#r;#i=!1;#a=0;#o;#s;constructor(e,t,n){this.#o=e,this.#r=t,this.#s=n,this.run()}close(){this.#i=!0,this.#a>0&&this.#n.resolve({error:Rr()})}async send(e){if(this.#i)return{error:Rr()};this.#a++,this.#o.debug?.(`send`,e),e?this.#t.resolve():await this.#s?.waitForVisible(),this.#e.resolve();let t=await this.#n.promise;return this.#a--,t}async run(){let e=[],t=D(),n,r=0,i=this.#r,{debug:a}=this.#o,o=0;a?.(`Starting connection loop`);let s=e=>Promise.race([this.#t.promise,Nr(e)]);for(;!this.#i;){a?.(Vr(e)?`Last request failed. Trying again`:`Waiting for a send`);let c=[this.#e.promise],l=i.watchdogTimer;if(l!==null&&c.push(Nr(l)),await Promise.race(c),this.#i||(a?.(`Waiting for debounce`),await s(i.debounceDelay),this.#i))break;if(a?.(`debounced`),this.#e=D(),r>=i.maxConnections){if(a?.(`Too many request in flight. Waiting until one finishes...`),await this.#u(),this.#i)break;a?.(`...finished`)}r>0||Vr(e)?(o=zr(o,i,e),a?.(Vr(e)?`Last connection errored. Sleeping for`:`More than one outstanding connection (`+r+`). Sleeping for`,o,`ms`)):o=0;let u=Math.min(i.maxDelayMs,Math.max(i.minDelayMs,o));if(n!==void 0){let e=Date.now()-n;if(u>e&&(await Promise.race([s(u-e),t.promise]),this.#i))break}r++,(async()=>{let o=Date.now(),s,c;try{n=o,a?.(`Sending request`),this.#t=D(),s=await i.invokeSend(),a?.(`Send returned`,s)}catch(e){a?.(`Send failed`,e),c=e,s=!1}if(this.#i){a?.(`Closed after invokeSend`);return}a?.(`Request done`,{duration:Date.now()-o,ok:s}),e.push({duration:Date.now()-o,ok:s}),Hr(e)&&(t.resolve(),t=D()),r--,this.#l();let l=this.#n;this.#n=D(),c?l.resolve({error:c}):l.resolve(void 0),s||this.#e.resolve()})()}}#c=void 0;#l(){if(this.#c){let e=this.#c;this.#c=void 0,e()}}#u(){let{promise:e,resolve:t}=D();return this.#c=t,e}},Lr=9;function Rr(){return Error(`Closed`)}function zr(e,t,n){let{length:r}=n;if(r===0)return e;let{ok:i}=n[n.length-1],{maxConnections:a,minDelayMs:o}=t;if(!i)return e===0?o:e*2;if(r>1){let e=n[n.length-2];for(;n.length>Lr;)n.shift();if(i&&!e.ok)return o}return Br(n.filter(({ok:e})=>e).map(({duration:e})=>e))/a|0}function Br(e){e.sort();let{length:t}=e,n=t>>1;return t%2==1?e[n]:(e[n-1]+e[n])/2}function Vr(e){return e.length>0&&!e[e.length-1].ok}function Hr(e){return e.length>1&&!e[e.length-2].ok&&e[e.length-1].ok}var Ur=process.env.NODE_ENV===`production`,Wr=Object.prototype.hasOwnProperty,Gr=Object.hasOwn||((e,t)=>Wr.call(e,t));function Kr(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;switch(typeof e){case`boolean`:case`number`:case`string`:return!1}if(e=e,Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!Kr(e[n],t[n]))return!1;return!0}if(e===null||t===null||Array.isArray(t))return!1;e=e,t=t;let n=0;for(let r in e)if(Gr(e,r)){if(!Kr(e[r],t[r]))return!1;n++}let r=0;for(let e in t)Gr(t,e)&&r++;return n===r}function qr(e){if(!Ur){switch(typeof e){case`boolean`:case`number`:case`string`:return;case`object`:return e===null?void 0:Array.isArray(e)?Xr(e):Yr(e)}yr(e,`JSON value`)}}function Jr(e){M(e),Yr(e)}function Yr(e){for(let t in e)if(Gr(e,t)){let n=e[t];n!==void 0&&qr(n)}}function Xr(e){for(let t of e)qr(t)}function Zr(e,t){switch(typeof e){case`boolean`:case`number`:case`string`:return!0;case`object`:return e===null?!0:Array.isArray(e)?ei(e,t):$r(e,t)}return!1}function Qr(e,t){return typeof e!=`object`||!e?!1:$r(e,t)}function $r(e,t){for(let n in e)if(Gr(e,n)){t.push(n);let r=e[n];if(r!==void 0&&!Zr(r,t))return!1;t.pop()}return!0}function ei(e,t){for(let n=0;n<e.length;n++){if(t.push(n),!Zr(e[n],t))return!1;t.pop()}return!0}function ti(e,t){return e===t?0:e<t?-1:1}function ni(e,t){if(e===t)return 0;if(e===null)return-1;if(t===null)return 1;let n=ri(e),r=ri(t);return typeof n==`string`||typeof r==`string`?ti(String(n),String(r)):n-r}function ri(e){return typeof e==`string`||typeof e==`number`?e:e.order}function ii(e){if(e!==null&&typeof e!=`string`&&typeof e!=`number`&&(Jr(e),typeof e.order!=`string`&&typeof e.order!=`number`))throw Error(`Invalid cookie`)}function*ai(...e){for(let t of e)yield*t}var oi=Promise.resolve(!0),si=Promise.resolve(!1);Promise.resolve(void 0);var ci=Promise.resolve(),li=1,ui=4,di=5,fi=8;function pi(e){switch(typeof e){case`string`:return li+ui+e.length;case`number`:return mi(e)?e<=-(2**30)||e>=2**30-1?li+di:li+ui:li+fi;case`boolean`:return li;case`object`:if(e===null)return li;if(Array.isArray(e)){let t=2*li+ui;for(let n of e)t+=pi(n);return t}{let t=e,n=2*li+ui;for(let e in t)if(Gr(t,e)){let r=t[e];r!==void 0&&(n+=pi(e)+pi(r))}return n}}throw Error(`Invalid value. type: ${typeof e}, value: ${e}`)}function mi(e){return e===(e|0)}var hi=2*li+ui+li+ui;function gi(e,t){return hi+pi(e)+pi(t)}var _i=new WeakSet;function vi(e){return Ur||yi(e,[]),e}function yi(e,t){switch(typeof e){case`undefined`:throw TypeError(`Unexpected value undefined`);case`boolean`:case`number`:case`string`:return;case`object`:if(e===null||_i.has(e))return;_i.add(e),t.includes(e)&&yr(e,`Cyclic JSON object`),t.push(e),Object.freeze(e),Array.isArray(e)?bi(e,t):xi(e,t),t.pop();return;default:yr(e,`JSON value`)}}function bi(e,t){for(let n of e)yi(n,t)}function xi(e,t){for(let n in e)if(Gr(e,n)){let r=e[n];r!==void 0&&yi(r,t)}}function Si(e){if(!Ur&&!Ci(e,[]))throw Error(`Expected frozen object`)}function Ci(e,t){switch(typeof e){case`boolean`:case`number`:case`string`:return!0;case`object`:if(e===null||_i.has(e))return!0;if(!Object.isFrozen(e))return!1;if(t.includes(e)&&yr(e,`Cyclic JSON object`),t.push(e),Array.isArray(e)){for(let n of e)if(!Ci(n,t))return t.pop(),!1}else for(let n in e)if(Gr(e,n)){let r=e[n];if(r!==void 0&&!Ci(r,t))return t.pop(),!1}return _i.add(e),t.pop(),!0;default:yr(e,`JSON value`)}}function wi(e){if(e!==void 0)return vi(e)}function Ti(e){if(Array.isArray(e)){e.sort();for(let t=1;t<e.length;t++)k(e[t-1]!==e[t],`Refs must not have duplicates`);return e}let t=[...e];return t.sort(),t}var Ei=class{hash;data;meta;constructor(e,t,n){k(!n.includes(e),`Chunk cannot reference itself`),Si(t),this.hash=e,this.data=t,this.meta=n}};function Di(e){if(!Array.isArray(e))throw Error(`Refs must be an array`);if(e.length>0){A(e[0]);for(let t=1;t<e.length;t++)A(e[t])}}function Oi(e,t,n){return new Ei(n(),e,t)}function ki(){throw Error(`unexpected call to compute chunk hash`)}function Ai(){let e=Math.floor(Math.random()*4294967295),t=Math.floor(Math.random()*4294967295);return BigInt(e)<<32n|BigInt(t)}var N={};dr(N,{assert:()=>Li,is:()=>Ii,parse:()=>Fi,readonly:()=>zi,readonlyArray:()=>Vi,readonlyObject:()=>Bi,readonlyRecord:()=>Hi,test:()=>Ri}),pr(N,Qt);function ji(e){switch(typeof e){case`string`:case`number`:case`boolean`:return JSON.stringify(e);case`undefined`:return`undefined`;case`bigint`:return e.toString()+`n`;default:return e===null?`null`:Array.isArray(e)?`array`:typeof e}}function Mi(e,t){if(!t?.length)return ji(e);let n=e;for(let e of t)n=n[e];return ji(n)}function Ni(e,t,n=e=>String(e)){if(t.length===1)return n(t[0]);let r=`${n(t[t.length-2])} ${e} ${n(t[t.length-1])}`;return t.length===2?r:`${t.slice(0,-2).map(n).join(`, `)}, ${r}`}function Pi(e,t){let n=e.issues[0],{path:r}=n,i=r?.length?` at ${r.join(`.`)}`:``;switch(n.code){case`invalid_type`:return`Expected ${Ni(`or`,n.expected)}${i}. Got ${Mi(t,r)}`;case`missing_value`:{let e=r&&r.length>1?` at ${r.slice(0,-1).join(`.`)}`:``;return n.path?.length?`Missing property ${n.path.at(-1)}${e}`:`TODO Unknown missing property${e}`}case`invalid_literal`:return`Expected literal value ${Ni(`or`,n.expected,ji)}${i} Got ${Mi(t,r)}`;case`invalid_length`:return`Expected array with length ${n.minLength===n.maxLength?n.minLength:`between ${n.minLength} and ${n.maxLength}`}${i}. Got array with length ${t.length}`;case`unrecognized_keys`:return n.keys.length===1?`Unexpected property ${n.keys[0]}${i}`:`Unexpected properties ${Ni(`and`,n.keys)}${i}`;case`invalid_union`:return`Invalid union value${i}`;case`custom_error`:{let{error:e}=n;return`${e?typeof e==`string`?e:e.message??`unknown`:`unknown`}${i}. Got ${Mi(t,r)}`}}}function Fi(e,t,n){let r=Ri(e,t,n);if(!r.ok)throw TypeError(r.error);return r.value}function Ii(e,t,n){return Ri(e,t,n).ok}function Li(e,t,n){Fi(e,t,n)}function Ri(e,t,n){let r=t.try(e,n?{mode:n}:void 0);return r.ok?r:{ok:!1,error:Pi(r,e)}}function zi(e){return e}function Bi(e){return tr(e)}function Vi(e){return rr(e)}function Hi(e){return nr(e)}var Ui=22,Wi=/^[0-9a-v-]+$/,P=`0`.repeat(Ui),Gi=qi();function Ki(e,t){return e.toString(32).slice(-t).padStart(t,`0`)}function qi(){let e=``,t=0;return()=>{e||=Ki(Ai(),12);let n=Ki(t++,10);return e+n}}function Ji(e){return typeof e==`string`&&Wi.test(e)}function Yi(e){Li(e,Xi)}var Xi=N.string().assert(Ji,`Invalid hash`);function Zi(e,t,n){return new Qi(e,t,n).compute()}var Qi=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e,t,n){let r=[],i=[];for(let t of e)t.old!==t.new&&(t.old&&i.push(t.old),t.new&&r.push(t.new));this.#e=r,this.#t=i,this.#n=t,this.#r=n,this.#a=new Map,this.#o=new Map,this.#s=n.areRefsCounted!==void 0,this.#i=this.#s?new Set:null}async compute(){for(let e of this.#e)await this.#c(e,1);if(await Promise.all(Array.from(this.#n.values(),e=>this.#u(e))),this.#s){k(this.#r.areRefsCounted),k(this.#i);let e;do{e=!1;for(let t of this.#n.values())if(!this.#r.areRefsCounted(t)&&!this.#i.has(t)&&this.#a.get(t)!==0){await this.#l(t,1),e=!0;break}}while(e)}for(let e of this.#t)await this.#c(e,-1);if(!Ur)for(let[e,t]of this.#a)k(t>=0,`ref count update must be non-negative. ${e}:${t}`);return this.#a}async#c(e,t){await this.#u(e),this.#d(e,t)&&await this.#l(e,t)}async#l(e,t){if(e===P)return;let n=await this.#r.getRefs(e);if(Ur||k(n||this.#s&&!this.#n.has(e),`refs must be defined`),n!==void 0){this.#i?.add(e);let r=n.map(e=>this.#c(e,t));await Promise.all(r)}}#u(e){let t=this.#o.get(e);return t===void 0&&(t=(async()=>{let t=await this.#r.getRefCount(e)||0;return this.#a.set(e,t),t})(),this.#o.set(e,t)),t}#d(e,t){let n=this.#a.get(e);return j(n),this.#a.set(e,n+t),n===0&&t===1||n===1&&t===-1}},$i=class extends Error{name=`ChunkNotFoundError`;hash;constructor(e){super(`Chunk not found ${e}`),this.hash=e}};async function ea(e,t){let n=await e.getChunk(t);if(n)return n;throw new $i(t)}async function ta(e,t){let n=await t.getHead(e);return k(n,`Missing head ${e}`),n}var na=class{#e=new Xt;#t=new Map;#n;#r;#i;t=new Map;n;h=new Map;m=new Map;constructor(e,t,n,r,i=pi){this.n=new aa(t,i,this.h,this.m),this.#n=e,this.#r=n,this.#i=r}async read(){let e=await this.#e.read();return new ra(this.#t,this.t,this.n,this.#n,e,this.#i)}async write(){let e=await this.#e.write();return new ia(this.#t,this.t,this.n,this.#n,this.h,this.m,e,this.#r,this.#i)}close(){return ci}isCached(e){return this.n.getWithoutUpdatingLRU(e)!==void 0}withSuspendedSourceCacheEvictsAndDeletes(e){return this.n.withSuspendedEvictsAndDeletes(e)}},ra=class{a;t;n;f;#e=void 0;#t;#n=!1;assertValidHash;constructor(e,t,n,r,i,a){this.a=e,this.t=t,this.n=n,this.f=r,this.#t=i,this.assertValidHash=a}isMemOnlyChunkHash(e){return this.t.has(e)}async hasChunk(e){return await this.getChunk(e)!==void 0}async getChunk(e){let t=this.t.get(e);if(t!==void 0)return t;let n=this.n.get(e);return n===void 0&&(n=await(await this.y()).getChunk(e),n!==void 0&&this.n.put(n)),n}mustGetChunk(e){return ea(this,e)}getHead(e){return Promise.resolve(this.a.get(e))}release(){this.#n||=(this.#t(),this.#e?.then(e=>e.release()).catch(e=>{}),!0)}get closed(){return this.#n}y(){return this.#e||=this.f.read(),this.#e}},ia=class extends ra{#e;#t;#n;i=new Map;o=new Map;s=new Map;#r=new Set;constructor(e,t,n,r,i,a,o,s,c){super(e,t,n,r,o,c),this.#e=i,this.#t=a,this.#n=s}createChunk=(e,t)=>{let n=Oi(e,t,this.#n);return this.#r.add(n.hash),n};putChunk(e,t){let{hash:n,meta:r}=e;if(this.assertValidHash(n),r.length>0)for(let e of r)this.assertValidHash(e);return this.#r.has(n)||this.isMemOnlyChunkHash(n)?this.o.set(n,e):this.s.set(n,{chunk:e,size:t??-1}),ci}async setHead(e,t){await this.#i(e,t)}async removeHead(e){await this.#i(e,void 0)}async#i(e,t){let n=await this.getHead(e),r=this.i.get(e);r===void 0?this.i.set(e,{new:t,old:n}):r.new=t}isMemOnlyChunkHash(e){return this.o.has(e)||super.isMemOnlyChunkHash(e)}async getChunk(e){let t=this.o.get(e);if(t!==void 0)return t;let n=this.t.get(e);if(n!==void 0)return n;let r=this.s.get(e);if(r!==void 0)return r.chunk;let i=this.n.get(e);return i===void 0&&(i=await(await this.y()).getChunk(e),i!==void 0&&this.s.set(i.hash,{chunk:i,size:-1})),i}getHead(e){let t=this.i.get(e);return t?Promise.resolve(t.new):super.getHead(e)}async commit(){let e=new Set(ai(this.o.keys(),this.s.keys())),t=await Zi(this.i.values(),e,this);for(let[e,n]of t)if(this.isMemOnlyChunkHash(e)){if(n===0)this.#e.delete(e),this.t.delete(e),this.#t.delete(e);else{this.#e.set(e,n);let t=this.o.get(e);t&&(this.#t.set(e,t.meta),this.t.set(e,t))}t.delete(e)}this.n.updateForCommit(this.s,t);for(let[e,t]of this.i)t.new?this.a.set(e,t.new):this.a.delete(e);this.o.clear(),this.s.clear(),this.i.clear(),this.release()}getRefCount(e){return this.#e.get(e)}getRefs(e){let t=this.o.get(e);if(t)return t.meta;let n=this.t.get(e);if(n)return n.meta;let r=this.s.get(e);return r===void 0?this.#t.get(e):r.chunk.meta}areRefsCounted(e){return this.#t.has(e)}chunksPersisted(e){let t=[];for(let n of e){let e=this.t.get(n);e&&(this.t.delete(n),t.push(e))}this.n.persisted(t)}},aa=class{#e;#t;#n;#r;#i=0;#a=!1;#o=[];cacheEntries=new Map;constructor(e,t,n,r){this.#e=e,this.#t=t,this.#n=n,this.#r=r}get(e){let t=this.cacheEntries.get(e);return t&&(this.cacheEntries.delete(e),this.cacheEntries.set(e,t)),t?.chunk}getWithoutUpdatingLRU(e){return this.cacheEntries.get(e)?.chunk}put(e){let{hash:t}=e,n=this.cacheEntries.get(t);if(n){this.cacheEntries.delete(t),this.cacheEntries.set(t,n);return}let r=this.#n.get(t);if(!(r===void 0||r<1)&&this.#c(e)){if(!this.#r.has(t)){for(let t of e.meta)this.#n.set(t,(this.#n.get(t)||0)+1);this.#r.set(t,e.meta)}this.#s()}}#s(){if(!this.#a)for(let e of this.cacheEntries.values()){if(this.#i<=this.#e)break;this.#l(e)}}#c(e,t){let n=t??this.#t(e);return n>this.#e?!1:(this.#i+=n,this.cacheEntries.set(e.hash,{chunk:e,size:n}),!0)}#l(e){let{hash:t}=e.chunk;this.#i-=e.size,this.cacheEntries.delete(t)}#u(e){this.#n.delete(e),this.#r.delete(e);let t=this.cacheEntries.get(e);t&&(this.#i-=t.size,this.cacheEntries.delete(e))}updateForCommit(e,t){for(let[n,r]of t)if(r===0)this.#a?(this.#n.set(n,0),this.#o.push(n)):this.#u(n);else{this.#n.set(n,r);let t=e.get(n);if(t){let{chunk:e,size:r}=t,i=this.cacheEntries.get(n);i?(this.cacheEntries.delete(n),this.cacheEntries.set(n,i)):(this.#c(e,r===-1?void 0:r),this.#r.set(n,e.meta))}}this.#s()}persisted(e){for(let t of e)this.#c(t);this.#s()}async withSuspendedEvictsAndDeletes(e){this.#a=!0;try{return await e()}finally{this.#a=!1;for(let e of this.#o)this.#n.get(e)===0&&this.#u(e);this.#s()}}};function oa(e){return`c/${e}/d`}function sa(e){return`c/${e}/m`}function ca(e){return`c/${e}/r`}function la(e){return`h/${e}`}var ua=class{#e;#t;#n;constructor(e,t,n){this.#e=e,this.#t=t,this.#n=n}async read(){return new da(await this.#e.read(),this.#n)}async write(){return new fa(await this.#e.write(),this.#t,this.#n)}close(){return this.#e.close()}},da=class{e;assertValidHash;constructor(e,t){this.e=e,this.assertValidHash=t}hasChunk(e){return this.e.has(oa(e))}async getChunk(e){let t=await this.e.get(oa(e));if(t===void 0)return;let n=await this.e.get(sa(e)),r;return n===void 0?r=[]:(Di(n),r=n),new Ei(e,t,r)}mustGetChunk(e){return ea(this,e)}async getHead(e){let t=await this.e.get(la(e));if(t!==void 0)return Yi(t),t}release(){this.e.release()}get closed(){return this.e.closed}},fa=class extends da{#e;#t=new Set;#n=new Map;constructor(e,t,n){super(e,n),this.#e=t}createChunk=(e,t)=>Oi(e,t,this.#e);get kvWrite(){return this.e}async putChunk(e){let{hash:t,data:n,meta:r}=e;this.assertValidHash(t);let i=oa(t),a=this.e.put(i,n),o;if(r.length>0){for(let e of r)this.assertValidHash(e);o=this.e.put(sa(t),r)}this.#t.add(t),await a,await o}setHead(e,t){return this.#r(e,t)}removeHead(e){return this.#r(e,void 0)}async#r(e,t){let n=await this.getHead(e),r=la(e),i;i=t===void 0?this.e.del(r):this.e.put(r,t);let a=this.#n.get(e);a===void 0?this.#n.set(e,{new:t,old:n}):a.new=t,await i}async commit(){let e=await Zi(this.#n.values(),this.#t,this);await this.#i(e),await this.e.commit()}async getRefCount(e){let t=await this.e.get(ca(e));if(t!==void 0){if(j(t),t<0||t>65535||t!==(t|0))throw Error(`Invalid ref count ${t}. We expect the value to be a Uint16`);return t}}async getRefs(e){let t=await this.e.get(sa(e));return t===void 0?[]:(Di(t),t)}async#i(e){let t=[];for(let[n,r]of e)if(r===0)t.push(this.#a(n));else{let e=ca(n);t.push(this.e.put(e,r))}await Promise.all(t)}async#a(e){await Promise.all([this.e.del(oa(e)),this.e.del(sa(e)),this.e.del(ca(e))]),this.#t.delete(e)}release(){this.e.release()}},F=`main`;function pa(e){return Ia(e.meta)}function ma(e){return Fa(e.meta)}function ha(e){return ma(e)||pa(e)}function ga(e){return Ha(e.meta)}function _a(e){return Ua(e.meta)}function va(e){return ga(e)||_a(e)}var ya=class{chunk;constructor(e){this.chunk=e}get meta(){return this.chunk.data.meta}get valueHash(){return this.chunk.data.valueHash}getMutationID(e,t){return ba(e,t,this.meta)}async getNextMutationID(e,t){return await this.getMutationID(e,t)+1}get indexes(){return this.chunk.data.indexes}};async function ba(e,t,n){switch(n.type){case 1:return n.lastMutationID;case 3:return n.lastMutationID;case 5:return n.lastMutationIDs[e]??0;case 2:return n.mutationID;case 4:{if(n.clientID===e)return n.mutationID;let{basisHash:r}=n;return ba(e,t,(await I(r,t)).meta)}default:Sr(n)}}async function xa(e,t){return(await Aa(e,t)).filter(e=>ha(e))}async function Sa(e,t){return(await Aa(e,t)).filter(e=>ma(e))}async function Ca(e,t,n){let r=[],i=new Map(Object.entries(t));for(;!va(e)&&i.size>0;){if(ma(e)){let{meta:t}=e,n=i.get(t.clientID);n!==void 0&&(t.mutationID<=n?i.delete(t.clientID):r.push(e))}let{basisHash:t}=e.meta;if(t===null)throw Error(`Commit ${e.chunk.hash} has no basis`);e=await I(t,n)}return r}async function wa(e,t){let n=await t.getHead(e);return k(n,`Missing head ${e}`),Ea(n,t)}async function Ta(e,t){return(await Ea(e,t)).chunk.hash}async function Ea(e,t){return Da(await I(e,t),t)}async function Da(e,t){for(;!va(e);){let{meta:n}=e;if(Fa(n))e=await I(n.baseSnapshotHash,t);else{let{basisHash:r}=n;if(r===null)throw Error(`Commit ${e.chunk.hash} has no basis`);e=await I(r,t)}}return e}function Oa(e,t){let n=e.meta;return Ha(n)?[n.lastMutationIDs[t]??0,n.cookieJSON]:[n.lastMutationID,n.cookieJSON]}function ka(e,t){return ni(e.meta.cookieJSON,t.meta.cookieJSON)}async function Aa(e,t){let n=await I(e,t),r=[];for(;!va(n);){let{meta:e}=n,{basisHash:i}=e;if(i===null)throw Error(`Commit ${n.chunk.hash} has no basis`);r.push(n),n=await I(i,t)}return r.push(n),r}async function I(e,t){return ro(await t.mustGetChunk(e))}async function ja(e,t){return I(await ta(e,t),t)}function Ma(e){j(e.lastMutationID)}function Na(e){if(j(e.mutationID),A(e.mutatorName),!e.mutatorName)throw Error(`Missing mutator name`);qr(e.mutatorArgsJSON),e.originalHash!==null&&Yi(e.originalHash),j(e.timestamp)}function Pa(e){A(e.clientID),Na(e)}function Fa(e){return e.type===4}function Ia(e){return e.type===2}function La(e){e.basisHash!==null&&Yi(e.basisHash),qr(e.cookieJSON)}function Ra(e){La(e),j(e.lastMutationID)}function za(e){La(e),Ba(e.lastMutationIDs)}function Ba(e){M(e);for(let t of Object.values(e))j(t)}function Va(e){za(e.meta)}function Ha(e){return e.type===5}function Ua(e){return e.type===3}function Wa(e){switch(M(e),Si(e),e.basisHash!==null&&A(e.basisHash),j(e.type),e.type){case 1:Ma(e);break;case 2:Na(e);break;case 4:Pa(e);break;case 3:Ra(e);break;case 5:za(e);break;default:throw Error(`Invalid enum value ${e.type}`)}}function Ga(e,t){return e.jsonPointer===t.jsonPointer&&(e.allowEmpty??!1)===(t.allowEmpty??!1)&&e.keyPrefix===t.keyPrefix}function Ka(e){M(e),Si(e),A(e.name),A(e.keyPrefix),A(e.jsonPointer),e.allowEmpty!==void 0&&hr(e.allowEmpty)}function qa(e,t){return{name:e,keyPrefix:t.prefix??``,jsonPointer:t.jsonPointer,allowEmpty:t.allowEmpty??!1}}function Ja(e){M(e),Si(e),Ka(e.definition),A(e.valueHash)}function Ya(e){_r(e),Si(e);for(let t of e)Ja(t)}function Xa(e,t,n,r,i,a,o,s,c){return io(e,oo({type:2,basisHash:t,mutationID:n,mutatorName:r,mutatorArgsJSON:i,originalHash:a,timestamp:c},o,s))}function Za(e,t,n,r,i,a,o,s,c,l,u){return io(e,oo({type:4,basisHash:t,baseSnapshotHash:n,mutationID:r,mutatorName:i,mutatorArgsJSON:a,originalHash:o,timestamp:l,clientID:u},s,c))}function Qa(e,t,n,r,i,a){return io(e,eo(t,n,r,i,a))}function $a(e,t,n,r,i,a){return io(e,to(t,n,r,i,a))}function eo(e,t,n,r,i){return oo({type:3,basisHash:e,lastMutationID:t,cookieJSON:n},r,i)}function to(e,t,n,r,i){return oo({type:5,basisHash:e,lastMutationIDs:t,cookieJSON:n},r,i)}function no(e,t,n,r,i){return io(e,oo({type:1,basisHash:t,lastMutationID:n},r,i))}function ro(e){return co(e),new ya(e)}function io(e,t){return new ya(e(t,ao(t)))}function ao(e){let t=new Set;t.add(e.valueHash);let{meta:n}=e;switch(n.type){case 1:n.basisHash&&t.add(n.basisHash);break;case 2:case 4:n.basisHash&&t.add(n.basisHash);break;case 3:case 5:break;default:Sr(n)}for(let n of e.indexes)t.add(n.valueHash);return Ti(t)}function oo(e,t,n){return vi({meta:e,valueHash:t,indexes:n})}function so(e){Ur||(M(e),Si(e),Wa(e.meta),A(e.valueHash),Ya(e.indexes))}function co(e){let{data:t}=e;so(t);let n=new Set;for(let e of t.indexes){let{name:t}=e.definition;if(n.has(t))throw Error(`Duplicate index ${t}`);n.add(t)}}function lo(e,t){let n=e.length,r=t.length,i=Math.min(n,r);for(let n=0;n<i;){let r=e.codePointAt(n),i=t.codePointAt(n);if(r!==i)return r<128&&i<128?r-i:uo(mo,go(r,mo),ho,go(i,ho));n+=fo(r)}return n-r}function uo(e,t,n,r){let i=Math.min(t,r);for(let t=0;t<i;t++){let r=e[t],i=n[t];if(r!==i)return r-i}return t-r}function fo(e){return e>65535?2:1}var po=()=>Array.from({length:4},()=>0),mo=po(),ho=po();function go(e,t){if(e<128)return t[0]=e,1;let n,r;if(e<=2047)n=1,r=192;else if(e<=65535)n=2,r=224;else if(e<=1114111)n=3,r=240;else throw Error(`Invalid code point`);t[0]=(e>>6*n)+r;let i=1;for(;n>0;n--){let r=e>>6*(n-1);t[i++]=128|r&63}return i}function _o(e,t){return lo(e,t)>0}function vo(e,t){return lo(e,t)<0}function yo(e,t){return lo(e,t)<=0}function bo(e,t){let n=0;for(;n<e;){let r=n+(e-n>>1),i=t(r);if(i===0)return r;i>0?n=r+1:e=r}return n}function xo(e){if(e!==(e|0)||e<4||e>7)throw Error(`Unsupported format version: ${e}`);return e}var So=0,Co=1;function wo(e,t,n){return vi([e,n>=7?t:t.map(e=>e.slice(0,2))])}async function To(e,t,n,r){let i=await n.getNode(t);if(r!==n.rootHash)return To(e,n.rootHash,n,n.rootHash);if(Lo(i))return i;let{entries:a}=i,o=Eo(e,a);o===a.length&&o--;let s=a[o];return To(e,s[1],n,r)}function Eo(e,t){return bo(t.length,n=>lo(e,t[n][0]))}function Do(e,t,n){return e!==t.length&&t[e][0]===n}function Oo(e,t,n){if(Ur&&t>=7)return e;_r(e),Si(e),k(e.length>=2);let[r,i]=e;j(r),_r(i);let a=r>0?A:qr;if(t>=7){for(let e of i)ko(e,a);return e}return[r,i.map(e=>Ao(e,a,n))]}function ko(e,t){_r(e),k(e.length>=3),A(e[0]),t(e[1]),j(e[2])}function Ao(e,t,n){_r(e),k(e.length>=2),A(e[0]),t(e[1]);let r=n(e[0],e[1]);return[e[0],e[1],r]}var jo=class{entries;hash;isMutable;#e=-1;constructor(e,t,n){this.entries=e,this.hash=t,this.isMutable=n}maxKey(){return this.entries[this.entries.length-1][0]}getChildNodeSize(e){if(this.#e!==-1)return this.#e;let t=e.chunkHeaderSize;for(let e of this.entries)t+=e[2];return this.#e=t}c(e){this.#e=-1,e.updateNode(this)}};function Mo(e,t){return wo(e.level,e.entries,t)}var No=class extends jo{level=0;set(e,t,n,r){let i,a=Eo(e,this.entries);return i=+!!Do(a,this.entries,e),Promise.resolve(this.#e(r,a,i,[e,t,n]))}#e(e,t,n,...r){if(this.isMutable)return this.entries.splice(t,n,...r),this.c(e),this;let i=Po(this.entries,t,n,...r);return e.newDataNodeImpl(i)}del(e,t){let n=Eo(e,this.entries);return Do(n,this.entries,e)?Promise.resolve(this.#e(t,n,1)):Promise.resolve(this)}async*keys(e){for(let e of this.entries)yield e[0]}async*entriesIter(e){for(let e of this.entries)yield e}};function Po(e,t,n,...r){let i=e.slice(0,t);for(let e=0;e<r.length;e++)i.push(r[e]);for(let r=t+n;r<e.length;r++)i.push(e[r]);return i}var Fo=class e extends jo{level;constructor(e,t,n,r){super(e,t,r),this.level=n}async set(e,t,n,r){let i=Eo(e,this.entries);i===this.entries.length&&i--;let a=this.entries[i][1],o=await(await r.getNode(a)).set(e,t,n,r),s=o.getChildNodeSize(r);if(s>r.maxSize||s<r.minSize)return this.#e(r,i,o);let c=Vo(o,r.getEntrySize);return this.#t(r,i,c)}async#e(e,t,n){let r=this.level-1,i=this.entries,a,o,s;if(t>0){let r=i[t-1][1];a=ai((await e.getNode(r)).entries,n.entries),o=t-1,s=2}else if(t<i.length-1){let r=i[t+1][1],c=await e.getNode(r);a=ai(n.entries,c.entries),o=t,s=2}else a=n.entries,o=t,s=1;let c=Ro(a,e=>e[2],e.minSize-e.chunkHeaderSize,e.maxSize-e.chunkHeaderSize),l=[];for(let t of c){let n=Vo(e.newNodeImpl(t,r),e.getEntrySize);l.push(n)}if(this.isMutable)return this.entries.splice(o,s,...l),this.c(e),this;let u=Po(i,o,s,...l);return e.newInternalNodeImpl(u,this.level)}#t(e,t,n){if(this.isMutable)return this.entries.splice(t,1,n),this.c(e),this;let r=Po(this.entries,t,1,n);return e.newInternalNodeImpl(r,this.level)}async del(e,t){let n=Eo(e,this.entries);if(n===this.entries.length)return this;let r=this.entries[n][1],i=await t.getNode(r),a=i.hash,o=await i.del(e,t);if(o.hash===a)return this;if(o.entries.length===0){let e=Po(this.entries,n,1);return t.newInternalNodeImpl(e,this.level)}if(n===0&&this.entries.length===1)return o;if(o.getChildNodeSize(t)>t.minSize){let e=Vo(o,t.getEntrySize);return this.#t(t,n,e)}return this.#e(t,n,o)}async*keys(e){for(let t of this.entries)yield*(await e.getNode(t[1])).keys(e)}async*entriesIter(e){for(let t of this.entries)yield*(await e.getNode(t[1])).entriesIter(e)}getChildren(e,t,n){let r=[];for(let i=e;i<t&&i<this.entries.length;i++)r.push(n.getNode(this.entries[i][1]));return Promise.all(r)}async getCompositeChildren(t,n,r){let{level:i}=this;if(n===0)return new e([],Gi(),i-1,!0);let a=await this.getChildren(t,t+n,r);if(i>1){let t=[];for(let e of a)t.push(...e.entries);return new e(t,Gi(),i-1,!0)}k(i===1);let o=[];for(let e of a)o.push(...e.entries);return new No(o,Gi(),!0)}};function Io(e,t,n,r){return n===0?new No(e,t,r):new Fo(e,t,n,r)}function Lo(e){return e.level===0}function Ro(e,t,n,r){let i=[],a=[],o=0,s=[];for(let c of e){let e=t(c);e>=r?(s.length>0&&(i.push(s),a.push(o)),i.push([c]),a.push(e),o=0,s=[]):o+e>=n?(s.push(c),i.push(s),a.push(o+e),o=0,s=[]):(o+=e,s.push(c))}return o>0&&(a.length>0&&o+a[a.length-1]<=r?i[i.length-1].push(...s):i.push(s)),i}var zo=wo(0,[],7),Bo=new No([],P,!1);function Vo(e,t){let n=e.maxKey(),r=e.hash;return[n,r,t(n,r)]}var Ho=-1,Uo=0,Wo=1,Go=2,Ko=3,qo=0,Jo=1;function*Yo(e,t){let n=0,r=0,i;function a(e,t){e[Ko]===Ho&&(e[Ko]=t)}function o(){return[n,0,0,Ho]}for(;n<e.length&&r<t.length;)e[n][qo]===t[r][qo]?(Kr(e[n][Jo],t[r][Jo])?i&&=(a(i,0),yield i,void 0):(i||=o(),i[Go]++,i[Wo]++,a(i,r)),n++,r++):e[n][qo]<t[r][qo]?(i||=o(),i[Wo]++,n++):(i||=o(),i[Go]++,a(i,r),r++);r<t.length&&(i||=o(),i[Go]+=t.length-r,a(i,r)),n<e.length&&(i||=o(),i[Wo]+=e.length-n),i&&(a(i,0),yield i)}var Xo=11,Zo=class{p=new Map;l;u;rootHash;getEntrySize;chunkHeaderSize;constructor(e,t,n=P,r=gi,i=Xo){this.l=e,this.u=t,this.rootHash=n,this.getEntrySize=r,this.chunkHeaderSize=i}async getNode(e){if(e===P)return Bo;let t=this.p.get(e);if(t)return t;let n=Oo((await this.l.mustGetChunk(e)).data,this.u,this.getEntrySize),r=Io(n[Co],e,n[So],!1);return this.p.set(e,r),r}async get(e){let t=await To(e,this.rootHash,this,this.rootHash),n=Eo(e,t.entries);if(Do(n,t.entries,e))return t.entries[n][1]}async has(e){let t=await To(e,this.rootHash,this,this.rootHash);return Do(Eo(e,t.entries),t.entries,e)}async isEmpty(){let{rootHash:e}=this,t=await this.getNode(this.rootHash);return this.rootHash===e?t.entries.length===0:this.isEmpty()}scan(e){return es(this.rootHash,()=>this.rootHash,this.rootHash,e,async e=>{let t=await this.getNode(e);return t?[t.level,t.isMutable?t.entries.slice():t.entries]:Oo((await this.l.mustGetChunk(e)).data,this.u,this.getEntrySize)})}async*keys(){yield*(await this.getNode(this.rootHash)).keys(this)}async*entries(){yield*(await this.getNode(this.rootHash)).entriesIter(this)}[Symbol.asyncIterator](){return this.entries()}async*diff(e){let[t,n]=await Promise.all([this.getNode(this.rootHash),e.getNode(e.rootHash)]);yield*Qo(n,t,e,this)}};async function*Qo(e,t,n,r){if(e.level>t.level){yield*Qo(await e.getCompositeChildren(0,e.entries.length,n),t,n,r);return}if(t.level>e.level){yield*Qo(e,await t.getCompositeChildren(0,t.entries.length,r),n,r);return}if(Lo(e)&&Lo(t)){yield*$o(e.entries,t.entries);return}let i=Yo(e.entries,t.entries);for(let a of i){let[i,o]=await Promise.all([e.getCompositeChildren(a[Uo],a[Wo],n),t.getCompositeChildren(a[Ko],a[Go],r)]);yield*Qo(i,o,n,r)}}function*$o(e,t){let n=e.length,r=t.length,i=0,a=0;for(;i<n&&a<r;){let n=e[i][0],r=t[a][0];n===r?(Kr(e[i][1],t[a][1])||(yield{op:`change`,key:n,oldValue:e[i][1],newValue:t[a][1]}),i++,a++):n<r?(yield{op:`del`,key:n,oldValue:e[i][1]},i++):(yield{op:`add`,key:r,newValue:t[a][1]},a++)}for(;i<n;i++)yield{op:`del`,key:e[i][0],oldValue:e[i][1]};for(;a<r;a++)yield{op:`add`,key:t[a][0],newValue:t[a][1]}}async function*es(e,t,n,r,i){if(n===P)return;let a=await i(n),o=a[Co],s=0;if(r&&(s=Eo(r,o)),a[So]>0)for(;s<o.length;s++)yield*es(e,t,o[s][1],r,i),r=``;else for(;s<o.length;s++){let n=t();if(e!==n){yield*es(n,t,n,o[s][0],i);return}yield o[s]}}async function ts(e,t){let n=[],r=t===`add`?e=>({op:`add`,key:e[0],newValue:e[1]}):e=>({op:`del`,key:e[0],oldValue:e[1]});for await(let t of e.entries())n.push(r(t));return n}var ns=class{meta;map;constructor(e,t){this.meta=e,this.map=t}},rs=class extends ns{flush(){return this.map.flush()}clear(){return this.map.clear()}};async function is(e,t,n,r,i,a,o){try{for(let e of as(r,i,a,o))switch(n){case 0:await t.put(e,i);break;case 1:await t.del(e);break}}catch(t){e.info?.(`Not indexing value`,i,`:`,t)}}function as(e,t,n,r){let i=ds(t,n);if(i===void 0){if(r)return[];throw Error(`No value at path: ${n}`)}let a=Array.isArray(i)?i:[i],o=[];for(let t of a)if(typeof t==`string`)o.push(cs([t,e]));else throw Error(`Unsupported target type`);return o}var os=`\0`,ss=`\0`;function cs(e){let t=e[0],n=e[1];if(t.includes(`\0`))throw Error(`Secondary key cannot contain null byte`);return os+t+ss+n}function ls(e,t){let n=cs([e,t||``]);return t===void 0?n.slice(0,n.length-1):n}function us(e){if(e[0]!==os)throw Error(`Invalid version`);let t=os.length,n=ss.length,r=e.indexOf(ss,t);if(r===-1)throw Error(`Invalid formatting`);return[e.slice(t,r),e.slice(r+n)]}function ds(e,t){function n(e){if(!(e.startsWith(`+`)||e.startsWith(`0`)&&e.length!==1))return parseInt(e,10)}if(t===``)return e;if(!t.startsWith(`/`))throw Error(`Invalid JSON pointer: ${t}`);let r=t.split(`/`).slice(1).map(e=>e.replace(/~1/g,`/`).replace(/~0/g,`~`)),i=e;for(let e of r){let t;if(Array.isArray(i)){let r=n(e);if(r===void 0)return;t=i[r]}else{if(i===null)return;typeof i==`object`&&(i=i,t=i[e])}if(t===void 0)return;i=t}return i}var fs=class{#e;map;indexes;constructor(e,t,n){this.#e=e,this.map=t,this.indexes=n}has(e){return this.map.has(e)}get(e){return this.map.get(e)}isEmpty(){return this.map.isEmpty()}getMapForIndex(e){let t=this.indexes.get(e);if(t===void 0)throw Error(`Unknown index name: ${e}`);return t.map}get closed(){return this.#e.closed}close(){this.#e.release()}};function ps(e,t){return ms(F,e,t)}async function ms(e,t,n){return hs(await ja(e,t),t,n)}function hs(e,t,n){let r=gs(e,t,n);return new fs(t,new Zo(t,n,e.valueHash),r)}function gs(e,t,n){let r=new Map;for(let i of e.indexes)r.set(i.definition.name,new ns(i,new Zo(t,n,i.valueHash)));return r}async function _s(e){let t=[];for await(let n of e)t.push(n);return t}function vs(e){return e.indexName!==void 0}function ys(e){return typeof e==`string`?[e]:e}function bs(e){if(!e)return{};let t,n,r,i;return e.start&&({key:t,exclusive:n}=e.start,e.indexName?typeof t==`string`?i=t:(i=t[0],r=t[1]):r=t),{prefix:e.prefix,startSecondaryKey:i,startKey:r,startExclusive:n,limit:e.limit,indexName:e.indexName}}var xs=class extends Error{constructor(){super(`Transaction is closed`)}};function Ss(e){if(e.closed)throw new xs}function Cs(e){return e.closed?Promise.reject(new xs):void 0}var ws=class{#e;#t;#n;#r;constructor(e,t,n,r){this.#e=e,this.#t=t,this.#n=n,this.#r=r}[Symbol.asyncIterator](){return this.values()}values(){return new Ts(this.#i(e=>e[1]))}keys(){return new Ts(this.#i(e=>e[0]))}entries(){return new Ts(this.#i(e=>[e[0],e[1]]))}toArray(){return this.values().toArray()}#i(e){return Es(e,this.#e,this.#t,this.#n,this.#r)}},Ts=class{#e;constructor(e){this.#e=e}next(){return this.#e.next()}[Symbol.asyncIterator](){return this.#e[Symbol.asyncIterator]()}toArray(){return _s(this.#e)}};async function*Es(e,t,n,r,i){Ss(r);let{limit:a=1/0}=n,{prefix:o=``}=n,s=n.start?.exclusive,c=vs(n);for await(let r of t){let t=r[0];if(!(c?t[0]:t).startsWith(o))return;if(s){if(s=!0,c){if(Ds(t,n.start.key))continue}else if(Os(t,n.start.key))continue}if(yield e(r),--a===0){c||i(t);return}}}function Ds(e,t){let[n,r]=ys(t),[i,a]=ys(e);return i===n?r===void 0||a===r:!1}function Os(e,t){return e===t}function ks(e){let{prefix:t,start:n}=e,r=``;if(t!==void 0&&(r=ls(t,void 0)),!n)return r;let{key:i}=n,[a,o]=ys(i),s=ls(a,o);return _o(s,r)?s:r}var As=0,js=class{clientID;dbtx;d;location;environment;constructor(e,t,n,r=`openReadTransaction`){this.clientID=e,this.dbtx=t,this.d=n.withContext(r).withContext(`txid`,As++),this.environment=`client`,this.location=`client`}get(e){return Cs(this.dbtx)||this.dbtx.get(e)}async has(e){return Ss(this.dbtx),this.dbtx.has(e)}async isEmpty(){return Ss(this.dbtx),this.dbtx.isEmpty()}scan(e){return Ns(e,this.dbtx,Ms)}};function Ms(e){}function Ns(e,t,n){return Rs(Is(t,e),e??{},t,n)}var Ps=class{#e=new Set;#t=[];#n;constructor(e){this.#n=e}get environment(){return this.#n.location}get location(){return this.#n.location}get clientID(){return this.#n.clientID}isEmpty(){return this.#t.push({options:{}}),this.#n.isEmpty()}get(e){return this.#e.add(e),this.#n.get(e)}has(e){return this.#e.add(e),this.#n.has(e)}scan(e){let t={options:bs(e),inclusiveLimitKey:void 0};return this.#t.push(t),Ns(e,this.#n.dbtx,e=>{t.inclusiveLimitKey=e})}get keys(){return this.#e}get scans(){return this.#t}},Fs=class extends js{reason;mutationID;constructor(e,t,n,r,i,a=`openWriteTransaction`){super(e,r,i,a),this.mutationID=t,this.reason=n}put(e,t){return this.set(e,t)}async set(e,t){Ss(this.dbtx),await this.dbtx.put(this.d,e,vi(t))}del(e){return Cs(this.dbtx)??this.dbtx.del(this.d,e)}};function Is(e,t){return t&&vs(t)?zs(e,t):e.map.scan(Ls(t))}function Ls(e){if(!e)return``;let{prefix:t=``,start:n}=e;return n&&_o(n.key,t)?n.key:t}function Rs(e,t,n,r){return new ws(e,t,n,r)}async function*zs(e,t){let n=e.getMapForIndex(t.indexName);for await(let e of n.scan(ks(t)))yield[us(e[0]),e[1]]}function Bs(e,t){return _s(t.diff(e))}var Vs=class extends Zo{#e=new Yt;#t=new Map;minSize;maxSize;constructor(e,t,n=P,r=8192,i=16384,a=gi,o){super(e,t,n,a,o),this.minSize=r,this.maxSize=i}#n(e){k(e.isMutable),this.#t.set(e.hash,e),this.p.set(e.hash,e)}updateNode(e){k(e.isMutable),this.#t.delete(e.hash),e.hash=Gi(),this.#n(e)}newInternalNodeImpl(e,t){let n=new Fo(e,Gi(),t,!0);return this.#n(n),n}newDataNodeImpl(e){let t=new No(e,Gi(),!0);return this.#n(t),t}newNodeImpl(e,t){let n=Io(e,Gi(),t,!0);return this.#n(n),n}put(e,t){return this.#e.withLock(async()=>{let n=await this.getNode(this.rootHash),r=this.getEntrySize(e,t),i=await n.set(e,t,r,this);if(i.getChildNodeSize(this)>this.maxSize){let e=this.chunkHeaderSize,t=Ro(i.entries,e=>e[2],this.minSize-e,this.maxSize-e),{level:n}=i,r=t.map(e=>Vo(this.newNodeImpl(e,n),this.getEntrySize)),a=this.newInternalNodeImpl(r,n+1);this.rootHash=a.hash;return}this.rootHash=i.hash})}del(e){return this.#e.withLock(async()=>{let t=await(await this.getNode(this.rootHash)).del(e,this),n=this.rootHash!==t.hash;return n&&(this.rootHash=t.level>0&&t.entries.length===1?t.entries[0][1]:t.hash),n})}clear(){return this.#e.withLock(()=>{this.#t.clear(),this.rootHash=P})}flush(){return this.#e.withLock(async()=>{let e=this.l;if(this.rootHash===P){let t=e.createChunk(zo,[]);return await e.putChunk(t),t.hash}let t=[],n=Hs(this.rootHash,t,e.createChunk,this.#t,this.u);return await Promise.all(t.map(t=>e.putChunk(t))),this.#t.clear(),this.rootHash=n,n})}};function Hs(e,t,n,r,i){let a=r.get(e);if(a===void 0)return e;if(Lo(a)){let e=n(Mo(a,i),[]);return t.push(e),e.hash}let o=[],{entries:s}=a;for(let e=0;e<s.length;e++){let a=s[e],c=a[1],l=Hs(c,t,n,r,i);l!==c&&(s[e]=[a[0],l,a[2]]),o.push(l)}let c=n(Mo(a,i),Ti(o));return t.push(c),c.hash}function Us(e){let t;return()=>(t===void 0&&(t=e()),t)}var Ws=class extends Map{set(e,t){return t.length===0?this:super.set(e,t)}};async function Gs(e,t,n,r,i){let a=new Ws;if(!r.shouldComputeDiffs())return a;let o=await Bs(new Zo(n,i,e.valueHash),new Zo(n,i,t.valueHash));return a.set(``,o),await Ks(e,t,n,a,r,i),a}async function Ks(e,t,n,r,i,a){let o=gs(e,n,a),s=gs(t,n,a);for(let[e,t]of o){if(!i.shouldComputeDiffsForIndex(e))continue;let n=s.get(e);if(n!==void 0){k(n!==t);let i=await Bs(t.map,n.map);s.delete(e),r.set(e,i)}else{let n=await ts(t.map,`del`);r.set(e,n)}}for(let[e,t]of s){if(!i.shouldComputeDiffsForIndex(e))continue;let n=await ts(t.map,`add`);r.set(e,n)}}var qs=class extends fs{#e;#t;#n;#r;#i;constructor(e,t,n,r,i,a,o){super(e,t,i),this.#e=e,this.#t=n,this.#n=r,this.#r=a,this.#i=o,k(n===void 0?r.basisHash===P:r.basisHash===n.chunk.hash)}async put(e,t,n){if(this.#n.type===1)throw Error(`Not allowed`);let r=Us(()=>this.map.get(t));await Zs(e,this.indexes,t,r,n),await this.map.put(t,n)}getMutationID(){return ba(this.#r,this.#e,this.#n)}async del(e,t){if(this.#n.type===1)throw Error(`Not allowed`);let n=Us(()=>this.map.get(t));return n!==void 0&&await Zs(e,this.indexes,t,n,void 0),this.map.del(t)}async clear(){if(this.#n.type===1)throw Error(`Not allowed`);await this.map.clear();let e=[];for(let t of this.indexes.values())e.push(t.clear());await Promise.all(e)}async putCommit(){let e=await this.map.flush(),t=[];for(let e of this.indexes.values()){let n=await e.flush(),r={definition:e.meta.definition,valueHash:n};t.push(r)}let n,r=this.#n;switch(r.type){case 2:{let{basisHash:i,mutationID:a,mutatorName:o,mutatorArgsJSON:s,originalHash:c,timestamp:l}=r;n=Xa(this.#e.createChunk,i,a,o,s,c,e,t,l);break}case 4:{k(this.#i>=5);let{basisHash:i,mutationID:a,mutatorName:o,mutatorArgsJSON:s,originalHash:c,timestamp:l}=r;n=Za(this.#e.createChunk,i,await Ta(i,this.#e),a,o,s,c,e,t,l,this.#r);break}case 3:{k(this.#i<=4);let{basisHash:i,lastMutationID:a,cookieJSON:o}=r;n=Qa(this.#e.createChunk,i,a,o,e,t);break}case 5:{k(this.#i>5);let{basisHash:i,lastMutationIDs:a,cookieJSON:o}=r;n=$a(this.#e.createChunk,i,a,o,e,t);break}case 1:{let{basisHash:i,lastMutationID:a}=r;if(this.#t!==void 0){if(await this.#t.getMutationID(this.#r,this.#e)!==a)throw Error(`Index change must not change mutationID`);if(this.#t.valueHash!==e)throw Error(`Index change must not change valueHash`)}n=no(this.#e.createChunk,i,a,e,t);break}}return await this.#e.putChunk(n.chunk),n}async commit(e){let t=(await this.putCommit()).chunk.hash;return await this.#e.setHead(e,t),await this.#e.commit(),t}async commitWithDiffs(e,t){let n=this.putCommit(),r=await this.#a(t),i=(await n).chunk.hash;return await this.#e.setHead(e,i),await this.#e.commit(),r}async#a(e){let t=new Ws;if(!e.shouldComputeDiffs())return t;let n=[];this.#t&&(n=await Bs(new Zo(this.#e,this.#i,this.#t.valueHash),this.map)),t.set(``,n);let r;r=this.#t?gs(this.#t,this.#e,this.#i):new Map;for(let[n,i]of this.indexes){if(!e.shouldComputeDiffsForIndex(n))continue;let a=r.get(n);k(i!==a);let o=await(a?Bs(a.map,i.map):ts(i.map,`add`));t.set(n,o)}for(let[n,i]of r)if(!this.indexes.has(n)&&e.shouldComputeDiffsForIndex(n)){let e=await ts(i.map,`del`);t.set(n,e)}return t}close(){this.#e.release()}};async function Js(e,t,n,r,i,a,o,s){let c=await I(e,i),l=new Vs(i,s,c.valueHash),u=await c.getNextMutationID(o,i),d=Qs(c,i,s);return new qs(i,l,c,s>=5?{type:4,basisHash:e,baseSnapshotHash:await Ta(e,i),mutatorName:t,mutatorArgsJSON:n,mutationID:u,originalHash:r,timestamp:a,clientID:o}:{type:2,basisHash:e,mutatorName:t,mutatorArgsJSON:n,mutationID:u,originalHash:r,timestamp:a},d,o,s)}async function Ys(e,t,n,r,i,a,o){k(o<=4);let s=await I(e,r);return new qs(r,new Vs(r,o,s.valueHash),s,{basisHash:e,type:3,lastMutationID:t,cookieJSON:n},i,a,o)}async function Xs(e,t,n,r,i,a){let o=await I(e,r);return new qs(r,new Vs(r,a,o.valueHash),o,{basisHash:e,type:5,lastMutationIDs:t,cookieJSON:n},Qs(o,r,a),i,a)}async function Zs(e,t,n,r,i){let a=[];for(let o of t.values()){let{keyPrefix:t}=o.meta.definition;if(!t||n.startsWith(t)){let t=await r();t!==void 0&&a.push(is(e,o.map,1,n,t,o.meta.definition.jsonPointer,o.meta.definition.allowEmpty??!1)),i!==void 0&&a.push(is(e,o.map,0,n,i,o.meta.definition.jsonPointer,o.meta.definition.allowEmpty??!1))}}await Promise.all(a)}function Qs(e,t,n){let r=new Map;for(let i of e.indexes)r.set(i.definition.name,new rs(i,new Vs(t,n,i.valueHash)));return r}async function $s(e,t,n,r,i,a,o){let s=new Vs(t,o);for await(let t of n.scan(r)){let n=t[0];if(!n.startsWith(r))break;await is(e,s,0,n,t[1],i,a)}return s}async function ec(e,t,n,r,i,a,o){let s=e.meta,c=s.mutatorName;Fa(s)&&k(s.clientID===a,`mutationClientID must match clientID of LocalMeta`);let l=r[c];l||i.error?.(`Cannot rebase unknown mutator ${c}`);let u=l||(async()=>{}),d=s.mutatorArgsJSON,f=await(await I(n,t)).getNextMutationID(a,t);if(f!==s.mutationID)throw Error(`Inconsistent mutation ID: original: ${s.mutationID}, next: ${f} - mutationClientID: ${a} mutatorName: ${c}`);o>=5&&Pa(s);let p=await Js(n,c,d,e.chunk.hash,t,s.timestamp,a,o);return await u(new Fs(a,await p.getMutationID(),`rebase`,p,i),d),p}async function tc(e,t,n,r,i,a,o){return(await ec(e,t,n,r,i,a,o)).putCommit()}async function nc(e,t,n,r,i,a,o,s){return(await ec(e,t,n,i,a,o,s)).commit(r)}function rc(e,t){return typeof e==`object`&&!!e&&e.error===t}function ic(e){return typeof e.error==`string`}function ac(e){return rc(e,`ClientStateNotFound`)}function oc(e){if(!rc(e,`VersionNotSupported`))return!1;let{versionType:t}=e;switch(t){case void 0:case`pull`:case`push`:case`schema`:return!0}return!1}function sc(e){k(oc(e))}async function cc(e,t,n,r){let i={headers:{"Content-type":`application/json`,Authorization:t,"X-Replicache-RequestID":n},body:JSON.stringify(r),method:`POST`},a=new Request(e,i),o=await fetch(a),s=o.status;return s===200?[o,{httpStatusCode:s,errorMessage:``}]:[void 0,{httpStatusCode:s,errorMessage:await o.text()}]}function lc(e){M(e),j(e.httpStatusCode),A(e.errorMessage)}function uc(e){_r(e);for(let t of e)dc(t)}function dc(e){switch(M(e),e.op){case`put`:A(e.key),qr(e.value);break;case`update`:if(A(e.key),e.merge!==void 0&&Jr(e.merge),e.constrain!==void 0){_r(e.constrain);for(let t of e.constrain)A(t)}break;case`del`:A(e.key);break;case`clear`:break;default:throw Error(`unknown patch op \`${e.op}\`, expected one of \`put\`, \`del\`, \`clear\``)}}function fc(e){async function t(t,n){let[r,i]=await cc(e.pullURL,e.auth,n,t);return r?{response:await r.json(),httpRequestInfo:i}:{httpRequestInfo:i}}return pc.add(t),t}var pc=new WeakSet;function mc(e){return pc.has(e)}function hc(e){if(M(e),ac(e)||oc(e))return;let t=e;t.cookie!==void 0&&qr(t.cookie),j(t.lastMutationID),uc(t.patch)}function gc(e){if(M(e),ac(e)||oc(e))return;let t=e;t.cookie!==void 0&&ii(t.cookie),_c(t.lastMutationIDChanges),uc(t.patch)}function _c(e){M(e);for(let[t,n]of Object.entries(e))A(t),j(n)}function vc(e){M(e),lc(e.httpRequestInfo),e.response!==void 0&&gc(e.response)}function yc(e){M(e),lc(e.httpRequestInfo),e.response!==void 0&&hc(e.response)}function bc(e){async function t(t,n){let[r,i]=await cc(e.pushURL,e.auth,n,t);if(!r)return{httpRequestInfo:i};let a={httpRequestInfo:i},o;try{o=await r.json()}catch{return a}return(ac(o)||oc(o))&&(a.response=o),a}return xc.add(t),t}var xc=new WeakSet;function Sc(e){return xc.has(e)}function Cc(e=`info`,t=[Wt],n){return new Gt(e,n,t.length===1?t[0]:new Ht(t))}var wc=Hi(Bi({prefix:N.string().optional(),jsonPointer:N.string(),allowEmpty:N.boolean().optional()}));function Tc(e,t){return e.jsonPointer===t.jsonPointer&&(e.allowEmpty??!1)===(t.allowEmpty??!1)&&(e.prefix??``)===(t.prefix??``)}function Ec(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let[n,r]of Object.entries(e)){let e=t[n];if(!e||!Tc(r,e))return!1}return!0}var Dc=Bi({headHash:Xi,mutatorNames:Vi(N.string()),indexes:wc,mutationIDs:Hi(N.number()),lastServerAckdMutationIDs:N.record(N.number()),disabled:N.boolean()}),Oc=`client-groups`;function kc(e){Li(e,Dc)}function Ac(e){M(e);let t=new Map;for(let[n,r]of Object.entries(e))r!==void 0&&(kc(r),t.set(n,r));return t}function jc(e,t){let n={};for(let[r,i]of e.entries())t.assertValidHash(i.headHash),n[r]={...i,mutatorNames:[...i.mutatorNames.values()]};return vi(n)}async function Mc(e,t){return Ac((await t.getChunk(e))?.data)}async function Nc(e){let t=await e.getHead(Oc);return t?Mc(t,e):new Map}async function Pc(e,t){let n=await Nc(t);for(let[t,r]of e)Ic(r,n.get(t));return Lc(e,t)}async function Fc(e,t,n){let r=await Nc(n);Ic(t,r.get(e));let i=new Map(r);return i.set(e,t),Lc(i,n)}function Ic(e,t){let n=new Set(e.mutatorNames);k(n.size===e.mutatorNames.length,`A client group's mutatorNames must be a set.`),t!==void 0&&(k(Ec(t.indexes,e.indexes),`A client group's index definitions must never change.`),k(Rc(n,t.mutatorNames),`A client group's mutatorNames must never change.`))}async function Lc(e,t){let n=jc(e,t),r=new Set;for(let t of e.values())r.add(t.headHash);let i=t.createChunk(n,Ti(r));return await t.putChunk(i),await t.setHead(Oc,i.hash),e}function Rc(e,t){if(t.length!==e.size)return!1;for(let n of t)if(!e.has(n))return!1;return!0}async function zc(e,t){return(await Nc(t)).get(e)}function Bc(e){for(let[t,n]of Object.entries(e.mutationIDs)){let r=e.lastServerAckdMutationIDs[t];if(r===void 0&&n!==0||r<n)return!0}return!1}async function Vc(e,t){let n=await zc(e,t);n&&await Fc(e,{...n,disabled:!0},t)}var Hc=N.string(),Uc=N.string();function L(e,t){return Gc(e.read(),t)}function Wc(e,t){return Gc(e.write(),t)}function R(e,t){return Gc(e.write(),async e=>{let n=await t(e);return await e.commit(),n})}async function Gc(e,t){let n=await e;try{return await t(n)}finally{n.release()}}function Kc(){let e=Ai(),t=Ai();return(e<<64n|t).toString(32).slice(-18).padStart(18,`0`)}var qc=Bi({heartbeatTimestampMs:N.number(),headHash:Xi,mutationID:N.number(),lastServerAckdMutationID:N.number()}),Jc=Bi({heartbeatTimestampMs:N.number(),headHash:Xi,tempRefreshHash:Xi.nullable(),clientGroupID:Hc}),Yc=Bi({heartbeatTimestampMs:N.number(),refreshHashes:Vi(Xi),persistHash:Xi.nullable(),clientGroupID:Hc});function Xc(e){return e.refreshHashes!==void 0}function Zc(e){return e.clientGroupID!==void 0}var Qc=`clients`,$c=N.union(qc,Jc,Yc);function el(e){Li(e,$c)}function tl(e){Li(e,qc)}function nl(e){Li(e,Yc)}function rl(e){M(e);let t=new Map;for(let n in e)if(Gr(e,n)){let r=e[n];r!==void 0&&(el(r),t.set(n,r))}return t}function il(e,t){for(let n of e.values())Xc(n)?(n.refreshHashes.forEach(t.assertValidHash),n.persistHash&&t.assertValidHash(n.persistHash)):(t.assertValidHash(n.headHash),Zc(n)&&n.tempRefreshHash&&t.assertValidHash(n.tempRefreshHash));return vi(Object.fromEntries(e))}async function al(e){return ol(await e.getHead(Qc),e)}async function ol(e,t){return e?rl((await t.getChunk(e))?.data):new Map}var sl=class extends Error{name=`ClientStateNotFoundError`;id;constructor(e){super(`Client state not found, id: ${e}`),this.id=e}};async function cl(e,t){if(!await ll(e,t))throw new sl(e)}async function ll(e,t){return!!await ul(e,t)}async function ul(e,t){return(await al(t)).get(e)}async function dl(e,t){let n=await ul(e,t);if(!n)throw new sl(e);return n}function fl(e,t,n,r,i,a,o){return Wc(n,async n=>{async function s(t,a,o,s){let l=to(t,{},a,o,s),u=n.createChunk(l,ao(l)),d=Kc(),f={heartbeatTimestampMs:Date.now(),refreshHashes:[u.hash],persistHash:null,clientGroupID:d},p=new Map(c).set(e,f),m={headHash:u.hash,mutatorNames:r,indexes:i,mutationIDs:{},lastServerAckdMutationIDs:{},disabled:!1};return await Promise.all([n.putChunk(u),Sl(p,n),Fc(d,m,n)]),await n.commit(),[f,u.hash,p,!0]}let c=await al(n),l=await _l(n,r,i);if(l.type===gl){let{clientGroupID:t,headHash:r}=l,i={clientGroupID:t,refreshHashes:[r],heartbeatTimestampMs:Date.now(),persistHash:null},a=new Map(c).set(e,i);return await Sl(a,n),await n.commit(),[i,r,a,!1]}if(!o||l.type===ml){let e=n.createChunk(zo,[]);await n.putChunk(e);let t=[];for(let[n,r]of Object.entries(i)){let i=qa(n,r);t.push({definition:i,valueHash:e.hash})}return s(null,null,e.hash,t)}k(l.type===hl);let{snapshot:u}=l,d=[],{valueHash:f,indexes:p}=u,m=new Zo(n,a,f);for(let[e,r]of Object.entries(i)){let{prefix:i=``,jsonPointer:o,allowEmpty:s=!1}=r,c={name:e,keyPrefix:i,jsonPointer:o,allowEmpty:s},l=pl(p,c);if(l)d.push({definition:c,valueHash:l.valueHash});else{let e=await $s(t,n,m,i,o,s,a);d.push({definition:c,valueHash:await e.flush()})}}return s(u.meta.basisHash,u.meta.cookieJSON,u.valueHash,d)})}function pl(e,t){return e.find(e=>Ga(e.definition,t))}var ml=0,hl=1,gl=2;async function _l(e,t,n){let r,i,a=new Set(t),o=await Nc(e);for(let[t,s]of o){if(!s.disabled&&Rc(a,s.mutatorNames)&&Ec(n,s.indexes))return{type:gl,clientGroupID:t,headHash:s.headHash};let o=await Ea(s.headHash,e);Va(o);let{cookieJSON:c}=o.meta;(r===void 0||ni(c,r)>0)&&(r=c,i=o)}return i?{type:hl,snapshot:i}:{type:ml}}function vl(e){let t=new Set;for(let n of e.values())if(Xc(n)){for(let e of n.refreshHashes)t.add(e);n.persistHash&&t.add(n.persistHash)}else t.add(n.headHash),Zc(n)&&n.tempRefreshHash&&t.add(n.tempRefreshHash);return Ti(t)}async function yl(e,t){let n=await bl(e,t);if(n)return zc(n,t)}async function bl(e,t){let n=await ul(e,t);if(!(!n||!Zc(n)))return n.clientGroupID}async function xl(e,t,n){let r=await al(n);return Sl(new Map(r).set(e,t),n)}async function Sl(e,t){let n=il(e,t),r=t.createChunk(n,vl(e));return await t.putChunk(r),await t.setHead(Qc,r.hash),r.hash}var Cl=typeof navigator<`u`?navigator:void 0,wl=Symbol(),Tl=class{r=new Map;#e;constructor(e){this.#e=e}has(e){switch(this.r.get(e)){case void 0:return this.#e.has(e);case wl:return si;default:return oi}}async get(e){let t=this.r.get(e);switch(t){case wl:return;case void 0:return wi(await this.#e.get(e));default:return t}}put(e,t){return this.r.set(e,vi(t)),ci}del(e){return this.r.set(e,wl),ci}release(){this.#e.release()}get closed(){return this.#e.closed}},El={durability:`relaxed`},Dl=`chunks`,Ol=class{#e;#t=!1;#n=!1;constructor(e){this.#e=Pl(e)}read(){return this.#r(Ml)}write(){return this.#r(jl)}async close(){this.#n||(await this.#e).close(),this.#t=!0}get closed(){return this.#t}async#r(e){let t=async e=>{let{promise:t,resolve:n,reject:r}=D(),i=indexedDB.open(e);i.onupgradeneeded=()=>{let t=i.transaction;br(t),t.abort(),this.#n=!0,r(new Fl(`Replicache IndexedDB not found: ${e}`))},i.onsuccess=()=>n(i.result),i.onerror=()=>r(i.error);let a=await t;return a.onversionchange=()=>a.close(),a},n=await this.#e;try{return e(n)}catch(r){if(!this.#t&&r instanceof DOMException){if(r.name===`InvalidStateError`)return this.#e=t(n.name),e(await this.#e);if(r.name===`NotFoundError`)throw this.#n=!0,indexedDB.deleteDatabase(n.name),new Fl(`Replicache IndexedDB ${n.name} missing object store. Deleting db.`)}throw r}}},kl=class{#e;#t=!1;constructor(e){this.#e=e}has(e){return new Promise((t,n)=>{let r=Nl(this.#e).count(e);r.onsuccess=()=>t(r.result>0),r.onerror=()=>n(r.error)})}get(e){return new Promise((t,n)=>{let r=Nl(this.#e).get(e);r.onsuccess=()=>t(wi(r.result)),r.onerror=()=>n(r.error)})}release(){this.#t=!0}get closed(){return this.#t}},Al=class extends Tl{#e;#t=!1;constructor(e){super(new kl(e)),this.#e=e}commit(){return this.r.size===0?ci:new Promise((e,t)=>{let n=this.#e,r=Nl(n);for(let[e,t]of this.r)t===wl?r.delete(e):r.put(t,e);n.oncomplete=()=>e(),n.onerror=()=>t(n.error)})}release(){this.#t=!0}get closed(){return this.#t}};function jl(e){return new Al(e.transaction(Dl,`readwrite`,El))}function Ml(e){return new kl(e.transaction(Dl,`readonly`))}function Nl(e){return e.objectStore(Dl)}function Pl(e){return new Promise((t,n)=>{let r=indexedDB.open(e);r.onupgradeneeded=()=>{r.result.createObjectStore(Dl)},r.onsuccess=()=>{let e=r.result;e.onversionchange=()=>e.close(),t(e)},r.onerror=()=>n(r.error)})}var Fl=class extends Error{name=`IDBNotFoundError`},Il=class{#e;#t;#n=!1;constructor(e,t){this.#e=e,this.#t=t}release(){this.#t(),this.#n=!0}get closed(){return this.#n}has(e){return Promise.resolve(this.#e.has(e))}get(e){return Promise.resolve(this.#e.get(e))}},Ll=class extends Tl{#e;constructor(e,t){super(new Il(e,t)),this.#e=e}commit(){return this.r.forEach((e,t)=>{e===wl?this.#e.delete(t):this.#e.set(t,e)}),this.r.clear(),this.release(),ci}},Rl=new Map;function zl(e){return Rl.delete(e),ci}var Bl=class{#e;#t;#n=!1;constructor(e){let t=Rl.get(e),n,r;t?{lock:n,map:r}=t:(n=new Xt,r=new Map,Rl.set(e,{lock:n,map:r})),this.#t=n,this.#e=r}async read(){let e=await this.#t.read();return new Il(this.#e,e)}async write(){let e=await this.#t.write();return new Ll(this.#e,e)}close(){return this.#n=!0,ci}get closed(){return this.#n}},Vl=class{#e;#t;#n;constructor(e,t){this.#e=e,this.#t=t,this.#n=new Ol(t)}read(){return this.#r(e=>e.read())}write(){return this.#r(e=>e.write())}async#r(e){try{return await e(this.#n)}catch(t){if(Hl(t))return this.#n instanceof Ol&&(this.#e.info?.(`Switching to MemStore because of Firefox private browsing error`),this.#n=new Bl(this.#t)),e(this.#n);throw t}}close(){return this.#n.close()}get closed(){return this.#n.closed}};function Hl(e){return Ul()&&e instanceof DOMException&&e.name===`InvalidStateError`&&e.message===`A mutation operation was attempted on a database that did not allow mutations.`}function Ul(){return Cl?.userAgent.includes(`Firefox`)??!1}function Wl(e,t){return Ul()?new Vl(e,t):new Ol(t)}function Gl(e){if(!Ul())return Kl(e);try{return Kl(e)}catch(t){if(Hl(t))return zl(e)}return ci}function Kl(e){return new Promise((t,n)=>{let r=indexedDB.deleteDatabase(e);r.onsuccess=()=>t(),r.onerror=()=>n(r.error)})}var ql=e=>new bf(e),Jl=401;function Yl(e,t){return Xl(e,t,7)}function Xl(e,t,n){let r=`rep:${e}:${n}`;return t?`${r}:${t}`:r}var Zl=class{#e;constructor(e){this.#e=ql(e)}get pullURL(){return this.#e.pullURL}set pullURL(e){this.#e.pullURL=e}get pushURL(){return this.#e.pushURL}set pushURL(e){this.#e.pushURL=e}get auth(){return this.#e.auth}set auth(e){this.#e.auth=e}get name(){return this.#e.name}get idbName(){return Yl(this.name,this.schemaVersion)}get schemaVersion(){return this.#e.schemaVersion}get mutate(){return this.#e.mutate}get pullInterval(){return this.#e.pullInterval}set pullInterval(e){this.#e.pullInterval=e}get pushDelay(){return this.#e.pushDelay}set pushDelay(e){this.#e.pushDelay=e}get puller(){return this.#e.puller}set puller(e){this.#e.puller=e}get pusher(){return this.#e.pusher}set pusher(e){this.#e.pusher=e}get requestOptions(){return this.#e.requestOptions}get onSync(){return this.#e.onSync}set onSync(e){this.#e.onSync=e}get onClientStateNotFound(){return this.#e.onClientStateNotFound}set onClientStateNotFound(e){this.#e.onClientStateNotFound=e}get onUpdateNeeded(){return this.#e.onUpdateNeeded}set onUpdateNeeded(e){this.#e.onUpdateNeeded=e}get getAuth(){return this.#e.getAuth}set getAuth(e){this.#e.getAuth=e}get profileID(){return this.#e.profileID}get clientID(){return this.#e.clientID}get clientGroupID(){return this.#e.clientGroupID}get onOnlineChange(){return this.#e.onOnlineChange}set onOnlineChange(e){this.#e.onOnlineChange=e}get online(){return this.#e.online}get closed(){return this.#e.closed}close(){return this.#e.close()}push({now:e=!1}={}){return this.#e.push({now:e})}pull({now:e=!1}={}){return this.#e.pull({now:e})}poke(e){return this.#e.poke(e)}subscribe(e,t){return this.#e.subscribe(e,t)}experimentalWatch(e,t){return this.#e.experimentalWatch(e,t)}query(e){return this.#e.query(e)}experimentalPendingMutations(){return this.#e.experimentalPendingMutations()}},Ql=class extends Error{};function $l(e){return new Bl(e)}function eu(e,t){switch(t){case`idb`:case void 0:return{create:t=>Wl(e,t),drop:Gl};case`mem`:return{create:$l,drop:e=>zl(e)};default:return t}}function tu(e){return e instanceof Error?e:Error(String(e))}async function nu(e,t,n){for(let r of n)switch(r.op){case`put`:await t.put(e,r.key,vi(r.value));break;case`update`:{let n=await t.get(r.key),i=[],a=e=>{for(let[t,n]of Object.entries(e))(!r.constrain||r.constrain.length===0||r.constrain.indexOf(t)>-1)&&i.push([t,n])};n!==void 0&&(M(n),a(n)),r.merge&&a(r.merge),await t.put(e,r.key,vi(Object.fromEntries(i)));break}case`del`:await t.del(e,r.key);break;case`clear`:await t.clear();break}}var ru=class extends Error{name=`PullError`;causedBy;constructor(e){super(`Failed to pull`),this.causedBy=e}},iu=`sync`,au=0,ou=1;function su(e){return e.pullVersion===ou}async function cu(e,t,n,r,i,a,o,s,c=!0){let[l,u]=await L(a,async e=>{let n=await e.getHead(F);if(!n)throw Error(`Internal no main head found`);let r=await Ea(n,e),i=r.meta.cookieJSON;return[await r.getMutationID(t,e),i]}),{response:d,httpRequestInfo:f}=await uu(s,r,{profileID:e,clientID:t,cookie:u,lastMutationID:l,pullVersion:au,schemaVersion:n},i);if(!d)return{httpRequestInfo:f,syncHead:P};if(!c||ic(d))return{httpRequestInfo:f,pullResponse:d,syncHead:P};let p=await du(s,a,u,d,t,o);if(p.type===2)throw Error(`Overlapping sync`);return{httpRequestInfo:f,pullResponse:d,syncHead:p.type===0?p.syncHead:P}}async function lu(e,t,n,r,i,a,o,s,c,l=!0){let u=await L(o,async e=>{let t=await e.getHead(F);if(!t)throw Error(`Internal no main head found`);let n=(await Ea(t,e)).meta;return za(n),n.cookieJSON}),{response:d,httpRequestInfo:f}=await uu(c,i,{profileID:e,clientGroupID:n,cookie:u,pullVersion:ou,schemaVersion:r},a);if(!d)return{httpRequestInfo:f,syncHead:P};if(!l||ic(d))return{httpRequestInfo:f,pullResponse:d,syncHead:P};let p=await pu(c,o,u,d,t,s);return{httpRequestInfo:f,pullResponse:d,syncHead:p.type===0?p.syncHead:P}}async function uu(e,t,n,r){e.debug?.(`Starting pull...`);let i=Date.now(),a;try{a=await t(n,r),e.debug?.(`...Pull ${a.response?`complete`:`failed`} in `,Date.now()-i,`ms`)}catch(e){throw new ru(tu(e))}try{return su(n)?vc(a):yc(a),a}catch(e){throw new Ql(`Invalid puller result`,tu(e))}}function du(e,t,n,r,i,a){return Wc(t,async t=>{k(a<=4);let o=t,s=await o.getHead(F);if(s===void 0)throw Error(`Main head disappeared`);let c=await Ea(s,o),[l,u]=Oa(c,i);if(!Kr(n,u))return{type:2};if(r.lastMutationID<l)throw Error(fu(`lastMutationID`,String(r.lastMutationID),String(l)));let d=vi(r.cookie??null);if(Kr(d,u))return r.patch.length>0&&e.error?.(`handlePullResponse: cookie ${JSON.stringify(u)} did not change, but patch is not empty`),r.lastMutationID!==l&&e.error?.(`handlePullResponse: cookie ${JSON.stringify(u)} did not change, but lastMutationID did change`),{type:1};let f=await Aa(s,o),p;for(let e of f)if(await e.getMutationID(i,o)<=r.lastMutationID){p=e;break}if(!p)throw Error(`Internal invalid chain`);let m=await Ys(c.chunk.hash,r.lastMutationID,d,t,Qs(p,t,a),i,a);await nu(e,m,r.patch);let h=new Zo(o,a,p.valueHash);for await(let t of m.map.diff(h))await Zs(e,m.indexes,t.key,()=>Promise.resolve(t.oldValue),t.newValue);return{type:0,syncHead:await m.commit(iu)}})}function fu(e,t,n){return`Received ${e} ${t} is < than last snapshot ${e} ${n}; ignoring client view`}function pu(e,t,n,r,i,a){return Wc(t,async t=>{let o=t,s=await o.getHead(F);if(s===void 0)throw Error(`Main head disappeared`);let c=await Ea(s,o),l=c.meta;za(l);let u=l.cookieJSON;if(!Kr(n,u))return e.debug?.(`handlePullResponse: cookie mismatch, response is not applicable`),{type:2};for(let[e,t]of Object.entries(r.lastMutationIDChanges)){let n=l.lastMutationIDs[e];if(n!==void 0&&t<n)throw Error(fu(`${e} lastMutationID`,String(t),String(n)))}let d=vi(r.cookie);if(ni(d,u)<0)throw Error(fu(`cookie`,JSON.stringify(d),JSON.stringify(u)));if(Kr(d,u))return r.patch.length>0&&e.error?.(`handlePullResponse: cookie ${JSON.stringify(u)} did not change, but patch is not empty`),Object.keys(r.lastMutationIDChanges).length>0&&(console.log(r.lastMutationIDChanges),e.error?.(`handlePullResponse: cookie ${JSON.stringify(u)} did not change, but lastMutationIDChanges is not empty`)),{type:1};let f=await Xs(c.chunk.hash,{...l.lastMutationIDs,...r.lastMutationIDChanges},d,t,i,a);return await nu(e,f,r.patch),{type:0,syncHead:await f.commit(iu)}})}function mu(e,t,n,r,i,a){return Wc(e,async e=>{let o=e,s=await o.getHead(iu);if(s===void 0)throw Error(`Missing sync head`);if(s!==n)throw t.error?.(`maybeEndPull, Wrong sync head. Expecting:`,n,`got:`,s),Error(`Wrong sync head`);let c=await Ea(s,o),l=await o.getHead(F);if(l===void 0)throw Error(`Missing main head`);let u=await Ea(l,o),{meta:d}=c,f=d.basisHash;if(c===null)throw Error(`Sync snapshot with no basis`);if(f!==u.chunk.hash)throw Error(`Overlapping syncs`);let p=await I(s,o),m=[],h=await xa(l,o);for(let e of h){let t=r;ma(e)&&(t=e.meta.clientID),await e.getMutationID(t,o)>await p.getMutationID(t,o)&&m.push(e)}m.reverse();let g=new Ws;if(m.length>0)return{syncHead:s,replayMutations:m,diffs:g};let _=await I(l,o);if(i.shouldComputeDiffs()){let e=await Bs(new Zo(o,a,_.valueHash),new Zo(o,a,p.valueHash));g.set(``,e),await Ks(_,p,o,g,i,a)}if(await Promise.all([e.setHead(F,s),e.removeHead(iu)]),await e.commit(),t.debug){let[e,n]=Oa(u,r),[i,a]=Oa(c,r);t.debug(`Successfully pulled new snapshot with lastMutationID:`,i,`(prev:`,e,`), cookie: `,a,`(prev:`,n,`), sync head hash:`,s,`, main head hash:`,l,`, valueHash:`,p.valueHash,`(prev:`,u.valueHash)}return{syncHead:s,replayMutations:[],diffs:g}})}var hu=[],gu=N.unknown().chain(e=>{if(Ur)return un(e);let t=Zr(e,hu)?un(e):dn({message:`Not a JSON value`,path:hu.slice()});return hu.length=0,t});N.unknown().chain(e=>{if(Ur)return un(e);let t=Qr(e,hu)?un(e):dn({message:`Not a JSON object`,path:hu.slice()});return hu.length=0,t});function _u(e){M(e),lc(e.httpRequestInfo),e.response!==void 0&&vu(e.response)}function vu(e){ac(e)||sc(e)}var yu=class extends Error{name=`PushError`;causedBy;constructor(e){super(`Failed to push`),this.causedBy=e}},bu=0,xu=1,Su=Bi({id:N.number(),name:N.string(),args:gu,timestamp:N.number()}),Cu=Bi({id:N.number(),name:N.string(),args:gu,timestamp:N.number(),clientID:Uc});N.object({pushVersion:N.literal(0),schemaVersion:N.string(),profileID:N.string(),clientID:Uc,mutations:N.array(Su)}),N.object({pushVersion:N.literal(1),schemaVersion:N.string(),profileID:N.string(),clientGroupID:Hc,mutations:N.array(Cu)});function wu(e){return{id:e.mutationID,name:e.mutatorName,args:e.mutatorArgsJSON,timestamp:e.timestamp}}function Tu(e){return{id:e.mutationID,name:e.mutatorName,args:e.mutatorArgsJSON,timestamp:e.timestamp,clientID:e.clientID}}async function Eu(e,t,n,r,i,a,o,s,c){let l=await L(t,async e=>{let t=await e.getHead(F);if(!t)throw Error(`Internal no main head`);return xa(t,e)});if(l.length===0)return;l.reverse();let u;if(c===xu){let e=[];for(let t of l)if(ma(t))e.push(Tu(t.meta));else throw Error(`Internal non local pending commit`);k(i),u={profileID:r,clientGroupID:i,mutations:e,pushVersion:xu,schemaVersion:s}}else{k(c===bu);let e=[];for(let t of l)if(pa(t))e.push(wu(t.meta));else throw Error(`Internal non local pending commit`);u={profileID:r,clientID:a,mutations:e,pushVersion:bu,schemaVersion:s}}n.debug?.(`Starting push...`);let d=Date.now(),f=await Du(o,u,e);return n.debug?.(`...Push complete in `,Date.now()-d,`ms`),f}async function Du(e,t,n){let r;try{r=await e(t,n)}catch(e){throw new yu(tu(e))}try{return _u(r),r}catch(e){throw new Ql(`Invalid pusher result`,tu(e))}}var Ou=10*2**20,ku=class{#e=!1;#t;constructor(e){this.#t=e}async recoverMutations(e,t,n,r,i,a){let{lc:o,enableMutationRecovery:s,isPushDisabled:c,delegate:l}=this.#t;if(!s||this.#e||!l.online||l.closed||c())return!1;let u=`Recovering mutations.`;o.debug?.(`Start:`,u);try{this.#e=!0,await t,await Nu(r,this.#t,n,e);for(let e of Object.values(await i.getDatabases())){if(l.closed)return o.debug?.(`Exiting early due to close:`,u),!0;if(e.replicacheName===l.name&&e.name!==l.idbName)switch(e.replicacheFormatVersion){case 4:case 5:case 6:case 7:await Mu(e,this.#t,void 0,a)}}}catch(e){Au(e,o,u,l)}finally{o.debug?.(`End:`,u),this.#e=!1}return!0}};function Au(e,t,n,r){r.closed?t.debug?.(`Mutation recovery error likely due to close during:
1
+ import{z as e}from"zod";import{errorBoundary as t,errorListBoundary as n}from"@stayradiated/error-boundary";import{z as r}from"zod/mini";import{getContext as i,mount as a,onDestroy as o,onMount as s,unmount as c}from"svelte";import"svelte/internal/disclose-version";import"svelte/internal/flags/async";import*as l from"svelte/internal/client";import{SvelteMap as u,SvelteSet as d}from"svelte/reactivity";import{newMessagePortRpcSession as f}from"capnweb";import"@andypf/json-viewer";var p=Object.create,m=Object.defineProperty,h=Object.getOwnPropertyDescriptor,g=Object.getOwnPropertyNames,_=Object.getPrototypeOf,v=Object.prototype.hasOwnProperty,y=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),b=(e,t)=>{let n={};for(var r in e)m(n,r,{get:e[r],enumerable:!0});return t||m(n,Symbol.toStringTag,{value:`Module`}),n},ee=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=g(t),a=0,o=i.length,s;a<o;a++)s=i[a],!v.call(e,s)&&s!==n&&m(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=h(t,s))||r.enumerable});return e},x=(e,t,n)=>(n=e==null?{}:p(_(e)),ee(t||!e||!e.__esModule||!v.call(e,`default`)?m(n,`default`,{value:e,enumerable:!0}):n,e)),te=e=>Object.fromEntries(e.map(e=>{switch(e.type){case`mutation`:case`query`:return[e.id,t=>e.call(t)];case`subscription`:return[e.id,async(t,n)=>{let r=n.dup(),i=await e.subscribe(r,t);return async()=>{i(),r[Symbol.dispose]()}}];default:throw Error(`Unknown tool type: '${JSON.stringify(e)}'`)}})),ne=e=>Object.fromEntries(e.map(e=>{switch(e.type){case`mutation`:case`query`:return[e.id,async t=>e.outputSample];case`subscription`:return[e.id,async(t,n)=>{let r=n.dup();return r(e.outputSample),async()=>{r[Symbol.dispose]()}}];default:throw Error(`Unknown tool type: '${JSON.stringify(e)}'`)}})),re=e=>({type:e.type,id:e.id,name:e.name,description:e.description,inputSchema:e.inputSchema.toJSONSchema(),outputSchema:e.outputSchema.toJSONSchema(),outputSample:e.outputSample}),ie=class t{type=`mutation`;id;name;description;inputSchema;outputSchema;outputSample;implementation;static create(e){new t(e)}constructor(e){this.id=e.id,this.name=e.name,this.description=e.description,this.inputSchema=e.inputSchema,this.outputSchema=e.outputSchema,this.outputSample=e.outputSample,this.implementation=e.implementation}toJSON(){return re(this)}async call(t){let n=this.inputSchema.safeParse(t);if(!n.success)throw Error(`Invalid input for ${this.id}: ${e.prettifyError(n.error)}`);let r=await this.implementation(n.data),i=this.outputSchema.safeParse(r);if(!i.success)throw Error(`Invalid output for ${this.id}: ${e.prettifyError(i.error)}`);return i.data}},ae=class t{type=`query`;id;name;description;inputSchema;outputSchema;outputSample;implementation;static create(e){new t(e)}constructor(e){this.id=e.id,this.name=e.name,this.description=e.description,this.inputSchema=e.inputSchema,this.outputSchema=e.outputSchema,this.outputSample=e.outputSample,this.implementation=e.implementation}toJSON(){return re(this)}async call(t){let n=this.inputSchema.safeParse(t);if(!n.success)throw Error(`Invalid input for ${this.id}: ${e.prettifyError(n.error)}`);let r=await this.implementation(n.data),i=this.outputSchema.safeParse(r);if(!i.success)throw Error(`Invalid output for ${this.id}: ${e.prettifyError(i.error)}`);return i.data}},oe=class t{type=`subscription`;id;name;description;inputSchema;outputSchema;outputSample;implementation;static create(e){new t(e)}constructor(e){this.id=e.id,this.name=e.name,this.description=e.description,this.inputSchema=e.inputSchema,this.outputSchema=e.outputSchema,this.outputSample=e.outputSample,this.implementation=e.implementation}toJSON(){return re(this)}async subscribe(t,n){let r=this.inputSchema.safeParse(n);if(!r.success)throw Error(`Invalid input for ${this.id}: ${e.prettifyError(r.error)}`);return await this.implementation(n=>{let r=this.outputSchema.safeParse(n);if(!r.success)throw Error(`Invalid output for ${this.id}: ${e.prettifyError(r.error)}`);t(r.data)},r.data)}},se=e=>{let t=new URL(e.path,e.baseUrl);for(let[n,r]of Object.entries(e.query??{}))r!==void 0&&t.searchParams.set(n,String(r));return t.toString()},ce=async e=>{let{replicache:n,projectId:r,signal:i}=e;return i?.aborted?Error(`Ping project aborted`):t(async()=>{await n.mutate.project_ping_v1({projectPublicId:r,context:{actionedAt:Date.now()}}),await n.push({now:!0})})},le=`/`,S=e=>{let t=`${e}${le}`,n=t.length;return()=>({name:e,value:t=>({name:e,idA:t,idB:void 0}),trimPrefix:e=>e.substring(n),prefix:(...e)=>{switch(e.length){case 0:return t;case 1:return`${t}${e[0]}`;default:throw Error(`Unexpected number of ids: "${e}"`)}},isMatch:e=>e.startsWith(t),encode:e=>`${t}${e}`,decode:e=>{if(!e.startsWith(t))throw Error(`Expected serialized to start with prefix "${t}", received "${e}"`);return e.substring(n)},decodeWithoutPrefix:e=>e})},C=e=>{let t=`${e}${le}`,n=t.length;return()=>({name:e,value:(t,n)=>({name:e,idA:t,idB:n}),trimPrefix:e=>e.substring(n),prefix:(...e)=>{switch(e.length){case 0:return t;case 1:return`${t}${e[0]}${le}`;case 2:return`${t}${e[0]}${le}${e[1]}`;default:throw Error(`Unexpected number of ids: "${e}"`)}},isMatch:e=>e.startsWith(t),encode:(e,n)=>`${t}${e}${le}${n}`,decode:e=>{if(!e.startsWith(t))throw Error(`Expected serialized to start with prefix "${t}", received "${e}"`);return e.substring(n).split(le)},decodeWithoutPrefix:e=>e.split(le)})},w={internal:S(`__internal`)(),apiToken:S(`apiToken`)(),asset:S(`asset`)(),backlogTask:S(`backlogTask`)(),block:S(`block`)(),comment:S(`comment`)(),commentThread:S(`commentThread`)(),content:S(`content`)(),document:S(`document`)(),draftContent:S(`draftContent`)(),event:S(`event`)(),filter:S(`filter`)(),filterRule:S(`filterRule`)(),fizzyAccount:S(`fizzyAccount`)(),fizzyBoard:S(`fizzyBoard`)(),fizzyIntegration:S(`fizzyIntegration`)(),invitation:S(`invitation`)(),inviteLink:S(`inviteLink`)(),label:S(`label`)(),llmModel:S(`llmModel`)(),llmModelDefault:S(`llmModelDefault`)(),llmProvider:S(`llmProvider`)(),note:S(`note`)(),notification:S(`notification`)(),person:S(`person`)(),project:S(`project`)(),projectAccount:S(`projectAccount`)(),reaction:S(`reaction`)(),reference:S(`reference`)(),sequence:S(`sequence`)(),signingKey:S(`signingKey`)(),sprite:S(`sprite`)(),spriteBuild:S(`spriteBuild`)(),spriteBuildEvent:S(`spriteBuildEvent`)(),surface:S(`surface`)(),task:S(`task`)(),vcsBranch:S(`vcsBranch`)(),vcsCommit:S(`vcsCommit`)(),vcsIntegration:S(`vcsIntegration`)(),vcsRepo:S(`vcsRepo`)(),vcsUser:S(`vcsUser`)(),watch:S(`watch`)(),workspace:S(`workspace`)(),blockUser:C(`blockUser`)(),documentUser:C(`documentUser`)(),sequenceDocument:C(`sequenceDocument`)(),signingKeyProject:C(`signingKeyProject`)(),vcsCommitDocument:C(`vcsCommitDocument`)(),noteLabel:C(`noteLabel`)(),spriteProjectAccount:C(`spriteProjectAccount`)(),taskLabel:C(`taskLabel`)(),relatedDocumentNote:C(`relatedDocumentNote`)(),relatedDocumentPair:C(`relatedDocumentPair`)(),relatedNotePair:C(`relatedNotePair`)(),relatedSpritePair:C(`relatedSpritePair`)(),stackTask:C(`stackTask`)(),workspaceUser:S(`workspaceUser`)()},ue=(e,t)=>{let n={};for(let r of e){let e=t(r);Object.hasOwn(n,e)?n[e]?.push(r):Object.defineProperty(n,e,{configurable:!0,enumerable:!0,value:[r],writable:!0})}return n},de=class{#e=0;#t=new Map;#n=new Map;#r;#i;#a;constructor(e){if(!(e.maxSize&&e.maxSize>0))throw TypeError("`maxSize` must be a number greater than 0");if(typeof e.maxAge==`number`&&e.maxAge===0)throw TypeError("`maxAge` must be a number greater than 0");this.#r=e.maxSize,this.#i=e.maxAge??1/0,this.#a=e.onEviction,Object.defineProperty(this,Symbol.for(`nodejs.util.inspect.custom`),{value:()=>this.toString()})}get __oldCache(){return this.#n}#o(e){if(typeof this.#a==`function`)for(let[t,n]of e)this.#a(t,n.value)}#s(e,t){return typeof t.expiry==`number`&&t.expiry<=Date.now()&&(this.#a?.(e,t.value),this.delete(e))}#c(e,t){if(!this.#s(e,t))return t.value}#l(e,t){if(t)return t.expiry?this.#c(e,t):t.value}#u(e,t){return this.#l(e,t.get(e))}#d(e,t){this.#t.set(e,t),this.#e++,this.#e>=this.#r&&(this.#e=0,this.#o(this.#n),this.#n=this.#t,this.#t=new Map)}#f(e,t){this.#n.delete(e),this.#d(e,t)}*#p(){for(let[e,t]of this.#n)!this.#t.has(e)&&!this.#s(e,t)&&(yield[e,t]);for(let[e,t]of this.#t)this.#s(e,t)||(yield[e,t])}get(e){if(this.#t.has(e))return this.#l(e,this.#t.get(e));if(this.#n.has(e)){let t=this.#n.get(e);if(t&&!this.#s(e,t))return this.#f(e,t),t.value}}set(e,t,{maxAge:n=this.#i}={}){let r={value:t,expiry:typeof n==`number`&&n!==1/0?Date.now()+n:void 0};return this.#t.has(e)?this.#t.set(e,r):this.#d(e,r),this}has(e){if(this.#t.has(e)){let t=this.#t.get(e);return t?!this.#s(e,t):!1}if(this.#n.has(e)){let t=this.#n.get(e);return t?!this.#s(e,t):!1}return!1}peek(e){if(this.#t.has(e))return this.#u(e,this.#t);if(this.#n.has(e))return this.#u(e,this.#n)}expiresIn(e){let t=this.#t.get(e)??this.#n.get(e);if(t)return t.expiry?t.expiry-Date.now():1/0}delete(e){let t=this.#t.delete(e);return t&&this.#e--,this.#n.delete(e)||t}clear(){this.#t.clear(),this.#n.clear(),this.#e=0}resize(e){if(!(e&&e>0))throw TypeError("`maxSize` must be a number greater than 0");let t=[...this.#p()],n=t.length-e;n<0?(this.#t=new Map(t),this.#n=new Map,this.#e=t.length):(n>0&&this.#o(t.slice(0,n)),this.#n=new Map(t.slice(n)),this.#t=new Map,this.#e=0),this.#r=e}evict(e=1){let t=Number(e);if(!t||t<=0)return;let n=[...this.#p()],r=Math.trunc(Math.min(t,Math.max(n.length-1,0)));r<=0||(this.#o(n.slice(0,r)),this.#n=new Map(n.slice(r)),this.#t=new Map,this.#e=0)}*keys(){for(let[e]of this)yield e}*values(){for(let[,e]of this)yield e}*[Symbol.iterator](){for(let[e,t]of this.#t)this.#s(e,t)||(yield[e,t.value]);for(let[e,t]of this.#n)!this.#t.has(e)&&!this.#s(e,t)&&(yield[e,t.value])}*entriesDescending(){let e=[...this.#t];for(let t=e.length-1;t>=0;t--){let n=e[t];if(n===void 0)continue;let[r,i]=n;this.#s(r,i)||(yield[r,i.value])}e=[...this.#n];for(let t=e.length-1;t>=0;t--){let n=e[t];if(n===void 0)continue;let[r,i]=n;!this.#t.has(r)&&!this.#s(r,i)&&(yield[r,i.value])}}*entriesAscending(){for(let[e,t]of this.#p())yield[e,t.value]}get size(){if(!this.#e)return this.#n.size;let e=0;for(let t of this.#n.keys())this.#t.has(t)||e++;return Math.min(this.#e+e,this.#r)}get maxSize(){return this.#r}get maxAge(){return this.#i}entries(){return this.entriesAscending()}forEach(e,t=this){for(let[n,r]of this.entriesAscending())e.call(t,r,n,this)}get[Symbol.toStringTag](){return`QuickLRU`}toString(){return`QuickLRU(${this.size}/${this.maxSize})`}},fe=class{arraySize=0;array=Array(8);set=null;get isEmpty(){if(this.array)return this.arraySize===0;if(this.set)return this.set.size===0;throw Error(`no set or array`)}add(e){if(this.array)return this.array.indexOf(e)===-1?this.arraySize<8?(this.array[this.arraySize]=e,this.arraySize++,!0):(this.set=new Set(this.array),this.array=null,this.set.add(e),!0):!1;if(this.set)return!this.set.has(e)&&(this.set.add(e),!0);throw Error(`no set or array`)}remove(e){if(this.array){let t=this.array.indexOf(e);return t!==-1&&(this.array[t]=void 0,this.arraySize--,t!==this.arraySize&&(this.array[t]=this.array[this.arraySize],this.array[this.arraySize]=void 0),!0)}if(this.set)return this.set.has(e)?(this.set.delete(e),!0):!1;throw Error(`no set or array`)}visit(e){if(this.array){for(let t=0;t<this.arraySize;t++){let n=this.array[t];n!==void 0&&e(n)}return}if(this.set){this.set.forEach(e);return}throw Error(`no set or array`)}};function T(e){return e&&typeof e==`object`&&`parents`in e}function pe(e){for(let t=0,n=e.parents.length;t<n;t++)if(e.parents[t].__unsafe__getWithoutCapture(),e.parents[t].lastChangedEpoch!==e.parentEpochs[t])return!0;return!1}var me=(e,t)=>{if(e.children.remove(t)&&e.children.isEmpty&&T(e))for(let t=0,n=e.parents.length;t<n;t++)me(e.parents[t],e)},he=(e,t)=>{if(e.children.add(t)&&T(e))for(let t=0,n=e.parents.length;t<n;t++)he(e.parents[t],e)};function ge(e,t){return e===t||Object.is(e,t)||!!(e&&t&&typeof e.equals==`function`&&e.equals(t))}var _e=Object.freeze([]),ve=Symbol.for(`__signia__`),ye=globalThis;ye[ve]?console.error(`Multiple versions of signia detected. This will cause unexpected behavior. Please add "resolutions" (yarn/pnpm) or "overrides" (npm) in your package.json to ensure only one version of signia is loaded.`):ye[ve]=!0;var be=class{constructor(e,t){this.below=e,this.child=t}offset=0;numNewParents=0;maybeRemoved},E=null;function xe(e){E=new be(E,e)}function Se(){let e=E;if(E=e.below,e.numNewParents>0||e.offset!==e.child.parents.length){for(let t=e.offset;t<e.child.parents.length;t++){let n=e.child.parents[t];e.child.parents.indexOf(n)>=e.offset&&me(n,e.child)}if(e.child.parents.length=e.offset,e.child.parentEpochs.length=e.offset,E?.maybeRemoved)for(let t=0;t<E.maybeRemoved.length;t++){let n=E.maybeRemoved[t];e.child.parents.indexOf(n)===-1&&me(n,e.child)}}}function Ce(e){if(E){let t=E.child.parents.indexOf(e);if(t<0&&(E.numNewParents++,E.child.isActivelyListening&&he(e,E.child)),t<0||t>=E.offset){if(t!==E.offset&&t>0){let e=E.child.parents[E.offset];E.maybeRemoved?E.maybeRemoved.indexOf(e)===-1&&E.maybeRemoved.push(e):E.maybeRemoved=[e]}E.child.parents[E.offset]=e,E.child.parentEpochs[E.offset]=e.lastChangedEpoch,E.offset++}}}var we=Symbol(`RESET_VALUE`),Te=class{constructor(e){this.capacity=e,this.buffer=Array(e)}index=0;buffer;pushEntry(e,t,n){if(n!==void 0){if(n===we){this.clear();return}this.buffer[this.index]=[e,t,n],this.index=(this.index+1)%this.capacity}}clear(){this.index=0,this.buffer.fill(void 0)}getChangesSince(e){let{index:t,capacity:n,buffer:r}=this;for(let i=0;i<n;i++){let a=(t-1+n-i)%n,o=r[a];if(!o)return we;let[s,c]=o;if(i===0&&e>=c)return[];if(s<=e&&e<c){let e=i+1,t=Array(e);for(let i=0;i<e;i++)t[i]=r[(a+i)%n][2];return t}}return we}},D=0,Ee=!1;function De(){D++}function Oe(e){if(Ee)throw Error(`cannot change atoms during reaction cycle`);try{Ee=!0;let t=new Set,n=e=>{e.lastTraversedEpoch!==D&&(e.lastTraversedEpoch=D,`maybeScheduleEffect`in e?t.add(e):e.children.visit(n))};for(let t of e)t.children.visit(n);for(let e of t)e.maybeScheduleEffect()}finally{Ee=!1}}function ke(e,t){Ae?Ae.initialAtomValues.has(e)||Ae.initialAtomValues.set(e,t):Oe([e])}var Ae=null,je=class{constructor(e,t,n){this.name=e,this.current=t,this.isEqual=n?.isEqual??null,n&&(n.historyLength&&(this.historyBuffer=new Te(n.historyLength)),this.computeDiff=n.computeDiff)}isEqual;computeDiff;lastChangedEpoch=D;children=new fe;historyBuffer;__unsafe__getWithoutCapture(){return this.current}get value(){return Ce(this),this.current}set(e,t){if(this.isEqual?.(this.current,e)??ge(this.current,e))return this.current;De(),this.historyBuffer&&this.historyBuffer.pushEntry(this.lastChangedEpoch,D,t??this.computeDiff?.(this.current,e,this.lastChangedEpoch,D)??we),this.lastChangedEpoch=D;let n=this.current;return this.current=e,ke(this,n),e}update(e){return this.set(e(this.current))}getDiffSince(e){return Ce(this),e>=this.lastChangedEpoch?_e:this.historyBuffer?.getChangesSince(e)??we}};function Me(e,t,n){return new je(e,t,n)}var Ne=Symbol(`UNINITIALIZED`),Pe=e=>e===Ne,Fe=class{constructor(e,t){this.value=e,this.diff=t}},Ie=class{constructor(e,t,n){this.name=e,this.derive=t,n?.historyLength&&(this.historyBuffer=new Te(n.historyLength)),this.computeDiff=n?.computeDiff,this.isEqual=n?.isEqual??ge}lastChangedEpoch=-1;lastTraversedEpoch=-1;lastCheckedEpoch=-1;parents=[];parentEpochs=[];children=new fe;get isActivelyListening(){return!this.children.isEmpty}historyBuffer;state=Ne;computeDiff;isEqual;__unsafe__getWithoutCapture(){let e=this.lastChangedEpoch===-1;if(!e&&(this.lastCheckedEpoch===D||!pe(this)))return this.lastCheckedEpoch=D,this.state;try{xe(this);let t=this.derive(this.state,this.lastCheckedEpoch),n=t instanceof Fe?t.value:t;if(this.state===Ne||!this.isEqual(n,this.state)){if(this.historyBuffer&&!e){let e=t instanceof Fe?t.diff:void 0;this.historyBuffer.pushEntry(this.lastChangedEpoch,D,e??this.computeDiff?.(this.state,n,this.lastCheckedEpoch,D)??we)}this.lastChangedEpoch=D,this.state=n}return this.lastCheckedEpoch=D,this.state}finally{Se()}}get value(){let e=this.__unsafe__getWithoutCapture();return Ce(this),e}getDiffSince(e){return this.value,e>=this.lastChangedEpoch?_e:this.historyBuffer?.getChangesSince(e)??we}};function Le(e={},t,n,r){let i=r.get,a=Symbol.for(`__signia__computed__`+n);return r.get=function(){let t=this[a];return t||(t=new Ie(n,i.bind(this),e),Object.defineProperty(this,a,{enumerable:!1,configurable:!1,writable:!1,value:t})),t.value},r}function Re(){if(arguments.length===1){let e=arguments[0];return(t,n,r)=>Le(e,t,n,r)}return typeof arguments[0]==`string`?new Ie(arguments[0],arguments[1],arguments[2]):Le(void 0,arguments[0],arguments[1],arguments[2])}var ze=class{constructor(e,t,n){this.name=e,this.runEffect=t,this._scheduleEffect=n?.scheduleEffect}_isActivelyListening=!1;get isActivelyListening(){return this._isActivelyListening}lastTraversedEpoch=-1;lastReactedEpoch=-1;_scheduleCount=0;get scheduleCount(){return this._scheduleCount}parentEpochs=[];parents=[];_scheduleEffect;maybeScheduleEffect(){if(this._isActivelyListening&&this.lastReactedEpoch!==D){if(this.parents.length&&!pe(this)){this.lastReactedEpoch=D;return}this.scheduleEffect()}}scheduleEffect(){this._scheduleCount++,this._scheduleEffect?this._scheduleEffect(this.maybeExecute):this.execute()}maybeExecute=()=>{this._isActivelyListening&&this.execute()};attach(){this._isActivelyListening=!0;for(let e=0,t=this.parents.length;e<t;e++)he(this.parents[e],this)}detach(){this._isActivelyListening=!1;for(let e=0,t=this.parents.length;e<t;e++)me(this.parents[e],this)}execute(){try{xe(this);let e=this.runEffect(this.lastReactedEpoch);return this.lastReactedEpoch=D,e}finally{Se()}}};function Be(e,t,n){let r=new ze(e,t,n);return r.attach(),r.scheduleEffect(),()=>{r.detach()}}var Ve=e=>{let{diffList:t,source:n,mapKey:r,mapValue:i}=e;if(t.length===0)return;let a={...n.__unsafe__getWithoutCapture()},o=[];for(let e of t)switch(e.op){case`add`:{let t=r(e.key),n=i(e.newValue,e.key);a[t]=n,o.push({op:`add`,key:t,value:n});break}case`change`:{let t=r(e.key),n=i(e.newValue,e.key);a[t]=n,o.push({op:`replace`,key:t,value:n});break}case`del`:{let t=r(e.key);delete a[t],o.push({op:`remove`,key:t});break}default:throw Error(`Unhandled diff op: ${JSON.stringify(e)}`)}n.set(a,o)},He=e=>{let t=new Set,n=[];for(let r=e.length-1;r>=0;r--){let i=e[r];for(let e=i.length-1;e>=0;e--){let r=i[e];t.has(r.key)||(t.add(r.key),n.push(r))}}return n.reverse(),n},Ue=(e,t,n)=>{let r={},i=()=>{r={};for(let[n,i]of Object.entries(e.value))t(i)&&(r[n]=i);return Object.values(r)};return Re(`${e.name}:filter`,(n,a)=>{if(Pe(n))return i();let o=e.getDiffSince(a);if(o===we)return i();let s=He(o);if(s.length===0)return i();for(let e of s)switch(e.op){case`add`:t(e.value)&&(r[e.key]=e.value);break;case`remove`:delete r[e.key];break;case`replace`:t(e.value)?r[e.key]=e.value:delete r[e.key];break;default:throw Error(`Unhandled patch operation: ${JSON.stringify(e)}`)}return Object.values(r)},{...n})},We=(e,t,n)=>{let r=new Set,i,a=()=>{r.clear(),i=void 0;let n=!1,a;for(let[o,s]of Object.entries(e.value))n?r.add(o):t(s)&&(n=!0,a=s,i=o);return a},o=()=>{for(let n of r){r.delete(n);let a=e.value[n];if(a!==void 0&&t(a))return i=n,a}i=void 0};return Re(`${e.name}:find`,(n,s)=>{if(Pe(n))return a();let c=e.getDiffSince(s);if(c===we)return a();let l=He(c);if(l.length===0)return a();for(let e of l)switch(e.op){case`add`:i===void 0?t(e.value)&&(i=e.key):r.add(e.key);break;case`remove`:e.key===i?o():r.delete(e.key);break;case`replace`:e.key===i||i===void 0?t(e.value)?i=e.key:o():r.add(e.key);break;default:throw Error(`Unhandled patch operation: ${JSON.stringify(e)}`)}return i===void 0?void 0:e.value[i]},{...n})},Ge=(e,t,n)=>Re(`${e.name}:get`,()=>e.value[t],{...n}),Ke=(e,t,n)=>{let r={},i=()=>{r={};for(let[n,i]of Object.entries(e.value))r[n]=t(i);return Object.values(r)};return Re(`${e.name}:map`,(n,a)=>{if(Pe(n))return i();let o=e.getDiffSince(a);if(o===we)return i();let s=He(o);if(s.length===0)return i();for(let e of s)switch(e.op){case`add`:r[e.key]=t(e.value);break;case`replace`:r[e.key]=t(e.value);break;case`remove`:delete r[e.key];break;default:throw Error(`Unhandled patch operation: ${JSON.stringify(e)}`)}return Object.values(r)},{...n})},qe=(e,t,n)=>{let r={},i=()=>{r={};for(let n of Object.keys(e.value)){let e=t(n);r[n]=e}return Object.values(r)};return Re(`${e.name}:keys`,(n,a)=>{if(Pe(n))return i();let o=e.getDiffSince(a);if(o===we)return i();let s=He(o);if(s.length===0)return i();for(let e of s)switch(e.op){case`add`:r[e.key]=t(e.key);break;case`remove`:delete r[e.key];break;case`replace`:e.key in r||(r[e.key]=t(e.key));break;default:throw Error(`Unhandled patch operation: ${JSON.stringify(e)}`)}return Object.values(r)},{...n})},Je=(e,t)=>Re(`${e.name}:values`,()=>Object.values(e.value),{...t}),Ye=(e,t,n)=>{let r=new Set,i=new Set,a=()=>{r.clear(),i.clear();let n=!1;for(let[a,o]of Object.entries(e.value))n?i.add(a):t(o)&&(r.add(a),n=!0);return n},o=()=>{for(let n of i){i.delete(n);let a=e.value[n];if(a!==void 0&&t(a))return r.add(n),!0}return!1};return Re(`${e.name}:some`,(n,s)=>{if(Pe(n))return a();let c=e.getDiffSince(s);if(c===we)return a();let l=He(c);if(l.length===0)return a();for(let e of l)switch(e.op){case`add`:r.size===0?t(e.value)&&r.add(e.key):i.add(e.key);break;case`remove`:i.delete(e.key),r.delete(e.key),r.size===0&&o();break;case`replace`:r.has(e.key)||r.size===0?(i.delete(e.key),t(e.value)?r.add(e.key):(r.delete(e.key),o())):i.add(e.key);break;default:throw Error(`Unhandled patch operation: ${JSON.stringify(e)}`)}return r.size>0},{...n})},Xe=50,Ze=class e{key;mapValue;name;atom;asRecord;asList;keys;#e=new Map;#t=e.#a();#n=e.#a();#r=e.#a();#i=e.#a();static#a(){return new de({maxSize:Xe})}constructor(e){this.key=e.key,this.mapValue=e.mapValue,this.name=`ReplicacheTable(${this.key.name})`,this.atom=Me(this.name,{},{historyLength:1}),this.asRecord=this.atom,this.asList=Je(this.atom),this.keys=qe(this.atom,e=>this.key.decodeWithoutPrefix(e))}#o(e,t,n){let r=e.get(t);if(r!==void 0)return r;let i=n();return e.set(t,i),i}#s(e){return typeof e==`string`?e:Array.isArray(e)?`${e[0]}/${e[1]}`:(console.error(`${this.name}.get: invalid key`,e),``)}get(e){let t=this.#s(e);return this.#o(this.#e,t,()=>Ge(this.atom,t))}find(e,t){return this.#o(this.#t,e,()=>We(this.atom,t))}filter(e,t){return this.#o(this.#n,e,()=>Ue(this.atom,t))}map(e,t){return this.#o(this.#r,e,()=>Ke(this.atom,t))}some(e,t){return this.#o(this.#i,e,()=>Ye(this.atom,t))}pushDiffList(e){Ve({diffList:e,source:this.atom,mapKey:e=>this.key.trimPrefix(e),mapValue:(e,t)=>this.mapValue(e,this.key.decode(t))})}clear(){let e=this.atom.__unsafe__getWithoutCapture(),t=Object.keys(e);if(t.length===0)return;let n=t.map(e=>({op:`remove`,key:e}));this.atom.set({},n)}},Qe=`store`,$e=S(`meta`)(),et=()=>{let e={meta:new Ze({key:$e,mapValue:e=>e}),person:new Ze({key:w.person,mapValue:(e,t)=>({id:t,name:e.name})}),surface:new Ze({key:w.surface,mapValue:(e,t)=>({id:t,key:e.key,name:e.name,description:e.description})}),sprite:new Ze({key:w.sprite,mapValue:(e,t)=>({id:t,name:e.name,surfaceId:e.surfaceId,ownedByPersonId:e.ownedByPersonId})}),spriteBuild:new Ze({key:w.spriteBuild,mapValue:(e,t)=>({id:t,spriteId:e.spriteId,parentSpriteBuildId:e.parentSpriteBuildId,createdByPersonId:e.createdByPersonId,prompt:e.prompt,status:e.status,cancelRequestedAt:e.cancelRequestedAt,artifactUrl:e.artifactUrl,sourceUrl:null,startedAt:e.startedAt,stoppedAt:e.stoppedAt,error:e.error,reasoningSummary:e.reasoningSummary,publishedAt:e.publishedAt})}),spriteBuildEvent:new Ze({key:w.spriteBuildEvent,mapValue:(e,t)=>({id:t,spriteBuildId:e.spriteBuildId,actionedAt:e.actionedAt,type:e.type,detail:e.detail})})},t={[w.person.name]:e.person,[w.surface.name]:e.surface,[w.spriteBuildEvent.name]:e.spriteBuildEvent,[w.spriteBuild.name]:e.spriteBuild,[w.sprite.name]:e.sprite},n=new Set,r,i=!1,a=t=>{let n=$e.encode(Qe);t===`LOADING`?e.meta.pushDiffList([{op:`add`,key:n,newValue:{state:t}}]):e.meta.pushDiffList([{op:`change`,key:n,newValue:{state:t},oldValue:{}}])},o=()=>{e.meta.clear(),e.person.clear(),e.surface.clear(),e.sprite.clear(),e.spriteBuild.clear(),e.spriteBuildEvent.clear()},s=()=>{for(let e of n)e()},c=e=>{if(i)return;r?.(),o(),a(`LOADING`);let n=!1;r=e.experimentalWatch(e=>{let r=ue(e,e=>e.key.match(/^(\w+)\//)?.[1]??``);for(let[e,n]of Object.entries(r))t[e]?.pushDiffList(n);n||(n=!0,a(`READY`)),s()},{initialValuesInFirstDiff:!0})},l=e=>(n.add(e),()=>{n.delete(e)}),u=async()=>{i=!0,r?.(),r=void 0,o(),n.clear()};return{...e,bind:c,subscribe:l,destroy:u}},tt=y(((e,t)=>{var n=self.crypto;function r(e){let t=new Uint8Array(e);return n.getRandomValues(t),t}t.exports={randomBytes:r}})),nt=y(((e,t)=>{var{randomBytes:n}=tt(),r=16;t.exports=new class{compare(e,t){let n=e.findIndex((e,n)=>e!==t[n]);return~n&&Math.sign(e[n]-t[n])}generateOneFilled(){return new Uint8Array(r).fill(255)}generateRandomFilled(){return n(r)}generateZeroFilled(){return new Uint8Array(r).fill(0)}}})),rt=y(((e,t)=>{var n=class extends Error{get name(){return this.constructor.name}};t.exports={Id128Error:n,ClockSequenceOverflow:class extends n{},InvalidBytes:class extends n{},InvalidEncoding:class extends n{},InvalidEpoch:class extends n{},UnsupportedVersion:class extends n{}}})),it=y(((e,t)=>{var{InvalidEpoch:n}=rt(),r=0,i=2**48;t.exports=new class{fromEpoch(e,t){return new Date(t+e)}toEpoch(e,t=null){let a=(t===null?Date.now():Number.isInteger(t)?t:t instanceof Date?t.getTime():(()=>{throw new n(`Failed to coerce time [${t}] to epoch`)})())-e;if(a<r||a>=i)throw new n(`Epoch must be between ${new Date(r+e).toISOString()} and ${new Date(i-1+e).toISOString()}`);return a}}})),at=y(((e,t)=>{var n=nt(),r=Symbol(`bytes`);t.exports={BaseId:class{constructor(e){this[r]=e}clone(){return new this.constructor(this.bytes.slice())}get bytes(){return this[r]}get[Symbol.toStringTag](){return this.constructor.name}compare(e){return n.compare(this.bytes,e.bytes)}equal(e){return this.compare(e)===0}}}})),ot=y(((e,t)=>{var n=nt(),r=it(),{BaseId:i}=at(),a=0,o=2**32,s=255;function c(e,t){let n=e%o,r=(e-n)/o,i=-1;t[++i]=r>>>8&s,t[++i]=r>>>0&s,t[++i]=n>>>24&s,t[++i]=n>>>16&s,t[++i]=n>>>8&s,t[++i]=n>>>0&s}t.exports={Ulid:class extends i{static generate({time:e}={}){e=r.toEpoch(a,e);let t=n.generateRandomFilled();return c(e,t),new this(t)}static MIN(){return new this(n.generateZeroFilled())}static MAX(){return new this(n.generateOneFilled())}get time(){let e=-1,t=0|this.bytes[++e]<<8|this.bytes[++e]<<0,n=0|this.bytes[++e]<<24|this.bytes[++e]<<16|this.bytes[++e]<<8|this.bytes[++e]<<0,i=t*o+(n>>>0);return r.fromEpoch(a,i)}},setTime:c}})),st=y(((e,t)=>{var{Ulid:n,setTime:r}=ot(),i=nt(),a=it(),{ClockSequenceOverflow:o}=rt(),s=0,c=6,l=8,u=0,d,f;function p(e){for(let t=7;t>5;--t)if(e[t]===255)e[t]=0;else{++e[t];return}throw new o(`Exhausted clock sequence`)}function m(e){e[c]&=127}function h(e){for(let t=s;t<l;++t)e[t]=d.bytes[t]}var g=class extends n{static reset(){f=-1,d=this.MIN()}static generate({time:e}={}){e=a.toEpoch(u,e);let t=i.generateRandomFilled();return e<=f?(h(t),p(t)):(r(e,t),m(t),f=e),d=new this(t)}};g.reset(),t.exports={UlidMonotonic:g}})),ct=y(((e,t)=>{var{BaseId:n}=at(),r=nt(),i=8,a=6;function o(e,t){t[i]&=255>>>e+1,t[i]|=(7<<3-e&7)<<5}function s(e,t){t[a]&=15,t[a]|=e<<4}t.exports={Uuid:class extends n{static MIN(){let e=r.generateZeroFilled();return o(this.VARIANT,e),s(this.VERSION,e),new this(e)}static MAX(){let e=r.generateOneFilled();return o(this.VARIANT,e),s(this.VERSION,e),new this(e)}get variant(){let e=this.bytes[i]>>>5;return e===7?3:(e&6)==6?2:+((e&4)==4)}get version(){return this.bytes[a]>>>4}},setVersion:s,setVariant:o}})),lt=y(((e,t)=>{var{randomBytes:n}=tt(),r=Symbol(`mac-address`);t.exports=new class{constructor(){this.reset()}get mac_address(){let e=this[r];return e||(e=this[r]=n(6),e[0]|=1),e}reset(){this[r]=null}}})),ut=y(((e,t)=>{var n=nt(),r=it(),i=lt(),{Uuid:a,setVariant:o,setVersion:s}=ct(),c=2,l=8,u=10,d=2**14,f=Date.parse(`1582-10-15Z`),p=4096,m=2**20,h=255,g,_,v;function y(){g=(g+1)%d}function b(e,t){if(g===null){let e=n.generateRandomFilled();g=(0|e[8]<<8|e[9]<<0)%d}else e<v&&y();let r=7;t[++r]=g>>>8&h,t[++r]=g>>>0&h}function ee(e,t){for(let n=0;n<6;++n)t[u+n]=e[n]}function x(e,t){_=e>v?0:_+1,_===p&&(_=0,y());let n=e%m,r=n*p+_,i=(e-n)/m,a=-1;t[++a]=r>>>24&h,t[++a]=r>>>16&h,t[++a]=r>>>8&h,t[++a]=r>>>0&h,t[++a]=i>>>8&h,t[++a]=i>>>0&h,t[++a]=i>>>24&h,t[++a]=i>>>16&h}var te=class extends a{static get VARIANT(){return 1}static get VERSION(){return 1}static reset(){g=null,_=-1,v=-1}static generate({node:e,time:t}={}){t=r.toEpoch(f,t);let a=n.generateZeroFilled();return x(t,a),b(t,a),ee(e||i.mac_address,a),o(this.VARIANT,a),s(this.VERSION,a),t>v&&(v=t),new this(a)}get clock_sequence(){return(0|this.bytes[l]<<8|this.bytes[9])&d-1}get hires_time(){return(0|this.bytes[c]<<8|this.bytes[3])&p-1}get node(){return this.bytes.slice(u)}get time(){let e=-1,t=0|this.bytes[++e]<<12|this.bytes[++e]<<4|this.bytes[++e]>>>4;++e;let n=(0|this.bytes[++e]<<8|this.bytes[++e]<<0|(this.bytes[++e]&15)<<24|this.bytes[++e]<<16)*m+t;return r.fromEpoch(f,n)}};te.reset(),t.exports={Uuid1:te}})),dt=y(((e,t)=>{var n=nt(),{Uuid:r,setVariant:i,setVersion:a}=ct();t.exports={Uuid4:class extends r{static get VARIANT(){return 1}static get VERSION(){return 4}static generate(){let e=n.generateRandomFilled();return i(this.VARIANT,e),a(this.VERSION,e),new this(e)}}}})),ft=y(((e,t)=>{var n=nt(),r=it(),i=lt(),{Uuid:a,setVariant:o,setVersion:s}=ct(),c=6,l=8,u=10,d=2**14,f=Date.parse(`1582-10-15Z`),p=4096,m=2**32,h=255,g,_,v;function y(){g=(g+1)%d}function b(e,t){if(g===null){let e=n.generateRandomFilled();g=(0|e[8]<<8|e[9]<<0)%d}else e<v&&y();let r=7;t[++r]=g>>>8&h,t[++r]=g>>>0&h}function ee(e,t){for(let n=0;n<6;++n)t[u+n]=e[n]}function x(e,t){_=e>v?0:_+1,_===p&&(_=0,y());let n=e%m,r=(e-n)/m,i=-1;t[++i]=r>>>8&h,t[++i]=r>>>0&h,t[++i]=n>>>24&h,t[++i]=n>>>16&h,t[++i]=n>>>8&h,t[++i]=n>>>0&h,t[++i]=_>>>8&h,t[++i]=_>>>0&h}var te=class extends a{static get VARIANT(){return 1}static get VERSION(){return 6}static reset(){g=null,_=-1,v=-1}static generate({node:e,time:t}={}){t=r.toEpoch(f,t);let a=n.generateZeroFilled();return x(t,a),b(t,a),ee(e||i.mac_address,a),o(this.VARIANT,a),s(this.VERSION,a),t>v&&(v=t),new this(a)}get clock_sequence(){return(0|this.bytes[l]<<8|this.bytes[9])&d-1}get hires_time(){return(0|this.bytes[c]<<8|this.bytes[7])&p-1}get node(){return this.bytes.slice(u)}get time(){let e=-1,t=0|this.bytes[++e]<<8|this.bytes[++e]<<0,n=0|this.bytes[++e]<<24|this.bytes[++e]<<16|this.bytes[++e]<<8|this.bytes[++e]<<0,i=t*m+(n>>>0);return r.fromEpoch(f,i)}};te.reset(),t.exports={Uuid6:te}})),pt=y(((e,t)=>{var n=nt(),{Uuid:r,setVariant:i,setVersion:a}=ct();t.exports={UuidNil:class extends r{static get VARIANT(){return 0}static get VERSION(){return 0}static generate(){let e=n.generateZeroFilled();return i(this.VARIANT,e),a(this.VERSION,e),new this(e)}static MAX(){let e=n.generateZeroFilled();return i(this.VARIANT,e),a(this.VERSION,e),new this(e)}}}})),mt=y(((e,t)=>{var{InvalidEncoding:n,InvalidBytes:r}=rt(),i=Symbol(`valid_encoding_pattern`);t.exports={BaseCoder:class{constructor({valid_encoding_pattern:e}={}){this[i]=e}decode(e){if(this.isValidEncoding(e))return this.decodeTrusted(e);throw new n(`Encoding [${e}] does not satisfy ${this[i]}`)}decodeTrusted(e){return ByteArray.generateRandomFilled()}encode(e){if(this.isValidBytes(e))return this.encodeTrusted(e);throw new r(`Requires a 16-byte Uint8Array`)}encodeTrusted(e){return``}isValidBytes(e){return e instanceof Uint8Array&&e.length===16}isValidEncoding(e){return(typeof e==`string`||e instanceof String)&&this[i].test(e)}}}})),ht=y(((e,t)=>{var{BaseCoder:n}=mt(),r=`0123456789ABCDEFGHJKMNPQRSTVWXYZ`,i=31,a=Array.from(r).reduce((e,t,n)=>(e[t]=e[t.toLowerCase()]=n,e),{I:r.indexOf(`1`),i:r.indexOf(`1`),L:r.indexOf(`1`),l:r.indexOf(`1`),O:r.indexOf(`0`),o:r.indexOf(`0`),U:r.indexOf(`V`),u:r.indexOf(`V`)}),o=Array.from(r);function s(e){return a[e]}function c(e){return o[e&i]}t.exports=new class extends n{constructor(){super({valid_encoding_pattern:/^[0-7][^\W_]{25}$/})}decodeTrusted(e){let t=new Uint8Array(16),n=[];for(let t=0,r=e.length;t<r;++t)n.push(s(e[t]));return t[0]=n[0]<<5|n[1],t[1]=n[2]<<3|n[3]>>2,t[2]=n[3]<<6|n[4]<<1|n[5]>>4,t[3]=n[5]<<4|n[6]>>1,t[4]=n[6]<<7|n[7]<<2|n[8]>>3,t[5]=n[8]<<5|n[9],t[6]=n[10]<<3|n[11]>>2,t[7]=n[11]<<6|n[12]<<1|n[13]>>4,t[8]=n[13]<<4|n[14]>>1,t[9]=n[14]<<7|n[15]<<2|n[16]>>3,t[10]=n[16]<<5|n[17],t[11]=n[18]<<3|n[19]>>2,t[12]=n[19]<<6|n[20]<<1|n[21]>>4,t[13]=n[21]<<4|n[22]>>1,t[14]=n[22]<<7|n[23]<<2|n[24]>>3,t[15]=n[24]<<5|n[25],t}encodeTrusted(e){let t=[e[0]>>5,e[0],e[1]>>3,e[1]<<2|e[2]>>6,e[2]>>1,e[2]<<4|e[3]>>4,e[3]<<1|e[4]>>7,e[4]>>2,e[4]<<3|e[5]>>5,e[5],e[6]>>3,e[6]<<2|e[7]>>6,e[7]>>1,e[7]<<4|e[8]>>4,e[8]<<1|e[9]>>7,e[9]>>2,e[9]<<3|e[10]>>5,e[10],e[11]>>3,e[11]<<2|e[12]>>6,e[12]>>1,e[12]<<4|e[13]>>4,e[13]<<1|e[14]>>7,e[14]>>2,e[14]<<3|e[15]>>5,e[15]],n=``;for(let e=0,r=t.length;e<r;++e)n+=c(t[e]);return n}}})),gt=y(((e,t)=>{var{BaseCoder:n}=mt(),r=`0123456789ABCDEF`,i=Array.from({length:256}).map((e,t)=>``+r.charAt(t/16)+r.charAt(t%16)),a=Array.from(r).reduce((e,t,n)=>Object.assign(e,{[t.toUpperCase()]:n,[t.toLowerCase()]:n}),Object.create(null));t.exports=new class extends n{constructor(){super({valid_encoding_pattern:/^[0-9A-Fa-f]{32}$/})}decodeTrusted(e){let t=new Uint8Array(16);for(let n=0,r=!0,i=0,o=e.length;i<o;++i){let o=e[i];r?t[n]=a[o]<<4:t[n++]|=a[o],r=!r}return t}encodeTrusted(e){let t=``;for(let n=0,r=e.length;n<r;++n)t+=i[e[n]];return t}}})),_t=y(((e,t)=>{var{BaseCoder:n}=mt(),r=`0123456789ABCDEF`,i=Array.from({length:256}).map((e,t)=>``+r.charAt(t/16)+r.charAt(t%16)),a=Array.from(r).reduce((e,t,n)=>Object.assign(e,{[t.toUpperCase()]:n,[t.toLowerCase()]:n}),Object.create(null));t.exports=new class extends n{constructor(){super({valid_encoding_pattern:/^[0-9A-Fa-f]{4}(?:-?[0-9A-Fa-f]{4}){7}$/})}decodeTrusted(e){let t=new Uint8Array(16);for(let n=0,r=!0,i=0,o=e.length;i<o;++i){let o=e[i];o!==`-`&&(r?t[n]=a[o]<<4:t[n++]|=a[o],r=!r)}return t}encodeTrusted(e){let t=-1;return``+i[e[++t]]+i[e[++t]]+i[e[++t]]+i[e[++t]]+`-`+i[e[++t]]+i[e[++t]]+`-`+i[e[++t]]+i[e[++t]]+`-`+i[e[++t]]+i[e[++t]]+`-`+i[e[++t]]+i[e[++t]]+i[e[++t]]+i[e[++t]]+i[e[++t]]+i[e[++t]]}}})),vt=y(((e,t)=>{var n=Symbol(`id`),r=Symbol(`canonical_coder`),i=Symbol(`raw_coder`);t.exports={IdFactory:class{constructor({id:e,canonical_coder:t,raw_coder:a}={}){this[n]=class extends e{static get name(){return e.name}static get[Symbol.species](){return e}get[Symbol.toStringTag](){return`${e.name} ${this.toRaw()}`}toCanonical(){return t.encodeTrusted(this.bytes)}toRaw(){return a.encodeTrusted(this.bytes)}},this[r]=t,this[i]=a}get name(){return this[n].name}get type(){return this[n][Symbol.species]}construct(e){return new this[n](e)}generate(){return this[n].generate(...arguments)}MIN(){return this[n].MIN(...arguments)}MAX(){return this[n].MAX(...arguments)}fromCanonical(e){return this.construct(this[r].decode(e))}fromCanonicalTrusted(e){return this.construct(this[r].decodeTrusted(e))}fromRaw(e){return this.construct(this[i].decode(e))}fromRawTrusted(e){return this.construct(this[i].decodeTrusted(e))}toCanonical(e){return this[r].encode(e.bytes)}toRaw(e){return this[i].encode(e.bytes)}compare(e,t){return console.warn(`Deprecated: use generic idCompare instead.`),e.compare(t)}equal(e,t){return console.warn(`Deprecated: use generic idEqual instead.`),e.equal(t)}isCanonical(e){return this[r].isValidEncoding(e)}isRaw(e){return this[i].isValidEncoding(e)}}}})),yt=y(((e,t)=>{var{IdFactory:n}=vt(),{UnsupportedVersion:r}=rt(),i=Symbol(`id_by_version`);function a(e,{version:t}={}){return e[i][t]||(()=>{throw new r(`No support for version [${t}]`)})()}t.exports={VersionedIdFactory:class extends n{constructor({abstract_id:e,versioned_ids:t,canonical_coder:r,raw_coder:a}){super({id:e,canonical_coder:r,raw_coder:a}),this[i]=t.reduce((e,t)=>Object.assign(e,{[t.MIN().version]:new n({id:t,canonical_coder:r,raw_coder:a})}),Object.create(null))}get versioned_ids(){return Object.values(this[i])}construct(e){let t=super.construct(e),n=t.version;try{return a(this,{version:n}).construct(e)}catch(e){if(e instanceof r)return t;throw e}}generate(){return a(this,...arguments).generate(...arguments)}MIN(){return a(this,...arguments).MIN()}MAX(){return a(this,...arguments).MAX()}}}})),bt=x(y(((e,t)=>{var{Ulid:n}=ot(),{UlidMonotonic:r}=st(),{Uuid:i}=ct(),{Uuid1:a}=ut(),{Uuid4:o}=dt(),{Uuid6:s}=ft(),{UuidNil:c}=pt(),l=ht(),u=gt(),d=_t(),{IdFactory:f}=vt(),{VersionedIdFactory:p}=yt(),m={idCompare:function(e,t){return e.compare(t)},idEqual:function(e,t){return e.equal(t)},Exception:rt(),Ulid:new f({id:n,canonical_coder:l,raw_coder:u}),UlidMonotonic:new f({id:r,canonical_coder:l,raw_coder:u}),Uuid:new p({abstract_id:i,versioned_ids:[a,o,s,c],canonical_coder:d,raw_coder:u})};m.Uuid.versioned_ids.reduce((e,t)=>Object.assign(e,{[t.name]:t}),m),t.exports=m}))(),1),xt=e=>bt.default.UlidMonotonic.generate({time:e}).toCanonical(),St=async(e,t)=>e.query(async e=>{for await(let[n,r]of e.scan({prefix:w.surface.prefix()}).entries())if(r.key===t)return{id:w.surface.decode(n),...r}}),Ct=async e=>{let{replicache:n,key:r,name:i,description:a,toolList:o,projectId:s,signal:c}=e;return c?.aborted?Error(`Register surface aborted`):t(async()=>{let e=xt();return await n.mutate.surface_upsert_v1({surfaceId:e,projectPublicId:s,key:r,name:i,description:a,toolList:o.map(e=>e.toJSON()),context:{actionedAt:Date.now()}}),await n.push({now:!0}),await n.pull({now:!0}),await St(n,r)||Error(`Surface "${r}" missing from Replicache`)})},wt=class extends Error{name=`RoughClientDestroyedError`;constructor(e=`The Rough client has been destroyed`){super(e)}},Tt=class extends Error{name=`RoughReplicacheIdentityConflictError`;replicacheName;constructor(e){super(`Another Rough client is already using the local database "${e.replicacheName}". Share the existing client through your framework ownership boundary, or await its destroy() before creating a replacement.`),this.replicacheName=e.replicacheName}},Et=class extends Error{name=`RoughSurfaceContractConflictError`;surfaceKey;constructor(e){super(`Surface "${e.surfaceKey}" is already active on this client with a different contract. Close the operations using the old definition before activating the new one.`),this.surfaceKey=e.surfaceKey}},Dt=class extends Error{name=`RoughClientDestroyError`;errors;constructor(e){super(`Rough client destruction finished with ${e.errors.length} error(s): ${e.errors.map(e=>e.message).join(`; `)}`),this.errors=e.errors}},Ot=class extends Error{name=`RoughInvalidClientError`;constructor(e=`Expected a RoughClient created by createRoughClient()`){super(e)}},kt=e=>e instanceof Error?e:Error(String(e)),At=e=>e.reason instanceof Error?e.reason:new wt,jt=e=>new Promise((t,n)=>{if(e.aborted){n(At(e));return}e.addEventListener(`abort`,()=>n(At(e)),{once:!0})}),Mt=e=>new Promise(t=>{if(e.aborted){t();return}e.addEventListener(`abort`,()=>t(),{once:!0})}),Nt=Symbol(`rough.surface.definition`),Pt=(e,t)=>{if(typeof e!=`string`||e.trim()===``)throw TypeError(`defineRoughSurface: "${t}" must be a non-empty string`);return e},Ft=e=>{let t=Pt(e.key,`key`),n=Pt(e.name,`name`),r=Pt(e.description,`description`);if(!Array.isArray(e.tools))throw TypeError(`defineRoughSurface: "tools" must be an array`);for(let t of e.tools)if(typeof t?.toJSON!=`function`)throw TypeError(`defineRoughSurface: every entry in "tools" must be a Query, Mutation or Subscription`);let i={key:t,name:n,description:r,tools:Object.freeze([...e.tools])};return Object.defineProperty(i,Nt,{value:!0,enumerable:!1,writable:!1,configurable:!1}),Object.freeze(i)},It=e=>typeof e==`object`&&!!e&&Nt in e&&e[Nt]===!0,Lt=e=>{if(!It(e))throw TypeError(`Expected a surface created by defineRoughSurface(). Object literals are not accepted because the definition must be validated and frozen.`);return e},Rt=e=>JSON.stringify({key:e.key,name:e.name,description:e.description,tools:e.tools.map(e=>e.toJSON())}),zt=e=>{let{getRuntime:t}=e,n=new Map,r=!1,i=(e,n)=>(async()=>{let r=t();r.assertUsable();let i=await Promise.race([r.getReplicache(),jt(n)]);r.assertUsable();let a=await Ct({replicache:i,projectId:r.projectId,key:e.key,name:e.name,description:e.description,toolList:e.tools,signal:n});if(a instanceof Error)throw a;return{id:a.id}})(),a=(e,t)=>{let r=new AbortController,a={registrationFingerprint:t,activeOperationCount:0,controller:r,resolution:i(e,r.signal)};return a.resolution.catch(()=>{n.get(e.key)===a&&n.delete(e.key)}),a};return{acquire:e=>{let i=Lt(e.surface);if(t().assertUsable(),r)throw new wt;let o=Rt(i),s=n.get(i.key);if(s&&s.registrationFingerprint!==o){if(s.activeOperationCount>0)throw new Et({surfaceKey:i.key});s.controller.abort(Error(`Surface contract replaced`)),n.delete(i.key),s=void 0}s||(s=a(i,o),n.set(i.key,s));let c=s;c.activeOperationCount+=1;let l=!1;return{surfaceKey:i.key,ready:c.resolution,release:()=>{l||(l=!0,c.activeOperationCount=Math.max(c.activeOperationCount-1,0))}}},destroy:async()=>{r=!0;let e=[...n.values()];n.clear();for(let t of e)t.controller.abort(new wt);await Promise.allSettled(e.map(e=>e.resolution))},getActiveOperationCount:e=>n.get(e)?.activeOperationCount??0}},Bt=()=>{let e=new Set;return{register:t=>(e.add(t),()=>{e.delete(t)}),closeAll:async()=>{let t=[...e];e.clear();let n=(await Promise.allSettled(t.map(async e=>{try{await e.close()}catch(t){let n=kt(t);throw n.message=`${e.label}: ${n.message}`,n}}))).flatMap(e=>e.status===`rejected`?[kt(e.reason)]:[]);if(n.length>0)throw new Dt({errors:n})},size:()=>e.size}},Vt=class{#e;constructor(e){this.#e=e}log(e,t,...n){for(let r of this.#e)r.log(e,t,...n)}async flush(){await Promise.all(this.#e.map(e=>e.flush?.()))}},Ht=class{debug=void 0;info=void 0;warn=void 0;error=void 0;flush;#e;#t;constructor(e,t=`info`,n){switch(this.#e=e,this.#t=n,t){case`debug`:this.debug=this.#n;case`info`:this.info=this.#r;case`warn`:this.warn=this.#i;case`error`:this.error=this.#a}this.flush=this.#o}#n(...e){this.#e.log(`debug`,this.#t,...e)}#r(...e){this.#e.log(`info`,this.#t,...e)}#i(...e){this.#e.log(`warn`,this.#t,...e)}#a(...e){this.#e.log(`error`,this.#t,...e)}#o(){return this.#e.flush?.()??Promise.resolve()}},Ut={log(e,t,...n){console[e](...Gt(t),...n.map(Kt))}},Wt=class e extends Ht{#e;#t;#n;constructor(e=`info`,t,n=Ut){super(n,e,t),this.#t=e,this.#e=n,this.#n=t}withContext(t,n){let r={...this.#n,[t]:n};return new e(this.#t,r,this.#e)}};function Gt(e){let t=[];for(let[n,r]of Object.entries(e??{})){let e=r===void 0?n:`${n}=${r}`;t.push(e)}return t}function Kt(e){switch(typeof e){case`string`:case`number`:case`boolean`:case`undefined`:case`symbol`:case`bigint`:return e;case`object`:if(e===null)return null}return JSON.stringify(e,qt)}function qt(e,t){return t instanceof Error?{name:t.name,message:t.message,stack:t.stack,...`cause`in t?{cause:t.cause}:null}:t}function O(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}var Jt=class{_lockP=null;async lock(){let e=this._lockP,{promise:t,resolve:n}=O();return this._lockP=t,await e,n}withLock(e){return Xt(this.lock(),e)}},Yt=class{_lock=new Jt;_writeP=null;_readP=[];read(){return this._lock.withLock(async()=>{await this._writeP;let{promise:e,resolve:t}=O();return this._readP.push(e),t})}withRead(e){return Xt(this.read(),e)}async write(){return await this._lock.withLock(async()=>{await this._writeP,await Promise.all(this._readP);let{promise:e,resolve:t}=O();return this._writeP=e,this._readP=[],t})}withWrite(e){return Xt(this.write(),e)}};async function Xt(e,t){let n=await e;try{return await t()}finally{n()}}var Zt=b({ValitaError:()=>sn,array:()=>nr,bigint:()=>qn,boolean:()=>Zn,err:()=>un,lazy:()=>ar,literal:()=>$n,never:()=>Ln,null:()=>Un,number:()=>Gn,object:()=>er,ok:()=>ln,record:()=>tr,string:()=>Yn,tuple:()=>rr,undefined:()=>Vn,union:()=>ir,unknown:()=>zn});function Qt(e,t){return e?{ok:!1,code:`join`,left:e,right:t}:t}function $t(e,t){return{ok:!1,code:`prepend`,key:e,tree:t}}function en(e,t){let n=e.code;switch(n){case`invalid_type`:return{code:n,path:t,expected:e.expected};case`invalid_literal`:return{code:n,path:t,expected:e.expected};case`missing_value`:return{code:n,path:t};case`invalid_length`:return{code:n,path:t,minLength:e.minLength,maxLength:e.maxLength};case`unrecognized_keys`:return{code:n,path:t,keys:e.keys};case`invalid_union`:return{code:n,path:t,tree:e.tree};case`custom_error`:return{code:n,path:t,error:e.error}}}function tn(e,t=[],n=[]){for(;;)if(e.code===`join`)tn(e.left,t.slice(),n),e=e.right;else if(e.code===`prepend`)t.push(e.key),e=e.tree;else return e.code===`custom_error`&&typeof e.error==`object`&&e.error.path!==void 0&&t.push(...e.error.path),n.push(en(e,t)),n}function nn(e,t){return e.length===0?`nothing`:e.length===1?e[0]:`${e.slice(0,-1).join(`, `)} ${t} ${e[e.length-1]}`}function rn(e){return typeof e==`bigint`?`${e}n`:JSON.stringify(e)}function an(e){let t=0;for(;;)if(e.code===`join`)t+=an(e.left),e=e.right;else if(e.code===`prepend`)e=e.tree;else return t+1}function on(e){let t=``,n=0;for(;;)if(e.code===`join`)n+=an(e.right),e=e.left;else if(e.code===`prepend`)t+=`.${e.key}`,e=e.tree;else break;let r=`validation failed`;if(e.code===`invalid_type`)r=`expected ${nn(e.expected,`or`)}`;else if(e.code===`invalid_literal`)r=`expected ${nn(e.expected.map(rn),`or`)}`;else if(e.code===`missing_value`)r=`missing value`;else if(e.code===`unrecognized_keys`){let t=e.keys;r=`unrecognized ${t.length===1?`key`:`keys`} ${nn(t.map(rn),`and`)}`}else if(e.code===`invalid_length`){let t=e.minLength,n=e.maxLength;r=`expected an array with `,r+=t>0?n===t?`${t}`:n===void 0?`at least ${t}`:`between ${t} and ${n}`:`at most ${n??`∞`}`,r+=` item(s)`}else if(e.code===`custom_error`){let n=e.error;typeof n==`string`?r=n:n!==void 0&&(n.message!==void 0&&(r=n.message),n.path!==void 0&&(t+=`.`+n.path.join(`.`)))}let i=`${e.code} at .${t.slice(1)} (${r})`;return n===1?i+=` (+ 1 other issue)`:n>1&&(i+=` (+ ${n} other issues)`),i}var sn=class extends Error{constructor(e){super(on(e)),this.issueTree=e,Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name,this._issues=void 0}get issues(){return this._issues===void 0&&(this._issues=tn(this.issueTree)),this._issues}},cn=class{constructor(e){this.issueTree=e,this.ok=!1,this._issues=void 0,this._message=void 0}get issues(){return this._issues===void 0&&(this._issues=tn(this.issueTree)),this._issues}get message(){return this._message===void 0&&(this._message=on(this.issueTree)),this._message}throw(){throw new sn(this.issueTree)}};function ln(e){return{ok:!0,value:e}}function un(e){return new cn({ok:!1,code:`custom_error`,error:e})}function dn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var fn=1,pn=2,mn=4,hn=class{optional(e){let t=new _n(this);return e?new Pn(t,t=>t===void 0?{ok:!0,value:e()}:void 0):t}default(e){let t=ln(e);return new Pn(this.optional(),e=>e===void 0?t:void 0)}assert(e,t){let n={ok:!1,code:`custom_error`,error:t};return new Pn(this,(t,r)=>e(t,r)?void 0:n)}map(e){return new Pn(this,(t,n)=>({ok:!0,value:e(t,n)}))}chain(e){return new Pn(this,(t,n)=>{let r=e(t,n);return r.ok?r:r.issueTree})}},k=class extends hn{nullable(){return new gn(this)}toTerminals(e){e(this)}try(e,t){let n=fn;t?.mode===`passthrough`?n=0:t?.mode===`strip`&&(n=pn);let r=this.func(e,n);return r===void 0?{ok:!0,value:e}:r.ok?{ok:!0,value:r.value}:new cn(r)}parse(e,t){let n=fn;t?.mode===`passthrough`?n=0:t?.mode===`strip`&&(n=pn);let r=this.func(e,n);if(r===void 0)return e;if(r.ok)return r.value;throw new sn(r)}},gn=class extends k{constructor(e){super(),this.type=e,this.name=`nullable`}func(e,t){return e===null?void 0:this.type.func(e,t)}toTerminals(e){e(Hn),this.type.toTerminals(e)}nullable(){return this}},_n=class extends hn{constructor(e){super(),this.type=e,this.name=`optional`}func(e,t){return e===void 0||t&mn?void 0:this.type.func(e,t)}toTerminals(e){e(this),e(Bn),this.type.toTerminals(e)}optional(e){return e?new Pn(this,t=>t===void 0?{ok:!0,value:e()}:void 0):this}};function vn(e,t){if(typeof e!=`number`){let n=t>>5;for(let t=e.length;t<=n;t++)e.push(0);return e[n]|=1<<t%32,e}return t<32?e|1<<t:vn([e,0],t)}function yn(e,t){return typeof e==`number`?t<32?e>>>t&1:0:e[t>>5]>>>t%32&1}var bn=class e extends k{constructor(e,t,n){super(),this.shape=e,this.restType=t,this.checks=n,this.name=`object`,this._invalidType={ok:!1,code:`invalid_type`,expected:[`object`]}}check(t,n){let r={ok:!1,code:`custom_error`,error:n};return new e(this.shape,this.restType,[...this.checks??[],{func:t,issue:r}])}func(e,t){if(!dn(e))return this._invalidType;let n=this._func;return n===void 0&&(n=xn(this.shape,this.restType,this.checks),this._func=n),n(e,t)}rest(t){return new e(this.shape,t)}extend(t){return new e(Object.assign(Object.assign({},this.shape),t),this.restType)}pick(...t){let n={};return t.forEach(e=>{n[e]=this.shape[e]}),new e(n,void 0)}omit(...t){let n=Object.assign({},this.shape);return t.forEach(e=>{delete n[e]}),new e(n,this.restType)}partial(){let t={};Object.keys(this.shape).forEach(e=>{t[e]=this.shape[e].optional()});let n=this.restType?.optional();return new e(t,n)}};function xn(e,t,n){let r=[],i=[];for(let t in e){let n=!1;e[t].toTerminals(e=>{n||=e.name===`optional`}),n?i.push(t):r.push(t)}let a=[...r,...i],o=a.length;if(o===0&&t?.name===`unknown`)return function(e,t){if(n!==void 0){for(let t=0;t<n.length;t++)if(!n[t].func(e))return n[t].issue}};let s=a.map(t=>e[t]),c=r.length,l=Object.create(null);a.forEach((e,t)=>{l[e]=~t});let u=r.map(e=>$t(e,{ok:!1,code:`missing_value`}));function d(e,t,n){t===`__proto__`?Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0}):e[t]=n}return function(e,r){let i=!1,f=e,p,m,h=0,g=0;if(r&fn||r&pn||t!==void 0)for(let n in e){let c=e[n],u=~l[n],_;if(u>=0)g++,h=vn(h,u),_=s[u].func(c,r);else if(t!==void 0)_=t.func(c,r);else{if(r&fn)m===void 0?m=[n]:m.push(n);else if(r&pn&&p===void 0&&!i){f={},i=!0;for(let t=0;t<o;t++)if(yn(h,t)){let n=a[t];d(f,n,e[n])}}continue}if(_===void 0)i&&p===void 0&&d(f,n,c);else if(!_.ok)p=Qt(p,$t(n,_));else if(p===void 0){if(!i){if(f={},i=!0,t===void 0){for(let t=0;t<o;t++)if(t!==u&&yn(h,t)){let n=a[t];d(f,n,e[n])}}else for(let t in e)d(f,t,e[t])}d(f,n,_.value)}}if(g<o)for(let n=0;n<o;n++){if(yn(h,n))continue;let l=a[n],m=e[l],g=r&-5;if(m===void 0&&!(l in e)){if(n<c){p=Qt(p,u[n]);continue}g|=mn}let _=s[n].func(m,g);if(_===void 0)i&&p===void 0&&!(g&mn)&&d(f,l,m);else if(!_.ok)p=Qt(p,$t(l,_));else if(p===void 0){if(!i){if(f={},i=!0,t===void 0){for(let t=0;t<o;t++)if(t<n||yn(h,t)){let n=a[t];d(f,n,e[n])}}else{for(let t in e)d(f,t,e[t]);for(let t=0;t<n;t++)if(!yn(h,t)){let n=a[t];d(f,n,e[n])}}}d(f,l,_.value)}}if(m!==void 0&&(p=Qt(p,{ok:!1,code:`unrecognized_keys`,keys:m})),p===void 0&&n!==void 0){for(let e=0;e<n.length;e++)if(!n[e].func(f))return n[e].issue}return p===void 0&&i?{ok:!0,value:f}:p}}var Sn=class e extends k{constructor(e,t,n){super(),this.prefix=e,this.rest=t,this.suffix=n,this.name=`array`,this.restType=t??Ln(),this.minLength=this.prefix.length+this.suffix.length,this.maxLength=t?void 0:this.minLength,this.invalidType={ok:!1,code:`invalid_type`,expected:[`array`]},this.invalidLength={ok:!1,code:`invalid_length`,minLength:this.minLength,maxLength:this.maxLength}}func(e,t){if(!Array.isArray(e))return this.invalidType;let n=e.length,r=this.minLength,i=this.maxLength??1/0;if(n<r||n>i)return this.invalidLength;let a=this.prefix.length,o=e.length-this.suffix.length,s,c=e;for(let n=0;n<e.length;n++){let r=(n<a?this.prefix[n]:n>=o?this.suffix[n-o]:this.restType).func(e[n],t);r!==void 0&&(r.ok?(c===e&&(c=e.slice()),c[n]=r.value):s=Qt(s,$t(n,r)))}return s||(e===c?void 0:{ok:!0,value:c})}concat(t){if(this.rest){if(t.rest)throw TypeError(`can not concatenate two variadic types`);return new e(this.prefix,this.rest,[...this.suffix,...t.prefix,...t.suffix])}return t.rest?new e([...this.prefix,...this.suffix,...t.prefix],t.rest,t.suffix):new e([...this.prefix,...this.suffix,...t.prefix,...t.suffix],t.rest,t.suffix)}};function Cn(e){let t=typeof e;return t===`object`?e===null?`null`:Array.isArray(e)?`array`:t:t}function wn(e){return Array.from(new Set(e))}function Tn(e){let t=new Map;e.forEach(e=>{for(let n in e)t.set(n,(t.get(n)??0)+1)});let n=[];return t.forEach((t,r)=>{t===e.length&&n.push(r)}),n}function En(e){let t=new Map,n=new Map,r=new Map,i=[],a=[],o=[];e.forEach(({root:e,terminal:s})=>{if(t.set(e,t.get(e)??t.size),s.name!==`never`){if(s.name===`optional`)a.push(e);else if(s.name===`unknown`)i.push(e);else if(s.name===`literal`){let t=n.get(s.value)??[];t.push(e),n.set(s.value,t),o.push(Cn(s.value))}else{let t=r.get(s.name)??[];t.push(e),r.set(s.name,t),o.push(s.name)}}}),n.forEach((e,t)=>{let i=r.get(Cn(t));i&&(i.push(...e),n.delete(t))});let s=(e,n)=>(t.get(e)??0)-(t.get(n)??0);return r.forEach((e,t)=>r.set(t,wn(e.concat(i).sort(s)))),n.forEach((e,t)=>n.set(t,wn(e.concat(i)).sort(s))),{types:r,literals:n,unknowns:wn(i).sort(s),optionals:wn(a).sort(s),expectedTypes:wn(o)}}function Dn(e,t){let n=[];for(let{root:r,terminal:i}of e)i.shape[t].toTerminals(e=>n.push({root:r,terminal:e}));let{types:r,literals:i,optionals:a,unknowns:o,expectedTypes:s}=En(n);if(o.length>0||a.length>1)return;for(let e of i.values())if(e.length>1)return;for(let e of r.values())if(e.length>1)return;let c=$t(t,{ok:!1,code:`missing_value`}),l=$t(t,r.size===0?{ok:!1,code:`invalid_literal`,expected:Array.from(i.keys())}:{ok:!1,code:`invalid_type`,expected:s}),u=i.size>0?new Map:void 0;for(let[e,t]of i)u.set(e,t[0]);let d=r.size>0?{}:void 0;for(let[e,t]of r)d[e]=t[0];return function(e,n){let r=e,i=r[t];if(i===void 0&&!(t in r))return a.length>0?a[0].func(r,n):c;let o=d?.[Cn(i)]??u?.get(i);return o?o.func(r,n):l}}function On(e){if(e.some(({terminal:e})=>e.name===`unknown`))return;let t=e.filter(e=>e.terminal.name===`object`);if(t.length<2)return;let n=t.map(({terminal:e})=>e.shape);for(let e of Tn(n)){let n=Dn(t,e);if(n)return n}}function kn(e){let{expectedTypes:t,literals:n,types:r,unknowns:i,optionals:a}=En(e),o=r.size===0&&i.length===0?{ok:!1,code:`invalid_literal`,expected:Array.from(n.keys())}:{ok:!1,code:`invalid_type`,expected:t},s=n.size>0?n:void 0,c=r.size>0?{}:void 0;for(let[e,t]of r)c[e]=t;return function(e,t){let n=t&mn?a:c?.[Cn(e)]??s?.get(e)??i,r=0,l=o;for(let i=0;i<n.length;i++){let a=n[i].func(e,t);if(a===void 0||a.ok)return a;l=r>0?Qt(l,a):a,r++}return r>1?{ok:!1,code:`invalid_union`,tree:l}:l}}var An=class extends k{constructor(e){super(),this.options=e,this.name=`union`}toTerminals(e){this.options.forEach(t=>{t.toTerminals(e)})}func(e,t){let n=this._func;if(n===void 0){let e=[];this.options.forEach(t=>{t.toTerminals(n=>{e.push({root:t,terminal:n})})});let t=kn(e),r=On(e);n=r?function(e,n){return dn(e)?r(e,n):t(e,n)}:t,this._func=n}return n(e,t)}},jn=Object.freeze({mode:`strict`}),Mn=Object.freeze({mode:`strip`}),Nn=Object.freeze({mode:`passthrough`}),Pn=class e extends k{constructor(e,t){super(),this.transformed=e,this.transform=t,this.name=`transform`,this.undef=ln(void 0),this.transformChain=void 0,this.transformRoot=void 0}func(t,n){let r=this.transformChain;if(!r){r=[];let t=this;for(;t instanceof e;)r.push(t.transform),t=t.transformed;r.reverse(),this.transformChain=r,this.transformRoot=t}let i=this.transformRoot.func(t,n);if(i!==void 0&&!i.ok)return i;let a;i===void 0?n&mn?(a=void 0,i=this.undef):a=t:a=i.value;let o=n&fn?jn:n&pn?Mn:Nn;for(let e=0;e<r.length;e++){let t=r[e](a,o);if(t!==void 0){if(!t.ok)return t;a=t.value,i=t}}return i}toTerminals(e){this.transformed.toTerminals(e)}},Fn=class extends k{constructor(e){super(),this.definer=e,this.name=`lazy`,this.recursing=!1}func(e,t){return this.type||=this.definer(),this.type.func(e,t)}toTerminals(e){if(!this.recursing)try{this.recursing=!0,this.type||=this.definer(),this.type.toTerminals(e)}finally{this.recursing=!1}}},In=new class extends k{constructor(){super(...arguments),this.name=`never`,this.issue={ok:!1,code:`invalid_type`,expected:[]}}func(e,t){return this.issue}};function Ln(){return In}var Rn=new class extends k{constructor(){super(...arguments),this.name=`unknown`}func(e,t){}};function zn(){return Rn}var Bn=new class extends k{constructor(){super(...arguments),this.name=`undefined`,this.issue={ok:!1,code:`invalid_type`,expected:[`undefined`]}}func(e,t){return e===void 0?void 0:this.issue}};function Vn(){return Bn}var Hn=new class extends k{constructor(){super(...arguments),this.name=`null`,this.issue={ok:!1,code:`invalid_type`,expected:[`null`]}}func(e,t){return e===null?void 0:this.issue}};function Un(){return Hn}var Wn=new class extends k{constructor(){super(...arguments),this.name=`number`,this.issue={ok:!1,code:`invalid_type`,expected:[`number`]}}func(e,t){return typeof e==`number`?void 0:this.issue}};function Gn(){return Wn}var Kn=new class extends k{constructor(){super(...arguments),this.name=`bigint`,this.issue={ok:!1,code:`invalid_type`,expected:[`bigint`]}}func(e,t){return typeof e==`bigint`?void 0:this.issue}};function qn(){return Kn}var Jn=new class extends k{constructor(){super(...arguments),this.name=`string`,this.issue={ok:!1,code:`invalid_type`,expected:[`string`]}}func(e,t){return typeof e==`string`?void 0:this.issue}};function Yn(){return Jn}var Xn=new class extends k{constructor(){super(...arguments),this.name=`boolean`,this.issue={ok:!1,code:`invalid_type`,expected:[`boolean`]}}func(e,t){return typeof e==`boolean`?void 0:this.issue}};function Zn(){return Xn}var Qn=class extends k{constructor(e){super(),this.value=e,this.name=`literal`,this.issue={ok:!1,code:`invalid_literal`,expected:[e]}}func(e,t){return e===this.value?void 0:this.issue}};function $n(e){return new Qn(e)}function er(e){return new bn(e,void 0)}function tr(e){return new bn({},e??zn())}function nr(e){return new Sn([],e??zn(),[])}function rr(e){return new Sn(e,void 0,[])}function ir(...e){return new An(e)}function ar(e){return new Fn(e)}var or=Object.defineProperty,sr=Object.getOwnPropertyDescriptor,cr=Object.getOwnPropertyNames,lr=Object.prototype.hasOwnProperty,ur=(e,t)=>{for(var n in t)or(e,n,{get:t[n],enumerable:!0})},dr=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let i of cr(t))!lr.call(e,i)&&i!==n&&or(e,i,{get:()=>t[i],enumerable:!(r=sr(t,i))||r.enumerable});return e},fr=(e,t,n)=>(dr(e,t,`default`),n&&dr(n,t,`default`)),pr=class extends Error{name=`AbortError`};function A(e,t=`Assertion failed`){if(!e)throw Error(t)}function j(e){hr(e,`string`)}function M(e){hr(e,`number`)}function mr(e){hr(e,`boolean`)}function hr(e,t){typeof e!==t&&vr(e,t)}function N(e){e===null&&vr(e,`object`),hr(e,`object`)}function gr(e){Array.isArray(e)||vr(e,`array`)}function _r(e,t){let n=`Invalid type: `;return n+=e==null?e:`${typeof e} \`${e}\``,n+`, expected ${t}`}function vr(e,t){throw Error(_r(e,t))}function yr(e){if(e===null)throw Error(`Expected non-null value`)}function br(e,t=`Expected non undefined value`){if(e===void 0)throw Error(t)}function xr(e){throw Error(`Unreachable`)}function Sr(){return typeof document<`u`?document:void 0}function Cr(e,t,n){return e?new wr(e,t,n):new Dr}var wr=class{#e;#t;#n=0;visibilityState;#r=new Set;constructor(e,t,n){this.#e=e,this.#t=t,this.visibilityState=e.visibilityState,this.#e.addEventListener(`visibilitychange`,this.#i,{signal:n})}#i=()=>{this.#e.visibilityState===`visible`?(clearTimeout(this.#n),this.#a(`visible`)):this.#n=setTimeout(()=>{this.#a(`hidden`)},this.#t)};#a(e){if(e!==this.visibilityState){this.visibilityState=e;for(let t of this.#r){let{resolve:n,state:r}=t;r===e&&(n(),this.#r.delete(t))}}}waitForVisible(){return this.#o(`visible`)}waitForHidden(){return this.#o(`hidden`)}#o(e){if(this.visibilityState===e)return Promise.resolve();let{promise:t,resolve:n}=O();return this.#r.add({resolve:n,state:e}),t}},Tr=Promise.resolve(),Er=new Promise(()=>{}),Dr=class{visibilityState=`visible`;waitForVisible(){return Tr}waitForHidden(){return Er}},Or=class{rep;invokeSend;maxConnections=1;constructor(e,t){this.rep=e,this.invokeSend=t}get maxDelayMs(){return this.rep.requestOptions.maxDelayMs}get minDelayMs(){return this.rep.requestOptions.minDelayMs}},kr=class extends Or{debounceDelay=0;get watchdogTimer(){return this.rep.pullInterval}},Ar=class extends Or{get debounceDelay(){return this.rep.pushDelay}watchdogTimer=null},jr=Promise.resolve();new Promise(()=>{});function Mr(e,t){return e===0?jr:new Promise((n,r)=>{let i;t&&(i=()=>{clearTimeout(a),r(new pr(`Aborted`))},t.addEventListener(`abort`,i,{once:!0}));let a=setTimeout(()=>{n(),t?.removeEventListener(`abort`,i)},e)})}var Nr=30,Pr=6e4,Fr=class{#e=O();#t=O();#n=O();#r;#i=!1;#a=0;#o;#s;constructor(e,t,n){this.#o=e,this.#r=t,this.#s=n,this.run()}close(){this.#i=!0,this.#a>0&&this.#n.resolve({error:Lr()})}async send(e){if(this.#i)return{error:Lr()};this.#a++,this.#o.debug?.(`send`,e),e?this.#t.resolve():await this.#s?.waitForVisible(),this.#e.resolve();let t=await this.#n.promise;return this.#a--,t}async run(){let e=[],t=O(),n,r=0,i=this.#r,{debug:a}=this.#o,o=0;a?.(`Starting connection loop`);let s=e=>Promise.race([this.#t.promise,Mr(e)]);for(;!this.#i;){a?.(Br(e)?`Last request failed. Trying again`:`Waiting for a send`);let c=[this.#e.promise],l=i.watchdogTimer;if(l!==null&&c.push(Mr(l)),await Promise.race(c),this.#i||(a?.(`Waiting for debounce`),await s(i.debounceDelay),this.#i))break;if(a?.(`debounced`),this.#e=O(),r>=i.maxConnections){if(a?.(`Too many request in flight. Waiting until one finishes...`),await this.#u(),this.#i)break;a?.(`...finished`)}r>0||Br(e)?(o=Rr(o,i,e),a?.(Br(e)?`Last connection errored. Sleeping for`:`More than one outstanding connection (`+r+`). Sleeping for`,o,`ms`)):o=0;let u=Math.min(i.maxDelayMs,Math.max(i.minDelayMs,o));if(n!==void 0){let e=Date.now()-n;if(u>e&&(await Promise.race([s(u-e),t.promise]),this.#i))break}r++,(async()=>{let o=Date.now(),s,c;try{n=o,a?.(`Sending request`),this.#t=O(),s=await i.invokeSend(),a?.(`Send returned`,s)}catch(e){a?.(`Send failed`,e),c=e,s=!1}if(this.#i){a?.(`Closed after invokeSend`);return}a?.(`Request done`,{duration:Date.now()-o,ok:s}),e.push({duration:Date.now()-o,ok:s}),Vr(e)&&(t.resolve(),t=O()),r--,this.#l();let l=this.#n;this.#n=O(),c?l.resolve({error:c}):l.resolve(void 0),s||this.#e.resolve()})()}}#c=void 0;#l(){if(this.#c){let e=this.#c;this.#c=void 0,e()}}#u(){let{promise:e,resolve:t}=O();return this.#c=t,e}},Ir=9;function Lr(){return Error(`Closed`)}function Rr(e,t,n){let{length:r}=n;if(r===0)return e;let{ok:i}=n[n.length-1],{maxConnections:a,minDelayMs:o}=t;if(!i)return e===0?o:e*2;if(r>1){let e=n[n.length-2];for(;n.length>Ir;)n.shift();if(i&&!e.ok)return o}return zr(n.filter(({ok:e})=>e).map(({duration:e})=>e))/a|0}function zr(e){e.sort();let{length:t}=e,n=t>>1;return t%2==1?e[n]:(e[n-1]+e[n])/2}function Br(e){return e.length>0&&!e[e.length-1].ok}function Vr(e){return e.length>1&&!e[e.length-2].ok&&e[e.length-1].ok}var Hr=process.env.NODE_ENV===`production`,Ur=Object.prototype.hasOwnProperty,Wr=Object.hasOwn||((e,t)=>Ur.call(e,t));function Gr(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;switch(typeof e){case`boolean`:case`number`:case`string`:return!1}if(e=e,Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!Gr(e[n],t[n]))return!1;return!0}if(e===null||t===null||Array.isArray(t))return!1;e=e,t=t;let n=0;for(let r in e)if(Wr(e,r)){if(!Gr(e[r],t[r]))return!1;n++}let r=0;for(let e in t)Wr(t,e)&&r++;return n===r}function Kr(e){if(!Hr){switch(typeof e){case`boolean`:case`number`:case`string`:return;case`object`:return e===null?void 0:Array.isArray(e)?Yr(e):Jr(e)}vr(e,`JSON value`)}}function qr(e){N(e),Jr(e)}function Jr(e){for(let t in e)if(Wr(e,t)){let n=e[t];n!==void 0&&Kr(n)}}function Yr(e){for(let t of e)Kr(t)}function Xr(e,t){switch(typeof e){case`boolean`:case`number`:case`string`:return!0;case`object`:return e===null?!0:Array.isArray(e)?$r(e,t):Qr(e,t)}return!1}function Zr(e,t){return typeof e!=`object`||!e?!1:Qr(e,t)}function Qr(e,t){for(let n in e)if(Wr(e,n)){t.push(n);let r=e[n];if(r!==void 0&&!Xr(r,t))return!1;t.pop()}return!0}function $r(e,t){for(let n=0;n<e.length;n++){if(t.push(n),!Xr(e[n],t))return!1;t.pop()}return!0}function ei(e,t){return e===t?0:e<t?-1:1}function ti(e,t){if(e===t)return 0;if(e===null)return-1;if(t===null)return 1;let n=ni(e),r=ni(t);return typeof n==`string`||typeof r==`string`?ei(String(n),String(r)):n-r}function ni(e){return typeof e==`string`||typeof e==`number`?e:e.order}function ri(e){if(e!==null&&typeof e!=`string`&&typeof e!=`number`&&(qr(e),typeof e.order!=`string`&&typeof e.order!=`number`))throw Error(`Invalid cookie`)}function*ii(...e){for(let t of e)yield*t}var ai=Promise.resolve(!0),oi=Promise.resolve(!1);Promise.resolve(void 0);var si=Promise.resolve(),ci=1,li=4,ui=5,di=8;function fi(e){switch(typeof e){case`string`:return ci+li+e.length;case`number`:return pi(e)?e<=-(2**30)||e>=2**30-1?ci+ui:ci+li:ci+di;case`boolean`:return ci;case`object`:if(e===null)return ci;if(Array.isArray(e)){let t=2*ci+li;for(let n of e)t+=fi(n);return t}{let t=e,n=2*ci+li;for(let e in t)if(Wr(t,e)){let r=t[e];r!==void 0&&(n+=fi(e)+fi(r))}return n}}throw Error(`Invalid value. type: ${typeof e}, value: ${e}`)}function pi(e){return e===(e|0)}var mi=2*ci+li+ci+li;function hi(e,t){return mi+fi(e)+fi(t)}var gi=new WeakSet;function _i(e){return Hr||vi(e,[]),e}function vi(e,t){switch(typeof e){case`undefined`:throw TypeError(`Unexpected value undefined`);case`boolean`:case`number`:case`string`:return;case`object`:if(e===null||gi.has(e))return;gi.add(e),t.includes(e)&&vr(e,`Cyclic JSON object`),t.push(e),Object.freeze(e),Array.isArray(e)?yi(e,t):bi(e,t),t.pop();return;default:vr(e,`JSON value`)}}function yi(e,t){for(let n of e)vi(n,t)}function bi(e,t){for(let n in e)if(Wr(e,n)){let r=e[n];r!==void 0&&vi(r,t)}}function xi(e){if(!Hr&&!Si(e,[]))throw Error(`Expected frozen object`)}function Si(e,t){switch(typeof e){case`boolean`:case`number`:case`string`:return!0;case`object`:if(e===null||gi.has(e))return!0;if(!Object.isFrozen(e))return!1;if(t.includes(e)&&vr(e,`Cyclic JSON object`),t.push(e),Array.isArray(e)){for(let n of e)if(!Si(n,t))return t.pop(),!1}else for(let n in e)if(Wr(e,n)){let r=e[n];if(r!==void 0&&!Si(r,t))return t.pop(),!1}return gi.add(e),t.pop(),!0;default:vr(e,`JSON value`)}}function Ci(e){if(e!==void 0)return _i(e)}function wi(e){if(Array.isArray(e)){e.sort();for(let t=1;t<e.length;t++)A(e[t-1]!==e[t],`Refs must not have duplicates`);return e}let t=[...e];return t.sort(),t}var Ti=class{hash;data;meta;constructor(e,t,n){A(!n.includes(e),`Chunk cannot reference itself`),xi(t),this.hash=e,this.data=t,this.meta=n}};function Ei(e){if(!Array.isArray(e))throw Error(`Refs must be an array`);if(e.length>0){j(e[0]);for(let t=1;t<e.length;t++)j(e[t])}}function Di(e,t,n){return new Ti(n(),e,t)}function Oi(){throw Error(`unexpected call to compute chunk hash`)}function ki(){let e=Math.floor(Math.random()*4294967295),t=Math.floor(Math.random()*4294967295);return BigInt(e)<<32n|BigInt(t)}var P={};ur(P,{assert:()=>Ii,is:()=>Fi,parse:()=>Pi,readonly:()=>Ri,readonlyArray:()=>Bi,readonlyObject:()=>zi,readonlyRecord:()=>Vi,test:()=>Li}),fr(P,Zt);function Ai(e){switch(typeof e){case`string`:case`number`:case`boolean`:return JSON.stringify(e);case`undefined`:return`undefined`;case`bigint`:return e.toString()+`n`;default:return e===null?`null`:Array.isArray(e)?`array`:typeof e}}function ji(e,t){if(!t?.length)return Ai(e);let n=e;for(let e of t)n=n[e];return Ai(n)}function Mi(e,t,n=e=>String(e)){if(t.length===1)return n(t[0]);let r=`${n(t[t.length-2])} ${e} ${n(t[t.length-1])}`;return t.length===2?r:`${t.slice(0,-2).map(n).join(`, `)}, ${r}`}function Ni(e,t){let n=e.issues[0],{path:r}=n,i=r?.length?` at ${r.join(`.`)}`:``;switch(n.code){case`invalid_type`:return`Expected ${Mi(`or`,n.expected)}${i}. Got ${ji(t,r)}`;case`missing_value`:{let e=r&&r.length>1?` at ${r.slice(0,-1).join(`.`)}`:``;return n.path?.length?`Missing property ${n.path.at(-1)}${e}`:`TODO Unknown missing property${e}`}case`invalid_literal`:return`Expected literal value ${Mi(`or`,n.expected,Ai)}${i} Got ${ji(t,r)}`;case`invalid_length`:return`Expected array with length ${n.minLength===n.maxLength?n.minLength:`between ${n.minLength} and ${n.maxLength}`}${i}. Got array with length ${t.length}`;case`unrecognized_keys`:return n.keys.length===1?`Unexpected property ${n.keys[0]}${i}`:`Unexpected properties ${Mi(`and`,n.keys)}${i}`;case`invalid_union`:return`Invalid union value${i}`;case`custom_error`:{let{error:e}=n;return`${e?typeof e==`string`?e:e.message??`unknown`:`unknown`}${i}. Got ${ji(t,r)}`}}}function Pi(e,t,n){let r=Li(e,t,n);if(!r.ok)throw TypeError(r.error);return r.value}function Fi(e,t,n){return Li(e,t,n).ok}function Ii(e,t,n){Pi(e,t,n)}function Li(e,t,n){let r=t.try(e,n?{mode:n}:void 0);return r.ok?r:{ok:!1,error:Ni(r,e)}}function Ri(e){return e}function zi(e){return er(e)}function Bi(e){return nr(e)}function Vi(e){return tr(e)}var Hi=22,Ui=/^[0-9a-v-]+$/,F=`0`.repeat(Hi),Wi=Ki();function Gi(e,t){return e.toString(32).slice(-t).padStart(t,`0`)}function Ki(){let e=``,t=0;return()=>{e||=Gi(ki(),12);let n=Gi(t++,10);return e+n}}function qi(e){return typeof e==`string`&&Ui.test(e)}function Ji(e){Ii(e,Yi)}var Yi=P.string().assert(qi,`Invalid hash`);function Xi(e,t,n){return new Zi(e,t,n).compute()}var Zi=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e,t,n){let r=[],i=[];for(let t of e)t.old!==t.new&&(t.old&&i.push(t.old),t.new&&r.push(t.new));this.#e=r,this.#t=i,this.#n=t,this.#r=n,this.#a=new Map,this.#o=new Map,this.#s=n.areRefsCounted!==void 0,this.#i=this.#s?new Set:null}async compute(){for(let e of this.#e)await this.#c(e,1);if(await Promise.all(Array.from(this.#n.values(),e=>this.#u(e))),this.#s){A(this.#r.areRefsCounted),A(this.#i);let e;do{e=!1;for(let t of this.#n.values())if(!this.#r.areRefsCounted(t)&&!this.#i.has(t)&&this.#a.get(t)!==0){await this.#l(t,1),e=!0;break}}while(e)}for(let e of this.#t)await this.#c(e,-1);if(!Hr)for(let[e,t]of this.#a)A(t>=0,`ref count update must be non-negative. ${e}:${t}`);return this.#a}async#c(e,t){await this.#u(e),this.#d(e,t)&&await this.#l(e,t)}async#l(e,t){if(e===F)return;let n=await this.#r.getRefs(e);if(Hr||A(n||this.#s&&!this.#n.has(e),`refs must be defined`),n!==void 0){this.#i?.add(e);let r=n.map(e=>this.#c(e,t));await Promise.all(r)}}#u(e){let t=this.#o.get(e);return t===void 0&&(t=(async()=>{let t=await this.#r.getRefCount(e)||0;return this.#a.set(e,t),t})(),this.#o.set(e,t)),t}#d(e,t){let n=this.#a.get(e);return M(n),this.#a.set(e,n+t),n===0&&t===1||n===1&&t===-1}},Qi=class extends Error{name=`ChunkNotFoundError`;hash;constructor(e){super(`Chunk not found ${e}`),this.hash=e}};async function $i(e,t){let n=await e.getChunk(t);if(n)return n;throw new Qi(t)}async function ea(e,t){let n=await t.getHead(e);return A(n,`Missing head ${e}`),n}var ta=class{#e=new Yt;#t=new Map;#n;#r;#i;t=new Map;n;h=new Map;m=new Map;constructor(e,t,n,r,i=fi){this.n=new ia(t,i,this.h,this.m),this.#n=e,this.#r=n,this.#i=r}async read(){let e=await this.#e.read();return new na(this.#t,this.t,this.n,this.#n,e,this.#i)}async write(){let e=await this.#e.write();return new ra(this.#t,this.t,this.n,this.#n,this.h,this.m,e,this.#r,this.#i)}close(){return si}isCached(e){return this.n.getWithoutUpdatingLRU(e)!==void 0}withSuspendedSourceCacheEvictsAndDeletes(e){return this.n.withSuspendedEvictsAndDeletes(e)}},na=class{a;t;n;f;#e=void 0;#t;#n=!1;assertValidHash;constructor(e,t,n,r,i,a){this.a=e,this.t=t,this.n=n,this.f=r,this.#t=i,this.assertValidHash=a}isMemOnlyChunkHash(e){return this.t.has(e)}async hasChunk(e){return await this.getChunk(e)!==void 0}async getChunk(e){let t=this.t.get(e);if(t!==void 0)return t;let n=this.n.get(e);return n===void 0&&(n=await(await this.y()).getChunk(e),n!==void 0&&this.n.put(n)),n}mustGetChunk(e){return $i(this,e)}getHead(e){return Promise.resolve(this.a.get(e))}release(){this.#n||=(this.#t(),this.#e?.then(e=>e.release()).catch(e=>{}),!0)}get closed(){return this.#n}y(){return this.#e||=this.f.read(),this.#e}},ra=class extends na{#e;#t;#n;i=new Map;o=new Map;s=new Map;#r=new Set;constructor(e,t,n,r,i,a,o,s,c){super(e,t,n,r,o,c),this.#e=i,this.#t=a,this.#n=s}createChunk=(e,t)=>{let n=Di(e,t,this.#n);return this.#r.add(n.hash),n};putChunk(e,t){let{hash:n,meta:r}=e;if(this.assertValidHash(n),r.length>0)for(let e of r)this.assertValidHash(e);return this.#r.has(n)||this.isMemOnlyChunkHash(n)?this.o.set(n,e):this.s.set(n,{chunk:e,size:t??-1}),si}async setHead(e,t){await this.#i(e,t)}async removeHead(e){await this.#i(e,void 0)}async#i(e,t){let n=await this.getHead(e),r=this.i.get(e);r===void 0?this.i.set(e,{new:t,old:n}):r.new=t}isMemOnlyChunkHash(e){return this.o.has(e)||super.isMemOnlyChunkHash(e)}async getChunk(e){let t=this.o.get(e);if(t!==void 0)return t;let n=this.t.get(e);if(n!==void 0)return n;let r=this.s.get(e);if(r!==void 0)return r.chunk;let i=this.n.get(e);return i===void 0&&(i=await(await this.y()).getChunk(e),i!==void 0&&this.s.set(i.hash,{chunk:i,size:-1})),i}getHead(e){let t=this.i.get(e);return t?Promise.resolve(t.new):super.getHead(e)}async commit(){let e=new Set(ii(this.o.keys(),this.s.keys())),t=await Xi(this.i.values(),e,this);for(let[e,n]of t)if(this.isMemOnlyChunkHash(e)){if(n===0)this.#e.delete(e),this.t.delete(e),this.#t.delete(e);else{this.#e.set(e,n);let t=this.o.get(e);t&&(this.#t.set(e,t.meta),this.t.set(e,t))}t.delete(e)}this.n.updateForCommit(this.s,t);for(let[e,t]of this.i)t.new?this.a.set(e,t.new):this.a.delete(e);this.o.clear(),this.s.clear(),this.i.clear(),this.release()}getRefCount(e){return this.#e.get(e)}getRefs(e){let t=this.o.get(e);if(t)return t.meta;let n=this.t.get(e);if(n)return n.meta;let r=this.s.get(e);return r===void 0?this.#t.get(e):r.chunk.meta}areRefsCounted(e){return this.#t.has(e)}chunksPersisted(e){let t=[];for(let n of e){let e=this.t.get(n);e&&(this.t.delete(n),t.push(e))}this.n.persisted(t)}},ia=class{#e;#t;#n;#r;#i=0;#a=!1;#o=[];cacheEntries=new Map;constructor(e,t,n,r){this.#e=e,this.#t=t,this.#n=n,this.#r=r}get(e){let t=this.cacheEntries.get(e);return t&&(this.cacheEntries.delete(e),this.cacheEntries.set(e,t)),t?.chunk}getWithoutUpdatingLRU(e){return this.cacheEntries.get(e)?.chunk}put(e){let{hash:t}=e,n=this.cacheEntries.get(t);if(n){this.cacheEntries.delete(t),this.cacheEntries.set(t,n);return}let r=this.#n.get(t);if(!(r===void 0||r<1)&&this.#c(e)){if(!this.#r.has(t)){for(let t of e.meta)this.#n.set(t,(this.#n.get(t)||0)+1);this.#r.set(t,e.meta)}this.#s()}}#s(){if(!this.#a)for(let e of this.cacheEntries.values()){if(this.#i<=this.#e)break;this.#l(e)}}#c(e,t){let n=t??this.#t(e);return n>this.#e?!1:(this.#i+=n,this.cacheEntries.set(e.hash,{chunk:e,size:n}),!0)}#l(e){let{hash:t}=e.chunk;this.#i-=e.size,this.cacheEntries.delete(t)}#u(e){this.#n.delete(e),this.#r.delete(e);let t=this.cacheEntries.get(e);t&&(this.#i-=t.size,this.cacheEntries.delete(e))}updateForCommit(e,t){for(let[n,r]of t)if(r===0)this.#a?(this.#n.set(n,0),this.#o.push(n)):this.#u(n);else{this.#n.set(n,r);let t=e.get(n);if(t){let{chunk:e,size:r}=t,i=this.cacheEntries.get(n);i?(this.cacheEntries.delete(n),this.cacheEntries.set(n,i)):(this.#c(e,r===-1?void 0:r),this.#r.set(n,e.meta))}}this.#s()}persisted(e){for(let t of e)this.#c(t);this.#s()}async withSuspendedEvictsAndDeletes(e){this.#a=!0;try{return await e()}finally{this.#a=!1;for(let e of this.#o)this.#n.get(e)===0&&this.#u(e);this.#s()}}};function aa(e){return`c/${e}/d`}function oa(e){return`c/${e}/m`}function sa(e){return`c/${e}/r`}function ca(e){return`h/${e}`}var la=class{#e;#t;#n;constructor(e,t,n){this.#e=e,this.#t=t,this.#n=n}async read(){return new ua(await this.#e.read(),this.#n)}async write(){return new da(await this.#e.write(),this.#t,this.#n)}close(){return this.#e.close()}},ua=class{e;assertValidHash;constructor(e,t){this.e=e,this.assertValidHash=t}hasChunk(e){return this.e.has(aa(e))}async getChunk(e){let t=await this.e.get(aa(e));if(t===void 0)return;let n=await this.e.get(oa(e)),r;return n===void 0?r=[]:(Ei(n),r=n),new Ti(e,t,r)}mustGetChunk(e){return $i(this,e)}async getHead(e){let t=await this.e.get(ca(e));if(t!==void 0)return Ji(t),t}release(){this.e.release()}get closed(){return this.e.closed}},da=class extends ua{#e;#t=new Set;#n=new Map;constructor(e,t,n){super(e,n),this.#e=t}createChunk=(e,t)=>Di(e,t,this.#e);get kvWrite(){return this.e}async putChunk(e){let{hash:t,data:n,meta:r}=e;this.assertValidHash(t);let i=aa(t),a=this.e.put(i,n),o;if(r.length>0){for(let e of r)this.assertValidHash(e);o=this.e.put(oa(t),r)}this.#t.add(t),await a,await o}setHead(e,t){return this.#r(e,t)}removeHead(e){return this.#r(e,void 0)}async#r(e,t){let n=await this.getHead(e),r=ca(e),i;i=t===void 0?this.e.del(r):this.e.put(r,t);let a=this.#n.get(e);a===void 0?this.#n.set(e,{new:t,old:n}):a.new=t,await i}async commit(){let e=await Xi(this.#n.values(),this.#t,this);await this.#i(e),await this.e.commit()}async getRefCount(e){let t=await this.e.get(sa(e));if(t!==void 0){if(M(t),t<0||t>65535||t!==(t|0))throw Error(`Invalid ref count ${t}. We expect the value to be a Uint16`);return t}}async getRefs(e){let t=await this.e.get(oa(e));return t===void 0?[]:(Ei(t),t)}async#i(e){let t=[];for(let[n,r]of e)if(r===0)t.push(this.#a(n));else{let e=sa(n);t.push(this.e.put(e,r))}await Promise.all(t)}async#a(e){await Promise.all([this.e.del(aa(e)),this.e.del(oa(e)),this.e.del(sa(e))]),this.#t.delete(e)}release(){this.e.release()}},I=`main`;function fa(e){return Fa(e.meta)}function pa(e){return Pa(e.meta)}function ma(e){return pa(e)||fa(e)}function ha(e){return Va(e.meta)}function ga(e){return Ha(e.meta)}function _a(e){return ha(e)||ga(e)}var va=class{chunk;constructor(e){this.chunk=e}get meta(){return this.chunk.data.meta}get valueHash(){return this.chunk.data.valueHash}getMutationID(e,t){return ya(e,t,this.meta)}async getNextMutationID(e,t){return await this.getMutationID(e,t)+1}get indexes(){return this.chunk.data.indexes}};async function ya(e,t,n){switch(n.type){case 1:return n.lastMutationID;case 3:return n.lastMutationID;case 5:return n.lastMutationIDs[e]??0;case 2:return n.mutationID;case 4:{if(n.clientID===e)return n.mutationID;let{basisHash:r}=n;return ya(e,t,(await L(r,t)).meta)}default:xr(n)}}async function ba(e,t){return(await ka(e,t)).filter(e=>ma(e))}async function xa(e,t){return(await ka(e,t)).filter(e=>pa(e))}async function Sa(e,t,n){let r=[],i=new Map(Object.entries(t));for(;!_a(e)&&i.size>0;){if(pa(e)){let{meta:t}=e,n=i.get(t.clientID);n!==void 0&&(t.mutationID<=n?i.delete(t.clientID):r.push(e))}let{basisHash:t}=e.meta;if(t===null)throw Error(`Commit ${e.chunk.hash} has no basis`);e=await L(t,n)}return r}async function Ca(e,t){let n=await t.getHead(e);return A(n,`Missing head ${e}`),Ta(n,t)}async function wa(e,t){return(await Ta(e,t)).chunk.hash}async function Ta(e,t){return Ea(await L(e,t),t)}async function Ea(e,t){for(;!_a(e);){let{meta:n}=e;if(Pa(n))e=await L(n.baseSnapshotHash,t);else{let{basisHash:r}=n;if(r===null)throw Error(`Commit ${e.chunk.hash} has no basis`);e=await L(r,t)}}return e}function Da(e,t){let n=e.meta;return Va(n)?[n.lastMutationIDs[t]??0,n.cookieJSON]:[n.lastMutationID,n.cookieJSON]}function Oa(e,t){return ti(e.meta.cookieJSON,t.meta.cookieJSON)}async function ka(e,t){let n=await L(e,t),r=[];for(;!_a(n);){let{meta:e}=n,{basisHash:i}=e;if(i===null)throw Error(`Commit ${n.chunk.hash} has no basis`);r.push(n),n=await L(i,t)}return r.push(n),r}async function L(e,t){return no(await t.mustGetChunk(e))}async function Aa(e,t){return L(await ea(e,t),t)}function ja(e){M(e.lastMutationID)}function Ma(e){if(M(e.mutationID),j(e.mutatorName),!e.mutatorName)throw Error(`Missing mutator name`);Kr(e.mutatorArgsJSON),e.originalHash!==null&&Ji(e.originalHash),M(e.timestamp)}function Na(e){j(e.clientID),Ma(e)}function Pa(e){return e.type===4}function Fa(e){return e.type===2}function Ia(e){e.basisHash!==null&&Ji(e.basisHash),Kr(e.cookieJSON)}function La(e){Ia(e),M(e.lastMutationID)}function Ra(e){Ia(e),za(e.lastMutationIDs)}function za(e){N(e);for(let t of Object.values(e))M(t)}function Ba(e){Ra(e.meta)}function Va(e){return e.type===5}function Ha(e){return e.type===3}function Ua(e){switch(N(e),xi(e),e.basisHash!==null&&j(e.basisHash),M(e.type),e.type){case 1:ja(e);break;case 2:Ma(e);break;case 4:Na(e);break;case 3:La(e);break;case 5:Ra(e);break;default:throw Error(`Invalid enum value ${e.type}`)}}function Wa(e,t){return e.jsonPointer===t.jsonPointer&&(e.allowEmpty??!1)===(t.allowEmpty??!1)&&e.keyPrefix===t.keyPrefix}function Ga(e){N(e),xi(e),j(e.name),j(e.keyPrefix),j(e.jsonPointer),e.allowEmpty!==void 0&&mr(e.allowEmpty)}function Ka(e,t){return{name:e,keyPrefix:t.prefix??``,jsonPointer:t.jsonPointer,allowEmpty:t.allowEmpty??!1}}function qa(e){N(e),xi(e),Ga(e.definition),j(e.valueHash)}function Ja(e){gr(e),xi(e);for(let t of e)qa(t)}function Ya(e,t,n,r,i,a,o,s,c){return ro(e,ao({type:2,basisHash:t,mutationID:n,mutatorName:r,mutatorArgsJSON:i,originalHash:a,timestamp:c},o,s))}function Xa(e,t,n,r,i,a,o,s,c,l,u){return ro(e,ao({type:4,basisHash:t,baseSnapshotHash:n,mutationID:r,mutatorName:i,mutatorArgsJSON:a,originalHash:o,timestamp:l,clientID:u},s,c))}function Za(e,t,n,r,i,a){return ro(e,$a(t,n,r,i,a))}function Qa(e,t,n,r,i,a){return ro(e,eo(t,n,r,i,a))}function $a(e,t,n,r,i){return ao({type:3,basisHash:e,lastMutationID:t,cookieJSON:n},r,i)}function eo(e,t,n,r,i){return ao({type:5,basisHash:e,lastMutationIDs:t,cookieJSON:n},r,i)}function to(e,t,n,r,i){return ro(e,ao({type:1,basisHash:t,lastMutationID:n},r,i))}function no(e){return so(e),new va(e)}function ro(e,t){return new va(e(t,io(t)))}function io(e){let t=new Set;t.add(e.valueHash);let{meta:n}=e;switch(n.type){case 1:n.basisHash&&t.add(n.basisHash);break;case 2:case 4:n.basisHash&&t.add(n.basisHash);break;case 3:case 5:break;default:xr(n)}for(let n of e.indexes)t.add(n.valueHash);return wi(t)}function ao(e,t,n){return _i({meta:e,valueHash:t,indexes:n})}function oo(e){Hr||(N(e),xi(e),Ua(e.meta),j(e.valueHash),Ja(e.indexes))}function so(e){let{data:t}=e;oo(t);let n=new Set;for(let e of t.indexes){let{name:t}=e.definition;if(n.has(t))throw Error(`Duplicate index ${t}`);n.add(t)}}function co(e,t){let n=e.length,r=t.length,i=Math.min(n,r);for(let n=0;n<i;){let r=e.codePointAt(n),i=t.codePointAt(n);if(r!==i)return r<128&&i<128?r-i:lo(po,ho(r,po),mo,ho(i,mo));n+=uo(r)}return n-r}function lo(e,t,n,r){let i=Math.min(t,r);for(let t=0;t<i;t++){let r=e[t],i=n[t];if(r!==i)return r-i}return t-r}function uo(e){return e>65535?2:1}var fo=()=>Array.from({length:4},()=>0),po=fo(),mo=fo();function ho(e,t){if(e<128)return t[0]=e,1;let n,r;if(e<=2047)n=1,r=192;else if(e<=65535)n=2,r=224;else if(e<=1114111)n=3,r=240;else throw Error(`Invalid code point`);t[0]=(e>>6*n)+r;let i=1;for(;n>0;n--){let r=e>>6*(n-1);t[i++]=128|r&63}return i}function go(e,t){return co(e,t)>0}function _o(e,t){return co(e,t)<0}function vo(e,t){return co(e,t)<=0}function yo(e,t){let n=0;for(;n<e;){let r=n+(e-n>>1),i=t(r);if(i===0)return r;i>0?n=r+1:e=r}return n}function bo(e){if(e!==(e|0)||e<4||e>7)throw Error(`Unsupported format version: ${e}`);return e}var xo=0,So=1;function Co(e,t,n){return _i([e,n>=7?t:t.map(e=>e.slice(0,2))])}async function wo(e,t,n,r){let i=await n.getNode(t);if(r!==n.rootHash)return wo(e,n.rootHash,n,n.rootHash);if(Io(i))return i;let{entries:a}=i,o=To(e,a);o===a.length&&o--;let s=a[o];return wo(e,s[1],n,r)}function To(e,t){return yo(t.length,n=>co(e,t[n][0]))}function Eo(e,t,n){return e!==t.length&&t[e][0]===n}function Do(e,t,n){if(Hr&&t>=7)return e;gr(e),xi(e),A(e.length>=2);let[r,i]=e;M(r),gr(i);let a=r>0?j:Kr;if(t>=7){for(let e of i)Oo(e,a);return e}return[r,i.map(e=>ko(e,a,n))]}function Oo(e,t){gr(e),A(e.length>=3),j(e[0]),t(e[1]),M(e[2])}function ko(e,t,n){gr(e),A(e.length>=2),j(e[0]),t(e[1]);let r=n(e[0],e[1]);return[e[0],e[1],r]}var Ao=class{entries;hash;isMutable;#e=-1;constructor(e,t,n){this.entries=e,this.hash=t,this.isMutable=n}maxKey(){return this.entries[this.entries.length-1][0]}getChildNodeSize(e){if(this.#e!==-1)return this.#e;let t=e.chunkHeaderSize;for(let e of this.entries)t+=e[2];return this.#e=t}c(e){this.#e=-1,e.updateNode(this)}};function jo(e,t){return Co(e.level,e.entries,t)}var Mo=class extends Ao{level=0;set(e,t,n,r){let i,a=To(e,this.entries);return i=+!!Eo(a,this.entries,e),Promise.resolve(this.#e(r,a,i,[e,t,n]))}#e(e,t,n,...r){if(this.isMutable)return this.entries.splice(t,n,...r),this.c(e),this;let i=No(this.entries,t,n,...r);return e.newDataNodeImpl(i)}del(e,t){let n=To(e,this.entries);return Eo(n,this.entries,e)?Promise.resolve(this.#e(t,n,1)):Promise.resolve(this)}async*keys(e){for(let e of this.entries)yield e[0]}async*entriesIter(e){for(let e of this.entries)yield e}};function No(e,t,n,...r){let i=e.slice(0,t);for(let e=0;e<r.length;e++)i.push(r[e]);for(let r=t+n;r<e.length;r++)i.push(e[r]);return i}var Po=class e extends Ao{level;constructor(e,t,n,r){super(e,t,r),this.level=n}async set(e,t,n,r){let i=To(e,this.entries);i===this.entries.length&&i--;let a=this.entries[i][1],o=await(await r.getNode(a)).set(e,t,n,r),s=o.getChildNodeSize(r);if(s>r.maxSize||s<r.minSize)return this.#e(r,i,o);let c=Bo(o,r.getEntrySize);return this.#t(r,i,c)}async#e(e,t,n){let r=this.level-1,i=this.entries,a,o,s;if(t>0){let r=i[t-1][1];a=ii((await e.getNode(r)).entries,n.entries),o=t-1,s=2}else if(t<i.length-1){let r=i[t+1][1],c=await e.getNode(r);a=ii(n.entries,c.entries),o=t,s=2}else a=n.entries,o=t,s=1;let c=Lo(a,e=>e[2],e.minSize-e.chunkHeaderSize,e.maxSize-e.chunkHeaderSize),l=[];for(let t of c){let n=Bo(e.newNodeImpl(t,r),e.getEntrySize);l.push(n)}if(this.isMutable)return this.entries.splice(o,s,...l),this.c(e),this;let u=No(i,o,s,...l);return e.newInternalNodeImpl(u,this.level)}#t(e,t,n){if(this.isMutable)return this.entries.splice(t,1,n),this.c(e),this;let r=No(this.entries,t,1,n);return e.newInternalNodeImpl(r,this.level)}async del(e,t){let n=To(e,this.entries);if(n===this.entries.length)return this;let r=this.entries[n][1],i=await t.getNode(r),a=i.hash,o=await i.del(e,t);if(o.hash===a)return this;if(o.entries.length===0){let e=No(this.entries,n,1);return t.newInternalNodeImpl(e,this.level)}if(n===0&&this.entries.length===1)return o;if(o.getChildNodeSize(t)>t.minSize){let e=Bo(o,t.getEntrySize);return this.#t(t,n,e)}return this.#e(t,n,o)}async*keys(e){for(let t of this.entries)yield*(await e.getNode(t[1])).keys(e)}async*entriesIter(e){for(let t of this.entries)yield*(await e.getNode(t[1])).entriesIter(e)}getChildren(e,t,n){let r=[];for(let i=e;i<t&&i<this.entries.length;i++)r.push(n.getNode(this.entries[i][1]));return Promise.all(r)}async getCompositeChildren(t,n,r){let{level:i}=this;if(n===0)return new e([],Wi(),i-1,!0);let a=await this.getChildren(t,t+n,r);if(i>1){let t=[];for(let e of a)t.push(...e.entries);return new e(t,Wi(),i-1,!0)}A(i===1);let o=[];for(let e of a)o.push(...e.entries);return new Mo(o,Wi(),!0)}};function Fo(e,t,n,r){return n===0?new Mo(e,t,r):new Po(e,t,n,r)}function Io(e){return e.level===0}function Lo(e,t,n,r){let i=[],a=[],o=0,s=[];for(let c of e){let e=t(c);e>=r?(s.length>0&&(i.push(s),a.push(o)),i.push([c]),a.push(e),o=0,s=[]):o+e>=n?(s.push(c),i.push(s),a.push(o+e),o=0,s=[]):(o+=e,s.push(c))}return o>0&&(a.length>0&&o+a[a.length-1]<=r?i[i.length-1].push(...s):i.push(s)),i}var Ro=Co(0,[],7),zo=new Mo([],F,!1);function Bo(e,t){let n=e.maxKey(),r=e.hash;return[n,r,t(n,r)]}var Vo=-1,Ho=0,Uo=1,Wo=2,Go=3,Ko=0,qo=1;function*Jo(e,t){let n=0,r=0,i;function a(e,t){e[Go]===Vo&&(e[Go]=t)}function o(){return[n,0,0,Vo]}for(;n<e.length&&r<t.length;)e[n][Ko]===t[r][Ko]?(Gr(e[n][qo],t[r][qo])?i&&=(a(i,0),yield i,void 0):(i||=o(),i[Wo]++,i[Uo]++,a(i,r)),n++,r++):e[n][Ko]<t[r][Ko]?(i||=o(),i[Uo]++,n++):(i||=o(),i[Wo]++,a(i,r),r++);r<t.length&&(i||=o(),i[Wo]+=t.length-r,a(i,r)),n<e.length&&(i||=o(),i[Uo]+=e.length-n),i&&(a(i,0),yield i)}var Yo=11,Xo=class{p=new Map;l;u;rootHash;getEntrySize;chunkHeaderSize;constructor(e,t,n=F,r=hi,i=Yo){this.l=e,this.u=t,this.rootHash=n,this.getEntrySize=r,this.chunkHeaderSize=i}async getNode(e){if(e===F)return zo;let t=this.p.get(e);if(t)return t;let n=Do((await this.l.mustGetChunk(e)).data,this.u,this.getEntrySize),r=Fo(n[So],e,n[xo],!1);return this.p.set(e,r),r}async get(e){let t=await wo(e,this.rootHash,this,this.rootHash),n=To(e,t.entries);if(Eo(n,t.entries,e))return t.entries[n][1]}async has(e){let t=await wo(e,this.rootHash,this,this.rootHash);return Eo(To(e,t.entries),t.entries,e)}async isEmpty(){let{rootHash:e}=this,t=await this.getNode(this.rootHash);return this.rootHash===e?t.entries.length===0:this.isEmpty()}scan(e){return $o(this.rootHash,()=>this.rootHash,this.rootHash,e,async e=>{let t=await this.getNode(e);return t?[t.level,t.isMutable?t.entries.slice():t.entries]:Do((await this.l.mustGetChunk(e)).data,this.u,this.getEntrySize)})}async*keys(){yield*(await this.getNode(this.rootHash)).keys(this)}async*entries(){yield*(await this.getNode(this.rootHash)).entriesIter(this)}[Symbol.asyncIterator](){return this.entries()}async*diff(e){let[t,n]=await Promise.all([this.getNode(this.rootHash),e.getNode(e.rootHash)]);yield*Zo(n,t,e,this)}};async function*Zo(e,t,n,r){if(e.level>t.level){yield*Zo(await e.getCompositeChildren(0,e.entries.length,n),t,n,r);return}if(t.level>e.level){yield*Zo(e,await t.getCompositeChildren(0,t.entries.length,r),n,r);return}if(Io(e)&&Io(t)){yield*Qo(e.entries,t.entries);return}let i=Jo(e.entries,t.entries);for(let a of i){let[i,o]=await Promise.all([e.getCompositeChildren(a[Ho],a[Uo],n),t.getCompositeChildren(a[Go],a[Wo],r)]);yield*Zo(i,o,n,r)}}function*Qo(e,t){let n=e.length,r=t.length,i=0,a=0;for(;i<n&&a<r;){let n=e[i][0],r=t[a][0];n===r?(Gr(e[i][1],t[a][1])||(yield{op:`change`,key:n,oldValue:e[i][1],newValue:t[a][1]}),i++,a++):n<r?(yield{op:`del`,key:n,oldValue:e[i][1]},i++):(yield{op:`add`,key:r,newValue:t[a][1]},a++)}for(;i<n;i++)yield{op:`del`,key:e[i][0],oldValue:e[i][1]};for(;a<r;a++)yield{op:`add`,key:t[a][0],newValue:t[a][1]}}async function*$o(e,t,n,r,i){if(n===F)return;let a=await i(n),o=a[So],s=0;if(r&&(s=To(r,o)),a[xo]>0)for(;s<o.length;s++)yield*$o(e,t,o[s][1],r,i),r=``;else for(;s<o.length;s++){let n=t();if(e!==n){yield*$o(n,t,n,o[s][0],i);return}yield o[s]}}async function es(e,t){let n=[],r=t===`add`?e=>({op:`add`,key:e[0],newValue:e[1]}):e=>({op:`del`,key:e[0],oldValue:e[1]});for await(let t of e.entries())n.push(r(t));return n}var ts=class{meta;map;constructor(e,t){this.meta=e,this.map=t}},ns=class extends ts{flush(){return this.map.flush()}clear(){return this.map.clear()}};async function rs(e,t,n,r,i,a,o){try{for(let e of is(r,i,a,o))switch(n){case 0:await t.put(e,i);break;case 1:await t.del(e);break}}catch(t){e.info?.(`Not indexing value`,i,`:`,t)}}function is(e,t,n,r){let i=us(t,n);if(i===void 0){if(r)return[];throw Error(`No value at path: ${n}`)}let a=Array.isArray(i)?i:[i],o=[];for(let t of a)if(typeof t==`string`)o.push(ss([t,e]));else throw Error(`Unsupported target type`);return o}var as=`\0`,os=`\0`;function ss(e){let t=e[0],n=e[1];if(t.includes(`\0`))throw Error(`Secondary key cannot contain null byte`);return as+t+os+n}function cs(e,t){let n=ss([e,t||``]);return t===void 0?n.slice(0,n.length-1):n}function ls(e){if(e[0]!==as)throw Error(`Invalid version`);let t=as.length,n=os.length,r=e.indexOf(os,t);if(r===-1)throw Error(`Invalid formatting`);return[e.slice(t,r),e.slice(r+n)]}function us(e,t){function n(e){if(!(e.startsWith(`+`)||e.startsWith(`0`)&&e.length!==1))return parseInt(e,10)}if(t===``)return e;if(!t.startsWith(`/`))throw Error(`Invalid JSON pointer: ${t}`);let r=t.split(`/`).slice(1).map(e=>e.replace(/~1/g,`/`).replace(/~0/g,`~`)),i=e;for(let e of r){let t;if(Array.isArray(i)){let r=n(e);if(r===void 0)return;t=i[r]}else{if(i===null)return;typeof i==`object`&&(i=i,t=i[e])}if(t===void 0)return;i=t}return i}var ds=class{#e;map;indexes;constructor(e,t,n){this.#e=e,this.map=t,this.indexes=n}has(e){return this.map.has(e)}get(e){return this.map.get(e)}isEmpty(){return this.map.isEmpty()}getMapForIndex(e){let t=this.indexes.get(e);if(t===void 0)throw Error(`Unknown index name: ${e}`);return t.map}get closed(){return this.#e.closed}close(){this.#e.release()}};function fs(e,t){return ps(I,e,t)}async function ps(e,t,n){return ms(await Aa(e,t),t,n)}function ms(e,t,n){let r=hs(e,t,n);return new ds(t,new Xo(t,n,e.valueHash),r)}function hs(e,t,n){let r=new Map;for(let i of e.indexes)r.set(i.definition.name,new ts(i,new Xo(t,n,i.valueHash)));return r}async function gs(e){let t=[];for await(let n of e)t.push(n);return t}function _s(e){return e.indexName!==void 0}function vs(e){return typeof e==`string`?[e]:e}function ys(e){if(!e)return{};let t,n,r,i;return e.start&&({key:t,exclusive:n}=e.start,e.indexName?typeof t==`string`?i=t:(i=t[0],r=t[1]):r=t),{prefix:e.prefix,startSecondaryKey:i,startKey:r,startExclusive:n,limit:e.limit,indexName:e.indexName}}var bs=class extends Error{constructor(){super(`Transaction is closed`)}};function xs(e){if(e.closed)throw new bs}function Ss(e){return e.closed?Promise.reject(new bs):void 0}var Cs=class{#e;#t;#n;#r;constructor(e,t,n,r){this.#e=e,this.#t=t,this.#n=n,this.#r=r}[Symbol.asyncIterator](){return this.values()}values(){return new ws(this.#i(e=>e[1]))}keys(){return new ws(this.#i(e=>e[0]))}entries(){return new ws(this.#i(e=>[e[0],e[1]]))}toArray(){return this.values().toArray()}#i(e){return Ts(e,this.#e,this.#t,this.#n,this.#r)}},ws=class{#e;constructor(e){this.#e=e}next(){return this.#e.next()}[Symbol.asyncIterator](){return this.#e[Symbol.asyncIterator]()}toArray(){return gs(this.#e)}};async function*Ts(e,t,n,r,i){xs(r);let{limit:a=1/0}=n,{prefix:o=``}=n,s=n.start?.exclusive,c=_s(n);for await(let r of t){let t=r[0];if(!(c?t[0]:t).startsWith(o))return;if(s){if(s=!0,c){if(Es(t,n.start.key))continue}else if(Ds(t,n.start.key))continue}if(yield e(r),--a===0){c||i(t);return}}}function Es(e,t){let[n,r]=vs(t),[i,a]=vs(e);return i===n?r===void 0||a===r:!1}function Ds(e,t){return e===t}function Os(e){let{prefix:t,start:n}=e,r=``;if(t!==void 0&&(r=cs(t,void 0)),!n)return r;let{key:i}=n,[a,o]=vs(i),s=cs(a,o);return go(s,r)?s:r}var ks=0,As=class{clientID;dbtx;d;location;environment;constructor(e,t,n,r=`openReadTransaction`){this.clientID=e,this.dbtx=t,this.d=n.withContext(r).withContext(`txid`,ks++),this.environment=`client`,this.location=`client`}get(e){return Ss(this.dbtx)||this.dbtx.get(e)}async has(e){return xs(this.dbtx),this.dbtx.has(e)}async isEmpty(){return xs(this.dbtx),this.dbtx.isEmpty()}scan(e){return Ms(e,this.dbtx,js)}};function js(e){}function Ms(e,t,n){return Ls(Fs(t,e),e??{},t,n)}var Ns=class{#e=new Set;#t=[];#n;constructor(e){this.#n=e}get environment(){return this.#n.location}get location(){return this.#n.location}get clientID(){return this.#n.clientID}isEmpty(){return this.#t.push({options:{}}),this.#n.isEmpty()}get(e){return this.#e.add(e),this.#n.get(e)}has(e){return this.#e.add(e),this.#n.has(e)}scan(e){let t={options:ys(e),inclusiveLimitKey:void 0};return this.#t.push(t),Ms(e,this.#n.dbtx,e=>{t.inclusiveLimitKey=e})}get keys(){return this.#e}get scans(){return this.#t}},Ps=class extends As{reason;mutationID;constructor(e,t,n,r,i,a=`openWriteTransaction`){super(e,r,i,a),this.mutationID=t,this.reason=n}put(e,t){return this.set(e,t)}async set(e,t){xs(this.dbtx),await this.dbtx.put(this.d,e,_i(t))}del(e){return Ss(this.dbtx)??this.dbtx.del(this.d,e)}};function Fs(e,t){return t&&_s(t)?Rs(e,t):e.map.scan(Is(t))}function Is(e){if(!e)return``;let{prefix:t=``,start:n}=e;return n&&go(n.key,t)?n.key:t}function Ls(e,t,n,r){return new Cs(e,t,n,r)}async function*Rs(e,t){let n=e.getMapForIndex(t.indexName);for await(let e of n.scan(Os(t)))yield[ls(e[0]),e[1]]}function zs(e,t){return gs(t.diff(e))}var Bs=class extends Xo{#e=new Jt;#t=new Map;minSize;maxSize;constructor(e,t,n=F,r=8192,i=16384,a=hi,o){super(e,t,n,a,o),this.minSize=r,this.maxSize=i}#n(e){A(e.isMutable),this.#t.set(e.hash,e),this.p.set(e.hash,e)}updateNode(e){A(e.isMutable),this.#t.delete(e.hash),e.hash=Wi(),this.#n(e)}newInternalNodeImpl(e,t){let n=new Po(e,Wi(),t,!0);return this.#n(n),n}newDataNodeImpl(e){let t=new Mo(e,Wi(),!0);return this.#n(t),t}newNodeImpl(e,t){let n=Fo(e,Wi(),t,!0);return this.#n(n),n}put(e,t){return this.#e.withLock(async()=>{let n=await this.getNode(this.rootHash),r=this.getEntrySize(e,t),i=await n.set(e,t,r,this);if(i.getChildNodeSize(this)>this.maxSize){let e=this.chunkHeaderSize,t=Lo(i.entries,e=>e[2],this.minSize-e,this.maxSize-e),{level:n}=i,r=t.map(e=>Bo(this.newNodeImpl(e,n),this.getEntrySize)),a=this.newInternalNodeImpl(r,n+1);this.rootHash=a.hash;return}this.rootHash=i.hash})}del(e){return this.#e.withLock(async()=>{let t=await(await this.getNode(this.rootHash)).del(e,this),n=this.rootHash!==t.hash;return n&&(this.rootHash=t.level>0&&t.entries.length===1?t.entries[0][1]:t.hash),n})}clear(){return this.#e.withLock(()=>{this.#t.clear(),this.rootHash=F})}flush(){return this.#e.withLock(async()=>{let e=this.l;if(this.rootHash===F){let t=e.createChunk(Ro,[]);return await e.putChunk(t),t.hash}let t=[],n=Vs(this.rootHash,t,e.createChunk,this.#t,this.u);return await Promise.all(t.map(t=>e.putChunk(t))),this.#t.clear(),this.rootHash=n,n})}};function Vs(e,t,n,r,i){let a=r.get(e);if(a===void 0)return e;if(Io(a)){let e=n(jo(a,i),[]);return t.push(e),e.hash}let o=[],{entries:s}=a;for(let e=0;e<s.length;e++){let a=s[e],c=a[1],l=Vs(c,t,n,r,i);l!==c&&(s[e]=[a[0],l,a[2]]),o.push(l)}let c=n(jo(a,i),wi(o));return t.push(c),c.hash}function Hs(e){let t;return()=>(t===void 0&&(t=e()),t)}var Us=class extends Map{set(e,t){return t.length===0?this:super.set(e,t)}};async function Ws(e,t,n,r,i){let a=new Us;if(!r.shouldComputeDiffs())return a;let o=await zs(new Xo(n,i,e.valueHash),new Xo(n,i,t.valueHash));return a.set(``,o),await Gs(e,t,n,a,r,i),a}async function Gs(e,t,n,r,i,a){let o=hs(e,n,a),s=hs(t,n,a);for(let[e,t]of o){if(!i.shouldComputeDiffsForIndex(e))continue;let n=s.get(e);if(n!==void 0){A(n!==t);let i=await zs(t.map,n.map);s.delete(e),r.set(e,i)}else{let n=await es(t.map,`del`);r.set(e,n)}}for(let[e,t]of s){if(!i.shouldComputeDiffsForIndex(e))continue;let n=await es(t.map,`add`);r.set(e,n)}}var Ks=class extends ds{#e;#t;#n;#r;#i;constructor(e,t,n,r,i,a,o){super(e,t,i),this.#e=e,this.#t=n,this.#n=r,this.#r=a,this.#i=o,A(n===void 0?r.basisHash===F:r.basisHash===n.chunk.hash)}async put(e,t,n){if(this.#n.type===1)throw Error(`Not allowed`);let r=Hs(()=>this.map.get(t));await Xs(e,this.indexes,t,r,n),await this.map.put(t,n)}getMutationID(){return ya(this.#r,this.#e,this.#n)}async del(e,t){if(this.#n.type===1)throw Error(`Not allowed`);let n=Hs(()=>this.map.get(t));return n!==void 0&&await Xs(e,this.indexes,t,n,void 0),this.map.del(t)}async clear(){if(this.#n.type===1)throw Error(`Not allowed`);await this.map.clear();let e=[];for(let t of this.indexes.values())e.push(t.clear());await Promise.all(e)}async putCommit(){let e=await this.map.flush(),t=[];for(let e of this.indexes.values()){let n=await e.flush(),r={definition:e.meta.definition,valueHash:n};t.push(r)}let n,r=this.#n;switch(r.type){case 2:{let{basisHash:i,mutationID:a,mutatorName:o,mutatorArgsJSON:s,originalHash:c,timestamp:l}=r;n=Ya(this.#e.createChunk,i,a,o,s,c,e,t,l);break}case 4:{A(this.#i>=5);let{basisHash:i,mutationID:a,mutatorName:o,mutatorArgsJSON:s,originalHash:c,timestamp:l}=r;n=Xa(this.#e.createChunk,i,await wa(i,this.#e),a,o,s,c,e,t,l,this.#r);break}case 3:{A(this.#i<=4);let{basisHash:i,lastMutationID:a,cookieJSON:o}=r;n=Za(this.#e.createChunk,i,a,o,e,t);break}case 5:{A(this.#i>5);let{basisHash:i,lastMutationIDs:a,cookieJSON:o}=r;n=Qa(this.#e.createChunk,i,a,o,e,t);break}case 1:{let{basisHash:i,lastMutationID:a}=r;if(this.#t!==void 0){if(await this.#t.getMutationID(this.#r,this.#e)!==a)throw Error(`Index change must not change mutationID`);if(this.#t.valueHash!==e)throw Error(`Index change must not change valueHash`)}n=to(this.#e.createChunk,i,a,e,t);break}}return await this.#e.putChunk(n.chunk),n}async commit(e){let t=(await this.putCommit()).chunk.hash;return await this.#e.setHead(e,t),await this.#e.commit(),t}async commitWithDiffs(e,t){let n=this.putCommit(),r=await this.#a(t),i=(await n).chunk.hash;return await this.#e.setHead(e,i),await this.#e.commit(),r}async#a(e){let t=new Us;if(!e.shouldComputeDiffs())return t;let n=[];this.#t&&(n=await zs(new Xo(this.#e,this.#i,this.#t.valueHash),this.map)),t.set(``,n);let r;r=this.#t?hs(this.#t,this.#e,this.#i):new Map;for(let[n,i]of this.indexes){if(!e.shouldComputeDiffsForIndex(n))continue;let a=r.get(n);A(i!==a);let o=await(a?zs(a.map,i.map):es(i.map,`add`));t.set(n,o)}for(let[n,i]of r)if(!this.indexes.has(n)&&e.shouldComputeDiffsForIndex(n)){let e=await es(i.map,`del`);t.set(n,e)}return t}close(){this.#e.release()}};async function qs(e,t,n,r,i,a,o,s){let c=await L(e,i),l=new Bs(i,s,c.valueHash),u=await c.getNextMutationID(o,i),d=Zs(c,i,s);return new Ks(i,l,c,s>=5?{type:4,basisHash:e,baseSnapshotHash:await wa(e,i),mutatorName:t,mutatorArgsJSON:n,mutationID:u,originalHash:r,timestamp:a,clientID:o}:{type:2,basisHash:e,mutatorName:t,mutatorArgsJSON:n,mutationID:u,originalHash:r,timestamp:a},d,o,s)}async function Js(e,t,n,r,i,a,o){A(o<=4);let s=await L(e,r);return new Ks(r,new Bs(r,o,s.valueHash),s,{basisHash:e,type:3,lastMutationID:t,cookieJSON:n},i,a,o)}async function Ys(e,t,n,r,i,a){let o=await L(e,r);return new Ks(r,new Bs(r,a,o.valueHash),o,{basisHash:e,type:5,lastMutationIDs:t,cookieJSON:n},Zs(o,r,a),i,a)}async function Xs(e,t,n,r,i){let a=[];for(let o of t.values()){let{keyPrefix:t}=o.meta.definition;if(!t||n.startsWith(t)){let t=await r();t!==void 0&&a.push(rs(e,o.map,1,n,t,o.meta.definition.jsonPointer,o.meta.definition.allowEmpty??!1)),i!==void 0&&a.push(rs(e,o.map,0,n,i,o.meta.definition.jsonPointer,o.meta.definition.allowEmpty??!1))}}await Promise.all(a)}function Zs(e,t,n){let r=new Map;for(let i of e.indexes)r.set(i.definition.name,new ns(i,new Bs(t,n,i.valueHash)));return r}async function Qs(e,t,n,r,i,a,o){let s=new Bs(t,o);for await(let t of n.scan(r)){let n=t[0];if(!n.startsWith(r))break;await rs(e,s,0,n,t[1],i,a)}return s}async function $s(e,t,n,r,i,a,o){let s=e.meta,c=s.mutatorName;Pa(s)&&A(s.clientID===a,`mutationClientID must match clientID of LocalMeta`);let l=r[c];l||i.error?.(`Cannot rebase unknown mutator ${c}`);let u=l||(async()=>{}),d=s.mutatorArgsJSON,f=await(await L(n,t)).getNextMutationID(a,t);if(f!==s.mutationID)throw Error(`Inconsistent mutation ID: original: ${s.mutationID}, next: ${f} - mutationClientID: ${a} mutatorName: ${c}`);o>=5&&Na(s);let p=await qs(n,c,d,e.chunk.hash,t,s.timestamp,a,o);return await u(new Ps(a,await p.getMutationID(),`rebase`,p,i),d),p}async function ec(e,t,n,r,i,a,o){return(await $s(e,t,n,r,i,a,o)).putCommit()}async function tc(e,t,n,r,i,a,o,s){return(await $s(e,t,n,i,a,o,s)).commit(r)}function nc(e,t){return typeof e==`object`&&!!e&&e.error===t}function rc(e){return typeof e.error==`string`}function ic(e){return nc(e,`ClientStateNotFound`)}function ac(e){if(!nc(e,`VersionNotSupported`))return!1;let{versionType:t}=e;switch(t){case void 0:case`pull`:case`push`:case`schema`:return!0}return!1}function oc(e){A(ac(e))}async function sc(e,t,n,r){let i={headers:{"Content-type":`application/json`,Authorization:t,"X-Replicache-RequestID":n},body:JSON.stringify(r),method:`POST`},a=new Request(e,i),o=await fetch(a),s=o.status;return s===200?[o,{httpStatusCode:s,errorMessage:``}]:[void 0,{httpStatusCode:s,errorMessage:await o.text()}]}function cc(e){N(e),M(e.httpStatusCode),j(e.errorMessage)}function lc(e){gr(e);for(let t of e)uc(t)}function uc(e){switch(N(e),e.op){case`put`:j(e.key),Kr(e.value);break;case`update`:if(j(e.key),e.merge!==void 0&&qr(e.merge),e.constrain!==void 0){gr(e.constrain);for(let t of e.constrain)j(t)}break;case`del`:j(e.key);break;case`clear`:break;default:throw Error(`unknown patch op \`${e.op}\`, expected one of \`put\`, \`del\`, \`clear\``)}}function dc(e){async function t(t,n){let[r,i]=await sc(e.pullURL,e.auth,n,t);return r?{response:await r.json(),httpRequestInfo:i}:{httpRequestInfo:i}}return fc.add(t),t}var fc=new WeakSet;function pc(e){return fc.has(e)}function mc(e){if(N(e),ic(e)||ac(e))return;let t=e;t.cookie!==void 0&&Kr(t.cookie),M(t.lastMutationID),lc(t.patch)}function hc(e){if(N(e),ic(e)||ac(e))return;let t=e;t.cookie!==void 0&&ri(t.cookie),gc(t.lastMutationIDChanges),lc(t.patch)}function gc(e){N(e);for(let[t,n]of Object.entries(e))j(t),M(n)}function _c(e){N(e),cc(e.httpRequestInfo),e.response!==void 0&&hc(e.response)}function vc(e){N(e),cc(e.httpRequestInfo),e.response!==void 0&&mc(e.response)}function yc(e){async function t(t,n){let[r,i]=await sc(e.pushURL,e.auth,n,t);if(!r)return{httpRequestInfo:i};let a={httpRequestInfo:i},o;try{o=await r.json()}catch{return a}return(ic(o)||ac(o))&&(a.response=o),a}return bc.add(t),t}var bc=new WeakSet;function xc(e){return bc.has(e)}function Sc(e=`info`,t=[Ut],n){return new Wt(e,n,t.length===1?t[0]:new Vt(t))}var Cc=Vi(zi({prefix:P.string().optional(),jsonPointer:P.string(),allowEmpty:P.boolean().optional()}));function wc(e,t){return e.jsonPointer===t.jsonPointer&&(e.allowEmpty??!1)===(t.allowEmpty??!1)&&(e.prefix??``)===(t.prefix??``)}function Tc(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let[n,r]of Object.entries(e)){let e=t[n];if(!e||!wc(r,e))return!1}return!0}var Ec=zi({headHash:Yi,mutatorNames:Bi(P.string()),indexes:Cc,mutationIDs:Vi(P.number()),lastServerAckdMutationIDs:P.record(P.number()),disabled:P.boolean()}),Dc=`client-groups`;function Oc(e){Ii(e,Ec)}function kc(e){N(e);let t=new Map;for(let[n,r]of Object.entries(e))r!==void 0&&(Oc(r),t.set(n,r));return t}function Ac(e,t){let n={};for(let[r,i]of e.entries())t.assertValidHash(i.headHash),n[r]={...i,mutatorNames:[...i.mutatorNames.values()]};return _i(n)}async function jc(e,t){return kc((await t.getChunk(e))?.data)}async function Mc(e){let t=await e.getHead(Dc);return t?jc(t,e):new Map}async function Nc(e,t){let n=await Mc(t);for(let[t,r]of e)Fc(r,n.get(t));return Ic(e,t)}async function Pc(e,t,n){let r=await Mc(n);Fc(t,r.get(e));let i=new Map(r);return i.set(e,t),Ic(i,n)}function Fc(e,t){let n=new Set(e.mutatorNames);A(n.size===e.mutatorNames.length,`A client group's mutatorNames must be a set.`),t!==void 0&&(A(Tc(t.indexes,e.indexes),`A client group's index definitions must never change.`),A(Lc(n,t.mutatorNames),`A client group's mutatorNames must never change.`))}async function Ic(e,t){let n=Ac(e,t),r=new Set;for(let t of e.values())r.add(t.headHash);let i=t.createChunk(n,wi(r));return await t.putChunk(i),await t.setHead(Dc,i.hash),e}function Lc(e,t){if(t.length!==e.size)return!1;for(let n of t)if(!e.has(n))return!1;return!0}async function Rc(e,t){return(await Mc(t)).get(e)}function zc(e){for(let[t,n]of Object.entries(e.mutationIDs)){let r=e.lastServerAckdMutationIDs[t];if(r===void 0&&n!==0||r<n)return!0}return!1}async function Bc(e,t){let n=await Rc(e,t);n&&await Pc(e,{...n,disabled:!0},t)}var Vc=P.string(),Hc=P.string();function R(e,t){return Wc(e.read(),t)}function Uc(e,t){return Wc(e.write(),t)}function z(e,t){return Wc(e.write(),async e=>{let n=await t(e);return await e.commit(),n})}async function Wc(e,t){let n=await e;try{return await t(n)}finally{n.release()}}function Gc(){let e=ki(),t=ki();return(e<<64n|t).toString(32).slice(-18).padStart(18,`0`)}var Kc=zi({heartbeatTimestampMs:P.number(),headHash:Yi,mutationID:P.number(),lastServerAckdMutationID:P.number()}),qc=zi({heartbeatTimestampMs:P.number(),headHash:Yi,tempRefreshHash:Yi.nullable(),clientGroupID:Vc}),Jc=zi({heartbeatTimestampMs:P.number(),refreshHashes:Bi(Yi),persistHash:Yi.nullable(),clientGroupID:Vc});function Yc(e){return e.refreshHashes!==void 0}function Xc(e){return e.clientGroupID!==void 0}var Zc=`clients`,Qc=P.union(Kc,qc,Jc);function $c(e){Ii(e,Qc)}function el(e){Ii(e,Kc)}function tl(e){Ii(e,Jc)}function nl(e){N(e);let t=new Map;for(let n in e)if(Wr(e,n)){let r=e[n];r!==void 0&&($c(r),t.set(n,r))}return t}function rl(e,t){for(let n of e.values())Yc(n)?(n.refreshHashes.forEach(t.assertValidHash),n.persistHash&&t.assertValidHash(n.persistHash)):(t.assertValidHash(n.headHash),Xc(n)&&n.tempRefreshHash&&t.assertValidHash(n.tempRefreshHash));return _i(Object.fromEntries(e))}async function il(e){return al(await e.getHead(Zc),e)}async function al(e,t){return e?nl((await t.getChunk(e))?.data):new Map}var ol=class extends Error{name=`ClientStateNotFoundError`;id;constructor(e){super(`Client state not found, id: ${e}`),this.id=e}};async function sl(e,t){if(!await cl(e,t))throw new ol(e)}async function cl(e,t){return!!await ll(e,t)}async function ll(e,t){return(await il(t)).get(e)}async function ul(e,t){let n=await ll(e,t);if(!n)throw new ol(e);return n}function dl(e,t,n,r,i,a,o){return Uc(n,async n=>{async function s(t,a,o,s){let l=eo(t,{},a,o,s),u=n.createChunk(l,io(l)),d=Gc(),f={heartbeatTimestampMs:Date.now(),refreshHashes:[u.hash],persistHash:null,clientGroupID:d},p=new Map(c).set(e,f),m={headHash:u.hash,mutatorNames:r,indexes:i,mutationIDs:{},lastServerAckdMutationIDs:{},disabled:!1};return await Promise.all([n.putChunk(u),xl(p,n),Pc(d,m,n)]),await n.commit(),[f,u.hash,p,!0]}let c=await il(n),l=await gl(n,r,i);if(l.type===hl){let{clientGroupID:t,headHash:r}=l,i={clientGroupID:t,refreshHashes:[r],heartbeatTimestampMs:Date.now(),persistHash:null},a=new Map(c).set(e,i);return await xl(a,n),await n.commit(),[i,r,a,!1]}if(!o||l.type===pl){let e=n.createChunk(Ro,[]);await n.putChunk(e);let t=[];for(let[n,r]of Object.entries(i)){let i=Ka(n,r);t.push({definition:i,valueHash:e.hash})}return s(null,null,e.hash,t)}A(l.type===ml);let{snapshot:u}=l,d=[],{valueHash:f,indexes:p}=u,m=new Xo(n,a,f);for(let[e,r]of Object.entries(i)){let{prefix:i=``,jsonPointer:o,allowEmpty:s=!1}=r,c={name:e,keyPrefix:i,jsonPointer:o,allowEmpty:s},l=fl(p,c);if(l)d.push({definition:c,valueHash:l.valueHash});else{let e=await Qs(t,n,m,i,o,s,a);d.push({definition:c,valueHash:await e.flush()})}}return s(u.meta.basisHash,u.meta.cookieJSON,u.valueHash,d)})}function fl(e,t){return e.find(e=>Wa(e.definition,t))}var pl=0,ml=1,hl=2;async function gl(e,t,n){let r,i,a=new Set(t),o=await Mc(e);for(let[t,s]of o){if(!s.disabled&&Lc(a,s.mutatorNames)&&Tc(n,s.indexes))return{type:hl,clientGroupID:t,headHash:s.headHash};let o=await Ta(s.headHash,e);Ba(o);let{cookieJSON:c}=o.meta;(r===void 0||ti(c,r)>0)&&(r=c,i=o)}return i?{type:ml,snapshot:i}:{type:pl}}function _l(e){let t=new Set;for(let n of e.values())if(Yc(n)){for(let e of n.refreshHashes)t.add(e);n.persistHash&&t.add(n.persistHash)}else t.add(n.headHash),Xc(n)&&n.tempRefreshHash&&t.add(n.tempRefreshHash);return wi(t)}async function vl(e,t){let n=await yl(e,t);if(n)return Rc(n,t)}async function yl(e,t){let n=await ll(e,t);if(!(!n||!Xc(n)))return n.clientGroupID}async function bl(e,t,n){let r=await il(n);return xl(new Map(r).set(e,t),n)}async function xl(e,t){let n=rl(e,t),r=t.createChunk(n,_l(e));return await t.putChunk(r),await t.setHead(Zc,r.hash),r.hash}var Sl=typeof navigator<`u`?navigator:void 0,Cl=Symbol(),wl=class{r=new Map;#e;constructor(e){this.#e=e}has(e){switch(this.r.get(e)){case void 0:return this.#e.has(e);case Cl:return oi;default:return ai}}async get(e){let t=this.r.get(e);switch(t){case Cl:return;case void 0:return Ci(await this.#e.get(e));default:return t}}put(e,t){return this.r.set(e,_i(t)),si}del(e){return this.r.set(e,Cl),si}release(){this.#e.release()}get closed(){return this.#e.closed}},Tl={durability:`relaxed`},El=`chunks`,Dl=class{#e;#t=!1;#n=!1;constructor(e){this.#e=Nl(e)}read(){return this.#r(jl)}write(){return this.#r(Al)}async close(){this.#n||(await this.#e).close(),this.#t=!0}get closed(){return this.#t}async#r(e){let t=async e=>{let{promise:t,resolve:n,reject:r}=O(),i=indexedDB.open(e);i.onupgradeneeded=()=>{let t=i.transaction;yr(t),t.abort(),this.#n=!0,r(new Pl(`Replicache IndexedDB not found: ${e}`))},i.onsuccess=()=>n(i.result),i.onerror=()=>r(i.error);let a=await t;return a.onversionchange=()=>a.close(),a},n=await this.#e;try{return e(n)}catch(r){if(!this.#t&&r instanceof DOMException){if(r.name===`InvalidStateError`)return this.#e=t(n.name),e(await this.#e);if(r.name===`NotFoundError`)throw this.#n=!0,indexedDB.deleteDatabase(n.name),new Pl(`Replicache IndexedDB ${n.name} missing object store. Deleting db.`)}throw r}}},Ol=class{#e;#t=!1;constructor(e){this.#e=e}has(e){return new Promise((t,n)=>{let r=Ml(this.#e).count(e);r.onsuccess=()=>t(r.result>0),r.onerror=()=>n(r.error)})}get(e){return new Promise((t,n)=>{let r=Ml(this.#e).get(e);r.onsuccess=()=>t(Ci(r.result)),r.onerror=()=>n(r.error)})}release(){this.#t=!0}get closed(){return this.#t}},kl=class extends wl{#e;#t=!1;constructor(e){super(new Ol(e)),this.#e=e}commit(){return this.r.size===0?si:new Promise((e,t)=>{let n=this.#e,r=Ml(n);for(let[e,t]of this.r)t===Cl?r.delete(e):r.put(t,e);n.oncomplete=()=>e(),n.onerror=()=>t(n.error)})}release(){this.#t=!0}get closed(){return this.#t}};function Al(e){return new kl(e.transaction(El,`readwrite`,Tl))}function jl(e){return new Ol(e.transaction(El,`readonly`))}function Ml(e){return e.objectStore(El)}function Nl(e){return new Promise((t,n)=>{let r=indexedDB.open(e);r.onupgradeneeded=()=>{r.result.createObjectStore(El)},r.onsuccess=()=>{let e=r.result;e.onversionchange=()=>e.close(),t(e)},r.onerror=()=>n(r.error)})}var Pl=class extends Error{name=`IDBNotFoundError`},Fl=class{#e;#t;#n=!1;constructor(e,t){this.#e=e,this.#t=t}release(){this.#t(),this.#n=!0}get closed(){return this.#n}has(e){return Promise.resolve(this.#e.has(e))}get(e){return Promise.resolve(this.#e.get(e))}},Il=class extends wl{#e;constructor(e,t){super(new Fl(e,t)),this.#e=e}commit(){return this.r.forEach((e,t)=>{e===Cl?this.#e.delete(t):this.#e.set(t,e)}),this.r.clear(),this.release(),si}},Ll=new Map;function Rl(e){return Ll.delete(e),si}var zl=class{#e;#t;#n=!1;constructor(e){let t=Ll.get(e),n,r;t?{lock:n,map:r}=t:(n=new Yt,r=new Map,Ll.set(e,{lock:n,map:r})),this.#t=n,this.#e=r}async read(){let e=await this.#t.read();return new Fl(this.#e,e)}async write(){let e=await this.#t.write();return new Il(this.#e,e)}close(){return this.#n=!0,si}get closed(){return this.#n}},Bl=class{#e;#t;#n;constructor(e,t){this.#e=e,this.#t=t,this.#n=new Dl(t)}read(){return this.#r(e=>e.read())}write(){return this.#r(e=>e.write())}async#r(e){try{return await e(this.#n)}catch(t){if(Vl(t))return this.#n instanceof Dl&&(this.#e.info?.(`Switching to MemStore because of Firefox private browsing error`),this.#n=new zl(this.#t)),e(this.#n);throw t}}close(){return this.#n.close()}get closed(){return this.#n.closed}};function Vl(e){return Hl()&&e instanceof DOMException&&e.name===`InvalidStateError`&&e.message===`A mutation operation was attempted on a database that did not allow mutations.`}function Hl(){return Sl?.userAgent.includes(`Firefox`)??!1}function Ul(e,t){return Hl()?new Bl(e,t):new Dl(t)}function Wl(e){if(!Hl())return Gl(e);try{return Gl(e)}catch(t){if(Vl(t))return Rl(e)}return si}function Gl(e){return new Promise((t,n)=>{let r=indexedDB.deleteDatabase(e);r.onsuccess=()=>t(),r.onerror=()=>n(r.error)})}var Kl=e=>new yf(e),ql=401;function Jl(e,t){return Yl(e,t,7)}function Yl(e,t,n){let r=`rep:${e}:${n}`;return t?`${r}:${t}`:r}var Xl=class{#e;constructor(e){this.#e=Kl(e)}get pullURL(){return this.#e.pullURL}set pullURL(e){this.#e.pullURL=e}get pushURL(){return this.#e.pushURL}set pushURL(e){this.#e.pushURL=e}get auth(){return this.#e.auth}set auth(e){this.#e.auth=e}get name(){return this.#e.name}get idbName(){return Jl(this.name,this.schemaVersion)}get schemaVersion(){return this.#e.schemaVersion}get mutate(){return this.#e.mutate}get pullInterval(){return this.#e.pullInterval}set pullInterval(e){this.#e.pullInterval=e}get pushDelay(){return this.#e.pushDelay}set pushDelay(e){this.#e.pushDelay=e}get puller(){return this.#e.puller}set puller(e){this.#e.puller=e}get pusher(){return this.#e.pusher}set pusher(e){this.#e.pusher=e}get requestOptions(){return this.#e.requestOptions}get onSync(){return this.#e.onSync}set onSync(e){this.#e.onSync=e}get onClientStateNotFound(){return this.#e.onClientStateNotFound}set onClientStateNotFound(e){this.#e.onClientStateNotFound=e}get onUpdateNeeded(){return this.#e.onUpdateNeeded}set onUpdateNeeded(e){this.#e.onUpdateNeeded=e}get getAuth(){return this.#e.getAuth}set getAuth(e){this.#e.getAuth=e}get profileID(){return this.#e.profileID}get clientID(){return this.#e.clientID}get clientGroupID(){return this.#e.clientGroupID}get onOnlineChange(){return this.#e.onOnlineChange}set onOnlineChange(e){this.#e.onOnlineChange=e}get online(){return this.#e.online}get closed(){return this.#e.closed}close(){return this.#e.close()}push({now:e=!1}={}){return this.#e.push({now:e})}pull({now:e=!1}={}){return this.#e.pull({now:e})}poke(e){return this.#e.poke(e)}subscribe(e,t){return this.#e.subscribe(e,t)}experimentalWatch(e,t){return this.#e.experimentalWatch(e,t)}query(e){return this.#e.query(e)}experimentalPendingMutations(){return this.#e.experimentalPendingMutations()}},Zl=class extends Error{};function Ql(e){return new zl(e)}function $l(e,t){switch(t){case`idb`:case void 0:return{create:t=>Ul(e,t),drop:Wl};case`mem`:return{create:Ql,drop:e=>Rl(e)};default:return t}}function eu(e){return e instanceof Error?e:Error(String(e))}async function tu(e,t,n){for(let r of n)switch(r.op){case`put`:await t.put(e,r.key,_i(r.value));break;case`update`:{let n=await t.get(r.key),i=[],a=e=>{for(let[t,n]of Object.entries(e))(!r.constrain||r.constrain.length===0||r.constrain.indexOf(t)>-1)&&i.push([t,n])};n!==void 0&&(N(n),a(n)),r.merge&&a(r.merge),await t.put(e,r.key,_i(Object.fromEntries(i)));break}case`del`:await t.del(e,r.key);break;case`clear`:await t.clear();break}}var nu=class extends Error{name=`PullError`;causedBy;constructor(e){super(`Failed to pull`),this.causedBy=e}},ru=`sync`,iu=0,au=1;function ou(e){return e.pullVersion===au}async function su(e,t,n,r,i,a,o,s,c=!0){let[l,u]=await R(a,async e=>{let n=await e.getHead(I);if(!n)throw Error(`Internal no main head found`);let r=await Ta(n,e),i=r.meta.cookieJSON;return[await r.getMutationID(t,e),i]}),{response:d,httpRequestInfo:f}=await lu(s,r,{profileID:e,clientID:t,cookie:u,lastMutationID:l,pullVersion:iu,schemaVersion:n},i);if(!d)return{httpRequestInfo:f,syncHead:F};if(!c||rc(d))return{httpRequestInfo:f,pullResponse:d,syncHead:F};let p=await uu(s,a,u,d,t,o);if(p.type===2)throw Error(`Overlapping sync`);return{httpRequestInfo:f,pullResponse:d,syncHead:p.type===0?p.syncHead:F}}async function cu(e,t,n,r,i,a,o,s,c,l=!0){let u=await R(o,async e=>{let t=await e.getHead(I);if(!t)throw Error(`Internal no main head found`);let n=(await Ta(t,e)).meta;return Ra(n),n.cookieJSON}),{response:d,httpRequestInfo:f}=await lu(c,i,{profileID:e,clientGroupID:n,cookie:u,pullVersion:au,schemaVersion:r},a);if(!d)return{httpRequestInfo:f,syncHead:F};if(!l||rc(d))return{httpRequestInfo:f,pullResponse:d,syncHead:F};let p=await fu(c,o,u,d,t,s);return{httpRequestInfo:f,pullResponse:d,syncHead:p.type===0?p.syncHead:F}}async function lu(e,t,n,r){e.debug?.(`Starting pull...`);let i=Date.now(),a;try{a=await t(n,r),e.debug?.(`...Pull ${a.response?`complete`:`failed`} in `,Date.now()-i,`ms`)}catch(e){throw new nu(eu(e))}try{return ou(n)?_c(a):vc(a),a}catch(e){throw new Zl(`Invalid puller result`,eu(e))}}function uu(e,t,n,r,i,a){return Uc(t,async t=>{A(a<=4);let o=t,s=await o.getHead(I);if(s===void 0)throw Error(`Main head disappeared`);let c=await Ta(s,o),[l,u]=Da(c,i);if(!Gr(n,u))return{type:2};if(r.lastMutationID<l)throw Error(du(`lastMutationID`,String(r.lastMutationID),String(l)));let d=_i(r.cookie??null);if(Gr(d,u))return r.patch.length>0&&e.error?.(`handlePullResponse: cookie ${JSON.stringify(u)} did not change, but patch is not empty`),r.lastMutationID!==l&&e.error?.(`handlePullResponse: cookie ${JSON.stringify(u)} did not change, but lastMutationID did change`),{type:1};let f=await ka(s,o),p;for(let e of f)if(await e.getMutationID(i,o)<=r.lastMutationID){p=e;break}if(!p)throw Error(`Internal invalid chain`);let m=await Js(c.chunk.hash,r.lastMutationID,d,t,Zs(p,t,a),i,a);await tu(e,m,r.patch);let h=new Xo(o,a,p.valueHash);for await(let t of m.map.diff(h))await Xs(e,m.indexes,t.key,()=>Promise.resolve(t.oldValue),t.newValue);return{type:0,syncHead:await m.commit(ru)}})}function du(e,t,n){return`Received ${e} ${t} is < than last snapshot ${e} ${n}; ignoring client view`}function fu(e,t,n,r,i,a){return Uc(t,async t=>{let o=t,s=await o.getHead(I);if(s===void 0)throw Error(`Main head disappeared`);let c=await Ta(s,o),l=c.meta;Ra(l);let u=l.cookieJSON;if(!Gr(n,u))return e.debug?.(`handlePullResponse: cookie mismatch, response is not applicable`),{type:2};for(let[e,t]of Object.entries(r.lastMutationIDChanges)){let n=l.lastMutationIDs[e];if(n!==void 0&&t<n)throw Error(du(`${e} lastMutationID`,String(t),String(n)))}let d=_i(r.cookie);if(ti(d,u)<0)throw Error(du(`cookie`,JSON.stringify(d),JSON.stringify(u)));if(Gr(d,u))return r.patch.length>0&&e.error?.(`handlePullResponse: cookie ${JSON.stringify(u)} did not change, but patch is not empty`),Object.keys(r.lastMutationIDChanges).length>0&&(console.log(r.lastMutationIDChanges),e.error?.(`handlePullResponse: cookie ${JSON.stringify(u)} did not change, but lastMutationIDChanges is not empty`)),{type:1};let f=await Ys(c.chunk.hash,{...l.lastMutationIDs,...r.lastMutationIDChanges},d,t,i,a);return await tu(e,f,r.patch),{type:0,syncHead:await f.commit(ru)}})}function pu(e,t,n,r,i,a){return Uc(e,async e=>{let o=e,s=await o.getHead(ru);if(s===void 0)throw Error(`Missing sync head`);if(s!==n)throw t.error?.(`maybeEndPull, Wrong sync head. Expecting:`,n,`got:`,s),Error(`Wrong sync head`);let c=await Ta(s,o),l=await o.getHead(I);if(l===void 0)throw Error(`Missing main head`);let u=await Ta(l,o),{meta:d}=c,f=d.basisHash;if(c===null)throw Error(`Sync snapshot with no basis`);if(f!==u.chunk.hash)throw Error(`Overlapping syncs`);let p=await L(s,o),m=[],h=await ba(l,o);for(let e of h){let t=r;pa(e)&&(t=e.meta.clientID),await e.getMutationID(t,o)>await p.getMutationID(t,o)&&m.push(e)}m.reverse();let g=new Us;if(m.length>0)return{syncHead:s,replayMutations:m,diffs:g};let _=await L(l,o);if(i.shouldComputeDiffs()){let e=await zs(new Xo(o,a,_.valueHash),new Xo(o,a,p.valueHash));g.set(``,e),await Gs(_,p,o,g,i,a)}if(await Promise.all([e.setHead(I,s),e.removeHead(ru)]),await e.commit(),t.debug){let[e,n]=Da(u,r),[i,a]=Da(c,r);t.debug(`Successfully pulled new snapshot with lastMutationID:`,i,`(prev:`,e,`), cookie: `,a,`(prev:`,n,`), sync head hash:`,s,`, main head hash:`,l,`, valueHash:`,p.valueHash,`(prev:`,u.valueHash)}return{syncHead:s,replayMutations:[],diffs:g}})}var mu=[],hu=P.unknown().chain(e=>{if(Hr)return ln(e);let t=Xr(e,mu)?ln(e):un({message:`Not a JSON value`,path:mu.slice()});return mu.length=0,t});P.unknown().chain(e=>{if(Hr)return ln(e);let t=Zr(e,mu)?ln(e):un({message:`Not a JSON object`,path:mu.slice()});return mu.length=0,t});function gu(e){N(e),cc(e.httpRequestInfo),e.response!==void 0&&_u(e.response)}function _u(e){ic(e)||oc(e)}var vu=class extends Error{name=`PushError`;causedBy;constructor(e){super(`Failed to push`),this.causedBy=e}},yu=0,bu=1,xu=zi({id:P.number(),name:P.string(),args:hu,timestamp:P.number()}),Su=zi({id:P.number(),name:P.string(),args:hu,timestamp:P.number(),clientID:Hc});P.object({pushVersion:P.literal(0),schemaVersion:P.string(),profileID:P.string(),clientID:Hc,mutations:P.array(xu)}),P.object({pushVersion:P.literal(1),schemaVersion:P.string(),profileID:P.string(),clientGroupID:Vc,mutations:P.array(Su)});function Cu(e){return{id:e.mutationID,name:e.mutatorName,args:e.mutatorArgsJSON,timestamp:e.timestamp}}function wu(e){return{id:e.mutationID,name:e.mutatorName,args:e.mutatorArgsJSON,timestamp:e.timestamp,clientID:e.clientID}}async function Tu(e,t,n,r,i,a,o,s,c){let l=await R(t,async e=>{let t=await e.getHead(I);if(!t)throw Error(`Internal no main head`);return ba(t,e)});if(l.length===0)return;l.reverse();let u;if(c===bu){let e=[];for(let t of l)if(pa(t))e.push(wu(t.meta));else throw Error(`Internal non local pending commit`);A(i),u={profileID:r,clientGroupID:i,mutations:e,pushVersion:bu,schemaVersion:s}}else{A(c===yu);let e=[];for(let t of l)if(fa(t))e.push(Cu(t.meta));else throw Error(`Internal non local pending commit`);u={profileID:r,clientID:a,mutations:e,pushVersion:yu,schemaVersion:s}}n.debug?.(`Starting push...`);let d=Date.now(),f=await Eu(o,u,e);return n.debug?.(`...Push complete in `,Date.now()-d,`ms`),f}async function Eu(e,t,n){let r;try{r=await e(t,n)}catch(e){throw new vu(eu(e))}try{return gu(r),r}catch(e){throw new Zl(`Invalid pusher result`,eu(e))}}var Du=10*2**20,Ou=class{#e=!1;#t;constructor(e){this.#t=e}async recoverMutations(e,t,n,r,i,a){let{lc:o,enableMutationRecovery:s,isPushDisabled:c,delegate:l}=this.#t;if(!s||this.#e||!l.online||l.closed||c())return!1;let u=`Recovering mutations.`;o.debug?.(`Start:`,u);try{this.#e=!0,await t,await Mu(r,this.#t,n,e);for(let e of Object.values(await i.getDatabases())){if(l.closed)return o.debug?.(`Exiting early due to close:`,u),!0;if(e.replicacheName===l.name&&e.name!==l.idbName)switch(e.replicacheFormatVersion){case 4:case 5:case 6:case 7:await ju(e,this.#t,void 0,a)}}}catch(e){ku(e,o,u,l)}finally{o.debug?.(`End:`,u),this.#e=!1}return!0}};function ku(e,t,n,r){r.closed?t.debug?.(`Mutation recovery error likely due to close during:
2
2
  ${n}
3
3
  Error:
4
4
  `,e):t.error?.(`Mutation recovery error during:
5
5
  ${n}
6
6
  Error:
7
- `,e)}async function ju(e,t,n,r,i,a){k(r.replicacheFormatVersion===4),tl(e);let{delegate:o,lc:s,wrapInOnlineCheck:c,wrapInReauthRetries:l,isPushDisabled:u,isPullDisabled:d}=i,f=o.clientID;if(f===t||e.lastServerAckdMutationID>=e.mutationID)return;let p=`Recovering mutations for ${t}.`;s.debug?.(`Start:`,p);let m=new na(n,Ou,ki,Yi);try{if(await R(m,t=>t.setHead(F,e.headHash)),u()){s.debug?.(`Cannot recover mutations for client ${t} because push is disabled.`);return}let{pusher:i}=o,p=`recoveringMutationsPush`;if(!await c(async()=>{let{result:e}=await l(async(e,n)=>{xr(m);let a=await Eu(e,m,n,await o.profileID,void 0,t,i,r.schemaVersion,bu);return{result:a,httpRequestInfo:a?.httpRequestInfo}},p,s);return!!e&&e.httpRequestInfo.httpStatusCode===200},p)){s.debug?.(`Failed to recover mutations for client ${t} due to a push error.`);return}if(d()){s.debug?.(`Cannot confirm mutations were recovered for client ${t} because pull is disabled.`);return}let{puller:h}=o,g=`recoveringMutationsPull`,_;if(!await c(async()=>{let{result:e}=await l(async(e,n)=>{let i=await cu(await o.profileID,t,r.schemaVersion,h,e,m,a,n,!1);return{result:i,httpRequestInfo:i.httpRequestInfo}},g,s);return{pullResponse:_}=e,!!_&&e.httpRequestInfo.httpStatusCode===200},g)){s.debug?.(`Failed to recover mutations for client ${t} due to a pull error.`);return}return s.debug&&_&&(ac(_)?s.debug?.(`Client ${f} cannot recover mutations for client ${t}. The client no longer exists on the server.`):oc(_)?s.debug?.(`Version is not supported on the server. versionType: ${_.versionType}. Cannot recover mutations for client ${t}.`):s.debug?.(`Client ${f} recovered mutations for client ${t}. Details`,{mutationID:e.mutationID,lastServerAckdMutationID:e.lastServerAckdMutationID,lastMutationID:_.lastMutationID})),await R(n,async e=>{let n=await al(e),r=n.get(t);if(!r)return n;tl(r);let i=async t=>(await Sl(t,e),t);if(ac(_)||oc(_)){let e=new Map(n);return e.delete(t),i(e)}return k(_),r.lastServerAckdMutationID>=_.lastMutationID?n:i(new Map(n).set(t,{...r,lastServerAckdMutationID:_.lastMutationID}))})}catch(e){Au(e,s,p,o)}finally{await m.close(),s.debug?.(`End:`,p)}}async function Mu(e,t,n,r){let i=new ua(r(e.name),Gi,Yi);try{await Nu(e,t,i,n)}finally{await i.close()}}function Nu(e,t,n,r){return e.replicacheFormatVersion>=5?Fu(e,t,n):Pu(e,t,n,r)}async function Pu(e,t,n,r){let{delegate:i,lc:a}=t,o=`Recovering mutations from db ${e.name}.`;a.debug?.(`Start:`,o);try{let s=xo(e.replicacheFormatVersion),c=r||await L(n,e=>al(e)),l=new Set;for(;c;){let r;for(let[u,d]of c){if(i.closed){a.debug?.(`Exiting early due to close:`,o);return}if(!l.has(u)&&(l.add(u),r=await ju(d,u,n,e,t,s),r))break}c=r}}catch(e){Au(e,a,o,i)}a.debug?.(`End:`,o)}async function Fu(e,t,n){let{delegate:r,lc:i}=t,a=`Recovering mutations from db ${e.name}.`;i.debug?.(`Start:`,a);try{let o=xo(e.replicacheFormatVersion),s=await L(n,e=>Nc(e)),c=new Set;for(;s;){let l;for(let[u,d]of s){if(r.closed){i.debug?.(`Exiting early due to close:`,a);return}if(!c.has(u)&&(c.add(u),l=await Ru(d,u,n,e,t,o),l))break}s=l}}catch(e){Au(e,i,a,r)}i.debug?.(`End:`,a)}function Iu(e){return ac(e)||oc(e)}async function Lu(e,t,n,r,i){ac(r)?e.debug?.(`Client group ${t} cannot recover mutations for client group ${n}. The client group is unknown on the server. Marking it as disabled.`):oc(r)&&e.debug?.(`Client group ${t} cannot recover mutations for client group ${n}. The client group's version is not supported on the server. versionType: ${r.versionType}. Marking it as disabled.`),await R(i,e=>Vc(n,e))}async function Ru(e,t,n,r,i,a){k(r.replicacheFormatVersion>=5);let{delegate:o,lc:s,wrapInOnlineCheck:c,wrapInReauthRetries:l,isPushDisabled:u,isPullDisabled:d,clientGroupIDPromise:f}=i,p=await f;if(xr(p),p===t)return;let m,h=!0;for(let[t,n]of Object.entries(e.mutationIDs))if(!e.lastServerAckdMutationIDs[t]||e.lastServerAckdMutationIDs[t]<n){m=t,h=!1;break}if(h)return;if(e.disabled){s.debug?.(`Not recovering mutations for client group ${t} because group is disabled.`);return}let g=`Recovering mutations for client group ${t}.`;s.debug?.(`Start:`,g);let _=new na(n,Ou,ki,Yi);try{if(await R(_,t=>t.setHead(F,e.headHash)),u()){s.debug?.(`Cannot recover mutations for client group ${t} because push is disabled.`);return}let{pusher:i}=o,f=`recoveringMutationsPush`;if(!await c(async()=>{let{result:e}=await l(async(e,n)=>{k(m),k(_);let a=await Eu(e,_,n,await o.profileID,t,m,i,r.schemaVersion,xu);return{result:a,httpRequestInfo:a?.httpRequestInfo}},f,s);if(!e)return!1;let a=e.response;return Iu(a)?(await Lu(s,p,t,a,n),!1):e.httpRequestInfo.httpStatusCode===200},f)){s.debug?.(`Failed to recover mutations for client ${t} due to a push error.`);return}if(d()){s.debug?.(`Cannot confirm mutations were recovered for client ${t} because pull is disabled.`);return}let{puller:h}=o,g=`recoveringMutationsPull`,v;if(!await c(async()=>{let{result:e}=await l(async(e,n)=>{k(m);let i=await lu(await o.profileID,m,t,r.schemaVersion,h,e,_,a,n,!1);return{result:i,httpRequestInfo:i.httpRequestInfo}},g,s),{pullResponse:i}=e;return Iu(i)?(await Lu(s,p,t,i,n),!1):!i||e.httpRequestInfo.httpStatusCode!==200?!1:(v=i,!0)},g)){s.debug?.(`Failed to recover mutations for client ${t} due to a pull error.`);return}return k(v),s.debug?.(`Client group ${p} recovered mutations for client group ${t}. Details`,{mutationIDs:e.mutationIDs,lastServerAckdMutationIDs:e.lastServerAckdMutationIDs,lastMutationIDChanges:v.lastMutationIDChanges}),await R(n,async e=>{let n=await Nc(e),r=n.get(t);if(!r)return n;k(v);let i={},a=!1;for(let[e,t]of Object.entries(v.lastMutationIDChanges))(r.lastServerAckdMutationIDs[e]??0)<t&&(i[e]=t,a=!0);if(!a)return n;let o=new Map(n).set(t,{...r,lastServerAckdMutationIDs:{...r.lastServerAckdMutationIDs,...i}});return await Pc(o,e),o})}catch(e){Au(e,s,g,o)}finally{await _.close(),s.debug?.(`End:`,g)}}var zu=class{name;onmessage=null;onmessageerror=null;constructor(e){this.name=e}addEventListener(){}removeEventListener(){}dispatchEvent(){return!1}close(){}postMessage(){}},Bu=typeof BroadcastChannel>`u`?zu:BroadcastChannel;function Vu(e){return`replicache-new-client-group:${e}`}function Hu(e){return`replicache-new-client-group-v1:${e}`}function Uu(e){return typeof e==`object`&&typeof e.clientGroupID==`string`&&typeof e.idbName==`string`}function Wu(e,t,n,r,i,a,o){if(n.aborted)return;let s=new Bu(Hu(e));if(i){s.postMessage({clientGroupID:r,idbName:t});let n=new Bu(Vu(e));n.postMessage([r]),n.close()}s.onmessage=async e=>{let{data:n}=e;if(Uu(n)){let{clientGroupID:e,idbName:i}=n;if(e!==r){if(i===t)await L(o,async t=>await zc(e,t)!==void 0)&&a();else{a();return}}}},n.addEventListener(`abort`,()=>s.close(),{once:!0})}function Gu(e){return`replicache-on-persist:${e}`}function Ku(e){M(e),A(e.clientGroupID),A(e.clientID)}function qu(e,t,n){if(t.aborted)return()=>{};let r=new Bu(Gu(e));return r.onmessage=e=>{let{data:t}=e;Ku(t),n({clientGroupID:t.clientGroupID,clientID:t.clientID})},t.addEventListener(`abort`,()=>r.close(),{once:!0}),e=>{t.aborted||(r.postMessage(e),n(e))}}async function Ju(e){return(await Sa(await ta(F,e),e)).map(e=>({id:e.meta.mutationID,name:e.meta.mutatorName,args:e.meta.mutatorArgsJSON,clientID:e.meta.clientID})).reverse()}function Yu(e,t,n,r,i){Xu(e,t,n,r,i)}async function Xu(e,t,n,r,i){if(!i.aborted){for(r=r.withContext(`bgIntervalProcess`,e),r.debug?.(`Starting`);!i.aborted;){try{await Nr(n(),i)}catch(e){if(!(e instanceof mr))throw e}if(!i.aborted){r.debug?.(`Running`);try{await t()}catch(e){i.aborted?r.debug?.(`Error running most likely due to close.`,e):r.error?.(`Error running.`,e)}}}r.debug?.(`Stopping`)}}var Zu=864e5,Qu=3e5,$u;function ed(e,t,n,r,i,a){Yu(`ClientGC`,()=>($u=td(e,t,n),$u),()=>r,i,a)}function td(e,t,n){return R(t,async t=>{let r=Date.now(),i=await al(t),a=Array.from(i).filter(([t,i])=>t===e||r-i.heartbeatTimestampMs<=n);if(a.length===i.size)return i;let o=new Map(a);return await Sl(o,t),o})}var nd=3e5,rd;function id(e,t,n){Yu(`ClientGroupGC`,()=>(rd=ad(e),rd),()=>nd,t,n)}function ad(e){return R(e,async e=>{let t=await al(e),n=new Set;for(let e of t.values())nl(e),n.add(e.clientGroupID);let r=new Map;for(let[t,i]of await Nc(e))(n.has(t)||Bc(i))&&r.set(t,i);return await Pc(r,e),r})}var od=`replicache-dbs-v0`,sd=``;function cd(){return sd+od}var ld=`dbs`,ud=`profileId`;function dd(e){M(e);for(let[t,n]of Object.entries(e))A(t),fd(n),k(t===n.name)}function fd(e){M(e),A(e.name),A(e.replicacheName),j(e.replicacheFormatVersion),A(e.schemaVersion),e.lastOpenedTimestampMS!==void 0&&j(e.lastOpenedTimestampMS)}var pd=class{#e;constructor(e){this.#e=e(cd())}putDatabase(e){return this.#t({...e,lastOpenedTimestampMS:Date.now()})}putDatabaseForTesting(e){return this.#t(e)}#t(e){return R(this.#e,async t=>{let n={...await md(t),[e.name]:e};return await t.put(ld,n),n})}clearDatabases(){return R(this.#e,e=>e.del(ld))}deleteDatabases(e){return R(this.#e,async t=>{let n={...await md(t)};for(let t of e)delete n[t];await t.put(ld,n)})}getDatabases(){return L(this.#e,md)}close(){return this.#e.close()}getProfileID(){return R(this.#e,async e=>{let t=await e.get(ud);return t===void 0&&(t=`p${Kc()}`,await e.put(ud,t)),A(t),t})}};async function md(e){let t=await e.get(ld);return t||=vi({}),dd(t),t}var hd=432e5,gd=2592e6,_d=3e5;function vd(e,t,n,r,i,a,o,s){let c=!0;Yu(`CollectIDBDatabases`,async()=>{await yd(e,Date.now(),i,a,t)},()=>c?(c=!1,r):n,o,s)}async function yd(e,t,n,r,i,a=Sd){let o=await e.getDatabases(),s=Object.values(o),{errors:c}=await xd(e,(await Promise.all(s.map(async e=>[e.name,await Cd(e,t,n,r,a)]))).filter(e=>e[1]).map(e=>e[0]),i);if(c.length)throw c[0]}async function bd(e,t,n){await n(e),await t.deleteDatabases([e])}async function xd(e,t,n){let r=await Promise.allSettled(t.map(async t=>(await bd(t,e,n),t))),i=[],a=[];for(let e of r)e.status===`fulfilled`?i.push(e.value):a.push(e.reason);return{dropped:i,errors:a}}function Sd(e){return new ua(new Ol(e),Gi,Yi)}async function Cd(e,t,n,r,i){if(e.replicacheFormatVersion>7)return!1;if(e.lastOpenedTimestampMS!==void 0){let a=e.replicacheFormatVersion>=5;return t-e.lastOpenedTimestampMS<(a?r:n)?!1:!a||(k(e.replicacheFormatVersion===5||e.replicacheFormatVersion===6||e.replicacheFormatVersion===7),!await Td(i(e.name)))}let a=i(e.name),o=await L(a,al);return await a.close(),wd(o,t,n)}function wd(e,t,n){for(let r of e.values())if(t-r.heartbeatTimestampMs<n)return!1;return!0}async function Td(e){let t=await L(e,Nc);for(let e of t.values())if(Bc(e))return!0;return!1}var Ed=6e4,Dd;function Od(e,t,n,r,i,a){Yu(`Heartbeat`,async()=>{Dd=kd(e,t);try{return await Dd}catch(e){if(e instanceof sl){n();return}throw e}},()=>r,i,a)}function kd(e,t){return R(t,async t=>{let n=await al(t),r=n.get(e);if(!r)throw new sl(e);let i={...r,heartbeatTimestampMs:Date.now()},a=new Map(n).set(e,i);return await Sl(a,t),a})}var Ad=class{#e=new Set;#t;constructor(e){this.#t=e}async visit(e){if(this.#e.has(e))return;this.#e.add(e);let t=await this.#t.mustGetChunk(e);await this.visitChunk(t)}async visitChunk(e){await Promise.all(e.meta.map(e=>this.visit(e)))}},jd=class extends Ad{#e=new Map;#t;constructor(e){super(e),this.#t=e}get gatheredChunks(){return this.#e}visit(e){return this.#t.isMemOnlyChunkHash(e)?super.visit(e):ci}visitChunk(e){return this.#e.set(e.hash,e),super.visitChunk(e)}};async function Md(e,t,n,r,i,a,o,s=()=>Promise.resolve()){if(a())return;let[c,l,u]=await L(r,async e=>{await cl(t,e);let n=await bl(t,e);k(n,`No main client group for clientID: ${t}`);let[,r]=await Nd(e,n),i=await r.getMutationID(t,e),a=await Da(r,e);return Va(a),[i,a,n]});if(a())return;let[d,f,p]=await L(n,async e=>{let n=await ja(F,e),r=await Ca(n,{[t]:c||0},e),i=await Da(n,e);Va(i);let a;if(ka(i,l)>0){await s();let t=i.chunk.hash,n=new jd(e);await n.visit(t),a=n.gatheredChunks}return[r,i,a]});if(a())return;let m=!1;await R(r,async n=>{let[r,a]=await Nd(n,u),s=a.chunk.hash,c={...r.mutationIDs},{lastServerAckdMutationIDs:l}=r;if(p){let u=await dl(t,n);nl(u);let d=await Da(a,n);if(Va(d),ka(f,d)>0){m=!0,await Promise.all(Array.from(p.values(),e=>n.putChunk(e))),await xl(t,{...u,persistHash:f.chunk.hash},n),s=f.chunk.hash;let a=await Sa(r.headHash,n);l=f.meta.lastMutationIDs,c={...l},s=await Pd(a,s,n,i,c,e,o)}}s=await Pd(d,s,n,i,c,e,o);let h={...r,headHash:s,mutationIDs:c,lastServerAckdMutationIDs:l};await Fc(u,h,n)}),p&&m&&await R(n,e=>e.chunksPersisted([...p.keys()]))}async function Nd(e,t){let n=await zc(t,e);return k(n,`No client group for clientGroupID: ${t}`),[n,await I(n.headHash,e)]}async function Pd(e,t,n,r,i,a,o){for(let s=e.length-1;s>=0;s--){let c=e[s],{meta:l}=c,u=await I(t,n);await c.getMutationID(l.clientID,n)>await u.getMutationID(l.clientID,n)&&(i[l.clientID]=l.mutationID,t=(await tc(c,n,t,r,a,l.clientID,o)).chunk.hash)}return t}var Fd=class extends Ad{#e=new Map;#t=0;#n;#r;#i;constructor(e,t,n,r=pi){super(e),this.#n=t,this.#r=n,this.#i=r}get gatheredChunks(){return this.#e}visit(e){return this.#t>=this.#r||this.#n.isCached(e)?ci:super.visit(e)}visitChunk(e){if(this.#t<this.#r){let t=this.#i(e);this.#e.set(e.hash,{chunk:e,size:t}),this.#t+=t}return super.visitChunk(e)}},Id=5*2**20,Ld=300;async function Rd(e,t,n,r,i,a,o,s){if(o())return;let c=await L(t,e=>wa(F,e));Va(c);let l=await t.withSuspendedSourceCacheEvictsAndDeletes(async()=>{let l=await R(n,async e=>{let n=await yl(r,e);if(!n)throw new sl(r);let i=n.headHash,a=await(await I(i,e)).getMutationID(r,e),o=await dl(r,e);nl(o);let s=await Ea(i,e);if(Va(s),zd(c,s,i))return;let l=new Fd(e,t,Id);await l.visit(i);let{gatheredChunks:u}=l,d=new Set(o.refreshHashes);return d.add(i),await xl(r,{...o,refreshHashes:[...d]},e),[i,s,a,u,o.refreshHashes]});if(o()||!l||(await Nr(Ld),o()))return{type:`aborted`};let[u,d,f,p,m]=l;return R(t,async t=>{let n=await ja(F,t),o=await Da(n,t);if(Va(o),zd(o,d,u))return{type:`aborted`,refreshHashesForRevert:m};let c=await Ca(n,{[r]:f},t),l=[];for(let{chunk:e,size:n}of p.values())l.push(t.putChunk(e,n));await Promise.all(l);let h=u;for(let n=c.length-1;n>=0;n--)h=(await tc(c[n],t,h,i,e,c[n].meta.clientID,s)).chunk.hash;let g=await Gs(n,await I(h,t),t,a,s);return await t.setHead(F,h),{type:`complete`,diffs:g,newPerdagClientHeadHash:u}})});if(o())return;let u=e=>R(n,async t=>{await xl(r,{...await dl(r,t),refreshHashes:e},t)});if(l.type===`aborted`){l.refreshHashesForRevert&&await u(l.refreshHashesForRevert);return}return await u([l.newPerdagClientHeadHash]),l.diffs}function zd(e,t,n){let r=ka(e,t);return r>0||r===0&&n===t.chunk.hash}function Bd(e){return new Promise(t=>{typeof requestIdleCallback==`function`?requestIdleCallback(()=>t(),{timeout:e}):setTimeout(()=>t(),e)})}var Vd=class{#e;#t;#n;#r;#i;#a=void 0;#o=void 0;#s=Promise.resolve();#c=Promise.resolve();constructor(e,t,n,r,i=Bd){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i,this.#r.addEventListener(`abort`,()=>{let e=new mr(`Aborted`);this.#o?.reject(e),this.#a?.reject(e),this.#o=void 0,this.#a=void 0},{once:!0})}schedule(){return this.#r.aborted?Promise.reject(new mr(`Aborted`)):this.#a?this.#a.promise:(this.#a=D(),this.#l(),this.#a.promise)}async#l(){try{await this.#s}catch{}if(await this.#c,this.#a&&(await this.#i(this.#t),this.#a)){this.#c=Hd(this.#n,this.#r),this.#o=this.#a,this.#a=void 0;try{this.#s=this.#e(),await this.#s,this.#o?.resolve()}catch(e){this.#o?.reject(e)}this.#o=void 0}}};async function Hd(e,t){try{await Nr(e,t)}catch(e){k(e instanceof mr)}}function Ud(e,t,n){let r=setInterval(e,t);n.addEventListener(`abort`,()=>{clearInterval(r)})}var Wd=new Set,Gd=Symbol(),Kd=class{#e;#t;#n=Gd;#r=Wd;#i=[];onError;onDone;#a;constructor(e,t,n,r,i=Kr){this.#e=e,this.#t=t,this.onError=n,this.onDone=r,this.#a=i}hasIndexSubscription(e){for(let t of this.#i)if(t.options.indexName===e)return!0;return!1}invoke(e,t,n){return this.#e(e)}matches(e){for(let[t,n]of e)if(Xd(this.#r,this.#i,t,n))return!0;return!1}updateDeps(e,t){this.#r=e,this.#i=t}onData(e){(this.#n===Gd||!this.#a(this.#n,e))&&(this.#n=e,this.#t(e))}},qd=class{#e;#t;#n;#r;onError=void 0;onDone=void 0;constructor(e,t){this.#e=e,this.#t=t?.prefix??``,this.#n=t?.indexName,this.#r=t?.initialValuesInFirstDiff??!1}hasIndexSubscription(e){return this.#n===e}onData(e){e!==void 0&&this.#e(e)}invoke(e,t,n){let r=async(r,i,a,o)=>{let s;if(t===0){if(!this.#r)return;k(n===void 0);let t=[];for await(let n of e.scan({prefix:i,indexName:r}).entries())t.push({op:`add`,key:n[0],newValue:n[1]});s=t}else k(n),s=o(n.get(r??``)??[]);let c=[],{length:l}=s;for(let e=nf(s,i,a);e<l&&a(s[e]).startsWith(i);e++)c.push(s[e]);return t===0||c.length>0?c:void 0};return this.#n?r(this.#n,this.#t,e=>e.key[0],e=>Jd(e,us)):r(void 0,this.#t,e=>e.key,e=>Jd(e,e=>e))}matches(e){let t=e.get(this.#n??``);return t!==void 0&&tf(t,this.#t,this.#n)}updateDeps(e,t){}};function Jd(e,t){return e.map(e=>{let n=t(e.key);switch(e.op){case`add`:return{op:`add`,key:n,newValue:e.newValue};case`change`:return{op:`change`,key:n,oldValue:e.oldValue,newValue:e.newValue};case`del`:return{op:`del`,key:n,oldValue:e.oldValue}}})}var Yd=class{#e=new Set;#t=new Set;#n;#r;hasPendingSubscriptionRuns=!1;constructor(e,t){this.#n=e,this.#r=t}add(e){return this.#e.add(e),this.#a(e),()=>this.#e.delete(e)}clear(){for(let e of this.#e)e.onDone?.();this.#e.clear()}async fire(e){let t=ef(this.#e,e);await this.#i(t,1,e)}async#i(e,t,n){let r=[...e];if(r.length===0)return;let i=await this.#n(e=>Promise.allSettled(r.map(async r=>{let i=new Ps(e);try{return await r.invoke(i,t,n)}finally{r.updateDeps(i.keys,i.scans)}})));this.callCallbacks(r,i)}callCallbacks(e,t){for(let n=0;n<e.length;n++){let r=e[n],i=t[n];i.status===`fulfilled`?r.onData(i.value):r.onError?r.onError(i.reason):this.#r.error?.(`Error in subscription body:`,i.reason)}}async#a(e){if(this.#t.add(e),!this.hasPendingSubscriptionRuns){this.hasPendingSubscriptionRuns=!0,await Promise.resolve(),this.hasPendingSubscriptionRuns=!1;let e=[...this.#t];this.#t.clear(),await this.#i(e,0,void 0)}}shouldComputeDiffs(){return this.#e.size>0}shouldComputeDiffsForIndex(e){for(let t of this.#e)if(t.hasIndexSubscription(e))return!0;return!1}};function Xd(e,t,n,r){if(n===``){for(let t of r)if(e.has(t.key))return!0}for(let e of t)if(Zd(e,n,r))return!0;return!1}function Zd(e,t,n){for(let r of n)if(Qd(e,t,r.key))return!0;return!1}function Qd(e,t,n){let{indexName:r=``,limit:i,prefix:a,startKey:o,startExclusive:s,startSecondaryKey:c}=e.options;if(t!==r)return!1;if(!r)return i!==void 0&&i<=0?!1:!a&&!o||!(a&&(!n.startsWith(a)||$d(e,n))||o&&(s&&yo(n,o)||vo(n,o)||$d(e,n)));if(!a&&!o&&!c)return!0;let[l,u]=us(n);return!(a&&!l.startsWith(a)||c&&(s&&yo(l,c)||vo(l,c))||o&&(s&&yo(u,o)||vo(u,o)))}function $d(e,t){let{inclusiveLimitKey:n}=e;return e.options.limit!==void 0&&n!==void 0&&_o(t,n)}function*ef(e,t){for(let n of e)n.matches(t)&&(yield n)}function tf(e,t,n){if(t===``)return!0;let r=n?e=>us(e.key)[0]:e=>e.key,i=nf(e,t,r);return i<e.length&&r(e[i]).startsWith(t)}function nf(e,t,n){return bo(e.length,r=>lo(t,n(e[r])))}function rf(e){if(e===null)throw TypeError(`array cannot be null`);for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256);return e}var af=``;function of(){if(af===``){let e=new Uint8Array(4);rf(e),af=Array.from(e,e=>e.toString(16)).join(``)}return af}var sf=new Map;function cf(e){let t=sf.get(e);return t?(t++,sf.set(e,t)):(sf.set(e,0),t=0),`${e}-${of()}-${t}`}var lf=`15.3.0`,uf=8,df=1e3,ff=1e3,pf=500,mf=500,hf=100*2**20,gf=3e5,_f=()=>{},vf={type:`NewClientGroup`},yf=(e,t)=>new Yd(e,t),bf=class{pullURL;pushURL;auth;name;subscriptions;#e;isClientGroupDisabled=!1;#t;lastMutationID=0;get idbName(){return Yl(this.name,this.schemaVersion)}schemaVersion;get#n(){return{name:this.idbName,replicacheName:this.name,replicacheFormatVersion:7,schemaVersion:this.schemaVersion}}#r=!1;#i=!0;#a=Kc();#o;#s;#c;#l={};mutate;#u=0;#d=0;#f;#p;pullInterval;pushDelay;#m;puller;pusher;memdag;perdag;#h;#g;#_=new AbortController;#v=!1;#y;#b;#x;#S=new Vd(()=>this.persist(),df,pf,this.#_.signal);#C;#w=new Vd(()=>this.refresh(),ff,mf,this.#_.signal);get requestOptions(){return this.#m}onSync=null;onClientStateNotFound=Cf;onUpdateNeeded=Cf;getAuth=null;onPushInvoked=()=>{};onBeginPull=()=>{};onRecoverMutations=e=>e;constructor(e,t={}){wf(e);let{name:n,logLevel:r=`info`,logSinks:i=[Wt],pullURL:a=``,auth:o,pushDelay:s=10,pushURL:c=``,schemaVersion:l=``,pullInterval:u=6e4,mutators:d={},requestOptions:f={},puller:p,pusher:m,indexes:h={},clientMaxAgeMs:g=Zu}=e,{enableMutationRecovery:_=!0,enableScheduledPersist:v=!0,enableScheduledRefresh:y=!0,enablePullAndPushInOpen:b=!0,makeSubscriptionsManager:ee=yf,enableClientGroupForking:te=!0}=t;this.auth=o??``,this.pullURL=a,this.pushURL=c,this.name=n,this.schemaVersion=l,this.pullInterval=u,this.pushDelay=s,this.puller=p??fc(this),this.pusher=m??bc(this),this.#y=v,this.#b=y,this.#x=b,this.#g=Cc(r,i,{name:n}),this.#g.debug?.(`Constructing Replicache`,{name:n,"replicache version":lf}),this.subscriptions=ee(this.#W,this.#g);let ne=eu(this.#g,e.kvStore);this.#t=ne;let re=ne.create(this.idbName);this.#h=new pd(ne.create),this.perdag=new ua(re,Gi,Yi),this.memdag=new na(this.perdag,hf,Gi,Yi);let ie=D();this.#o=ie.promise;let{minDelayMs:ae=Pr,maxDelayMs:oe=Fr}=f;this.#m={maxDelayMs:oe,minDelayMs:ae};let se=wr(Cr(),0,this.#_.signal);this.#f=new Ir(this.#g.withContext(`PULL`),new Ar(this,()=>this.#O()),se),this.#p=new Ir(this.#g.withContext(`PUSH`),new jr(this,()=>this.#N())),this.mutate=this.#K(d);let ce=D();this.#s=ce.promise;let le=D();this.#c=le.promise,this.#e=new ku({delegate:this,lc:this.#g,enableMutationRecovery:_,wrapInOnlineCheck:this.#A.bind(this),wrapInReauthRetries:this.#j.bind(this),isPullDisabled:this.#k.bind(this),isPushDisabled:this.#M.bind(this),clientGroupIDPromise:this.#c}),this.#C=qu(this.name,this.#_.signal,e=>{this.#B(e)}),this.#T(h,te,g,ce.resolve,le.resolve,ie.resolve)}async#T(e,t,n,r,i,a){let{clientID:o}=this;await xf.get(this.name),await this.#h.getProfileID().then(r),await this.#h.putDatabase(this.#n);let[s,c,l,u]=await fl(o,this.#g,this.perdag,Object.keys(this.#l),e,7,t);i(s.clientGroupID),await R(this.memdag,e=>e.setHead(F,c)),a(),this.#x&&(this.pull().catch(_f),this.push().catch(_f));let{signal:d}=this.#_;Od(o,this.perdag,()=>{this.#I(o)},Ed,this.#g,d),ed(o,this.perdag,n,Qu,this.#g,d),vd(this.#h,this.#t.drop,hd,_d,gd,2*n,this.#g,d),id(this.perdag,this.#g,d),Wu(this.name,this.idbName,d,s.clientGroupID,u,()=>{this.#R(vf)},this.perdag),Ud(()=>this.recoverMutations(),gf,d),this.recoverMutations(l),Cr()?.addEventListener(`visibilitychange`,this.#E)}#E=async()=>{this.#r||Cr()?.visibilityState===`visible`&&await this.#D()};async#D(){let{clientID:e}=this,t=await L(this.perdag,t=>ll(e,t));return t||this.#I(e),!t}get profileID(){return this.#s}get clientID(){return this.#a}get clientGroupID(){return this.#c}onOnlineChange=null;get online(){return this.#i}get closed(){return this.#r}async close(){this.#r=!0;let{promise:e,resolve:t}=D();xf.set(this.name,e),this.#_.abort(),Cr()?.removeEventListener(`visibilitychange`,this.#E),await this.#o;let n=[this.memdag.close(),this.perdag.close(),this.#h.close()];this.#f.close(),this.#p.close(),this.subscriptions.clear(),await Promise.all(n),xf.delete(this.name),t()}async maybeEndPull(e,t){for(;;){if(this.#r)return;await this.#o;let{clientID:n}=this,r=this.#g.withContext(`maybeEndPull`).withContext(`requestID`,t),{replayMutations:i,diffs:a}=await mu(this.memdag,r,e,n,this.subscriptions,7);if(!i||i.length===0){await this.subscriptions.fire(a),this.#z();return}for(let t of i){this.subscriptions.hasPendingSubscriptionRuns&&await Promise.resolve();let{meta:i}=t;e=await Wc(this.memdag,a=>nc(t,a,e,iu,this.#l,r,Fa(i)?i.clientID:n,7))}}}#O(){return this.#k()?Promise.resolve(!0):this.#A(async()=>{try{this.#U(0,1);let{syncHead:e,requestID:t,ok:n}=await this.beginPull();if(!n)return!1;e!==P&&await this.maybeEndPull(e,t)}catch(e){throw await this.#J(e)}finally{this.#U(0,-1)}return!0},`Pull`)}#k(){return this.isClientGroupDisabled||this.pullURL===``&&mc(this.puller)}async#A(e,t){let n=!0;try{return await e()}catch(e){return e instanceof yu||e instanceof ru?(n=!1,this.#g.debug?.(`${t} threw:
7
+ `,e)}async function Au(e,t,n,r,i,a){A(r.replicacheFormatVersion===4),el(e);let{delegate:o,lc:s,wrapInOnlineCheck:c,wrapInReauthRetries:l,isPushDisabled:u,isPullDisabled:d}=i,f=o.clientID;if(f===t||e.lastServerAckdMutationID>=e.mutationID)return;let p=`Recovering mutations for ${t}.`;s.debug?.(`Start:`,p);let m=new ta(n,Du,Oi,Ji);try{if(await z(m,t=>t.setHead(I,e.headHash)),u()){s.debug?.(`Cannot recover mutations for client ${t} because push is disabled.`);return}let{pusher:i}=o,p=`recoveringMutationsPush`;if(!await c(async()=>{let{result:e}=await l(async(e,n)=>{br(m);let a=await Tu(e,m,n,await o.profileID,void 0,t,i,r.schemaVersion,yu);return{result:a,httpRequestInfo:a?.httpRequestInfo}},p,s);return!!e&&e.httpRequestInfo.httpStatusCode===200},p)){s.debug?.(`Failed to recover mutations for client ${t} due to a push error.`);return}if(d()){s.debug?.(`Cannot confirm mutations were recovered for client ${t} because pull is disabled.`);return}let{puller:h}=o,g=`recoveringMutationsPull`,_;if(!await c(async()=>{let{result:e}=await l(async(e,n)=>{let i=await su(await o.profileID,t,r.schemaVersion,h,e,m,a,n,!1);return{result:i,httpRequestInfo:i.httpRequestInfo}},g,s);return{pullResponse:_}=e,!!_&&e.httpRequestInfo.httpStatusCode===200},g)){s.debug?.(`Failed to recover mutations for client ${t} due to a pull error.`);return}return s.debug&&_&&(ic(_)?s.debug?.(`Client ${f} cannot recover mutations for client ${t}. The client no longer exists on the server.`):ac(_)?s.debug?.(`Version is not supported on the server. versionType: ${_.versionType}. Cannot recover mutations for client ${t}.`):s.debug?.(`Client ${f} recovered mutations for client ${t}. Details`,{mutationID:e.mutationID,lastServerAckdMutationID:e.lastServerAckdMutationID,lastMutationID:_.lastMutationID})),await z(n,async e=>{let n=await il(e),r=n.get(t);if(!r)return n;el(r);let i=async t=>(await xl(t,e),t);if(ic(_)||ac(_)){let e=new Map(n);return e.delete(t),i(e)}return A(_),r.lastServerAckdMutationID>=_.lastMutationID?n:i(new Map(n).set(t,{...r,lastServerAckdMutationID:_.lastMutationID}))})}catch(e){ku(e,s,p,o)}finally{await m.close(),s.debug?.(`End:`,p)}}async function ju(e,t,n,r){let i=new la(r(e.name),Wi,Ji);try{await Mu(e,t,i,n)}finally{await i.close()}}function Mu(e,t,n,r){return e.replicacheFormatVersion>=5?Pu(e,t,n):Nu(e,t,n,r)}async function Nu(e,t,n,r){let{delegate:i,lc:a}=t,o=`Recovering mutations from db ${e.name}.`;a.debug?.(`Start:`,o);try{let s=bo(e.replicacheFormatVersion),c=r||await R(n,e=>il(e)),l=new Set;for(;c;){let r;for(let[u,d]of c){if(i.closed){a.debug?.(`Exiting early due to close:`,o);return}if(!l.has(u)&&(l.add(u),r=await Au(d,u,n,e,t,s),r))break}c=r}}catch(e){ku(e,a,o,i)}a.debug?.(`End:`,o)}async function Pu(e,t,n){let{delegate:r,lc:i}=t,a=`Recovering mutations from db ${e.name}.`;i.debug?.(`Start:`,a);try{let o=bo(e.replicacheFormatVersion),s=await R(n,e=>Mc(e)),c=new Set;for(;s;){let l;for(let[u,d]of s){if(r.closed){i.debug?.(`Exiting early due to close:`,a);return}if(!c.has(u)&&(c.add(u),l=await Lu(d,u,n,e,t,o),l))break}s=l}}catch(e){ku(e,i,a,r)}i.debug?.(`End:`,a)}function Fu(e){return ic(e)||ac(e)}async function Iu(e,t,n,r,i){ic(r)?e.debug?.(`Client group ${t} cannot recover mutations for client group ${n}. The client group is unknown on the server. Marking it as disabled.`):ac(r)&&e.debug?.(`Client group ${t} cannot recover mutations for client group ${n}. The client group's version is not supported on the server. versionType: ${r.versionType}. Marking it as disabled.`),await z(i,e=>Bc(n,e))}async function Lu(e,t,n,r,i,a){A(r.replicacheFormatVersion>=5);let{delegate:o,lc:s,wrapInOnlineCheck:c,wrapInReauthRetries:l,isPushDisabled:u,isPullDisabled:d,clientGroupIDPromise:f}=i,p=await f;if(br(p),p===t)return;let m,h=!0;for(let[t,n]of Object.entries(e.mutationIDs))if(!e.lastServerAckdMutationIDs[t]||e.lastServerAckdMutationIDs[t]<n){m=t,h=!1;break}if(h)return;if(e.disabled){s.debug?.(`Not recovering mutations for client group ${t} because group is disabled.`);return}let g=`Recovering mutations for client group ${t}.`;s.debug?.(`Start:`,g);let _=new ta(n,Du,Oi,Ji);try{if(await z(_,t=>t.setHead(I,e.headHash)),u()){s.debug?.(`Cannot recover mutations for client group ${t} because push is disabled.`);return}let{pusher:i}=o,f=`recoveringMutationsPush`;if(!await c(async()=>{let{result:e}=await l(async(e,n)=>{A(m),A(_);let a=await Tu(e,_,n,await o.profileID,t,m,i,r.schemaVersion,bu);return{result:a,httpRequestInfo:a?.httpRequestInfo}},f,s);if(!e)return!1;let a=e.response;return Fu(a)?(await Iu(s,p,t,a,n),!1):e.httpRequestInfo.httpStatusCode===200},f)){s.debug?.(`Failed to recover mutations for client ${t} due to a push error.`);return}if(d()){s.debug?.(`Cannot confirm mutations were recovered for client ${t} because pull is disabled.`);return}let{puller:h}=o,g=`recoveringMutationsPull`,v;if(!await c(async()=>{let{result:e}=await l(async(e,n)=>{A(m);let i=await cu(await o.profileID,m,t,r.schemaVersion,h,e,_,a,n,!1);return{result:i,httpRequestInfo:i.httpRequestInfo}},g,s),{pullResponse:i}=e;return Fu(i)?(await Iu(s,p,t,i,n),!1):!i||e.httpRequestInfo.httpStatusCode!==200?!1:(v=i,!0)},g)){s.debug?.(`Failed to recover mutations for client ${t} due to a pull error.`);return}return A(v),s.debug?.(`Client group ${p} recovered mutations for client group ${t}. Details`,{mutationIDs:e.mutationIDs,lastServerAckdMutationIDs:e.lastServerAckdMutationIDs,lastMutationIDChanges:v.lastMutationIDChanges}),await z(n,async e=>{let n=await Mc(e),r=n.get(t);if(!r)return n;A(v);let i={},a=!1;for(let[e,t]of Object.entries(v.lastMutationIDChanges))(r.lastServerAckdMutationIDs[e]??0)<t&&(i[e]=t,a=!0);if(!a)return n;let o=new Map(n).set(t,{...r,lastServerAckdMutationIDs:{...r.lastServerAckdMutationIDs,...i}});return await Nc(o,e),o})}catch(e){ku(e,s,g,o)}finally{await _.close(),s.debug?.(`End:`,g)}}var Ru=class{name;onmessage=null;onmessageerror=null;constructor(e){this.name=e}addEventListener(){}removeEventListener(){}dispatchEvent(){return!1}close(){}postMessage(){}},zu=typeof BroadcastChannel>`u`?Ru:BroadcastChannel;function Bu(e){return`replicache-new-client-group:${e}`}function Vu(e){return`replicache-new-client-group-v1:${e}`}function Hu(e){return typeof e==`object`&&typeof e.clientGroupID==`string`&&typeof e.idbName==`string`}function Uu(e,t,n,r,i,a,o){if(n.aborted)return;let s=new zu(Vu(e));if(i){s.postMessage({clientGroupID:r,idbName:t});let n=new zu(Bu(e));n.postMessage([r]),n.close()}s.onmessage=async e=>{let{data:n}=e;if(Hu(n)){let{clientGroupID:e,idbName:i}=n;if(e!==r){if(i===t)await R(o,async t=>await Rc(e,t)!==void 0)&&a();else{a();return}}}},n.addEventListener(`abort`,()=>s.close(),{once:!0})}function Wu(e){return`replicache-on-persist:${e}`}function Gu(e){N(e),j(e.clientGroupID),j(e.clientID)}function Ku(e,t,n){if(t.aborted)return()=>{};let r=new zu(Wu(e));return r.onmessage=e=>{let{data:t}=e;Gu(t),n({clientGroupID:t.clientGroupID,clientID:t.clientID})},t.addEventListener(`abort`,()=>r.close(),{once:!0}),e=>{t.aborted||(r.postMessage(e),n(e))}}async function qu(e){return(await xa(await ea(I,e),e)).map(e=>({id:e.meta.mutationID,name:e.meta.mutatorName,args:e.meta.mutatorArgsJSON,clientID:e.meta.clientID})).reverse()}function Ju(e,t,n,r,i){Yu(e,t,n,r,i)}async function Yu(e,t,n,r,i){if(!i.aborted){for(r=r.withContext(`bgIntervalProcess`,e),r.debug?.(`Starting`);!i.aborted;){try{await Mr(n(),i)}catch(e){if(!(e instanceof pr))throw e}if(!i.aborted){r.debug?.(`Running`);try{await t()}catch(e){i.aborted?r.debug?.(`Error running most likely due to close.`,e):r.error?.(`Error running.`,e)}}}r.debug?.(`Stopping`)}}var Xu=864e5,Zu=3e5,Qu;function $u(e,t,n,r,i,a){Ju(`ClientGC`,()=>(Qu=ed(e,t,n),Qu),()=>r,i,a)}function ed(e,t,n){return z(t,async t=>{let r=Date.now(),i=await il(t),a=Array.from(i).filter(([t,i])=>t===e||r-i.heartbeatTimestampMs<=n);if(a.length===i.size)return i;let o=new Map(a);return await xl(o,t),o})}var td=3e5,nd;function rd(e,t,n){Ju(`ClientGroupGC`,()=>(nd=id(e),nd),()=>td,t,n)}function id(e){return z(e,async e=>{let t=await il(e),n=new Set;for(let e of t.values())tl(e),n.add(e.clientGroupID);let r=new Map;for(let[t,i]of await Mc(e))(n.has(t)||zc(i))&&r.set(t,i);return await Nc(r,e),r})}var ad=`replicache-dbs-v0`,od=``;function sd(){return od+ad}var cd=`dbs`,ld=`profileId`;function ud(e){N(e);for(let[t,n]of Object.entries(e))j(t),dd(n),A(t===n.name)}function dd(e){N(e),j(e.name),j(e.replicacheName),M(e.replicacheFormatVersion),j(e.schemaVersion),e.lastOpenedTimestampMS!==void 0&&M(e.lastOpenedTimestampMS)}var fd=class{#e;constructor(e){this.#e=e(sd())}putDatabase(e){return this.#t({...e,lastOpenedTimestampMS:Date.now()})}putDatabaseForTesting(e){return this.#t(e)}#t(e){return z(this.#e,async t=>{let n={...await pd(t),[e.name]:e};return await t.put(cd,n),n})}clearDatabases(){return z(this.#e,e=>e.del(cd))}deleteDatabases(e){return z(this.#e,async t=>{let n={...await pd(t)};for(let t of e)delete n[t];await t.put(cd,n)})}getDatabases(){return R(this.#e,pd)}close(){return this.#e.close()}getProfileID(){return z(this.#e,async e=>{let t=await e.get(ld);return t===void 0&&(t=`p${Gc()}`,await e.put(ld,t)),j(t),t})}};async function pd(e){let t=await e.get(cd);return t||=_i({}),ud(t),t}var md=432e5,hd=2592e6,gd=3e5;function _d(e,t,n,r,i,a,o,s){let c=!0;Ju(`CollectIDBDatabases`,async()=>{await vd(e,Date.now(),i,a,t)},()=>c?(c=!1,r):n,o,s)}async function vd(e,t,n,r,i,a=xd){let o=await e.getDatabases(),s=Object.values(o),{errors:c}=await bd(e,(await Promise.all(s.map(async e=>[e.name,await Sd(e,t,n,r,a)]))).filter(e=>e[1]).map(e=>e[0]),i);if(c.length)throw c[0]}async function yd(e,t,n){await n(e),await t.deleteDatabases([e])}async function bd(e,t,n){let r=await Promise.allSettled(t.map(async t=>(await yd(t,e,n),t))),i=[],a=[];for(let e of r)e.status===`fulfilled`?i.push(e.value):a.push(e.reason);return{dropped:i,errors:a}}function xd(e){return new la(new Dl(e),Wi,Ji)}async function Sd(e,t,n,r,i){if(e.replicacheFormatVersion>7)return!1;if(e.lastOpenedTimestampMS!==void 0){let a=e.replicacheFormatVersion>=5;return t-e.lastOpenedTimestampMS<(a?r:n)?!1:!a||(A(e.replicacheFormatVersion===5||e.replicacheFormatVersion===6||e.replicacheFormatVersion===7),!await wd(i(e.name)))}let a=i(e.name),o=await R(a,il);return await a.close(),Cd(o,t,n)}function Cd(e,t,n){for(let r of e.values())if(t-r.heartbeatTimestampMs<n)return!1;return!0}async function wd(e){let t=await R(e,Mc);for(let e of t.values())if(zc(e))return!0;return!1}var Td=6e4,Ed;function Dd(e,t,n,r,i,a){Ju(`Heartbeat`,async()=>{Ed=Od(e,t);try{return await Ed}catch(e){if(e instanceof ol){n();return}throw e}},()=>r,i,a)}function Od(e,t){return z(t,async t=>{let n=await il(t),r=n.get(e);if(!r)throw new ol(e);let i={...r,heartbeatTimestampMs:Date.now()},a=new Map(n).set(e,i);return await xl(a,t),a})}var kd=class{#e=new Set;#t;constructor(e){this.#t=e}async visit(e){if(this.#e.has(e))return;this.#e.add(e);let t=await this.#t.mustGetChunk(e);await this.visitChunk(t)}async visitChunk(e){await Promise.all(e.meta.map(e=>this.visit(e)))}},Ad=class extends kd{#e=new Map;#t;constructor(e){super(e),this.#t=e}get gatheredChunks(){return this.#e}visit(e){return this.#t.isMemOnlyChunkHash(e)?super.visit(e):si}visitChunk(e){return this.#e.set(e.hash,e),super.visitChunk(e)}};async function jd(e,t,n,r,i,a,o,s=()=>Promise.resolve()){if(a())return;let[c,l,u]=await R(r,async e=>{await sl(t,e);let n=await yl(t,e);A(n,`No main client group for clientID: ${t}`);let[,r]=await Md(e,n),i=await r.getMutationID(t,e),a=await Ea(r,e);return Ba(a),[i,a,n]});if(a())return;let[d,f,p]=await R(n,async e=>{let n=await Aa(I,e),r=await Sa(n,{[t]:c||0},e),i=await Ea(n,e);Ba(i);let a;if(Oa(i,l)>0){await s();let t=i.chunk.hash,n=new Ad(e);await n.visit(t),a=n.gatheredChunks}return[r,i,a]});if(a())return;let m=!1;await z(r,async n=>{let[r,a]=await Md(n,u),s=a.chunk.hash,c={...r.mutationIDs},{lastServerAckdMutationIDs:l}=r;if(p){let u=await ul(t,n);tl(u);let d=await Ea(a,n);if(Ba(d),Oa(f,d)>0){m=!0,await Promise.all(Array.from(p.values(),e=>n.putChunk(e))),await bl(t,{...u,persistHash:f.chunk.hash},n),s=f.chunk.hash;let a=await xa(r.headHash,n);l=f.meta.lastMutationIDs,c={...l},s=await Nd(a,s,n,i,c,e,o)}}s=await Nd(d,s,n,i,c,e,o);let h={...r,headHash:s,mutationIDs:c,lastServerAckdMutationIDs:l};await Pc(u,h,n)}),p&&m&&await z(n,e=>e.chunksPersisted([...p.keys()]))}async function Md(e,t){let n=await Rc(t,e);return A(n,`No client group for clientGroupID: ${t}`),[n,await L(n.headHash,e)]}async function Nd(e,t,n,r,i,a,o){for(let s=e.length-1;s>=0;s--){let c=e[s],{meta:l}=c,u=await L(t,n);await c.getMutationID(l.clientID,n)>await u.getMutationID(l.clientID,n)&&(i[l.clientID]=l.mutationID,t=(await ec(c,n,t,r,a,l.clientID,o)).chunk.hash)}return t}var Pd=class extends kd{#e=new Map;#t=0;#n;#r;#i;constructor(e,t,n,r=fi){super(e),this.#n=t,this.#r=n,this.#i=r}get gatheredChunks(){return this.#e}visit(e){return this.#t>=this.#r||this.#n.isCached(e)?si:super.visit(e)}visitChunk(e){if(this.#t<this.#r){let t=this.#i(e);this.#e.set(e.hash,{chunk:e,size:t}),this.#t+=t}return super.visitChunk(e)}},Fd=5*2**20,Id=300;async function Ld(e,t,n,r,i,a,o,s){if(o())return;let c=await R(t,e=>Ca(I,e));Ba(c);let l=await t.withSuspendedSourceCacheEvictsAndDeletes(async()=>{let l=await z(n,async e=>{let n=await vl(r,e);if(!n)throw new ol(r);let i=n.headHash,a=await(await L(i,e)).getMutationID(r,e),o=await ul(r,e);tl(o);let s=await Ta(i,e);if(Ba(s),Rd(c,s,i))return;let l=new Pd(e,t,Fd);await l.visit(i);let{gatheredChunks:u}=l,d=new Set(o.refreshHashes);return d.add(i),await bl(r,{...o,refreshHashes:[...d]},e),[i,s,a,u,o.refreshHashes]});if(o()||!l||(await Mr(Id),o()))return{type:`aborted`};let[u,d,f,p,m]=l;return z(t,async t=>{let n=await Aa(I,t),o=await Ea(n,t);if(Ba(o),Rd(o,d,u))return{type:`aborted`,refreshHashesForRevert:m};let c=await Sa(n,{[r]:f},t),l=[];for(let{chunk:e,size:n}of p.values())l.push(t.putChunk(e,n));await Promise.all(l);let h=u;for(let n=c.length-1;n>=0;n--)h=(await ec(c[n],t,h,i,e,c[n].meta.clientID,s)).chunk.hash;let g=await Ws(n,await L(h,t),t,a,s);return await t.setHead(I,h),{type:`complete`,diffs:g,newPerdagClientHeadHash:u}})});if(o())return;let u=e=>z(n,async t=>{await bl(r,{...await ul(r,t),refreshHashes:e},t)});if(l.type===`aborted`){l.refreshHashesForRevert&&await u(l.refreshHashesForRevert);return}return await u([l.newPerdagClientHeadHash]),l.diffs}function Rd(e,t,n){let r=Oa(e,t);return r>0||r===0&&n===t.chunk.hash}function zd(e){return new Promise(t=>{typeof requestIdleCallback==`function`?requestIdleCallback(()=>t(),{timeout:e}):setTimeout(()=>t(),e)})}var Bd=class{#e;#t;#n;#r;#i;#a=void 0;#o=void 0;#s=Promise.resolve();#c=Promise.resolve();constructor(e,t,n,r,i=zd){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i,this.#r.addEventListener(`abort`,()=>{let e=new pr(`Aborted`);this.#o?.reject(e),this.#a?.reject(e),this.#o=void 0,this.#a=void 0},{once:!0})}schedule(){return this.#r.aborted?Promise.reject(new pr(`Aborted`)):this.#a?this.#a.promise:(this.#a=O(),this.#l(),this.#a.promise)}async#l(){try{await this.#s}catch{}if(await this.#c,this.#a&&(await this.#i(this.#t),this.#a)){this.#c=Vd(this.#n,this.#r),this.#o=this.#a,this.#a=void 0;try{this.#s=this.#e(),await this.#s,this.#o?.resolve()}catch(e){this.#o?.reject(e)}this.#o=void 0}}};async function Vd(e,t){try{await Mr(e,t)}catch(e){A(e instanceof pr)}}function Hd(e,t,n){let r=setInterval(e,t);n.addEventListener(`abort`,()=>{clearInterval(r)})}var Ud=new Set,Wd=Symbol(),Gd=class{#e;#t;#n=Wd;#r=Ud;#i=[];onError;onDone;#a;constructor(e,t,n,r,i=Gr){this.#e=e,this.#t=t,this.onError=n,this.onDone=r,this.#a=i}hasIndexSubscription(e){for(let t of this.#i)if(t.options.indexName===e)return!0;return!1}invoke(e,t,n){return this.#e(e)}matches(e){for(let[t,n]of e)if(Yd(this.#r,this.#i,t,n))return!0;return!1}updateDeps(e,t){this.#r=e,this.#i=t}onData(e){(this.#n===Wd||!this.#a(this.#n,e))&&(this.#n=e,this.#t(e))}},Kd=class{#e;#t;#n;#r;onError=void 0;onDone=void 0;constructor(e,t){this.#e=e,this.#t=t?.prefix??``,this.#n=t?.indexName,this.#r=t?.initialValuesInFirstDiff??!1}hasIndexSubscription(e){return this.#n===e}onData(e){e!==void 0&&this.#e(e)}invoke(e,t,n){let r=async(r,i,a,o)=>{let s;if(t===0){if(!this.#r)return;A(n===void 0);let t=[];for await(let n of e.scan({prefix:i,indexName:r}).entries())t.push({op:`add`,key:n[0],newValue:n[1]});s=t}else A(n),s=o(n.get(r??``)??[]);let c=[],{length:l}=s;for(let e=tf(s,i,a);e<l&&a(s[e]).startsWith(i);e++)c.push(s[e]);return t===0||c.length>0?c:void 0};return this.#n?r(this.#n,this.#t,e=>e.key[0],e=>qd(e,ls)):r(void 0,this.#t,e=>e.key,e=>qd(e,e=>e))}matches(e){let t=e.get(this.#n??``);return t!==void 0&&ef(t,this.#t,this.#n)}updateDeps(e,t){}};function qd(e,t){return e.map(e=>{let n=t(e.key);switch(e.op){case`add`:return{op:`add`,key:n,newValue:e.newValue};case`change`:return{op:`change`,key:n,oldValue:e.oldValue,newValue:e.newValue};case`del`:return{op:`del`,key:n,oldValue:e.oldValue}}})}var Jd=class{#e=new Set;#t=new Set;#n;#r;hasPendingSubscriptionRuns=!1;constructor(e,t){this.#n=e,this.#r=t}add(e){return this.#e.add(e),this.#a(e),()=>this.#e.delete(e)}clear(){for(let e of this.#e)e.onDone?.();this.#e.clear()}async fire(e){let t=$d(this.#e,e);await this.#i(t,1,e)}async#i(e,t,n){let r=[...e];if(r.length===0)return;let i=await this.#n(e=>Promise.allSettled(r.map(async r=>{let i=new Ns(e);try{return await r.invoke(i,t,n)}finally{r.updateDeps(i.keys,i.scans)}})));this.callCallbacks(r,i)}callCallbacks(e,t){for(let n=0;n<e.length;n++){let r=e[n],i=t[n];i.status===`fulfilled`?r.onData(i.value):r.onError?r.onError(i.reason):this.#r.error?.(`Error in subscription body:`,i.reason)}}async#a(e){if(this.#t.add(e),!this.hasPendingSubscriptionRuns){this.hasPendingSubscriptionRuns=!0,await Promise.resolve(),this.hasPendingSubscriptionRuns=!1;let e=[...this.#t];this.#t.clear(),await this.#i(e,0,void 0)}}shouldComputeDiffs(){return this.#e.size>0}shouldComputeDiffsForIndex(e){for(let t of this.#e)if(t.hasIndexSubscription(e))return!0;return!1}};function Yd(e,t,n,r){if(n===``){for(let t of r)if(e.has(t.key))return!0}for(let e of t)if(Xd(e,n,r))return!0;return!1}function Xd(e,t,n){for(let r of n)if(Zd(e,t,r.key))return!0;return!1}function Zd(e,t,n){let{indexName:r=``,limit:i,prefix:a,startKey:o,startExclusive:s,startSecondaryKey:c}=e.options;if(t!==r)return!1;if(!r)return i!==void 0&&i<=0?!1:!a&&!o||!(a&&(!n.startsWith(a)||Qd(e,n))||o&&(s&&vo(n,o)||_o(n,o)||Qd(e,n)));if(!a&&!o&&!c)return!0;let[l,u]=ls(n);return!(a&&!l.startsWith(a)||c&&(s&&vo(l,c)||_o(l,c))||o&&(s&&vo(u,o)||_o(u,o)))}function Qd(e,t){let{inclusiveLimitKey:n}=e;return e.options.limit!==void 0&&n!==void 0&&go(t,n)}function*$d(e,t){for(let n of e)n.matches(t)&&(yield n)}function ef(e,t,n){if(t===``)return!0;let r=n?e=>ls(e.key)[0]:e=>e.key,i=tf(e,t,r);return i<e.length&&r(e[i]).startsWith(t)}function tf(e,t,n){return yo(e.length,r=>co(t,n(e[r])))}function nf(e){if(e===null)throw TypeError(`array cannot be null`);for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256);return e}var rf=``;function af(){if(rf===``){let e=new Uint8Array(4);nf(e),rf=Array.from(e,e=>e.toString(16)).join(``)}return rf}var of=new Map;function sf(e){let t=of.get(e);return t?(t++,of.set(e,t)):(of.set(e,0),t=0),`${e}-${af()}-${t}`}var cf=`15.3.0`,lf=8,uf=1e3,df=1e3,ff=500,pf=500,mf=100*2**20,hf=3e5,gf=()=>{},_f={type:`NewClientGroup`},vf=(e,t)=>new Jd(e,t),yf=class{pullURL;pushURL;auth;name;subscriptions;#e;isClientGroupDisabled=!1;#t;lastMutationID=0;get idbName(){return Jl(this.name,this.schemaVersion)}schemaVersion;get#n(){return{name:this.idbName,replicacheName:this.name,replicacheFormatVersion:7,schemaVersion:this.schemaVersion}}#r=!1;#i=!0;#a=Gc();#o;#s;#c;#l={};mutate;#u=0;#d=0;#f;#p;pullInterval;pushDelay;#m;puller;pusher;memdag;perdag;#h;#g;#_=new AbortController;#v=!1;#y;#b;#x;#S=new Bd(()=>this.persist(),uf,ff,this.#_.signal);#C;#w=new Bd(()=>this.refresh(),df,pf,this.#_.signal);get requestOptions(){return this.#m}onSync=null;onClientStateNotFound=Sf;onUpdateNeeded=Sf;getAuth=null;onPushInvoked=()=>{};onBeginPull=()=>{};onRecoverMutations=e=>e;constructor(e,t={}){Cf(e);let{name:n,logLevel:r=`info`,logSinks:i=[Ut],pullURL:a=``,auth:o,pushDelay:s=10,pushURL:c=``,schemaVersion:l=``,pullInterval:u=6e4,mutators:d={},requestOptions:f={},puller:p,pusher:m,indexes:h={},clientMaxAgeMs:g=Xu}=e,{enableMutationRecovery:_=!0,enableScheduledPersist:v=!0,enableScheduledRefresh:y=!0,enablePullAndPushInOpen:b=!0,makeSubscriptionsManager:ee=vf,enableClientGroupForking:x=!0}=t;this.auth=o??``,this.pullURL=a,this.pushURL=c,this.name=n,this.schemaVersion=l,this.pullInterval=u,this.pushDelay=s,this.puller=p??dc(this),this.pusher=m??yc(this),this.#y=v,this.#b=y,this.#x=b,this.#g=Sc(r,i,{name:n}),this.#g.debug?.(`Constructing Replicache`,{name:n,"replicache version":cf}),this.subscriptions=ee(this.#W,this.#g);let te=$l(this.#g,e.kvStore);this.#t=te;let ne=te.create(this.idbName);this.#h=new fd(te.create),this.perdag=new la(ne,Wi,Ji),this.memdag=new ta(this.perdag,mf,Wi,Ji);let re=O();this.#o=re.promise;let{minDelayMs:ie=Nr,maxDelayMs:ae=Pr}=f;this.#m={maxDelayMs:ae,minDelayMs:ie};let oe=Cr(Sr(),0,this.#_.signal);this.#f=new Fr(this.#g.withContext(`PULL`),new kr(this,()=>this.#O()),oe),this.#p=new Fr(this.#g.withContext(`PUSH`),new Ar(this,()=>this.#N())),this.mutate=this.#K(d);let se=O();this.#s=se.promise;let ce=O();this.#c=ce.promise,this.#e=new Ou({delegate:this,lc:this.#g,enableMutationRecovery:_,wrapInOnlineCheck:this.#A.bind(this),wrapInReauthRetries:this.#j.bind(this),isPullDisabled:this.#k.bind(this),isPushDisabled:this.#M.bind(this),clientGroupIDPromise:this.#c}),this.#C=Ku(this.name,this.#_.signal,e=>{this.#B(e)}),this.#T(h,x,g,se.resolve,ce.resolve,re.resolve)}async#T(e,t,n,r,i,a){let{clientID:o}=this;await bf.get(this.name),await this.#h.getProfileID().then(r),await this.#h.putDatabase(this.#n);let[s,c,l,u]=await dl(o,this.#g,this.perdag,Object.keys(this.#l),e,7,t);i(s.clientGroupID),await z(this.memdag,e=>e.setHead(I,c)),a(),this.#x&&(this.pull().catch(gf),this.push().catch(gf));let{signal:d}=this.#_;Dd(o,this.perdag,()=>{this.#I(o)},Td,this.#g,d),$u(o,this.perdag,n,Zu,this.#g,d),_d(this.#h,this.#t.drop,md,gd,hd,2*n,this.#g,d),rd(this.perdag,this.#g,d),Uu(this.name,this.idbName,d,s.clientGroupID,u,()=>{this.#R(_f)},this.perdag),Hd(()=>this.recoverMutations(),hf,d),this.recoverMutations(l),Sr()?.addEventListener(`visibilitychange`,this.#E)}#E=async()=>{this.#r||Sr()?.visibilityState===`visible`&&await this.#D()};async#D(){let{clientID:e}=this,t=await R(this.perdag,t=>cl(e,t));return t||this.#I(e),!t}get profileID(){return this.#s}get clientID(){return this.#a}get clientGroupID(){return this.#c}onOnlineChange=null;get online(){return this.#i}get closed(){return this.#r}async close(){this.#r=!0;let{promise:e,resolve:t}=O();bf.set(this.name,e),this.#_.abort(),Sr()?.removeEventListener(`visibilitychange`,this.#E),await this.#o;let n=[this.memdag.close(),this.perdag.close(),this.#h.close()];this.#f.close(),this.#p.close(),this.subscriptions.clear(),await Promise.all(n),bf.delete(this.name),t()}async maybeEndPull(e,t){for(;;){if(this.#r)return;await this.#o;let{clientID:n}=this,r=this.#g.withContext(`maybeEndPull`).withContext(`requestID`,t),{replayMutations:i,diffs:a}=await pu(this.memdag,r,e,n,this.subscriptions,7);if(!i||i.length===0){await this.subscriptions.fire(a),this.#z();return}for(let t of i){this.subscriptions.hasPendingSubscriptionRuns&&await Promise.resolve();let{meta:i}=t;e=await Uc(this.memdag,a=>tc(t,a,e,ru,this.#l,r,Pa(i)?i.clientID:n,7))}}}#O(){return this.#k()?Promise.resolve(!0):this.#A(async()=>{try{this.#U(0,1);let{syncHead:e,requestID:t,ok:n}=await this.beginPull();if(!n)return!1;e!==F&&await this.maybeEndPull(e,t)}catch(e){throw await this.#J(e)}finally{this.#U(0,-1)}return!0},`Pull`)}#k(){return this.isClientGroupDisabled||this.pullURL===``&&pc(this.puller)}async#A(e,t){let n=!0;try{return await e()}catch(e){return e instanceof vu||e instanceof nu?(n=!1,this.#g.debug?.(`${t} threw:
8
8
  `,e,`
9
9
  with cause:
10
- `,e.causedBy)):e instanceof Ql?this.#g.error?.(e):this.#g.info?.(`${t} threw:
11
- `,e),!1}finally{this.#i!==n&&(this.#i=n,this.onOnlineChange?.(n),n&&this.recoverMutations())}}async#j(e,t,n,r=_f,i=_f){let{clientID:a}=this,o=0,s;n=n.withContext(t);do{let c=cf(a),l=n.withContext(`requestID`,c),{httpRequestInfo:u,result:d}=await e(c,l);if(s=d,!u)return{result:d,authFailure:!1};let{errorMessage:f,httpStatusCode:p}=u;if((f||p!==200)&&l.error?.(`Got a non 200 response doing ${t}: ${p}`+(f?`: ${f}`:``)),p!==Jl)return{result:d,authFailure:!1};if(!this.getAuth)return{result:d,authFailure:!0};let m;try{await r(),m=await this.getAuth()}finally{await i()}if(m==null)return{result:d,authFailure:!0};this.auth=m,o++}while(o<uf);return n.info?.(`Tried to reauthenticate too many times`),{result:s,authFailure:!0}}#M(){return this.isClientGroupDisabled||this.pushURL===``&&Sc(this.pusher)}async#N(){if(this.#M())return!0;await this.#o;let e=await this.#s,{clientID:t}=this,n=await this.#c;return this.#A(async()=>{let{result:r}=await this.#j(async(r,i)=>{try{this.#U(1,0);let a=await Eu(r,this.memdag,i,e,n,t,this.pusher,this.schemaVersion,xu);return{result:a,httpRequestInfo:a?.httpRequestInfo}}finally{this.#U(-1,0)}},`push`,this.#g);if(r===void 0)return!0;let{response:i,httpRequestInfo:a}=r;return oc(i)?this.#P(i):ac(i)&&await this.#L(),a.httpStatusCode===200},`Push`)}#P(e){let t={type:e.error};e.versionType&&(t.versionType=e.versionType),this.#R(t)}push({now:e=!1}={}){return Sf(this.#p.send(e))}pull({now:e=!1}={}){return Sf(this.#f.send(e))}async poke(e){await this.#o;let{clientID:t}=this,n=cf(t),r=this.#g.withContext(`handlePullResponse`).withContext(`requestID`,n),{pullResponse:i}=e;if(oc(i)){this.#P(i);return}if(ac(i)){await this.#L();return}let a=await pu(r,this.memdag,vi(e.baseCookie),i,t,7);switch(a.type){case 0:await this.maybeEndPull(a.syncHead,n);break;case 2:throw Error(`unexpected base cookie for poke: `+JSON.stringify(e))}}async beginPull(){await this.#o;let e=await this.profileID,{clientID:t}=this,n=await this.#c,{result:{beginPullResponse:r,requestID:i}}=await this.#j(async(r,i)=>{let a=await lu(e,t,n,this.schemaVersion,this.puller,r,this.memdag,7,i);return{result:{beginPullResponse:a,requestID:r},httpRequestInfo:a.httpRequestInfo}},`pull`,this.#g,()=>this.#U(0,-1),()=>this.#U(0,1)),{pullResponse:a}=r;oc(a)?this.#P(a):ac(r.pullResponse)&&await this.#L();let{syncHead:o,httpRequestInfo:s}=r;return{requestID:i,syncHead:o,ok:s.httpStatusCode===200}}async persist(){k(!this.#v),this.#v=!0;try{let{clientID:e}=this;if(await this.#o,this.#r)return;try{await Md(this.#g,e,this.memdag,this.perdag,this.#l,()=>this.closed,7)}catch(t){if(t instanceof sl)this.#I(e);else if(this.#r)this.#g.debug?.(`Exception persisting during close`,t);else throw t}}finally{this.#v=!1}let{clientID:e}=this,t=await this.#c;k(t),this.#C({clientID:e,clientGroupID:t})}async refresh(){await this.#o;let{clientID:e}=this;if(this.#r)return;let t;try{t=await Rd(this.#g,this.memdag,this.perdag,e,this.#l,this.subscriptions,()=>this.closed,7)}catch(t){if(t instanceof sl)this.#I(e);else if(this.#r)this.#g.debug?.(`Exception refreshing during close`,t);else throw t}t!==void 0&&await this.subscriptions.fire(t)}#F(){this.onClientStateNotFound?.()}#I(e){this.#g.error?.(`Client state not found on client, clientID: ${e}`),this.#F()}async#L(){let e=await this.#c;this.#g.error?.(`Client state not found on server, clientGroupID: ${e}`),await this.disableClientGroup(),this.#F()}async disableClientGroup(){let e=await this.#c;k(e),this.isClientGroupDisabled=!0,await R(this.perdag,t=>Vc(e,t))}#R(e){this.#g.debug?.(`Update needed, reason: ${e}`),this.onUpdateNeeded?.(e)}async#z(){this.#y&&await this.#H(`persist`,this.#S)}async#B(e){this.#g.debug?.(`Handling persist`,e);let t=await this.#c;e.clientGroupID===t&&this.#V()}async#V(){this.#b&&await this.#H(`refresh from storage`,this.#w)}async#H(e,t){try{await t.schedule()}catch(t){t instanceof mr?this.#g.debug?.(`Scheduled ${e} did not complete before close.`):this.#g.error?.(`Error during ${e}`,t)}}#U(e,t){this.#u+=e,this.#d+=t;let n=e+t,r=this.#u+this.#d;if(n===1&&r===1||r===0){let e=r>0;Promise.resolve().then(()=>this.onSync?.(e))}}subscribe(e,t){typeof t==`function`&&(t={onData:t});let{onData:n,onError:r,onDone:i,isEqual:a}=t;return this.subscriptions.add(new Kd(e,n,r,i,a))}experimentalWatch(e,t){return this.subscriptions.add(new qd(e,t))}query(e){return this.#W(e)}get cookie(){return this.#o.then(()=>L(this.memdag,async e=>{let t=await e.getHead(F);if(!t)throw Error(`Internal no main head found`);let n=(await Ea(t,e)).meta.cookieJSON;return ii(n),n}))}#W=async e=>{await this.#o;let{clientID:t}=this;return L(this.memdag,async n=>{try{let r=await ps(n,7);return await e(new js(t,r,this.#g))}catch(e){throw await this.#J(e)}})};#G(e,t){return this.#l[e]=t,n=>this.#q(e,t,n,performance.now())}#K(e){let t=Object.create(null);for(let n in e)t[n]=this.#G(n,e[n]);return t}async#q(e,t,n,r){let i=vi(n??null);this.subscriptions.hasPendingSubscriptionRuns&&await Promise.resolve(),await this.#o;let{clientID:a}=this;return Wc(this.memdag,async o=>{try{let s=await Js(await ta(F,o),e,i,null,o,r,a,7),c=await t(new Fs(a,await s.getMutationID(),`initial`,s,this.#g),n);Ss(s);let l=await s.getMutationID(),u=await s.commitWithDiffs(F,this.subscriptions);return this.lastMutationID=l,this.#p.send(!1).catch(()=>{}),await this.subscriptions.fire(u),this.#z(),c}catch(e){throw await this.#J(e)}})}async#J(e){return e instanceof $i&&await this.#D()?new sl(this.clientID):e}recoverMutations(e){return this.#e.recoverMutations(e,this.#o,this.perdag,this.#n,this.#h,this.#t.create)}experimentalPendingMutations(){return L(this.memdag,Ju)}},xf=new Map;async function Sf(e){let t=await e;if(t)throw t.error}function Cf(){typeof location<`u`&&location.reload()}function wf(e){let{name:t,clientMaxAgeMs:n}=e;if(typeof t!=`string`||!t)throw TypeError(`name is required and must be non-empty`);if(n!==void 0){let e=Math.max(Qu,Ed);if(typeof n!=`number`||n<=e)throw TypeError(`clientAgeMaxMs must be a number larger than ${e}ms`)}}var Tf={PENDING:`PENDING`,IN_PROGRESS:`IN_PROGRESS`,READY:`READY`,ERROR:`ERROR`,CANCELED:`CANCELED`},Ef=async(e,t)=>{let{tx:n,sessionPersonId:r}=e,{spriteId:i,spriteBuildId:a,prompt:o,name:s,surfaceId:c}=t,l=C.sprite.encode(i);if(await n.get(l))return Error(`Sprite "${i}" already exists`);let u=C.spriteBuild.encode(a);if(await n.get(u))return Error(`SpriteBuild "${a}" already exists`);let d={name:s?.trim().length?s:``,surfaceId:c,ownedByPersonId:r};await n.set(l,d);let f={spriteId:i,parentSpriteBuildId:null,prompt:o,status:Tf.PENDING,cancelRequestedAt:null,artifactUrl:null,startedAt:null,stoppedAt:null,error:null,reasoningSummary:null,publishedAt:null,createdByPersonId:r};await n.set(u,f)},Df=async(e,t)=>{let{tx:n,sessionPersonId:r}=e,{spriteId:i,name:a,surfaceId:o}=t,s=C.sprite.encode(i);if(await n.get(s))return Error(`Sprite "${i}" already exists`);let c={name:a?.trim().length?a:``,surfaceId:o,ownedByPersonId:r};await n.set(s,c)},Of=async()=>{},kf=async(e,t)=>{let{tx:n,actionedAt:r}=e,{spriteBuildId:i}=t,a=C.spriteBuild.encode(i),o=await n.get(a);if(!o)return Error(`Could not find that build.`);o.status!==Tf.PENDING&&o.status!==Tf.IN_PROGRESS||o.cancelRequestedAt!==null||await n.set(a,{...o,cancelRequestedAt:r})},Af=async(e,t)=>{let{tx:n,sessionPersonId:r}=e,{spriteBuildId:i,spriteId:a,parentSpriteBuildId:o,prompt:s}=t,c=C.spriteBuild.encode(i);if(await n.get(c))return Error(`SpriteBuild "${i}" already exists`);let l={spriteId:a,parentSpriteBuildId:o,prompt:s,status:Tf.PENDING,cancelRequestedAt:null,artifactUrl:null,startedAt:null,stoppedAt:null,error:null,reasoningSummary:null,publishedAt:null,createdByPersonId:r};await n.set(c,l)},jf=async(e,t)=>{let{tx:n,sessionPersonId:r}=e,{spriteBuildId:i,spriteId:a,parentSpriteBuildId:o,prompt:s}=t,c=C.spriteBuild.encode(i);if(await n.get(c))return Error(`SpriteBuild "${i}" already exists`);let l={spriteId:a,parentSpriteBuildId:o??null,prompt:s,status:Tf.PENDING,cancelRequestedAt:null,artifactUrl:null,startedAt:null,stoppedAt:null,error:null,reasoningSummary:null,publishedAt:null,createdByPersonId:r};await n.set(c,l)},Mf=async(e,t)=>{let{tx:n,actionedAt:r}=e,{spriteBuildId:i}=t,a=C.spriteBuild.encode(i),o=await n.get(a);if(!o)return Error(`Could not find that build.`);if(o.status!==Tf.READY)return Error(`Only ready builds can be published.`);await n.set(a,{...o,publishedAt:r})},Nf={surface_upsert_v1:async(e,t)=>{let{tx:n}=e,{surfaceId:r,key:i,name:a,description:o}=t,s={key:i,name:a,description:o};for await(let[e,t]of n.scan({prefix:C.surface.prefix()}).entries())if(t.key===i){await n.set(e,s);return}await n.set(C.surface.encode(r),s)},project_ping_v1:Of,sprite_create_v2:Df,spriteBuild_create_v2:jf,spriteBuild_cancel_v1:kf,spriteBuild_publish_v2:async(e,t)=>{let{tx:n,actionedAt:r}=e,{spriteBuildId:i}=t,a=C.spriteBuild.encode(i),o=await n.get(a);if(!o)return Error(`Could not find that build.`);if(o.status!==Tf.READY)return Error(`Only ready builds can be published.`);await n.set(a,{...o,publishedAt:r})}},Pf={sprite_create_v1:Ef,spriteBuild_create_v1:Af,spriteBuild_publish_v1:Mf},Ff={...Nf,...Pf};async function If(e,t,{concurrency:n=1/0,stopOnError:r=!0,signal:i}={}){return new Promise((a,o)=>{if(e[Symbol.iterator]===void 0&&e[Symbol.asyncIterator]===void 0)throw TypeError(`Expected \`input\` to be either an \`Iterable\` or \`AsyncIterable\`, got (${typeof e})`);if(typeof t!=`function`)throw TypeError(`Mapper function is required`);if(!(Number.isSafeInteger(n)&&n>=1||n===1/0))throw TypeError(`Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${n}\` (${typeof n})`);let s=[],c=[],l=new Map,u=!1,d=!1,f=!1,p=0,m=0,h=e[Symbol.iterator]===void 0?e[Symbol.asyncIterator]():e[Symbol.iterator](),g=()=>{y(i.reason)},_=()=>{i?.removeEventListener(`abort`,g)},v=e=>{a(e),_()},y=e=>{u=!0,d=!0,o(e),_()};if(i){if(i.aborted){y(i.reason);return}i.addEventListener(`abort`,g,{once:!0})}let b=async()=>{if(d)return;let e=await h.next(),n=m;if(m++,e.done){if(f=!0,p===0&&!d){if(!r&&c.length>0){y(AggregateError(c));return}if(d=!0,l.size===0){v(s);return}let e=[];for(let[t,n]of s.entries())l.get(t)!==Lf&&e.push(n);v(e)}return}p++,(async()=>{try{let r=await e.value;if(d)return;let i=await t(r,n);i===Lf&&l.set(n,i),s[n]=i,p--,await b()}catch(e){if(r)y(e);else{c.push(e),p--;try{await b()}catch(e){y(e)}}}})()};(async()=>{for(let e=0;e<n;e++){try{await b()}catch(e){y(e);break}if(f||u)break}})()})}var Lf=Symbol(`skip`),Rf={concurrency:5,stopOnError:!1},zf=async(e,r,i=Rf)=>{let{stopOnError:a}=i;return n(async()=>If(e,async e=>{let n=await t(async()=>r(e));if(a&&n instanceof Error)throw n;return n},i))},Bf=async(e,t,n)=>{let r=await zf(Object.entries(e),async([e,n])=>[e,await t(n,e)],n);return r instanceof Error?r:Object.fromEntries(r)},Vf=async(e,t)=>Bf(t,async t=>{let n=t;return async(t,r)=>{let{context:i,...a}=r,o={...e,tx:t,actionedAt:i?.actionedAt??Date.now(),sessionPersonId:i?.sessionPersonId??e.sessionPersonId},s=await n(o,a);if(s instanceof Error)throw s;return s}}),Hf=`2026.08.20/1`,Uf=async e=>{let{name:t,pushURL:n,pullURL:r,auth:i,getAuth:a,pullInterval:o,sessionPersonId:s}=e;if(!t)return Error(`Replicache name is required`);let c=new Zl({schemaVersion:Hf,name:t,pushURL:n,pullURL:r,auth:i,pullInterval:o,mutators:await Vf({sessionPersonId:s},Ff)});return c.getAuth=a,c},Wf=class{constructor(e,t){if(this._retries=0,!Number.isInteger(e)||e<0)throw Error(`Base must be a positive integer or zero`);if(t!==void 0&&(!Number.isInteger(t)||t<0))throw Error(`ExpMax must be undefined, a positive integer, or zero`);this.base=e,this.expMax=t,this.i=0}get retries(){return this._retries}get current(){return this.base*2**this.i}next(){return this._retries++,this.i=this.expMax===void 0?this.i+1:Math.min(this.i+1,this.expMax),this.current}reset(){this._retries=0,this.i=0}},z={open:`open`,close:`close`,error:`error`,message:`message`,retry:`retry`,reconnect:`reconnect`},Gf=class{constructor(e,t,n){this._closedByUser=!1,this.handleOpenEvent=e=>this.handleEvent(z.open,e),this.handleErrorEvent=e=>this.handleEvent(z.error,e),this.handleCloseEvent=e=>this.handleEvent(z.close,e),this.handleMessageEvent=e=>this.handleEvent(z.message,e),this._urlProvider=e,this._protocols=t,this._options={buffer:n?.buffer,retry:{maxRetries:n?.retry?.maxRetries,instantReconnect:n?.retry?.instantReconnect,backoff:n?.retry?.backoff},listeners:{open:[...n?.listeners?.open??[]],close:[...n?.listeners?.close??[]],error:[...n?.listeners?.error??[]],message:[...n?.listeners?.message??[]],retry:[...n?.listeners?.retry??[]],reconnect:[...n?.listeners?.reconnect??[]]}},this._underlyingWebsocket=this.tryConnect()}get url(){return this._url}get protocols(){return this._protocols}get buffer(){return this._options.buffer}get maxRetries(){return this._options.retry.maxRetries}get instantReconnect(){return this._options.retry.instantReconnect}get backoff(){return this._options.retry.backoff}get closedByUser(){return this._closedByUser}get lastConnection(){return this._lastConnection}get underlyingWebsocket(){return this._underlyingWebsocket}get readyState(){return this._underlyingWebsocket.readyState}get bufferedAmount(){return this._underlyingWebsocket.bufferedAmount}get extensions(){return this._underlyingWebsocket.extensions}get binaryType(){return this._underlyingWebsocket.binaryType}set binaryType(e){this._underlyingWebsocket.binaryType=e}send(e){this.closedByUser||(this._underlyingWebsocket.readyState===this._underlyingWebsocket.OPEN?this._underlyingWebsocket.send(e):this.buffer!==void 0&&this.buffer.add(e))}close(e,t){this.cancelScheduledConnectionRetry(),this._closedByUser=!0,this._underlyingWebsocket.close(e,t)}addEventListener(e,t,n){this._options.listeners[e].push({listener:t,options:n})}removeEventListener(e,t,n){let r=e=>e.listener!==t||e.options!==n;this._options.listeners[e]=this._options.listeners[e].filter(r)}tryConnect(){return this._url=typeof this._urlProvider==`function`?this._urlProvider():this._urlProvider,this._underlyingWebsocket=new WebSocket(this._url,this.protocols),this._underlyingWebsocket.addEventListener(z.open,this.handleOpenEvent),this._underlyingWebsocket.addEventListener(z.close,this.handleCloseEvent),this._underlyingWebsocket.addEventListener(z.error,this.handleErrorEvent),this._underlyingWebsocket.addEventListener(z.message,this.handleMessageEvent),this._underlyingWebsocket}clearWebsocket(){this._underlyingWebsocket.removeEventListener(z.open,this.handleOpenEvent),this._underlyingWebsocket.removeEventListener(z.close,this.handleCloseEvent),this._underlyingWebsocket.removeEventListener(z.error,this.handleErrorEvent),this._underlyingWebsocket.removeEventListener(z.message,this.handleMessageEvent),this._underlyingWebsocket.close()}dispatchEvent(e,t){let n=this._options.listeners[e],r=[];n.forEach(({listener:e,options:n})=>{e(this,t),(n===void 0||n.once===void 0||!n.once)&&r.push({listener:e,options:n})}),this._options.listeners[e]=r}handleEvent(e,t){switch(e){case z.close:this.dispatchEvent(e,t),this.scheduleConnectionRetryIfNeeded();break;case z.open:if(this.backoff!==void 0&&this._lastConnection!==void 0){let e={retries:this.backoff.retries,lastConnection:new Date(this._lastConnection)},t=new CustomEvent(z.reconnect,{detail:e});this.dispatchEvent(z.reconnect,t),this.backoff.reset()}this._lastConnection=new Date,this.dispatchEvent(e,t),this.sendBufferedData();break;case z.retry:this.dispatchEvent(e,t),this.clearWebsocket(),this.tryConnect();break;default:this.dispatchEvent(e,t)}}sendBufferedData(){if(this.buffer!==void 0)for(let e=this.buffer.read();e!==void 0;e=this.buffer.read())this.send(e)}scheduleConnectionRetryIfNeeded(){if(this.closedByUser||this.backoff===void 0)return;let e=e=>{let t=new CustomEvent(z.retry,{detail:e});this.handleEvent(z.retry,t)},t={backoff:this._options.retry.instantReconnect===!0?0:this.backoff.next(),retries:this._options.retry.instantReconnect===!0?0:this.backoff.retries,lastConnection:this._lastConnection};(this._options.retry.maxRetries===void 0||t.retries<=this._options.retry.maxRetries)&&(this.retryTimeout=globalThis.setTimeout(()=>e(t),t.backoff))}cancelScheduledConnectionRetry(){globalThis.clearTimeout(this.retryTimeout)}},Kf=class{constructor(e){this._url=e}get url(){return this._url}withProtocols(e){return this._protocols=e,this}get protocols(){return this._protocols}withMaxRetries(e){return this._options=Object.assign(Object.assign({},this._options),{retry:Object.assign(Object.assign({},this._options?.retry),{maxRetries:e})}),this}get maxRetries(){return this._options?.retry?.maxRetries}withInstantReconnect(e){return this._options=Object.assign(Object.assign({},this._options),{retry:Object.assign(Object.assign({},this._options?.retry),{instantReconnect:e})}),this}get instantReconnect(){return this._options?.retry?.instantReconnect}withBackoff(e){return this._options=Object.assign(Object.assign({},this._options),{retry:Object.assign(Object.assign({},this._options?.retry),{backoff:e})}),this}get backoff(){return this._options?.retry?.backoff}withBuffer(e){return this._options=Object.assign(Object.assign({},this._options),{buffer:e}),this}get buffer(){return this._options?.buffer}onOpen(e,t){return this.addListener(z.open,e,t),this}onClose(e,t){return this.addListener(z.close,e,t),this}onError(e,t){return this.addListener(z.error,e,t),this}onMessage(e,t){return this.addListener(z.message,e,t),this}onRetry(e,t){return this.addListener(z.retry,e,t),this}onReconnect(e,t){return this.addListener(z.reconnect,e,t),this}build(){return new Gf(this._url,this._protocols,this._options)}addListener(e,t,n){return this._options=Object.assign(Object.assign({},this._options),{listeners:{open:this._options?.listeners?.open??[],close:this._options?.listeners?.close??[],error:this._options?.listeners?.error??[],message:this._options?.listeners?.message??[],retry:this._options?.listeners?.retry??[],reconnect:this._options?.listeners?.reconnect??[],[e]:[...this._options?.listeners?.[e]??[],{listener:t,options:n}]}}),this}},qf=e.object({type:e.literal(`poke`)}).strict(),Jf=e=>{console.warn(`[Rough poke] ${e}`)},Yf=e=>{let{getToken:t,onPoke:n,url:r}=e,i=!1,a=0;try{let e=new Kf(r).withBackoff(new Wf(1e3,7)).build(),o=()=>{let n=++a;t().then(t=>{i||n!==a||e.readyState!==1||e.send(JSON.stringify({type:`authenticate`,token:t}))}).catch(()=>{Jf(`Failed to get a session token`)})},s=(e,t)=>{if(typeof t.data!=`string`){Jf(`Received an invalid server message`);return}let r;try{r=JSON.parse(t.data)}catch{Jf(`Received malformed server JSON`);return}if(!qf.safeParse(r).success){Jf(`Received an invalid server message`);return}Promise.resolve(n()).catch(()=>{Jf(`Failed to pull after a server poke`)})},c=()=>{Jf(`Connection failed`)},l=()=>{i||Jf(`Connection closed; reconnecting`)};return e.addEventListener(z.open,o),e.addEventListener(z.message,s),e.addEventListener(z.error,c),e.addEventListener(z.close,l),{close:()=>{i||(i=!0,e.removeEventListener(z.open,o),e.removeEventListener(z.message,s),e.removeEventListener(z.error,c),e.removeEventListener(z.close,l),e.close())}}}catch{return Jf(`Failed to create connection`),{close:()=>{}}}};function Xf(e){let t=Error(e.message||e.error?.message||`An error occurred`),n=e.code??e.error?.code;return n!==void 0&&Object.assign(t,{code:n}),e.rawEvent!==void 0&&Object.assign(t,{rawEvent:e.rawEvent}),t}var Zf=new Uint32Array([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]);function Qf(e,t){return e>>>t|e<<32-t}function $f(e){let t=new TextEncoder().encode(e),n=t.length*8,r=t.length+1,i=r+(56-r%64+64)%64+8,a=new Uint8Array(i);a.set(t),a[t.length]=128;let o=new DataView(a.buffer);o.setUint32(i-8,Math.floor(n/4294967296)),o.setUint32(i-4,n>>>0);let s=1779033703,c=3144134277,l=1013904242,u=2773480762,d=1359893119,f=2600822924,p=528734635,m=1541459225,h=new Uint32Array(64);for(let e=0;e<i;e+=64){for(let t=0;t<16;t++)h[t]=o.getUint32(e+t*4);for(let e=16;e<64;e++){let t=h[e-15]??0,n=h[e-2]??0,r=Qf(t,7)^Qf(t,18)^t>>>3,i=Qf(n,17)^Qf(n,19)^n>>>10;h[e]=(h[e-16]??0)+r+(h[e-7]??0)+i>>>0}let t=s,n=c,r=l,i=u,a=d,g=f,_=p,v=m;for(let e=0;e<64;e++){let o=Qf(a,6)^Qf(a,11)^Qf(a,25),s=a&g^~a&_,c=v+o+s+(Zf[e]??0)+(h[e]??0)>>>0,l=(Qf(t,2)^Qf(t,13)^Qf(t,22))+(t&n^t&r^n&r)>>>0;v=_,_=g,g=a,a=i+c>>>0,i=r,r=n,n=t,t=c+l>>>0}s=s+t>>>0,c=c+n>>>0,l=l+r>>>0,u=u+i>>>0,d=d+a>>>0,f=f+g>>>0,p=p+_>>>0,m=m+v>>>0}let g=e=>(e>>>0).toString(16).padStart(8,`0`);return g(s)+g(c)+g(l)+g(u)+g(d)+g(f)+g(p)+g(m)}function ep(e){return`sha256:${$f(e)}`}function tp(e,t){if(e===null)return`null`;if(typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return JSON.stringify(e);if(typeof e!=`object`)throw TypeError(`Interrupt values must be JSON-compatible.`);if(t.has(e))throw TypeError(`Interrupt values must not cycle.`);if(!Array.isArray(e)&&Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw TypeError(`Interrupt values must use plain JSON objects.`);t.add(e);let n;if(Array.isArray(e)){let r=[];for(let n=0;n<e.length;n++)r.push(tp(e[n],t));n=`[${r.join(`,`)}]`}else{let r=e;n=`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${tp(r[e],t)}`).join(`,`)}}`}return t.delete(e),n}function np(e){return tp(e,new WeakSet)}function rp(e,t=ep){if(typeof e!=`string`)throw TypeError(`Interrupt digests require canonical JSON text.`);return t(e)}function ip(e){typeof e!=`object`||!e||Object.isFrozen(e)||(Object.values(e).forEach(ip),Object.freeze(e))}function B(e){let t=JSON.parse(np(e));return ip(t),t}function ap(e){let t=B([...e].sort((e,t)=>e.interruptId.localeCompare(t.interruptId))),n=np(t);return Object.freeze({resolutions:t,canonicalResolutions:n,fingerprint:rp(n)})}function op(e){let t={};for(let[n,r]of Object.entries(e))n!==`$schema`&&(t[n]=r);return t}function sp(e){return(typeof e==`object`||typeof e==`function`)&&e!==null}function cp(e){if(!sp(e)||!(`~standard`in e))return!1;let t=e[`~standard`];return typeof t!=`object`||!t||!(`version`in t)||t.version!==1||!(`jsonSchema`in t)||typeof t.jsonSchema!=`object`||t.jsonSchema===null||!(`input`in t.jsonSchema)?!1:typeof t.jsonSchema.input==`function`}function lp(e){return sp(e)&&`~standard`in e&&typeof e[`~standard`]==`object`&&e[`~standard`]!==null&&`version`in e[`~standard`]&&e[`~standard`].version===1&&`validate`in e[`~standard`]&&typeof e[`~standard`].validate==`function`}function up(e){return Object.keys(e).length>0?e:void 0}function dp(e,t=[]){let n={...e},r={};if(n.type===`object`&&n.properties){let e={...n.properties},i=Object.keys(e),a={};for(let n of i){let r=e[n];if(!r)continue;let i=!t.includes(n),o=!1,s;if(r.type===`object`&&r.properties){let t=dp(r,r.required||[]);e[n]=i?{...t.schema,type:[`object`,`null`]}:t.schema,o=i,s=t.nullWidening}else if(r.type===`array`&&r.items){let t=Array.isArray(r.items)?r.items[0]:r.items,a=t?dp(t,t.required||[]):void 0;e[n]={...r,items:a?a.schema:r.items,...i?{type:[`array`,`null`]}:{}},o=i,s=a?.nullWidening?{items:a.nullWidening}:void 0}else i&&(r.type&&!Array.isArray(r.type)?(e[n]={...r,type:[r.type,`null`]},o=!0):Array.isArray(r.type)&&!r.type.includes(`null`)&&(e[n]={...r,type:[...r.type,`null`]},o=!0));(o||s)&&(a[n]={...s??{},...o?{widened:!0}:{}})}n.properties=e,n.required=i,n.additionalProperties=!1,Object.keys(a).length>0&&(r.properties=a)}if(n.type===`array`&&n.items){let e=Array.isArray(n.items)?n.items[0]:n.items;if(e){let t=dp(e,e.required||[]);n.items=t.schema,t.nullWidening&&(r.items=t.nullWidening)}}return{schema:n,nullWidening:up(r)}}function fp(e){if(cp(e)){let t=op(e[`~standard`].jsonSchema.input({target:`draft-07`}));return`properties`in t&&!t.type&&(t.type=`object`),t.type===`object`&&!(`properties`in t)&&(t.properties={}),t.type===`object`&&!(`required`in t)&&(t.required=[]),t}if(lp(e))throw Error("Schema is a Standard Schema validator but does not expose a JSON Schema converter on `~standard.jsonSchema`. Use Zod v4.2+, ArkType v2.1.28+, or wrap a Valibot schema with `toStandardJsonSchema()` from `@valibot/to-json-schema` before passing it as `outputSchema`.");return typeof e==`object`?op(e):e}function pp(e,t={}){if(!e)return;let{forStructuredOutput:n=!1}=t;if(!n&&!cp(e)&&!lp(e))return e;let r=fp(e);return!r||typeof r!=`object`||!n?r:dp(r,r.required||[]).schema}var mp=class extends Error{name=`StandardSchemaValidationError`;issues;constructor(e){super(`Validation failed: ${e.map(e=>e.message||`Validation failed`).join(`, `)}`),this.issues=e}};function hp(e,t){if(!lp(e))return t;let n=e[`~standard`].validate(t);if(n instanceof Promise)throw Error(`Schema validation returned a Promise. Use validateWithStandardSchema for async validation.`);if(!n.issues)return n.value;throw new mp(n.issues)}var gp=new Set([`$schema`,`$id`,`$ref`,`$defs`,`type`,`properties`,`required`,`additionalProperties`,`items`,`oneOf`,`anyOf`,`allOf`,`enum`,`const`,`format`,`minimum`,`maximum`,`minLength`,`maxLength`,`pattern`]);function _p(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null)}function vp(e){return _p(e)&&Object.keys(e).some(e=>gp.has(e))}function yp(e){return lp(e)||cp(e)||vp(e)}function bp(e){if(!_p(e))return!1;let t=Object.keys(e);return t.length>0&&t.every(e=>e===`approve`||e===`reject`)&&t.every(t=>yp(e[t]))}function xp(e){let t={};for(let[n,r]of Object.entries(e))t[n]=r;return t}function Sp(e){if(lp(e)){let t=cp(e)?xp(e[`~standard`].jsonSchema.input({target:`draft-2020-12`})):void 0;return{source:e,validator:e,...t!==void 0&&{jsonSchema:t}}}if(vp(e))return{source:e,jsonSchema:e};throw TypeError(`Expected a supported SchemaInput.`)}function Cp(e){let t={approved:{const:e.approved}},n=[`approved`];return e.approved&&e.inputSchema&&(t.editedArgs=e.inputSchema.jsonSchema??{}),e.payload&&(t.payload=e.payload.jsonSchema??{},n.push(`payload`)),{type:`object`,properties:t,required:n,additionalProperties:!1}}function wp(e,t){let n=t===void 0?null:Sp(t),r=null,i=null;if(e!==void 0){if(lp(e)||vp(e))r=Sp(e),i=r;else if(bp(e))r=e.approve===void 0?null:Sp(e.approve),i=e.reject===void 0?null:Sp(e.reject);else throw TypeError(`approvalSchema must be a SchemaInput or a nonempty map containing approve or reject.`)}let a={oneOf:[Cp({approved:!0,payload:r,inputSchema:n}),Cp({approved:!1,payload:i,inputSchema:null})]},o=np(a),s=np({approve:r?.jsonSchema??null,reject:i?.jsonSchema??null});return{branches:{approve:r,reject:i},responseSchema:a,responseSchemaHash:rp(o),approvalSchemaHash:rp(s)}}function Tp(e){return rp(e===void 0?`undefined`:np(Sp(e).jsonSchema??{standardValidator:`unserialized`}))}var Ep=`tanstack:interruptBinding`,Dp=Ep;function Op(e){return e&&typeof e==`object`?e:null}function kp(e,t){return typeof e[t]==`string`?e[t]:void 0}function Ap(e){let t=e.v;return t===void 0||t===1}function jp(e){let t=Op(e.metadata),n=t?Op(t[Dp]):null;if(!n||kp(n,`interruptId`)!==e.id||!Ap(n))return;let r=kp(n,`kind`),i=kp(n,`interruptId`),a=kp(n,`responseSchemaHash`),o=kp(n,`expiresAt`);if(!i||a===``||o!==void 0&&!Number.isFinite(Date.parse(o)))return;if(r===`generic`){let e=kp(n,`definitionId`),t=kp(n,`key`),s=n.batchIndex,c=kp(n,`payloadSchemaHash`);return(e!==void 0||t!==void 0||s!==void 0||c!==void 0)&&(!e||!t||typeof s!=`number`||!Number.isInteger(s)||s<0)?void 0:{v:1,kind:r,interruptId:i,...a?{responseSchemaHash:a}:{},...o?{expiresAt:o}:{},...e?{definitionId:e}:{},...t?{key:t}:{},...typeof s==`number`?{batchIndex:s}:{},...c?{payloadSchemaHash:c}:{}}}if(!a)return;let s=kp(n,`toolName`),c=kp(n,`toolCallId`);if(!(!s||!c)){if(r===`client-tool-execution`){let e=kp(n,`outputSchemaHash`);return e?{v:1,kind:r,interruptId:i,toolName:s,toolCallId:c,outputSchemaHash:e,responseSchemaHash:a,...o?{expiresAt:o}:{}}:void 0}if(r===`tool-approval`){let e=kp(n,`inputSchemaHash`),t=kp(n,`approvalSchemaHash`);return!e||!t?void 0:{v:1,kind:r,interruptId:i,toolName:s,toolCallId:c,originalArgs:n.originalArgs,inputSchemaHash:e,approvalSchemaHash:t,responseSchemaHash:a,...o?{expiresAt:o}:{}}}}}function Mp(e){let t=jp(e);if(!t)return;let n=Op(e.metadata),r=n?Op(n[Dp]):null;if(!r)return;let i=kp(r,`interruptedRunId`),a=r.generation;if(!(!i||typeof a!=`number`||!Number.isInteger(a)||a<0))return{...t,interruptedRunId:i,generation:a}}var Np=`tanstack:interruptPayload`;function Pp(e,t){if(!cp(e))throw TypeError(`${t} must be a Standard Schema with a JSON Schema converter.`);try{let t=e[`~standard`].jsonSchema.input({target:`draft-07`});if(t===void 0)throw TypeError(`The exported schema is undefined.`);if(typeof t==`function`)throw TypeError(`The exported schema must not be a function.`);if(Array.isArray(t)||!t||typeof t!=`object`||![Object.prototype,null].includes(Object.getPrototypeOf(t)))throw TypeError(`The exported schema must be a plain JSON object.`);let n={};for(let[e,r]of Object.entries(t))e!==`$schema`&&(n[e]=r);return{json:n,canonicalJson:np(n)}}catch(e){throw TypeError(`${t} could not export compatible JSON Schema: ${e instanceof Error?e.message:String(e)}`)}}function Fp(e){return rp(Pp(e,`Interrupt schema`).canonicalJson)}var Ip=`tanstack:interruptContinuation`;function Lp(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Rp(e){return{[Ip]:e}}function zp(e){let t=jp(e);if(t?.kind!==`generic`||t.definitionId===void 0||t.key===void 0||t.batchIndex===void 0)return;let n=Lp(e.metadata)?e.metadata:void 0,r=n!==void 0&&Object.prototype.hasOwnProperty.call(n,`tanstack:interruptPayload`);return{v:1,definitionId:t.definitionId,key:t.key,batchIndex:t.batchIndex,reason:e.reason,message:e.message??``,...e.expiresAt===void 0?{}:{expiresAt:e.expiresAt},...t.responseSchemaHash===void 0?{}:{responseSchemaHash:t.responseSchemaHash},...t.payloadSchemaHash===void 0?{}:{payloadSchemaHash:t.payloadSchemaHash},...r?{payload:n[Np]}:{}}}var Bp=new Set([`text`,`image`,`audio`,`video`,`document`]);function Vp(e){if(typeof e!=`object`||!e)return!1;let t=e;if(typeof t.type!=`string`||!Bp.has(t.type))return!1;if(t.type===`text`)return typeof t.content==`string`;let n=t.source;if(typeof n!=`object`||!n)return!1;let r=n;return typeof r.value==`string`?r.type===`data`?typeof r.mimeType==`string`:r.type===`url`:!1}function Hp(e){return Array.isArray(e)&&e.length>0&&e.every(Vp)}function Up(e){return typeof e==`string`||Hp(e)?e:JSON.stringify(e)}function Wp(e){let t=e?.metadata;return typeof t==`object`&&t&&t.providerExecuted===!0?t:null}function Gp(e){return Wp(e)!==null}function Kp(e){return e.type===`text`||e.type===`image`||e.type===`audio`||e.type===`video`||e.type===`document`}function qp(e){try{return JSON.stringify(e)??``}catch{return``}}function Jp(e){return e.length===0?null:e.every(e=>e.type===`text`)?e.map(e=>e.content).join(``)||null:e}function Yp(e){return e===null?``:typeof e==`string`?e:e.filter(e=>e.type===`text`).map(e=>e.content).join(``)}function Xp(e){let t=new Set;for(let n of e)if(`parts`in n)for(let e of n.parts)e.type===`tool-result`&&t.add(e.toolCallId);let n=[];for(let r of e){if(`parts`in r){n.push(...Zp(r));continue}let e=r.role;if(!(e===`tool`&&r.toolCallId&&t.has(r.toolCallId))&&e!==`reasoning`&&e!==`activity`){if(e===`developer`){n.push({role:`system`,content:r.content});continue}n.push(r)}}return n}function Zp(e){return e.role===`system`?[]:e.role===`assistant`?tm(e):[Qp(e)]}function Qp(e){let t=[];for(let n of e.parts)Kp(n)&&t.push(n);return{id:e.id,role:e.role,content:Jp(t),...e.createdAt!==void 0&&{createdAt:e.createdAt}}}function $p(){return{contentParts:[],toolCalls:[]}}function em(e){return e.state===`input-complete`||e.state===`complete`||e.state===`approval-requested`||e.state===`approval-responded`||e.state===`error`||e.output!==void 0}function tm(e){let t=[],n=$p(),r=[],i=new Set;function a(){let i=Jp(n.contentParts),a=i!==null,o=n.toolCalls.length>0,s=r.length>0;(a||o||s)&&(t.push({id:e.id,role:`assistant`,content:i,...o&&{toolCalls:n.toolCalls},...s&&{thinking:r},...n.structuredOutput&&{structuredOutput:n.structuredOutput},...e.createdAt!==void 0&&{createdAt:e.createdAt}}),r=[]),n=$p()}for(let o of e.parts)switch(o.type){case`text`:case`image`:case`audio`:case`video`:case`document`:n.contentParts.push(o);break;case`tool-call`:em(o)&&n.toolCalls.push({id:o.id,type:`function`,function:{name:o.name,arguments:o.arguments},...o.metadata!==void 0&&{metadata:o.metadata}});break;case`tool-result`:a(),(o.state===`complete`||o.state===`error`)&&!i.has(o.toolCallId)&&(t.push({id:e.id,role:`tool`,content:o.content,toolCallId:o.toolCallId,...e.createdAt!==void 0&&{createdAt:e.createdAt}}),i.add(o.toolCallId));break;case`thinking`:o.content&&(n.toolCalls.some(Gp)&&a(),r.push({content:o.content,...o.signature&&{signature:o.signature}}));break;case`structured-output`:if(o.status===`complete`){let e=o.raw===``?o.data===void 0?``:qp(o.data):o.raw;e!==``&&(n.contentParts.push({type:`text`,content:e}),n.structuredOutput=o)}}a();for(let n of e.parts)if(n.type===`tool-call`&&(n.output!==void 0&&!i.has(n.id)&&(t.push({id:e.id,role:`tool`,content:Up(n.output),toolCallId:n.id,...e.createdAt!==void 0&&{createdAt:e.createdAt}}),i.add(n.id)),n.output===void 0&&n.state===`approval-responded`&&n.approval?.approved!==void 0&&!i.has(n.id))){let r=n.approval.approved;t.push({id:e.id,role:`tool`,content:JSON.stringify({approved:r,...r&&{pendingExecution:!0},message:r?`User approved this action`:`User denied this action`}),toolCallId:n.id,...e.createdAt!==void 0&&{createdAt:e.createdAt}}),i.add(n.id)}return t.length===0&&t.push({id:e.id,role:`assistant`,content:null,...e.createdAt!==void 0&&{createdAt:e.createdAt}}),t}function nm(e,t){let n=[];if(e.role===`assistant`&&e.thinking?.length)for(let t of e.thinking)t.content&&n.push({type:`thinking`,content:t.content,...t.signature&&{signature:t.signature}});if(e.role===`assistant`&&e.structuredOutput)n.push(e.structuredOutput);else if(e.role===`tool`&&e.toolCallId)n.push({type:`tool-result`,toolCallId:e.toolCallId,content:Yp(e.content),state:`complete`});else if(Array.isArray(e.content))for(let t of e.content)n.push(t);else{let t=Yp(e.content);t&&n.push({type:`text`,content:t})}if(e.toolCalls&&e.toolCalls.length>0)for(let t of e.toolCalls){let e;try{e=JSON.parse(t.function.arguments)}catch{e=void 0}n.push({type:`tool-call`,id:t.id,name:t.function.name,arguments:t.function.arguments,state:`input-complete`,...e!==void 0&&{input:e},...t.metadata!==void 0&&{metadata:t.metadata}})}return{id:t||om(),role:e.role===`tool`?`assistant`:e.role,parts:n,...e.createdAt!==void 0&&{createdAt:e.createdAt}}}function rm(e){if(`parts`in e)return{...e,id:e.id||om()};let t=e.id||om();switch(e.role){case`user`:return{id:t,role:`user`,parts:im(e.content)};case`assistant`:return nm({role:`assistant`,content:e.content??null,...e.toolCalls&&{toolCalls:e.toolCalls}},t);case`tool`:return nm({role:`tool`,content:e.content,toolCallId:e.toolCallId},t);case`system`:case`developer`:return{id:t,role:`system`,parts:e.content?[{type:`text`,content:e.content}]:[]};case`reasoning`:return{id:t,role:`assistant`,parts:e.content?[{type:`thinking`,content:e.content}]:[]};default:return{id:t,role:`assistant`,parts:[]}}}function im(e){if(typeof e==`string`)return e?[{type:`text`,content:e}]:[];let t=[];for(let n of e)n.type===`text`?t.push({type:`text`,content:n.text}):n.type!==`binary`&&t.push(n);return t}function am(e,t){return`parts`in e?{...e,id:e.id||t(),createdAt:e.createdAt||new Date}:{...nm(e,t()),createdAt:e.createdAt??new Date}}function om(){return`msg-${Date.now()}-${Math.random().toString(36).substring(7)}`}function sm(e){if(e.approvalSchema!==void 0&&e.needsApproval!==!0)throw TypeError(`approvalSchema requires needsApproval: true.`);let t=e.inputSchema,n=e.outputSchema,r=e.approvalSchema,i=e.needsApproval;return{__toolSide:`definition`,...e,inputSchema:t,outputSchema:n,approvalSchema:r,needsApproval:i,server(a){return{__toolSide:`server`,...e,inputSchema:t,outputSchema:n,approvalSchema:r,needsApproval:i,execute:a}},client(a){return{__toolSide:`client`,...e,inputSchema:t,outputSchema:n,approvalSchema:r,needsApproval:i,...a!==void 0&&{execute:a}}}}}var cm=y((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.ALL=e.COLLECTION=e.ATOM=e.SPECIAL=e.INF=e._INFINITY=e.INFINITY=e.NAN=e.BOOL=e.NULL=e.OBJ=e.ARR=e.NUM=e.STR=void 0,e.STR=1,e.NUM=2,e.ARR=4,e.OBJ=8,e.NULL=16,e.BOOL=32,e.NAN=64,e.INFINITY=128,e._INFINITY=256,e.INF=e.INFINITY|e._INFINITY,e.SPECIAL=e.NULL|e.BOOL|e.INF|e.NAN,e.ATOM=e.STR|e.NUM|e.SPECIAL,e.COLLECTION=e.ARR|e.OBJ,e.ALL=e.ATOM|e.COLLECTION,e.Allow={STR:e.STR,NUM:e.NUM,ARR:e.ARR,OBJ:e.OBJ,NULL:e.NULL,BOOL:e.BOOL,NAN:e.NAN,INFINITY:e.INFINITY,_INFINITY:e._INFINITY,INF:e.INF,SPECIAL:e.SPECIAL,ATOM:e.ATOM,COLLECTION:e.COLLECTION,ALL:e.ALL},e.default=e.Allow})),lm=y((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__exportStar||function(e,n){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(n,r)&&t(n,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.MalformedJSON=e.PartialJSON=e.parseJSON=e.parse=void 0;var r=cm();Object.defineProperty(e,"Allow",{enumerable:!0,get:function(){return r.Allow}}),n(cm(),e);var i=class extends Error{};e.PartialJSON=i;var a=class extends Error{};e.MalformedJSON=a;function o(e,t=r.Allow.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return s(e.trim(),t)}e.parseJSON=o;var s=(e,t)=>{let n=e.length,o=0,s=e=>{throw new i(`${e} at position ${o}`)},c=e=>{throw new a(`${e} at position ${o}`)},l=()=>(m(),o>=n&&s(`Unexpected end of input`),e[o]===`"`?u():e[o]===`{`?d():e[o]===`[`?f():e.substring(o,o+4)===`null`||r.Allow.NULL&t&&n-o<4&&`null`.startsWith(e.substring(o))?(o+=4,null):e.substring(o,o+4)===`true`||r.Allow.BOOL&t&&n-o<4&&`true`.startsWith(e.substring(o))?(o+=4,!0):e.substring(o,o+5)===`false`||r.Allow.BOOL&t&&n-o<5&&`false`.startsWith(e.substring(o))?(o+=5,!1):e.substring(o,o+8)===`Infinity`||r.Allow.INFINITY&t&&n-o<8&&`Infinity`.startsWith(e.substring(o))?(o+=8,1/0):e.substring(o,o+9)===`-Infinity`||r.Allow._INFINITY&t&&1<n-o&&n-o<9&&`-Infinity`.startsWith(e.substring(o))?(o+=9,-1/0):e.substring(o,o+3)===`NaN`||r.Allow.NAN&t&&n-o<3&&`NaN`.startsWith(e.substring(o))?(o+=3,NaN):p()),u=()=>{let i=o,a=!1;for(o++;o<n&&(e[o]!==`"`||a&&e[o-1]===`\\`);)a=e[o]===`\\`&&!a,o++;if(e.charAt(o)==`"`)try{return JSON.parse(e.substring(i,++o-Number(a)))}catch(e){c(String(e))}else if(r.Allow.STR&t)try{return JSON.parse(e.substring(i,o-Number(a))+`"`)}catch{return JSON.parse(e.substring(i,e.lastIndexOf(`\\`))+`"`)}s(`Unterminated string literal`)},d=()=>{o++,m();let i={};try{for(;e[o]!==`}`;){if(m(),o>=n&&r.Allow.OBJ&t)return i;let a=u();m(),o++;try{i[a]=l()}catch(e){if(r.Allow.OBJ&t)return i;throw e}m(),e[o]===`,`&&o++}}catch{if(r.Allow.OBJ&t)return i;s(`Expected '}' at end of object`)}return o++,i},f=()=>{o++;let n=[];try{for(;e[o]!==`]`;)n.push(l()),m(),e[o]===`,`&&o++}catch{if(r.Allow.ARR&t)return n;s(`Expected ']' at end of array`)}return o++,n},p=()=>{if(o===0){e===`-`&&c(`Not sure what '-' is`);try{return JSON.parse(e)}catch(n){if(r.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf(`e`)))}catch{}c(String(n))}}let i=o;for(e[o]===`-`&&o++;e[o]&&`,]}`.indexOf(e[o])===-1;)o++;o==n&&!(r.Allow.NUM&t)&&s(`Unterminated number literal`);try{return JSON.parse(e.substring(i,o))}catch{e.substring(i,o)===`-`&&s(`Not sure what '-' is`);try{return JSON.parse(e.substring(i,e.lastIndexOf(`e`)))}catch(e){c(String(e))}}},m=()=>{for(;o<n&&`
12
- \r `.includes(e[o]);)o++};return l()};e.parse=o}))(),um=new class{parse(e){if(!(!e||e.trim()===``))try{return(0,lm.parse)(e)}catch{return}}};function dm(e){return um.parse(e)}var fm=class{shouldEmit(e,t){return!0}};function pm(e,t,n){return e.map(e=>{if(e.id!==t)return e;let r=[...e.parts],i=r.length>0?r[r.length-1]:null;return i&&i.type===`text`?r[r.length-1]={type:`text`,content:n}:r.push({type:`text`,content:n}),{...e,parts:r}})}function mm(e,t,n){return e.map(e=>{if(e.id!==t)return e;let r=[...e.parts],i=r.find(e=>e.type===`tool-call`&&e.id===n.id),a=n.metadata??i?.metadata,o=n.input??i?.input,s={type:`tool-call`,id:n.id,name:n.name,arguments:n.arguments,state:n.state,...i?.approval&&{approval:{...i.approval}},...i?.output!==void 0&&{output:i.output},...o!==void 0&&{input:o},...a!==void 0&&{metadata:a}};return i?r[r.indexOf(i)]=s:r.push(s),{...e,parts:r}})}function hm(e,t,n,r,i,a){return e.map(e=>{if(e.id!==t)return e;let o=[...e.parts],s=o.findIndex(e=>e.type===`tool-result`&&e.toolCallId===n),c={type:`tool-result`,toolCallId:n,content:r,state:i,...a&&{error:a}};return s>=0?o[s]=c:o.push(c),{...e,parts:o}})}function gm(e,t,n,r){return e.map(e=>{if(e.id!==t)return e;let i=[...e.parts],a=i.find(e=>e.type===`tool-call`&&e.id===n);if(a){let e=i.indexOf(a);i[e]={...a,state:`approval-requested`,approval:{id:r,needsApproval:!0}}}return{...e,parts:i}})}function _m(e,t,n,r,i){return e.map(e=>{let a=[...e.parts],o=a.find(e=>e.type===`tool-call`&&e.id===t);if(o){let e=a.indexOf(o);a[e]={...o,output:i?{error:i}:n,state:r??(i?`error`:`complete`)}}return{...e,parts:a}})}function vm(e,t,n){return e.map(e=>{let r=[...e.parts],i=r.find(e=>e.type===`tool-call`&&e.approval?.id===t);if(i&&i.approval){let e=r.indexOf(i);r[e]={...i,approval:{...i.approval,approved:n},state:`approval-responded`}}return{...e,parts:r}})}function ym(e,t,n){return e.map(e=>{if(e.id!==t)return e;let r=[...e.parts],i=r.findIndex(e=>e.type===`structured-output`),a=i>=0?r[i]:null,o=(a?.raw??``)+n,s=dm(o)??a?.partial,c={type:`structured-output`,status:`streaming`,raw:o,...s===void 0?{}:{partial:s},...a?.reasoning===void 0?{}:{reasoning:a.reasoning}};return i>=0?r[i]=c:r.push(c),{...e,parts:r}})}function bm(e,t,n,r,i){return e.map(e=>{if(e.id!==t)return e;let a=[...e.parts],o=a.findIndex(e=>e.type===`structured-output`),s=o>=0?a[o].raw:``,c=r||s;if(c===``&&n!==void 0)try{c=JSON.stringify(n)}catch{}let l={type:`structured-output`,status:`complete`,data:n,partial:n,raw:c,...i===void 0?{}:{reasoning:i}};return o>=0?a[o]=l:a.push(l),{...e,parts:a}})}function xm(e,t,n){return e.map(e=>{if(e.id!==t)return e;let r=[...e.parts],i=r.findIndex(e=>e.type===`structured-output`);if(i<0)return r.push({type:`structured-output`,status:`error`,raw:``,errorMessage:n}),{...e,parts:r};let a=r[i];return a.status===`complete`?e:(r[i]={...a,status:`error`,errorMessage:n},{...e,parts:r})})}function Sm(e,t,n,r,i){return e.map(e=>{if(e.id!==t)return e;let a=[...e.parts],o=a.findIndex(e=>e.type===`thinking`&&e.stepId===n),s={type:`thinking`,content:r,stepId:n,...i&&{signature:i}};return o>=0?a[o]=s:a.push(s),{...e,parts:a}})}var Cm=12;function wm(e){return e.some(e=>{let t=e.metadata;if(!t||typeof t!=`object`||Array.isArray(t))return!1;let n=t[Ep];return typeof n==`object`&&!!n&&!Array.isArray(n)&&n.kind===`generic`})}var Tm=class e{chunkStrategy;events;jsonParser;recordingEnabled;messages=[];messageStates=new Map;activeMessageIds=new Set;toolCallToMessage=new Map;pendingManualMessageId=null;pendingThinkingStepId=null;structuredMessageIds=new Set;structuredOutputUpdateBatches=new Map;activeRuns=new Set;finishReason=null;hasError=!1;isDone=!1;recording=null;recordingStartTime=0;constructor(e={}){this.chunkStrategy=e.chunkStrategy||new fm,this.events=e.events||{},this.jsonParser=e.jsonParser||um,this.recordingEnabled=e.recording??!1,e.initialMessages&&(this.messages=[...e.initialMessages])}setMessages(e){this.messages=[...e],this.emitMessagesChange()}addUserMessage(e,t){let n=typeof e==`string`?[{type:`text`,content:e}]:e.map(e=>e),r={id:t??om(),role:`user`,parts:n,createdAt:new Date};return this.messages=[...this.messages,r],this.emitMessagesChange(),r}prepareAssistantMessage(){this.resetStreamState()}startAssistantMessage(e){this.prepareAssistantMessage();let{messageId:t}=this.ensureAssistantMessage(e);return this.pendingManualMessageId=t,t}getCurrentAssistantMessageId(){let e=null;for(let[t,n]of this.messageStates)n.role===`assistant`&&(e=t);return e}addToolResult(e,t,n){let r=this.messages.find(t=>t.parts.some(t=>t.type===`tool-call`&&t.id===e));if(!r){console.warn(`[StreamProcessor] Could not find message with tool call ${e}`);return}let i=_m(this.messages,e,t,n?`error`:void 0,n),a=Up(t),o=n?`error`:`complete`;i=hm(i,r.id,e,a,o,n),this.messages=i,this.emitMessagesChange()}addToolApprovalResponse(e,t){this.messages=vm(this.messages,e,t),this.emitMessagesChange()}toModelMessages(){let e=[];for(let t of this.messages)e.push(...Zp(t));return e}getMessages(){return this.messages}areAllToolsComplete(){let e=this.messages.findLast(e=>e.role===`assistant`);if(!e)return!0;let t=e.parts.filter(e=>e.type===`tool-call`);if(t.length===0)return!0;let n=new Set(e.parts.filter(e=>e.type===`tool-result`).map(e=>e.toolCallId));return t.every(e=>e.state===`complete`||e.state===`approval-responded`||e.output!==void 0&&!e.approval||n.has(e.id)||Gp(e))}removeMessagesAfter(e){let t=new Set(this.messages.slice(0,e+1).map(e=>e.id));for(let e of this.structuredMessageIds)t.has(e)||this.structuredMessageIds.delete(e);for(let e of this.structuredOutputUpdateBatches.keys())t.has(e)||this.structuredOutputUpdateBatches.delete(e);for(let e of this.messageStates.keys())t.has(e)||this.messageStates.delete(e);for(let[e,n]of this.toolCallToMessage)t.has(n)||this.toolCallToMessage.delete(e);for(let e of this.activeMessageIds)t.has(e)||this.activeMessageIds.delete(e);this.messages=this.messages.slice(0,e+1),this.emitMessagesChange()}clearMessages(){this.messages=[],this.messageStates.clear(),this.activeMessageIds.clear(),this.toolCallToMessage.clear(),this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.pendingManualMessageId=null,this.emitMessagesChange()}async process(e){this.resetStreamState(),this.recordingEnabled&&this.startRecording();for await(let t of e)this.processChunk(t);return this.finalizeStream(),this.recording&&(this.recording.result=this.getResult()),this.getResult()}processChunk(e){switch(this.recording&&this.recording.chunks.push({chunk:e,timestamp:Date.now(),index:this.recording.chunks.length}),e.type){case`TEXT_MESSAGE_START`:this.handleTextMessageStartEvent(e);break;case`TEXT_MESSAGE_CONTENT`:this.handleTextMessageContentEvent(e);break;case`TEXT_MESSAGE_END`:this.handleTextMessageEndEvent(e);break;case`TOOL_CALL_START`:this.handleToolCallStartEvent(e);break;case`TOOL_CALL_ARGS`:this.handleToolCallArgsEvent(e);break;case`TOOL_CALL_END`:this.handleToolCallEndEvent(e);break;case`RUN_FINISHED`:this.handleRunFinishedEvent(e);break;case`RUN_ERROR`:this.handleRunErrorEvent(e);break;case`STEP_FINISHED`:this.handleStepFinishedEvent(e);break;case`MESSAGES_SNAPSHOT`:this.handleMessagesSnapshotEvent(e);break;case`CUSTOM`:this.handleCustomEvent(e);break;case`RUN_STARTED`:this.handleRunStartedEvent(e);break;case`REASONING_START`:case`REASONING_MESSAGE_START`:case`REASONING_MESSAGE_END`:case`REASONING_END`:break;case`REASONING_MESSAGE_CONTENT`:this.handleReasoningMessageContentEvent(e);break;case`TOOL_CALL_RESULT`:this.handleToolCallResultEvent(e);break;case`STEP_STARTED`:this.handleStepStartedEvent(e)}}createMessageState(e,t){let n={id:e,role:t,totalTextContent:``,currentSegmentText:``,lastEmittedText:``,hasSeenReasoningEvents:!1,thinkingSteps:new Map,thinkingStepSignatures:new Map,thinkingStepOrder:[],currentThinkingStepId:null,toolCalls:new Map,toolCallOrder:[],hasToolCallsSinceTextStart:!1,isComplete:!1};return this.messageStates.set(e,n),n}getMessageState(e){return this.messageStates.get(e)}consumePendingThinkingStep(e){if(!this.pendingThinkingStepId)return;let t=this.pendingThinkingStepId;e.currentThinkingStepId=t,e.thinkingSteps.has(t)||(e.thinkingSteps.set(t,``),e.thinkingStepOrder.push(t)),this.pendingThinkingStepId=null}getActiveAssistantMessageId(){let e=Array.from(this.activeMessageIds).reverse();for(let t of e){let e=this.messageStates.get(t);if(e&&e.role===`assistant`)return t}return null}ensureAssistantMessage(e){if(e){let t=this.getMessageState(e);if(t)return{messageId:e,state:t}}let t=this.getActiveAssistantMessageId();if(t){let e=this.getMessageState(t);if(e)return{messageId:t,state:e}}if(e){let t=this.messages.find(t=>t.id===e);if(t){let n=this.createMessageState(e,t.role);this.activeMessageIds.add(e);let r=t.parts.length>0?t.parts[t.parts.length-1]:null;return r&&r.type===`text`&&(n.currentSegmentText=r.content,n.lastEmittedText=r.content,n.totalTextContent=r.content),{messageId:e,state:n}}}let n=e||om(),r={id:n,role:`assistant`,parts:[],createdAt:new Date};this.messages=[...this.messages,r];let i=this.createMessageState(n,`assistant`);return this.activeMessageIds.add(n),this.pendingManualMessageId=n,this.events.onStreamStart?.(),this.emitMessagesChange(),{messageId:n,state:i}}handleTextMessageStartEvent(e){let{messageId:t,role:n}=e,r=n===`user`||n===`system`?n:`assistant`;if(this.pendingManualMessageId){let e=this.pendingManualMessageId;if(this.pendingManualMessageId=null,e!==t){this.messages=this.messages.map(n=>n.id===e?{...n,id:t}:n);let n=this.messageStates.get(e);n&&(n.id=t,this.messageStates.delete(e),this.messageStates.set(t,n)),this.activeMessageIds.delete(e),this.activeMessageIds.add(t);for(let[n,r]of this.toolCallToMessage)r===e&&this.toolCallToMessage.set(n,t)}this.messageStates.has(t)||(this.createMessageState(t,r),this.activeMessageIds.add(t)),this.emitMessagesChange();return}if(this.messages.find(e=>e.id===t)){this.activeMessageIds.add(t);let e=this.messageStates.get(t);e?e.hasToolCallsSinceTextStart&&=(e.currentSegmentText!==e.lastEmittedText&&this.emitTextUpdateForMessage(t),e.currentSegmentText=``,e.lastEmittedText=``,!1):this.createMessageState(t,r);return}let i={id:t,role:r,parts:[],createdAt:new Date};this.messages=[...this.messages,i],this.createMessageState(t,r),this.activeMessageIds.add(t),this.events.onStreamStart?.(),this.emitMessagesChange()}handleTextMessageEndEvent(e){let{messageId:t}=e,n=this.getMessageState(t);n&&(n.isComplete||n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(t))}handleMessagesSnapshotEvent(e){this.resetStreamState();let t=this.messages,n=e.messages.map(rm);this.messages=this.reconcileSnapshotToolCalls(n,t),this.emitMessagesChange()}reconcileSnapshotToolCalls(e,t){let n=new Map;for(let e of t)for(let t of e.parts)t.type===`tool-call`&&n.set(t.id,t);let r=new Set;for(let t of e)for(let e of t.parts)e.type===`tool-call`&&r.add(e.id);let i=[];for(let t of e){let e=t.role===`assistant`&&t.parts.length===1?t.parts.find(e=>e.type===`tool-result`):void 0;if(!e){i.push(t);continue}let a=i.findLast(t=>t.parts.some(t=>t.type===`tool-call`&&t.id===e.toolCallId))??i.findLast(e=>e.role===`assistant`&&(e.parts.length!==1||e.parts[0]?.type!==`tool-result`));if(!a){r.has(e.toolCallId)||console.warn(`[StreamProcessor] MESSAGES_SNAPSHOT contains a tool-result for "${e.toolCallId}" but no matching tool-call exists in the snapshot, and there is no assistant message to anchor into; addToolResult("${e.toolCallId}") will not be able to locate this call`),i.push(t);continue}let o=[...a.parts];if(!r.has(e.toolCallId)&&!o.some(t=>t.type===`tool-call`&&t.id===e.toolCallId)){let t=n.get(e.toolCallId);t?(o.push({...t}),r.add(t.id)):console.warn(`[StreamProcessor] MESSAGES_SNAPSHOT contains a tool-result for "${e.toolCallId}" but no matching tool-call exists in the snapshot or the pre-snapshot state; addToolResult("${e.toolCallId}") will not be able to locate this call`)}o.push(e),a.parts=o}return this.enrichSnapshotToolCallsFromResults(i,n)}enrichSnapshotToolCallsFromResults(e,t){let n=new Map;for(let t of e)for(let e of t.parts)e.type===`tool-result`&&n.set(e.toolCallId,e);return e.map(e=>{let r=e.parts.map(e=>{if(e.type!==`tool-call`)return e;let r=t.get(e.id),i=n.get(e.id),a=e;if(r&&(r.output!==void 0||r.state===`complete`||r.state===`error`)&&(e.output===void 0||e.state===`input-complete`||e.state===`input-streaming`||e.state===`awaiting-input`)&&(a={...e,...r.output===void 0?{}:{output:r.output},state:r.state,...r.approval===void 0?{}:{approval:r.approval},...r.metadata===void 0?{}:{metadata:r.metadata}}),i&&a.output===void 0){let e;if(Array.isArray(i.content))e=i.content;else try{e=JSON.parse(i.content)}catch{e=i.content}let t=i.state===`error`?this.extractToolResultError(e):void 0;a={...a,output:t?{error:t}:e,state:i.state===`error`?`error`:`complete`}}return a});return r.some((t,n)=>t!==e.parts[n])?{...e,parts:r}:e})}handleTextMessageContentEvent(e){let{messageId:t,state:n}=this.ensureAssistantMessage(e.messageId);if(this.structuredMessageIds.has(t)){let r=e.delta||``;if(r===``&&e.content!==void 0&&e.content!==``){let n=(this.messages.find(e=>e.id===t)?.parts.find(e=>e.type===`structured-output`)??{raw:``}).raw;r=e.content.startsWith(n)?e.content.slice(n.length):n.startsWith(e.content)?``:e.content}r!==``&&(this.messages=ym(this.messages,t,r),n.totalTextContent+=r,this.queueStructuredOutputUpdate(t,r),this.emitMessagesChange());return}let r=n.currentSegmentText;n.hasToolCallsSinceTextStart&&r.length>0&&this.isNewTextSegment(e,r)&&(r!==n.lastEmittedText&&this.emitTextUpdateForMessage(t),n.currentSegmentText=``,n.lastEmittedText=``,n.hasToolCallsSinceTextStart=!1);let i=n.currentSegmentText,a=i,o=e.delta||``;o===``?e.content!==void 0&&e.content!==``&&(a=e.content.startsWith(i)?e.content:i.startsWith(e.content)?i:i+e.content):a=i+o;let s=a.slice(i.length);n.currentSegmentText=a,n.totalTextContent+=s;let c=e.delta||e.content||``;this.chunkStrategy.shouldEmit(c,n.currentSegmentText)&&n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(t)}handleToolCallStartEvent(e){let t=e.parentMessageId??this.getActiveAssistantMessageId(),{messageId:n,state:r}=this.ensureAssistantMessage(t??void 0);r.hasToolCallsSinceTextStart=!0;let i=e.toolCallId;if(!r.toolCalls.get(i)){let t=`awaiting-input`,a=e.toolCallName??e.toolName,o=e.metadata,s={id:e.toolCallId,name:a,arguments:``,state:t,parsedArguments:void 0,index:e.index??r.toolCalls.size,...o!==void 0&&{metadata:o}};r.toolCalls.set(i,s),r.toolCallOrder.push(i),this.toolCallToMessage.set(i,n),this.messages=mm(this.messages,n,{id:e.toolCallId,name:a,arguments:``,state:t,...o!==void 0&&{metadata:o}}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(n,e.toolCallId,t,``)}}handleToolCallArgsEvent(e){let t=e.toolCallId,n=this.toolCallToMessage.get(t);if(!n)return;let r=this.getMessageState(n);if(!r)return;let i=r.toolCalls.get(t);if(!i)return;let a=i.state===`awaiting-input`;i.arguments+=e.delta||``,a&&e.delta&&(i.state=`input-streaming`),i.parsedArguments=this.jsonParser.parse(i.arguments),this.messages=mm(this.messages,n,{id:i.id,name:i.name,arguments:i.arguments,state:i.state}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(n,i.id,i.state,i.arguments)}handleToolCallEndEvent(e){let t=this.toolCallToMessage.get(e.toolCallId);if(!t)return;let n=this.getMessageState(t);if(!n)return;let r=n.toolCalls.get(e.toolCallId);if(r&&r.state!==`input-complete`){if(e.input!==void 0&&!r.arguments)try{r.arguments=JSON.stringify(e.input)}catch{}let i=n.toolCallOrder.indexOf(e.toolCallId);this.completeToolCall(t,i,r),e.input!==void 0&&(r.parsedArguments=e.input,this.messages=mm(this.messages,t,{id:r.id,name:r.name,arguments:r.arguments,state:`input-complete`,input:e.input,...r.metadata!==void 0&&{metadata:r.metadata}}),this.emitMessagesChange())}if(e.result){let n;if(Array.isArray(e.result))n=e.result;else try{n=JSON.parse(e.result)}catch{n=e.result}this.messages=_m(this.messages,e.toolCallId,n,e.state===`output-error`?`error`:void 0);let r=e.state===`output-error`?`error`:`complete`;this.messages=hm(this.messages,t,e.toolCallId,e.result,r,r===`error`?this.extractToolResultError(n):void 0),this.emitMessagesChange()}}extractToolResultError(e){return e&&typeof e==`object`&&`error`in e&&typeof e.error==`string`?e.error:typeof e==`string`?e:`Tool execution failed`}handleToolCallResultEvent(e){let t=this.toolCallToMessage.get(e.toolCallId);if(!t)return;let n;try{n=JSON.parse(e.content)}catch{n=e.content}this.messages=_m(this.messages,e.toolCallId,n,e.state===`output-error`?`error`:void 0);let r=e.state===`output-error`?`error`:`complete`;this.messages=hm(this.messages,t,e.toolCallId,e.content,r,r===`error`?this.extractToolResultError(n):void 0),this.emitMessagesChange()}handleRunStartedEvent(e){this.activeRuns.add(e.runId)}handleRunFinishedEvent(e){this.finishReason=e.finishReason??null,this.activeRuns.delete(e.runId),e.outcome?.type===`interrupt`&&this.handleInterrupts(e.outcome.interrupts),this.activeRuns.size===0&&(this.isDone=!0,this.completeAllToolCalls(),this.finalizeStream())}handleInterrupts(e){let t=wm(e);for(let n of e){let e=n.metadata&&typeof n.metadata==`object`?n.metadata:{},r=typeof e.kind==`string`?e.kind:void 0,i=n.toolCallId;if(!i)continue;let a=typeof e.toolName==`string`?e.toolName:this.findToolCallName(i),o=Object.hasOwn(e,`input`)?e.input:{};if(r===`approval`||n.reason===`approval_required`){let e=this.getActiveAssistantMessageId()??this.toolCallToMessage.get(i)??this.messages.find(e=>e.role===`assistant`&&e.parts.some(e=>e.type===`tool-call`&&e.id===i))?.id;e&&(this.messages=gm(this.messages,e,i,n.id),this.emitMessagesChange()),this.events.onApprovalRequest?.({toolCallId:i,toolName:a,input:o,approvalId:n.id});continue}if(r===`client_tool`||n.reason===`client_tool_input`){if(t)continue;this.events.onToolCall?.({toolCallId:i,toolName:a,input:o})}}}findToolCallName(e){for(let t of this.messageStates.values()){let n=t.toolCalls.get(e);if(n)return n.name}return``}handleRunErrorEvent(e){this.hasError=!0;let t=`runId`in e&&typeof e.runId==`string`?e.runId:void 0;t?this.activeRuns.delete(t):this.activeRuns.clear();let{messageId:n}=this.ensureAssistantMessage(),r=e.message||e.error?.message||`An error occurred`;!e.message&&!e.error?.message&&console.error(`[StreamProcessor] RUN_ERROR with no message; original chunk:`,e),this.structuredMessageIds.has(n)&&(this.flushStructuredOutputUpdate(n),this.messages=xm(this.messages,n,r),this.structuredMessageIds.delete(n),this.emitStructuredOutputChange(n,`error`),this.emitMessagesChange()),this.events.onError?.(Xf(e))}handleStepStartedEvent(e){let t=e.stepId??om(),n=this.getActiveAssistantMessageId();if(n){let e=this.getMessageState(n);if(e){e.currentThinkingStepId=t,e.thinkingSteps.has(t)||(e.thinkingSteps.set(t,``),e.thinkingStepOrder.push(t)),this.pendingThinkingStepId=null;return}}this.pendingThinkingStepId=t}handleStepFinishedEvent(e){let{messageId:t,state:n}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0);if(n.hasSeenReasoningEvents){if(e.signature){let r=n.currentThinkingStepId??e.stepId;if(!r)return;let i=n.thinkingSteps.get(r);i!==void 0&&(n.thinkingStepSignatures.set(r,e.signature),this.messages=Sm(this.messages,t,r,i,e.signature),this.emitMessagesChange())}return}this.consumePendingThinkingStep(n);let r=n.currentThinkingStepId??e.stepId??om();n.thinkingSteps.has(r)||(n.thinkingSteps.set(r,``),n.thinkingStepOrder.push(r),n.currentThinkingStepId=r);let i=n.thinkingSteps.get(r)??``,a=i;e.delta&&e.delta!==``?a=i+e.delta:e.content&&e.content!==``&&(a=e.content.startsWith(i)?e.content:i.startsWith(e.content)?i:i+e.content),n.thinkingSteps.set(r,a),e.signature&&n.thinkingStepSignatures.set(r,e.signature),this.messages=Sm(this.messages,t,r,a,n.thinkingStepSignatures.get(r)),this.emitMessagesChange(),this.events.onThinkingUpdate?.(t,r,a)}handleReasoningMessageContentEvent(e){let{messageId:t,state:n}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0);n.hasSeenReasoningEvents=!0;let r=e.delta||``;this.consumePendingThinkingStep(n);let i=n.currentThinkingStepId??e.messageId;n.thinkingSteps.has(i)||(n.thinkingSteps.set(i,``),n.thinkingStepOrder.push(i),n.currentThinkingStepId=i);let a=(n.thinkingSteps.get(i)??``)+r;n.thinkingSteps.set(i,a),this.messages=Sm(this.messages,t,i,a,n.thinkingStepSignatures.get(i)),this.emitMessagesChange(),this.events.onThinkingUpdate?.(t,i,a)}handleCustomEvent(e){let t=this.getActiveAssistantMessageId();if(e.name===`structured-output.start`&&e.value){let n=e.value,{messageId:r}=this.ensureAssistantMessage(n.messageId??t??void 0);r&&(this.structuredMessageIds.add(r),this.structuredOutputUpdateBatches.delete(r),this.events.onStructuredOutputChange?.({phase:`start`,messageId:r,status:`streaming`,raw:``}));return}if(e.name===`structured-output.complete`&&e.value){let n=e.value,{messageId:r}=this.ensureAssistantMessage(n.messageId??t??void 0);r&&(this.flushStructuredOutputUpdate(r),this.messages=bm(this.messages,r,n.object,n.raw??``,n.reasoning),this.structuredMessageIds.delete(r),this.emitStructuredOutputChange(r,`complete`),this.emitMessagesChange())}if(e.name===`tool-input-available`&&e.value){let{toolCallId:t,toolName:n,input:r}=e.value;this.events.onToolCall?.({toolCallId:t,toolName:n,input:r});return}if(e.name===`approval-requested`&&e.value){let{toolCallId:n,toolName:r,input:i,approval:a}=e.value,o=t??this.toolCallToMessage.get(n);o&&(this.messages=gm(this.messages,o,n,a.id),this.emitMessagesChange()),this.events.onApprovalRequest?.({toolCallId:n,toolName:r,input:i,approvalId:a.id});return}if(e.name===`ui-resource`&&e.value){let n=e.value,r=this.toolCallToMessage.get(n.toolCallId)??t;if(r){let e={type:`ui-resource`,resource:n.resource,toolCallId:n.toolCallId,toolName:n.toolName,...n.serverId!==void 0&&{serverId:n.serverId},...n.meta!==void 0&&{meta:n.meta}};this.messages=this.messages.map(t=>t.id===r?{...t,parts:[...t.parts,e]}:t),this.emitMessagesChange()}else console.warn(`[mcp-apps] dropped ui-resource: no target message for toolCallId "${n.toolCallId}" (toolName "${n.toolName}")`);return}if(this.events.onCustomEvent){let t=e.value&&typeof e.value==`object`?e.value.toolCallId:void 0;this.events.onCustomEvent(e.name,e.value,{toolCallId:t})}}isNewTextSegment(e,t){return e.content!==void 0&&(e.content.length<t.length||!e.content.startsWith(t)&&!t.startsWith(e.content))}completeAllToolCalls(){for(let e of this.activeMessageIds)this.completeAllToolCallsForMessage(e)}completeAllToolCallsForMessage(e){let t=this.getMessageState(e);t&&t.toolCalls.forEach((n,r)=>{if(n.state!==`input-complete`){let i=t.toolCallOrder.indexOf(r);this.completeToolCall(e,i,n)}})}completeToolCall(e,t,n){n.state=`input-complete`;let r=!1;try{n.parsedArguments=JSON.parse(n.arguments),r=!0}catch{n.parsedArguments=void 0}this.isToolCallPartErrored(n.id)||this.isToolCallPartAwaitingUserAction(n.id)||(this.messages=mm(this.messages,e,{id:n.id,name:n.name,arguments:n.arguments,state:`input-complete`,...r&&{input:n.parsedArguments},...n.metadata!==void 0&&{metadata:n.metadata}}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(e,n.id,`input-complete`,n.arguments))}isToolCallPartAwaitingUserAction(e){return this.messages.some(t=>t.parts?.some(t=>t.type===`tool-call`&&t.id===e&&(t.state===`approval-requested`||t.state===`approval-responded`)))}isToolCallPartErrored(e){return this.messages.some(t=>t.parts?.some(t=>t.type===`tool-call`&&t.id===e&&t.state===`error`))}emitTextUpdateForMessage(e){let t=this.getMessageState(e);t&&(t.lastEmittedText=t.currentSegmentText,this.messages=pm(this.messages,e,t.currentSegmentText),this.emitMessagesChange(),this.events.onTextUpdate?.(e,t.currentSegmentText))}queueStructuredOutputUpdate(e,t){let n=this.structuredOutputUpdateBatches.get(e),r={delta:`${n?.delta??``}${t}`,chunkCount:(n?.chunkCount??0)+1};this.structuredOutputUpdateBatches.set(e,r),r.chunkCount>=Cm&&this.flushStructuredOutputUpdate(e)}flushStructuredOutputUpdate(e){let t=this.structuredOutputUpdateBatches.get(e);!t||t.chunkCount===0||(this.structuredOutputUpdateBatches.delete(e),this.emitStructuredOutputChange(e,`update`,t.delta))}emitStructuredOutputChange(e,t,n){let r=this.messages.find(t=>t.id===e)?.parts.find(e=>e.type===`structured-output`);r&&this.events.onStructuredOutputChange?.({phase:t,messageId:e,status:r.status,raw:r.raw,...r.partial===void 0?{}:{partial:r.partial},...r.data===void 0?{}:{data:r.data},...r.reasoning===void 0?{}:{reasoning:r.reasoning},...r.errorMessage===void 0?{}:{errorMessage:r.errorMessage},...n===void 0?{}:{delta:n}})}emitMessagesChange(){this.events.onMessagesChange?.([...this.messages])}finalizeStream(){let e;for(let t of this.activeMessageIds){let n=this.getMessageState(t);if(!n)continue;this.completeAllToolCallsForMessage(t),n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(t),n.isComplete=!0;let r=this.messages.find(e=>e.id===t);r&&r.role===`assistant`&&(e=r)}for(let e of this.structuredMessageIds)this.flushStructuredOutputUpdate(e),this.messages=xm(this.messages,e,`Stream ended without structured-output.complete`),this.emitStructuredOutputChange(e,`error`);if(this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.activeMessageIds.clear(),e&&!this.hasError&&this.isWhitespaceOnlyMessage(e)){this.messages=this.messages.filter(t=>t.id!==e.id),this.emitMessagesChange();return}e&&this.events.onStreamEnd?.(e)}getCompletedToolCalls(){let e=[];for(let t of this.messageStates.values())for(let n of t.toolCalls.values())n.state===`input-complete`&&e.push({id:n.id,type:`function`,function:{name:n.name,arguments:n.arguments},...n.metadata!==void 0&&{metadata:n.metadata}});return e}getResult(){let e=this.getCompletedToolCalls(),t=``,n=``;for(let e of this.messageStates.values()){t+=e.totalTextContent;for(let t of e.thinkingStepOrder)n+=e.thinkingSteps.get(t)??``}return{content:t,thinking:n||void 0,toolCalls:e.length>0?e:void 0,finishReason:this.finishReason}}getState(){let e=``,t=``,n=new Map,r=[];for(let i of this.messageStates.values()){e+=i.totalTextContent;for(let e of i.thinkingStepOrder)t+=i.thinkingSteps.get(e)??``;for(let[e,t]of i.toolCalls)n.set(e,t);r.push(...i.toolCallOrder)}return{content:e,thinking:t,toolCalls:n,toolCallOrder:r,finishReason:this.finishReason,done:this.isDone}}startRecording(){this.recordingEnabled=!0,this.recordingStartTime=Date.now(),this.recording={version:`1.0`,timestamp:this.recordingStartTime,chunks:[]}}getRecording(){return this.recording}resetStreamState(){this.messageStates.clear(),this.activeMessageIds.clear(),this.activeRuns.clear(),this.toolCallToMessage.clear(),this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.pendingManualMessageId=null,this.pendingThinkingStepId=null,this.finishReason=null,this.hasError=!1,this.isDone=!1,this.chunkStrategy.reset?.()}reset(){this.resetStreamState(),this.messages=[]}isWhitespaceOnlyMessage(e){return e.parts.length!==0&&e.parts.every(e=>e.type===`text`&&e.content.trim()===``)}static async replay(t,n){return new e(n).process(Em(t))}};function Em(e){return{async*[Symbol.asyncIterator](){for(let{chunk:t}of e.chunks)yield t}}}function Dm(e){let t=[];for(let n of e){let e=n.parts??[];if(n.role===`system`){t.push({...n,content:e.length>0?Om(e):n.content??``});continue}if(n.role===`user`){t.push({...n,content:e.length>0?km(e):n.content??``});continue}for(let r of e)r.type===`thinking`&&t.push({role:`reasoning`,id:jm(n.id,r),content:r.content});let r=Om(e),i=Am(e);t.push({...n,...r!==``&&{content:r},...i&&{toolCalls:i}});for(let n of e)n.type===`tool-result`&&t.push({role:`tool`,id:Mm(n.toolCallId),toolCallId:n.toolCallId,content:typeof n.content==`string`?n.content:JSON.stringify(n.content),...n.error!==void 0&&{error:n.error}})}return t}function Om(e){let t=[];for(let n of e)n.type===`text`?t.push(n.content):n.type===`structured-output`&&n.status===`complete`&&n.raw!==``&&t.push(n.raw);return t.join(``)}function km(e){if(!e.some(e=>e.type===`image`||e.type===`audio`||e.type===`video`||e.type===`document`))return Om(e);let t=[];for(let n of e)n.type===`text`?t.push({type:`text`,text:n.content}):(n.type===`image`||n.type===`audio`||n.type===`video`||n.type===`document`)&&t.push(n);return t}function Am(e){let t=[];for(let n of e)n.type===`tool-call`&&t.push({id:n.id,type:`function`,function:{name:n.name,arguments:n.arguments}});return t.length>0?t:void 0}function jm(e,t){return`${e}-reasoning-${t.id??Nm(t.content)}`}function Mm(e){return`tool-${e}`}function Nm(e){let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)|0;return Math.abs(t).toString(36)}var Pm=function(e){return e.TEXT_MESSAGE_START=`TEXT_MESSAGE_START`,e.TEXT_MESSAGE_CONTENT=`TEXT_MESSAGE_CONTENT`,e.TEXT_MESSAGE_END=`TEXT_MESSAGE_END`,e.TEXT_MESSAGE_CHUNK=`TEXT_MESSAGE_CHUNK`,e.TOOL_CALL_START=`TOOL_CALL_START`,e.TOOL_CALL_ARGS=`TOOL_CALL_ARGS`,e.TOOL_CALL_END=`TOOL_CALL_END`,e.TOOL_CALL_CHUNK=`TOOL_CALL_CHUNK`,e.TOOL_CALL_RESULT=`TOOL_CALL_RESULT`,e.THINKING_START=`THINKING_START`,e.THINKING_END=`THINKING_END`,e.THINKING_TEXT_MESSAGE_START=`THINKING_TEXT_MESSAGE_START`,e.THINKING_TEXT_MESSAGE_CONTENT=`THINKING_TEXT_MESSAGE_CONTENT`,e.THINKING_TEXT_MESSAGE_END=`THINKING_TEXT_MESSAGE_END`,e.STATE_SNAPSHOT=`STATE_SNAPSHOT`,e.STATE_DELTA=`STATE_DELTA`,e.MESSAGES_SNAPSHOT=`MESSAGES_SNAPSHOT`,e.ACTIVITY_SNAPSHOT=`ACTIVITY_SNAPSHOT`,e.ACTIVITY_DELTA=`ACTIVITY_DELTA`,e.RAW=`RAW`,e.CUSTOM=`CUSTOM`,e.RUN_STARTED=`RUN_STARTED`,e.RUN_FINISHED=`RUN_FINISHED`,e.RUN_ERROR=`RUN_ERROR`,e.STEP_STARTED=`STEP_STARTED`,e.STEP_FINISHED=`STEP_FINISHED`,e.REASONING_START=`REASONING_START`,e.REASONING_MESSAGE_START=`REASONING_MESSAGE_START`,e.REASONING_MESSAGE_CONTENT=`REASONING_MESSAGE_CONTENT`,e.REASONING_MESSAGE_END=`REASONING_MESSAGE_END`,e.REASONING_MESSAGE_CHUNK=`REASONING_MESSAGE_CHUNK`,e.REASONING_END=`REASONING_END`,e.REASONING_ENCRYPTED_VALUE=`REASONING_ENCRYPTED_VALUE`,e}({}),Fm=e.object({type:e.enum([`query`,`mutation`,`subscription`]),id:e.string(),name:e.string(),description:e.string(),inputSchema:e.unknown(),outputSchema:e.unknown(),outputSample:e.unknown()}),Im=sm({name:`getCapabilities`,description:`Get the APIs available to the generated Rough feature`,inputSchema:e.object({}),outputSchema:e.array(Fm)}),Lm=sm({name:`startBuild`,description:`Start a Rough feature build`,inputSchema:e.object({prompt:e.string().min(1)}),outputSchema:e.object({spriteBuildId:e.string().min(1)})}),Rm=e=>{let{content:t}=e;return t===null?``:typeof t==`string`?t:t.filter(e=>e.type===`text`).map(e=>e.content??``).join(`
10
+ `,e.causedBy)):e instanceof Zl?this.#g.error?.(e):this.#g.info?.(`${t} threw:
11
+ `,e),!1}finally{this.#i!==n&&(this.#i=n,this.onOnlineChange?.(n),n&&this.recoverMutations())}}async#j(e,t,n,r=gf,i=gf){let{clientID:a}=this,o=0,s;n=n.withContext(t);do{let c=sf(a),l=n.withContext(`requestID`,c),{httpRequestInfo:u,result:d}=await e(c,l);if(s=d,!u)return{result:d,authFailure:!1};let{errorMessage:f,httpStatusCode:p}=u;if((f||p!==200)&&l.error?.(`Got a non 200 response doing ${t}: ${p}`+(f?`: ${f}`:``)),p!==ql)return{result:d,authFailure:!1};if(!this.getAuth)return{result:d,authFailure:!0};let m;try{await r(),m=await this.getAuth()}finally{await i()}if(m==null)return{result:d,authFailure:!0};this.auth=m,o++}while(o<lf);return n.info?.(`Tried to reauthenticate too many times`),{result:s,authFailure:!0}}#M(){return this.isClientGroupDisabled||this.pushURL===``&&xc(this.pusher)}async#N(){if(this.#M())return!0;await this.#o;let e=await this.#s,{clientID:t}=this,n=await this.#c;return this.#A(async()=>{let{result:r}=await this.#j(async(r,i)=>{try{this.#U(1,0);let a=await Tu(r,this.memdag,i,e,n,t,this.pusher,this.schemaVersion,bu);return{result:a,httpRequestInfo:a?.httpRequestInfo}}finally{this.#U(-1,0)}},`push`,this.#g);if(r===void 0)return!0;let{response:i,httpRequestInfo:a}=r;return ac(i)?this.#P(i):ic(i)&&await this.#L(),a.httpStatusCode===200},`Push`)}#P(e){let t={type:e.error};e.versionType&&(t.versionType=e.versionType),this.#R(t)}push({now:e=!1}={}){return xf(this.#p.send(e))}pull({now:e=!1}={}){return xf(this.#f.send(e))}async poke(e){await this.#o;let{clientID:t}=this,n=sf(t),r=this.#g.withContext(`handlePullResponse`).withContext(`requestID`,n),{pullResponse:i}=e;if(ac(i)){this.#P(i);return}if(ic(i)){await this.#L();return}let a=await fu(r,this.memdag,_i(e.baseCookie),i,t,7);switch(a.type){case 0:await this.maybeEndPull(a.syncHead,n);break;case 2:throw Error(`unexpected base cookie for poke: `+JSON.stringify(e))}}async beginPull(){await this.#o;let e=await this.profileID,{clientID:t}=this,n=await this.#c,{result:{beginPullResponse:r,requestID:i}}=await this.#j(async(r,i)=>{let a=await cu(e,t,n,this.schemaVersion,this.puller,r,this.memdag,7,i);return{result:{beginPullResponse:a,requestID:r},httpRequestInfo:a.httpRequestInfo}},`pull`,this.#g,()=>this.#U(0,-1),()=>this.#U(0,1)),{pullResponse:a}=r;ac(a)?this.#P(a):ic(r.pullResponse)&&await this.#L();let{syncHead:o,httpRequestInfo:s}=r;return{requestID:i,syncHead:o,ok:s.httpStatusCode===200}}async persist(){A(!this.#v),this.#v=!0;try{let{clientID:e}=this;if(await this.#o,this.#r)return;try{await jd(this.#g,e,this.memdag,this.perdag,this.#l,()=>this.closed,7)}catch(t){if(t instanceof ol)this.#I(e);else if(this.#r)this.#g.debug?.(`Exception persisting during close`,t);else throw t}}finally{this.#v=!1}let{clientID:e}=this,t=await this.#c;A(t),this.#C({clientID:e,clientGroupID:t})}async refresh(){await this.#o;let{clientID:e}=this;if(this.#r)return;let t;try{t=await Ld(this.#g,this.memdag,this.perdag,e,this.#l,this.subscriptions,()=>this.closed,7)}catch(t){if(t instanceof ol)this.#I(e);else if(this.#r)this.#g.debug?.(`Exception refreshing during close`,t);else throw t}t!==void 0&&await this.subscriptions.fire(t)}#F(){this.onClientStateNotFound?.()}#I(e){this.#g.error?.(`Client state not found on client, clientID: ${e}`),this.#F()}async#L(){let e=await this.#c;this.#g.error?.(`Client state not found on server, clientGroupID: ${e}`),await this.disableClientGroup(),this.#F()}async disableClientGroup(){let e=await this.#c;A(e),this.isClientGroupDisabled=!0,await z(this.perdag,t=>Bc(e,t))}#R(e){this.#g.debug?.(`Update needed, reason: ${e}`),this.onUpdateNeeded?.(e)}async#z(){this.#y&&await this.#H(`persist`,this.#S)}async#B(e){this.#g.debug?.(`Handling persist`,e);let t=await this.#c;e.clientGroupID===t&&this.#V()}async#V(){this.#b&&await this.#H(`refresh from storage`,this.#w)}async#H(e,t){try{await t.schedule()}catch(t){t instanceof pr?this.#g.debug?.(`Scheduled ${e} did not complete before close.`):this.#g.error?.(`Error during ${e}`,t)}}#U(e,t){this.#u+=e,this.#d+=t;let n=e+t,r=this.#u+this.#d;if(n===1&&r===1||r===0){let e=r>0;Promise.resolve().then(()=>this.onSync?.(e))}}subscribe(e,t){typeof t==`function`&&(t={onData:t});let{onData:n,onError:r,onDone:i,isEqual:a}=t;return this.subscriptions.add(new Gd(e,n,r,i,a))}experimentalWatch(e,t){return this.subscriptions.add(new Kd(e,t))}query(e){return this.#W(e)}get cookie(){return this.#o.then(()=>R(this.memdag,async e=>{let t=await e.getHead(I);if(!t)throw Error(`Internal no main head found`);let n=(await Ta(t,e)).meta.cookieJSON;return ri(n),n}))}#W=async e=>{await this.#o;let{clientID:t}=this;return R(this.memdag,async n=>{try{let r=await fs(n,7);return await e(new As(t,r,this.#g))}catch(e){throw await this.#J(e)}})};#G(e,t){return this.#l[e]=t,n=>this.#q(e,t,n,performance.now())}#K(e){let t=Object.create(null);for(let n in e)t[n]=this.#G(n,e[n]);return t}async#q(e,t,n,r){let i=_i(n??null);this.subscriptions.hasPendingSubscriptionRuns&&await Promise.resolve(),await this.#o;let{clientID:a}=this;return Uc(this.memdag,async o=>{try{let s=await qs(await ea(I,o),e,i,null,o,r,a,7),c=await t(new Ps(a,await s.getMutationID(),`initial`,s,this.#g),n);xs(s);let l=await s.getMutationID(),u=await s.commitWithDiffs(I,this.subscriptions);return this.lastMutationID=l,this.#p.send(!1).catch(()=>{}),await this.subscriptions.fire(u),this.#z(),c}catch(e){throw await this.#J(e)}})}async#J(e){return e instanceof Qi&&await this.#D()?new ol(this.clientID):e}recoverMutations(e){return this.#e.recoverMutations(e,this.#o,this.perdag,this.#n,this.#h,this.#t.create)}experimentalPendingMutations(){return R(this.memdag,qu)}},bf=new Map;async function xf(e){let t=await e;if(t)throw t.error}function Sf(){typeof location<`u`&&location.reload()}function Cf(e){let{name:t,clientMaxAgeMs:n}=e;if(typeof t!=`string`||!t)throw TypeError(`name is required and must be non-empty`);if(n!==void 0){let e=Math.max(Zu,Td);if(typeof n!=`number`||n<=e)throw TypeError(`clientAgeMaxMs must be a number larger than ${e}ms`)}}var wf={PENDING:`PENDING`,IN_PROGRESS:`IN_PROGRESS`,READY:`READY`,ERROR:`ERROR`,CANCELED:`CANCELED`},Tf=async(e,t)=>{let{tx:n,sessionPersonId:r}=e,{spriteId:i,spriteBuildId:a,prompt:o,name:s,surfaceId:c}=t,l=w.sprite.encode(i);if(await n.get(l))return Error(`Sprite "${i}" already exists`);let u=w.spriteBuild.encode(a);if(await n.get(u))return Error(`SpriteBuild "${a}" already exists`);let d={name:s?.trim().length?s:``,surfaceId:c,ownedByPersonId:r};await n.set(l,d);let f={spriteId:i,parentSpriteBuildId:null,prompt:o,status:wf.PENDING,cancelRequestedAt:null,artifactUrl:null,startedAt:null,stoppedAt:null,error:null,reasoningSummary:null,publishedAt:null,createdByPersonId:r};await n.set(u,f)},Ef=async(e,t)=>{let{tx:n,sessionPersonId:r}=e,{spriteId:i,name:a,surfaceId:o}=t,s=w.sprite.encode(i);if(await n.get(s))return Error(`Sprite "${i}" already exists`);let c={name:a?.trim().length?a:``,surfaceId:o,ownedByPersonId:r};await n.set(s,c)},Df=async()=>{},Of=async(e,t)=>{let{tx:n,actionedAt:r}=e,{spriteBuildId:i}=t,a=w.spriteBuild.encode(i),o=await n.get(a);if(!o)return Error(`Could not find that build.`);o.status!==wf.PENDING&&o.status!==wf.IN_PROGRESS||o.cancelRequestedAt!==null||await n.set(a,{...o,cancelRequestedAt:r})},kf=async(e,t)=>{let{tx:n,sessionPersonId:r}=e,{spriteBuildId:i,spriteId:a,parentSpriteBuildId:o,prompt:s}=t,c=w.spriteBuild.encode(i);if(await n.get(c))return Error(`SpriteBuild "${i}" already exists`);let l={spriteId:a,parentSpriteBuildId:o,prompt:s,status:wf.PENDING,cancelRequestedAt:null,artifactUrl:null,startedAt:null,stoppedAt:null,error:null,reasoningSummary:null,publishedAt:null,createdByPersonId:r};await n.set(c,l)},Af=async(e,t)=>{let{tx:n,sessionPersonId:r}=e,{spriteBuildId:i,spriteId:a,parentSpriteBuildId:o,prompt:s}=t,c=w.spriteBuild.encode(i);if(await n.get(c))return Error(`SpriteBuild "${i}" already exists`);let l={spriteId:a,parentSpriteBuildId:o??null,prompt:s,status:wf.PENDING,cancelRequestedAt:null,artifactUrl:null,startedAt:null,stoppedAt:null,error:null,reasoningSummary:null,publishedAt:null,createdByPersonId:r};await n.set(c,l)},jf=async(e,t)=>{let{tx:n,actionedAt:r}=e,{spriteBuildId:i}=t,a=w.spriteBuild.encode(i),o=await n.get(a);if(!o)return Error(`Could not find that build.`);if(o.status!==wf.READY)return Error(`Only ready builds can be published.`);await n.set(a,{...o,publishedAt:r})},Mf={surface_upsert_v1:async(e,t)=>{let{tx:n}=e,{surfaceId:r,key:i,name:a,description:o}=t,s={key:i,name:a,description:o};for await(let[e,t]of n.scan({prefix:w.surface.prefix()}).entries())if(t.key===i){await n.set(e,s);return}await n.set(w.surface.encode(r),s)},project_ping_v1:Df,sprite_create_v2:Ef,spriteBuild_create_v2:Af,spriteBuild_cancel_v1:Of,spriteBuild_publish_v2:async(e,t)=>{let{tx:n,actionedAt:r}=e,{spriteBuildId:i}=t,a=w.spriteBuild.encode(i),o=await n.get(a);if(!o)return Error(`Could not find that build.`);if(o.status!==wf.READY)return Error(`Only ready builds can be published.`);await n.set(a,{...o,publishedAt:r})}},Nf={sprite_create_v1:Tf,spriteBuild_create_v1:kf,spriteBuild_publish_v1:jf},Pf={...Mf,...Nf};async function Ff(e,t,{concurrency:n=1/0,stopOnError:r=!0,signal:i}={}){return new Promise((a,o)=>{if(e[Symbol.iterator]===void 0&&e[Symbol.asyncIterator]===void 0)throw TypeError(`Expected \`input\` to be either an \`Iterable\` or \`AsyncIterable\`, got (${typeof e})`);if(typeof t!=`function`)throw TypeError(`Mapper function is required`);if(!(Number.isSafeInteger(n)&&n>=1||n===1/0))throw TypeError(`Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${n}\` (${typeof n})`);let s=[],c=[],l=new Map,u=!1,d=!1,f=!1,p=0,m=0,h=e[Symbol.iterator]===void 0?e[Symbol.asyncIterator]():e[Symbol.iterator](),g=()=>{y(i.reason)},_=()=>{i?.removeEventListener(`abort`,g)},v=e=>{a(e),_()},y=e=>{u=!0,d=!0,o(e),_()};if(i){if(i.aborted){y(i.reason);return}i.addEventListener(`abort`,g,{once:!0})}let b=async()=>{if(d)return;let e=await h.next(),n=m;if(m++,e.done){if(f=!0,p===0&&!d){if(!r&&c.length>0){y(AggregateError(c));return}if(d=!0,l.size===0){v(s);return}let e=[];for(let[t,n]of s.entries())l.get(t)!==If&&e.push(n);v(e)}return}p++,(async()=>{try{let r=await e.value;if(d)return;let i=await t(r,n);i===If&&l.set(n,i),s[n]=i,p--,await b()}catch(e){if(r)y(e);else{c.push(e),p--;try{await b()}catch(e){y(e)}}}})()};(async()=>{for(let e=0;e<n;e++){try{await b()}catch(e){y(e);break}if(f||u)break}})()})}var If=Symbol(`skip`),Lf={concurrency:5,stopOnError:!1},Rf=async(e,r,i=Lf)=>{let{stopOnError:a}=i;return n(async()=>Ff(e,async e=>{let n=await t(async()=>r(e));if(a&&n instanceof Error)throw n;return n},i))},zf=async(e,t,n)=>{let r=await Rf(Object.entries(e),async([e,n])=>[e,await t(n,e)],n);return r instanceof Error?r:Object.fromEntries(r)},Bf=async(e,t)=>zf(t,async t=>{let n=t;return async(t,r)=>{let{context:i,...a}=r,o={...e,tx:t,actionedAt:i?.actionedAt??Date.now(),sessionPersonId:i?.sessionPersonId??e.sessionPersonId},s=await n(o,a);if(s instanceof Error)throw s;return s}}),Vf=`2026.08.20/1`,Hf=async e=>{let{name:t,pushURL:n,pullURL:r,auth:i,getAuth:a,pullInterval:o,sessionPersonId:s}=e;if(!t)return Error(`Replicache name is required`);let c=new Xl({schemaVersion:Vf,name:t,pushURL:n,pullURL:r,auth:i,pullInterval:o,mutators:await Bf({sessionPersonId:s},Pf)});return c.getAuth=a,c},Uf=class{constructor(e,t){if(this._retries=0,!Number.isInteger(e)||e<0)throw Error(`Base must be a positive integer or zero`);if(t!==void 0&&(!Number.isInteger(t)||t<0))throw Error(`ExpMax must be undefined, a positive integer, or zero`);this.base=e,this.expMax=t,this.i=0}get retries(){return this._retries}get current(){return this.base*2**this.i}next(){return this._retries++,this.i=this.expMax===void 0?this.i+1:Math.min(this.i+1,this.expMax),this.current}reset(){this._retries=0,this.i=0}},B={open:`open`,close:`close`,error:`error`,message:`message`,retry:`retry`,reconnect:`reconnect`},Wf=class{constructor(e,t,n){this._closedByUser=!1,this.handleOpenEvent=e=>this.handleEvent(B.open,e),this.handleErrorEvent=e=>this.handleEvent(B.error,e),this.handleCloseEvent=e=>this.handleEvent(B.close,e),this.handleMessageEvent=e=>this.handleEvent(B.message,e),this._urlProvider=e,this._protocols=t,this._options={buffer:n?.buffer,retry:{maxRetries:n?.retry?.maxRetries,instantReconnect:n?.retry?.instantReconnect,backoff:n?.retry?.backoff},listeners:{open:[...n?.listeners?.open??[]],close:[...n?.listeners?.close??[]],error:[...n?.listeners?.error??[]],message:[...n?.listeners?.message??[]],retry:[...n?.listeners?.retry??[]],reconnect:[...n?.listeners?.reconnect??[]]}},this._underlyingWebsocket=this.tryConnect()}get url(){return this._url}get protocols(){return this._protocols}get buffer(){return this._options.buffer}get maxRetries(){return this._options.retry.maxRetries}get instantReconnect(){return this._options.retry.instantReconnect}get backoff(){return this._options.retry.backoff}get closedByUser(){return this._closedByUser}get lastConnection(){return this._lastConnection}get underlyingWebsocket(){return this._underlyingWebsocket}get readyState(){return this._underlyingWebsocket.readyState}get bufferedAmount(){return this._underlyingWebsocket.bufferedAmount}get extensions(){return this._underlyingWebsocket.extensions}get binaryType(){return this._underlyingWebsocket.binaryType}set binaryType(e){this._underlyingWebsocket.binaryType=e}send(e){this.closedByUser||(this._underlyingWebsocket.readyState===this._underlyingWebsocket.OPEN?this._underlyingWebsocket.send(e):this.buffer!==void 0&&this.buffer.add(e))}close(e,t){this.cancelScheduledConnectionRetry(),this._closedByUser=!0,this._underlyingWebsocket.close(e,t)}addEventListener(e,t,n){this._options.listeners[e].push({listener:t,options:n})}removeEventListener(e,t,n){let r=e=>e.listener!==t||e.options!==n;this._options.listeners[e]=this._options.listeners[e].filter(r)}tryConnect(){return this._url=typeof this._urlProvider==`function`?this._urlProvider():this._urlProvider,this._underlyingWebsocket=new WebSocket(this._url,this.protocols),this._underlyingWebsocket.addEventListener(B.open,this.handleOpenEvent),this._underlyingWebsocket.addEventListener(B.close,this.handleCloseEvent),this._underlyingWebsocket.addEventListener(B.error,this.handleErrorEvent),this._underlyingWebsocket.addEventListener(B.message,this.handleMessageEvent),this._underlyingWebsocket}clearWebsocket(){this._underlyingWebsocket.removeEventListener(B.open,this.handleOpenEvent),this._underlyingWebsocket.removeEventListener(B.close,this.handleCloseEvent),this._underlyingWebsocket.removeEventListener(B.error,this.handleErrorEvent),this._underlyingWebsocket.removeEventListener(B.message,this.handleMessageEvent),this._underlyingWebsocket.close()}dispatchEvent(e,t){let n=this._options.listeners[e],r=[];n.forEach(({listener:e,options:n})=>{e(this,t),(n===void 0||n.once===void 0||!n.once)&&r.push({listener:e,options:n})}),this._options.listeners[e]=r}handleEvent(e,t){switch(e){case B.close:this.dispatchEvent(e,t),this.scheduleConnectionRetryIfNeeded();break;case B.open:if(this.backoff!==void 0&&this._lastConnection!==void 0){let e={retries:this.backoff.retries,lastConnection:new Date(this._lastConnection)},t=new CustomEvent(B.reconnect,{detail:e});this.dispatchEvent(B.reconnect,t),this.backoff.reset()}this._lastConnection=new Date,this.dispatchEvent(e,t),this.sendBufferedData();break;case B.retry:this.dispatchEvent(e,t),this.clearWebsocket(),this.tryConnect();break;default:this.dispatchEvent(e,t)}}sendBufferedData(){if(this.buffer!==void 0)for(let e=this.buffer.read();e!==void 0;e=this.buffer.read())this.send(e)}scheduleConnectionRetryIfNeeded(){if(this.closedByUser||this.backoff===void 0)return;let e=e=>{let t=new CustomEvent(B.retry,{detail:e});this.handleEvent(B.retry,t)},t={backoff:this._options.retry.instantReconnect===!0?0:this.backoff.next(),retries:this._options.retry.instantReconnect===!0?0:this.backoff.retries,lastConnection:this._lastConnection};(this._options.retry.maxRetries===void 0||t.retries<=this._options.retry.maxRetries)&&(this.retryTimeout=globalThis.setTimeout(()=>e(t),t.backoff))}cancelScheduledConnectionRetry(){globalThis.clearTimeout(this.retryTimeout)}},Gf=class{constructor(e){this._url=e}get url(){return this._url}withProtocols(e){return this._protocols=e,this}get protocols(){return this._protocols}withMaxRetries(e){return this._options=Object.assign(Object.assign({},this._options),{retry:Object.assign(Object.assign({},this._options?.retry),{maxRetries:e})}),this}get maxRetries(){return this._options?.retry?.maxRetries}withInstantReconnect(e){return this._options=Object.assign(Object.assign({},this._options),{retry:Object.assign(Object.assign({},this._options?.retry),{instantReconnect:e})}),this}get instantReconnect(){return this._options?.retry?.instantReconnect}withBackoff(e){return this._options=Object.assign(Object.assign({},this._options),{retry:Object.assign(Object.assign({},this._options?.retry),{backoff:e})}),this}get backoff(){return this._options?.retry?.backoff}withBuffer(e){return this._options=Object.assign(Object.assign({},this._options),{buffer:e}),this}get buffer(){return this._options?.buffer}onOpen(e,t){return this.addListener(B.open,e,t),this}onClose(e,t){return this.addListener(B.close,e,t),this}onError(e,t){return this.addListener(B.error,e,t),this}onMessage(e,t){return this.addListener(B.message,e,t),this}onRetry(e,t){return this.addListener(B.retry,e,t),this}onReconnect(e,t){return this.addListener(B.reconnect,e,t),this}build(){return new Wf(this._url,this._protocols,this._options)}addListener(e,t,n){return this._options=Object.assign(Object.assign({},this._options),{listeners:{open:this._options?.listeners?.open??[],close:this._options?.listeners?.close??[],error:this._options?.listeners?.error??[],message:this._options?.listeners?.message??[],retry:this._options?.listeners?.retry??[],reconnect:this._options?.listeners?.reconnect??[],[e]:[...this._options?.listeners?.[e]??[],{listener:t,options:n}]}}),this}},Kf=e.object({type:e.literal(`poke`)}).strict(),qf=e=>{console.warn(`[Rough poke] ${e}`)},Jf=e=>{let{getToken:t,onPoke:n,url:r}=e,i=!1,a=0;try{let e=new Gf(r).withBackoff(new Uf(1e3,7)).build(),o=()=>{let n=++a;t().then(t=>{i||n!==a||e.readyState!==1||e.send(JSON.stringify({type:`authenticate`,token:t}))}).catch(()=>{qf(`Failed to get a session token`)})},s=(e,t)=>{if(typeof t.data!=`string`){qf(`Received an invalid server message`);return}let r;try{r=JSON.parse(t.data)}catch{qf(`Received malformed server JSON`);return}if(!Kf.safeParse(r).success){qf(`Received an invalid server message`);return}Promise.resolve(n()).catch(()=>{qf(`Failed to pull after a server poke`)})},c=()=>{qf(`Connection failed`)},l=()=>{i||qf(`Connection closed; reconnecting`)};return e.addEventListener(B.open,o),e.addEventListener(B.message,s),e.addEventListener(B.error,c),e.addEventListener(B.close,l),{close:()=>{i||(i=!0,e.removeEventListener(B.open,o),e.removeEventListener(B.message,s),e.removeEventListener(B.error,c),e.removeEventListener(B.close,l),e.close())}}}catch{return qf(`Failed to create connection`),{close:()=>{}}}};function Yf(e){let t=Error(e.message||e.error?.message||`An error occurred`),n=e.code??e.error?.code;return n!==void 0&&Object.assign(t,{code:n}),e.rawEvent!==void 0&&Object.assign(t,{rawEvent:e.rawEvent}),t}var Xf=new Uint32Array([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]);function Zf(e,t){return e>>>t|e<<32-t}function Qf(e){let t=new TextEncoder().encode(e),n=t.length*8,r=t.length+1,i=r+(56-r%64+64)%64+8,a=new Uint8Array(i);a.set(t),a[t.length]=128;let o=new DataView(a.buffer);o.setUint32(i-8,Math.floor(n/4294967296)),o.setUint32(i-4,n>>>0);let s=1779033703,c=3144134277,l=1013904242,u=2773480762,d=1359893119,f=2600822924,p=528734635,m=1541459225,h=new Uint32Array(64);for(let e=0;e<i;e+=64){for(let t=0;t<16;t++)h[t]=o.getUint32(e+t*4);for(let e=16;e<64;e++){let t=h[e-15]??0,n=h[e-2]??0,r=Zf(t,7)^Zf(t,18)^t>>>3,i=Zf(n,17)^Zf(n,19)^n>>>10;h[e]=(h[e-16]??0)+r+(h[e-7]??0)+i>>>0}let t=s,n=c,r=l,i=u,a=d,g=f,_=p,v=m;for(let e=0;e<64;e++){let o=Zf(a,6)^Zf(a,11)^Zf(a,25),s=a&g^~a&_,c=v+o+s+(Xf[e]??0)+(h[e]??0)>>>0,l=(Zf(t,2)^Zf(t,13)^Zf(t,22))+(t&n^t&r^n&r)>>>0;v=_,_=g,g=a,a=i+c>>>0,i=r,r=n,n=t,t=c+l>>>0}s=s+t>>>0,c=c+n>>>0,l=l+r>>>0,u=u+i>>>0,d=d+a>>>0,f=f+g>>>0,p=p+_>>>0,m=m+v>>>0}let g=e=>(e>>>0).toString(16).padStart(8,`0`);return g(s)+g(c)+g(l)+g(u)+g(d)+g(f)+g(p)+g(m)}function $f(e){return`sha256:${Qf(e)}`}function ep(e,t){if(e===null)return`null`;if(typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return JSON.stringify(e);if(typeof e!=`object`)throw TypeError(`Interrupt values must be JSON-compatible.`);if(t.has(e))throw TypeError(`Interrupt values must not cycle.`);if(!Array.isArray(e)&&Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw TypeError(`Interrupt values must use plain JSON objects.`);t.add(e);let n;if(Array.isArray(e)){let r=[];for(let n=0;n<e.length;n++)r.push(ep(e[n],t));n=`[${r.join(`,`)}]`}else{let r=e;n=`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${ep(r[e],t)}`).join(`,`)}}`}return t.delete(e),n}function tp(e){return ep(e,new WeakSet)}function np(e,t=$f){if(typeof e!=`string`)throw TypeError(`Interrupt digests require canonical JSON text.`);return t(e)}function rp(e){typeof e!=`object`||!e||Object.isFrozen(e)||(Object.values(e).forEach(rp),Object.freeze(e))}function V(e){let t=JSON.parse(tp(e));return rp(t),t}function ip(e){let t=V([...e].sort((e,t)=>e.interruptId.localeCompare(t.interruptId))),n=tp(t);return Object.freeze({resolutions:t,canonicalResolutions:n,fingerprint:np(n)})}function ap(e){let t={};for(let[n,r]of Object.entries(e))n!==`$schema`&&(t[n]=r);return t}function op(e){return(typeof e==`object`||typeof e==`function`)&&e!==null}function sp(e){if(!op(e)||!(`~standard`in e))return!1;let t=e[`~standard`];return typeof t!=`object`||!t||!(`version`in t)||t.version!==1||!(`jsonSchema`in t)||typeof t.jsonSchema!=`object`||t.jsonSchema===null||!(`input`in t.jsonSchema)?!1:typeof t.jsonSchema.input==`function`}function cp(e){return op(e)&&`~standard`in e&&typeof e[`~standard`]==`object`&&e[`~standard`]!==null&&`version`in e[`~standard`]&&e[`~standard`].version===1&&`validate`in e[`~standard`]&&typeof e[`~standard`].validate==`function`}function lp(e){return Object.keys(e).length>0?e:void 0}function up(e,t=[]){let n={...e},r={};if(n.type===`object`&&n.properties){let e={...n.properties},i=Object.keys(e),a={};for(let n of i){let r=e[n];if(!r)continue;let i=!t.includes(n),o=!1,s;if(r.type===`object`&&r.properties){let t=up(r,r.required||[]);e[n]=i?{...t.schema,type:[`object`,`null`]}:t.schema,o=i,s=t.nullWidening}else if(r.type===`array`&&r.items){let t=Array.isArray(r.items)?r.items[0]:r.items,a=t?up(t,t.required||[]):void 0;e[n]={...r,items:a?a.schema:r.items,...i?{type:[`array`,`null`]}:{}},o=i,s=a?.nullWidening?{items:a.nullWidening}:void 0}else i&&(r.type&&!Array.isArray(r.type)?(e[n]={...r,type:[r.type,`null`]},o=!0):Array.isArray(r.type)&&!r.type.includes(`null`)&&(e[n]={...r,type:[...r.type,`null`]},o=!0));(o||s)&&(a[n]={...s??{},...o?{widened:!0}:{}})}n.properties=e,n.required=i,n.additionalProperties=!1,Object.keys(a).length>0&&(r.properties=a)}if(n.type===`array`&&n.items){let e=Array.isArray(n.items)?n.items[0]:n.items;if(e){let t=up(e,e.required||[]);n.items=t.schema,t.nullWidening&&(r.items=t.nullWidening)}}return{schema:n,nullWidening:lp(r)}}function dp(e){if(sp(e)){let t=ap(e[`~standard`].jsonSchema.input({target:`draft-07`}));return`properties`in t&&!t.type&&(t.type=`object`),t.type===`object`&&!(`properties`in t)&&(t.properties={}),t.type===`object`&&!(`required`in t)&&(t.required=[]),t}if(cp(e))throw Error("Schema is a Standard Schema validator but does not expose a JSON Schema converter on `~standard.jsonSchema`. Use Zod v4.2+, ArkType v2.1.28+, or wrap a Valibot schema with `toStandardJsonSchema()` from `@valibot/to-json-schema` before passing it as `outputSchema`.");return typeof e==`object`?ap(e):e}function fp(e,t={}){if(!e)return;let{forStructuredOutput:n=!1}=t;if(!n&&!sp(e)&&!cp(e))return e;let r=dp(e);return!r||typeof r!=`object`||!n?r:up(r,r.required||[]).schema}var pp=class extends Error{name=`StandardSchemaValidationError`;issues;constructor(e){super(`Validation failed: ${e.map(e=>e.message||`Validation failed`).join(`, `)}`),this.issues=e}};function mp(e,t){if(!cp(e))return t;let n=e[`~standard`].validate(t);if(n instanceof Promise)throw Error(`Schema validation returned a Promise. Use validateWithStandardSchema for async validation.`);if(!n.issues)return n.value;throw new pp(n.issues)}var hp=new Set([`$schema`,`$id`,`$ref`,`$defs`,`type`,`properties`,`required`,`additionalProperties`,`items`,`oneOf`,`anyOf`,`allOf`,`enum`,`const`,`format`,`minimum`,`maximum`,`minLength`,`maxLength`,`pattern`]);function gp(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null)}function _p(e){return gp(e)&&Object.keys(e).some(e=>hp.has(e))}function vp(e){return cp(e)||sp(e)||_p(e)}function yp(e){if(!gp(e))return!1;let t=Object.keys(e);return t.length>0&&t.every(e=>e===`approve`||e===`reject`)&&t.every(t=>vp(e[t]))}function bp(e){let t={};for(let[n,r]of Object.entries(e))t[n]=r;return t}function xp(e){if(cp(e)){let t=sp(e)?bp(e[`~standard`].jsonSchema.input({target:`draft-2020-12`})):void 0;return{source:e,validator:e,...t!==void 0&&{jsonSchema:t}}}if(_p(e))return{source:e,jsonSchema:e};throw TypeError(`Expected a supported SchemaInput.`)}function Sp(e){let t={approved:{const:e.approved}},n=[`approved`];return e.approved&&e.inputSchema&&(t.editedArgs=e.inputSchema.jsonSchema??{}),e.payload&&(t.payload=e.payload.jsonSchema??{},n.push(`payload`)),{type:`object`,properties:t,required:n,additionalProperties:!1}}function Cp(e,t){let n=t===void 0?null:xp(t),r=null,i=null;if(e!==void 0){if(cp(e)||_p(e))r=xp(e),i=r;else if(yp(e))r=e.approve===void 0?null:xp(e.approve),i=e.reject===void 0?null:xp(e.reject);else throw TypeError(`approvalSchema must be a SchemaInput or a nonempty map containing approve or reject.`)}let a={oneOf:[Sp({approved:!0,payload:r,inputSchema:n}),Sp({approved:!1,payload:i,inputSchema:null})]},o=tp(a),s=tp({approve:r?.jsonSchema??null,reject:i?.jsonSchema??null});return{branches:{approve:r,reject:i},responseSchema:a,responseSchemaHash:np(o),approvalSchemaHash:np(s)}}function wp(e){return np(e===void 0?`undefined`:tp(xp(e).jsonSchema??{standardValidator:`unserialized`}))}var Tp=`tanstack:interruptBinding`,Ep=Tp;function Dp(e){return e&&typeof e==`object`?e:null}function Op(e,t){return typeof e[t]==`string`?e[t]:void 0}function kp(e){let t=e.v;return t===void 0||t===1}function Ap(e){let t=Dp(e.metadata),n=t?Dp(t[Ep]):null;if(!n||Op(n,`interruptId`)!==e.id||!kp(n))return;let r=Op(n,`kind`),i=Op(n,`interruptId`),a=Op(n,`responseSchemaHash`),o=Op(n,`expiresAt`);if(!i||a===``||o!==void 0&&!Number.isFinite(Date.parse(o)))return;if(r===`generic`){let e=Op(n,`definitionId`),t=Op(n,`key`),s=n.batchIndex,c=Op(n,`payloadSchemaHash`);return(e!==void 0||t!==void 0||s!==void 0||c!==void 0)&&(!e||!t||typeof s!=`number`||!Number.isInteger(s)||s<0)?void 0:{v:1,kind:r,interruptId:i,...a?{responseSchemaHash:a}:{},...o?{expiresAt:o}:{},...e?{definitionId:e}:{},...t?{key:t}:{},...typeof s==`number`?{batchIndex:s}:{},...c?{payloadSchemaHash:c}:{}}}if(!a)return;let s=Op(n,`toolName`),c=Op(n,`toolCallId`);if(!(!s||!c)){if(r===`client-tool-execution`){let e=Op(n,`outputSchemaHash`);return e?{v:1,kind:r,interruptId:i,toolName:s,toolCallId:c,outputSchemaHash:e,responseSchemaHash:a,...o?{expiresAt:o}:{}}:void 0}if(r===`tool-approval`){let e=Op(n,`inputSchemaHash`),t=Op(n,`approvalSchemaHash`);return!e||!t?void 0:{v:1,kind:r,interruptId:i,toolName:s,toolCallId:c,originalArgs:n.originalArgs,inputSchemaHash:e,approvalSchemaHash:t,responseSchemaHash:a,...o?{expiresAt:o}:{}}}}}function jp(e){let t=Ap(e);if(!t)return;let n=Dp(e.metadata),r=n?Dp(n[Ep]):null;if(!r)return;let i=Op(r,`interruptedRunId`),a=r.generation;if(!(!i||typeof a!=`number`||!Number.isInteger(a)||a<0))return{...t,interruptedRunId:i,generation:a}}var Mp=`tanstack:interruptPayload`;function Np(e,t){if(!sp(e))throw TypeError(`${t} must be a Standard Schema with a JSON Schema converter.`);try{let t=e[`~standard`].jsonSchema.input({target:`draft-07`});if(t===void 0)throw TypeError(`The exported schema is undefined.`);if(typeof t==`function`)throw TypeError(`The exported schema must not be a function.`);if(Array.isArray(t)||!t||typeof t!=`object`||![Object.prototype,null].includes(Object.getPrototypeOf(t)))throw TypeError(`The exported schema must be a plain JSON object.`);let n={};for(let[e,r]of Object.entries(t))e!==`$schema`&&(n[e]=r);return{json:n,canonicalJson:tp(n)}}catch(e){throw TypeError(`${t} could not export compatible JSON Schema: ${e instanceof Error?e.message:String(e)}`)}}function Pp(e){return np(Np(e,`Interrupt schema`).canonicalJson)}var Fp=`tanstack:interruptContinuation`;function Ip(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Lp(e){return{[Fp]:e}}function Rp(e){let t=Ap(e);if(t?.kind!==`generic`||t.definitionId===void 0||t.key===void 0||t.batchIndex===void 0)return;let n=Ip(e.metadata)?e.metadata:void 0,r=n!==void 0&&Object.prototype.hasOwnProperty.call(n,`tanstack:interruptPayload`);return{v:1,definitionId:t.definitionId,key:t.key,batchIndex:t.batchIndex,reason:e.reason,message:e.message??``,...e.expiresAt===void 0?{}:{expiresAt:e.expiresAt},...t.responseSchemaHash===void 0?{}:{responseSchemaHash:t.responseSchemaHash},...t.payloadSchemaHash===void 0?{}:{payloadSchemaHash:t.payloadSchemaHash},...r?{payload:n[Mp]}:{}}}var zp=new Set([`text`,`image`,`audio`,`video`,`document`]);function Bp(e){if(typeof e!=`object`||!e)return!1;let t=e;if(typeof t.type!=`string`||!zp.has(t.type))return!1;if(t.type===`text`)return typeof t.content==`string`;let n=t.source;if(typeof n!=`object`||!n)return!1;let r=n;return typeof r.value==`string`?r.type===`data`?typeof r.mimeType==`string`:r.type===`url`:!1}function Vp(e){return Array.isArray(e)&&e.length>0&&e.every(Bp)}function Hp(e){return typeof e==`string`||Vp(e)?e:JSON.stringify(e)}function Up(e){let t=e?.metadata;return typeof t==`object`&&t&&t.providerExecuted===!0?t:null}function Wp(e){return Up(e)!==null}function Gp(e){return e.type===`text`||e.type===`image`||e.type===`audio`||e.type===`video`||e.type===`document`}function Kp(e){try{return JSON.stringify(e)??``}catch{return``}}function qp(e){return e.length===0?null:e.every(e=>e.type===`text`)?e.map(e=>e.content).join(``)||null:e}function Jp(e){return e===null?``:typeof e==`string`?e:e.filter(e=>e.type===`text`).map(e=>e.content).join(``)}function Yp(e){let t=new Set;for(let n of e)if(`parts`in n)for(let e of n.parts)e.type===`tool-result`&&t.add(e.toolCallId);let n=[];for(let r of e){if(`parts`in r){n.push(...Xp(r));continue}let e=r.role;if(!(e===`tool`&&r.toolCallId&&t.has(r.toolCallId))&&e!==`reasoning`&&e!==`activity`){if(e===`developer`){n.push({role:`system`,content:r.content});continue}n.push(r)}}return n}function Xp(e){return e.role===`system`?[]:e.role===`assistant`?em(e):[Zp(e)]}function Zp(e){let t=[];for(let n of e.parts)Gp(n)&&t.push(n);return{id:e.id,role:e.role,content:qp(t),...e.createdAt!==void 0&&{createdAt:e.createdAt}}}function Qp(){return{contentParts:[],toolCalls:[]}}function $p(e){return e.state===`input-complete`||e.state===`complete`||e.state===`approval-requested`||e.state===`approval-responded`||e.state===`error`||e.output!==void 0}function em(e){let t=[],n=Qp(),r=[],i=new Set;function a(){let i=qp(n.contentParts),a=i!==null,o=n.toolCalls.length>0,s=r.length>0;(a||o||s)&&(t.push({id:e.id,role:`assistant`,content:i,...o&&{toolCalls:n.toolCalls},...s&&{thinking:r},...n.structuredOutput&&{structuredOutput:n.structuredOutput},...e.createdAt!==void 0&&{createdAt:e.createdAt}}),r=[]),n=Qp()}for(let o of e.parts)switch(o.type){case`text`:case`image`:case`audio`:case`video`:case`document`:n.contentParts.push(o);break;case`tool-call`:$p(o)&&n.toolCalls.push({id:o.id,type:`function`,function:{name:o.name,arguments:o.arguments},...o.metadata!==void 0&&{metadata:o.metadata}});break;case`tool-result`:a(),(o.state===`complete`||o.state===`error`)&&!i.has(o.toolCallId)&&(t.push({id:e.id,role:`tool`,content:o.content,toolCallId:o.toolCallId,...e.createdAt!==void 0&&{createdAt:e.createdAt}}),i.add(o.toolCallId));break;case`thinking`:o.content&&(n.toolCalls.some(Wp)&&a(),r.push({content:o.content,...o.signature&&{signature:o.signature}}));break;case`structured-output`:if(o.status===`complete`){let e=o.raw===``?o.data===void 0?``:Kp(o.data):o.raw;e!==``&&(n.contentParts.push({type:`text`,content:e}),n.structuredOutput=o)}}a();for(let n of e.parts)if(n.type===`tool-call`&&(n.output!==void 0&&!i.has(n.id)&&(t.push({id:e.id,role:`tool`,content:Hp(n.output),toolCallId:n.id,...e.createdAt!==void 0&&{createdAt:e.createdAt}}),i.add(n.id)),n.output===void 0&&n.state===`approval-responded`&&n.approval?.approved!==void 0&&!i.has(n.id))){let r=n.approval.approved;t.push({id:e.id,role:`tool`,content:JSON.stringify({approved:r,...r&&{pendingExecution:!0},message:r?`User approved this action`:`User denied this action`}),toolCallId:n.id,...e.createdAt!==void 0&&{createdAt:e.createdAt}}),i.add(n.id)}return t.length===0&&t.push({id:e.id,role:`assistant`,content:null,...e.createdAt!==void 0&&{createdAt:e.createdAt}}),t}function tm(e,t){let n=[];if(e.role===`assistant`&&e.thinking?.length)for(let t of e.thinking)t.content&&n.push({type:`thinking`,content:t.content,...t.signature&&{signature:t.signature}});if(e.role===`assistant`&&e.structuredOutput)n.push(e.structuredOutput);else if(e.role===`tool`&&e.toolCallId)n.push({type:`tool-result`,toolCallId:e.toolCallId,content:Jp(e.content),state:`complete`});else if(Array.isArray(e.content))for(let t of e.content)n.push(t);else{let t=Jp(e.content);t&&n.push({type:`text`,content:t})}if(e.toolCalls&&e.toolCalls.length>0)for(let t of e.toolCalls){let e;try{e=JSON.parse(t.function.arguments)}catch{e=void 0}n.push({type:`tool-call`,id:t.id,name:t.function.name,arguments:t.function.arguments,state:`input-complete`,...e!==void 0&&{input:e},...t.metadata!==void 0&&{metadata:t.metadata}})}return{id:t||am(),role:e.role===`tool`?`assistant`:e.role,parts:n,...e.createdAt!==void 0&&{createdAt:e.createdAt}}}function nm(e){if(`parts`in e)return{...e,id:e.id||am()};let t=e.id||am();switch(e.role){case`user`:return{id:t,role:`user`,parts:rm(e.content)};case`assistant`:return tm({role:`assistant`,content:e.content??null,...e.toolCalls&&{toolCalls:e.toolCalls}},t);case`tool`:return tm({role:`tool`,content:e.content,toolCallId:e.toolCallId},t);case`system`:case`developer`:return{id:t,role:`system`,parts:e.content?[{type:`text`,content:e.content}]:[]};case`reasoning`:return{id:t,role:`assistant`,parts:e.content?[{type:`thinking`,content:e.content}]:[]};default:return{id:t,role:`assistant`,parts:[]}}}function rm(e){if(typeof e==`string`)return e?[{type:`text`,content:e}]:[];let t=[];for(let n of e)n.type===`text`?t.push({type:`text`,content:n.text}):n.type!==`binary`&&t.push(n);return t}function im(e,t){return`parts`in e?{...e,id:e.id||t(),createdAt:e.createdAt||new Date}:{...tm(e,t()),createdAt:e.createdAt??new Date}}function am(){return`msg-${Date.now()}-${Math.random().toString(36).substring(7)}`}function om(e){if(e.approvalSchema!==void 0&&e.needsApproval!==!0)throw TypeError(`approvalSchema requires needsApproval: true.`);let t=e.inputSchema,n=e.outputSchema,r=e.approvalSchema,i=e.needsApproval;return{__toolSide:`definition`,...e,inputSchema:t,outputSchema:n,approvalSchema:r,needsApproval:i,server(a){return{__toolSide:`server`,...e,inputSchema:t,outputSchema:n,approvalSchema:r,needsApproval:i,execute:a}},client(a){return{__toolSide:`client`,...e,inputSchema:t,outputSchema:n,approvalSchema:r,needsApproval:i,...a!==void 0&&{execute:a}}}}}var sm=y((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.ALL=e.COLLECTION=e.ATOM=e.SPECIAL=e.INF=e._INFINITY=e.INFINITY=e.NAN=e.BOOL=e.NULL=e.OBJ=e.ARR=e.NUM=e.STR=void 0,e.STR=1,e.NUM=2,e.ARR=4,e.OBJ=8,e.NULL=16,e.BOOL=32,e.NAN=64,e.INFINITY=128,e._INFINITY=256,e.INF=e.INFINITY|e._INFINITY,e.SPECIAL=e.NULL|e.BOOL|e.INF|e.NAN,e.ATOM=e.STR|e.NUM|e.SPECIAL,e.COLLECTION=e.ARR|e.OBJ,e.ALL=e.ATOM|e.COLLECTION,e.Allow={STR:e.STR,NUM:e.NUM,ARR:e.ARR,OBJ:e.OBJ,NULL:e.NULL,BOOL:e.BOOL,NAN:e.NAN,INFINITY:e.INFINITY,_INFINITY:e._INFINITY,INF:e.INF,SPECIAL:e.SPECIAL,ATOM:e.ATOM,COLLECTION:e.COLLECTION,ALL:e.ALL},e.default=e.Allow})),cm=y((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__exportStar||function(e,n){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(n,r)&&t(n,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.MalformedJSON=e.PartialJSON=e.parseJSON=e.parse=void 0;var r=sm();Object.defineProperty(e,"Allow",{enumerable:!0,get:function(){return r.Allow}}),n(sm(),e);var i=class extends Error{};e.PartialJSON=i;var a=class extends Error{};e.MalformedJSON=a;function o(e,t=r.Allow.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return s(e.trim(),t)}e.parseJSON=o;var s=(e,t)=>{let n=e.length,o=0,s=e=>{throw new i(`${e} at position ${o}`)},c=e=>{throw new a(`${e} at position ${o}`)},l=()=>(m(),o>=n&&s(`Unexpected end of input`),e[o]===`"`?u():e[o]===`{`?d():e[o]===`[`?f():e.substring(o,o+4)===`null`||r.Allow.NULL&t&&n-o<4&&`null`.startsWith(e.substring(o))?(o+=4,null):e.substring(o,o+4)===`true`||r.Allow.BOOL&t&&n-o<4&&`true`.startsWith(e.substring(o))?(o+=4,!0):e.substring(o,o+5)===`false`||r.Allow.BOOL&t&&n-o<5&&`false`.startsWith(e.substring(o))?(o+=5,!1):e.substring(o,o+8)===`Infinity`||r.Allow.INFINITY&t&&n-o<8&&`Infinity`.startsWith(e.substring(o))?(o+=8,1/0):e.substring(o,o+9)===`-Infinity`||r.Allow._INFINITY&t&&1<n-o&&n-o<9&&`-Infinity`.startsWith(e.substring(o))?(o+=9,-1/0):e.substring(o,o+3)===`NaN`||r.Allow.NAN&t&&n-o<3&&`NaN`.startsWith(e.substring(o))?(o+=3,NaN):p()),u=()=>{let i=o,a=!1;for(o++;o<n&&(e[o]!==`"`||a&&e[o-1]===`\\`);)a=e[o]===`\\`&&!a,o++;if(e.charAt(o)==`"`)try{return JSON.parse(e.substring(i,++o-Number(a)))}catch(e){c(String(e))}else if(r.Allow.STR&t)try{return JSON.parse(e.substring(i,o-Number(a))+`"`)}catch{return JSON.parse(e.substring(i,e.lastIndexOf(`\\`))+`"`)}s(`Unterminated string literal`)},d=()=>{o++,m();let i={};try{for(;e[o]!==`}`;){if(m(),o>=n&&r.Allow.OBJ&t)return i;let a=u();m(),o++;try{i[a]=l()}catch(e){if(r.Allow.OBJ&t)return i;throw e}m(),e[o]===`,`&&o++}}catch{if(r.Allow.OBJ&t)return i;s(`Expected '}' at end of object`)}return o++,i},f=()=>{o++;let n=[];try{for(;e[o]!==`]`;)n.push(l()),m(),e[o]===`,`&&o++}catch{if(r.Allow.ARR&t)return n;s(`Expected ']' at end of array`)}return o++,n},p=()=>{if(o===0){e===`-`&&c(`Not sure what '-' is`);try{return JSON.parse(e)}catch(n){if(r.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf(`e`)))}catch{}c(String(n))}}let i=o;for(e[o]===`-`&&o++;e[o]&&`,]}`.indexOf(e[o])===-1;)o++;o==n&&!(r.Allow.NUM&t)&&s(`Unterminated number literal`);try{return JSON.parse(e.substring(i,o))}catch{e.substring(i,o)===`-`&&s(`Not sure what '-' is`);try{return JSON.parse(e.substring(i,e.lastIndexOf(`e`)))}catch(e){c(String(e))}}},m=()=>{for(;o<n&&`
12
+ \r `.includes(e[o]);)o++};return l()};e.parse=o}))(),lm=new class{parse(e){if(!(!e||e.trim()===``))try{return(0,cm.parse)(e)}catch{return}}};function um(e){return lm.parse(e)}var dm=class{shouldEmit(e,t){return!0}};function fm(e,t,n){return e.map(e=>{if(e.id!==t)return e;let r=[...e.parts],i=r.length>0?r[r.length-1]:null;return i&&i.type===`text`?r[r.length-1]={type:`text`,content:n}:r.push({type:`text`,content:n}),{...e,parts:r}})}function pm(e,t,n){return e.map(e=>{if(e.id!==t)return e;let r=[...e.parts],i=r.find(e=>e.type===`tool-call`&&e.id===n.id),a=n.metadata??i?.metadata,o=n.input??i?.input,s={type:`tool-call`,id:n.id,name:n.name,arguments:n.arguments,state:n.state,...i?.approval&&{approval:{...i.approval}},...i?.output!==void 0&&{output:i.output},...o!==void 0&&{input:o},...a!==void 0&&{metadata:a}};return i?r[r.indexOf(i)]=s:r.push(s),{...e,parts:r}})}function mm(e,t,n,r,i,a){return e.map(e=>{if(e.id!==t)return e;let o=[...e.parts],s=o.findIndex(e=>e.type===`tool-result`&&e.toolCallId===n),c={type:`tool-result`,toolCallId:n,content:r,state:i,...a&&{error:a}};return s>=0?o[s]=c:o.push(c),{...e,parts:o}})}function hm(e,t,n,r){return e.map(e=>{if(e.id!==t)return e;let i=[...e.parts],a=i.find(e=>e.type===`tool-call`&&e.id===n);if(a){let e=i.indexOf(a);i[e]={...a,state:`approval-requested`,approval:{id:r,needsApproval:!0}}}return{...e,parts:i}})}function gm(e,t,n,r,i){return e.map(e=>{let a=[...e.parts],o=a.find(e=>e.type===`tool-call`&&e.id===t);if(o){let e=a.indexOf(o);a[e]={...o,output:i?{error:i}:n,state:r??(i?`error`:`complete`)}}return{...e,parts:a}})}function _m(e,t,n){return e.map(e=>{let r=[...e.parts],i=r.find(e=>e.type===`tool-call`&&e.approval?.id===t);if(i&&i.approval){let e=r.indexOf(i);r[e]={...i,approval:{...i.approval,approved:n},state:`approval-responded`}}return{...e,parts:r}})}function vm(e,t,n){return e.map(e=>{if(e.id!==t)return e;let r=[...e.parts],i=r.findIndex(e=>e.type===`structured-output`),a=i>=0?r[i]:null,o=(a?.raw??``)+n,s=um(o)??a?.partial,c={type:`structured-output`,status:`streaming`,raw:o,...s===void 0?{}:{partial:s},...a?.reasoning===void 0?{}:{reasoning:a.reasoning}};return i>=0?r[i]=c:r.push(c),{...e,parts:r}})}function ym(e,t,n,r,i){return e.map(e=>{if(e.id!==t)return e;let a=[...e.parts],o=a.findIndex(e=>e.type===`structured-output`),s=o>=0?a[o].raw:``,c=r||s;if(c===``&&n!==void 0)try{c=JSON.stringify(n)}catch{}let l={type:`structured-output`,status:`complete`,data:n,partial:n,raw:c,...i===void 0?{}:{reasoning:i}};return o>=0?a[o]=l:a.push(l),{...e,parts:a}})}function bm(e,t,n){return e.map(e=>{if(e.id!==t)return e;let r=[...e.parts],i=r.findIndex(e=>e.type===`structured-output`);if(i<0)return r.push({type:`structured-output`,status:`error`,raw:``,errorMessage:n}),{...e,parts:r};let a=r[i];return a.status===`complete`?e:(r[i]={...a,status:`error`,errorMessage:n},{...e,parts:r})})}function xm(e,t,n,r,i){return e.map(e=>{if(e.id!==t)return e;let a=[...e.parts],o=a.findIndex(e=>e.type===`thinking`&&e.stepId===n),s={type:`thinking`,content:r,stepId:n,...i&&{signature:i}};return o>=0?a[o]=s:a.push(s),{...e,parts:a}})}var Sm=12;function Cm(e){return e.some(e=>{let t=e.metadata;if(!t||typeof t!=`object`||Array.isArray(t))return!1;let n=t[Tp];return typeof n==`object`&&!!n&&!Array.isArray(n)&&n.kind===`generic`})}var wm=class e{chunkStrategy;events;jsonParser;recordingEnabled;messages=[];messageStates=new Map;activeMessageIds=new Set;toolCallToMessage=new Map;pendingManualMessageId=null;pendingThinkingStepId=null;structuredMessageIds=new Set;structuredOutputUpdateBatches=new Map;activeRuns=new Set;finishReason=null;hasError=!1;isDone=!1;recording=null;recordingStartTime=0;constructor(e={}){this.chunkStrategy=e.chunkStrategy||new dm,this.events=e.events||{},this.jsonParser=e.jsonParser||lm,this.recordingEnabled=e.recording??!1,e.initialMessages&&(this.messages=[...e.initialMessages])}setMessages(e){this.messages=[...e],this.emitMessagesChange()}addUserMessage(e,t){let n=typeof e==`string`?[{type:`text`,content:e}]:e.map(e=>e),r={id:t??am(),role:`user`,parts:n,createdAt:new Date};return this.messages=[...this.messages,r],this.emitMessagesChange(),r}prepareAssistantMessage(){this.resetStreamState()}startAssistantMessage(e){this.prepareAssistantMessage();let{messageId:t}=this.ensureAssistantMessage(e);return this.pendingManualMessageId=t,t}getCurrentAssistantMessageId(){let e=null;for(let[t,n]of this.messageStates)n.role===`assistant`&&(e=t);return e}addToolResult(e,t,n){let r=this.messages.find(t=>t.parts.some(t=>t.type===`tool-call`&&t.id===e));if(!r){console.warn(`[StreamProcessor] Could not find message with tool call ${e}`);return}let i=gm(this.messages,e,t,n?`error`:void 0,n),a=Hp(t),o=n?`error`:`complete`;i=mm(i,r.id,e,a,o,n),this.messages=i,this.emitMessagesChange()}addToolApprovalResponse(e,t){this.messages=_m(this.messages,e,t),this.emitMessagesChange()}toModelMessages(){let e=[];for(let t of this.messages)e.push(...Xp(t));return e}getMessages(){return this.messages}areAllToolsComplete(){let e=this.messages.findLast(e=>e.role===`assistant`);if(!e)return!0;let t=e.parts.filter(e=>e.type===`tool-call`);if(t.length===0)return!0;let n=new Set(e.parts.filter(e=>e.type===`tool-result`).map(e=>e.toolCallId));return t.every(e=>e.state===`complete`||e.state===`approval-responded`||e.output!==void 0&&!e.approval||n.has(e.id)||Wp(e))}removeMessagesAfter(e){let t=new Set(this.messages.slice(0,e+1).map(e=>e.id));for(let e of this.structuredMessageIds)t.has(e)||this.structuredMessageIds.delete(e);for(let e of this.structuredOutputUpdateBatches.keys())t.has(e)||this.structuredOutputUpdateBatches.delete(e);for(let e of this.messageStates.keys())t.has(e)||this.messageStates.delete(e);for(let[e,n]of this.toolCallToMessage)t.has(n)||this.toolCallToMessage.delete(e);for(let e of this.activeMessageIds)t.has(e)||this.activeMessageIds.delete(e);this.messages=this.messages.slice(0,e+1),this.emitMessagesChange()}clearMessages(){this.messages=[],this.messageStates.clear(),this.activeMessageIds.clear(),this.toolCallToMessage.clear(),this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.pendingManualMessageId=null,this.emitMessagesChange()}async process(e){this.resetStreamState(),this.recordingEnabled&&this.startRecording();for await(let t of e)this.processChunk(t);return this.finalizeStream(),this.recording&&(this.recording.result=this.getResult()),this.getResult()}processChunk(e){switch(this.recording&&this.recording.chunks.push({chunk:e,timestamp:Date.now(),index:this.recording.chunks.length}),e.type){case`TEXT_MESSAGE_START`:this.handleTextMessageStartEvent(e);break;case`TEXT_MESSAGE_CONTENT`:this.handleTextMessageContentEvent(e);break;case`TEXT_MESSAGE_END`:this.handleTextMessageEndEvent(e);break;case`TOOL_CALL_START`:this.handleToolCallStartEvent(e);break;case`TOOL_CALL_ARGS`:this.handleToolCallArgsEvent(e);break;case`TOOL_CALL_END`:this.handleToolCallEndEvent(e);break;case`RUN_FINISHED`:this.handleRunFinishedEvent(e);break;case`RUN_ERROR`:this.handleRunErrorEvent(e);break;case`STEP_FINISHED`:this.handleStepFinishedEvent(e);break;case`MESSAGES_SNAPSHOT`:this.handleMessagesSnapshotEvent(e);break;case`CUSTOM`:this.handleCustomEvent(e);break;case`RUN_STARTED`:this.handleRunStartedEvent(e);break;case`REASONING_START`:case`REASONING_MESSAGE_START`:case`REASONING_MESSAGE_END`:case`REASONING_END`:break;case`REASONING_MESSAGE_CONTENT`:this.handleReasoningMessageContentEvent(e);break;case`TOOL_CALL_RESULT`:this.handleToolCallResultEvent(e);break;case`STEP_STARTED`:this.handleStepStartedEvent(e)}}createMessageState(e,t){let n={id:e,role:t,totalTextContent:``,currentSegmentText:``,lastEmittedText:``,hasSeenReasoningEvents:!1,thinkingSteps:new Map,thinkingStepSignatures:new Map,thinkingStepOrder:[],currentThinkingStepId:null,toolCalls:new Map,toolCallOrder:[],hasToolCallsSinceTextStart:!1,isComplete:!1};return this.messageStates.set(e,n),n}getMessageState(e){return this.messageStates.get(e)}consumePendingThinkingStep(e){if(!this.pendingThinkingStepId)return;let t=this.pendingThinkingStepId;e.currentThinkingStepId=t,e.thinkingSteps.has(t)||(e.thinkingSteps.set(t,``),e.thinkingStepOrder.push(t)),this.pendingThinkingStepId=null}getActiveAssistantMessageId(){let e=Array.from(this.activeMessageIds).reverse();for(let t of e){let e=this.messageStates.get(t);if(e&&e.role===`assistant`)return t}return null}ensureAssistantMessage(e){if(e){let t=this.getMessageState(e);if(t)return{messageId:e,state:t}}let t=this.getActiveAssistantMessageId();if(t){let e=this.getMessageState(t);if(e)return{messageId:t,state:e}}if(e){let t=this.messages.find(t=>t.id===e);if(t){let n=this.createMessageState(e,t.role);this.activeMessageIds.add(e);let r=t.parts.length>0?t.parts[t.parts.length-1]:null;return r&&r.type===`text`&&(n.currentSegmentText=r.content,n.lastEmittedText=r.content,n.totalTextContent=r.content),{messageId:e,state:n}}}let n=e||am(),r={id:n,role:`assistant`,parts:[],createdAt:new Date};this.messages=[...this.messages,r];let i=this.createMessageState(n,`assistant`);return this.activeMessageIds.add(n),this.pendingManualMessageId=n,this.events.onStreamStart?.(),this.emitMessagesChange(),{messageId:n,state:i}}handleTextMessageStartEvent(e){let{messageId:t,role:n}=e,r=n===`user`||n===`system`?n:`assistant`;if(this.pendingManualMessageId){let e=this.pendingManualMessageId;if(this.pendingManualMessageId=null,e!==t){this.messages=this.messages.map(n=>n.id===e?{...n,id:t}:n);let n=this.messageStates.get(e);n&&(n.id=t,this.messageStates.delete(e),this.messageStates.set(t,n)),this.activeMessageIds.delete(e),this.activeMessageIds.add(t);for(let[n,r]of this.toolCallToMessage)r===e&&this.toolCallToMessage.set(n,t)}this.messageStates.has(t)||(this.createMessageState(t,r),this.activeMessageIds.add(t)),this.emitMessagesChange();return}if(this.messages.find(e=>e.id===t)){this.activeMessageIds.add(t);let e=this.messageStates.get(t);e?e.hasToolCallsSinceTextStart&&=(e.currentSegmentText!==e.lastEmittedText&&this.emitTextUpdateForMessage(t),e.currentSegmentText=``,e.lastEmittedText=``,!1):this.createMessageState(t,r);return}let i={id:t,role:r,parts:[],createdAt:new Date};this.messages=[...this.messages,i],this.createMessageState(t,r),this.activeMessageIds.add(t),this.events.onStreamStart?.(),this.emitMessagesChange()}handleTextMessageEndEvent(e){let{messageId:t}=e,n=this.getMessageState(t);n&&(n.isComplete||n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(t))}handleMessagesSnapshotEvent(e){this.resetStreamState();let t=this.messages,n=e.messages.map(nm);this.messages=this.reconcileSnapshotToolCalls(n,t),this.emitMessagesChange()}reconcileSnapshotToolCalls(e,t){let n=new Map;for(let e of t)for(let t of e.parts)t.type===`tool-call`&&n.set(t.id,t);let r=new Set;for(let t of e)for(let e of t.parts)e.type===`tool-call`&&r.add(e.id);let i=[];for(let t of e){let e=t.role===`assistant`&&t.parts.length===1?t.parts.find(e=>e.type===`tool-result`):void 0;if(!e){i.push(t);continue}let a=i.findLast(t=>t.parts.some(t=>t.type===`tool-call`&&t.id===e.toolCallId))??i.findLast(e=>e.role===`assistant`&&(e.parts.length!==1||e.parts[0]?.type!==`tool-result`));if(!a){r.has(e.toolCallId)||console.warn(`[StreamProcessor] MESSAGES_SNAPSHOT contains a tool-result for "${e.toolCallId}" but no matching tool-call exists in the snapshot, and there is no assistant message to anchor into; addToolResult("${e.toolCallId}") will not be able to locate this call`),i.push(t);continue}let o=[...a.parts];if(!r.has(e.toolCallId)&&!o.some(t=>t.type===`tool-call`&&t.id===e.toolCallId)){let t=n.get(e.toolCallId);t?(o.push({...t}),r.add(t.id)):console.warn(`[StreamProcessor] MESSAGES_SNAPSHOT contains a tool-result for "${e.toolCallId}" but no matching tool-call exists in the snapshot or the pre-snapshot state; addToolResult("${e.toolCallId}") will not be able to locate this call`)}o.push(e),a.parts=o}return this.enrichSnapshotToolCallsFromResults(i,n)}enrichSnapshotToolCallsFromResults(e,t){let n=new Map;for(let t of e)for(let e of t.parts)e.type===`tool-result`&&n.set(e.toolCallId,e);return e.map(e=>{let r=e.parts.map(e=>{if(e.type!==`tool-call`)return e;let r=t.get(e.id),i=n.get(e.id),a=e;if(r&&(r.output!==void 0||r.state===`complete`||r.state===`error`)&&(e.output===void 0||e.state===`input-complete`||e.state===`input-streaming`||e.state===`awaiting-input`)&&(a={...e,...r.output===void 0?{}:{output:r.output},state:r.state,...r.approval===void 0?{}:{approval:r.approval},...r.metadata===void 0?{}:{metadata:r.metadata}}),i&&a.output===void 0){let e;if(Array.isArray(i.content))e=i.content;else try{e=JSON.parse(i.content)}catch{e=i.content}let t=i.state===`error`?this.extractToolResultError(e):void 0;a={...a,output:t?{error:t}:e,state:i.state===`error`?`error`:`complete`}}return a});return r.some((t,n)=>t!==e.parts[n])?{...e,parts:r}:e})}handleTextMessageContentEvent(e){let{messageId:t,state:n}=this.ensureAssistantMessage(e.messageId);if(this.structuredMessageIds.has(t)){let r=e.delta||``;if(r===``&&e.content!==void 0&&e.content!==``){let n=(this.messages.find(e=>e.id===t)?.parts.find(e=>e.type===`structured-output`)??{raw:``}).raw;r=e.content.startsWith(n)?e.content.slice(n.length):n.startsWith(e.content)?``:e.content}r!==``&&(this.messages=vm(this.messages,t,r),n.totalTextContent+=r,this.queueStructuredOutputUpdate(t,r),this.emitMessagesChange());return}let r=n.currentSegmentText;n.hasToolCallsSinceTextStart&&r.length>0&&this.isNewTextSegment(e,r)&&(r!==n.lastEmittedText&&this.emitTextUpdateForMessage(t),n.currentSegmentText=``,n.lastEmittedText=``,n.hasToolCallsSinceTextStart=!1);let i=n.currentSegmentText,a=i,o=e.delta||``;o===``?e.content!==void 0&&e.content!==``&&(a=e.content.startsWith(i)?e.content:i.startsWith(e.content)?i:i+e.content):a=i+o;let s=a.slice(i.length);n.currentSegmentText=a,n.totalTextContent+=s;let c=e.delta||e.content||``;this.chunkStrategy.shouldEmit(c,n.currentSegmentText)&&n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(t)}handleToolCallStartEvent(e){let t=e.parentMessageId??this.getActiveAssistantMessageId(),{messageId:n,state:r}=this.ensureAssistantMessage(t??void 0);r.hasToolCallsSinceTextStart=!0;let i=e.toolCallId;if(!r.toolCalls.get(i)){let t=`awaiting-input`,a=e.toolCallName??e.toolName,o=e.metadata,s={id:e.toolCallId,name:a,arguments:``,state:t,parsedArguments:void 0,index:e.index??r.toolCalls.size,...o!==void 0&&{metadata:o}};r.toolCalls.set(i,s),r.toolCallOrder.push(i),this.toolCallToMessage.set(i,n),this.messages=pm(this.messages,n,{id:e.toolCallId,name:a,arguments:``,state:t,...o!==void 0&&{metadata:o}}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(n,e.toolCallId,t,``)}}handleToolCallArgsEvent(e){let t=e.toolCallId,n=this.toolCallToMessage.get(t);if(!n)return;let r=this.getMessageState(n);if(!r)return;let i=r.toolCalls.get(t);if(!i)return;let a=i.state===`awaiting-input`;i.arguments+=e.delta||``,a&&e.delta&&(i.state=`input-streaming`),i.parsedArguments=this.jsonParser.parse(i.arguments),this.messages=pm(this.messages,n,{id:i.id,name:i.name,arguments:i.arguments,state:i.state}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(n,i.id,i.state,i.arguments)}handleToolCallEndEvent(e){let t=this.toolCallToMessage.get(e.toolCallId);if(!t)return;let n=this.getMessageState(t);if(!n)return;let r=n.toolCalls.get(e.toolCallId);if(r&&r.state!==`input-complete`){if(e.input!==void 0&&!r.arguments)try{r.arguments=JSON.stringify(e.input)}catch{}let i=n.toolCallOrder.indexOf(e.toolCallId);this.completeToolCall(t,i,r),e.input!==void 0&&(r.parsedArguments=e.input,this.messages=pm(this.messages,t,{id:r.id,name:r.name,arguments:r.arguments,state:`input-complete`,input:e.input,...r.metadata!==void 0&&{metadata:r.metadata}}),this.emitMessagesChange())}if(e.result){let n;if(Array.isArray(e.result))n=e.result;else try{n=JSON.parse(e.result)}catch{n=e.result}this.messages=gm(this.messages,e.toolCallId,n,e.state===`output-error`?`error`:void 0);let r=e.state===`output-error`?`error`:`complete`;this.messages=mm(this.messages,t,e.toolCallId,e.result,r,r===`error`?this.extractToolResultError(n):void 0),this.emitMessagesChange()}}extractToolResultError(e){return e&&typeof e==`object`&&`error`in e&&typeof e.error==`string`?e.error:typeof e==`string`?e:`Tool execution failed`}handleToolCallResultEvent(e){let t=this.toolCallToMessage.get(e.toolCallId);if(!t)return;let n;try{n=JSON.parse(e.content)}catch{n=e.content}this.messages=gm(this.messages,e.toolCallId,n,e.state===`output-error`?`error`:void 0);let r=e.state===`output-error`?`error`:`complete`;this.messages=mm(this.messages,t,e.toolCallId,e.content,r,r===`error`?this.extractToolResultError(n):void 0),this.emitMessagesChange()}handleRunStartedEvent(e){this.activeRuns.add(e.runId)}handleRunFinishedEvent(e){this.finishReason=e.finishReason??null,this.activeRuns.delete(e.runId),e.outcome?.type===`interrupt`&&this.handleInterrupts(e.outcome.interrupts),this.activeRuns.size===0&&(this.isDone=!0,this.completeAllToolCalls(),this.finalizeStream())}handleInterrupts(e){let t=Cm(e);for(let n of e){let e=n.metadata&&typeof n.metadata==`object`?n.metadata:{},r=typeof e.kind==`string`?e.kind:void 0,i=n.toolCallId;if(!i)continue;let a=typeof e.toolName==`string`?e.toolName:this.findToolCallName(i),o=Object.hasOwn(e,`input`)?e.input:{};if(r===`approval`||n.reason===`approval_required`){let e=this.getActiveAssistantMessageId()??this.toolCallToMessage.get(i)??this.messages.find(e=>e.role===`assistant`&&e.parts.some(e=>e.type===`tool-call`&&e.id===i))?.id;e&&(this.messages=hm(this.messages,e,i,n.id),this.emitMessagesChange()),this.events.onApprovalRequest?.({toolCallId:i,toolName:a,input:o,approvalId:n.id});continue}if(r===`client_tool`||n.reason===`client_tool_input`){if(t)continue;this.events.onToolCall?.({toolCallId:i,toolName:a,input:o})}}}findToolCallName(e){for(let t of this.messageStates.values()){let n=t.toolCalls.get(e);if(n)return n.name}return``}handleRunErrorEvent(e){this.hasError=!0;let t=`runId`in e&&typeof e.runId==`string`?e.runId:void 0;t?this.activeRuns.delete(t):this.activeRuns.clear();let{messageId:n}=this.ensureAssistantMessage(),r=e.message||e.error?.message||`An error occurred`;!e.message&&!e.error?.message&&console.error(`[StreamProcessor] RUN_ERROR with no message; original chunk:`,e),this.structuredMessageIds.has(n)&&(this.flushStructuredOutputUpdate(n),this.messages=bm(this.messages,n,r),this.structuredMessageIds.delete(n),this.emitStructuredOutputChange(n,`error`),this.emitMessagesChange()),this.events.onError?.(Yf(e))}handleStepStartedEvent(e){let t=e.stepId??am(),n=this.getActiveAssistantMessageId();if(n){let e=this.getMessageState(n);if(e){e.currentThinkingStepId=t,e.thinkingSteps.has(t)||(e.thinkingSteps.set(t,``),e.thinkingStepOrder.push(t)),this.pendingThinkingStepId=null;return}}this.pendingThinkingStepId=t}handleStepFinishedEvent(e){let{messageId:t,state:n}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0);if(n.hasSeenReasoningEvents){if(e.signature){let r=n.currentThinkingStepId??e.stepId;if(!r)return;let i=n.thinkingSteps.get(r);i!==void 0&&(n.thinkingStepSignatures.set(r,e.signature),this.messages=xm(this.messages,t,r,i,e.signature),this.emitMessagesChange())}return}this.consumePendingThinkingStep(n);let r=n.currentThinkingStepId??e.stepId??am();n.thinkingSteps.has(r)||(n.thinkingSteps.set(r,``),n.thinkingStepOrder.push(r),n.currentThinkingStepId=r);let i=n.thinkingSteps.get(r)??``,a=i;e.delta&&e.delta!==``?a=i+e.delta:e.content&&e.content!==``&&(a=e.content.startsWith(i)?e.content:i.startsWith(e.content)?i:i+e.content),n.thinkingSteps.set(r,a),e.signature&&n.thinkingStepSignatures.set(r,e.signature),this.messages=xm(this.messages,t,r,a,n.thinkingStepSignatures.get(r)),this.emitMessagesChange(),this.events.onThinkingUpdate?.(t,r,a)}handleReasoningMessageContentEvent(e){let{messageId:t,state:n}=this.ensureAssistantMessage(this.getActiveAssistantMessageId()??void 0);n.hasSeenReasoningEvents=!0;let r=e.delta||``;this.consumePendingThinkingStep(n);let i=n.currentThinkingStepId??e.messageId;n.thinkingSteps.has(i)||(n.thinkingSteps.set(i,``),n.thinkingStepOrder.push(i),n.currentThinkingStepId=i);let a=(n.thinkingSteps.get(i)??``)+r;n.thinkingSteps.set(i,a),this.messages=xm(this.messages,t,i,a,n.thinkingStepSignatures.get(i)),this.emitMessagesChange(),this.events.onThinkingUpdate?.(t,i,a)}handleCustomEvent(e){let t=this.getActiveAssistantMessageId();if(e.name===`structured-output.start`&&e.value){let n=e.value,{messageId:r}=this.ensureAssistantMessage(n.messageId??t??void 0);r&&(this.structuredMessageIds.add(r),this.structuredOutputUpdateBatches.delete(r),this.events.onStructuredOutputChange?.({phase:`start`,messageId:r,status:`streaming`,raw:``}));return}if(e.name===`structured-output.complete`&&e.value){let n=e.value,{messageId:r}=this.ensureAssistantMessage(n.messageId??t??void 0);r&&(this.flushStructuredOutputUpdate(r),this.messages=ym(this.messages,r,n.object,n.raw??``,n.reasoning),this.structuredMessageIds.delete(r),this.emitStructuredOutputChange(r,`complete`),this.emitMessagesChange())}if(e.name===`tool-input-available`&&e.value){let{toolCallId:t,toolName:n,input:r}=e.value;this.events.onToolCall?.({toolCallId:t,toolName:n,input:r});return}if(e.name===`approval-requested`&&e.value){let{toolCallId:n,toolName:r,input:i,approval:a}=e.value,o=t??this.toolCallToMessage.get(n);o&&(this.messages=hm(this.messages,o,n,a.id),this.emitMessagesChange()),this.events.onApprovalRequest?.({toolCallId:n,toolName:r,input:i,approvalId:a.id});return}if(e.name===`ui-resource`&&e.value){let n=e.value,r=this.toolCallToMessage.get(n.toolCallId)??t;if(r){let e={type:`ui-resource`,resource:n.resource,toolCallId:n.toolCallId,toolName:n.toolName,...n.serverId!==void 0&&{serverId:n.serverId},...n.meta!==void 0&&{meta:n.meta}};this.messages=this.messages.map(t=>t.id===r?{...t,parts:[...t.parts,e]}:t),this.emitMessagesChange()}else console.warn(`[mcp-apps] dropped ui-resource: no target message for toolCallId "${n.toolCallId}" (toolName "${n.toolName}")`);return}if(this.events.onCustomEvent){let t=e.value&&typeof e.value==`object`?e.value.toolCallId:void 0;this.events.onCustomEvent(e.name,e.value,{toolCallId:t})}}isNewTextSegment(e,t){return e.content!==void 0&&(e.content.length<t.length||!e.content.startsWith(t)&&!t.startsWith(e.content))}completeAllToolCalls(){for(let e of this.activeMessageIds)this.completeAllToolCallsForMessage(e)}completeAllToolCallsForMessage(e){let t=this.getMessageState(e);t&&t.toolCalls.forEach((n,r)=>{if(n.state!==`input-complete`){let i=t.toolCallOrder.indexOf(r);this.completeToolCall(e,i,n)}})}completeToolCall(e,t,n){n.state=`input-complete`;let r=!1;try{n.parsedArguments=JSON.parse(n.arguments),r=!0}catch{n.parsedArguments=void 0}this.isToolCallPartErrored(n.id)||this.isToolCallPartAwaitingUserAction(n.id)||(this.messages=pm(this.messages,e,{id:n.id,name:n.name,arguments:n.arguments,state:`input-complete`,...r&&{input:n.parsedArguments},...n.metadata!==void 0&&{metadata:n.metadata}}),this.emitMessagesChange(),this.events.onToolCallStateChange?.(e,n.id,`input-complete`,n.arguments))}isToolCallPartAwaitingUserAction(e){return this.messages.some(t=>t.parts?.some(t=>t.type===`tool-call`&&t.id===e&&(t.state===`approval-requested`||t.state===`approval-responded`)))}isToolCallPartErrored(e){return this.messages.some(t=>t.parts?.some(t=>t.type===`tool-call`&&t.id===e&&t.state===`error`))}emitTextUpdateForMessage(e){let t=this.getMessageState(e);t&&(t.lastEmittedText=t.currentSegmentText,this.messages=fm(this.messages,e,t.currentSegmentText),this.emitMessagesChange(),this.events.onTextUpdate?.(e,t.currentSegmentText))}queueStructuredOutputUpdate(e,t){let n=this.structuredOutputUpdateBatches.get(e),r={delta:`${n?.delta??``}${t}`,chunkCount:(n?.chunkCount??0)+1};this.structuredOutputUpdateBatches.set(e,r),r.chunkCount>=Sm&&this.flushStructuredOutputUpdate(e)}flushStructuredOutputUpdate(e){let t=this.structuredOutputUpdateBatches.get(e);!t||t.chunkCount===0||(this.structuredOutputUpdateBatches.delete(e),this.emitStructuredOutputChange(e,`update`,t.delta))}emitStructuredOutputChange(e,t,n){let r=this.messages.find(t=>t.id===e)?.parts.find(e=>e.type===`structured-output`);r&&this.events.onStructuredOutputChange?.({phase:t,messageId:e,status:r.status,raw:r.raw,...r.partial===void 0?{}:{partial:r.partial},...r.data===void 0?{}:{data:r.data},...r.reasoning===void 0?{}:{reasoning:r.reasoning},...r.errorMessage===void 0?{}:{errorMessage:r.errorMessage},...n===void 0?{}:{delta:n}})}emitMessagesChange(){this.events.onMessagesChange?.([...this.messages])}finalizeStream(){let e;for(let t of this.activeMessageIds){let n=this.getMessageState(t);if(!n)continue;this.completeAllToolCallsForMessage(t),n.currentSegmentText!==n.lastEmittedText&&this.emitTextUpdateForMessage(t),n.isComplete=!0;let r=this.messages.find(e=>e.id===t);r&&r.role===`assistant`&&(e=r)}for(let e of this.structuredMessageIds)this.flushStructuredOutputUpdate(e),this.messages=bm(this.messages,e,`Stream ended without structured-output.complete`),this.emitStructuredOutputChange(e,`error`);if(this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.activeMessageIds.clear(),e&&!this.hasError&&this.isWhitespaceOnlyMessage(e)){this.messages=this.messages.filter(t=>t.id!==e.id),this.emitMessagesChange();return}e&&this.events.onStreamEnd?.(e)}getCompletedToolCalls(){let e=[];for(let t of this.messageStates.values())for(let n of t.toolCalls.values())n.state===`input-complete`&&e.push({id:n.id,type:`function`,function:{name:n.name,arguments:n.arguments},...n.metadata!==void 0&&{metadata:n.metadata}});return e}getResult(){let e=this.getCompletedToolCalls(),t=``,n=``;for(let e of this.messageStates.values()){t+=e.totalTextContent;for(let t of e.thinkingStepOrder)n+=e.thinkingSteps.get(t)??``}return{content:t,thinking:n||void 0,toolCalls:e.length>0?e:void 0,finishReason:this.finishReason}}getState(){let e=``,t=``,n=new Map,r=[];for(let i of this.messageStates.values()){e+=i.totalTextContent;for(let e of i.thinkingStepOrder)t+=i.thinkingSteps.get(e)??``;for(let[e,t]of i.toolCalls)n.set(e,t);r.push(...i.toolCallOrder)}return{content:e,thinking:t,toolCalls:n,toolCallOrder:r,finishReason:this.finishReason,done:this.isDone}}startRecording(){this.recordingEnabled=!0,this.recordingStartTime=Date.now(),this.recording={version:`1.0`,timestamp:this.recordingStartTime,chunks:[]}}getRecording(){return this.recording}resetStreamState(){this.messageStates.clear(),this.activeMessageIds.clear(),this.activeRuns.clear(),this.toolCallToMessage.clear(),this.structuredMessageIds.clear(),this.structuredOutputUpdateBatches.clear(),this.pendingManualMessageId=null,this.pendingThinkingStepId=null,this.finishReason=null,this.hasError=!1,this.isDone=!1,this.chunkStrategy.reset?.()}reset(){this.resetStreamState(),this.messages=[]}isWhitespaceOnlyMessage(e){return e.parts.length!==0&&e.parts.every(e=>e.type===`text`&&e.content.trim()===``)}static async replay(t,n){return new e(n).process(Tm(t))}};function Tm(e){return{async*[Symbol.asyncIterator](){for(let{chunk:t}of e.chunks)yield t}}}function Em(e){let t=[];for(let n of e){let e=n.parts??[];if(n.role===`system`){t.push({...n,content:e.length>0?Dm(e):n.content??``});continue}if(n.role===`user`){t.push({...n,content:e.length>0?Om(e):n.content??``});continue}for(let r of e)r.type===`thinking`&&t.push({role:`reasoning`,id:Am(n.id,r),content:r.content});let r=Dm(e),i=km(e);t.push({...n,...r!==``&&{content:r},...i&&{toolCalls:i}});for(let n of e)n.type===`tool-result`&&t.push({role:`tool`,id:jm(n.toolCallId),toolCallId:n.toolCallId,content:typeof n.content==`string`?n.content:JSON.stringify(n.content),...n.error!==void 0&&{error:n.error}})}return t}function Dm(e){let t=[];for(let n of e)n.type===`text`?t.push(n.content):n.type===`structured-output`&&n.status===`complete`&&n.raw!==``&&t.push(n.raw);return t.join(``)}function Om(e){if(!e.some(e=>e.type===`image`||e.type===`audio`||e.type===`video`||e.type===`document`))return Dm(e);let t=[];for(let n of e)n.type===`text`?t.push({type:`text`,text:n.content}):(n.type===`image`||n.type===`audio`||n.type===`video`||n.type===`document`)&&t.push(n);return t}function km(e){let t=[];for(let n of e)n.type===`tool-call`&&t.push({id:n.id,type:`function`,function:{name:n.name,arguments:n.arguments}});return t.length>0?t:void 0}function Am(e,t){return`${e}-reasoning-${t.id??Mm(t.content)}`}function jm(e){return`tool-${e}`}function Mm(e){let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)|0;return Math.abs(t).toString(36)}var Nm=function(e){return e.TEXT_MESSAGE_START=`TEXT_MESSAGE_START`,e.TEXT_MESSAGE_CONTENT=`TEXT_MESSAGE_CONTENT`,e.TEXT_MESSAGE_END=`TEXT_MESSAGE_END`,e.TEXT_MESSAGE_CHUNK=`TEXT_MESSAGE_CHUNK`,e.TOOL_CALL_START=`TOOL_CALL_START`,e.TOOL_CALL_ARGS=`TOOL_CALL_ARGS`,e.TOOL_CALL_END=`TOOL_CALL_END`,e.TOOL_CALL_CHUNK=`TOOL_CALL_CHUNK`,e.TOOL_CALL_RESULT=`TOOL_CALL_RESULT`,e.THINKING_START=`THINKING_START`,e.THINKING_END=`THINKING_END`,e.THINKING_TEXT_MESSAGE_START=`THINKING_TEXT_MESSAGE_START`,e.THINKING_TEXT_MESSAGE_CONTENT=`THINKING_TEXT_MESSAGE_CONTENT`,e.THINKING_TEXT_MESSAGE_END=`THINKING_TEXT_MESSAGE_END`,e.STATE_SNAPSHOT=`STATE_SNAPSHOT`,e.STATE_DELTA=`STATE_DELTA`,e.MESSAGES_SNAPSHOT=`MESSAGES_SNAPSHOT`,e.ACTIVITY_SNAPSHOT=`ACTIVITY_SNAPSHOT`,e.ACTIVITY_DELTA=`ACTIVITY_DELTA`,e.RAW=`RAW`,e.CUSTOM=`CUSTOM`,e.RUN_STARTED=`RUN_STARTED`,e.RUN_FINISHED=`RUN_FINISHED`,e.RUN_ERROR=`RUN_ERROR`,e.STEP_STARTED=`STEP_STARTED`,e.STEP_FINISHED=`STEP_FINISHED`,e.REASONING_START=`REASONING_START`,e.REASONING_MESSAGE_START=`REASONING_MESSAGE_START`,e.REASONING_MESSAGE_CONTENT=`REASONING_MESSAGE_CONTENT`,e.REASONING_MESSAGE_END=`REASONING_MESSAGE_END`,e.REASONING_MESSAGE_CHUNK=`REASONING_MESSAGE_CHUNK`,e.REASONING_END=`REASONING_END`,e.REASONING_ENCRYPTED_VALUE=`REASONING_ENCRYPTED_VALUE`,e}({}),Pm=e.object({type:e.enum([`query`,`mutation`,`subscription`]),id:e.string(),name:e.string(),description:e.string(),inputSchema:e.unknown(),outputSchema:e.unknown(),outputSample:e.unknown()}),Fm=om({name:`getCapabilities`,description:`Get the APIs available to the generated Rough feature`,inputSchema:e.object({}),outputSchema:e.array(Pm)}),Im=om({name:`getLogs`,description:`Get Rough feature logs`,inputSchema:e.object({spriteBuildId:e.string().min(1)}),outputSchema:e.array(e.object({id:e.string().min(1),spriteBuildId:e.string().min(1),actionedAt:e.number(),type:e.enum([`STEP_STARTED`,`STEP_COMPLETED`,`STEP_FAILED`,`EXEC_STARTED`,`EXEC_COMPLETED`,`EXEC_FAILED`,`FETCH_STARTED`,`FETCH_COMPLETED`,`FETCH_FAILED`,`AGENT_STARTED`,`AGENT_USAGE`,`AGENT_COMPLETED`,`AGENT_TOOL_STARTED`,`AGENT_TOOL_COMPLETED`,`AGENT_TOOL_FAILED`,`AGENT_META`,`AGENT_MESSAGE`,`AGENT_THOUGHT`]),detail:e.unknown()}))}),Lm=om({name:`startBuild`,description:`Start a Rough feature build`,inputSchema:e.object({prompt:e.string().min(1)}),outputSchema:e.object({spriteBuildId:e.string().min(1)})}),Rm=e=>{let{content:t}=e;return t===null?``:typeof t==`string`?t:t.filter(e=>e.type===`text`).map(e=>e.content??``).join(`
13
13
  `)},zm=e=>`${e.role}:\n${e.text}`,Bm=(e,t)=>{let n=`
14
14
 
15
15
  ---
@@ -22,37 +22,37 @@ ${t.map(zm).join(n)}${n}
22
22
  `.trim():``}
23
23
  # current user message
24
24
 
25
- ${zm(e)}`.trim()},Vm=e=>{let{messageList:t}=e,n=t.flatMap(e=>{if(e.role===`tool`)return[];let t=Rm(e);return t.trim().length===0?[]:[{role:e.role,text:t}]}),r=n.findLastIndex(e=>e.role===`user`),i=n[r];return i?Bm(i,n.slice(0,r)):Error(`Could not find a user message in the sprite chat`)},Hm=new Map,Um=e=>{let{clientId:t,replicacheName:n}=e,r=()=>{},i={clientId:t,state:`starting`,released:new Promise(e=>{r=e})};Hm.set(n,i);let a=!1;return{replicacheName:n,markActive:()=>{!a&&i.state===`starting`&&(i.state=`active`)},markDestroying:()=>{a||(i.state=`destroying`)},release:()=>{a||(a=!0,Hm.get(n)===i&&Hm.delete(n),r())}}},Wm=async e=>{let{clientId:t,replicacheName:n,signal:r}=e;for(;;){if(r?.aborted)throw r.reason instanceof Error?r.reason:Error(`Replicache identity acquisition aborted`);let e=Hm.get(n);if(!e)return Um({clientId:t,replicacheName:n});if(e.state===`destroying`){await e.released;continue}throw new Et({replicacheName:n})}},Gm=e=>{let{baseUrl:t,personId:n,projectId:r}=e;return[`rough-feature`,t,r,n].join(`:`)},Km=e=>{let{auth:t,baseUrl:n,clientId:r,projectId:i,signal:a,store:o}=e,s=`/api/v1/project/${encodeURIComponent(i)}`,c,l,u,d=!1,f,p=()=>{if(a.aborted)throw jt(a)},m=async e=>{let{name:r}=e,{sessionToken:i}=e,a=i.personId;return Uf({name:r,pushURL:ce({baseUrl:n,path:`${s}/replicache/push`}),pullURL:ce({baseUrl:n,path:`${s}/replicache/pull`}),auth:`Bearer ${i.token}`,pullInterval:5e3,getAuth:async()=>{t.invalidateToken(i.token);let e=await t.getSessionToken();if(e.personId!==a)throw Error(`Session person changed during auth refresh. Destroy this Rough client and create a new one.`);return i=e,`Bearer ${i.token}`},sessionPersonId:a})},h=async()=>{if(typeof window>`u`)return;p();let e=await Promise.race([t.getSessionToken(),Mt(a)]);p();let f=Gm({baseUrl:n,projectId:i,personId:e.personId});c=await Wm({clientId:r,replicacheName:f,signal:a}),d&&c.markDestroying(),p();let h=await m({name:f,sessionToken:e});if(h instanceof Error)throw h;if(d||a.aborted)throw await h.close(),new Tt(`Replicache finished starting after the Rough client was destroyed`);l=h,c.markActive(),o.bind(h);let g=new URL(ce({baseUrl:n,path:`${s}/replicache/poke`}));g.protocol=g.protocol===`https:`?`wss:`:`ws:`;let _=Yf({url:g.toString(),getToken:async()=>(await t.getSessionToken()).token,onPoke:()=>h.pull()});if(d||a.aborted)throw _.close(),await h.close(),l=void 0,new Tt(`Replicache finished starting after the Rough client was destroyed`);u=_,await Promise.race([h.pull({now:!0}),Mt(a)])},g=()=>l,_=()=>{d=!0,c?.markDestroying()};return{start:h,peek:g,markDestroying:_,destroy:()=>(f??=(async()=>{_();let e=u;u=void 0,e?.close();let t=l;l=void 0,await t?.close()})(),f),releaseIdentity:()=>{c?.release()}}},qm=e.enum([`ACTIVE`,`DELETED`]),Jm=e.enum([`DOCUMENTS_ENABLED`,`TASKS_ENABLED`]),V=e.string();e.object({id:V,publicId:e.string(),name:e.string(),createdAt:e.number(),updatedAt:e.number(),icp:e.string(),strategy:e.string(),vision:e.string(),icon:e.string(),status:qm,deletedAt:e.number().nullable(),version:e.number(),flagList:Jm.array()}),e.object({id:V,publicId:e.string(),name:e.string(),createdAt:e.number(),updatedAt:e.number(),icp:e.string().optional(),strategy:e.string().optional(),vision:e.string().optional(),icon:e.string(),status:qm,deletedAt:e.number().optional().nullable(),version:e.number(),flagList:Jm.array()}),e.object({id:V.optional(),publicId:e.string().optional(),name:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),icp:e.string().optional(),strategy:e.string().optional(),vision:e.string().optional(),icon:e.string().optional(),status:qm.optional(),deletedAt:e.number().optional().nullable(),version:e.number().optional(),flagList:Jm.array().optional()});var Ym=e.string();e.object({id:Ym,name:e.string(),url:e.string(),workspaceId:V,version:e.number(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:Ym,name:e.string(),url:e.string(),workspaceId:V,version:e.number(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:Ym.optional(),name:e.string().optional(),url:e.string().optional(),workspaceId:V.optional(),version:e.number().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var Xm=e.enum([`authorization_code`,`client_credentials`,`refresh_token`]),Zm=e.enum([`read:workspace`,`write:workspace`,`create:sprite`,`read:sprite`]),Qm=e.string();e.object({id:Qm,name:e.string(),secret:e.string().nullable(),redirectUris:e.string().array(),allowedGrants:Xm.array(),scopes:Zm.array(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:Qm,name:e.string(),secret:e.string().optional().nullable(),redirectUris:e.string().array(),allowedGrants:Xm.array(),scopes:Zm.array(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:Qm.optional(),name:e.string().optional(),secret:e.string().optional().nullable(),redirectUris:e.string().array().optional(),allowedGrants:Xm.array().optional(),scopes:Zm.array().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var $m=e.enum([`UNKNOWN`]),H=e.string();e.object({id:H,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),state:e.instanceof(Uint8Array),serialized:e.record(e.string(),e.json()),plaintext:e.string(),version:e.number(),documentMentionList:e.string().array(),hash:e.instanceof(Uint8Array),dirtyAt:e.number().nullable(),flagList:$m.array(),personMentionList:e.string().array()}),e.object({id:H,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),state:e.instanceof(Uint8Array),serialized:e.record(e.string(),e.json()),plaintext:e.string(),version:e.number(),documentMentionList:e.string().array(),hash:e.instanceof(Uint8Array),dirtyAt:e.number().optional().nullable(),flagList:$m.array(),personMentionList:e.string().array()}),e.object({id:H.optional(),workspaceId:V.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),state:e.instanceof(Uint8Array).optional(),serialized:e.record(e.string(),e.json()).optional(),plaintext:e.string().optional(),version:e.number().optional(),documentMentionList:e.string().array().optional(),hash:e.instanceof(Uint8Array).optional(),dirtyAt:e.number().optional().nullable(),flagList:$m.array().optional(),personMentionList:e.string().array().optional()});var eh=e=>{let t=e.toLowerCase().trim().split(`@`),n=t.at(0)?.trim(),r=t.at(1)?.split(`,`).at(0)?.trim();return!n||!r?Error(`Invalid email address`):`${n}@${r}`},U=e.string().min(1).transform((t,n)=>{let r=eh(t);return r instanceof Error?(n.issues.push({code:`custom`,message:r.message,input:t}),e.NEVER):r}).pipe(e.string()),th=e.enum([`WORKSPACE`,`USER`]),nh=e.enum([`PENDING`,`UPLOADING`,`READY`,`ERROR`]),rh=e.enum([`IMAGE`,`VIDEO`,`AUDIO`,`OTHER`]),ih=e.string();e.object({id:ih,scope:th,userId:e.lazy(()=>W),workspaceId:V.nullable(),storageBucket:e.string(),storageKey:e.string(),status:nh,type:rh,mimeType:e.string(),originalFileName:e.string(),byteSize:e.number(),metadata:e.record(e.string(),e.json()),tusUploadToken:e.string().nullable(),createdAt:e.number(),updatedAt:e.number(),deletedAt:e.number().nullable(),version:e.number(),originalAssetId:ih.nullable()}),e.object({id:ih,scope:th,userId:e.lazy(()=>W),workspaceId:V.optional().nullable(),storageBucket:e.string(),storageKey:e.string(),status:nh,type:rh,mimeType:e.string(),originalFileName:e.string(),byteSize:e.number(),metadata:e.record(e.string(),e.json()),tusUploadToken:e.string().optional().nullable(),createdAt:e.number(),updatedAt:e.number(),deletedAt:e.number().optional().nullable(),version:e.number(),originalAssetId:ih.optional().nullable()}),e.object({id:ih.optional(),scope:th.optional(),userId:e.lazy(()=>W.optional()),workspaceId:V.optional().nullable(),storageBucket:e.string().optional(),storageKey:e.string().optional(),status:nh.optional(),type:rh.optional(),mimeType:e.string().optional(),originalFileName:e.string().optional(),byteSize:e.number().optional(),metadata:e.record(e.string(),e.json()).optional(),tusUploadToken:e.string().optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional(),deletedAt:e.number().optional().nullable(),version:e.number().optional(),originalAssetId:ih.optional().nullable()});var W=e.string();e.object({id:W,name:e.string(),email:U,isDemoAccount:e.boolean(),createdAt:e.number(),updatedAt:e.number(),passwordHash:e.string().nullable(),googleUid:e.string().nullable(),totpSecret:e.string().nullable(),totpEnabledAt:e.number().nullable(),recoveryHash:e.string().nullable(),recoveryCodeGeneratedAt:e.number().nullable(),avatarAssetId:ih.nullable()}),e.object({id:W,name:e.string(),email:U,isDemoAccount:e.boolean().optional(),createdAt:e.number(),updatedAt:e.number(),passwordHash:e.string().optional().nullable(),googleUid:e.string().optional().nullable(),totpSecret:e.string().optional().nullable(),totpEnabledAt:e.number().optional().nullable(),recoveryHash:e.string().optional().nullable(),recoveryCodeGeneratedAt:e.number().optional().nullable(),avatarAssetId:ih.optional().nullable()}),e.object({id:W.optional(),name:e.string().optional(),email:U.optional(),isDemoAccount:e.boolean().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),passwordHash:e.string().optional().nullable(),googleUid:e.string().optional().nullable(),totpSecret:e.string().optional().nullable(),totpEnabledAt:e.number().optional().nullable(),recoveryHash:e.string().optional().nullable(),recoveryCodeGeneratedAt:e.number().optional().nullable(),avatarAssetId:ih.optional().nullable()});var ah=e.enum([`DRAFT`,`ACTIVE`]),G=e.string();e.object({id:G,name:e.string(),workspaceId:V,version:e.number(),createdAt:e.number(),updatedAt:e.number(),description:e.string(),avatarAssetId:ih.nullable()}),e.object({id:G,name:e.string(),workspaceId:V,version:e.number(),createdAt:e.number(),updatedAt:e.number(),description:e.string(),avatarAssetId:ih.optional().nullable()}),e.object({id:G.optional(),name:e.string().optional(),workspaceId:V.optional(),version:e.number().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),description:e.string().optional(),avatarAssetId:ih.optional().nullable()});var K=e.string();e.object({id:K,workspaceId:V,contentId:H,createdAt:e.number(),updatedAt:e.number(),userId:W,version:e.number(),lastModifiedAt:e.number(),status:ah,personId:G,referenceId:Ym.nullable(),publicId:e.number(),parentNoteId:K.nullable(),sortOrder:e.number(),transcriptContentId:H.nullable()}),e.object({id:K,workspaceId:V,contentId:H,createdAt:e.number(),updatedAt:e.number(),userId:W,version:e.number(),lastModifiedAt:e.number(),status:ah,personId:G,referenceId:Ym.optional().nullable(),publicId:e.number(),parentNoteId:K.optional().nullable(),sortOrder:e.number(),transcriptContentId:H.optional().nullable()}),e.object({id:K.optional(),workspaceId:V.optional(),contentId:H.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),userId:W.optional(),version:e.number().optional(),lastModifiedAt:e.number().optional(),status:ah.optional(),personId:G.optional(),referenceId:Ym.optional().nullable(),publicId:e.number().optional(),parentNoteId:K.optional().nullable(),sortOrder:e.number().optional(),transcriptContentId:H.optional().nullable()});var oh=e.enum([`NOTE`,`TASK`]),sh=e.string();e.object({id:sh,workspaceId:V,name:e.string(),color:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),description:e.string(),type:oh}),e.object({id:sh,workspaceId:V,name:e.string(),color:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),description:e.string(),type:oh}),e.object({id:sh.optional(),workspaceId:V.optional(),name:e.string().optional(),color:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),description:e.string().optional(),type:oh.optional()}),e.object({noteId:K,labelId:sh,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),version:e.number(),labelType:oh}),e.object({noteId:K,labelId:sh,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),version:e.number(),labelType:oh}),e.object({noteId:K.optional(),labelId:sh.optional(),workspaceId:V.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),labelType:oh.optional()});var ch=e.string();e.object({code:ch,redirectUri:e.string().nullable(),codeChallenge:e.string().nullable(),codeChallengeMethod:e.string().nullable(),expiresAt:e.number(),userId:W,workspaceId:V,oauthClientId:Qm,scopes:Zm.array(),createdAt:e.number(),updatedAt:e.number()}),e.object({code:ch,redirectUri:e.string().optional().nullable(),codeChallenge:e.string().optional().nullable(),codeChallengeMethod:e.string().optional().nullable(),expiresAt:e.number(),userId:W,workspaceId:V,oauthClientId:Qm,scopes:Zm.array(),createdAt:e.number(),updatedAt:e.number()}),e.object({code:ch.optional(),redirectUri:e.string().optional().nullable(),codeChallenge:e.string().optional().nullable(),codeChallengeMethod:e.string().optional().nullable(),expiresAt:e.number().optional(),userId:W.optional(),workspaceId:V.optional(),oauthClientId:Qm.optional(),scopes:Zm.array().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var lh=e.string();e.object({accessToken:lh,accessTokenExpiresAt:e.number(),refreshToken:e.string().nullable(),refreshTokenExpiresAt:e.number().nullable(),userId:W,workspaceId:V,oauthClientId:Qm,scopes:Zm.array(),originatingAuthCodeId:ch.nullable(),createdAt:e.number(),updatedAt:e.number()}),e.object({accessToken:lh,accessTokenExpiresAt:e.number(),refreshToken:e.string().optional().nullable(),refreshTokenExpiresAt:e.number().optional().nullable(),userId:W,workspaceId:V,oauthClientId:Qm,scopes:Zm.array(),originatingAuthCodeId:ch.optional().nullable(),createdAt:e.number(),updatedAt:e.number()}),e.object({accessToken:lh.optional(),accessTokenExpiresAt:e.number().optional(),refreshToken:e.string().optional().nullable(),refreshTokenExpiresAt:e.number().optional().nullable(),userId:W.optional(),workspaceId:V.optional(),oauthClientId:Qm.optional(),scopes:Zm.array().optional(),originatingAuthCodeId:ch.optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var uh=e.string();e.object({id:uh,name:e.string(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:uh,name:e.string(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:uh.optional(),name:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var dh=e.string();e.object({id:dh,llmProviderId:uh,providerModelId:e.string(),name:e.string(),releasedOn:e.iso.date(),isSelectable:e.boolean(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:dh,llmProviderId:uh,providerModelId:e.string(),name:e.string(),releasedOn:e.iso.date(),isSelectable:e.boolean(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:dh.optional(),llmProviderId:uh.optional(),providerModelId:e.string().optional(),name:e.string().optional(),releasedOn:e.iso.date().optional(),isSelectable:e.boolean().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var q=e.string();e.object({id:q,workspaceId:V,name:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),firstUsedViaApiAt:e.number().nullable(),publicId:e.string(),spriteLlmModelId:dh.nullable()}),e.object({id:q,workspaceId:V,name:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),firstUsedViaApiAt:e.number().optional().nullable(),publicId:e.string(),spriteLlmModelId:dh.optional().nullable()}),e.object({id:q.optional(),workspaceId:V.optional(),name:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),firstUsedViaApiAt:e.number().optional().nullable(),publicId:e.string().optional(),spriteLlmModelId:dh.optional().nullable()});var fh=e.string();e.object({id:fh,createdAt:e.number(),updatedAt:e.number(),version:e.number(),workspaceId:V,projectId:q,personId:G,key:e.string(),name:e.string(),email:U.nullable().nullable(),lastSeenAt:e.number().nullable()}),e.object({id:fh,createdAt:e.number(),updatedAt:e.number(),version:e.number(),workspaceId:V,projectId:q,personId:G,key:e.string(),name:e.string(),email:U.nullable().optional().nullable(),lastSeenAt:e.number().optional().nullable()}),e.object({id:fh.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),workspaceId:V.optional(),projectId:q.optional(),personId:G.optional(),key:e.string().optional(),name:e.string().optional(),email:U.nullable().optional().nullable(),lastSeenAt:e.number().optional().nullable()});var ph=e.string();e.object({id:ph,createdAt:e.number(),updatedAt:e.number(),version:e.number(),workspaceId:V,projectId:q,key:e.string(),name:e.string(),lastSeenAt:e.number().nullable()}),e.object({id:ph,createdAt:e.number(),updatedAt:e.number(),version:e.number(),workspaceId:V,projectId:q,key:e.string(),name:e.string(),lastSeenAt:e.number().optional().nullable()}),e.object({id:ph.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),workspaceId:V.optional(),projectId:q.optional(),key:e.string().optional(),name:e.string().optional(),lastSeenAt:e.number().optional().nullable()});var mh=e.string();e.object({id:mh,publicId:e.string(),workspaceId:V,name:e.string(),publicKey:e.string(),createdByUserId:W,createdAt:e.number(),updatedAt:e.number(),version:e.number(),revokedAt:e.number().nullable(),revokedByUserId:W.nullable(),lastUsedAt:e.number().nullable()}),e.object({id:mh,publicId:e.string(),workspaceId:V,name:e.string(),publicKey:e.string(),createdByUserId:W,createdAt:e.number(),updatedAt:e.number(),version:e.number(),revokedAt:e.number().optional().nullable(),revokedByUserId:W.optional().nullable(),lastUsedAt:e.number().optional().nullable()}),e.object({id:mh.optional(),publicId:e.string().optional(),workspaceId:V.optional(),name:e.string().optional(),publicKey:e.string().optional(),createdByUserId:W.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),revokedAt:e.number().optional().nullable(),revokedByUserId:W.optional().nullable(),lastUsedAt:e.number().optional().nullable()});var hh=e.string();e.object({id:hh,workspaceId:V,projectId:q,projectUserId:fh,projectAccountId:ph,signingKeyId:mh,hash:e.instanceof(Uint8Array),createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number()}),e.object({id:hh,workspaceId:V,projectId:q,projectUserId:fh,projectAccountId:ph,signingKeyId:mh,hash:e.instanceof(Uint8Array),createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number()}),e.object({id:hh.optional(),workspaceId:V.optional(),projectId:q.optional(),projectUserId:fh.optional(),projectAccountId:ph.optional(),signingKeyId:mh.optional(),hash:e.instanceof(Uint8Array).optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),expiresAt:e.number().optional()});var gh=e.enum([`PENDING`,`INSTALLED`]),_h=e.string();e.object({id:_h,fizzyIntegrationId:e.lazy(()=>vh),fizzyAccountId:e.lazy(()=>yh),workspaceId:V,publicId:e.string(),name:e.string(),url:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:_h,fizzyIntegrationId:e.lazy(()=>vh),fizzyAccountId:e.lazy(()=>yh),workspaceId:V,publicId:e.string(),name:e.string(),url:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:_h.optional(),fizzyIntegrationId:e.lazy(()=>vh.optional()),fizzyAccountId:e.lazy(()=>yh.optional()),workspaceId:V.optional(),publicId:e.string().optional(),name:e.string().optional(),url:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()});var vh=e.string();e.object({id:vh,workspaceId:V,email:e.string(),state:gh,pendingAuthenticationToken:e.string().nullable(),sessionToken:e.string().nullable(),defaultFizzyBoardId:_h.nullable(),syncAccountListStartedAt:e.number().nullable(),syncAccountListFinishedAt:e.number().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),lastRequestedMagicLinkAt:e.number().nullable()}),e.object({id:vh,workspaceId:V,email:e.string(),state:gh,pendingAuthenticationToken:e.string().optional().nullable(),sessionToken:e.string().optional().nullable(),defaultFizzyBoardId:_h.optional().nullable(),syncAccountListStartedAt:e.number().optional().nullable(),syncAccountListFinishedAt:e.number().optional().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),lastRequestedMagicLinkAt:e.number().optional().nullable()}),e.object({id:vh.optional(),workspaceId:V.optional(),email:e.string().optional(),state:gh.optional(),pendingAuthenticationToken:e.string().optional().nullable(),sessionToken:e.string().optional().nullable(),defaultFizzyBoardId:_h.optional().nullable(),syncAccountListStartedAt:e.number().optional().nullable(),syncAccountListFinishedAt:e.number().optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),lastRequestedMagicLinkAt:e.number().optional().nullable()});var yh=e.string();e.object({id:yh,fizzyIntegrationId:vh,workspaceId:V,slug:e.string(),name:e.string(),syncBoardListStartedAt:e.number().nullable(),syncBoardListFinishedAt:e.number().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:yh,fizzyIntegrationId:vh,workspaceId:V,slug:e.string(),name:e.string(),syncBoardListStartedAt:e.number().optional().nullable(),syncBoardListFinishedAt:e.number().optional().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:yh.optional(),fizzyIntegrationId:vh.optional(),workspaceId:V.optional(),slug:e.string().optional(),name:e.string().optional(),syncBoardListStartedAt:e.number().optional().nullable(),syncBoardListFinishedAt:e.number().optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()});var bh=e.string();e.object({id:bh,userId:W.nullable(),workspaceId:V,pullCount:e.number(),projectUserId:fh.nullable(),projectAccountId:ph.nullable()}),e.object({id:bh,userId:W.optional().nullable(),workspaceId:V,pullCount:e.number(),projectUserId:fh.optional().nullable(),projectAccountId:ph.optional().nullable()}),e.object({id:bh.optional(),userId:W.optional().nullable(),workspaceId:V.optional(),pullCount:e.number().optional(),projectUserId:fh.optional().nullable(),projectAccountId:ph.optional().nullable()});var xh=e.enum([`GITHUB`]),Sh=e.enum([`PENDING`,`INSTALLED`,`DELETED`]),J=e.string();e.object({id:J,createdAt:e.number(),updatedAt:e.number(),workspaceId:V,type:xh,state:Sh,token:e.string().nullable(),ghInstallationId:e.number().nullable(),ghSettingsUrl:e.string().nullable(),version:e.number(),ghInstallationUrl:e.string().nullable(),name:e.string().nullable(),avatarUrl:e.string().nullable(),syncRepoListStartedAt:e.number().nullable(),syncRepoListFinishedAt:e.number().nullable()}),e.object({id:J,createdAt:e.number(),updatedAt:e.number(),workspaceId:V,type:xh,state:Sh,token:e.string().optional().nullable(),ghInstallationId:e.number().optional().nullable(),ghSettingsUrl:e.string().optional().nullable(),version:e.number(),ghInstallationUrl:e.string().optional().nullable(),name:e.string().optional().nullable(),avatarUrl:e.string().optional().nullable(),syncRepoListStartedAt:e.number().optional().nullable(),syncRepoListFinishedAt:e.number().optional().nullable()}),e.object({id:J.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),workspaceId:V.optional(),type:xh.optional(),state:Sh.optional(),token:e.string().optional().nullable(),ghInstallationId:e.number().optional().nullable(),ghSettingsUrl:e.string().optional().nullable(),version:e.number().optional(),ghInstallationUrl:e.string().optional().nullable(),name:e.string().optional().nullable(),avatarUrl:e.string().optional().nullable(),syncRepoListStartedAt:e.number().optional().nullable(),syncRepoListFinishedAt:e.number().optional().nullable()});var Ch=e.string();e.object({id:Ch,createdAt:e.number(),updatedAt:e.number(),vcsIntegrationId:J,owner:e.string(),name:e.string(),branch:e.string(),excludeAuthorEmail:e.string().array().nullable(),version:e.number(),activatedAt:e.number().nullable(),unavailableAt:e.number().nullable(),defaultBranch:e.string(),workspaceId:V,description:e.string(),url:e.string(),syncCommitListStartedAt:e.number().nullable(),syncCommitListFinishedAt:e.number().nullable(),originId:e.string().nullable(),originUpdatedAt:e.number().nullable(),syncBranchListStartedAt:e.number().nullable(),syncBranchListFinishedAt:e.number().nullable()}),e.object({id:Ch,createdAt:e.number(),updatedAt:e.number(),vcsIntegrationId:J,owner:e.string(),name:e.string(),branch:e.string(),excludeAuthorEmail:e.string().array().optional().nullable(),version:e.number(),activatedAt:e.number().optional().nullable(),unavailableAt:e.number().optional().nullable(),defaultBranch:e.string(),workspaceId:V,description:e.string(),url:e.string(),syncCommitListStartedAt:e.number().optional().nullable(),syncCommitListFinishedAt:e.number().optional().nullable(),originId:e.string().optional().nullable(),originUpdatedAt:e.number().optional().nullable(),syncBranchListStartedAt:e.number().optional().nullable(),syncBranchListFinishedAt:e.number().optional().nullable()}),e.object({id:Ch.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),vcsIntegrationId:J.optional(),owner:e.string().optional(),name:e.string().optional(),branch:e.string().optional(),excludeAuthorEmail:e.string().array().optional().nullable(),version:e.number().optional(),activatedAt:e.number().optional().nullable(),unavailableAt:e.number().optional().nullable(),defaultBranch:e.string().optional(),workspaceId:V.optional(),description:e.string().optional(),url:e.string().optional(),syncCommitListStartedAt:e.number().optional().nullable(),syncCommitListFinishedAt:e.number().optional().nullable(),originId:e.string().optional().nullable(),originUpdatedAt:e.number().optional().nullable(),syncBranchListStartedAt:e.number().optional().nullable(),syncBranchListFinishedAt:e.number().optional().nullable()});var wh=e.string();e.object({id:wh,createdAt:e.number(),updatedAt:e.number(),version:e.number(),vcsRepoId:Ch,vcsIntegrationId:J,workspaceId:V,name:e.string(),commitSha:e.string()}),e.object({id:wh,createdAt:e.number(),updatedAt:e.number(),version:e.number(),vcsRepoId:Ch,vcsIntegrationId:J,workspaceId:V,name:e.string(),commitSha:e.string()}),e.object({id:wh.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),vcsRepoId:Ch.optional(),vcsIntegrationId:J.optional(),workspaceId:V.optional(),name:e.string().optional(),commitSha:e.string().optional()});var Th=e.enum([`SUGGESTED`,`APPROVED`,`REJECTED`]);e.object({noteIdA:K,noteIdB:K,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),distance:e.number().nullable(),version:e.number(),status:Th,createdByUserId:W.nullable(),lastModifiedByUserId:W.nullable(),lastModifiedAt:e.number().nullable()}),e.object({noteIdA:K,noteIdB:K,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),distance:e.number().optional().nullable(),version:e.number(),status:Th,createdByUserId:W.optional().nullable(),lastModifiedByUserId:W.optional().nullable(),lastModifiedAt:e.number().optional().nullable()}),e.object({noteIdA:K.optional(),noteIdB:K.optional(),workspaceId:V.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),distance:e.number().optional().nullable(),version:e.number().optional(),status:Th.optional(),createdByUserId:W.optional().nullable(),lastModifiedByUserId:W.optional().nullable(),lastModifiedAt:e.number().optional().nullable()});var Eh=e.string();e.object({id:Eh,workspaceId:V,projectId:q,key:e.string(),name:e.string(),toolList:e.array(e.json()),createdAt:e.number(),updatedAt:e.number(),description:e.string(),version:e.number()}),e.object({id:Eh,workspaceId:V,projectId:q,key:e.string(),name:e.string(),toolList:e.array(e.json()),createdAt:e.number(),updatedAt:e.number(),description:e.string(),version:e.number()}),e.object({id:Eh.optional(),workspaceId:V.optional(),projectId:q.optional(),key:e.string().optional(),name:e.string().optional(),toolList:e.array(e.json()).optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),description:e.string().optional(),version:e.number().optional()});var Y=e.string();e.object({id:Y,workspaceId:V,version:e.number(),createdAt:e.number(),updatedAt:e.number(),name:e.string(),projectId:q,surfaceId:Eh,ownedByPersonId:G}),e.object({id:Y,workspaceId:V,version:e.number(),createdAt:e.number(),updatedAt:e.number(),name:e.string(),projectId:q,surfaceId:Eh,ownedByPersonId:G}),e.object({id:Y.optional(),workspaceId:V.optional(),version:e.number().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),name:e.string().optional(),projectId:q.optional(),surfaceId:Eh.optional(),ownedByPersonId:G.optional()});var Dh=e.enum([`PENDING`,`IN_PROGRESS`,`READY`,`ERROR`,`CANCELED`]),Oh=e.string();e.object({id:Oh,workspaceId:V,version:e.number(),createdAt:e.number(),updatedAt:e.number(),spriteId:Y,parentSpriteBuildId:Oh.nullable(),prompt:e.string(),artifactUrl:e.string().nullable(),sourceUrl:e.string().nullable(),status:Dh,startedAt:e.number().nullable(),stoppedAt:e.number().nullable(),error:e.record(e.string(),e.json()).nullable(),toolList:e.array(e.json()),reasoningSummary:e.string().nullable(),publishedAt:e.number().nullable(),createdByPersonId:G,agentProvider:e.string(),agentModel:e.string(),agentInputTokens:e.number(),agentOutputTokens:e.number(),agentCacheReadTokens:e.number(),agentCacheWriteTokens:e.number(),agentEstimatedCostUsd:e.number(),cancelRequestedAt:e.number().nullable()}),e.object({id:Oh,workspaceId:V,version:e.number(),createdAt:e.number(),updatedAt:e.number(),spriteId:Y,parentSpriteBuildId:Oh.optional().nullable(),prompt:e.string(),artifactUrl:e.string().optional().nullable(),sourceUrl:e.string().optional().nullable(),status:Dh,startedAt:e.number().optional().nullable(),stoppedAt:e.number().optional().nullable(),error:e.record(e.string(),e.json()).optional().nullable(),toolList:e.array(e.json()),reasoningSummary:e.string().optional().nullable(),publishedAt:e.number().optional().nullable(),createdByPersonId:G,agentProvider:e.string(),agentModel:e.string(),agentInputTokens:e.number(),agentOutputTokens:e.number(),agentCacheReadTokens:e.number(),agentCacheWriteTokens:e.number(),agentEstimatedCostUsd:e.number(),cancelRequestedAt:e.number().optional().nullable()}),e.object({id:Oh.optional(),workspaceId:V.optional(),version:e.number().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),spriteId:Y.optional(),parentSpriteBuildId:Oh.optional().nullable(),prompt:e.string().optional(),artifactUrl:e.string().optional().nullable(),sourceUrl:e.string().optional().nullable(),status:Dh.optional(),startedAt:e.number().optional().nullable(),stoppedAt:e.number().optional().nullable(),error:e.record(e.string(),e.json()).optional().nullable(),toolList:e.array(e.json()).optional(),reasoningSummary:e.string().optional().nullable(),publishedAt:e.number().optional().nullable(),createdByPersonId:G.optional(),agentProvider:e.string().optional(),agentModel:e.string().optional(),agentInputTokens:e.number().optional(),agentOutputTokens:e.number().optional(),agentCacheReadTokens:e.number().optional(),agentCacheWriteTokens:e.number().optional(),agentEstimatedCostUsd:e.number().optional(),cancelRequestedAt:e.number().optional().nullable()});var kh=e.string();e.object({id:kh,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),snapshot:e.record(e.string(),e.json()).nullable()}),e.object({id:kh,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),snapshot:e.record(e.string(),e.json()).optional().nullable()}),e.object({id:kh.optional(),workspaceId:V.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),snapshot:e.record(e.string(),e.json()).optional().nullable()});var Ah=e.enum(`DOCUMENT_COMMENT_CREATE.DOCUMENT_COMMENT_DELETE.DOCUMENT_COMMENT_RESOLVE.DOCUMENT_COMMENT_UPDATE.DOCUMENT_CREATE.DOCUMENT_DELETE.DOCUMENT_PERSON_MENTION.DOCUMENT_UPDATE_BLOCK_CONTENT.DOCUMENT_UPDATE_STATUS.DOCUMENT_UPDATE_TITLE.NOTE_COMMENT_CREATE.NOTE_COMMENT_DELETE.NOTE_COMMENT_RESOLVE.NOTE_COMMENT_UPDATE.NOTE_CREATE.NOTE_PERSON_MENTION.NOTE_UPDATE_CONTENT.NOTE_UPDATE_LABEL.NOTE_UPDATE_PERSON.NOTE_UPDATE_REFERENCE.NOTE_UPDATE_STATUS.NOTE_UPDATE_TITLE.SEQUENCE_DOCUMENT_DELETE.SEQUENCE_DOCUMENT_INSERT.SEQUENCE_DOCUMENT_STATUS_IN.SEQUENCE_DOCUMENT_STATUS_OUT.SEQUENCE_DOCUMENT_UPDATE_ORDER.SEQUENCE_COMMENT_CREATE.SEQUENCE_COMMENT_DELETE.SEQUENCE_COMMENT_RESOLVE.SEQUENCE_COMMENT_UPDATE.SEQUENCE_PERSON_MENTION.SPRITE_CREATE.SPRITE_COMMENT_CREATE`.split(`.`)),jh=e.enum([`CANCELED`,`IDEA`,`DEVELOPMENT`,`RELEASED`,`DRAFT`,`ARCHIVED`]),X=e.string();e.object({id:X,title:e.string(),status:jh,createdAt:e.number(),updatedAt:e.number(),publicId:e.number(),createdByUserId:W,workspaceId:V,vcsTagList:e.string().array(),archivedAt:e.number().nullable(),archivedByUserId:W.nullable(),version:e.number(),lastModifiedAt:e.number(),releasedAt:e.number().nullable(),ownedByPersonId:G}),e.object({id:X,title:e.string(),status:jh,createdAt:e.number(),updatedAt:e.number(),publicId:e.number(),createdByUserId:W,workspaceId:V,vcsTagList:e.string().array(),archivedAt:e.number().optional().nullable(),archivedByUserId:W.optional().nullable(),version:e.number(),lastModifiedAt:e.number(),releasedAt:e.number().optional().nullable(),ownedByPersonId:G}),e.object({id:X.optional(),title:e.string().optional(),status:jh.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),publicId:e.number().optional(),createdByUserId:W.optional(),workspaceId:V.optional(),vcsTagList:e.string().array().optional(),archivedAt:e.number().optional().nullable(),archivedByUserId:W.optional().nullable(),version:e.number().optional(),lastModifiedAt:e.number().optional(),releasedAt:e.number().optional().nullable(),ownedByPersonId:G.optional()});var Mh=e.enum([`USER`,`STATUS`,`WISH`]),Nh=e.enum([`NONE`,`STATUS`]),Z=e.string();e.object({id:Z,createdAt:e.number(),updatedAt:e.number(),name:e.string(),workspaceId:V,publicId:e.string(),type:Mh,status:jh.nullable().nullable(),version:e.number(),icon:e.string(),pinned:e.number().nullable(),groupBy:Nh,ownedByPersonId:G.nullable()}),e.object({id:Z,createdAt:e.number(),updatedAt:e.number(),name:e.string(),workspaceId:V,publicId:e.string(),type:Mh,status:jh.nullable().optional().nullable(),version:e.number(),icon:e.string(),pinned:e.number().optional().nullable(),groupBy:Nh,ownedByPersonId:G.optional().nullable()}),e.object({id:Z.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),name:e.string().optional(),workspaceId:V.optional(),publicId:e.string().optional(),type:Mh.optional(),status:jh.nullable().optional().nullable(),version:e.number().optional(),icon:e.string().optional(),pinned:e.number().optional().nullable(),groupBy:Nh.optional(),ownedByPersonId:G.optional().nullable()});var Ph=e.string();e.object({id:Ph,workspaceId:V,type:Ah,detail:e.record(e.string(),e.json()),actionedAt:e.number(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),documentId:X.nullable(),noteId:K.nullable(),sequenceId:Z.nullable(),spriteId:Y.nullable(),actionedByPersonId:G}),e.object({id:Ph,workspaceId:V,type:Ah,detail:e.record(e.string(),e.json()),actionedAt:e.number(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),documentId:X.optional().nullable(),noteId:K.optional().nullable(),sequenceId:Z.optional().nullable(),spriteId:Y.optional().nullable(),actionedByPersonId:G}),e.object({id:Ph.optional(),workspaceId:V.optional(),type:Ah.optional(),detail:e.record(e.string(),e.json()).optional(),actionedAt:e.number().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),documentId:X.optional().nullable(),noteId:K.optional().nullable(),sequenceId:Z.optional().nullable(),spriteId:Y.optional().nullable(),actionedByPersonId:G.optional()});var Fh=e.enum([`DOCUMENT`,`NOTE`,`SEQUENCE`,`SPRITE`]),Ih=e.enum([`TEXT`,`DRAWING`]),Lh=e.enum([`UNKNOWN`]),Rh=e.string();e.object({id:Rh,sortOrder:e.number(),documentId:X,createdAt:e.number(),updatedAt:e.number(),type:Ih,lockedAt:e.number().nullable(),version:e.number(),lastModifiedAt:e.number(),workspaceId:V,archivedAt:e.number().nullable(),archivedByUserId:W.nullable(),flagList:Lh.array(),title:e.string(),contentId:H.nullable(),canvasId:kh.nullable(),lastModifiedByUserId:W}),e.object({id:Rh,sortOrder:e.number(),documentId:X,createdAt:e.number(),updatedAt:e.number(),type:Ih,lockedAt:e.number().optional().nullable(),version:e.number(),lastModifiedAt:e.number(),workspaceId:V,archivedAt:e.number().optional().nullable(),archivedByUserId:W.optional().nullable(),flagList:Lh.array(),title:e.string(),contentId:H.optional().nullable(),canvasId:kh.optional().nullable(),lastModifiedByUserId:W}),e.object({id:Rh.optional(),sortOrder:e.number().optional(),documentId:X.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),type:Ih.optional(),lockedAt:e.number().optional().nullable(),version:e.number().optional(),lastModifiedAt:e.number().optional(),workspaceId:V.optional(),archivedAt:e.number().optional().nullable(),archivedByUserId:W.optional().nullable(),flagList:Lh.array().optional(),title:e.string().optional(),contentId:H.optional().nullable(),canvasId:kh.optional().nullable(),lastModifiedByUserId:W.optional()});var Q=e.string();e.object({id:Q,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),version:e.number(),title:e.string(),contentId:H,completedAt:e.number().nullable(),createdByPersonId:G}),e.object({id:Q,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),version:e.number(),title:e.string(),contentId:H,completedAt:e.number().optional().nullable(),createdByPersonId:G}),e.object({id:Q.optional(),workspaceId:V.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),title:e.string().optional(),contentId:H.optional(),completedAt:e.number().optional().nullable(),createdByPersonId:G.optional()});var zh=e.string();e.object({id:zh,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),version:e.number(),openedAt:e.number(),openedByUserId:W,resolvedAt:e.number().nullable(),resolvedByUserId:W.nullable(),documentId:X.nullable(),blockId:Rh.nullable(),sequenceId:Z.nullable(),eventId:Ph.nullable(),noteId:K.nullable(),spriteId:Y.nullable(),taskId:Q.nullable()}),e.object({id:zh,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),version:e.number(),openedAt:e.number(),openedByUserId:W,resolvedAt:e.number().optional().nullable(),resolvedByUserId:W.optional().nullable(),documentId:X.optional().nullable(),blockId:Rh.optional().nullable(),sequenceId:Z.optional().nullable(),eventId:Ph.optional().nullable(),noteId:K.optional().nullable(),spriteId:Y.optional().nullable(),taskId:Q.optional().nullable()}),e.object({id:zh.optional(),workspaceId:V.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),openedAt:e.number().optional(),openedByUserId:W.optional(),resolvedAt:e.number().optional().nullable(),resolvedByUserId:W.optional().nullable(),documentId:X.optional().nullable(),blockId:Rh.optional().nullable(),sequenceId:Z.optional().nullable(),eventId:Ph.optional().nullable(),noteId:K.optional().nullable(),spriteId:Y.optional().nullable(),taskId:Q.optional().nullable()});var Bh=e.string();e.object({id:Bh,createdAt:e.number(),updatedAt:e.number(),postedAt:e.number(),userId:W,workspaceId:V,version:e.number(),contentId:H,commentThreadId:zh}),e.object({id:Bh,createdAt:e.number(),updatedAt:e.number(),postedAt:e.number(),userId:W,workspaceId:V,version:e.number(),contentId:H,commentThreadId:zh}),e.object({id:Bh.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),postedAt:e.number().optional(),userId:W.optional(),workspaceId:V.optional(),version:e.number().optional(),contentId:H.optional(),commentThreadId:zh.optional()});var Vh=e.string();e.object({id:Vh,workspaceId:V,userId:W,eventId:Ph,readAt:e.number().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),type:Fh,documentId:X.nullable(),noteId:K.nullable(),sequenceId:Z.nullable(),commentId:Bh.nullable(),spriteId:Y.nullable(),commentThreadId:zh.nullable()}),e.object({id:Vh,workspaceId:V,userId:W,eventId:Ph,readAt:e.number().optional().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),type:Fh,documentId:X.optional().nullable(),noteId:K.optional().nullable(),sequenceId:Z.optional().nullable(),commentId:Bh.optional().nullable(),spriteId:Y.optional().nullable(),commentThreadId:zh.optional().nullable()}),e.object({id:Vh.optional(),workspaceId:V.optional(),userId:W.optional(),eventId:Ph.optional(),readAt:e.number().optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),type:Fh.optional(),documentId:X.optional().nullable(),noteId:K.optional().nullable(),sequenceId:Z.optional().nullable(),commentId:Bh.optional().nullable(),spriteId:Y.optional().nullable(),commentThreadId:zh.optional().nullable()});var Hh=e.string();e.object({id:Hh,userId:W,contentId:H,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),version:e.number(),state:e.instanceof(Uint8Array)}),e.object({id:Hh,userId:W,contentId:H,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),version:e.number(),state:e.instanceof(Uint8Array)}),e.object({id:Hh.optional(),userId:W.optional(),contentId:H.optional(),workspaceId:V.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),state:e.instanceof(Uint8Array).optional()});var Uh=e.string();e.object({id:Uh,createdAt:e.number(),record:e.record(e.string(),e.json())}),e.object({id:Uh,createdAt:e.number(),record:e.record(e.string(),e.json())}),e.object({id:Uh.optional(),createdAt:e.number().optional(),record:e.record(e.string(),e.json()).optional()}),e.object({spriteId:Y,projectAccountId:ph,workspaceId:V,projectId:q,createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({spriteId:Y,projectAccountId:ph,workspaceId:V,projectId:q,createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({spriteId:Y.optional(),projectAccountId:ph.optional(),workspaceId:V.optional(),projectId:q.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()}),e.object({projectAccountId:ph,projectUserId:fh,createdAt:e.number(),updatedAt:e.number(),version:e.number(),workspaceId:V,projectId:q}),e.object({projectAccountId:ph,projectUserId:fh,createdAt:e.number(),updatedAt:e.number(),version:e.number(),workspaceId:V,projectId:q}),e.object({projectAccountId:ph.optional(),projectUserId:fh.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),workspaceId:V.optional(),projectId:q.optional()});var Wh=e.string();e.object({id:Wh,workspaceId:V,userId:W,emoji:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),commentId:Bh.nullable(),noteId:K.nullable()}),e.object({id:Wh,workspaceId:V,userId:W,emoji:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),commentId:Bh.optional().nullable(),noteId:K.optional().nullable()}),e.object({id:Wh.optional(),workspaceId:V.optional(),userId:W.optional(),emoji:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),commentId:Bh.optional().nullable(),noteId:K.optional().nullable()}),e.object({taskId:Q,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),version:e.number(),sortOrder:e.number()}),e.object({taskId:Q,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),version:e.number(),sortOrder:e.number()}),e.object({taskId:Q.optional(),workspaceId:V.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),sortOrder:e.number().optional()});var Gh=e.string();e.object({id:Gh,workspaceId:V,token:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:Gh,workspaceId:V,token:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:Gh.optional(),workspaceId:V.optional(),token:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()});var Kh=e.string();e.object({id:Kh,workspaceId:V,userId:W,hash:e.instanceof(Uint8Array),createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number()}),e.object({id:Kh,workspaceId:V,userId:W,hash:e.instanceof(Uint8Array),createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number()}),e.object({id:Kh.optional(),workspaceId:V.optional(),userId:W.optional(),hash:e.instanceof(Uint8Array).optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),expiresAt:e.number().optional()});var qh=e.enum([`STEP_STARTED`,`STEP_COMPLETED`,`STEP_FAILED`,`EXEC_STARTED`,`EXEC_COMPLETED`,`EXEC_FAILED`,`FETCH_STARTED`,`FETCH_COMPLETED`,`FETCH_FAILED`,`AGENT_STARTED`,`AGENT_COMPLETED`,`AGENT_TOOL_STARTED`,`AGENT_TOOL_COMPLETED`,`AGENT_TOOL_FAILED`,`AGENT_META`,`AGENT_MESSAGE`,`AGENT_THOUGHT`,`AGENT_USAGE`]),Jh=e.string();e.object({id:Jh,workspaceId:V,spriteBuildId:Oh,createdAt:e.number(),updatedAt:e.number(),version:e.number(),type:qh,detail:e.record(e.string(),e.json()),actionedAt:e.number()}),e.object({id:Jh,workspaceId:V,spriteBuildId:Oh,createdAt:e.number(),updatedAt:e.number(),version:e.number(),type:qh,detail:e.record(e.string(),e.json()),actionedAt:e.number()}),e.object({id:Jh.optional(),workspaceId:V.optional(),spriteBuildId:Oh.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),type:qh.optional(),detail:e.record(e.string(),e.json()).optional(),actionedAt:e.number().optional()}),e.object({blockId:Rh,userId:W,workspaceId:V,lastReadAt:e.number(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({blockId:Rh,userId:W,workspaceId:V,lastReadAt:e.number(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({blockId:Rh.optional(),userId:W.optional(),workspaceId:V.optional(),lastReadAt:e.number().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()});var Yh=e.enum([`NOTE`,`DOCUMENT`]),Xh=e.string();e.object({id:Xh,workspaceId:V,userId:W,type:Yh,matchAll:e.boolean(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:Xh,workspaceId:V,userId:W,type:Yh,matchAll:e.boolean(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:Xh.optional(),workspaceId:V.optional(),userId:W.optional(),type:Yh.optional(),matchAll:e.boolean().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()});var Zh=e.enum([`ADMIN`,`GUEST`,`ARCHIVED`,`DEMO`]);e.object({workspaceId:V,userId:W,createdAt:e.number(),updatedAt:e.number(),role:Zh,version:e.number(),personId:G,lastReadNotificationsAt:e.number().nullable()}),e.object({workspaceId:V,userId:W,createdAt:e.number(),updatedAt:e.number(),role:Zh,version:e.number(),personId:G,lastReadNotificationsAt:e.number().optional().nullable()}),e.object({workspaceId:V.optional(),userId:W.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),role:Zh.optional(),version:e.number().optional(),personId:G.optional(),lastReadNotificationsAt:e.number().optional().nullable()});var Qh=e.string();e.object({id:Qh,workspaceId:V,name:e.string(),url:e.string(),secret:e.string(),eventTypeList:Ah.array(),createdByPersonId:G,createdAt:e.number(),updatedAt:e.number()}),e.object({id:Qh,workspaceId:V,name:e.string(),url:e.string(),secret:e.string(),eventTypeList:Ah.array(),createdByPersonId:G,createdAt:e.number(),updatedAt:e.number()}),e.object({id:Qh.optional(),workspaceId:V.optional(),name:e.string().optional(),url:e.string().optional(),secret:e.string().optional(),eventTypeList:Ah.array().optional(),createdByPersonId:G.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var $h=e.enum([`FEATURE`,`FIX`,`RELEASE`,`CHORE`]),eg=e.string();e.object({id:eg,createdAt:e.number(),updatedAt:e.number(),version:e.number(),vcsIntegrationId:J,workspaceId:V,name:e.string(),email:e.string(),avatarUrl:e.string().nullable()}),e.object({id:eg,createdAt:e.number(),updatedAt:e.number(),version:e.number(),vcsIntegrationId:J,workspaceId:V,name:e.string(),email:e.string(),avatarUrl:e.string().optional().nullable()}),e.object({id:eg.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),vcsIntegrationId:J.optional(),workspaceId:V.optional(),name:e.string().optional(),email:e.string().optional(),avatarUrl:e.string().optional().nullable()});var tg=e.string();e.object({id:tg,createdAt:e.number(),updatedAt:e.number(),sha:e.string(),vcsRepoId:Ch,url:e.string(),message:e.string(),parentShaList:e.string().array().nullable(),version:e.number(),authoredAt:e.number().nullable(),committedAt:e.number().nullable(),vcsIntegrationId:J,workspaceId:V,type:$h,subject:e.string(),scope:e.string().nullable(),authorId:eg.nullable(),committerId:eg.nullable()}),e.object({id:tg,createdAt:e.number(),updatedAt:e.number(),sha:e.string(),vcsRepoId:Ch,url:e.string(),message:e.string(),parentShaList:e.string().array().optional().nullable(),version:e.number(),authoredAt:e.number().optional().nullable(),committedAt:e.number().optional().nullable(),vcsIntegrationId:J,workspaceId:V,type:$h,subject:e.string(),scope:e.string().optional().nullable(),authorId:eg.optional().nullable(),committerId:eg.optional().nullable()}),e.object({id:tg.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),sha:e.string().optional(),vcsRepoId:Ch.optional(),url:e.string().optional(),message:e.string().optional(),parentShaList:e.string().array().optional().nullable(),version:e.number().optional(),authoredAt:e.number().optional().nullable(),committedAt:e.number().optional().nullable(),vcsIntegrationId:J.optional(),workspaceId:V.optional(),type:$h.optional(),subject:e.string().optional(),scope:e.string().optional().nullable(),authorId:eg.optional().nullable(),committerId:eg.optional().nullable()}),e.object({vcsCommitId:tg,documentId:X,createdAt:e.number(),updatedAt:e.number(),description:e.string(),version:e.number(),vcsIntegrationId:J,workspaceId:V}),e.object({vcsCommitId:tg,documentId:X,createdAt:e.number(),updatedAt:e.number(),description:e.string(),version:e.number(),vcsIntegrationId:J,workspaceId:V}),e.object({vcsCommitId:tg.optional(),documentId:X.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),description:e.string().optional(),version:e.number().optional(),vcsIntegrationId:J.optional(),workspaceId:V.optional()}),e.object({documentId:X,userId:W,workspaceId:V,lastReadAt:e.number(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({documentId:X,userId:W,workspaceId:V,lastReadAt:e.number(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({documentId:X.optional(),userId:W.optional(),workspaceId:V.optional(),lastReadAt:e.number().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()}),e.object({personId:G,taskId:Q,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),version:e.number(),sortOrder:e.number(),date:e.iso.date()}),e.object({personId:G,taskId:Q,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),version:e.number(),sortOrder:e.number(),date:e.iso.date()}),e.object({personId:G.optional(),taskId:Q.optional(),workspaceId:V.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),sortOrder:e.number().optional(),date:e.iso.date().optional()});var ng=e.enum([`DOCUMENT`,`NOTE`,`SEQUENCE`,`NEW_NOTE`,`SPRITE`,`COMMENT_THREAD`]),rg=e.string();e.object({id:rg,workspaceId:V,userId:W,type:ng,noteId:K.nullable(),documentId:X.nullable(),sequenceId:Z.nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),spriteId:Y.nullable(),commentThreadId:zh.nullable()}),e.object({id:rg,workspaceId:V,userId:W,type:ng,noteId:K.optional().nullable(),documentId:X.optional().nullable(),sequenceId:Z.optional().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),spriteId:Y.optional().nullable(),commentThreadId:zh.optional().nullable()}),e.object({id:rg.optional(),workspaceId:V.optional(),userId:W.optional(),type:ng.optional(),noteId:K.optional().nullable(),documentId:X.optional().nullable(),sequenceId:Z.optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),spriteId:Y.optional().nullable(),commentThreadId:zh.optional().nullable()});var ig=e.string();e.object({id:ig,workspaceId:V,email:U,lastSentAt:e.number().nullable(),invitedByUserId:W,createdAt:e.number(),updatedAt:e.number(),version:e.number(),token:e.string().nullable()}),e.object({id:ig,workspaceId:V,email:U,lastSentAt:e.number().optional().nullable(),invitedByUserId:W,createdAt:e.number(),updatedAt:e.number(),version:e.number(),token:e.string().optional().nullable()}),e.object({id:ig.optional(),workspaceId:V.optional(),email:U.optional(),lastSentAt:e.number().optional().nullable(),invitedByUserId:W.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),token:e.string().optional().nullable()});var ag=e.string();e.object({id:ag,workspaceId:V,projectId:q,spriteId:Y,messageList:e.array(e.json()),createdAt:e.number(),updatedAt:e.number()}),e.object({id:ag,workspaceId:V,projectId:q,spriteId:Y,messageList:e.array(e.json()),createdAt:e.number(),updatedAt:e.number()}),e.object({id:ag.optional(),workspaceId:V.optional(),projectId:q.optional(),spriteId:Y.optional(),messageList:e.array(e.json()).optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var og=e.string();e.object({id:og,clientGroupId:bh,lastMutationId:e.number(),version:e.number()}),e.object({id:og,clientGroupId:bh,lastMutationId:e.number(),version:e.number()}),e.object({id:og.optional(),clientGroupId:bh.optional(),lastMutationId:e.number().optional(),version:e.number().optional()}),e.object({documentIdA:X,documentIdB:X,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),distance:e.number().nullable(),version:e.number(),status:Th,createdByUserId:W.nullable(),lastModifiedByUserId:W.nullable(),lastModifiedAt:e.number().nullable()}),e.object({documentIdA:X,documentIdB:X,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),distance:e.number().optional().nullable(),version:e.number(),status:Th,createdByUserId:W.optional().nullable(),lastModifiedByUserId:W.optional().nullable(),lastModifiedAt:e.number().optional().nullable()}),e.object({documentIdA:X.optional(),documentIdB:X.optional(),workspaceId:V.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),distance:e.number().optional().nullable(),version:e.number().optional(),status:Th.optional(),createdByUserId:W.optional().nullable(),lastModifiedByUserId:W.optional().nullable(),lastModifiedAt:e.number().optional().nullable()});var sg=e.string();e.object({id:sg,userId:W,createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number(),twoFactorVerifiedAt:e.number().nullable()}),e.object({id:sg,userId:W,createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number(),twoFactorVerifiedAt:e.number().optional().nullable()}),e.object({id:sg.optional(),userId:W.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),expiresAt:e.number().optional(),twoFactorVerifiedAt:e.number().optional().nullable()});var cg=e.string();e.object({id:cg,workspaceId:V,hash:e.instanceof(Uint8Array),createdAt:e.number(),updatedAt:e.number(),contentHash:e.instanceof(Uint8Array),contentId:H,offset:e.number(),size:e.number(),tokenCount:e.number(),plaintext:e.string()}),e.object({id:cg,workspaceId:V,hash:e.instanceof(Uint8Array),createdAt:e.number(),updatedAt:e.number(),contentHash:e.instanceof(Uint8Array),contentId:H,offset:e.number(),size:e.number(),tokenCount:e.number(),plaintext:e.string()}),e.object({id:cg.optional(),workspaceId:V.optional(),hash:e.instanceof(Uint8Array).optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),contentHash:e.instanceof(Uint8Array).optional(),contentId:H.optional(),offset:e.number().optional(),size:e.number().optional(),tokenCount:e.number().optional(),plaintext:e.string().optional()}),e.object({llmProviderId:uh,encryptedValue:e.string(),plaintextSuffix:e.string(),createdAt:e.number(),updatedAt:e.number()}),e.object({llmProviderId:uh,encryptedValue:e.string(),plaintextSuffix:e.string(),createdAt:e.number(),updatedAt:e.number()}),e.object({llmProviderId:uh.optional(),encryptedValue:e.string().optional(),plaintextSuffix:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var lg=e.enum([`IS_IN`,`IS_NOT_IN`]),ug=e.string();e.object({id:ug,filterId:Xh,workspaceId:V,field:e.string(),comparator:lg,value:e.record(e.string(),e.json()),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:ug,filterId:Xh,workspaceId:V,field:e.string(),comparator:lg,value:e.record(e.string(),e.json()),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:ug.optional(),filterId:Xh.optional(),workspaceId:V.optional(),field:e.string().optional(),comparator:lg.optional(),value:e.record(e.string(),e.json()).optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()}),e.object({spriteIdA:Y,spriteIdB:Y,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),distance:e.number().nullable(),version:e.number(),status:Th,createdByUserId:W.nullable(),lastModifiedByUserId:W.nullable(),lastModifiedAt:e.number().nullable()}),e.object({spriteIdA:Y,spriteIdB:Y,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),distance:e.number().optional().nullable(),version:e.number(),status:Th,createdByUserId:W.optional().nullable(),lastModifiedByUserId:W.optional().nullable(),lastModifiedAt:e.number().optional().nullable()}),e.object({spriteIdA:Y.optional(),spriteIdB:Y.optional(),workspaceId:V.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),distance:e.number().optional().nullable(),version:e.number().optional(),status:Th.optional(),createdByUserId:W.optional().nullable(),lastModifiedByUserId:W.optional().nullable(),lastModifiedAt:e.number().optional().nullable()}),e.object({taskId:Q,labelId:sh,labelType:oh,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({taskId:Q,labelId:sh,labelType:oh,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({taskId:Q.optional(),labelId:sh.optional(),labelType:oh.optional(),workspaceId:V.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()});var dg=e.enum([`SIGNUP_REQUEST`,`SIGNUP_ATTEMPT_TOKEN`,`SIGNUP_SUCCESS`,`LOGIN_VIA_GOOGLE_SUCCESS`,`LOGIN_VIA_PASSWORD_ATTEMPT`,`LOGIN_VIA_PASSWORD_SUCCESS`,`RESET_PASSWORD_REQUEST`,`RESET_PASSWORD_ATTEMPT_TOKEN`,`RESET_PASSWORD_SUCCESS`,`PASSWORD_CHANGE`,`TOTP_ENABLE`,`TOTP_DISABLE`,`TOTP_VERIFY_ATTEMPT`,`TOTP_VERIFY_SUCCESS`,`RECOVERY_CODE_REGENERATED`,`RECOVERY_CODE_ATTEMPT`,`RECOVERY_CODE_SUCCESS`,`VALIDATE_INVITE_LINK_ATTEMPT`,`VALIDATE_INVITE_LINK_SUCCESS`,`VALIDATE_INVITATION_ATTEMPT`,`VALIDATE_INVITATION_SUCCESS`]),fg=e.string();e.object({id:fg,type:dg,userId:W.nullable(),email:U.nullable().nullable(),clientAddress:e.string(),userAgent:e.string(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:fg,type:dg,userId:W.optional().nullable(),email:U.nullable().optional().nullable(),clientAddress:e.string(),userAgent:e.string(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:fg.optional(),type:dg.optional(),userId:W.optional().nullable(),email:U.nullable().optional().nullable(),clientAddress:e.string().optional(),userAgent:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var pg=U;e.object({workspaceId:V,personId:G,email:pg,createdAt:e.number(),updatedAt:e.number(),isPrimary:e.boolean()}),e.object({workspaceId:V,personId:G,email:pg,createdAt:e.number(),updatedAt:e.number(),isPrimary:e.boolean()}),e.object({workspaceId:V.optional(),personId:G.optional(),email:pg.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),isPrimary:e.boolean().optional()}),e.object({documentId:X,noteId:K,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),distance:e.number().nullable(),version:e.number(),status:Th,createdByUserId:W.nullable(),lastModifiedByUserId:W.nullable(),lastModifiedAt:e.number().nullable()}),e.object({documentId:X,noteId:K,workspaceId:V,createdAt:e.number(),updatedAt:e.number(),distance:e.number().optional().nullable(),version:e.number(),status:Th,createdByUserId:W.optional().nullable(),lastModifiedByUserId:W.optional().nullable(),lastModifiedAt:e.number().optional().nullable()}),e.object({documentId:X.optional(),noteId:K.optional(),workspaceId:V.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),distance:e.number().optional().nullable(),version:e.number().optional(),status:Th.optional(),createdByUserId:W.optional().nullable(),lastModifiedByUserId:W.optional().nullable(),lastModifiedAt:e.number().optional().nullable()});var mg=e.string();e.object({id:mg,workspaceId:V,name:e.string(),hash:e.instanceof(Uint8Array),createdByUserId:W,lastUsedAt:e.number().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),scopeList:Zm.array()}),e.object({id:mg,workspaceId:V,name:e.string(),hash:e.instanceof(Uint8Array),createdByUserId:W,lastUsedAt:e.number().optional().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),scopeList:Zm.array()}),e.object({id:mg.optional(),workspaceId:V.optional(),name:e.string().optional(),hash:e.instanceof(Uint8Array).optional(),createdByUserId:W.optional(),lastUsedAt:e.number().optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),scopeList:Zm.array().optional()});var hg=e.enum([`MXBAI_EMBED_LARGE_V1`,`TEST`,`STELLA_EN_400M_V5`,`GTE_MULTILINGUAL_BASE`]),gg=e.enum([`DIM_1024`,`DIM_768`]),_g=e.string();e.object({id:_g,createdAt:e.number(),updatedAt:e.number(),hash:e.instanceof(Uint8Array),model:hg,dimension:gg,vector1024:e.array(e.number()).nullable(),vector768:e.array(e.number()).nullable()}),e.object({id:_g,createdAt:e.number(),updatedAt:e.number(),hash:e.instanceof(Uint8Array),model:hg,dimension:gg,vector1024:e.array(e.number()).optional().nullable(),vector768:e.array(e.number()).optional().nullable()}),e.object({id:_g.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),hash:e.instanceof(Uint8Array).optional(),model:hg.optional(),dimension:gg.optional(),vector1024:e.array(e.number()).optional().nullable(),vector768:e.array(e.number()).optional().nullable()});var vg=e.string(),yg=e.string(),bg=e.string();e.object({tableName:vg,idA:yg,idB:bg,workspaceId:V,deletedAt:e.number(),version:e.number()}),e.object({tableName:vg,idA:yg,idB:bg,workspaceId:V,deletedAt:e.number(),version:e.number()}),e.object({tableName:vg.optional(),idA:yg.optional(),idB:bg.optional(),workspaceId:V.optional(),deletedAt:e.number().optional(),version:e.number().optional()}),e.object({sequenceId:Z,documentId:X,createdAt:e.number(),updatedAt:e.number(),sortOrder:e.number(),version:e.number(),workspaceId:V}),e.object({sequenceId:Z,documentId:X,createdAt:e.number(),updatedAt:e.number(),sortOrder:e.number(),version:e.number(),workspaceId:V}),e.object({sequenceId:Z.optional(),documentId:X.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),sortOrder:e.number().optional(),version:e.number().optional(),workspaceId:V.optional()});var xg=e.enum([`SPRITE_BUILD`]);e.object({useCase:xg,llmModelId:dh,createdAt:e.number(),updatedAt:e.number()}),e.object({useCase:xg,llmModelId:dh,createdAt:e.number(),updatedAt:e.number()}),e.object({useCase:xg.optional(),llmModelId:dh.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()}),e.object({spriteId:Y,workspaceId:V,hash:e.instanceof(Uint8Array),version:e.number(),updatedAt:e.number(),plaintext:e.string()}),e.object({spriteId:Y,workspaceId:V,hash:e.instanceof(Uint8Array),version:e.number(),updatedAt:e.number(),plaintext:e.string()}),e.object({spriteId:Y.optional(),workspaceId:V.optional(),hash:e.instanceof(Uint8Array).optional(),version:e.number().optional(),updatedAt:e.number().optional(),plaintext:e.string().optional()});var Sg=e.enum([`SIGNUP`,`PASSWORD_RESET`]),Cg=e.string();e.object({id:Cg,type:Sg,userId:W.nullable(),email:U,tokenHash:e.string(),createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number(),verifiedAt:e.number().nullable(),retryCount:e.number()}),e.object({id:Cg,type:Sg,userId:W.optional().nullable(),email:U,tokenHash:e.string(),createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number(),verifiedAt:e.number().optional().nullable(),retryCount:e.number()}),e.object({id:Cg.optional(),type:Sg.optional(),userId:W.optional().nullable(),email:U.optional(),tokenHash:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),expiresAt:e.number().optional(),verifiedAt:e.number().optional().nullable(),retryCount:e.number().optional()}),e.object({id:G,name:e.string(),workspaceId:V,version:e.number(),createdAt:e.number(),updatedAt:e.number(),avatarAssetId:ih.nullable(),description:e.string(),emailList:U.array()}),e.enum([`PENDING`,`CREATED`,`FINISHED`,`TERMINATED`]);var wg=e.number();e.object({id:wg,jobQueueId:e.number().nullable(),taskId:e.number(),payload:e.unknown(),priority:e.number(),runAt:e.date(),attempts:e.number(),maxAttempts:e.number(),lastError:e.string().nullable(),createdAt:e.date(),updatedAt:e.date(),key:e.string().nullable(),lockedAt:e.date().nullable(),lockedBy:e.string().nullable(),revision:e.number(),flags:e.record(e.string(),e.json()).nullable(),isAvailable:e.boolean()}),e.object({id:wg.optional(),jobQueueId:e.number().optional().nullable(),taskId:e.number(),payload:e.unknown().optional(),priority:e.number().optional(),runAt:e.date().optional(),attempts:e.number().optional(),maxAttempts:e.number().optional(),lastError:e.string().optional().nullable(),createdAt:e.date().optional(),updatedAt:e.date().optional(),key:e.string().optional().nullable(),lockedAt:e.date().optional().nullable(),lockedBy:e.string().optional().nullable(),revision:e.number().optional(),flags:e.record(e.string(),e.json()).optional().nullable(),isAvailable:e.boolean()}),e.object({id:wg.optional(),jobQueueId:e.number().optional().nullable(),taskId:e.number().optional(),payload:e.unknown().optional(),priority:e.number().optional(),runAt:e.date().optional(),attempts:e.number().optional(),maxAttempts:e.number().optional(),lastError:e.string().optional().nullable(),createdAt:e.date().optional(),updatedAt:e.date().optional(),key:e.string().optional().nullable(),lockedAt:e.date().optional().nullable(),lockedBy:e.string().optional().nullable(),revision:e.number().optional(),flags:e.record(e.string(),e.json()).optional().nullable(),isAvailable:e.boolean().optional()});var Tg=e.number();e.object({id:Tg,ts:e.date(),breaking:e.boolean()}),e.object({id:Tg,ts:e.date().optional(),breaking:e.boolean().optional()}),e.object({id:Tg.optional(),ts:e.date().optional(),breaking:e.boolean().optional()});var Eg=e.enum([`IN_PROGRESS`,`SUCCESS`,`ERROR`]),Dg=e.string();e.object({id:Dg,graphileWorkerJobId:e.string(),serviceName:e.string(),machineId:e.string(),attempt:e.number(),taskIdentifier:e.string(),payload:e.record(e.string(),e.json()),jobKey:e.string().nullable(),queueName:e.string().nullable(),workerId:e.string(),status:Eg,runnableAt:e.number(),startedAt:e.number(),finishedAt:e.number().nullable(),error:e.record(e.string(),e.json()).nullable(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:Dg,graphileWorkerJobId:e.string(),serviceName:e.string(),machineId:e.string(),attempt:e.number(),taskIdentifier:e.string(),payload:e.record(e.string(),e.json()),jobKey:e.string().optional().nullable(),queueName:e.string().optional().nullable(),workerId:e.string(),status:Eg,runnableAt:e.number(),startedAt:e.number(),finishedAt:e.number().optional().nullable(),error:e.record(e.string(),e.json()).optional().nullable(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:Dg.optional(),graphileWorkerJobId:e.string().optional(),serviceName:e.string().optional(),machineId:e.string().optional(),attempt:e.number().optional(),taskIdentifier:e.string().optional(),payload:e.record(e.string(),e.json()).optional(),jobKey:e.string().optional().nullable(),queueName:e.string().optional().nullable(),workerId:e.string().optional(),status:Eg.optional(),runnableAt:e.number().optional(),startedAt:e.number().optional(),finishedAt:e.number().optional().nullable(),error:e.record(e.string(),e.json()).optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var Og=e.number();e.object({id:Og,identifier:e.string()}),e.object({id:Og.optional(),identifier:e.string()}),e.object({id:Og.optional(),identifier:e.string().optional()});var kg=e.enum([`MISSING_HEARTBEAT`,`STALE_HEARTBEAT`,`STOPPED_WITH_LOCKS`,`ALREADY_RECOVERED_WITH_LOCKS`]),Ag=e.string();e.object({workerPoolId:Ag,serviceName:e.string(),machineId:e.string(),startedAt:e.number().nullable(),lastHeartbeatAt:e.number().nullable(),stoppedAt:e.number().nullable(),recoveredAt:e.number().nullable(),recoveryReason:kg.nullable().nullable(),recoveredJobCount:e.number().nullable(),createdAt:e.number(),updatedAt:e.number()}),e.object({workerPoolId:Ag,serviceName:e.string(),machineId:e.string(),startedAt:e.number().optional().nullable(),lastHeartbeatAt:e.number().optional().nullable(),stoppedAt:e.number().optional().nullable(),recoveredAt:e.number().optional().nullable(),recoveryReason:kg.nullable().optional().nullable(),recoveredJobCount:e.number().optional().nullable(),createdAt:e.number(),updatedAt:e.number()}),e.object({workerPoolId:Ag.optional(),serviceName:e.string().optional(),machineId:e.string().optional(),startedAt:e.number().optional().nullable(),lastHeartbeatAt:e.number().optional().nullable(),stoppedAt:e.number().optional().nullable(),recoveredAt:e.number().optional().nullable(),recoveryReason:kg.nullable().optional().nullable(),recoveredJobCount:e.number().optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var jg=e.string();e.object({identifier:jg,knownSince:e.date(),lastExecution:e.date().nullable()}),e.object({identifier:jg,knownSince:e.date(),lastExecution:e.date().optional().nullable()}),e.object({identifier:jg.optional(),knownSince:e.date().optional(),lastExecution:e.date().optional().nullable()});var Mg=e.number();e.object({id:Mg,queueName:e.string(),lockedAt:e.date().nullable(),lockedBy:e.string().nullable(),isAvailable:e.boolean()}),e.object({id:Mg.optional(),queueName:e.string(),lockedAt:e.date().optional().nullable(),lockedBy:e.string().optional().nullable(),isAvailable:e.boolean()}),e.object({id:Mg.optional(),queueName:e.string().optional(),lockedAt:e.date().optional().nullable(),lockedBy:e.string().optional().nullable(),isAvailable:e.boolean().optional()}),e.object({id:wg,queueName:e.string(),taskIdentifier:e.string(),priority:e.number(),runAt:e.date(),attempts:e.number(),maxAttempts:e.number(),lastError:e.string().nullable(),createdAt:e.date(),updatedAt:e.date(),key:e.string().nullable(),lockedAt:e.date().nullable(),lockedBy:e.string().nullable(),revision:e.number(),flags:e.record(e.string(),e.json()).nullable()}),e.object({identifier:e.string().nullable(),payload:e.unknown().nullable(),queueName:e.string().nullable(),runAt:e.date().nullable(),maxAttempts:e.number().nullable(),jobKey:e.string().nullable(),priority:e.number().nullable(),flags:e.string().nullable()});var Ng=e=>r.object({token:r.string().check(r.minLength(1),r.refine(e=>e.trim()!==``,{message:`Token must not be empty or whitespace`})),expiresAt:r.number().check(r.int(),r.gt(e)),personId:G}),Pg=(e,t=Date.now())=>{let n=Ng(t).safeParse(e);return n.success?n.data:Error(r.prettifyError(n.error))},Fg=class extends Error{status;constructor(e,t){super(t),this.name=`GatewayHttpError`,this.status=e}},Ig=r.object({message:r.string()}),Lg=async e=>{let t=`Gateway request failed with status ${e.status}`;try{let n=await e.json(),r=Ig.safeParse(n);r.success&&(t=r.data.message)}catch{}return new Fg(e.status,t)},Rg=async e=>{try{return await e.json()}catch{return Error(`Gateway returned an invalid JSON response`)}},zg=async e=>{let{baseUrl:n,projectId:r,userToken:i}=e,a=await t(()=>fetch(ce({baseUrl:n,path:`/api/v1/project/${encodeURIComponent(r)}/session-token`}),{method:`POST`,headers:{authorization:`Bearer ${i}`}}));if(a instanceof Error)return a;if(!a.ok)return Lg(a);let o=await Rg(a);return o instanceof Error?o:Pg(o)},Bg=r.object({token:r.string(),expiresAt:r.number(),personId:r.string()}),Vg=e=>Bg.safeParse(e).success,Hg=1e3,Ug=3e4,Wg=6e4,Gg=e=>Math.min(Hg*2**Math.max(e-1,0),Ug),Kg=(e,t)=>t>=e.expiresAt-Wg,qg=e=>{let{fetchSessionToken:t,now:n=Date.now}=e,r,i,a=0,o=0,s=0,c=()=>{r=void 0,i=void 0,a=0,o=0,s+=1},l=e=>{r&&(e===void 0||r.token===e)&&(r=void 0)},u=()=>{let e=o-n();if(e>0)return Promise.reject(Error(`fetchSessionToken is rate limited after repeated failures; retry in ${e}ms`));let c=s;return i=t().then(e=>{if(c!==s)throw Error(`Session token fetch was reset before it completed`);return r=e,a=0,o=0,e}).catch(e=>{throw c===s&&(r=void 0,a+=1,o=n()+Gg(a)),e}).finally(()=>{c===s&&(i=void 0)}),i};return{getSessionToken:()=>r&&!Kg(r,n())?Promise.resolve(r):i===void 0?u():i,invalidateToken:l,reset:c}},Jg=e=>{let{baseUrl:t,projectId:n,fetchUserToken:r,exchangeIdentityTokenForSessionToken:i=zg}=e,a=qg({fetchSessionToken:async()=>{let e=await r();if(typeof e==`string`){if(e.trim()===``)throw Error(`fetchUserToken must return a non-empty string`);let r=await i({baseUrl:t,projectId:n,userToken:e});if(r instanceof Error)throw r;return r}if(Vg(e)){let t=Pg(e);if(t instanceof Error)throw t;return t}throw Error(`fetchUserToken must return a non-empty string`)}});return{getSessionToken:()=>a.getSessionToken(),invalidateToken:e=>{a.invalidateToken(e)},destroy:async()=>{a.reset()}}},Yg=Symbol(`rough.client.runtime`),Xg=e=>{let t=e?.[Yg];if(!t)throw new kt;return t},Zg=e=>{let{fetchUserToken:t,projectId:n}=e,r=e.baseUrl??`https://gateway.rough.app`;if(typeof n!=`string`||n.trim()===``)throw TypeError(`createRoughClient: "projectId" is required`);if(typeof t!=`function`)throw TypeError(`createRoughClient: "fetchUserToken" is required`);let i=Symbol(`rough.client:${n}`),a=new AbortController,o=`starting`,s,c=Jg({baseUrl:r,fetchUserToken:t,projectId:n}),l=tt(),u=Vt(),d=Bt({getRuntime:()=>h}),f=Km({auth:c,baseUrl:r,clientId:i,projectId:n,signal:a.signal,store:l}),p=()=>{if(o===`destroying`||o===`destroyed`)throw new Tt},m=(async()=>{await f.start();let e=f.peek();if(!e||a.signal.aborted)return;let t=await le({projectId:n,replicache:e});t instanceof Error&&!a.signal.aborted&&console.error(`[Rough] Failed to ping project`,t)})().then(()=>{o===`starting`&&(o=`active`)},e=>{throw o===`starting`&&(o=`failed`),At(e)});m.catch(()=>{});let h={clientId:i,baseUrl:r,projectId:n,auth:c,store:l,surfaces:d,operations:u,getState:()=>o,assertUsable:p,whenReady:()=>m,getReplicache:async()=>{p(),await m,p();let e=f.peek();if(!e)throw Error(`Replicache is not available in this environment. Rough clients only open a local database in the browser.`);return e},buildUrl:e=>ce({baseUrl:r,...e})},g=async()=>{let e=[],t=async(t,n)=>{try{await n()}catch(n){let r=At(n);r.message=`${t}: ${r.message}`,e.push(r)}};try{await t(`operations`,()=>u.closeAll()),await t(`surfaces`,()=>d.destroy()),await Promise.allSettled([m]),await t(`replicache`,()=>f.destroy()),await Promise.all([t(`store`,()=>l.destroy()),t(`auth`,()=>c.destroy())])}finally{f.releaseIdentity(),o=`destroyed`}if(e.length>0)throw new Ot({errors:e})},_={get projectId(){return n},destroy:()=>s||(o=`destroying`,f.markDestroying(),a.abort(new Tt),s=g(),s)};return Object.defineProperty(_,Yg,{value:h,enumerable:!1,writable:!1,configurable:!1}),Object.freeze(_)},Qg=async e=>{await Xg(e.client).whenReady()},$g=e=>e.filter(e=>e.publishedAt!==null).toSorted((e,t)=>{let n=(t.publishedAt??0)-(e.publishedAt??0);return n===0?t.id.localeCompare(e.id):n}).at(0)??null,e_=e=>{let{sprite:t,spriteBuildList:n}=e;return{id:t.id,name:t.name,ownedByPersonId:t.ownedByPersonId,publishedSpriteBuildId:$g(n)?.id??null}},t_=(e,t)=>{let n=new Map;for(let t of e.spriteBuild.asList.value){let e=n.get(t.spriteId);e||(e=[],n.set(t.spriteId,e)),e.push(t)}let r=[];for(let i of e.sprite.asList.value){if(i.surfaceId!==t)continue;let e=e_({sprite:i,spriteBuildList:n.get(i.id)??[]});e.publishedSpriteBuildId&&r.push(e)}return r.toSorted((e,t)=>t.id.localeCompare(e.id))},n_=e=>{let{client:t,onError:n,onFeatures:r,signal:i}=e,a=Xg(t);a.assertUsable();let o=Rt(e.surface),s=a.surfaces.acquire({surface:o}),c=new AbortController,l,u,d,f=(async()=>{let e=await Promise.race([s.ready.then(e=>({type:`resolved`,resolution:e})),Nt(c.signal).then(()=>({type:`aborted`}))]);if(e.type===`aborted`||c.signal.aborted)return;let t=e.resolution.id,n=()=>{c.signal.aborted||r(t_(a.store,t))};l=a.store.subscribe(n),n()})();f.catch(e=>{c.signal.aborted||n?.(At(e))});let p=()=>(d??=(async()=>{c.abort(),l?.(),l=void 0,s.release(),u?.(),u=void 0,await Promise.allSettled([f])})(),d);return u=a.operations.register({label:`getRoughFeatures(${o.key})`,close:p}),i&&(i.aborted?p():i.addEventListener(`abort`,()=>void p(),{once:!0})),{get ready(){return f},unsubscribe:p}},r_={xmlns:`http://www.w3.org/2000/svg`,width:24,height:24,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,"stroke-width":2,"stroke-linecap":`round`,"stroke-linejoin":`round`},i_=e=>{for(let t in e)if(t.startsWith(`aria-`)||t===`role`||t===`title`)return!0;return!1},a_=Symbol(`lucide-context`),o_=()=>i(a_),s_=new Set([`$$slots`,`$$events`,`$$legacy`,`$$host`,`name`,`color`,`size`,`strokeWidth`,`absoluteStrokeWidth`,`iconNode`,`children`]),c_=l.from_svg(`<svg><!><!></svg>`);function l_(e,t){l.push(t,!0);let n=o_()??{},r=l.prop(t,`name`,7),i=l.prop(t,`color`,23,()=>n.color??`currentColor`),a=l.prop(t,`size`,23,()=>n.size??24),o=l.prop(t,`strokeWidth`,23,()=>n.strokeWidth??2),s=l.prop(t,`absoluteStrokeWidth`,23,()=>n.absoluteStrokeWidth??!1),c=l.prop(t,`iconNode`,23,()=>[]),u=l.prop(t,`children`,7),d=l.rest_props(t,s_),f=l.derived(()=>s()?Number(o())*24/Number(a()):o());var p={get name(){return r()},set name(e){r(e),l.flush()},get color(){return i()},set color(e=n.color??`currentColor`){i(e),l.flush()},get size(){return a()},set size(e=n.size??24){a(e),l.flush()},get strokeWidth(){return o()},set strokeWidth(e=n.strokeWidth??2){o(e),l.flush()},get absoluteStrokeWidth(){return s()},set absoluteStrokeWidth(e=n.absoluteStrokeWidth??!1){s(e),l.flush()},get iconNode(){return c()},set iconNode(e=[]){c(e),l.flush()},get children(){return u()},set children(e){u(e),l.flush()}},m=c_();l.attribute_effect(m,e=>({...r_,...e,...d,width:a(),height:a(),stroke:i(),"stroke-width":l.get(f),class:[`lucide-icon lucide`,n.class,r()&&`lucide-${r()}`,t.class]}),[()=>!u()&&!i_(d)&&{"aria-hidden":`true`}]);var h=l.child(m);l.each(h,17,c,l.index,(e,t)=>{var n=l.derived(()=>l.to_array(l.get(t),2));let r=()=>l.get(n)[0],i=()=>l.get(n)[1];var a=l.comment(),o=l.first_child(a);l.element(o,r,!0,(e,t)=>{l.attribute_effect(e,()=>({...i()}))}),l.append(e,a)});var g=l.sibling(h);return l.snippet(g,()=>u()??l.noop),l.reset(m),l.append(e,m),l.pop(p)}l.create_custom_element(l_,{name:{},color:{},size:{},strokeWidth:{},absoluteStrokeWidth:{},iconNode:{},children:{}},[],[],{mode:`open`});var u_=new Set([`$$slots`,`$$events`,`$$legacy`,`$$host`]);function d_(e,t){let n=l.rest_props(t,u_),r=[[`path`,{d:`m5 12 7-7 7 7`}],[`path`,{d:`M12 19V5`}]];l_(e,l.spread_props({name:`arrow-up`},()=>n,{get iconNode(){return r}}))}l.create_custom_element(d_,{},[],[],{mode:`open`});var f_=new Set([`$$slots`,`$$events`,`$$legacy`,`$$host`]);function p_(e,t){let n=l.rest_props(t,f_),r=[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`}]];l_(e,l.spread_props({name:`square`},()=>n,{get iconNode(){return r}}))}l.create_custom_element(p_,{},[],[],{mode:`open`});var m_=class extends Error{missingFeature;constructor(e){super(h_(e)),this.name=`UnsupportedResponseStreamError`,this.missingFeature=e}};function h_(e){return`Streaming fetch responses are not supported in this runtime because ${e} is unavailable. React Native users need a compatible fetch/stream/TextDecoder polyfill, or should use a fetch, XHR, or custom transport that can deliver streaming chunks.`}function g_(e){if(!e.body)throw new m_(`Response.body`);if(typeof e.body.getReader!=`function`)throw new m_(`Response.body.getReader`);return e.body.getReader()}function __(){if(typeof globalThis.TextDecoder!=`function`)throw new m_(`TextDecoder`);return new globalThis.TextDecoder}function v_(e){if(!e.startsWith(`data:`))return e;let t=e.slice(5);return t.startsWith(` `)?t.slice(1):t}var y_=new WeakMap;function b_(e){return y_.get(e)??(`runId`in e&&typeof e.runId==`string`?e.runId:void 0)}var x_=class extends Error{constructor(){super(`Stream ended with unterminated trailing data — connection was likely cut short.`),this.name=`StreamTruncatedError`}},S_=class extends Error{constructor(e){super(`Stream response body read failed`,{cause:e}),this.name=`StreamReadError`}},C_=class extends Error{constructor(){super(`Durable run ended without a terminal event and could not resume — the run did not complete.`),this.name=`DurableStreamIncompleteError`}},w_=class extends Error{constructor(e){super(`Durable run exceeded its reconnect ceiling of ${e} attempts — giving up.`),this.name=`StreamReconnectLimitError`}};function T_(e){let t=e?.maxAttempts??5,n=e?.delayMs??250;if(!Number.isInteger(t)||t<0)throw Error(`Invalid reconnect.maxAttempts: ${t}. Must be a non-negative integer.`);if(!Number.isFinite(n)||n<0)throw Error(`Invalid reconnect.delayMs: ${n}. Must be a non-negative finite number.`);return{maxAttempts:t,delayMs:n}}function E_(e){let t=T_(e),n=new Set,r,i=0;return{get lastEventId(){return r},note(e){return e===void 0?`new`:e===``?(r=void 0,n.clear(),`reset`):n.has(e)?`duplicate`:(n.add(e),r=e,`new`)},async waitBeforeReconnect(e,n){if(e)i=0;else if(i+=1,i>t.maxAttempts)throw new w_(t.maxAttempts);await D_(t.delayMs,n)}}}function D_(e,t){return e<=0||t?.aborted?Promise.resolve():new Promise(n=>{let r=()=>{clearTimeout(i),n()},i=setTimeout(()=>{t?.removeEventListener(`abort`,r),n()},e);t?.addEventListener(`abort`,r,{once:!0})})}function O_(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function k_(e,t){if(!e)throw Error(`Cannot synthesize terminal event: ${t} not supplied via runContext and not observed in the upstream stream.`);return e}function A_(e){if(!e)return{};if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}return e}var j_=`X-Run-Id`;function M_(e){return e===void 0?{}:{[j_]:e}}function N_(e,t){let n=e.indexOf(`#`),r=n===-1?``:e.slice(n),i=n===-1?e:e.slice(0,n),a=i.indexOf(`?`),o=a===-1?i:i.slice(0,a),s=new URLSearchParams(a===-1?``:i.slice(a+1));for(let[e,n]of Object.entries(t))s.set(e,n);let c=s.toString();return`${o}${c.length===0?``:`?${c}`}${r}`}async function*P_(e,t){try{let n=__(),r=``;for(;!t?.aborted;){let i;try{i=await e.read()}catch(e){if(t?.aborted)return;throw new S_(e)}let{done:a,value:o}=i;if(a)break;r+=n.decode(o,{stream:!0});let s=r.split(`
26
- `);r=s.pop()||``;for(let e of s){let t=e.endsWith(`\r`)?e.slice(0,-1):e;t.trim()&&(yield t)}}if(r+=n.decode(),r.trim()&&!t?.aborted)throw new x_}finally{e.releaseLock()}}async function*F_(e,t){let n,r,i,a;for await(let o of e){if(o===`id`||o.startsWith(`id:`)){let e=o===`id`?``:o.slice(3);a=e.startsWith(` `)?e.slice(1):e;continue}if(o.startsWith(`:`)||o.startsWith(`event:`)||o.startsWith(`retry:`))continue;let e=v_(o);if(e===`[DONE]`){yield{chunk:{type:Pm.RUN_FINISHED,threadId:n??t?.threadId??``,runId:r??t?.runId??``,model:i??``,timestamp:Date.now(),finishReason:`stop`}};return}let s=JSON.parse(e);`threadId`in s&&typeof s.threadId==`string`&&(n=s.threadId),`runId`in s&&typeof s.runId==`string`&&(r=s.runId),`model`in s&&typeof s.model==`string`&&(i=s.model);let c=a;a=void 0,yield{chunk:s,...c===void 0?{}:{id:c}}}}function I_(e){if(!e.ok)throw Error(`HTTP error! status: ${e.status} ${e.statusText}`)}async function L_(e,t,n,r,i){let a=await e(N_(t,{threadId:i}),{method:`GET`,headers:{Accept:`application/json`,...n},credentials:r});I_(a);let o=await a.json(),s=o.activeRun&&typeof o.activeRun.runId==`string`?{runId:o.activeRun.runId}:null,c=o.interrupts&&typeof o.interrupts.runId==`string`&&Array.isArray(o.interrupts.pending)&&o.interrupts.pending.length>0?{runId:o.interrupts.runId,pending:o.interrupts.pending}:null;return{messages:Array.isArray(o.messages)?o.messages:[],activeRun:s,interrupts:c}}async function R_(e,t,n,r,i){let a=await e(N_(t,{threadId:i}),{method:`GET`,headers:{Accept:`application/json`,...n},credentials:r});I_(a);let o=await a.json();if(o===null)return{resumeSnapshot:null,activeRun:null};if(typeof o!=`object`||Array.isArray(o))throw Error(`Generation hydration expected a JSON object from ${t}, received ${Array.isArray(o)?`an array`:typeof o}.`);let s=o,c=s.activeRun&&typeof s.activeRun.runId==`string`?{runId:s.activeRun.runId}:null;return{resumeSnapshot:s.resumeSnapshot??null,activeRun:c}}async function*z_(e,t,n){I_(e),yield*F_(P_(g_(e),t),n)}async function*B_(e,t){for await(let{chunk:n}of z_(e,t))yield n}function V_(e,t,n,r){return async function*(i,a){let o;try{o=await e(t,{...n,headers:{...n.headers,...i},...a?{signal:a}:{}})}catch(e){throw new S_(e)}yield*r(o,a)}}async function*H_(e,t,n){let r=E_(n);for(;;){if(t?.aborted)return;let n=r.lastEventId===void 0?{}:{"Last-Event-ID":r.lastEventId},i=!1,a=!1;try{for await(let{chunk:o,id:s}of e(n,t))r.note(s)!==`duplicate`&&(a=!0,(o.type===`RUN_FINISHED`||o.type===`RUN_ERROR`)&&(i=!0),yield o)}catch(e){if(t?.aborted)return;if((e instanceof x_||e instanceof S_)&&r.lastEventId!==void 0){await r.waitBeforeReconnect(a,t);continue}throw e}if(t?.aborted||i)return;if(r.lastEventId!==void 0){if(a){await r.waitBeforeReconnect(!0,t);continue}throw new C_}return}}function U_(e){if(!e)throw Error(`Connection adapter is required`);let t=`connect`in e,n=`subscribe`in e,r=`send`in e;if(t&&(n||r))throw Error(`Connection adapter must provide either connect or both subscribe and send, not both modes`);if(n&&r){let t=e.joinRun?.bind(e),n=e.hydrate?.bind(e);return{subscribe:e.subscribe.bind(e),send:e.send.bind(e),...t?{joinRun:t}:{},...n?{hydrate:n}:{}}}if(!t)throw Error(`Connection adapter must provide either connect or both subscribe and send`);let i=[],a=[];function o(e,t){t&&y_.set(e,t);let n=a.shift();n?n(e):i.push(e)}return{subscribe(e){let t=i.splice(0),n=[];return i=t,a=n,(async function*(){for(;!e?.aborted;){let r,i=t.shift();r=i===void 0?await new Promise(t=>{let r=()=>t(null);n.push(n=>{e?.removeEventListener(`abort`,r),t(n)}),e?.addEventListener(`abort`,r,{once:!0})}):i,r!==null&&(yield r)}})()},async send(t,n,r,i){let a=!1,s,c;try{let l=e.connect(t,n,r,i);for await(let e of l)`threadId`in e&&typeof e.threadId==`string`&&(s=e.threadId),`runId`in e&&typeof e.runId==`string`&&(c=e.runId),(e.type===`RUN_FINISHED`||e.type===`RUN_ERROR`)&&(a=!0),o(e,i?.runId);!r?.aborted&&!a&&o({type:Pm.RUN_FINISHED,threadId:k_(s??i?.threadId,`threadId`),runId:k_(c??i?.runId,`runId`),model:`connect-wrapper`,timestamp:Date.now(),finishReason:`stop`},i?.runId)}catch(e){if(!r?.aborted&&!a)try{let t=e instanceof Error?e.message:`Unknown error in connect()`;o({type:Pm.RUN_ERROR,threadId:k_(s??i?.threadId,`threadId`),runId:k_(c??i?.runId,`runId`),timestamp:Date.now(),message:t},i?.runId)}catch{}throw e}},...typeof e.joinRun==`function`?{joinRun:(t,n)=>e.joinRun(t,n)}:{},...(()=>{let t=e.hydrate;return typeof t==`function`?{hydrate:e=>t(e)}:{}})()}}function W_(e,t,n,r){let i=Dm(e),a={...r.body,...n?.forwardedProps??{},...t};return{threadId:n?.threadId??O_(`thread`),runId:n?.runId??O_(`run`),...n?.parentRunId!==void 0&&{parentRunId:n.parentRunId},...n?.resume!==void 0&&{resume:n.resume},state:{},messages:i,tools:n?.clientTools??[],context:[],forwardedProps:a,data:{...a}}}function G_(e,t={}){return{async*connect(n,r,i,a){let o=typeof e==`function`?e():e,s=typeof t==`function`?await t():t,c={"Content-Type":`application/json`,...A_(s.headers),...M_(a?.runId)},l=W_(n,r,a,s),u=s.fetchClient??fetch,d=i||s.signal;yield*H_(V_(u,o,{method:`POST`,headers:c,body:JSON.stringify(l),credentials:s.credentials||`same-origin`},(e,t)=>z_(e,t,{...a?.threadId===void 0?{}:{threadId:a.threadId},...a?.runId===void 0?{}:{runId:a.runId}})),d,s.reconnect)},async*joinRun(n,r){let i=typeof e==`function`?e():e,a=typeof t==`function`?await t():t,o=N_(i,{offset:`-1`,runId:n}),s={...A_(a.headers)},c=a.fetchClient??fetch,l=r||a.signal;yield*H_(V_(c,o,{method:`GET`,headers:s,credentials:a.credentials||`same-origin`},(e,t)=>z_(e,t,{runId:n})),l,a.reconnect)},async hydrate(n){let r=typeof e==`function`?e():e,i=typeof t==`function`?await t():t;return L_(i.fetchClient??fetch,r,A_(i.headers),i.credentials||`same-origin`,n)},async hydrateGeneration(n){let r=typeof e==`function`?e():e,i=typeof t==`function`?await t():t;return R_(i.fetchClient??fetch,r,A_(i.headers),i.credentials||`same-origin`,n)}}}function K_(e){return{async*connect(t,n,r,i){if(!r)throw Error(`fetcherToConnectionAdapter requires an AbortSignal — the chat client always supplies one.`);if(!i)throw Error(`fetcherToConnectionAdapter requires a RunAgentInputContext — the chat client always supplies one.`);let a=await e({messages:t,data:n,threadId:i.threadId,runId:i.runId,...i.parentRunId===void 0?{}:{parentRunId:i.parentRunId},...i.resume===void 0?{}:{resume:i.resume}},{signal:r});a instanceof Response?yield*B_(a,r):yield*q_(a,r)}}}async function*q_(e,t){if(t.aborted)return;let n=e[Symbol.asyncIterator](),r=new Promise(e=>{t.addEventListener(`abort`,()=>e({done:!0,value:void 0}),{once:!0})});try{for(;;){let e=await Promise.race([n.next(),r]);if(e.done)return;yield e.value}}finally{await n.return?.()}}function J_(e){return e.resumable}function Y_(e,t){let n=zp(e.descriptor);return n?{...t,metadata:Rp(n)}:t}function X_(e){return`cancel`in e&&`clearResolution`in e}var Z_=new Set([`invalid-payload`,`invalid-edited-args`,`invalid-tool-output`,`invalid-response-schema`,`unknown-interrupt`,`expired`,`stale`,`conflict`,`legacy-unsupported`]),Q_=new Set([`incomplete-batch`,`item-validation-failed`,`unsupported-bulk-operation`,`async-resolver`,`inactive-transaction`,`mixed-provenance`,`transport`,`server`,`protocol`,`invalid-response-schema`,`expired`,`stale`,`conflict`,`legacy-submit-failed`]);function $_(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ev(e){return $_(e)&&e.kind===`approval`&&typeof e.toolName==`string`&&`input`in e}function tv(e){return $_(e)&&e.kind===`client_tool`&&typeof e.toolName==`string`&&`input`in e}function nv(e){return ev(e.metadata)||tv(e.metadata)}function rv(e){return Mp(e)}function iv(e){if(!$_(e.metadata))return!1;let t=e.metadata[Ep];return!$_(t)||t.v!==void 0&&t.v!==1?!1:t.kind===`generic`||t.kind===`tool-approval`||t.kind===`client-tool-execution`||`definitionId`in t||`key`in t||`batchIndex`in t||`payloadSchemaHash`in t}function av(e){if(!$_(e.metadata))return!1;let t=e.metadata[Ep];return!$_(t)||t.kind!==`generic`?!1:`definitionId`in t||`key`in t||`batchIndex`in t||`payloadSchemaHash`in t}function ov(e){return e.metadata?.[`tanstack:interruptPayload`]}function sv(e){return e===`tanstack:client_tool_execution`||e===`client_tool_input`}function cv(e){if(e.responseSchema!==void 0)try{return rp(np(e.responseSchema))}catch{return}}function lv(e){if(e!==void 0)try{return Fp(e)}catch{return}}function uv(e){return e!==null&&(typeof e==`object`||typeof e==`function`)&&`then`in e&&typeof e.then==`function`}function dv(e,t,n){if(e===void 0)return{valid:!0,payload:t};if(lp(e)){let r=e[`~standard`].validate(t),i=e=>e.issues?{code:n,message:e.issues[0]?.message??`Schema validation failed.`}:{valid:!0,payload:e.value};return uv(r)?Promise.resolve(r).then(i):i(r)}return{valid:!0,payload:t}}function fv(e){for(let t of Z_)if(t===e)return!0;return!1}function pv(e){for(let t of Q_)if(t===e)return!0;return!1}function mv(e){if(!$_(e))return!1;let t=e.scope,n=e.code;return typeof n!=`string`||typeof e.message!=`string`||typeof e.retryable!=`boolean`||typeof e.threadId!=`string`||typeof e.interruptedRunId!=`string`||typeof e.generation!=`number`?!1:t===`item`?fv(n)&&typeof e.interruptId==`string`&&(e.source===`client`||e.source===`server`):t===`batch`&&pv(n)&&Array.isArray(e.interruptIds)&&e.interruptIds.every(e=>typeof e==`string`)&&(e.source===`client`||e.source===`server`||e.source===`transport`)}function hv(e){return mv(e)?[e]:!$_(e)||!Array.isArray(e.errors)?[]:e.errors.every(mv)?e.errors:[]}function gv(e,t){if(e.length!==t.length)return!1;let n=[...e].sort(),r=[...t].sort();return n.every((e,t)=>e===r[t])}function _v(e,t){return e.threadId===t.threadId&&e.interruptedRunId===t.interruptedRunId&&e.generation===t.generation&&gv(e.interruptIds,t.interruptIds)}function vv(e,t,n){let r=n.filter(e=>e.source!==`transport`),i=e=>t.includes(e)&&r.some(t=>_v(e,t)),a=e.filter(e=>!i(e)),o=t.filter(e=>!r.some(t=>_v(e,t)));return Object.freeze({rootErrors:Object.freeze([...a,...n]),submissionRootErrors:Object.freeze([...o,...r])})}function yv(e,t){if(e.threadId!==t.threadId||e.interruptedRunId!==t.interruptedRunId||e.generation!==t.generation)return!1;let n=t.resolutions.map(e=>e.interruptId);return e.scope===`item`?n.includes(e.interruptId):gv(e.interruptIds,n)}function bv(e,t,n){let r=cv(e)??n?.responseSchemaHash;return B({v:1,kind:`generic`,interruptId:e.id,interruptedRunId:t.interruptedRunId,generation:t.generation,...r===void 0?{}:{responseSchemaHash:r},...e.expiresAt===void 0?{}:{expiresAt:e.expiresAt}})}function xv(e,t){let n=B(e.descriptor),r=e.error===void 0?Object.freeze([]):Object.freeze([B(e.error)]),i=r[0];return{id:n.id,interruptId:n.id,reason:n.reason,...n.message===void 0?{}:{message:n.message},...n.responseSchema===void 0?{}:{responseSchema:n.responseSchema},...n.expiresAt===void 0?{}:{expiresAt:n.expiresAt},...n.metadata===void 0?{}:{metadata:n.metadata},threadId:t.threadId,interruptedRunId:t.interruptedRunId,generation:t.generation,status:e.status,errors:r,...i===void 0?{}:{error:i},canResolve:e.canResolve}}var Sv=class{options;hydration;items=[];snapshot=Object.freeze([]);rootErrors=Object.freeze([]);submissionRootErrors=Object.freeze([]);state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:!1});activeTransaction;retrySubmission;resuming=!1;tools;interruptDefinitions;constructor(e){this.options=e,this.tools=e.tools;let t=new Map;for(let n of e.interrupts??[]){if(t.has(n.id))throw Error(`Duplicate interrupt definition id: ${n.id}`);t.set(n.id,n)}this.interruptDefinitions=t}updateTools(e){this.tools=e}hydrate(e,t=`live`){this.hydration={threadId:e.threadId,interruptedRunId:e.interruptedRunId,generation:e.generation,interrupts:B(e.interrupts)};let n=new Map;for(let t of e.interrupts){let e=rv(t);e?.kind===`generic`&&e.definitionId!==void 0&&e.key!==void 0&&e.batchIndex!==void 0&&n.set(e.batchIndex,(n.get(e.batchIndex)??0)+1)}this.items=e.interrupts.map(t=>this.hydrateInterrupt(t,e,n)),this.rootErrors=Object.freeze([]),this.submissionRootErrors=Object.freeze([]),this.retrySubmission=void 0,this.resuming=!1,this.publish(t)}getInterrupts(){return this.snapshot}getState(){return this.state}getDescriptors(){return this.hydration?.interrupts??Object.freeze([])}hasValidatedFirstPartyGenericBatch(){return this.items.some(e=>e.kind===`generic`&&e.definition!==void 0)}reset(e){this.hydration=void 0,this.items=[],this.snapshot=Object.freeze([]),e?.preserveRootErrors!==!0&&(this.rootErrors=Object.freeze([]),this.submissionRootErrors=Object.freeze([])),this.retrySubmission=void 0,this.resuming=!1,this.state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:!1}),this.options.onChange?.(e?.source??`live`)}getInterruptErrors(){return this.rootErrors}getResuming(){return this.resuming}resolve(e){if(this.assertRootMutable(),typeof e==`boolean`){this.resolveBooleanBulk(e);return}this.resolveTransaction(e)}cancel(){this.assertRootMutable(),this.invalidateRetry();for(let e of this.items)J_(e)&&(e.validationGeneration++,e.resolution=Object.freeze(Y_(e,{interruptId:e.descriptor.id,status:`cancelled`})),e.status=`staged`,e.error=void 0);this.publish(),this.maybeSubmit()}retry(){if(this.resuming)throw Error(`Interrupt submission is already active.`);let e=this.retrySubmission;if(!e){this.addRootError(`transport`,`There is no retryable interrupt submission.`,!1);return}this.submitBatch(e)}resolveClientToolOutput(e,t){let n=this.items.find(t=>t.kind===`client-tool-execution`&&t.binding?.kind===`client-tool-execution`&&t.binding.toolCallId===e||t.kind===`generic`&&sv(t.descriptor.reason)&&t.descriptor.toolCallId===e&&tv(t.descriptor.metadata));return n?(this.resolveItem(n.descriptor.id,t),!0):!1}resolveToolApprovalDecision(e,t){let n=this.items.find(t=>t.descriptor.id===e&&(t.kind===`tool-approval`||t.kind===`generic`&&t.descriptor.reason===`approval_required`&&ev(t.descriptor.metadata)));return n?(this.resolveItem(n.descriptor.id,{approved:t}),!0):!1}hydrateInterrupt(e,t,n){let r=B(e),i=rv(r),a=i===void 0&&nv(r);if(i===void 0&&!a)return iv(r)?{descriptor:r,binding:bv(r,t,void 0),kind:`generic`,status:`error`,canResolve:!1,resumable:!1,error:this.itemError(r.id,`stale`,`The interrupt binding is invalid or incomplete.`),validationGeneration:0}:{descriptor:r,binding:void 0,kind:`unbound`,status:`pending`,canResolve:!1,resumable:!1,validationGeneration:0};let o=i!==void 0&&i.interruptId===r.id&&i.interruptedRunId===t.interruptedRunId&&i.generation===t.generation&&cv(r)===i.responseSchemaHash,s=i!==void 0&&i.interruptId===r.id&&i.interruptedRunId===t.interruptedRunId&&i.generation===t.generation&&i.responseSchemaHash===(cv(r)??i.responseSchemaHash);if(i!==void 0&&av(r)&&(!s||i.kind!==`generic`||i.definitionId===void 0||i.key===void 0||i.batchIndex===void 0))return{descriptor:r,binding:bv(r,t,i),kind:`generic`,status:`error`,canResolve:!1,resumable:!1,error:this.itemError(r.id,`stale`,`The interrupt binding does not match this interrupted run.`),validationGeneration:0};if(s&&i.kind===`tool-approval`){let e=this.tools?.find(e=>e.name===i.toolName);if(e?.needsApproval===!0&&r.toolCallId===i.toolCallId)try{let t=wp(e.approvalSchema,e.inputSchema);if(Tp(e.inputSchema)===i.inputSchemaHash&&t.approvalSchemaHash===i.approvalSchemaHash&&t.responseSchemaHash===i.responseSchemaHash)return{descriptor:r,binding:B(i),kind:`tool-approval`,status:`pending`,canResolve:!0,resumable:!0,tool:e,validationGeneration:0}}catch{}}if(s&&i.kind===`client-tool-execution`){let e=this.tools?.find(e=>e.name===i.toolName);if(e!==void 0&&r.toolCallId===i.toolCallId&&Tp(e.outputSchema)===i.outputSchemaHash)return{descriptor:r,binding:B(i),kind:`client-tool-execution`,status:`pending`,canResolve:!0,resumable:!0,tool:e,validationGeneration:0}}if(i!==void 0&&i.kind===`generic`&&i.definitionId!==void 0&&i.key!==void 0&&i.batchIndex!==void 0&&i.key.length>0&&n.get(i.batchIndex)!==1)return{descriptor:r,binding:B(i),kind:`generic`,status:`error`,canResolve:!1,resumable:!1,error:this.itemError(r.id,`stale`,`Generic interrupt batch contains a duplicate batchIndex.`),validationGeneration:0};if(o&&i.kind===`generic`&&i.definitionId!==void 0&&i.key!==void 0&&i.batchIndex!==void 0&&i.key.length>0&&n.get(i.batchIndex)===1){let e=this.interruptDefinitions.get(i.definitionId);if(e!==void 0&&lv(e.responseSchema)===i.responseSchemaHash&&(e.payloadSchema===void 0?i.payloadSchemaHash===void 0:i.payloadSchemaHash===lv(e.payloadSchema))){let t=ov(r);return{descriptor:r,binding:B(i),definition:e,kind:`generic`,status:`pending`,canResolve:!0,resumable:!0,...t===void 0?{}:{payload:B(t)},validationGeneration:0}}}let c=a||i!==void 0&&i.interruptId===r.id&&i.interruptedRunId===t.interruptedRunId&&i.generation===t.generation&&(i.kind!==`generic`||cv(r)===void 0||i.responseSchemaHash===cv(r));return{descriptor:r,binding:bv(r,t,i),kind:`generic`,status:`pending`,canResolve:c,resumable:c,validationGeneration:0}}buildSnapshot(e){let t=this.requireHydration(),n=this.items.filter(e=>e.kind!==`client-tool-execution`&&e.status!==`submitting`).map(n=>{let r=xv(n,t);if(n.kind===`unbound`||n.binding===void 0){let e={...r,kind:`unbound`,canResolve:!1};return Object.freeze(e)}if(n.kind===`tool-approval`&&n.binding.kind===`tool-approval`){let t=B(n.binding),i={...r,kind:`tool-approval`,binding:t,toolName:n.binding.toolName,toolCallId:n.binding.toolCallId,originalArgs:B(n.binding.originalArgs),cancel:()=>this.cancelItem(n.descriptor.id,e),clearResolution:()=>this.clearItem(n.descriptor.id,e),resolveInterrupt:(t,r)=>{let i=$_(r)?r:void 0;this.resolveItem(n.descriptor.id,{approved:t,...t&&i?.editedArgs!==void 0?{editedArgs:i.editedArgs}:{},...i?.payload===void 0?{}:{payload:i.payload}},e)}};return Object.freeze(i)}let i=n.binding.kind===`generic`?B(n.binding):B({v:1,kind:`generic`,interruptId:n.descriptor.id,interruptedRunId:t.interruptedRunId,generation:t.generation,...typeof n.binding.responseSchemaHash==`string`?{responseSchemaHash:n.binding.responseSchemaHash}:{}});if(n.definition!==void 0&&n.binding.kind===`generic`){let t={...r,kind:`generic`,definitionId:n.definition.id,key:n.binding.key??``,payload:n.payload,binding:i,cancel:()=>this.cancelItem(n.descriptor.id,e),clearResolution:()=>this.clearItem(n.descriptor.id,e),resolveInterrupt:t=>this.resolveItem(n.descriptor.id,t,e)};return Object.freeze(t)}let a={...r,kind:`generic`,binding:i,cancel:()=>this.cancelItem(n.descriptor.id,e),clearResolution:()=>this.clearItem(n.descriptor.id,e),resolveInterrupt:t=>this.resolveItem(n.descriptor.id,t,e)};return Object.freeze(a)});return Object.freeze(n)}publish(e=`live`){if(!this.hydration){this.snapshot=Object.freeze([]),this.state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:this.resuming}),this.options.onChange?.(e);return}this.snapshot=this.buildSnapshot(),this.state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:this.resuming}),this.options.onChange?.(e)}resolveItem(e,t,n){this.assertItemMutable(n);let r=this.findItem(e);if(this.invalidateRetry(),!r.canResolve){r.status=`error`,r.error=this.itemError(e,`invalid-response-schema`,`The interrupt response schema is invalid and cannot be resolved.`),n||this.publish();return}let i=++r.validationGeneration,a=this.validateCandidate(r,t);if(uv(a)){r.status=`validating`,r.error=void 0,n||this.publish(),Promise.resolve(a).then(e=>{i===r.validationGeneration&&this.applyValidation(r,e,n)}).catch(e=>{i===r.validationGeneration&&this.applyValidation(r,{code:this.validationCode(r),message:e instanceof Error?e.message:String(e)},n)});return}this.applyValidation(r,a,n)}cancelItem(e,t){this.assertItemMutable(t);let n=this.findItem(e);this.invalidateRetry(),n.validationGeneration++,n.resolution=Object.freeze(Y_(n,{interruptId:e,status:`cancelled`})),n.status=`staged`,n.error=void 0,t||(this.publish(),this.maybeSubmit())}clearItem(e,t){this.assertItemMutable(t);let n=this.findItem(e);this.invalidateRetry(),n.validationGeneration++,n.resolution=void 0,n.error=void 0,n.status=`pending`,t||this.publish()}maybeSubmit(){let e=this.items.some(e=>e.kind===`generic`),t=this.items.filter(t=>J_(t)&&!(e&&t.kind===`client-tool-execution`));if(t.length===0||t.some(e=>e.resolution===void 0||e.status!==`staged`))return;let n=this.requireHydration(),r=ap(t.map(e=>e.resolution).filter(e=>e!==void 0)),i=Object.freeze({threadId:n.threadId,interruptedRunId:n.interruptedRunId,generation:n.generation,resolutions:r.resolutions,canonicalResolutions:r.canonicalResolutions,fingerprint:r.fingerprint});this.submitBatch(i)}applyValidation(e,t,n){if(!(`valid`in t)){e.status=`error`;let r=this.itemError(e.descriptor.id,t.code,t.message,t.path);e.error=r,e.kind===`client-tool-execution`&&(this.rootErrors=Object.freeze([...this.rootErrors.filter(t=>!(t.code===`item-validation-failed`&&t.interruptIds.includes(e.descriptor.id))),Object.freeze({scope:`batch`,code:`item-validation-failed`,message:r.message,source:`client`,retryable:!1,interruptIds:Object.freeze([e.descriptor.id]),threadId:r.threadId,interruptedRunId:r.interruptedRunId,generation:r.generation})])),n||this.publish();return}e.resolution=B(Y_(e,{interruptId:e.descriptor.id,status:`resolved`,payload:t.payload})),e.status=`staged`,e.error=void 0,n||(this.publish(),this.maybeSubmit())}validateCandidate(e,t){if(e.kind===`generic`){let n=dv(e.definition?.responseSchema??e.descriptor.responseSchema,t,`invalid-payload`);if(e.definition===void 0)return n;let r=e=>`valid`in e?{valid:!0,payload:t}:e;return uv(n)?Promise.resolve(n).then(r):r(n)}return e.kind===`client-tool-execution`?dv(e.tool?.outputSchema,t,`invalid-tool-output`):this.validateApprovalCandidate(e,t)}validateApprovalCandidate(e,t){if(!$_(t)||typeof t.approved!=`boolean`)return{code:`invalid-payload`,message:`Tool approval resolutions require an approved boolean.`};let n=t.approved,r=t.editedArgs;if(!n&&r!==void 0)return{code:`invalid-edited-args`,message:`Rejected tool approvals cannot edit tool arguments.`};if(n&&r!==void 0){let n=dv(e.tool?.inputSchema,r,`invalid-edited-args`);return uv(n)?Promise.resolve(n).then(n=>`valid`in n?this.validateApprovalPayload(e,t,n.payload):n):`valid`in n?this.validateApprovalPayload(e,t,n.payload):n}return this.validateApprovalPayload(e,t,void 0)}validateApprovalPayload(e,t,n){let r=t.approved===!0,i=this.approvalBranchSchema(e.tool,r),a=t.payload;if(i===void 0&&a!==void 0)return{code:`invalid-payload`,message:`This approval branch does not accept a payload.`};if(i!==void 0&&a===void 0)return{code:`invalid-payload`,message:`This approval branch requires a payload.`};let o=dv(i,a,`invalid-payload`),s=e=>`valid`in e?{valid:!0,payload:{approved:r,...n===void 0?{}:{editedArgs:n},...i===void 0?{}:{payload:e.payload}}}:e;return uv(o)?Promise.resolve(o).then(s):s(o)}approvalBranchSchema(e,t){let n=e?.approvalSchema;return!$_(n)||!(`approve`in n||`reject`in n)?n:t?n.approve:n.reject}validationCode(e){return e.kind===`client-tool-execution`?`invalid-tool-output`:`invalid-payload`}resolveBooleanBulk(e){let t=this.items.filter(e=>J_(e)&&e.kind!==`client-tool-execution`);if(!t.every(t=>t.kind===`tool-approval`&&this.approvalBranchSchema(t.tool,e)===void 0)||t.length===0){this.addRootError(`unsupported-bulk-operation`,`Boolean bulk resolution requires payloadless tool approvals.`,!1);return}this.invalidateRetry();for(let n of t)n.validationGeneration++,n.resolution=B({interruptId:n.descriptor.id,status:`resolved`,payload:{approved:e}}),n.status=`staged`,n.error=void 0;this.publish(),this.maybeSubmit()}resolveTransaction(e){let t=this.items.map(e=>({status:e.status,...e.resolution===void 0?{}:{resolution:e.resolution},...e.error===void 0?{}:{error:e.error},validationGeneration:e.validationGeneration})),n={active:!0};this.activeTransaction=n;let r=this.buildSnapshot(n).filter(X_),i;try{for(let t of r){let n=e(t);if(n!==void 0){i={code:uv(n)?`async-resolver`:`inactive-transaction`,message:uv(n)?`Interrupt transaction resolvers must be synchronous.`:`Interrupt transaction resolvers must return literal undefined.`};break}}i===void 0&&this.items.some(e=>J_(e)&&e.kind!==`client-tool-execution`&&(e.resolution===void 0||e.status!==`staged`))&&(i={code:`incomplete-batch`,message:`Interrupt transaction did not resolve every item.`})}catch(e){i={code:`item-validation-failed`,message:e instanceof Error?e.message:String(e)}}finally{n.active=!1,this.activeTransaction=void 0}if(i){this.restoreCheckpoints(t),this.addRootError(i.code,i.message,!1);return}this.publish(),this.maybeSubmit()}restoreCheckpoints(e){this.items.forEach((t,n)=>{let r=e[n];r&&(t.status=r.status,t.resolution=r.resolution,t.error=r.error,t.validationGeneration=r.validationGeneration+1)}),this.publish()}assertItemMutable(e){if(e&&!e.active||this.activeTransaction&&e!==this.activeTransaction)throw Error(`Interrupt transaction is inactive.`);if(this.resuming)throw Error(`Interrupts cannot be mutated while submitting.`)}assertRootMutable(){if(this.activeTransaction)throw Error(`Interrupt transaction is already active.`);if(this.resuming)throw Error(`Interrupts cannot be mutated while submitting.`)}invalidateRetry(){this.retrySubmission=void 0}submitBatch(e){this.resuming=!0,this.retrySubmission=void 0;for(let e of this.items)J_(e)&&(e.status=`submitting`);this.publish(),this.performSubmission(e)}async performSubmission(e){try{await this.options.submit(e)}catch(t){this.handleSubmissionFailure(t,e)}finally{this.resuming=!1,this.publish()}}handleSubmissionFailure(e,t){let n=hv(e);if(n.length===0){let n=e instanceof Error?e.message:String(e);this.addRootError(`transport`,n,!0,`transport`),this.retrySubmission=t;for(let e of this.items)J_(e)&&(e.status=`error`);return}let r=n.filter(e=>yv(e,t));r.length!==n.length&&this.addRootError(`protocol`,`Interrupt submission errors did not match the active batch.`,!1);let i=!1,a=!1,o=[];for(let e of r)if((e.code===`stale`||e.code===`expired`||e.code===`conflict`)&&(i=!0),a||=e.retryable,e.scope===`item`){let t=this.items.find(t=>J_(t)&&t.descriptor.id===e.interruptId);t&&(t.status=`error`,t.error=B(e))}else o.push(B(e));let s=vv(this.rootErrors,this.submissionRootErrors,o);this.rootErrors=s.rootErrors,this.submissionRootErrors=s.submissionRootErrors;for(let e of this.items)J_(e)&&e.status===`submitting`&&(e.status=`error`);this.retrySubmission=a&&!i?t:void 0}addRootError(e,t,n,r=`client`){let i=this.requireHydration();this.rootErrors=Object.freeze([...this.rootErrors,Object.freeze({scope:`batch`,code:e,message:t,source:r,retryable:n,interruptIds:Object.freeze(this.items.filter(J_).map(e=>e.descriptor.id)),threadId:i.threadId,interruptedRunId:i.interruptedRunId,generation:i.generation})]),this.publish()}findItem(e){let t=this.items.find(t=>t.descriptor.id===e);if(!t)throw Error(`Unknown interrupt: ${e}`);return t}requireHydration(){if(!this.hydration)throw Error(`InterruptManager is not hydrated.`);return this.hydration}itemError(e,t,n,r){let i=this.requireHydration();return Object.freeze({scope:`item`,interruptId:e,code:t,message:n,...r===void 0?{}:{path:Object.freeze([...r])},source:`client`,retryable:!1,threadId:i.threadId,interruptedRunId:i.interruptedRunId,generation:i.generation})}},Cv=class{clientId;constructor(e){this.clientId=e}clientCreated(e){this.emitEvent(`client:created`,{initialMessageCount:e})}loadingChanged(e){this.emitEvent(`client:loading:changed`,{isLoading:e})}errorChanged(e){this.emitEvent(`client:error:changed`,{error:e})}textUpdated(e,t,n,r){this.emitEvent(`text:chunk:content`,{streamId:e,messageId:t,content:n,...r})}toolCallStateChanged(e,t,n,r,i,a,o){this.emitEvent(`tools:call:updated`,{streamId:e,messageId:t,toolCallId:n,toolName:r,state:i,arguments:a,...o})}thinkingUpdated(e,t,n,r,i){this.emitEvent(`text:chunk:thinking`,{streamId:e,messageId:t,content:n,delta:r,...i})}structuredOutputChanged(e,t,n,r,i){this.emitEvent(e,{streamId:t,messageId:n,...r,...i})}approvalRequested(e,t,n,r,i,a,o){this.emitEvent(`tools:approval:requested`,{streamId:e,messageId:t,toolCallId:n,toolName:r,input:i,approvalId:a,...o})}messageAppended(e,t,n){let r=e.parts.filter(e=>e.type===`text`).map(e=>e.content).join(` `);this.emitEvent(`text:message:created`,{streamId:t,messageId:e.id,role:e.role,content:r,parts:e.parts,...n})}messageSent(e,t){let n=typeof t==`string`?t:t.filter(e=>e.type===`text`).map(e=>e.content).join(``);this.emitEvent(`text:message:created`,{messageId:e,role:`user`,content:n,...Array.isArray(t)&&{parts:t}}),this.emitEvent(`text:message:user`,{messageId:e,role:`user`,content:n,...Array.isArray(t)&&{parts:t}})}reloaded(e){this.emitEvent(`client:reloaded`,{fromMessageIndex:e})}stopped(){this.emitEvent(`client:stopped`)}messagesCleared(){this.emitEvent(`client:messages:cleared`)}toolResultAdded(e,t,n,r,i){this.emitEvent(`tools:result:added`,{toolCallId:e,toolName:t,output:n,state:r,...i})}toolApprovalResponded(e,t,n,r){this.emitEvent(`tools:approval:responded`,{approvalId:e,toolCallId:t,approved:n,...r})}toolFixtureApplied(e){this.emitEvent(`devtools:tool-fixture:applied`,{...e})}},wv=class extends Cv{emitEvent(){}},Tv=class{events;constructor(e){this.events=new wv(e.clientId)}emitRegistered(){}emitUpdated(){}emitSnapshot(){}emitToolsRegistered(){}emitRunLifecycle(e,t,n,r){}deactivate(){}supersede(){}dispose(){}mountWithTools(e){}notifyToolsChanged(){}setCurrentStreamId(e){}recordStreamId(e){}getCurrentStreamId(){return null}getLastStreamId(){return null}resolveStreamId(){return``}observeChunk(e){}recordMemoryState(e){}beginRun(e,t){}getCurrentRunEventContext(){}getCurrentOrLastRunEventContext(){}findToolCallContext(e){return{toolCallId:e}}async applyFixture(e){}},Ev=e=>new Tv(e);function Dv(e){if(Array.isArray(e))return{messages:e};if(e&&Array.isArray(e.messages))return e}function Ov(e){return`toolCallId`in e&&typeof e.toolCallId==`string`?e.toolCallId:void 0}function kv(e){return`messageId`in e&&typeof e.messageId==`string`?e.messageId:void 0}function Av(e){return`parentMessageId`in e&&typeof e.parentMessageId==`string`?e.parentMessageId:void 0}var jv=class{adapter;id;applyMessages;applyResume;skipNextPersist=!1;generation=0;queue=Promise.resolve();queuePending=!1;messagesGeneration=0;lastMessages=[];lastResume=null;clearedMessageIds=new Set;clearedRunIds=new Set;ignoredActiveRunIds=new Set;clearedToolCallIds=new Set;currentRunlessRunId=null;constructor(e,t,n,r){this.adapter=e,this.id=t,this.applyMessages=n,this.applyResume=r}writeState(){let e=[...this.lastMessages];if(e.length===0&&!this.lastResume){let e=this.generation;this.runOperation(()=>{if(e===this.generation)return this.adapter.removeItem(this.id)});return}let t=this.generation,n={messages:e,...this.lastResume?{resume:this.lastResume}:{}};this.runOperation(()=>{if(t===this.generation)return this.adapter.setItem(this.id,n)})}readInitial(){try{let e=this.adapter.getItem(this.id);if(e instanceof Promise)return e.then(Dv).catch(()=>void 0);let t=Dv(e);return t&&(this.lastMessages=t.messages,this.lastResume=t.resume??null),t}catch{return}}hydrateAsync(e){if(!(e instanceof Promise))return;let t=this.messagesGeneration;e.then(e=>{!e||this.messagesGeneration!==t||(this.lastResume=e.resume??null,this.lastMessages=e.messages,this.applyMessages(e.messages),e.resume&&this.applyResume&&this.applyResume(e.resume))}).catch(()=>{})}notifyMessagesChanged(e){if(this.messagesGeneration++,this.lastMessages=[...e],this.skipNextPersist){this.skipNextPersist=!1;return}this.writeState()}persistResumeSnapshot(e){this.lastResume=e,!this.skipNextPersist&&this.writeState()}remove(){this.lastMessages=[],this.lastResume=null;let e=++this.generation;this.runOperation(()=>{if(e===this.generation)return this.adapter.removeItem(this.id)})}runOperation(e){if(this.queuePending){let t=this.queue.then(e).catch(()=>{});this.queue=t,t.finally(()=>{this.queue===t&&(this.queuePending=!1)});return}try{let t=e();if(t instanceof Promise){this.queuePending=!0;let e=t.catch(()=>{});this.queue=e,e.finally(()=>{this.queue===e&&(this.queuePending=!1)})}}catch{}}snapshotClear(e){for(let t of e.messages)this.clearedMessageIds.add(t.id);for(let t of e.activeRunIds)this.clearedRunIds.add(t),this.ignoredActiveRunIds.add(t);e.currentRunId&&(this.clearedRunIds.add(e.currentRunId),this.ignoredActiveRunIds.add(e.currentRunId))}beginClear(){this.skipNextPersist=!0}shouldIgnoreChunk(e){let t=b_(e);if(t&&this.clearedRunIds.has(t))return e.type===`RUN_STARTED`&&(this.ignoredActiveRunIds.add(t),this.currentRunlessRunId=t),this.markIgnoredChunkIds(e),!0;if(t&&this.ignoredActiveRunIds.has(t)||this.isRunlessChunkFromIgnoredRun(e))return this.markIgnoredChunkIds(e),!0;let n=Ov(e);if(n&&this.clearedToolCallIds.has(n))return!0;let r=Av(e);if(r&&this.clearedMessageIds.has(r))return n&&this.clearedToolCallIds.add(n),!0;let i=kv(e);return i?!!this.clearedMessageIds.has(i):!1}onRunStarted(e){this.currentRunlessRunId=e}onRunSettled(e){this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId===e&&(this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null)}onSessionRunError(){this.ignoredActiveRunIds.clear(),this.currentRunlessRunId=null}resetIgnored(){this.ignoredActiveRunIds.clear()}takeRunlessRunId(){let e=this.currentRunlessRunId;return e?(this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null,e):null}markIgnoredChunkIds(e){let t=kv(e);t&&this.clearedMessageIds.add(t);let n=Ov(e);n&&this.clearedToolCallIds.add(n)}isRunlessChunkFromIgnoredRun(e){return b_(e)||!this.currentRunlessRunId||!this.ignoredActiveRunIds.has(this.currentRunlessRunId)&&!this.clearedRunIds.has(this.currentRunlessRunId)?!1:e.type===`TEXT_MESSAGE_START`||e.type===`TEXT_MESSAGE_CONTENT`||e.type===`TOOL_CALL_START`||e.type===`TOOL_CALL_ARGS`||e.type===`TOOL_CALL_END`||e.type===`TOOL_CALL_RESULT`||e.type===`MESSAGES_SNAPSHOT`||e.type===`RUN_ERROR`}};function Mv(e){return`toolCallId`in e&&typeof e.toolCallId==`string`?e.toolCallId:void 0}function Nv(e){return`messageId`in e&&typeof e.messageId==`string`?e.messageId:void 0}function Pv(e){return`parentMessageId`in e&&typeof e.parentMessageId==`string`?e.parentMessageId:void 0}var Fv=class{clearedMessageIds=new Set;clearedRunIds=new Set;ignoredActiveRunIds=new Set;clearedToolCallIds=new Set;currentRunlessRunId=null;snapshotClear(e){for(let t of e.messages)this.clearedMessageIds.add(t.id);for(let t of e.activeRunIds)this.clearedRunIds.add(t),this.ignoredActiveRunIds.add(t);e.currentRunId&&(this.clearedRunIds.add(e.currentRunId),this.ignoredActiveRunIds.add(e.currentRunId))}shouldIgnoreChunk(e){let t=b_(e);if(t&&this.clearedRunIds.has(t))return e.type===`RUN_STARTED`&&(this.ignoredActiveRunIds.add(t),this.currentRunlessRunId=t),this.markIgnoredChunkIds(e),!0;if(t&&this.ignoredActiveRunIds.has(t)||this.isRunlessChunkFromIgnoredRun(e))return this.markIgnoredChunkIds(e),!0;let n=Mv(e);if(n&&this.clearedToolCallIds.has(n))return!0;let r=Pv(e);if(r&&this.clearedMessageIds.has(r))return n&&this.clearedToolCallIds.add(n),!0;let i=Nv(e);return!!(i&&this.clearedMessageIds.has(i))}onRunStarted(e){this.currentRunlessRunId=e}onRunSettled(e){this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId===e&&(this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null)}onSessionRunError(){this.ignoredActiveRunIds.clear(),this.currentRunlessRunId=null}resetActiveRuns(){this.ignoredActiveRunIds.clear(),this.currentRunlessRunId=null}takeRunlessRunId(){let e=this.currentRunlessRunId;return e?(this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null,e):null}markIgnoredChunkIds(e){let t=Nv(e);t&&this.clearedMessageIds.add(t);let n=Mv(e);n&&this.clearedToolCallIds.add(n)}isRunlessChunkFromIgnoredRun(e){return b_(e)||!this.currentRunlessRunId||!this.ignoredActiveRunIds.has(this.currentRunlessRunId)&&!this.clearedRunIds.has(this.currentRunlessRunId)?!1:e.type===`TEXT_MESSAGE_START`||e.type===`TEXT_MESSAGE_CONTENT`||e.type===`TOOL_CALL_START`||e.type===`TOOL_CALL_ARGS`||e.type===`TOOL_CALL_END`||e.type===`TOOL_CALL_RESULT`||e.type===`MESSAGES_SNAPSHOT`||e.type===`RUN_ERROR`}};function Iv(e){let t=new Set;for(let n of e??[]){if(t.has(n.id))throw Error(`Duplicate interrupt definition id: ${n.id}`);t.add(n.id)}}function Lv(e){let{connection:t,fetcher:n}=e;if(t&&n)throw Error("ChatClient: pass either `connection` or `fetcher`, not both.");if(t)return t;if(n)return K_(n);throw Error("ChatClient: either `connection` or `fetcher` is required.")}function Rv(e){let t={whenBusy:`queue`,drain:`fifo`,onOverflow:`reject`};if(!e)return t;if(typeof e==`string`)return{...t,whenBusy:e};if(typeof e==`function`)return{...t,strategy:e};let n=e.maxSize;if(n!==void 0&&(!Number.isInteger(n)||n<0))throw Error(`ChatClient: queue.maxSize must be a non-negative integer`);return{whenBusy:e.whenBusy??`queue`,drain:e.drain??`fifo`,onOverflow:e.onOverflow??`reject`,...n===void 0?{}:{maxSize:n}}}function zv(e){let t=e.at(-1)?.body,n=[];for(let t of e){if(typeof t.content!=`string`)break;n.push(t.content)}if(n.length===e.length)return{content:n.join(`
27
- `),...t===void 0?{}:{body:t}};let r=[];for(let t of e)typeof t.content==`string`?r.push({type:`text`,content:t.content}):typeof t.content.content==`string`?r.push({type:`text`,content:t.content.content}):r.push(...t.content.content);return{content:{content:r},...t===void 0?{}:{body:t}}}function Bv(e){if(!(typeof e!=`object`||!e||Array.isArray(e))&&!(!(`approved`in e)||typeof e.approved!=`boolean`))return e.approved}function Vv(e){let t=e;if(typeof t!=`object`||!t||!(`resumeState`in t))return;let n=t.resumeState;if(!(typeof n!=`object`||!n||!(`threadId`in n)||typeof n.threadId!=`string`||n.threadId.length===0||!(`runId`in n)||typeof n.runId!=`string`||n.runId.length===0))return{threadId:n.threadId,runId:n.runId}}var Hv=2e3,Uv=new Set([`TEXT_MESSAGE_START`,`TEXT_MESSAGE_CONTENT`,`TOOL_CALL_START`,`MESSAGES_SNAPSHOT`]),Wv=class{processor;connection;uniqueId;threadId;persistor;clearedStreamTracker=new Fv;currentRunId=null;lastResume=null;rejoinedRunId=null;interruptManager;activeInterruptSubmission;interruptSubmissionFailure;joinedRunWaiters=new Map;pendingResumeParentRunId=null;pendingResumeThreadId=null;pendingResumeItems=null;activeResumeThreadId=null;activeResumeRunId=null;bodyOption={};forwardedPropsOption={};context=void 0;pendingMessageBody=void 0;queueConfig;messageQueue=[];sendInFlight=!1;messageQueueDraining=!1;stopMessageQueueDrain=!1;deliverClaim=!1;isLoading=!1;isSubscribed=!1;error=void 0;status=`ready`;connectionStatus=`disconnected`;abortController=null;clientToolsRef;devtoolsBridge;events;currentStreamId=null;currentMessageId=null;postStreamActions=[];pendingToolExecutions=new Map;activeClientTools=null;activeContext=void 0;continuationPending=!1;subscriptionAbortController=null;processingResolve=null;errorReportedGeneration=null;streamGeneration=0;continuationSkipped=!1;draining=!1;sessionGenerating=!1;activeRunIds=new Set;disposed=!1;tailing=!1;rejoinRunId;cachesMessages;devtoolsMounted=!1;callbacksRef;constructor(e){Iv(e.interrupts),this.threadId=e.threadId||``,this.uniqueId=this.threadId;let t=!0;if(e.persistence===!0){if(!e.threadId)throw Error("[TanStack AI] persistence needs a stable `threadId` to key on. Pass a threadId from your app (for example support-42).");t=!1}else if(e.persistence){if(!e.threadId)throw Error("[TanStack AI] persistence needs a stable `threadId` to key on. Pass a threadId from your app (for example support-42).");this.persistor=new jv(e.persistence,e.threadId,e=>this.processor.setMessages(e),e=>this.applyPersistedResume(e))}if(this.bodyOption=e.body||{},this.forwardedPropsOption=e.forwardedProps||{},this.context=e.context,this.queueConfig=Rv(e.queue),this.connection=U_(Lv(e)),this.clientToolsRef={current:new Map},e.tools)for(let t of e.tools)this.clientToolsRef.current.set(t.name,t);this.devtoolsBridge=(e.devtoolsBridgeFactory??Ev)(this.buildDevtoolsBridgeOptions(e.devtools)),this.events=this.devtoolsBridge.events,this.callbacksRef={current:{onResponse:e.onResponse||(()=>{}),onChunk:e.onChunk||(()=>{}),onFinish:e.onFinish||(()=>{}),onError:e.onError||(()=>{}),onMessagesChange:e.onMessagesChange||(()=>{}),onLoadingChange:e.onLoadingChange||(()=>{}),onErrorChange:e.onErrorChange||(()=>{}),onStatusChange:e.onStatusChange||(()=>{}),onSubscriptionChange:e.onSubscriptionChange||(()=>{}),onConnectionStatusChange:e.onConnectionStatusChange||(()=>{}),onSessionGeneratingChange:e.onSessionGeneratingChange||(()=>{}),onQueueChange:e.onQueueChange||(()=>{}),onResumeStateChange:e.onResumeStateChange||(()=>{}),onRunIdChange:e.onRunIdChange||(()=>{}),onInterruptStateChange:e.onInterruptStateChange||(()=>{}),onCustomEvent:e.onCustomEvent||(()=>{})}},this.interruptManager=new Sv({...e.tools===void 0?{}:{tools:e.tools},...e.interrupts===void 0?{}:{interrupts:e.interrupts},submit:e=>this.submitInterruptBatch(e),onChange:e=>this.notifyResumeStateChange(e)}),e.initialResumeSnapshot&&this.applyResumeSnapshot(e.initialResumeSnapshot);let n=this.persistor?.readInitial(),r=n instanceof Promise?void 0:n,i=r?r.messages:e.initialMessages,a=null;if(r?.resume){let e=r.resume;Array.isArray(e.pendingInterrupts)&&e.pendingInterrupts.length>0?this.applyResumeSnapshot(e):e.resumeState.runId&&(a=e.resumeState.runId)}if(!a&&e.initialResumeSnapshot){let t=e.initialResumeSnapshot;!(Array.isArray(t.pendingInterrupts)&&t.pendingInterrupts.length>0)&&t.resumeState.runId&&(a=t.resumeState.runId)}this.processor=new Tm({...e.streamProcessor?.chunkStrategy?{chunkStrategy:e.streamProcessor.chunkStrategy}:{},...i?{initialMessages:i}:{},events:{onMessagesChange:e=>{this.persistor?.notifyMessagesChanged(e),this.callbacksRef.current.onMessagesChange(e)},onStreamStart:()=>{this.setStatus(`streaming`);let e=this.processor.getCurrentAssistantMessageId();if(!e)return;let t=this.processor.getMessages().find(t=>t.id===e);t&&(this.currentMessageId=t.id,this.events.messageAppended(t,this.currentStreamId||void 0))},onStreamEnd:e=>{this.callbacksRef.current.onFinish(e),this.setStatus(`ready`),this.resolveProcessing()},onError:e=>{this.reportStreamError(e)},onTextUpdate:(e,t)=>{this.currentStreamId&&this.events.textUpdated(this.currentStreamId,e,t)},onThinkingUpdate:(e,t)=>{this.currentStreamId&&this.events.thinkingUpdated(this.currentStreamId,e,t,void 0)},onStructuredOutputChange:e=>{let t=this.devtoolsBridge.resolveStreamId(),n=e.phase===`start`?`structured-output:started`:e.phase===`complete`?`structured-output:completed`:e.phase===`error`?`structured-output:errored`:`structured-output:updated`;this.currentMessageId=e.messageId,this.events.structuredOutputChanged(n,t,e.messageId,{status:e.status,raw:e.raw,...e.partial===void 0?{}:{partial:e.partial},...e.data===void 0?{}:{data:e.data},...e.reasoning===void 0?{}:{reasoning:e.reasoning},...e.errorMessage===void 0?{}:{errorMessage:e.errorMessage},...e.delta===void 0?{}:{delta:e.delta}})},onToolCallStateChange:(e,t,n,r)=>{let i=this.processor.getMessages().find(t=>t.id===e)?.parts.find(e=>e.type===`tool-call`&&e.id===t)?.name||`unknown`;this.currentStreamId&&this.events.toolCallStateChanged(this.currentStreamId,e,t,i,n,r)},onToolCall:e=>{let t=(this.activeClientTools??this.clientToolsRef.current).get(e.toolName),n=t?.execute;if(n){let r=this.devtoolsBridge.getCurrentRunEventContext(),i=(async()=>{try{let i=this.activeClientTools===null?this.context:this.activeContext,a=await n(e.input,{toolCallId:e.toolCallId,context:i,emitCustomEvent:()=>{}});await this.addToolResultForClientTool({toolCallId:e.toolCallId,tool:e.toolName,output:a,state:`output-available`},t,r)}catch(n){await this.addToolResultForClientTool({toolCallId:e.toolCallId,tool:e.toolName,output:null,state:`output-error`,errorText:n.message},t,r)}finally{this.pendingToolExecutions.delete(e.toolCallId)}})();this.pendingToolExecutions.set(e.toolCallId,i)}},onApprovalRequest:e=>{let t=this.devtoolsBridge.resolveStreamId(),n=this.findMessageIdForToolCall(e.toolCallId)??this.currentMessageId??``;this.events.approvalRequested(t,n,e.toolCallId,e.toolName,e.input,e.approvalId)},onCustomEvent:(e,t,n)=>{e===`memory:state`&&this.devtoolsBridge.recordMemoryState(t),this.callbacksRef.current.onCustomEvent(e,t,n)}}}),this.persistor?.hydrateAsync(n),this.rejoinRunId=a,this.cachesMessages=t}attach(){this.disposed||this.tailing||(this.ensureThreadId(),this.tailing=!0,this.rejoinRunId&&this.maybeRejoinInFlight(this.rejoinRunId),!this.cachesMessages&&this.connection.hydrate&&this.hydrateFromServer())}detach(){this.tailing&&(this.tailing=!1,this.cancelInFlightStream({setReadyStatus:!0}),this.rejoinedRunId=null)}applyResumeSnapshot(e){let t=Vv(e);if(t===void 0){this.interruptManager.reset({source:`hydrate`});return}this.lastResume=t;let n=Array.isArray(e.pendingInterrupts)?e.pendingInterrupts:[];if(n.length===0){this.interruptManager.reset({source:`hydrate`});return}let r=this.interruptGeneration(n);this.interruptManager.hydrate({threadId:t.threadId,interruptedRunId:t.runId,generation:r,interrupts:n},`hydrate`)}applyPersistedResume(e){this.applyResumeSnapshot(e);let t=Array.isArray(e.pendingInterrupts)&&e.pendingInterrupts.length>0,n=e.resumeState?.runId;!t&&n&&this.maybeRejoinInFlight(n)}maybeRejoinInFlight(e){this.connection.joinRun&&(this.disposed||!this.tailing||this.rejoinedRunId!==e&&(this.isLoading||this.abortController||(this.rejoinedRunId=e,this.resumeInFlightRun(e))))}hydrateFromServer(){let e=this.connection.hydrate;e&&(this.isLoading||this.abortController||this.disposed||(async()=>{let t;try{t=await e(this.threadId)}catch{return}this.disposed||!this.tailing||this.isLoading||this.abortController||(t.messages.length>0&&this.processor.setMessages(t.messages),t.interrupts&&t.interrupts.pending.length>0?this.applyResumeSnapshot({resumeState:{threadId:this.threadId,runId:t.interrupts.runId},pendingInterrupts:t.interrupts.pending}):t.activeRun?.runId&&this.maybeRejoinInFlight(t.activeRun.runId))})())}mountDevtools(){this.ensureThreadId(),!this.devtoolsMounted&&(this.devtoolsMounted=!0,this.devtoolsBridge.mountWithTools(this.processor.getMessages().length))}ensureThreadId(){return this.threadId||=this.generateUniqueId(`thread`),this.uniqueId=this.threadId,this.threadId}drainIgnoredRunlessChunk(e){if(e.type!==`RUN_ERROR`)return;let t=this.clearedStreamTracker.takeRunlessRunId();t&&(this.activeRunIds.delete(t),this.setSessionGenerating(this.activeRunIds.size>0),this.resolveProcessing())}retireIgnoredClearedTerminalChunk(e){if(e.type!==`RUN_FINISHED`&&e.type!==`RUN_ERROR`)return;let t=b_(e)??this.clearedStreamTracker.takeRunlessRunId();t&&(this.activeRunIds.delete(t),this.setSessionGenerating(this.activeRunIds.size>0),b_(e)||this.resolveProcessing())}updateRunLifecycle(e,t){if(e.type===`RUN_STARTED`){let t=b_(e)??e.runId;this.activeResumeThreadId=`threadId`in e&&typeof e.threadId==`string`?e.threadId:this.activeResumeThreadId,this.activeResumeRunId=t,this.activeRunIds.add(t),this.clearedStreamTracker.onRunStarted(t),this.setSessionGenerating(!0),this.persistor&&this.connection.joinRun&&!this.lastResume&&this.persistResumeSnapshot({threadId:this.activeResumeThreadId??this.threadId,runId:t});return}if(e.type!==`RUN_FINISHED`&&e.type!==`RUN_ERROR`)return;let n=b_(e);n?(this.activeRunIds.delete(n),this.clearedStreamTracker.onRunSettled(n)):e.type===`RUN_ERROR`&&(this.activeRunIds.clear(),this.clearedStreamTracker.onSessionRunError()),this.setSessionGenerating(this.activeRunIds.size>0),t?.resolveProcessing!==!1&&this.resolveProcessing()}observeInterruptState(e){if(e.type!==`RUN_FINISHED`&&e.type!==`RUN_ERROR`||this.activeInterruptSubmission&&e.type===`RUN_ERROR`)return;let t=b_(e),n=`threadId`in e&&typeof e.threadId==`string`?e.threadId:this.activeResumeThreadId;if(e.type===`RUN_FINISHED`&&e.outcome?.type===`interrupt`){let r=this.currentRunId??t??this.activeResumeRunId??``;this.lastResume={threadId:n??this.threadId,runId:r},this.interruptManager.hydrate({threadId:this.lastResume.threadId,interruptedRunId:r,generation:this.interruptGeneration(e.outcome.interrupts),interrupts:e.outcome.interrupts},`live`);return}let r=e.type===`RUN_ERROR`&&!t,i=!!(t&&this.lastResume?.runId===t),a=!!(t&&this.currentRunId===t||this.currentRunId&&this.lastResume?.runId===this.currentRunId),o=!!(this.isLoading&&t&&(t===this.activeResumeRunId||t===this.currentRunId)),s=this.isLoading&&e.type===`RUN_FINISHED`&&!t,c=!!(this.activeInterruptSubmission&&this.isLoading&&e.type===`RUN_FINISHED`&&e.outcome?.type!==`interrupt`);if(r||i||a||o||s||c){this.lastResume=null,this.persistor?.persistResumeSnapshot(null),this.interruptManager.reset();return}this.notifyResumeStateChange(`live`)}getResumeState(){return this.lastResume?{...this.lastResume}:null}getCurrentRunId(){return this.currentRunId}setCurrentRunId(e){this.currentRunId!==e&&(this.currentRunId=e,this.callbacksRef.current.onRunIdChange(e))}getInterruptState(){return this.interruptManager.getState()}getInterrupts(){return this.interruptManager.getInterrupts()}getPendingInterrupts(){return this.interruptManager.getInterrupts()}resolveInterrupts(e){if(typeof e==`boolean`){this.interruptManager.resolve(e);return}this.interruptManager.resolve(e)}cancelInterrupts(){this.interruptManager.cancel()}retryInterrupts(){this.interruptManager.retry()}resumeInterruptsUnsafe(e,t){let n=t??this.lastResume;return n?this.isLoading?new Promise((t,r)=>{this.queuePostStreamAction(async()=>{try{t(await this.resumeInterruptsUnsafe(e,n))}catch(e){r(e)}})}):(this.pendingResumeThreadId=n.threadId,this.pendingResumeParentRunId=n.runId,this.pendingResumeItems=[...e],this.streamResponse()):Promise.resolve(!1)}resumeInterrupts(e,t){return this.resumeInterruptsUnsafe(e,t)}async submitInterruptBatch(e){this.activeInterruptSubmission=e,this.interruptSubmissionFailure=void 0;for(let t of e.resolutions){let e=Bv(t.payload);if(e===void 0)continue;let n=t.interruptId;this.processor.addToolApprovalResponse(n,e)}let t=await this.resumeInterruptsUnsafe([...e.resolutions],{threadId:e.threadId,runId:e.interruptedRunId}).finally(()=>{this.activeInterruptSubmission=void 0}),n=this.takeInterruptSubmissionFailure();if(n!==void 0)throw{errors:n.errors};if(!t)throw Error(`Interrupt continuation could not be started.`);this.lastResume?.runId===e.interruptedRunId&&(this.lastResume=null,this.interruptManager.reset())}takeInterruptSubmissionFailure(){let e=this.interruptSubmissionFailure;return this.interruptSubmissionFailure=void 0,e}interruptGeneration(e){let t;for(let n of e){let e=n.metadata?.[`tanstack:interruptBinding`];if(typeof e!=`object`||!e||!(`generation`in e)||typeof e.generation!=`number`||!Number.isInteger(e.generation)||e.generation<0||t!==void 0&&t!==e.generation)return 0;t=e.generation}return t??0}generateUniqueId(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(7)}`}setIsLoading(e){this.isLoading=e,this.callbacksRef.current.onLoadingChange(e),this.events.loadingChanged(e)}setStatus(e){this.status=e,this.callbacksRef.current.onStatusChange(e),this.devtoolsBridge.emitSnapshot()}setIsSubscribed(e){this.isSubscribed=e,this.callbacksRef.current.onSubscriptionChange(e),this.devtoolsBridge.emitSnapshot()}setConnectionStatus(e){this.connectionStatus=e,this.callbacksRef.current.onConnectionStatusChange(e),this.devtoolsBridge.emitSnapshot()}setSessionGenerating(e){this.sessionGenerating!==e&&(this.sessionGenerating=e,this.callbacksRef.current.onSessionGeneratingChange(e),this.devtoolsBridge.emitSnapshot())}notifyResumeStateChange(e){let t=this.getResumeState(),n=this.interruptManager.getState();this.persistResumeSnapshot(t),this.callbacksRef.current.onResumeStateChange(t,n.interrupts),this.callbacksRef.current.onInterruptStateChange(n,{source:e})}persistResumeSnapshot(e){if(!this.persistor)return;if(!e){this.persistor.persistResumeSnapshot(null);return}let t=this.interruptManager.getDescriptors();this.persistor.persistResumeSnapshot({resumeState:e,...t.length>0?{pendingInterrupts:[...t]}:{}})}resetSessionGenerating(e){this.activeRunIds.clear(),e?.preserveClearedStreamTracking||this.clearedStreamTracker.resetActiveRuns(),this.setSessionGenerating(!1)}setError(e){this.error=e,this.callbacksRef.current.onErrorChange(e),this.events.errorChanged(e?.message||null)}buildDevtoolsBridgeOptions(e){let t=this;return{get hookId(){return t.uniqueId},get clientId(){return t.uniqueId},get threadId(){return t.threadId},metadata:{hookName:e?.hookName??`useChat`,outputKind:e?.outputKind??`chat`,...e?.framework?{framework:e.framework}:{},...e?.name?{name:e.name}:{}},getSnapshot:()=>this.getDevtoolsSnapshot(),getTools:()=>this.clientToolsRef.current.values(),getMessages:()=>this.processor.getMessages(),setMessages:e=>{this.processor.setMessages(e)},addToolResult:(e,t,n)=>{this.processor.addToolResult(e,t,n)},generateId:e=>this.generateUniqueId(e)}}getDevtoolsSnapshot(){return{messages:this.processor.getMessages(),status:this.status,isLoading:this.isLoading,isSubscribed:this.isSubscribed,connectionStatus:this.connectionStatus,sessionGenerating:this.sessionGenerating,activeRunIds:Array.from(this.activeRunIds),queue:this.getQueue(),...this.error?{error:this.error.message}:{}}}findMessageIdForToolCall(e){let t=this.processor.getMessages();for(let n of t)if(n.parts.find(t=>t.type===`tool-call`&&t.id===e))return n.id}abortSubscriptionLoop(){this.subscriptionAbortController?.abort(),this.subscriptionAbortController=null}resolveProcessing(){this.processingResolve?.(),this.processingResolve=null}cancelInFlightStream(e){this.abortController?.abort(),this.abortController=null,e?.abortSubscription&&this.abortSubscriptionLoop(),this.resolveProcessing(),this.setIsLoading(!1),this.deliverClaim=!1,e?.setReadyStatus&&this.setStatus(`ready`)}reportStreamError(e){let t=this.errorReportedGeneration===this.streamGeneration;this.setError(e),(this.isLoading||this.status===`submitted`||this.status===`streaming`)&&this.setStatus(`error`),t||(this.errorReportedGeneration=this.streamGeneration,this.callbacksRef.current.onError(e))}startSubscription(){this.subscriptionAbortController=new AbortController;let e=this.subscriptionAbortController.signal;this.consumeSubscription(e).catch(e=>{e instanceof Error&&e.name!==`AbortError`&&(this.setConnectionStatus(`error`),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.reportStreamError(e)),this.resolveProcessing()}).finally(()=>{this.subscriptionAbortController?.signal===e&&(this.subscriptionAbortController=null,!e.aborted&&this.isSubscribed&&(this.setIsSubscribed(!1),this.connectionStatus!==`error`&&this.setConnectionStatus(`disconnected`)))})}async consumeSubscription(e){let t=this.connection.subscribe(e);for await(let n of t){if(e.aborted)break;await this.processIncomingChunk(n)}}resumeInFlightRun(e){let t=this.connection.joinRun;if(!t)return;let n=new AbortController;this.abortController=n,this.setCurrentRunId(e),this.lastResume={threadId:this.threadId,runId:e},this.setIsLoading(!0),this.setStatus(`streaming`),(async()=>{let r=!1,i=!1,a=!1,o=setTimeout(()=>{i||n.abort()},Hv);try{for await(let a of t(e,n.signal)){if(n.signal.aborted)break;i||(i=!0,clearTimeout(o)),!r&&Uv.has(a.type)&&(r=!0,this.dropTrailingInFlightAssistant()),await this.processIncomingChunk(a,{defer:!1})}this.pendingToolExecutions.size>0&&await Promise.all(this.pendingToolExecutions.values())}catch(e){let t=e instanceof Error&&(e.name===`AbortError`||e.name===`TimeoutError`);!i&&!t&&(a=!0),i&&!t&&this.reportStreamError(e instanceof Error?e:Error(String(e)))}finally{clearTimeout(o),!i&&a&&this.tailing&&!this.disposed&&(this.lastResume=null,this.persistor?.persistResumeSnapshot(null)),this.abortController===n&&(this.abortController=null,this.setIsLoading(!1),this.status===`streaming`&&this.setStatus(`ready`),await this.drainPostStreamActions())}})()}dropTrailingInFlightAssistant(){let e=this.processor.getMessages(),t=e[e.length-1];t&&t.role===`assistant`&&this.processor.setMessages(e.slice(0,-1))}async processIncomingChunk(e,t){if(e.type===`RUN_ERROR`&&this.isActiveInterruptSubmissionFailure(e)&&(this.interruptSubmissionFailure={errors:e[`tanstack:interruptErrors`]??[]}),this.connectionStatus===`connecting`&&this.setConnectionStatus(`connected`),this.clearedStreamTracker.shouldIgnoreChunk(e)){(e.type===`RUN_FINISHED`||e.type===`RUN_ERROR`)&&(b_(e)?this.updateRunLifecycle(e,{resolveProcessing:!1}):this.drainIgnoredRunlessChunk(e),this.retireIgnoredClearedTerminalChunk(e),this.resolveJoinedRun(e));return}this.callbacksRef.current.onChunk(e),this.devtoolsBridge.observeChunk(e),this.processor.processChunk(e),this.updateRunLifecycle(e),this.observeInterruptState(e),t?.defer!==!1&&(typeof document>`u`||!document.hidden)&&await new Promise(e=>setTimeout(e,0)),this.resolveJoinedRun(e)}isActiveInterruptSubmissionFailure(e){let t=this.activeInterruptSubmission,n=e[`tanstack:interruptErrors`];if(!t||!n||n.length===0)return!1;let r=b_(e);return r!==void 0&&r!==this.currentRunId||typeof e.threadId==`string`&&e.threadId!==t.threadId?!1:n.every(e=>e.threadId===t.threadId&&e.interruptedRunId===t.interruptedRunId&&e.generation===t.generation)}resolveJoinedRun(e){if(e.type!==`RUN_FINISHED`&&e.type!==`RUN_ERROR`)return;let t=b_(e);if(t===void 0)return;let n=this.joinedRunWaiters.get(t);n!==void 0&&(this.joinedRunWaiters.delete(t),n())}ensureSubscription(){if(!this.isSubscribed){this.subscribe();return}(!this.subscriptionAbortController||this.subscriptionAbortController.signal.aborted)&&this.subscribe({restart:!0})}waitForProcessing(){return this.resolveProcessing(),new Promise(e=>{this.processingResolve=e})}async sendMessage(e,t,n){if(this.mountDevtools(),!(typeof e==`string`&&!e.trim())){if(this.hasBlockingInterrupts())throw Error(`ChatClient: cannot send normal input while pending interrupts exist. Use resumeInterrupts() instead.`);if(this.isSendBusy()){let{action:r,id:i}=this.decideWhenBusy(e,n);if(r===`drop`)return;if(r===`queue`){this.enqueueMessage(e,t,i);return}this.stopMessageQueueDrain=!0,this.sendInFlight=!0,this.cancelInFlightStream({setReadyStatus:!0}),this.resetSessionGenerating()}else this.sendInFlight=!0;try{await this.deliverMessage(e,t)}finally{this.sendInFlight=!1}}}hasPendingInterrupts(){return this.interruptManager.getDescriptors().length>0}hasBlockingInterrupts(){return this.activeInterruptSubmission!==void 0||this.hasPendingInterrupts()}isSendBusy(){return this.isLoading||this.sendInFlight||this.messageQueueDraining}resolveBusyReason(){return this.isLoading?`streaming`:this.messageQueueDraining?`draining`:`sendInFlight`}async deliverMessage(e,t){if(this.isLoading||this.deliverClaim)return!1;this.deliverClaim=!0;try{let n=this.normalizeMessageInput(e);this.pendingMessageBody=t;let r=this.processor.addUserMessage(n.content,n.id);return this.events.messageSent(r.id,n.content),await this.streamResponse()}finally{this.deliverClaim=!1}}decideWhenBusy(e,t){let n=this.generateUniqueId(`queued`);if(t?.whenBusy)return{action:t.whenBusy,id:n};let{strategy:r,whenBusy:i}=this.queueConfig;if(r){let{action:t}=r({pending:{id:n,content:e,createdAt:Date.now()},busyReason:this.resolveBusyReason(),queued:this.getQueue()});return{action:t,id:n}}return{action:i,id:n}}enqueueMessage(e,t,n){let{maxSize:r,onOverflow:i}=this.queueConfig;if(r!==void 0&&this.messageQueue.length>=r){if(i===`reject`||r===0)return;this.messageQueue.shift()}this.messageQueue.push({id:n??this.generateUniqueId(`queued`),content:e,createdAt:Date.now(),...t===void 0?{}:{body:t}}),this.emitQueueChange()}normalizeMessageInput(e){return typeof e==`string`?{content:e.trim()}:{content:e.content,id:e.id}}async append(e){if(this.mountDevtools(),this.hasBlockingInterrupts())throw Error(`ChatClient: cannot append normal input while pending interrupts exist. Use resumeInterrupts() instead.`);let t=am(e,om);if(t.role===`system`)return;let n=t;this.events.messageAppended(n);let r=this.processor.getMessages();if(this.processor.setMessages([...r,n]),this.devtoolsBridge.emitSnapshot(),this.isLoading){this.queuePostStreamAction(async()=>{await this.streamResponse()});return}await this.streamResponse()}async streamResponse(){if(this.isLoading)return!1;let e=++this.streamGeneration,t=this.pendingResumeThreadId,n=this.pendingResumeParentRunId,r=this.pendingResumeItems;this.pendingResumeThreadId=null,this.pendingResumeParentRunId=null,this.pendingResumeItems=null;let i=`run-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.setCurrentRunId(i),this.activeResumeThreadId=t??this.threadId,this.activeResumeRunId=i,this.setIsLoading(!0),this.deliverClaim=!1,this.setStatus(`submitted`),this.setError(void 0),this.errorReportedGeneration=null,this.abortController=new AbortController;let a=this.abortController.signal;this.pendingToolExecutions.clear();let o=!1,s=null,c=!1;try{let l=this.processor.getMessages(),u=new Map(this.clientToolsRef.current),d=this.context;if(await this.callbacksRef.current.onResponse(),a.aborted)return!1;let f={...this.bodyOption,...this.forwardedPropsOption,...this.pendingMessageBody};this.pendingMessageBody=void 0,this.currentStreamId=this.generateUniqueId(`stream`),this.devtoolsBridge.setCurrentStreamId(this.currentStreamId),this.currentMessageId=null,this.activeClientTools=u,this.activeContext=d,this.processor.prepareAssistantMessage(),this.ensureSubscription();let p=this.waitForProcessing(),m={threadId:t??this.threadId,runId:i,...n===null?{}:{parentRunId:n},clientTools:Array.from(u.values()).map(e=>({name:e.name,description:e.description,parameters:e.inputSchema?pp(e.inputSchema):{type:`object`}})),forwardedProps:{...f},...r?{resume:r}:{}};if(this.devtoolsBridge.beginRun(m.runId,m.threadId),s=m.runId,this.devtoolsBridge.emitRunLifecycle(`run:created`,m.runId,`created`),this.devtoolsBridge.emitRunLifecycle(`run:started`,m.runId,`started`),this.devtoolsBridge.emitSnapshot(),await this.connection.send(l,f,a,m),e!==this.streamGeneration||a.aborted||(await p,e!==this.streamGeneration))return!1;if(this.status===`error`)return s&&(this.devtoolsBridge.emitRunLifecycle(`run:errored`,s,`errored`,this.error?{error:this.error.message}:{}),c=!0),!1;this.pendingToolExecutions.size>0&&await Promise.all(this.pendingToolExecutions.values()),this.processor.finalizeStream(),o=!0}catch(t){if(t instanceof Error){if(t.name===`AbortError`)return s&&(this.devtoolsBridge.emitRunLifecycle(`run:cancelled`,s,`cancelled`),c=!0),!1;e===this.streamGeneration&&(this.reportStreamError(t),s&&(this.devtoolsBridge.emitRunLifecycle(`run:errored`,s,`errored`,{error:t.message}),c=!0))}}finally{if(e===this.streamGeneration){if(this.currentStreamId=null,this.devtoolsBridge.setCurrentStreamId(null),this.currentMessageId=null,this.setCurrentRunId(null),this.activeClientTools=null,this.activeContext=void 0,this.abortController=null,this.setIsLoading(!1),this.pendingMessageBody=void 0,s&&!c&&(o?this.devtoolsBridge.emitRunLifecycle(`run:completed`,s,`completed`):a.aborted&&this.devtoolsBridge.emitRunLifecycle(`run:cancelled`,s,`cancelled`)),await this.drainPostStreamActions(),o){let e=this.processor.getMessages().at(-1)?.parts.at(-1),{finishReason:t}=this.processor.getState();if(e?.type===`tool-result`&&t!==`stop`&&this.shouldAutoSend())try{await this.checkForContinuation()}catch(e){console.error(`Failed to continue flow after tool result:`,e),await this.drainQueue()}else this.status!==`ready`&&this.setStatus(`ready`),this.messageQueueDraining||await this.drainQueue()}else this.flushQueue()}}return o}subscribe(e){let t=e?.restart===!0;this.isSubscribed&&!t||(this.isSubscribed&&t&&this.abortSubscriptionLoop(),this.setIsSubscribed(!0),this.setConnectionStatus(`connecting`),this.startSubscription())}unsubscribe(){this.cancelInFlightStream({setReadyStatus:!0,abortSubscription:!0}),this.discardPendingSends(),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.setConnectionStatus(`disconnected`)}async reload(){let e=this.processor.getMessages();if(e.length===0)return;let t=e.findLastIndex(e=>e.role===`user`);t!==-1&&(this.isLoading&&this.cancelInFlightStream(),this.discardPendingSends(),this.events.reloaded(t),this.processor.removeMessagesAfter(t),this.devtoolsBridge.emitSnapshot(),await this.streamResponse())}stop(){let e=this.abortController!==null;this.cancelInFlightStream({setReadyStatus:!0}),this.discardPendingSends(),e&&this.resetSessionGenerating(),this.events.stopped()}clear(){let e=this.abortController!==null;this.clearedStreamTracker.snapshotClear({messages:this.processor.getMessages(),activeRunIds:this.activeRunIds,currentRunId:this.currentRunId}),this.isLoading||e?(this.cancelInFlightStream({setReadyStatus:!0}),this.resetSessionGenerating({preserveClearedStreamTracking:!0})):this.activeRunIds.size>0&&this.resetSessionGenerating({preserveClearedStreamTracking:!0}),this.persistor?.beginClear(),this.processor.clearMessages(),this.discardPendingSends(),this.persistor?.remove(),this.lastResume=null,this.interruptManager.reset(),this.pendingResumeThreadId=null,this.pendingResumeParentRunId=null,this.pendingResumeItems=null,this.setError(void 0),this.events.messagesCleared()}async addToolResult(e){let t=this.clientToolsRef.current.get(e.tool);await this.addToolResultForClientTool(e,t)}async addToolResultForClientTool(e,t,n){if(t&&e.state!==`output-error`)try{e={...e,output:this.validateClientToolOutput(t,e.output)}}catch(t){e={...e,output:null,state:`output-error`,errorText:t.message}}if(this.events.toolResultAdded(e.toolCallId,e.tool,e.output,e.state||`output-available`,n),this.processor.addToolResult(e.toolCallId,e.output,e.state===`output-error`?e.errorText||`Tool execution failed`:void 0),this.devtoolsBridge.emitSnapshot(),!this.interruptManager.resolveClientToolOutput(e.toolCallId,e.state===`output-error`?{error:e.errorText||`Tool execution failed`}:e.output)){if(this.isLoading){this.queuePostStreamAction(()=>this.checkForContinuation());return}await this.checkForContinuation()}}validateClientToolOutput(e,t){return e.outputSchema&&lp(e.outputSchema)?hp(e.outputSchema,t):t}async addToolApprovalResponse(e){if(this.processor.addToolApprovalResponse(e.id,e.approved),this.devtoolsBridge.emitSnapshot(),this.interruptManager.resolveToolApprovalDecision(e.id,e.approved))return;let t=this.processor.getMessages(),n;for(let r of t){let t=r.parts.find(t=>t.type===`tool-call`&&t.approval?.id===e.id);if(t){n=t.id;break}}if(n&&this.events.toolApprovalResponded(e.id,n,e.approved),this.processor.addToolApprovalResponse(e.id,e.approved),this.devtoolsBridge.emitSnapshot(),this.isLoading){this.queuePostStreamAction(()=>this.checkForContinuation());return}await this.checkForContinuation()}queuePostStreamAction(e){this.postStreamActions.push(e)}async drainPostStreamActions(){if(!this.draining){this.draining=!0;try{let e;for(;(e=this.postStreamActions.shift())!==void 0;)await e()}finally{this.draining=!1}}}async checkForContinuation(){if(!this.hasPendingInterrupts()){if(this.continuationPending||this.isLoading){this.continuationSkipped=!0;return}if(this.shouldAutoSend()){this.continuationPending=!0,this.continuationSkipped=!1;let e=!1;try{e=await this.streamResponse()}finally{this.continuationPending=!1}this.continuationSkipped&&e&&(this.continuationSkipped=!1,await this.checkForContinuation())}}}shouldAutoSend(){if(this.lastResume||this.activeInterruptSubmission&&this.hasPendingInterrupts()||this.interruptManager.getInterrupts().length>0)return!1;let e=this.processor.getMessages().findLast(e=>e.role===`assistant`);return!e||!e.parts.some(e=>e.type===`tool-call`)?!1:this.processor.areAllToolsComplete()}getMessages(){return this.processor.getMessages()}shouldAbortMessageQueueDrain(){return this.isLoading||this.stopMessageQueueDrain}async drainQueue(){if(!(this.messageQueueDraining||this.isLoading||this.messageQueue.length===0)){this.messageQueueDraining=!0,this.stopMessageQueueDrain=!1;try{if(this.queueConfig.drain===`batch`){for(;this.messageQueue.length>0;){if(this.shouldAbortMessageQueueDrain())return;let e=this.messageQueue.splice(0);this.emitQueueChange();let t=zv(e);if(!await this.deliverMessage(t.content,t.body)||this.shouldAbortMessageQueueDrain())return}return}for(;this.messageQueue.length>0;){if(this.shouldAbortMessageQueueDrain())return;let e=this.messageQueue.shift();if(e===void 0||(this.emitQueueChange(),!await this.deliverMessage(e.content,e.body)||this.shouldAbortMessageQueueDrain()))return}}finally{this.messageQueueDraining=!1,this.stopMessageQueueDrain=!1}}}discardPendingSends(){this.sendInFlight=!1,this.flushQueue()}getQueue(){return this.messageQueue.map(({id:e,content:t,createdAt:n})=>({id:e,content:t,createdAt:n}))}emitQueueChange(){this.callbacksRef.current.onQueueChange(this.getQueue()),this.devtoolsBridge.emitSnapshot()}cancelQueued(e){let t=this.messageQueue.findIndex(t=>t.id===e);t!==-1&&(this.messageQueue.splice(t,1),this.emitQueueChange())}flushQueue(){this.messageQueue.length!==0&&(this.messageQueue=[],this.emitQueueChange())}getIsLoading(){return this.isLoading}getStatus(){return this.status}getIsSubscribed(){return this.isSubscribed}getConnectionStatus(){return this.connectionStatus}getSessionGenerating(){return this.sessionGenerating}getError(){return this.error}setMessagesManually(e){this.processor.setMessages(e),this.devtoolsBridge.emitSnapshot()}updateOptions(e){if(e.connection!==void 0||e.fetcher!==void 0){let t=this.isSubscribed;this.isLoading?this.cancelInFlightStream({setReadyStatus:!0,abortSubscription:!0}):t&&this.abortSubscriptionLoop(),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.setConnectionStatus(`disconnected`),this.connection=U_(Lv({connection:e.connection,fetcher:e.fetcher})),t&&this.subscribe()}if(e.body!==void 0&&(this.bodyOption=e.body),e.forwardedProps!==void 0&&(this.forwardedPropsOption=e.forwardedProps),`context`in e&&(this.context=e.context),e.tools!==void 0){this.interruptManager.updateTools(e.tools),this.clientToolsRef.current=new Map;for(let t of e.tools)this.clientToolsRef.current.set(t.name,t);this.devtoolsBridge.notifyToolsChanged()}e.queue!==void 0&&(this.queueConfig=Rv(e.queue)),e.onResponse!==void 0&&(this.callbacksRef.current.onResponse=e.onResponse),e.onChunk!==void 0&&(this.callbacksRef.current.onChunk=e.onChunk),e.onFinish!==void 0&&(this.callbacksRef.current.onFinish=e.onFinish),e.onError!==void 0&&(this.callbacksRef.current.onError=e.onError),e.onSubscriptionChange!==void 0&&(this.callbacksRef.current.onSubscriptionChange=e.onSubscriptionChange),e.onConnectionStatusChange!==void 0&&(this.callbacksRef.current.onConnectionStatusChange=e.onConnectionStatusChange),e.onSessionGeneratingChange!==void 0&&(this.callbacksRef.current.onSessionGeneratingChange=e.onSessionGeneratingChange),e.onQueueChange!==void 0&&(this.callbacksRef.current.onQueueChange=e.onQueueChange),e.onResumeStateChange!==void 0&&(this.callbacksRef.current.onResumeStateChange=e.onResumeStateChange),e.onRunIdChange!==void 0&&(this.callbacksRef.current.onRunIdChange=e.onRunIdChange),e.onInterruptStateChange!==void 0&&(this.callbacksRef.current.onInterruptStateChange=e.onInterruptStateChange),e.onCustomEvent!==void 0&&(this.callbacksRef.current.onCustomEvent=e.onCustomEvent)}dispose(){this.disposed=!0,this.unsubscribe(),this.devtoolsBridge.dispose(),this.devtoolsMounted=!1}};function Gv(){return{name:`streaming`,transformDocument(e){let t=Kv(e.children);return t===e.children?e:{...e,children:t}}}}function Kv(e){let t=e.at(-1);if(!t)return e;let n=qv(t);return n===t?e:n?[...e.slice(0,-1),n]:e.slice(0,-1)}function qv(e){if(e.type===`heading`&&e.children.length===0)return;if(e.type===`blockquote`){let t=Kv(e.children);return t.length===0?void 0:t===e.children?e:{...e,children:t}}if(e.type!==`list`)return e;let t=e.items.at(-1);if(!t)return;let n=Jv(t);if(n===t)return e;let r=n?[...e.items.slice(0,-1),n]:e.items.slice(0,-1);return r.length===0?void 0:{...e,items:r}}function Jv(e){let t=Kv(e.children);if(t.length!==0)return t===e.children?e:{...e,children:t}}var Yv={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`};function Xv(e){return e.replace(/^\uFEFF/,``).replace(/\r\n?/g,`
28
- `)}function Zv(e){return e.replace(/[&<>"']/g,e=>Yv[e])}function $(e){return Zv(e).replace(/`/g,`&#96;`)}function Qv(e){return/^\s*$/.test(e)}function $v(e,t){let n=0;for(;n<e.length&&n<t&&e[n]===` `;)n++;return e.slice(n)}function ey(e){let t=``;for(let n of e)n.type===`text`||n.type===`inlineCode`?t+=n.value:`children`in n?t+=ey(n.children):n.type===`image`&&(t+=n.alt);return t}function ty(){let e=new Map;return t=>{let n=t.toLowerCase().normalize(`NFKD`).replace(/[\u0300-\u036f]/g,``).replace(/&[a-z0-9#]+;/gi,``).replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`section`,r=e.get(n)??0;return e.set(n,r+1),r===0?n:`${n}-${r+1}`}}function ny(e){let t=e.trim().replace(/[\u0000-\u001F\u007F\s]+/g,``);return t?/^(#|\/|\.\/|\.\.\/)/.test(t)||/^(https?:|mailto:|tel:)/i.test(t)?t:/^[a-z][a-z0-9+.-]*:/i.test(t)?``:t:``}function ry(e){return e.trim().toLowerCase()}function iy(e){return ry(e).replace(/[^a-z0-9_-]+/g,`-`).replace(/^-+|-+$/g,``)}function ay(e,t={}){let n=Ty(cy(e,t));for(let e of t.extensions??[])n=e.transformInline?.(n,{options:t})??n;return n}var oy=32,sy=16;function cy(e,t,n={scans:Math.max(e.length*sy,1024),depth:0}){if(n.depth>=oy)return e?[{type:`text`,value:e}]:[];n.depth++;let r=[],i=0,a=``,o=()=>{a&&=(r.push({type:`text`,value:a}),``)};for(;i<e.length;){let s=e[i],c=e[i+1];if(s===`\\`){if(c===`
29
- `){o(),r.push({type:`break`}),i+=2;continue}if(c&&/[\\`*_[\]{}()#+\-.!|~<>]/.test(c)){a+=c,i+=2;continue}}if(s==="`"){let t=my(e,i,"`"),s=hy(e,i+t,"`",t,n);if(s!==-1){o(),r.push({type:`inlineCode`,value:e.slice(i+t,s).replace(/\s+/g,` `).trim()}),i=s+t;continue}a+=e.slice(i,i+t),i+=t;continue}if(s===`!`&&c===`[`){let a=uy(e,i+1,t,n);if(a){o(),r.push({type:`image`,src:ny(a.href),alt:wy(a.label,n),...a.title?{title:a.title}:{}}),i=a.end;continue}}if(s===`[`){let a=ly(e,i,t,n);if(a){o(),r.push(a.node),i=a.end;continue}let s=uy(e,i,t,n);if(s){let e=ny(s.href);o(),e?r.push({type:`link`,href:e,...s.title?{title:s.title}:{},children:cy(s.label,t,n)}):r.push(...cy(s.label,t,n)),i=s.end;continue}}if(s===`*`&&c===`*`&&e[i+2]===`*`){let a=gy(e,i+3,`***`,n);if(a!==-1){o(),r.push({type:`emphasis`,children:cy(e.slice(i+1,a+2),t,n)}),i=a+3;continue}}if(s===`*`&&c===`*`||s===`_`&&c===`_`){let l=s===`_`&&!by(e,i,2,!0)?-1:gy(e,i+2,s+s,n);if(l!==-1){o(),r.push({type:`strong`,children:cy(e.slice(i+2,l),t,n)}),i=l+2;continue}a+=s+c,i+=2;continue}if(s===`~`&&c===`~`&&e[i+2]===`~`){let t=my(e,i,`~`);a+=e.slice(i,i+t),i+=t;continue}if(s===`~`&&c===`~`){let s=gy(e,i+2,`~~`,n);if(s!==-1){o(),r.push({type:`strike`,children:cy(e.slice(i+2,s),t,n)}),i=s+2;continue}a+=`~~`,i+=2;continue}if(s===`~`){let a=_y(e,i+1,n);if(a!==-1){o(),r.push({type:`strike`,children:cy(e.slice(i+1,a),t,n)}),i=a+1;continue}}if(s===`*`||s===`_`){let a=s===`_`&&!by(e,i,1,!0)?-1:gy(e,i+1,s,n);if(a!==-1){o(),r.push({type:`emphasis`,children:cy(e.slice(i+1,a),t,n)}),i=a+1;continue}}if(s===`<`&&t.allowHtml){let t=vy(e,i+1,`>`,n);if(t!==-1&&dy(e.slice(i,t+1))){o(),r.push({type:`inlineHtml`,value:e.slice(i,t+1)}),i=t+1;continue}}a+=s,i++}return o(),n.depth--,r}function ly(e,t,n,r){if(e[t+1]!==`^`)return;let i=vy(e,t+2,`]`,r);if(i===-1)return;let a=ry(e.slice(t+2,i)),o=n.footnotes?.[a];if(!o||!n.footnoteOrder)return;let s=n.footnoteOrder.indexOf(a);s===-1&&(n.footnoteOrder.push(a),s=n.footnoteOrder.length-1);let c=(n.footnoteCounts?.[a]??0)+1;return n.footnoteCounts&&(n.footnoteCounts[a]=c),{node:{type:`footnoteReference`,id:o.id??(iy(o.label)||`footnote`),number:s+1,...c>1?{referenceIndex:c}:{}},end:i+1}}function uy(e,t,n,r){let i=py(e,t,`[`,`]`,r);if(i===-1)return;let a=e.slice(t+1,i);if(e[i+1]===`(`){let t=py(e,i+1,`(`,`)`,r);if(t===-1)return;let n=fy(e.slice(i+2,t).trim());return n?{label:a,href:n.href,...n.title?{title:n.title}:{},end:t+1}:void 0}if(e[i+1]===`[`){let t=py(e,i+1,`[`,`]`,r);if(t===-1)return;let o=e.slice(i+2,t),s=n.references?.[ry(o||a)];return s?{label:a,href:s.href,...s.title?{title:s.title}:{},end:t+1}:void 0}let o=n.references?.[ry(a)];if(o)return{label:a,href:o.href,...o.title?{title:o.title}:{},end:i+1}}function dy(e){return/^<!--(?:[\s\S]*--|-?)>$/.test(e)||/^<\?[\s\S]*\?>$/.test(e)||/^<![A-Z][\s\S]*>$/.test(e)||/^<!\[CDATA\[[\s\S]*\]\]>$/.test(e)||/^<\/[A-Za-z][\w:-]*\s*>$/.test(e)?!0:/^<[A-Za-z][\w:-]*(?:\s+[A-Za-z_:][\w:.-]*(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+))?)*\s*\/?>$/.test(e)}function fy(e){let t=e.match(/^(\S+)(?:\s+["']([^"']*)["'])?$/);return t?{href:t[1].replace(/^<|>$/g,``),...t[2]?{title:t[2]}:{}}:{href:e}}function py(e,t,n,r,i){let a=0;for(let o=t;o<e.length;o++){if(!yy(i))return-1;if(e[o-1]!==`\\`&&(e[o]===n&&a++,e[o]===r&&(a--,a===0)))return o}return-1}function my(e,t,n,r){let i=0;for(;e[t+i]===n&&!(r&&!yy(r));)i++;return i}function hy(e,t,n,r,i){for(let a=t;a<e.length;a++){if(!yy(i))return-1;if(e[a]===n&&my(e,a,n,i)>=r)return a}return-1}function gy(e,t,n,r){for(let i=t;i<e.length;i++){if(!yy(r))return-1;if(e[i-1]!==`\\`&&e.startsWith(n,i)){if(e[i+1]===n){let t=gy(e,i+2,n+n,r);if(t>i+2){i=t+1;continue}}if((n!==`~~`||e[i-1]!==`~`&&e[i+2]!==`~`)&&!(n[0]===`_`&&!by(e,i,n.length,!1)))return i}}return-1}function _y(e,t,n){if(Cy(e[t]??``)||/\d/.test(e[t]??``))return-1;for(let r=t;r<e.length;r++){if(!yy(n))return-1;if(e[r-1]!==`\\`&&e[r]===`~`&&e[r-1]!==`~`&&e[r+1]!==`~`)return Cy(e[r-1]??``)?-1:r}return-1}function vy(e,t,n,r){for(let i=t;i<e.length;i++){if(!yy(r))return-1;if(e[i]===n)return i}return-1}function yy(e){return e.scans<=0?!1:(e.scans--,!0)}function by(e,t,n,r){let i=e[t-1],a=e[t+n],o=!xy(a)&&(!Sy(a)||xy(i)||Sy(i)),s=!xy(i)&&(!Sy(i)||xy(a)||Sy(a));return r?o&&(!s||Sy(i)):s&&(!o||Sy(a))}function xy(e){return e===void 0||/\s/.test(e)}function Sy(e){return e!==void 0&&/[^\p{L}\p{N}\s]/u.test(e)}function Cy(e){return/\s/.test(e)}function wy(e,t){return cy(e,{},t).map(e=>e.type===`text`||e.type===`inlineCode`?e.value:``).join(``)}function Ty(e){let t=[];for(let n of e){let e=t.at(-1);e?.type===`text`&&n.type===`text`?e.value+=n.value:t.push(n)}return t}var Ey=64;function Dy(e,t={}){let n=Xv(e),r=t.frontmatter!==!1,i=n.split(`
25
+ ${zm(e)}`.trim()},Vm=e=>{let{messageList:t}=e,n=t.flatMap(e=>{if(e.role===`tool`)return[];let t=Rm(e);return t.trim().length===0?[]:[{role:e.role,text:t}]}),r=n.findLastIndex(e=>e.role===`user`),i=n[r];return i?Bm(i,n.slice(0,r)):Error(`Could not find a user message in the sprite chat`)},Hm=new Map,Um=e=>{let{clientId:t,replicacheName:n}=e,r=()=>{},i={clientId:t,state:`starting`,released:new Promise(e=>{r=e})};Hm.set(n,i);let a=!1;return{replicacheName:n,markActive:()=>{!a&&i.state===`starting`&&(i.state=`active`)},markDestroying:()=>{a||(i.state=`destroying`)},release:()=>{a||(a=!0,Hm.get(n)===i&&Hm.delete(n),r())}}},Wm=async e=>{let{clientId:t,replicacheName:n,signal:r}=e;for(;;){if(r?.aborted)throw r.reason instanceof Error?r.reason:Error(`Replicache identity acquisition aborted`);let e=Hm.get(n);if(!e)return Um({clientId:t,replicacheName:n});if(e.state===`destroying`){await e.released;continue}throw new Tt({replicacheName:n})}},Gm=e=>{let{baseUrl:t,personId:n,projectId:r}=e;return[`rough-feature`,t,r,n].join(`:`)},Km=e=>{let{auth:t,baseUrl:n,clientId:r,projectId:i,signal:a,store:o}=e,s=`/api/v1/project/${encodeURIComponent(i)}`,c,l,u,d=!1,f,p=()=>{if(a.aborted)throw At(a)},m=async e=>{let{name:r}=e,{sessionToken:i}=e,a=i.personId;return Hf({name:r,pushURL:se({baseUrl:n,path:`${s}/replicache/push`}),pullURL:se({baseUrl:n,path:`${s}/replicache/pull`}),auth:`Bearer ${i.token}`,pullInterval:6e4,getAuth:async()=>{t.invalidateToken(i.token);let e=await t.getSessionToken();if(e.personId!==a)throw Error(`Session person changed during auth refresh. Destroy this Rough client and create a new one.`);return i=e,`Bearer ${i.token}`},sessionPersonId:a})},h=async()=>{if(typeof window>`u`)return;p();let e=await Promise.race([t.getSessionToken(),jt(a)]);p();let f=Gm({baseUrl:n,projectId:i,personId:e.personId});c=await Wm({clientId:r,replicacheName:f,signal:a}),d&&c.markDestroying(),p();let h=await m({name:f,sessionToken:e});if(h instanceof Error)throw h;if(d||a.aborted)throw await h.close(),new wt(`Replicache finished starting after the Rough client was destroyed`);l=h,c.markActive(),o.bind(h);let g=new URL(se({baseUrl:n,path:`${s}/replicache/poke`}));g.protocol=g.protocol===`https:`?`wss:`:`ws:`;let _=Jf({url:g.toString(),getToken:async()=>(await t.getSessionToken()).token,onPoke:()=>h.pull()});if(d||a.aborted)throw _.close(),await h.close(),l=void 0,new wt(`Replicache finished starting after the Rough client was destroyed`);u=_,await Promise.race([h.pull({now:!0}),jt(a)])},g=()=>l,_=()=>{d=!0,c?.markDestroying()};return{start:h,peek:g,markDestroying:_,destroy:()=>(f??=(async()=>{_();let e=u;u=void 0,e?.close();let t=l;l=void 0,await t?.close()})(),f),releaseIdentity:()=>{c?.release()}}},qm=e.enum([`ACTIVE`,`DELETED`]),Jm=e.enum([`DOCUMENTS_ENABLED`,`TASKS_ENABLED`]),H=e.string();e.object({id:H,publicId:e.string(),name:e.string(),createdAt:e.number(),updatedAt:e.number(),icp:e.string(),strategy:e.string(),vision:e.string(),icon:e.string(),status:qm,deletedAt:e.number().nullable(),version:e.number(),flagList:Jm.array()}),e.object({id:H,publicId:e.string(),name:e.string(),createdAt:e.number(),updatedAt:e.number(),icp:e.string().optional(),strategy:e.string().optional(),vision:e.string().optional(),icon:e.string(),status:qm,deletedAt:e.number().optional().nullable(),version:e.number(),flagList:Jm.array()}),e.object({id:H.optional(),publicId:e.string().optional(),name:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),icp:e.string().optional(),strategy:e.string().optional(),vision:e.string().optional(),icon:e.string().optional(),status:qm.optional(),deletedAt:e.number().optional().nullable(),version:e.number().optional(),flagList:Jm.array().optional()});var Ym=e.string();e.object({id:Ym,name:e.string(),url:e.string(),workspaceId:H,version:e.number(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:Ym,name:e.string(),url:e.string(),workspaceId:H,version:e.number(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:Ym.optional(),name:e.string().optional(),url:e.string().optional(),workspaceId:H.optional(),version:e.number().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var Xm=e.enum([`authorization_code`,`client_credentials`,`refresh_token`]),Zm=e.enum([`read:workspace`,`write:workspace`,`create:sprite`,`read:sprite`]),Qm=e.string();e.object({id:Qm,name:e.string(),secret:e.string().nullable(),redirectUris:e.string().array(),allowedGrants:Xm.array(),scopes:Zm.array(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:Qm,name:e.string(),secret:e.string().optional().nullable(),redirectUris:e.string().array(),allowedGrants:Xm.array(),scopes:Zm.array(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:Qm.optional(),name:e.string().optional(),secret:e.string().optional().nullable(),redirectUris:e.string().array().optional(),allowedGrants:Xm.array().optional(),scopes:Zm.array().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var $m=e.enum([`UNKNOWN`]),U=e.string();e.object({id:U,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),state:e.instanceof(Uint8Array),serialized:e.record(e.string(),e.json()),plaintext:e.string(),version:e.number(),documentMentionList:e.string().array(),hash:e.instanceof(Uint8Array),dirtyAt:e.number().nullable(),flagList:$m.array(),personMentionList:e.string().array()}),e.object({id:U,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),state:e.instanceof(Uint8Array),serialized:e.record(e.string(),e.json()),plaintext:e.string(),version:e.number(),documentMentionList:e.string().array(),hash:e.instanceof(Uint8Array),dirtyAt:e.number().optional().nullable(),flagList:$m.array(),personMentionList:e.string().array()}),e.object({id:U.optional(),workspaceId:H.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),state:e.instanceof(Uint8Array).optional(),serialized:e.record(e.string(),e.json()).optional(),plaintext:e.string().optional(),version:e.number().optional(),documentMentionList:e.string().array().optional(),hash:e.instanceof(Uint8Array).optional(),dirtyAt:e.number().optional().nullable(),flagList:$m.array().optional(),personMentionList:e.string().array().optional()});var eh=e=>{let t=e.toLowerCase().trim().split(`@`),n=t.at(0)?.trim(),r=t.at(1)?.split(`,`).at(0)?.trim();return!n||!r?Error(`Invalid email address`):`${n}@${r}`},W=e.string().min(1).transform((t,n)=>{let r=eh(t);return r instanceof Error?(n.issues.push({code:`custom`,message:r.message,input:t}),e.NEVER):r}).pipe(e.string()),th=e.enum([`WORKSPACE`,`USER`]),nh=e.enum([`PENDING`,`UPLOADING`,`READY`,`ERROR`]),rh=e.enum([`IMAGE`,`VIDEO`,`AUDIO`,`OTHER`]),ih=e.string();e.object({id:ih,scope:th,userId:e.lazy(()=>G),workspaceId:H.nullable(),storageBucket:e.string(),storageKey:e.string(),status:nh,type:rh,mimeType:e.string(),originalFileName:e.string(),byteSize:e.number(),metadata:e.record(e.string(),e.json()),tusUploadToken:e.string().nullable(),createdAt:e.number(),updatedAt:e.number(),deletedAt:e.number().nullable(),version:e.number(),originalAssetId:ih.nullable()}),e.object({id:ih,scope:th,userId:e.lazy(()=>G),workspaceId:H.optional().nullable(),storageBucket:e.string(),storageKey:e.string(),status:nh,type:rh,mimeType:e.string(),originalFileName:e.string(),byteSize:e.number(),metadata:e.record(e.string(),e.json()),tusUploadToken:e.string().optional().nullable(),createdAt:e.number(),updatedAt:e.number(),deletedAt:e.number().optional().nullable(),version:e.number(),originalAssetId:ih.optional().nullable()}),e.object({id:ih.optional(),scope:th.optional(),userId:e.lazy(()=>G.optional()),workspaceId:H.optional().nullable(),storageBucket:e.string().optional(),storageKey:e.string().optional(),status:nh.optional(),type:rh.optional(),mimeType:e.string().optional(),originalFileName:e.string().optional(),byteSize:e.number().optional(),metadata:e.record(e.string(),e.json()).optional(),tusUploadToken:e.string().optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional(),deletedAt:e.number().optional().nullable(),version:e.number().optional(),originalAssetId:ih.optional().nullable()});var G=e.string();e.object({id:G,name:e.string(),email:W,isDemoAccount:e.boolean(),createdAt:e.number(),updatedAt:e.number(),passwordHash:e.string().nullable(),googleUid:e.string().nullable(),totpSecret:e.string().nullable(),totpEnabledAt:e.number().nullable(),recoveryHash:e.string().nullable(),recoveryCodeGeneratedAt:e.number().nullable(),avatarAssetId:ih.nullable()}),e.object({id:G,name:e.string(),email:W,isDemoAccount:e.boolean().optional(),createdAt:e.number(),updatedAt:e.number(),passwordHash:e.string().optional().nullable(),googleUid:e.string().optional().nullable(),totpSecret:e.string().optional().nullable(),totpEnabledAt:e.number().optional().nullable(),recoveryHash:e.string().optional().nullable(),recoveryCodeGeneratedAt:e.number().optional().nullable(),avatarAssetId:ih.optional().nullable()}),e.object({id:G.optional(),name:e.string().optional(),email:W.optional(),isDemoAccount:e.boolean().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),passwordHash:e.string().optional().nullable(),googleUid:e.string().optional().nullable(),totpSecret:e.string().optional().nullable(),totpEnabledAt:e.number().optional().nullable(),recoveryHash:e.string().optional().nullable(),recoveryCodeGeneratedAt:e.number().optional().nullable(),avatarAssetId:ih.optional().nullable()});var ah=e.enum([`DRAFT`,`ACTIVE`]),K=e.string();e.object({id:K,name:e.string(),workspaceId:H,version:e.number(),createdAt:e.number(),updatedAt:e.number(),description:e.string(),avatarAssetId:ih.nullable()}),e.object({id:K,name:e.string(),workspaceId:H,version:e.number(),createdAt:e.number(),updatedAt:e.number(),description:e.string(),avatarAssetId:ih.optional().nullable()}),e.object({id:K.optional(),name:e.string().optional(),workspaceId:H.optional(),version:e.number().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),description:e.string().optional(),avatarAssetId:ih.optional().nullable()});var q=e.string();e.object({id:q,workspaceId:H,contentId:U,createdAt:e.number(),updatedAt:e.number(),userId:G,version:e.number(),lastModifiedAt:e.number(),status:ah,personId:K,referenceId:Ym.nullable(),publicId:e.number(),parentNoteId:q.nullable(),sortOrder:e.number(),transcriptContentId:U.nullable()}),e.object({id:q,workspaceId:H,contentId:U,createdAt:e.number(),updatedAt:e.number(),userId:G,version:e.number(),lastModifiedAt:e.number(),status:ah,personId:K,referenceId:Ym.optional().nullable(),publicId:e.number(),parentNoteId:q.optional().nullable(),sortOrder:e.number(),transcriptContentId:U.optional().nullable()}),e.object({id:q.optional(),workspaceId:H.optional(),contentId:U.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),userId:G.optional(),version:e.number().optional(),lastModifiedAt:e.number().optional(),status:ah.optional(),personId:K.optional(),referenceId:Ym.optional().nullable(),publicId:e.number().optional(),parentNoteId:q.optional().nullable(),sortOrder:e.number().optional(),transcriptContentId:U.optional().nullable()});var oh=e.enum([`NOTE`,`TASK`]),sh=e.string();e.object({id:sh,workspaceId:H,name:e.string(),color:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),description:e.string(),type:oh}),e.object({id:sh,workspaceId:H,name:e.string(),color:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),description:e.string(),type:oh}),e.object({id:sh.optional(),workspaceId:H.optional(),name:e.string().optional(),color:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),description:e.string().optional(),type:oh.optional()}),e.object({noteId:q,labelId:sh,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),version:e.number(),labelType:oh}),e.object({noteId:q,labelId:sh,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),version:e.number(),labelType:oh}),e.object({noteId:q.optional(),labelId:sh.optional(),workspaceId:H.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),labelType:oh.optional()});var ch=e.string();e.object({code:ch,redirectUri:e.string().nullable(),codeChallenge:e.string().nullable(),codeChallengeMethod:e.string().nullable(),expiresAt:e.number(),userId:G,workspaceId:H,oauthClientId:Qm,scopes:Zm.array(),createdAt:e.number(),updatedAt:e.number()}),e.object({code:ch,redirectUri:e.string().optional().nullable(),codeChallenge:e.string().optional().nullable(),codeChallengeMethod:e.string().optional().nullable(),expiresAt:e.number(),userId:G,workspaceId:H,oauthClientId:Qm,scopes:Zm.array(),createdAt:e.number(),updatedAt:e.number()}),e.object({code:ch.optional(),redirectUri:e.string().optional().nullable(),codeChallenge:e.string().optional().nullable(),codeChallengeMethod:e.string().optional().nullable(),expiresAt:e.number().optional(),userId:G.optional(),workspaceId:H.optional(),oauthClientId:Qm.optional(),scopes:Zm.array().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var lh=e.string();e.object({accessToken:lh,accessTokenExpiresAt:e.number(),refreshToken:e.string().nullable(),refreshTokenExpiresAt:e.number().nullable(),userId:G,workspaceId:H,oauthClientId:Qm,scopes:Zm.array(),originatingAuthCodeId:ch.nullable(),createdAt:e.number(),updatedAt:e.number()}),e.object({accessToken:lh,accessTokenExpiresAt:e.number(),refreshToken:e.string().optional().nullable(),refreshTokenExpiresAt:e.number().optional().nullable(),userId:G,workspaceId:H,oauthClientId:Qm,scopes:Zm.array(),originatingAuthCodeId:ch.optional().nullable(),createdAt:e.number(),updatedAt:e.number()}),e.object({accessToken:lh.optional(),accessTokenExpiresAt:e.number().optional(),refreshToken:e.string().optional().nullable(),refreshTokenExpiresAt:e.number().optional().nullable(),userId:G.optional(),workspaceId:H.optional(),oauthClientId:Qm.optional(),scopes:Zm.array().optional(),originatingAuthCodeId:ch.optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var uh=e.string();e.object({id:uh,name:e.string(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:uh,name:e.string(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:uh.optional(),name:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var dh=e.enum([`TEXT`,`IMAGE`]),fh=e.string();e.object({id:fh,llmProviderId:uh,providerModelId:e.string(),name:e.string(),releasedOn:e.iso.date(),isSelectable:e.boolean(),createdAt:e.number(),updatedAt:e.number(),inputModalityList:dh.array(),outputModalityList:dh.array()}),e.object({id:fh,llmProviderId:uh,providerModelId:e.string(),name:e.string(),releasedOn:e.iso.date(),isSelectable:e.boolean(),createdAt:e.number(),updatedAt:e.number(),inputModalityList:dh.array(),outputModalityList:dh.array()}),e.object({id:fh.optional(),llmProviderId:uh.optional(),providerModelId:e.string().optional(),name:e.string().optional(),releasedOn:e.iso.date().optional(),isSelectable:e.boolean().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),inputModalityList:dh.array().optional(),outputModalityList:dh.array().optional()});var J=e.string();e.object({id:J,workspaceId:H,name:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),firstUsedViaApiAt:e.number().nullable(),publicId:e.string(),spriteLlmModelId:fh.nullable()}),e.object({id:J,workspaceId:H,name:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),firstUsedViaApiAt:e.number().optional().nullable(),publicId:e.string(),spriteLlmModelId:fh.optional().nullable()}),e.object({id:J.optional(),workspaceId:H.optional(),name:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),firstUsedViaApiAt:e.number().optional().nullable(),publicId:e.string().optional(),spriteLlmModelId:fh.optional().nullable()});var ph=e.string();e.object({id:ph,createdAt:e.number(),updatedAt:e.number(),version:e.number(),workspaceId:H,projectId:J,personId:K,key:e.string(),name:e.string(),email:W.nullable().nullable(),lastSeenAt:e.number().nullable()}),e.object({id:ph,createdAt:e.number(),updatedAt:e.number(),version:e.number(),workspaceId:H,projectId:J,personId:K,key:e.string(),name:e.string(),email:W.nullable().optional().nullable(),lastSeenAt:e.number().optional().nullable()}),e.object({id:ph.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),workspaceId:H.optional(),projectId:J.optional(),personId:K.optional(),key:e.string().optional(),name:e.string().optional(),email:W.nullable().optional().nullable(),lastSeenAt:e.number().optional().nullable()});var mh=e.string();e.object({id:mh,createdAt:e.number(),updatedAt:e.number(),version:e.number(),workspaceId:H,projectId:J,key:e.string(),name:e.string(),lastSeenAt:e.number().nullable()}),e.object({id:mh,createdAt:e.number(),updatedAt:e.number(),version:e.number(),workspaceId:H,projectId:J,key:e.string(),name:e.string(),lastSeenAt:e.number().optional().nullable()}),e.object({id:mh.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),workspaceId:H.optional(),projectId:J.optional(),key:e.string().optional(),name:e.string().optional(),lastSeenAt:e.number().optional().nullable()});var hh=e.string();e.object({id:hh,publicId:e.string(),workspaceId:H,name:e.string(),publicKey:e.string(),createdByUserId:G,createdAt:e.number(),updatedAt:e.number(),version:e.number(),revokedAt:e.number().nullable(),revokedByUserId:G.nullable(),lastUsedAt:e.number().nullable()}),e.object({id:hh,publicId:e.string(),workspaceId:H,name:e.string(),publicKey:e.string(),createdByUserId:G,createdAt:e.number(),updatedAt:e.number(),version:e.number(),revokedAt:e.number().optional().nullable(),revokedByUserId:G.optional().nullable(),lastUsedAt:e.number().optional().nullable()}),e.object({id:hh.optional(),publicId:e.string().optional(),workspaceId:H.optional(),name:e.string().optional(),publicKey:e.string().optional(),createdByUserId:G.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),revokedAt:e.number().optional().nullable(),revokedByUserId:G.optional().nullable(),lastUsedAt:e.number().optional().nullable()});var gh=e.string();e.object({id:gh,workspaceId:H,projectId:J,projectUserId:ph,projectAccountId:mh,signingKeyId:hh,hash:e.instanceof(Uint8Array),createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number()}),e.object({id:gh,workspaceId:H,projectId:J,projectUserId:ph,projectAccountId:mh,signingKeyId:hh,hash:e.instanceof(Uint8Array),createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number()}),e.object({id:gh.optional(),workspaceId:H.optional(),projectId:J.optional(),projectUserId:ph.optional(),projectAccountId:mh.optional(),signingKeyId:hh.optional(),hash:e.instanceof(Uint8Array).optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),expiresAt:e.number().optional()});var _h=e.enum([`PENDING`,`INSTALLED`]),vh=e.string();e.object({id:vh,fizzyIntegrationId:e.lazy(()=>yh),fizzyAccountId:e.lazy(()=>bh),workspaceId:H,publicId:e.string(),name:e.string(),url:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:vh,fizzyIntegrationId:e.lazy(()=>yh),fizzyAccountId:e.lazy(()=>bh),workspaceId:H,publicId:e.string(),name:e.string(),url:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:vh.optional(),fizzyIntegrationId:e.lazy(()=>yh.optional()),fizzyAccountId:e.lazy(()=>bh.optional()),workspaceId:H.optional(),publicId:e.string().optional(),name:e.string().optional(),url:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()});var yh=e.string();e.object({id:yh,workspaceId:H,email:e.string(),state:_h,pendingAuthenticationToken:e.string().nullable(),sessionToken:e.string().nullable(),defaultFizzyBoardId:vh.nullable(),syncAccountListStartedAt:e.number().nullable(),syncAccountListFinishedAt:e.number().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),lastRequestedMagicLinkAt:e.number().nullable()}),e.object({id:yh,workspaceId:H,email:e.string(),state:_h,pendingAuthenticationToken:e.string().optional().nullable(),sessionToken:e.string().optional().nullable(),defaultFizzyBoardId:vh.optional().nullable(),syncAccountListStartedAt:e.number().optional().nullable(),syncAccountListFinishedAt:e.number().optional().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),lastRequestedMagicLinkAt:e.number().optional().nullable()}),e.object({id:yh.optional(),workspaceId:H.optional(),email:e.string().optional(),state:_h.optional(),pendingAuthenticationToken:e.string().optional().nullable(),sessionToken:e.string().optional().nullable(),defaultFizzyBoardId:vh.optional().nullable(),syncAccountListStartedAt:e.number().optional().nullable(),syncAccountListFinishedAt:e.number().optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),lastRequestedMagicLinkAt:e.number().optional().nullable()});var bh=e.string();e.object({id:bh,fizzyIntegrationId:yh,workspaceId:H,slug:e.string(),name:e.string(),syncBoardListStartedAt:e.number().nullable(),syncBoardListFinishedAt:e.number().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:bh,fizzyIntegrationId:yh,workspaceId:H,slug:e.string(),name:e.string(),syncBoardListStartedAt:e.number().optional().nullable(),syncBoardListFinishedAt:e.number().optional().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:bh.optional(),fizzyIntegrationId:yh.optional(),workspaceId:H.optional(),slug:e.string().optional(),name:e.string().optional(),syncBoardListStartedAt:e.number().optional().nullable(),syncBoardListFinishedAt:e.number().optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()});var xh=e.string();e.object({id:xh,userId:G.nullable(),workspaceId:H,pullCount:e.number(),projectUserId:ph.nullable(),projectAccountId:mh.nullable()}),e.object({id:xh,userId:G.optional().nullable(),workspaceId:H,pullCount:e.number(),projectUserId:ph.optional().nullable(),projectAccountId:mh.optional().nullable()}),e.object({id:xh.optional(),userId:G.optional().nullable(),workspaceId:H.optional(),pullCount:e.number().optional(),projectUserId:ph.optional().nullable(),projectAccountId:mh.optional().nullable()});var Sh=e.enum([`GITHUB`]),Ch=e.enum([`PENDING`,`INSTALLED`,`DELETED`]),Y=e.string();e.object({id:Y,createdAt:e.number(),updatedAt:e.number(),workspaceId:H,type:Sh,state:Ch,token:e.string().nullable(),ghInstallationId:e.number().nullable(),ghSettingsUrl:e.string().nullable(),version:e.number(),ghInstallationUrl:e.string().nullable(),name:e.string().nullable(),avatarUrl:e.string().nullable(),syncRepoListStartedAt:e.number().nullable(),syncRepoListFinishedAt:e.number().nullable()}),e.object({id:Y,createdAt:e.number(),updatedAt:e.number(),workspaceId:H,type:Sh,state:Ch,token:e.string().optional().nullable(),ghInstallationId:e.number().optional().nullable(),ghSettingsUrl:e.string().optional().nullable(),version:e.number(),ghInstallationUrl:e.string().optional().nullable(),name:e.string().optional().nullable(),avatarUrl:e.string().optional().nullable(),syncRepoListStartedAt:e.number().optional().nullable(),syncRepoListFinishedAt:e.number().optional().nullable()}),e.object({id:Y.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),workspaceId:H.optional(),type:Sh.optional(),state:Ch.optional(),token:e.string().optional().nullable(),ghInstallationId:e.number().optional().nullable(),ghSettingsUrl:e.string().optional().nullable(),version:e.number().optional(),ghInstallationUrl:e.string().optional().nullable(),name:e.string().optional().nullable(),avatarUrl:e.string().optional().nullable(),syncRepoListStartedAt:e.number().optional().nullable(),syncRepoListFinishedAt:e.number().optional().nullable()});var wh=e.string();e.object({id:wh,createdAt:e.number(),updatedAt:e.number(),vcsIntegrationId:Y,owner:e.string(),name:e.string(),branch:e.string(),excludeAuthorEmail:e.string().array().nullable(),version:e.number(),activatedAt:e.number().nullable(),unavailableAt:e.number().nullable(),defaultBranch:e.string(),workspaceId:H,description:e.string(),url:e.string(),syncCommitListStartedAt:e.number().nullable(),syncCommitListFinishedAt:e.number().nullable(),originId:e.string().nullable(),originUpdatedAt:e.number().nullable(),syncBranchListStartedAt:e.number().nullable(),syncBranchListFinishedAt:e.number().nullable()}),e.object({id:wh,createdAt:e.number(),updatedAt:e.number(),vcsIntegrationId:Y,owner:e.string(),name:e.string(),branch:e.string(),excludeAuthorEmail:e.string().array().optional().nullable(),version:e.number(),activatedAt:e.number().optional().nullable(),unavailableAt:e.number().optional().nullable(),defaultBranch:e.string(),workspaceId:H,description:e.string(),url:e.string(),syncCommitListStartedAt:e.number().optional().nullable(),syncCommitListFinishedAt:e.number().optional().nullable(),originId:e.string().optional().nullable(),originUpdatedAt:e.number().optional().nullable(),syncBranchListStartedAt:e.number().optional().nullable(),syncBranchListFinishedAt:e.number().optional().nullable()}),e.object({id:wh.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),vcsIntegrationId:Y.optional(),owner:e.string().optional(),name:e.string().optional(),branch:e.string().optional(),excludeAuthorEmail:e.string().array().optional().nullable(),version:e.number().optional(),activatedAt:e.number().optional().nullable(),unavailableAt:e.number().optional().nullable(),defaultBranch:e.string().optional(),workspaceId:H.optional(),description:e.string().optional(),url:e.string().optional(),syncCommitListStartedAt:e.number().optional().nullable(),syncCommitListFinishedAt:e.number().optional().nullable(),originId:e.string().optional().nullable(),originUpdatedAt:e.number().optional().nullable(),syncBranchListStartedAt:e.number().optional().nullable(),syncBranchListFinishedAt:e.number().optional().nullable()});var Th=e.string();e.object({id:Th,createdAt:e.number(),updatedAt:e.number(),version:e.number(),vcsRepoId:wh,vcsIntegrationId:Y,workspaceId:H,name:e.string(),commitSha:e.string()}),e.object({id:Th,createdAt:e.number(),updatedAt:e.number(),version:e.number(),vcsRepoId:wh,vcsIntegrationId:Y,workspaceId:H,name:e.string(),commitSha:e.string()}),e.object({id:Th.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),vcsRepoId:wh.optional(),vcsIntegrationId:Y.optional(),workspaceId:H.optional(),name:e.string().optional(),commitSha:e.string().optional()});var Eh=e.enum([`SUGGESTED`,`APPROVED`,`REJECTED`]);e.object({noteIdA:q,noteIdB:q,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),distance:e.number().nullable(),version:e.number(),status:Eh,createdByUserId:G.nullable(),lastModifiedByUserId:G.nullable(),lastModifiedAt:e.number().nullable()}),e.object({noteIdA:q,noteIdB:q,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),distance:e.number().optional().nullable(),version:e.number(),status:Eh,createdByUserId:G.optional().nullable(),lastModifiedByUserId:G.optional().nullable(),lastModifiedAt:e.number().optional().nullable()}),e.object({noteIdA:q.optional(),noteIdB:q.optional(),workspaceId:H.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),distance:e.number().optional().nullable(),version:e.number().optional(),status:Eh.optional(),createdByUserId:G.optional().nullable(),lastModifiedByUserId:G.optional().nullable(),lastModifiedAt:e.number().optional().nullable()});var Dh=e.string();e.object({id:Dh,workspaceId:H,projectId:J,key:e.string(),name:e.string(),toolList:e.array(e.json()),createdAt:e.number(),updatedAt:e.number(),description:e.string(),version:e.number()}),e.object({id:Dh,workspaceId:H,projectId:J,key:e.string(),name:e.string(),toolList:e.array(e.json()),createdAt:e.number(),updatedAt:e.number(),description:e.string(),version:e.number()}),e.object({id:Dh.optional(),workspaceId:H.optional(),projectId:J.optional(),key:e.string().optional(),name:e.string().optional(),toolList:e.array(e.json()).optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),description:e.string().optional(),version:e.number().optional()});var X=e.string();e.object({id:X,workspaceId:H,version:e.number(),createdAt:e.number(),updatedAt:e.number(),name:e.string(),projectId:J,surfaceId:Dh,ownedByPersonId:K}),e.object({id:X,workspaceId:H,version:e.number(),createdAt:e.number(),updatedAt:e.number(),name:e.string(),projectId:J,surfaceId:Dh,ownedByPersonId:K}),e.object({id:X.optional(),workspaceId:H.optional(),version:e.number().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),name:e.string().optional(),projectId:J.optional(),surfaceId:Dh.optional(),ownedByPersonId:K.optional()});var Oh=e.enum([`PENDING`,`IN_PROGRESS`,`READY`,`ERROR`,`CANCELED`]),kh=e.string();e.object({id:kh,workspaceId:H,version:e.number(),createdAt:e.number(),updatedAt:e.number(),spriteId:X,parentSpriteBuildId:kh.nullable(),prompt:e.string(),artifactUrl:e.string().nullable(),sourceUrl:e.string().nullable(),status:Oh,startedAt:e.number().nullable(),stoppedAt:e.number().nullable(),error:e.record(e.string(),e.json()).nullable(),toolList:e.array(e.json()),reasoningSummary:e.string().nullable(),publishedAt:e.number().nullable(),createdByPersonId:K,agentProvider:e.string(),agentModel:e.string(),agentInputTokens:e.number(),agentOutputTokens:e.number(),agentCacheReadTokens:e.number(),agentCacheWriteTokens:e.number(),agentEstimatedCostUsd:e.number(),cancelRequestedAt:e.number().nullable()}),e.object({id:kh,workspaceId:H,version:e.number(),createdAt:e.number(),updatedAt:e.number(),spriteId:X,parentSpriteBuildId:kh.optional().nullable(),prompt:e.string(),artifactUrl:e.string().optional().nullable(),sourceUrl:e.string().optional().nullable(),status:Oh,startedAt:e.number().optional().nullable(),stoppedAt:e.number().optional().nullable(),error:e.record(e.string(),e.json()).optional().nullable(),toolList:e.array(e.json()),reasoningSummary:e.string().optional().nullable(),publishedAt:e.number().optional().nullable(),createdByPersonId:K,agentProvider:e.string(),agentModel:e.string(),agentInputTokens:e.number(),agentOutputTokens:e.number(),agentCacheReadTokens:e.number(),agentCacheWriteTokens:e.number(),agentEstimatedCostUsd:e.number(),cancelRequestedAt:e.number().optional().nullable()}),e.object({id:kh.optional(),workspaceId:H.optional(),version:e.number().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),spriteId:X.optional(),parentSpriteBuildId:kh.optional().nullable(),prompt:e.string().optional(),artifactUrl:e.string().optional().nullable(),sourceUrl:e.string().optional().nullable(),status:Oh.optional(),startedAt:e.number().optional().nullable(),stoppedAt:e.number().optional().nullable(),error:e.record(e.string(),e.json()).optional().nullable(),toolList:e.array(e.json()).optional(),reasoningSummary:e.string().optional().nullable(),publishedAt:e.number().optional().nullable(),createdByPersonId:K.optional(),agentProvider:e.string().optional(),agentModel:e.string().optional(),agentInputTokens:e.number().optional(),agentOutputTokens:e.number().optional(),agentCacheReadTokens:e.number().optional(),agentCacheWriteTokens:e.number().optional(),agentEstimatedCostUsd:e.number().optional(),cancelRequestedAt:e.number().optional().nullable()});var Ah=e.string();e.object({id:Ah,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),snapshot:e.record(e.string(),e.json()).nullable()}),e.object({id:Ah,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),snapshot:e.record(e.string(),e.json()).optional().nullable()}),e.object({id:Ah.optional(),workspaceId:H.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),snapshot:e.record(e.string(),e.json()).optional().nullable()});var jh=e.enum(`DOCUMENT_COMMENT_CREATE.DOCUMENT_COMMENT_DELETE.DOCUMENT_COMMENT_RESOLVE.DOCUMENT_COMMENT_UPDATE.DOCUMENT_CREATE.DOCUMENT_DELETE.DOCUMENT_PERSON_MENTION.DOCUMENT_UPDATE_BLOCK_CONTENT.DOCUMENT_UPDATE_STATUS.DOCUMENT_UPDATE_TITLE.NOTE_COMMENT_CREATE.NOTE_COMMENT_DELETE.NOTE_COMMENT_RESOLVE.NOTE_COMMENT_UPDATE.NOTE_CREATE.NOTE_PERSON_MENTION.NOTE_UPDATE_CONTENT.NOTE_UPDATE_LABEL.NOTE_UPDATE_PERSON.NOTE_UPDATE_REFERENCE.NOTE_UPDATE_STATUS.NOTE_UPDATE_TITLE.SEQUENCE_DOCUMENT_DELETE.SEQUENCE_DOCUMENT_INSERT.SEQUENCE_DOCUMENT_STATUS_IN.SEQUENCE_DOCUMENT_STATUS_OUT.SEQUENCE_DOCUMENT_UPDATE_ORDER.SEQUENCE_COMMENT_CREATE.SEQUENCE_COMMENT_DELETE.SEQUENCE_COMMENT_RESOLVE.SEQUENCE_COMMENT_UPDATE.SEQUENCE_PERSON_MENTION.SPRITE_CREATE.SPRITE_COMMENT_CREATE`.split(`.`)),Mh=e.enum([`CANCELED`,`IDEA`,`DEVELOPMENT`,`RELEASED`,`DRAFT`,`ARCHIVED`]),Z=e.string();e.object({id:Z,title:e.string(),status:Mh,createdAt:e.number(),updatedAt:e.number(),publicId:e.number(),createdByUserId:G,workspaceId:H,vcsTagList:e.string().array(),archivedAt:e.number().nullable(),archivedByUserId:G.nullable(),version:e.number(),lastModifiedAt:e.number(),releasedAt:e.number().nullable(),ownedByPersonId:K}),e.object({id:Z,title:e.string(),status:Mh,createdAt:e.number(),updatedAt:e.number(),publicId:e.number(),createdByUserId:G,workspaceId:H,vcsTagList:e.string().array(),archivedAt:e.number().optional().nullable(),archivedByUserId:G.optional().nullable(),version:e.number(),lastModifiedAt:e.number(),releasedAt:e.number().optional().nullable(),ownedByPersonId:K}),e.object({id:Z.optional(),title:e.string().optional(),status:Mh.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),publicId:e.number().optional(),createdByUserId:G.optional(),workspaceId:H.optional(),vcsTagList:e.string().array().optional(),archivedAt:e.number().optional().nullable(),archivedByUserId:G.optional().nullable(),version:e.number().optional(),lastModifiedAt:e.number().optional(),releasedAt:e.number().optional().nullable(),ownedByPersonId:K.optional()});var Nh=e.enum([`USER`,`STATUS`,`WISH`]),Ph=e.enum([`NONE`,`STATUS`]),Q=e.string();e.object({id:Q,createdAt:e.number(),updatedAt:e.number(),name:e.string(),workspaceId:H,publicId:e.string(),type:Nh,status:Mh.nullable().nullable(),version:e.number(),icon:e.string(),pinned:e.number().nullable(),groupBy:Ph,ownedByPersonId:K.nullable()}),e.object({id:Q,createdAt:e.number(),updatedAt:e.number(),name:e.string(),workspaceId:H,publicId:e.string(),type:Nh,status:Mh.nullable().optional().nullable(),version:e.number(),icon:e.string(),pinned:e.number().optional().nullable(),groupBy:Ph,ownedByPersonId:K.optional().nullable()}),e.object({id:Q.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),name:e.string().optional(),workspaceId:H.optional(),publicId:e.string().optional(),type:Nh.optional(),status:Mh.nullable().optional().nullable(),version:e.number().optional(),icon:e.string().optional(),pinned:e.number().optional().nullable(),groupBy:Ph.optional(),ownedByPersonId:K.optional().nullable()});var Fh=e.string();e.object({id:Fh,workspaceId:H,type:jh,detail:e.record(e.string(),e.json()),actionedAt:e.number(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),documentId:Z.nullable(),noteId:q.nullable(),sequenceId:Q.nullable(),spriteId:X.nullable(),actionedByPersonId:K}),e.object({id:Fh,workspaceId:H,type:jh,detail:e.record(e.string(),e.json()),actionedAt:e.number(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),documentId:Z.optional().nullable(),noteId:q.optional().nullable(),sequenceId:Q.optional().nullable(),spriteId:X.optional().nullable(),actionedByPersonId:K}),e.object({id:Fh.optional(),workspaceId:H.optional(),type:jh.optional(),detail:e.record(e.string(),e.json()).optional(),actionedAt:e.number().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),documentId:Z.optional().nullable(),noteId:q.optional().nullable(),sequenceId:Q.optional().nullable(),spriteId:X.optional().nullable(),actionedByPersonId:K.optional()});var Ih=e.enum([`DOCUMENT`,`NOTE`,`SEQUENCE`,`SPRITE`]),Lh=e.enum([`TEXT`,`DRAWING`]),Rh=e.enum([`UNKNOWN`]),zh=e.string();e.object({id:zh,sortOrder:e.number(),documentId:Z,createdAt:e.number(),updatedAt:e.number(),type:Lh,lockedAt:e.number().nullable(),version:e.number(),lastModifiedAt:e.number(),workspaceId:H,archivedAt:e.number().nullable(),archivedByUserId:G.nullable(),flagList:Rh.array(),title:e.string(),contentId:U.nullable(),canvasId:Ah.nullable(),lastModifiedByUserId:G}),e.object({id:zh,sortOrder:e.number(),documentId:Z,createdAt:e.number(),updatedAt:e.number(),type:Lh,lockedAt:e.number().optional().nullable(),version:e.number(),lastModifiedAt:e.number(),workspaceId:H,archivedAt:e.number().optional().nullable(),archivedByUserId:G.optional().nullable(),flagList:Rh.array(),title:e.string(),contentId:U.optional().nullable(),canvasId:Ah.optional().nullable(),lastModifiedByUserId:G}),e.object({id:zh.optional(),sortOrder:e.number().optional(),documentId:Z.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),type:Lh.optional(),lockedAt:e.number().optional().nullable(),version:e.number().optional(),lastModifiedAt:e.number().optional(),workspaceId:H.optional(),archivedAt:e.number().optional().nullable(),archivedByUserId:G.optional().nullable(),flagList:Rh.array().optional(),title:e.string().optional(),contentId:U.optional().nullable(),canvasId:Ah.optional().nullable(),lastModifiedByUserId:G.optional()});var Bh=e.string();e.object({id:Bh,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),version:e.number(),title:e.string(),contentId:U,completedAt:e.number().nullable(),createdByPersonId:K}),e.object({id:Bh,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),version:e.number(),title:e.string(),contentId:U,completedAt:e.number().optional().nullable(),createdByPersonId:K}),e.object({id:Bh.optional(),workspaceId:H.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),title:e.string().optional(),contentId:U.optional(),completedAt:e.number().optional().nullable(),createdByPersonId:K.optional()});var Vh=e.string();e.object({id:Vh,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),version:e.number(),openedAt:e.number(),openedByUserId:G,resolvedAt:e.number().nullable(),resolvedByUserId:G.nullable(),documentId:Z.nullable(),blockId:zh.nullable(),sequenceId:Q.nullable(),eventId:Fh.nullable(),noteId:q.nullable(),spriteId:X.nullable(),taskId:Bh.nullable()}),e.object({id:Vh,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),version:e.number(),openedAt:e.number(),openedByUserId:G,resolvedAt:e.number().optional().nullable(),resolvedByUserId:G.optional().nullable(),documentId:Z.optional().nullable(),blockId:zh.optional().nullable(),sequenceId:Q.optional().nullable(),eventId:Fh.optional().nullable(),noteId:q.optional().nullable(),spriteId:X.optional().nullable(),taskId:Bh.optional().nullable()}),e.object({id:Vh.optional(),workspaceId:H.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),openedAt:e.number().optional(),openedByUserId:G.optional(),resolvedAt:e.number().optional().nullable(),resolvedByUserId:G.optional().nullable(),documentId:Z.optional().nullable(),blockId:zh.optional().nullable(),sequenceId:Q.optional().nullable(),eventId:Fh.optional().nullable(),noteId:q.optional().nullable(),spriteId:X.optional().nullable(),taskId:Bh.optional().nullable()});var Hh=e.string();e.object({id:Hh,createdAt:e.number(),updatedAt:e.number(),postedAt:e.number(),userId:G,workspaceId:H,version:e.number(),contentId:U,commentThreadId:Vh}),e.object({id:Hh,createdAt:e.number(),updatedAt:e.number(),postedAt:e.number(),userId:G,workspaceId:H,version:e.number(),contentId:U,commentThreadId:Vh}),e.object({id:Hh.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),postedAt:e.number().optional(),userId:G.optional(),workspaceId:H.optional(),version:e.number().optional(),contentId:U.optional(),commentThreadId:Vh.optional()});var Uh=e.string();e.object({id:Uh,workspaceId:H,userId:G,eventId:Fh,readAt:e.number().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),type:Ih,documentId:Z.nullable(),noteId:q.nullable(),sequenceId:Q.nullable(),commentId:Hh.nullable(),spriteId:X.nullable(),commentThreadId:Vh.nullable()}),e.object({id:Uh,workspaceId:H,userId:G,eventId:Fh,readAt:e.number().optional().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),type:Ih,documentId:Z.optional().nullable(),noteId:q.optional().nullable(),sequenceId:Q.optional().nullable(),commentId:Hh.optional().nullable(),spriteId:X.optional().nullable(),commentThreadId:Vh.optional().nullable()}),e.object({id:Uh.optional(),workspaceId:H.optional(),userId:G.optional(),eventId:Fh.optional(),readAt:e.number().optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),type:Ih.optional(),documentId:Z.optional().nullable(),noteId:q.optional().nullable(),sequenceId:Q.optional().nullable(),commentId:Hh.optional().nullable(),spriteId:X.optional().nullable(),commentThreadId:Vh.optional().nullable()});var Wh=e.string();e.object({id:Wh,userId:G,contentId:U,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),version:e.number(),state:e.instanceof(Uint8Array)}),e.object({id:Wh,userId:G,contentId:U,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),version:e.number(),state:e.instanceof(Uint8Array)}),e.object({id:Wh.optional(),userId:G.optional(),contentId:U.optional(),workspaceId:H.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),state:e.instanceof(Uint8Array).optional()});var Gh=e.string();e.object({id:Gh,createdAt:e.number(),record:e.record(e.string(),e.json())}),e.object({id:Gh,createdAt:e.number(),record:e.record(e.string(),e.json())}),e.object({id:Gh.optional(),createdAt:e.number().optional(),record:e.record(e.string(),e.json()).optional()}),e.object({spriteId:X,projectAccountId:mh,workspaceId:H,projectId:J,createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({spriteId:X,projectAccountId:mh,workspaceId:H,projectId:J,createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({spriteId:X.optional(),projectAccountId:mh.optional(),workspaceId:H.optional(),projectId:J.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()}),e.object({projectAccountId:mh,projectUserId:ph,createdAt:e.number(),updatedAt:e.number(),version:e.number(),workspaceId:H,projectId:J}),e.object({projectAccountId:mh,projectUserId:ph,createdAt:e.number(),updatedAt:e.number(),version:e.number(),workspaceId:H,projectId:J}),e.object({projectAccountId:mh.optional(),projectUserId:ph.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),workspaceId:H.optional(),projectId:J.optional()});var Kh=e.string();e.object({id:Kh,workspaceId:H,userId:G,emoji:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),commentId:Hh.nullable(),noteId:q.nullable()}),e.object({id:Kh,workspaceId:H,userId:G,emoji:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),commentId:Hh.optional().nullable(),noteId:q.optional().nullable()}),e.object({id:Kh.optional(),workspaceId:H.optional(),userId:G.optional(),emoji:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),commentId:Hh.optional().nullable(),noteId:q.optional().nullable()}),e.object({taskId:Bh,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),version:e.number(),sortOrder:e.number()}),e.object({taskId:Bh,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),version:e.number(),sortOrder:e.number()}),e.object({taskId:Bh.optional(),workspaceId:H.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),sortOrder:e.number().optional()});var qh=e.string();e.object({id:qh,workspaceId:H,token:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:qh,workspaceId:H,token:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:qh.optional(),workspaceId:H.optional(),token:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()});var Jh=e.string();e.object({id:Jh,workspaceId:H,userId:G,hash:e.instanceof(Uint8Array),createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number()}),e.object({id:Jh,workspaceId:H,userId:G,hash:e.instanceof(Uint8Array),createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number()}),e.object({id:Jh.optional(),workspaceId:H.optional(),userId:G.optional(),hash:e.instanceof(Uint8Array).optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),expiresAt:e.number().optional()});var Yh=e.enum([`STEP_STARTED`,`STEP_COMPLETED`,`STEP_FAILED`,`EXEC_STARTED`,`EXEC_COMPLETED`,`EXEC_FAILED`,`FETCH_STARTED`,`FETCH_COMPLETED`,`FETCH_FAILED`,`AGENT_STARTED`,`AGENT_COMPLETED`,`AGENT_TOOL_STARTED`,`AGENT_TOOL_COMPLETED`,`AGENT_TOOL_FAILED`,`AGENT_META`,`AGENT_MESSAGE`,`AGENT_THOUGHT`,`AGENT_USAGE`]),Xh=e.string();e.object({id:Xh,workspaceId:H,spriteBuildId:kh,createdAt:e.number(),updatedAt:e.number(),version:e.number(),type:Yh,detail:e.record(e.string(),e.json()),actionedAt:e.number()}),e.object({id:Xh,workspaceId:H,spriteBuildId:kh,createdAt:e.number(),updatedAt:e.number(),version:e.number(),type:Yh,detail:e.record(e.string(),e.json()),actionedAt:e.number()}),e.object({id:Xh.optional(),workspaceId:H.optional(),spriteBuildId:kh.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),type:Yh.optional(),detail:e.record(e.string(),e.json()).optional(),actionedAt:e.number().optional()}),e.object({blockId:zh,userId:G,workspaceId:H,lastReadAt:e.number(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({blockId:zh,userId:G,workspaceId:H,lastReadAt:e.number(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({blockId:zh.optional(),userId:G.optional(),workspaceId:H.optional(),lastReadAt:e.number().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()});var Zh=e.enum([`NOTE`,`DOCUMENT`]),Qh=e.string();e.object({id:Qh,workspaceId:H,userId:G,type:Zh,matchAll:e.boolean(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:Qh,workspaceId:H,userId:G,type:Zh,matchAll:e.boolean(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:Qh.optional(),workspaceId:H.optional(),userId:G.optional(),type:Zh.optional(),matchAll:e.boolean().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()});var $h=e.enum([`ADMIN`,`GUEST`,`ARCHIVED`,`DEMO`]);e.object({workspaceId:H,userId:G,createdAt:e.number(),updatedAt:e.number(),role:$h,version:e.number(),personId:K,lastReadNotificationsAt:e.number().nullable()}),e.object({workspaceId:H,userId:G,createdAt:e.number(),updatedAt:e.number(),role:$h,version:e.number(),personId:K,lastReadNotificationsAt:e.number().optional().nullable()}),e.object({workspaceId:H.optional(),userId:G.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),role:$h.optional(),version:e.number().optional(),personId:K.optional(),lastReadNotificationsAt:e.number().optional().nullable()});var eg=e.string();e.object({id:eg,workspaceId:H,name:e.string(),url:e.string(),secret:e.string(),eventTypeList:jh.array(),createdByPersonId:K,createdAt:e.number(),updatedAt:e.number()}),e.object({id:eg,workspaceId:H,name:e.string(),url:e.string(),secret:e.string(),eventTypeList:jh.array(),createdByPersonId:K,createdAt:e.number(),updatedAt:e.number()}),e.object({id:eg.optional(),workspaceId:H.optional(),name:e.string().optional(),url:e.string().optional(),secret:e.string().optional(),eventTypeList:jh.array().optional(),createdByPersonId:K.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var tg=e.enum([`FEATURE`,`FIX`,`RELEASE`,`CHORE`]),ng=e.string();e.object({id:ng,createdAt:e.number(),updatedAt:e.number(),version:e.number(),vcsIntegrationId:Y,workspaceId:H,name:e.string(),email:e.string(),avatarUrl:e.string().nullable()}),e.object({id:ng,createdAt:e.number(),updatedAt:e.number(),version:e.number(),vcsIntegrationId:Y,workspaceId:H,name:e.string(),email:e.string(),avatarUrl:e.string().optional().nullable()}),e.object({id:ng.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),vcsIntegrationId:Y.optional(),workspaceId:H.optional(),name:e.string().optional(),email:e.string().optional(),avatarUrl:e.string().optional().nullable()});var rg=e.string();e.object({id:rg,createdAt:e.number(),updatedAt:e.number(),sha:e.string(),vcsRepoId:wh,url:e.string(),message:e.string(),parentShaList:e.string().array().nullable(),version:e.number(),authoredAt:e.number().nullable(),committedAt:e.number().nullable(),vcsIntegrationId:Y,workspaceId:H,type:tg,subject:e.string(),scope:e.string().nullable(),authorId:ng.nullable(),committerId:ng.nullable()}),e.object({id:rg,createdAt:e.number(),updatedAt:e.number(),sha:e.string(),vcsRepoId:wh,url:e.string(),message:e.string(),parentShaList:e.string().array().optional().nullable(),version:e.number(),authoredAt:e.number().optional().nullable(),committedAt:e.number().optional().nullable(),vcsIntegrationId:Y,workspaceId:H,type:tg,subject:e.string(),scope:e.string().optional().nullable(),authorId:ng.optional().nullable(),committerId:ng.optional().nullable()}),e.object({id:rg.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),sha:e.string().optional(),vcsRepoId:wh.optional(),url:e.string().optional(),message:e.string().optional(),parentShaList:e.string().array().optional().nullable(),version:e.number().optional(),authoredAt:e.number().optional().nullable(),committedAt:e.number().optional().nullable(),vcsIntegrationId:Y.optional(),workspaceId:H.optional(),type:tg.optional(),subject:e.string().optional(),scope:e.string().optional().nullable(),authorId:ng.optional().nullable(),committerId:ng.optional().nullable()}),e.object({vcsCommitId:rg,documentId:Z,createdAt:e.number(),updatedAt:e.number(),description:e.string(),version:e.number(),vcsIntegrationId:Y,workspaceId:H}),e.object({vcsCommitId:rg,documentId:Z,createdAt:e.number(),updatedAt:e.number(),description:e.string(),version:e.number(),vcsIntegrationId:Y,workspaceId:H}),e.object({vcsCommitId:rg.optional(),documentId:Z.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),description:e.string().optional(),version:e.number().optional(),vcsIntegrationId:Y.optional(),workspaceId:H.optional()}),e.object({documentId:Z,userId:G,workspaceId:H,lastReadAt:e.number(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({documentId:Z,userId:G,workspaceId:H,lastReadAt:e.number(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({documentId:Z.optional(),userId:G.optional(),workspaceId:H.optional(),lastReadAt:e.number().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()}),e.object({personId:K,taskId:Bh,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),version:e.number(),sortOrder:e.number(),date:e.iso.date()}),e.object({personId:K,taskId:Bh,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),version:e.number(),sortOrder:e.number(),date:e.iso.date()}),e.object({personId:K.optional(),taskId:Bh.optional(),workspaceId:H.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),sortOrder:e.number().optional(),date:e.iso.date().optional()});var ig=e.enum([`DOCUMENT`,`NOTE`,`SEQUENCE`,`NEW_NOTE`,`SPRITE`,`COMMENT_THREAD`]),ag=e.string();e.object({id:ag,workspaceId:H,userId:G,type:ig,noteId:q.nullable(),documentId:Z.nullable(),sequenceId:Q.nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),spriteId:X.nullable(),commentThreadId:Vh.nullable()}),e.object({id:ag,workspaceId:H,userId:G,type:ig,noteId:q.optional().nullable(),documentId:Z.optional().nullable(),sequenceId:Q.optional().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),spriteId:X.optional().nullable(),commentThreadId:Vh.optional().nullable()}),e.object({id:ag.optional(),workspaceId:H.optional(),userId:G.optional(),type:ig.optional(),noteId:q.optional().nullable(),documentId:Z.optional().nullable(),sequenceId:Q.optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),spriteId:X.optional().nullable(),commentThreadId:Vh.optional().nullable()});var og=e.string();e.object({id:og,workspaceId:H,email:W,lastSentAt:e.number().nullable(),invitedByUserId:G,createdAt:e.number(),updatedAt:e.number(),version:e.number(),token:e.string().nullable()}),e.object({id:og,workspaceId:H,email:W,lastSentAt:e.number().optional().nullable(),invitedByUserId:G,createdAt:e.number(),updatedAt:e.number(),version:e.number(),token:e.string().optional().nullable()}),e.object({id:og.optional(),workspaceId:H.optional(),email:W.optional(),lastSentAt:e.number().optional().nullable(),invitedByUserId:G.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),token:e.string().optional().nullable()});var sg=e.string();e.object({id:sg,workspaceId:H,projectId:J,spriteId:X,messageList:e.array(e.json()),createdAt:e.number(),updatedAt:e.number()}),e.object({id:sg,workspaceId:H,projectId:J,spriteId:X,messageList:e.array(e.json()),createdAt:e.number(),updatedAt:e.number()}),e.object({id:sg.optional(),workspaceId:H.optional(),projectId:J.optional(),spriteId:X.optional(),messageList:e.array(e.json()).optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var cg=e.string();e.object({id:cg,clientGroupId:xh,lastMutationId:e.number(),version:e.number()}),e.object({id:cg,clientGroupId:xh,lastMutationId:e.number(),version:e.number()}),e.object({id:cg.optional(),clientGroupId:xh.optional(),lastMutationId:e.number().optional(),version:e.number().optional()}),e.object({documentIdA:Z,documentIdB:Z,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),distance:e.number().nullable(),version:e.number(),status:Eh,createdByUserId:G.nullable(),lastModifiedByUserId:G.nullable(),lastModifiedAt:e.number().nullable()}),e.object({documentIdA:Z,documentIdB:Z,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),distance:e.number().optional().nullable(),version:e.number(),status:Eh,createdByUserId:G.optional().nullable(),lastModifiedByUserId:G.optional().nullable(),lastModifiedAt:e.number().optional().nullable()}),e.object({documentIdA:Z.optional(),documentIdB:Z.optional(),workspaceId:H.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),distance:e.number().optional().nullable(),version:e.number().optional(),status:Eh.optional(),createdByUserId:G.optional().nullable(),lastModifiedByUserId:G.optional().nullable(),lastModifiedAt:e.number().optional().nullable()});var lg=e.string();e.object({id:lg,userId:G,createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number(),twoFactorVerifiedAt:e.number().nullable()}),e.object({id:lg,userId:G,createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number(),twoFactorVerifiedAt:e.number().optional().nullable()}),e.object({id:lg.optional(),userId:G.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),expiresAt:e.number().optional(),twoFactorVerifiedAt:e.number().optional().nullable()});var ug=e.string();e.object({id:ug,workspaceId:H,hash:e.instanceof(Uint8Array),createdAt:e.number(),updatedAt:e.number(),contentHash:e.instanceof(Uint8Array),contentId:U,offset:e.number(),size:e.number(),tokenCount:e.number(),plaintext:e.string()}),e.object({id:ug,workspaceId:H,hash:e.instanceof(Uint8Array),createdAt:e.number(),updatedAt:e.number(),contentHash:e.instanceof(Uint8Array),contentId:U,offset:e.number(),size:e.number(),tokenCount:e.number(),plaintext:e.string()}),e.object({id:ug.optional(),workspaceId:H.optional(),hash:e.instanceof(Uint8Array).optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),contentHash:e.instanceof(Uint8Array).optional(),contentId:U.optional(),offset:e.number().optional(),size:e.number().optional(),tokenCount:e.number().optional(),plaintext:e.string().optional()}),e.object({llmProviderId:uh,encryptedValue:e.string(),plaintextSuffix:e.string(),createdAt:e.number(),updatedAt:e.number()}),e.object({llmProviderId:uh,encryptedValue:e.string(),plaintextSuffix:e.string(),createdAt:e.number(),updatedAt:e.number()}),e.object({llmProviderId:uh.optional(),encryptedValue:e.string().optional(),plaintextSuffix:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var dg=e.enum([`IS_IN`,`IS_NOT_IN`]),fg=e.string();e.object({id:fg,filterId:Qh,workspaceId:H,field:e.string(),comparator:dg,value:e.record(e.string(),e.json()),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:fg,filterId:Qh,workspaceId:H,field:e.string(),comparator:dg,value:e.record(e.string(),e.json()),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:fg.optional(),filterId:Qh.optional(),workspaceId:H.optional(),field:e.string().optional(),comparator:dg.optional(),value:e.record(e.string(),e.json()).optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()}),e.object({spriteIdA:X,spriteIdB:X,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),distance:e.number().nullable(),version:e.number(),status:Eh,createdByUserId:G.nullable(),lastModifiedByUserId:G.nullable(),lastModifiedAt:e.number().nullable()}),e.object({spriteIdA:X,spriteIdB:X,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),distance:e.number().optional().nullable(),version:e.number(),status:Eh,createdByUserId:G.optional().nullable(),lastModifiedByUserId:G.optional().nullable(),lastModifiedAt:e.number().optional().nullable()}),e.object({spriteIdA:X.optional(),spriteIdB:X.optional(),workspaceId:H.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),distance:e.number().optional().nullable(),version:e.number().optional(),status:Eh.optional(),createdByUserId:G.optional().nullable(),lastModifiedByUserId:G.optional().nullable(),lastModifiedAt:e.number().optional().nullable()}),e.object({taskId:Bh,labelId:sh,labelType:oh,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({taskId:Bh,labelId:sh,labelType:oh,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({taskId:Bh.optional(),labelId:sh.optional(),labelType:oh.optional(),workspaceId:H.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()});var pg=e.enum([`SIGNUP_REQUEST`,`SIGNUP_ATTEMPT_TOKEN`,`SIGNUP_SUCCESS`,`LOGIN_VIA_GOOGLE_SUCCESS`,`LOGIN_VIA_PASSWORD_ATTEMPT`,`LOGIN_VIA_PASSWORD_SUCCESS`,`RESET_PASSWORD_REQUEST`,`RESET_PASSWORD_ATTEMPT_TOKEN`,`RESET_PASSWORD_SUCCESS`,`PASSWORD_CHANGE`,`TOTP_ENABLE`,`TOTP_DISABLE`,`TOTP_VERIFY_ATTEMPT`,`TOTP_VERIFY_SUCCESS`,`RECOVERY_CODE_REGENERATED`,`RECOVERY_CODE_ATTEMPT`,`RECOVERY_CODE_SUCCESS`,`VALIDATE_INVITE_LINK_ATTEMPT`,`VALIDATE_INVITE_LINK_SUCCESS`,`VALIDATE_INVITATION_ATTEMPT`,`VALIDATE_INVITATION_SUCCESS`]),mg=e.string();e.object({id:mg,type:pg,userId:G.nullable(),email:W.nullable().nullable(),clientAddress:e.string(),userAgent:e.string(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:mg,type:pg,userId:G.optional().nullable(),email:W.nullable().optional().nullable(),clientAddress:e.string(),userAgent:e.string(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:mg.optional(),type:pg.optional(),userId:G.optional().nullable(),email:W.nullable().optional().nullable(),clientAddress:e.string().optional(),userAgent:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var hg=W;e.object({workspaceId:H,personId:K,email:hg,createdAt:e.number(),updatedAt:e.number(),isPrimary:e.boolean()}),e.object({workspaceId:H,personId:K,email:hg,createdAt:e.number(),updatedAt:e.number(),isPrimary:e.boolean()}),e.object({workspaceId:H.optional(),personId:K.optional(),email:hg.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),isPrimary:e.boolean().optional()}),e.object({documentId:Z,noteId:q,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),distance:e.number().nullable(),version:e.number(),status:Eh,createdByUserId:G.nullable(),lastModifiedByUserId:G.nullable(),lastModifiedAt:e.number().nullable()}),e.object({documentId:Z,noteId:q,workspaceId:H,createdAt:e.number(),updatedAt:e.number(),distance:e.number().optional().nullable(),version:e.number(),status:Eh,createdByUserId:G.optional().nullable(),lastModifiedByUserId:G.optional().nullable(),lastModifiedAt:e.number().optional().nullable()}),e.object({documentId:Z.optional(),noteId:q.optional(),workspaceId:H.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),distance:e.number().optional().nullable(),version:e.number().optional(),status:Eh.optional(),createdByUserId:G.optional().nullable(),lastModifiedByUserId:G.optional().nullable(),lastModifiedAt:e.number().optional().nullable()});var gg=e.string();e.object({id:gg,workspaceId:H,name:e.string(),hash:e.instanceof(Uint8Array),createdByUserId:G,lastUsedAt:e.number().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),scopeList:Zm.array()}),e.object({id:gg,workspaceId:H,name:e.string(),hash:e.instanceof(Uint8Array),createdByUserId:G,lastUsedAt:e.number().optional().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),scopeList:Zm.array()}),e.object({id:gg.optional(),workspaceId:H.optional(),name:e.string().optional(),hash:e.instanceof(Uint8Array).optional(),createdByUserId:G.optional(),lastUsedAt:e.number().optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),scopeList:Zm.array().optional()});var _g=e.enum([`MXBAI_EMBED_LARGE_V1`,`TEST`,`STELLA_EN_400M_V5`,`GTE_MULTILINGUAL_BASE`]),vg=e.enum([`DIM_1024`,`DIM_768`]),yg=e.string();e.object({id:yg,createdAt:e.number(),updatedAt:e.number(),hash:e.instanceof(Uint8Array),model:_g,dimension:vg,vector1024:e.array(e.number()).nullable(),vector768:e.array(e.number()).nullable()}),e.object({id:yg,createdAt:e.number(),updatedAt:e.number(),hash:e.instanceof(Uint8Array),model:_g,dimension:vg,vector1024:e.array(e.number()).optional().nullable(),vector768:e.array(e.number()).optional().nullable()}),e.object({id:yg.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),hash:e.instanceof(Uint8Array).optional(),model:_g.optional(),dimension:vg.optional(),vector1024:e.array(e.number()).optional().nullable(),vector768:e.array(e.number()).optional().nullable()});var bg=e.string(),xg=e.string(),Sg=e.string();e.object({tableName:bg,idA:xg,idB:Sg,workspaceId:H,deletedAt:e.number(),version:e.number()}),e.object({tableName:bg,idA:xg,idB:Sg,workspaceId:H,deletedAt:e.number(),version:e.number()}),e.object({tableName:bg.optional(),idA:xg.optional(),idB:Sg.optional(),workspaceId:H.optional(),deletedAt:e.number().optional(),version:e.number().optional()}),e.object({sequenceId:Q,documentId:Z,createdAt:e.number(),updatedAt:e.number(),sortOrder:e.number(),version:e.number(),workspaceId:H}),e.object({sequenceId:Q,documentId:Z,createdAt:e.number(),updatedAt:e.number(),sortOrder:e.number(),version:e.number(),workspaceId:H}),e.object({sequenceId:Q.optional(),documentId:Z.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),sortOrder:e.number().optional(),version:e.number().optional(),workspaceId:H.optional()});var Cg=e.enum([`SPRITE_BUILD`]);e.object({useCase:Cg,llmModelId:fh,createdAt:e.number(),updatedAt:e.number()}),e.object({useCase:Cg,llmModelId:fh,createdAt:e.number(),updatedAt:e.number()}),e.object({useCase:Cg.optional(),llmModelId:fh.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()}),e.object({spriteId:X,workspaceId:H,hash:e.instanceof(Uint8Array),version:e.number(),updatedAt:e.number(),plaintext:e.string()}),e.object({spriteId:X,workspaceId:H,hash:e.instanceof(Uint8Array),version:e.number(),updatedAt:e.number(),plaintext:e.string()}),e.object({spriteId:X.optional(),workspaceId:H.optional(),hash:e.instanceof(Uint8Array).optional(),version:e.number().optional(),updatedAt:e.number().optional(),plaintext:e.string().optional()});var wg=e.enum([`SIGNUP`,`PASSWORD_RESET`]),Tg=e.string();e.object({id:Tg,type:wg,userId:G.nullable(),email:W,tokenHash:e.string(),createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number(),verifiedAt:e.number().nullable(),retryCount:e.number()}),e.object({id:Tg,type:wg,userId:G.optional().nullable(),email:W,tokenHash:e.string(),createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number(),verifiedAt:e.number().optional().nullable(),retryCount:e.number()}),e.object({id:Tg.optional(),type:wg.optional(),userId:G.optional().nullable(),email:W.optional(),tokenHash:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),expiresAt:e.number().optional(),verifiedAt:e.number().optional().nullable(),retryCount:e.number().optional()}),e.object({id:K,name:e.string(),workspaceId:H,version:e.number(),createdAt:e.number(),updatedAt:e.number(),avatarAssetId:ih.nullable(),description:e.string(),emailList:W.array()}),e.enum([`PENDING`,`CREATED`,`FINISHED`,`TERMINATED`]);var Eg=e.number();e.object({id:Eg,jobQueueId:e.number().nullable(),taskId:e.number(),payload:e.unknown(),priority:e.number(),runAt:e.date(),attempts:e.number(),maxAttempts:e.number(),lastError:e.string().nullable(),createdAt:e.date(),updatedAt:e.date(),key:e.string().nullable(),lockedAt:e.date().nullable(),lockedBy:e.string().nullable(),revision:e.number(),flags:e.record(e.string(),e.json()).nullable(),isAvailable:e.boolean()}),e.object({id:Eg.optional(),jobQueueId:e.number().optional().nullable(),taskId:e.number(),payload:e.unknown().optional(),priority:e.number().optional(),runAt:e.date().optional(),attempts:e.number().optional(),maxAttempts:e.number().optional(),lastError:e.string().optional().nullable(),createdAt:e.date().optional(),updatedAt:e.date().optional(),key:e.string().optional().nullable(),lockedAt:e.date().optional().nullable(),lockedBy:e.string().optional().nullable(),revision:e.number().optional(),flags:e.record(e.string(),e.json()).optional().nullable(),isAvailable:e.boolean()}),e.object({id:Eg.optional(),jobQueueId:e.number().optional().nullable(),taskId:e.number().optional(),payload:e.unknown().optional(),priority:e.number().optional(),runAt:e.date().optional(),attempts:e.number().optional(),maxAttempts:e.number().optional(),lastError:e.string().optional().nullable(),createdAt:e.date().optional(),updatedAt:e.date().optional(),key:e.string().optional().nullable(),lockedAt:e.date().optional().nullable(),lockedBy:e.string().optional().nullable(),revision:e.number().optional(),flags:e.record(e.string(),e.json()).optional().nullable(),isAvailable:e.boolean().optional()});var Dg=e.number();e.object({id:Dg,ts:e.date(),breaking:e.boolean()}),e.object({id:Dg,ts:e.date().optional(),breaking:e.boolean().optional()}),e.object({id:Dg.optional(),ts:e.date().optional(),breaking:e.boolean().optional()});var Og=e.enum([`IN_PROGRESS`,`SUCCESS`,`ERROR`]),kg=e.string();e.object({id:kg,graphileWorkerJobId:e.string(),serviceName:e.string(),machineId:e.string(),attempt:e.number(),taskIdentifier:e.string(),payload:e.record(e.string(),e.json()),jobKey:e.string().nullable(),queueName:e.string().nullable(),workerId:e.string(),status:Og,runnableAt:e.number(),startedAt:e.number(),finishedAt:e.number().nullable(),error:e.record(e.string(),e.json()).nullable(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:kg,graphileWorkerJobId:e.string(),serviceName:e.string(),machineId:e.string(),attempt:e.number(),taskIdentifier:e.string(),payload:e.record(e.string(),e.json()),jobKey:e.string().optional().nullable(),queueName:e.string().optional().nullable(),workerId:e.string(),status:Og,runnableAt:e.number(),startedAt:e.number(),finishedAt:e.number().optional().nullable(),error:e.record(e.string(),e.json()).optional().nullable(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:kg.optional(),graphileWorkerJobId:e.string().optional(),serviceName:e.string().optional(),machineId:e.string().optional(),attempt:e.number().optional(),taskIdentifier:e.string().optional(),payload:e.record(e.string(),e.json()).optional(),jobKey:e.string().optional().nullable(),queueName:e.string().optional().nullable(),workerId:e.string().optional(),status:Og.optional(),runnableAt:e.number().optional(),startedAt:e.number().optional(),finishedAt:e.number().optional().nullable(),error:e.record(e.string(),e.json()).optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var Ag=e.number();e.object({id:Ag,identifier:e.string()}),e.object({id:Ag.optional(),identifier:e.string()}),e.object({id:Ag.optional(),identifier:e.string().optional()});var jg=e.enum([`MISSING_HEARTBEAT`,`STALE_HEARTBEAT`,`STOPPED_WITH_LOCKS`,`ALREADY_RECOVERED_WITH_LOCKS`]),Mg=e.string();e.object({workerPoolId:Mg,serviceName:e.string(),machineId:e.string(),startedAt:e.number().nullable(),lastHeartbeatAt:e.number().nullable(),stoppedAt:e.number().nullable(),recoveredAt:e.number().nullable(),recoveryReason:jg.nullable().nullable(),recoveredJobCount:e.number().nullable(),createdAt:e.number(),updatedAt:e.number()}),e.object({workerPoolId:Mg,serviceName:e.string(),machineId:e.string(),startedAt:e.number().optional().nullable(),lastHeartbeatAt:e.number().optional().nullable(),stoppedAt:e.number().optional().nullable(),recoveredAt:e.number().optional().nullable(),recoveryReason:jg.nullable().optional().nullable(),recoveredJobCount:e.number().optional().nullable(),createdAt:e.number(),updatedAt:e.number()}),e.object({workerPoolId:Mg.optional(),serviceName:e.string().optional(),machineId:e.string().optional(),startedAt:e.number().optional().nullable(),lastHeartbeatAt:e.number().optional().nullable(),stoppedAt:e.number().optional().nullable(),recoveredAt:e.number().optional().nullable(),recoveryReason:jg.nullable().optional().nullable(),recoveredJobCount:e.number().optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var Ng=e.string();e.object({identifier:Ng,knownSince:e.date(),lastExecution:e.date().nullable()}),e.object({identifier:Ng,knownSince:e.date(),lastExecution:e.date().optional().nullable()}),e.object({identifier:Ng.optional(),knownSince:e.date().optional(),lastExecution:e.date().optional().nullable()});var Pg=e.number();e.object({id:Pg,queueName:e.string(),lockedAt:e.date().nullable(),lockedBy:e.string().nullable(),isAvailable:e.boolean()}),e.object({id:Pg.optional(),queueName:e.string(),lockedAt:e.date().optional().nullable(),lockedBy:e.string().optional().nullable(),isAvailable:e.boolean()}),e.object({id:Pg.optional(),queueName:e.string().optional(),lockedAt:e.date().optional().nullable(),lockedBy:e.string().optional().nullable(),isAvailable:e.boolean().optional()}),e.object({id:Eg,queueName:e.string(),taskIdentifier:e.string(),priority:e.number(),runAt:e.date(),attempts:e.number(),maxAttempts:e.number(),lastError:e.string().nullable(),createdAt:e.date(),updatedAt:e.date(),key:e.string().nullable(),lockedAt:e.date().nullable(),lockedBy:e.string().nullable(),revision:e.number(),flags:e.record(e.string(),e.json()).nullable()}),e.object({identifier:e.string().nullable(),payload:e.unknown().nullable(),queueName:e.string().nullable(),runAt:e.date().nullable(),maxAttempts:e.number().nullable(),jobKey:e.string().nullable(),priority:e.number().nullable(),flags:e.string().nullable()});var Fg=e=>r.object({token:r.string().check(r.minLength(1),r.refine(e=>e.trim()!==``,{message:`Token must not be empty or whitespace`})),expiresAt:r.number().check(r.int(),r.gt(e)),personId:K}),Ig=(e,t=Date.now())=>{let n=Fg(t).safeParse(e);return n.success?n.data:Error(r.prettifyError(n.error))},Lg=class extends Error{status;constructor(e,t){super(t),this.name=`GatewayHttpError`,this.status=e}},Rg=r.object({message:r.string()}),zg=async e=>{let t=`Gateway request failed with status ${e.status}`;try{let n=await e.json(),r=Rg.safeParse(n);r.success&&(t=r.data.message)}catch{}return new Lg(e.status,t)},Bg=async e=>{try{return await e.json()}catch{return Error(`Gateway returned an invalid JSON response`)}},Vg=async e=>{let{baseUrl:n,projectId:r,userToken:i}=e,a=await t(()=>fetch(se({baseUrl:n,path:`/api/v1/project/${encodeURIComponent(r)}/session-token`}),{method:`POST`,headers:{authorization:`Bearer ${i}`}}));if(a instanceof Error)return a;if(!a.ok)return zg(a);let o=await Bg(a);return o instanceof Error?o:Ig(o)},Hg=r.object({token:r.string(),expiresAt:r.number(),personId:r.string()}),Ug=e=>Hg.safeParse(e).success,Wg=1e3,Gg=3e4,Kg=6e4,qg=e=>Math.min(Wg*2**Math.max(e-1,0),Gg),Jg=(e,t)=>t>=e.expiresAt-Kg,Yg=e=>{let{fetchSessionToken:t,now:n=Date.now}=e,r,i,a=0,o=0,s=0,c=()=>{r=void 0,i=void 0,a=0,o=0,s+=1},l=e=>{r&&(e===void 0||r.token===e)&&(r=void 0)},u=()=>{let e=o-n();if(e>0)return Promise.reject(Error(`fetchSessionToken is rate limited after repeated failures; retry in ${e}ms`));let c=s;return i=t().then(e=>{if(c!==s)throw Error(`Session token fetch was reset before it completed`);return r=e,a=0,o=0,e}).catch(e=>{throw c===s&&(r=void 0,a+=1,o=n()+qg(a)),e}).finally(()=>{c===s&&(i=void 0)}),i};return{getSessionToken:()=>r&&!Jg(r,n())?Promise.resolve(r):i===void 0?u():i,invalidateToken:l,reset:c}},Xg=e=>{let{baseUrl:t,projectId:n,fetchUserToken:r,exchangeIdentityTokenForSessionToken:i=Vg}=e,a=Yg({fetchSessionToken:async()=>{let e=await r();if(typeof e==`string`){if(e.trim()===``)throw Error(`fetchUserToken must return a non-empty string`);let r=await i({baseUrl:t,projectId:n,userToken:e});if(r instanceof Error)throw r;return r}if(Ug(e)){let t=Ig(e);if(t instanceof Error)throw t;return t}throw Error(`fetchUserToken must return a non-empty string`)}});return{getSessionToken:()=>a.getSessionToken(),invalidateToken:e=>{a.invalidateToken(e)},destroy:async()=>{a.reset()}}},Zg=Symbol(`rough.client.runtime`),Qg=e=>{let t=e?.[Zg];if(!t)throw new Ot;return t},$g=e=>{let{fetchUserToken:t,projectId:n}=e,r=e.baseUrl??`https://gateway.rough.app`;if(typeof n!=`string`||n.trim()===``)throw TypeError(`createRoughClient: "projectId" is required`);if(typeof t!=`function`)throw TypeError(`createRoughClient: "fetchUserToken" is required`);let i=Symbol(`rough.client:${n}`),a=new AbortController,o=`starting`,s,c=Xg({baseUrl:r,fetchUserToken:t,projectId:n}),l=et(),u=Bt(),d=zt({getRuntime:()=>h}),f=Km({auth:c,baseUrl:r,clientId:i,projectId:n,signal:a.signal,store:l}),p=()=>{if(o===`destroying`||o===`destroyed`)throw new wt},m=(async()=>{await f.start();let e=f.peek();if(!e||a.signal.aborted)return;let t=await ce({projectId:n,replicache:e});t instanceof Error&&!a.signal.aborted&&console.error(`[Rough] Failed to ping project`,t)})().then(()=>{o===`starting`&&(o=`active`)},e=>{throw o===`starting`&&(o=`failed`),kt(e)});m.catch(()=>{});let h={clientId:i,baseUrl:r,projectId:n,auth:c,store:l,surfaces:d,operations:u,getState:()=>o,assertUsable:p,whenReady:()=>m,getReplicache:async()=>{p(),await m,p();let e=f.peek();if(!e)throw Error(`Replicache is not available in this environment. Rough clients only open a local database in the browser.`);return e},buildUrl:e=>se({baseUrl:r,...e})},g=async()=>{let e=[],t=async(t,n)=>{try{await n()}catch(n){let r=kt(n);r.message=`${t}: ${r.message}`,e.push(r)}};try{await t(`operations`,()=>u.closeAll()),await t(`surfaces`,()=>d.destroy()),await Promise.allSettled([m]),await t(`replicache`,()=>f.destroy()),await Promise.all([t(`store`,()=>l.destroy()),t(`auth`,()=>c.destroy())])}finally{f.releaseIdentity(),o=`destroyed`}if(e.length>0)throw new Dt({errors:e})},_={get projectId(){return n},destroy:()=>s||(o=`destroying`,f.markDestroying(),a.abort(new wt),s=g(),s)};return Object.defineProperty(_,Zg,{value:h,enumerable:!1,writable:!1,configurable:!1}),Object.freeze(_)},e_=async e=>{await Qg(e.client).whenReady()},t_=e=>e.filter(e=>e.publishedAt!==null).toSorted((e,t)=>{let n=(t.publishedAt??0)-(e.publishedAt??0);return n===0?t.id.localeCompare(e.id):n}).at(0)??null,n_=e=>{let{sprite:t,spriteBuildList:n}=e;return{id:t.id,name:t.name,ownedByPersonId:t.ownedByPersonId,publishedSpriteBuildId:t_(n)?.id??null}},r_=(e,t)=>{let n=new Map;for(let t of e.spriteBuild.asList.value){let e=n.get(t.spriteId);e||(e=[],n.set(t.spriteId,e)),e.push(t)}let r=[];for(let i of e.sprite.asList.value){if(i.surfaceId!==t)continue;let e=n_({sprite:i,spriteBuildList:n.get(i.id)??[]});e.publishedSpriteBuildId&&r.push(e)}return r.toSorted((e,t)=>t.id.localeCompare(e.id))},i_=e=>{let{client:t,onError:n,onFeatures:r,signal:i}=e,a=Qg(t);a.assertUsable();let o=Lt(e.surface),s=a.surfaces.acquire({surface:o}),c=new AbortController,l,u,d,f=(async()=>{let e=await Promise.race([s.ready.then(e=>({type:`resolved`,resolution:e})),Mt(c.signal).then(()=>({type:`aborted`}))]);if(e.type===`aborted`||c.signal.aborted)return;let t=e.resolution.id,n=()=>{c.signal.aborted||r(r_(a.store,t))};l=a.store.subscribe(n),n()})();f.catch(e=>{c.signal.aborted||n?.(kt(e))});let p=()=>(d??=(async()=>{c.abort(),l?.(),l=void 0,s.release(),u?.(),u=void 0,await Promise.allSettled([f])})(),d);return u=a.operations.register({label:`getRoughFeatures(${o.key})`,close:p}),i&&(i.aborted?p():i.addEventListener(`abort`,()=>void p(),{once:!0})),{get ready(){return f},unsubscribe:p}},a_={xmlns:`http://www.w3.org/2000/svg`,width:24,height:24,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,"stroke-width":2,"stroke-linecap":`round`,"stroke-linejoin":`round`},o_=e=>{for(let t in e)if(t.startsWith(`aria-`)||t===`role`||t===`title`)return!0;return!1},s_=Symbol(`lucide-context`),c_=()=>i(s_),l_=new Set([`$$slots`,`$$events`,`$$legacy`,`$$host`,`name`,`color`,`size`,`strokeWidth`,`absoluteStrokeWidth`,`iconNode`,`children`]),u_=l.from_svg(`<svg><!><!></svg>`);function d_(e,t){l.push(t,!0);let n=c_()??{},r=l.prop(t,`name`,7),i=l.prop(t,`color`,23,()=>n.color??`currentColor`),a=l.prop(t,`size`,23,()=>n.size??24),o=l.prop(t,`strokeWidth`,23,()=>n.strokeWidth??2),s=l.prop(t,`absoluteStrokeWidth`,23,()=>n.absoluteStrokeWidth??!1),c=l.prop(t,`iconNode`,23,()=>[]),u=l.prop(t,`children`,7),d=l.rest_props(t,l_),f=l.derived(()=>s()?Number(o())*24/Number(a()):o());var p={get name(){return r()},set name(e){r(e),l.flush()},get color(){return i()},set color(e=n.color??`currentColor`){i(e),l.flush()},get size(){return a()},set size(e=n.size??24){a(e),l.flush()},get strokeWidth(){return o()},set strokeWidth(e=n.strokeWidth??2){o(e),l.flush()},get absoluteStrokeWidth(){return s()},set absoluteStrokeWidth(e=n.absoluteStrokeWidth??!1){s(e),l.flush()},get iconNode(){return c()},set iconNode(e=[]){c(e),l.flush()},get children(){return u()},set children(e){u(e),l.flush()}},m=u_();l.attribute_effect(m,e=>({...a_,...e,...d,width:a(),height:a(),stroke:i(),"stroke-width":l.get(f),class:[`lucide-icon lucide`,n.class,r()&&`lucide-${r()}`,t.class]}),[()=>!u()&&!o_(d)&&{"aria-hidden":`true`}]);var h=l.child(m);l.each(h,17,c,l.index,(e,t)=>{var n=l.derived(()=>l.to_array(l.get(t),2));let r=()=>l.get(n)[0],i=()=>l.get(n)[1];var a=l.comment(),o=l.first_child(a);l.element(o,r,!0,(e,t)=>{l.attribute_effect(e,()=>({...i()}))}),l.append(e,a)});var g=l.sibling(h);return l.snippet(g,()=>u()??l.noop),l.reset(m),l.append(e,m),l.pop(p)}l.create_custom_element(d_,{name:{},color:{},size:{},strokeWidth:{},absoluteStrokeWidth:{},iconNode:{},children:{}},[],[],{mode:`open`});var f_=new Set([`$$slots`,`$$events`,`$$legacy`,`$$host`]);function p_(e,t){let n=l.rest_props(t,f_),r=[[`path`,{d:`m5 12 7-7 7 7`}],[`path`,{d:`M12 19V5`}]];d_(e,l.spread_props({name:`arrow-up`},()=>n,{get iconNode(){return r}}))}l.create_custom_element(p_,{},[],[],{mode:`open`});var m_=new Set([`$$slots`,`$$events`,`$$legacy`,`$$host`]);function h_(e,t){let n=l.rest_props(t,m_),r=[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`}]];d_(e,l.spread_props({name:`square`},()=>n,{get iconNode(){return r}}))}l.create_custom_element(h_,{},[],[],{mode:`open`});var g_=class extends Error{missingFeature;constructor(e){super(__(e)),this.name=`UnsupportedResponseStreamError`,this.missingFeature=e}};function __(e){return`Streaming fetch responses are not supported in this runtime because ${e} is unavailable. React Native users need a compatible fetch/stream/TextDecoder polyfill, or should use a fetch, XHR, or custom transport that can deliver streaming chunks.`}function v_(e){if(!e.body)throw new g_(`Response.body`);if(typeof e.body.getReader!=`function`)throw new g_(`Response.body.getReader`);return e.body.getReader()}function y_(){if(typeof globalThis.TextDecoder!=`function`)throw new g_(`TextDecoder`);return new globalThis.TextDecoder}function b_(e){if(!e.startsWith(`data:`))return e;let t=e.slice(5);return t.startsWith(` `)?t.slice(1):t}var x_=new WeakMap;function S_(e){return x_.get(e)??(`runId`in e&&typeof e.runId==`string`?e.runId:void 0)}var C_=class extends Error{constructor(){super(`Stream ended with unterminated trailing data — connection was likely cut short.`),this.name=`StreamTruncatedError`}},w_=class extends Error{constructor(e){super(`Stream response body read failed`,{cause:e}),this.name=`StreamReadError`}},T_=class extends Error{constructor(){super(`Durable run ended without a terminal event and could not resume — the run did not complete.`),this.name=`DurableStreamIncompleteError`}},E_=class extends Error{constructor(e){super(`Durable run exceeded its reconnect ceiling of ${e} attempts — giving up.`),this.name=`StreamReconnectLimitError`}};function D_(e){let t=e?.maxAttempts??5,n=e?.delayMs??250;if(!Number.isInteger(t)||t<0)throw Error(`Invalid reconnect.maxAttempts: ${t}. Must be a non-negative integer.`);if(!Number.isFinite(n)||n<0)throw Error(`Invalid reconnect.delayMs: ${n}. Must be a non-negative finite number.`);return{maxAttempts:t,delayMs:n}}function O_(e){let t=D_(e),n=new Set,r,i=0;return{get lastEventId(){return r},note(e){return e===void 0?`new`:e===``?(r=void 0,n.clear(),`reset`):n.has(e)?`duplicate`:(n.add(e),r=e,`new`)},async waitBeforeReconnect(e,n){if(e)i=0;else if(i+=1,i>t.maxAttempts)throw new E_(t.maxAttempts);await k_(t.delayMs,n)}}}function k_(e,t){return e<=0||t?.aborted?Promise.resolve():new Promise(n=>{let r=()=>{clearTimeout(i),n()},i=setTimeout(()=>{t?.removeEventListener(`abort`,r),n()},e);t?.addEventListener(`abort`,r,{once:!0})})}function A_(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function j_(e,t){if(!e)throw Error(`Cannot synthesize terminal event: ${t} not supplied via runContext and not observed in the upstream stream.`);return e}function M_(e){if(!e)return{};if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}return e}var N_=`X-Run-Id`;function P_(e){return e===void 0?{}:{[N_]:e}}function F_(e,t){let n=e.indexOf(`#`),r=n===-1?``:e.slice(n),i=n===-1?e:e.slice(0,n),a=i.indexOf(`?`),o=a===-1?i:i.slice(0,a),s=new URLSearchParams(a===-1?``:i.slice(a+1));for(let[e,n]of Object.entries(t))s.set(e,n);let c=s.toString();return`${o}${c.length===0?``:`?${c}`}${r}`}async function*I_(e,t){try{let n=y_(),r=``;for(;!t?.aborted;){let i;try{i=await e.read()}catch(e){if(t?.aborted)return;throw new w_(e)}let{done:a,value:o}=i;if(a)break;r+=n.decode(o,{stream:!0});let s=r.split(`
26
+ `);r=s.pop()||``;for(let e of s){let t=e.endsWith(`\r`)?e.slice(0,-1):e;t.trim()&&(yield t)}}if(r+=n.decode(),r.trim()&&!t?.aborted)throw new C_}finally{e.releaseLock()}}async function*L_(e,t){let n,r,i,a;for await(let o of e){if(o===`id`||o.startsWith(`id:`)){let e=o===`id`?``:o.slice(3);a=e.startsWith(` `)?e.slice(1):e;continue}if(o.startsWith(`:`)||o.startsWith(`event:`)||o.startsWith(`retry:`))continue;let e=b_(o);if(e===`[DONE]`){yield{chunk:{type:Nm.RUN_FINISHED,threadId:n??t?.threadId??``,runId:r??t?.runId??``,model:i??``,timestamp:Date.now(),finishReason:`stop`}};return}let s=JSON.parse(e);`threadId`in s&&typeof s.threadId==`string`&&(n=s.threadId),`runId`in s&&typeof s.runId==`string`&&(r=s.runId),`model`in s&&typeof s.model==`string`&&(i=s.model);let c=a;a=void 0,yield{chunk:s,...c===void 0?{}:{id:c}}}}function R_(e){if(!e.ok)throw Error(`HTTP error! status: ${e.status} ${e.statusText}`)}async function z_(e,t,n,r,i){let a=await e(F_(t,{threadId:i}),{method:`GET`,headers:{Accept:`application/json`,...n},credentials:r});R_(a);let o=await a.json(),s=o.activeRun&&typeof o.activeRun.runId==`string`?{runId:o.activeRun.runId}:null,c=o.interrupts&&typeof o.interrupts.runId==`string`&&Array.isArray(o.interrupts.pending)&&o.interrupts.pending.length>0?{runId:o.interrupts.runId,pending:o.interrupts.pending}:null;return{messages:Array.isArray(o.messages)?o.messages:[],activeRun:s,interrupts:c}}async function B_(e,t,n,r,i){let a=await e(F_(t,{threadId:i}),{method:`GET`,headers:{Accept:`application/json`,...n},credentials:r});R_(a);let o=await a.json();if(o===null)return{resumeSnapshot:null,activeRun:null};if(typeof o!=`object`||Array.isArray(o))throw Error(`Generation hydration expected a JSON object from ${t}, received ${Array.isArray(o)?`an array`:typeof o}.`);let s=o,c=s.activeRun&&typeof s.activeRun.runId==`string`?{runId:s.activeRun.runId}:null;return{resumeSnapshot:s.resumeSnapshot??null,activeRun:c}}async function*V_(e,t,n){R_(e),yield*L_(I_(v_(e),t),n)}async function*H_(e,t){for await(let{chunk:n}of V_(e,t))yield n}function U_(e,t,n,r){return async function*(i,a){let o;try{o=await e(t,{...n,headers:{...n.headers,...i},...a?{signal:a}:{}})}catch(e){throw new w_(e)}yield*r(o,a)}}async function*W_(e,t,n){let r=O_(n);for(;;){if(t?.aborted)return;let n=r.lastEventId===void 0?{}:{"Last-Event-ID":r.lastEventId},i=!1,a=!1;try{for await(let{chunk:o,id:s}of e(n,t))r.note(s)!==`duplicate`&&(a=!0,(o.type===`RUN_FINISHED`||o.type===`RUN_ERROR`)&&(i=!0),yield o)}catch(e){if(t?.aborted)return;if((e instanceof C_||e instanceof w_)&&r.lastEventId!==void 0){await r.waitBeforeReconnect(a,t);continue}throw e}if(t?.aborted||i)return;if(r.lastEventId!==void 0){if(a){await r.waitBeforeReconnect(!0,t);continue}throw new T_}return}}function G_(e){if(!e)throw Error(`Connection adapter is required`);let t=`connect`in e,n=`subscribe`in e,r=`send`in e;if(t&&(n||r))throw Error(`Connection adapter must provide either connect or both subscribe and send, not both modes`);if(n&&r){let t=e.joinRun?.bind(e),n=e.hydrate?.bind(e);return{subscribe:e.subscribe.bind(e),send:e.send.bind(e),...t?{joinRun:t}:{},...n?{hydrate:n}:{}}}if(!t)throw Error(`Connection adapter must provide either connect or both subscribe and send`);let i=[],a=[];function o(e,t){t&&x_.set(e,t);let n=a.shift();n?n(e):i.push(e)}return{subscribe(e){let t=i.splice(0),n=[];return i=t,a=n,(async function*(){for(;!e?.aborted;){let r,i=t.shift();r=i===void 0?await new Promise(t=>{let r=()=>t(null);n.push(n=>{e?.removeEventListener(`abort`,r),t(n)}),e?.addEventListener(`abort`,r,{once:!0})}):i,r!==null&&(yield r)}})()},async send(t,n,r,i){let a=!1,s,c;try{let l=e.connect(t,n,r,i);for await(let e of l)`threadId`in e&&typeof e.threadId==`string`&&(s=e.threadId),`runId`in e&&typeof e.runId==`string`&&(c=e.runId),(e.type===`RUN_FINISHED`||e.type===`RUN_ERROR`)&&(a=!0),o(e,i?.runId);!r?.aborted&&!a&&o({type:Nm.RUN_FINISHED,threadId:j_(s??i?.threadId,`threadId`),runId:j_(c??i?.runId,`runId`),model:`connect-wrapper`,timestamp:Date.now(),finishReason:`stop`},i?.runId)}catch(e){if(!r?.aborted&&!a)try{let t=e instanceof Error?e.message:`Unknown error in connect()`;o({type:Nm.RUN_ERROR,threadId:j_(s??i?.threadId,`threadId`),runId:j_(c??i?.runId,`runId`),timestamp:Date.now(),message:t},i?.runId)}catch{}throw e}},...typeof e.joinRun==`function`?{joinRun:(t,n)=>e.joinRun(t,n)}:{},...(()=>{let t=e.hydrate;return typeof t==`function`?{hydrate:e=>t(e)}:{}})()}}function K_(e,t,n,r){let i=Em(e),a={...r.body,...n?.forwardedProps??{},...t};return{threadId:n?.threadId??A_(`thread`),runId:n?.runId??A_(`run`),...n?.parentRunId!==void 0&&{parentRunId:n.parentRunId},...n?.resume!==void 0&&{resume:n.resume},state:{},messages:i,tools:n?.clientTools??[],context:[],forwardedProps:a,data:{...a}}}function q_(e,t={}){return{async*connect(n,r,i,a){let o=typeof e==`function`?e():e,s=typeof t==`function`?await t():t,c={"Content-Type":`application/json`,...M_(s.headers),...P_(a?.runId)},l=K_(n,r,a,s),u=s.fetchClient??fetch,d=i||s.signal;yield*W_(U_(u,o,{method:`POST`,headers:c,body:JSON.stringify(l),credentials:s.credentials||`same-origin`},(e,t)=>V_(e,t,{...a?.threadId===void 0?{}:{threadId:a.threadId},...a?.runId===void 0?{}:{runId:a.runId}})),d,s.reconnect)},async*joinRun(n,r){let i=typeof e==`function`?e():e,a=typeof t==`function`?await t():t,o=F_(i,{offset:`-1`,runId:n}),s={...M_(a.headers)},c=a.fetchClient??fetch,l=r||a.signal;yield*W_(U_(c,o,{method:`GET`,headers:s,credentials:a.credentials||`same-origin`},(e,t)=>V_(e,t,{runId:n})),l,a.reconnect)},async hydrate(n){let r=typeof e==`function`?e():e,i=typeof t==`function`?await t():t;return z_(i.fetchClient??fetch,r,M_(i.headers),i.credentials||`same-origin`,n)},async hydrateGeneration(n){let r=typeof e==`function`?e():e,i=typeof t==`function`?await t():t;return B_(i.fetchClient??fetch,r,M_(i.headers),i.credentials||`same-origin`,n)}}}function J_(e){return{async*connect(t,n,r,i){if(!r)throw Error(`fetcherToConnectionAdapter requires an AbortSignal — the chat client always supplies one.`);if(!i)throw Error(`fetcherToConnectionAdapter requires a RunAgentInputContext — the chat client always supplies one.`);let a=await e({messages:t,data:n,threadId:i.threadId,runId:i.runId,...i.parentRunId===void 0?{}:{parentRunId:i.parentRunId},...i.resume===void 0?{}:{resume:i.resume}},{signal:r});a instanceof Response?yield*H_(a,r):yield*Y_(a,r)}}}async function*Y_(e,t){if(t.aborted)return;let n=e[Symbol.asyncIterator](),r=new Promise(e=>{t.addEventListener(`abort`,()=>e({done:!0,value:void 0}),{once:!0})});try{for(;;){let e=await Promise.race([n.next(),r]);if(e.done)return;yield e.value}}finally{await n.return?.()}}function X_(e){return e.resumable}function Z_(e,t){let n=Rp(e.descriptor);return n?{...t,metadata:Lp(n)}:t}function Q_(e){return`cancel`in e&&`clearResolution`in e}var $_=new Set([`invalid-payload`,`invalid-edited-args`,`invalid-tool-output`,`invalid-response-schema`,`unknown-interrupt`,`expired`,`stale`,`conflict`,`legacy-unsupported`]),ev=new Set([`incomplete-batch`,`item-validation-failed`,`unsupported-bulk-operation`,`async-resolver`,`inactive-transaction`,`mixed-provenance`,`transport`,`server`,`protocol`,`invalid-response-schema`,`expired`,`stale`,`conflict`,`legacy-submit-failed`]);function tv(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function nv(e){return tv(e)&&e.kind===`approval`&&typeof e.toolName==`string`&&`input`in e}function rv(e){return tv(e)&&e.kind===`client_tool`&&typeof e.toolName==`string`&&`input`in e}function iv(e){return nv(e.metadata)||rv(e.metadata)}function av(e){return jp(e)}function ov(e){if(!tv(e.metadata))return!1;let t=e.metadata[Tp];return!tv(t)||t.v!==void 0&&t.v!==1?!1:t.kind===`generic`||t.kind===`tool-approval`||t.kind===`client-tool-execution`||`definitionId`in t||`key`in t||`batchIndex`in t||`payloadSchemaHash`in t}function sv(e){if(!tv(e.metadata))return!1;let t=e.metadata[Tp];return!tv(t)||t.kind!==`generic`?!1:`definitionId`in t||`key`in t||`batchIndex`in t||`payloadSchemaHash`in t}function cv(e){return e.metadata?.[`tanstack:interruptPayload`]}function lv(e){return e===`tanstack:client_tool_execution`||e===`client_tool_input`}function uv(e){if(e.responseSchema!==void 0)try{return np(tp(e.responseSchema))}catch{return}}function dv(e){if(e!==void 0)try{return Pp(e)}catch{return}}function fv(e){return e!==null&&(typeof e==`object`||typeof e==`function`)&&`then`in e&&typeof e.then==`function`}function pv(e,t,n){if(e===void 0)return{valid:!0,payload:t};if(cp(e)){let r=e[`~standard`].validate(t),i=e=>e.issues?{code:n,message:e.issues[0]?.message??`Schema validation failed.`}:{valid:!0,payload:e.value};return fv(r)?Promise.resolve(r).then(i):i(r)}return{valid:!0,payload:t}}function mv(e){for(let t of $_)if(t===e)return!0;return!1}function hv(e){for(let t of ev)if(t===e)return!0;return!1}function gv(e){if(!tv(e))return!1;let t=e.scope,n=e.code;return typeof n!=`string`||typeof e.message!=`string`||typeof e.retryable!=`boolean`||typeof e.threadId!=`string`||typeof e.interruptedRunId!=`string`||typeof e.generation!=`number`?!1:t===`item`?mv(n)&&typeof e.interruptId==`string`&&(e.source===`client`||e.source===`server`):t===`batch`&&hv(n)&&Array.isArray(e.interruptIds)&&e.interruptIds.every(e=>typeof e==`string`)&&(e.source===`client`||e.source===`server`||e.source===`transport`)}function _v(e){return gv(e)?[e]:!tv(e)||!Array.isArray(e.errors)?[]:e.errors.every(gv)?e.errors:[]}function vv(e,t){if(e.length!==t.length)return!1;let n=[...e].sort(),r=[...t].sort();return n.every((e,t)=>e===r[t])}function yv(e,t){return e.threadId===t.threadId&&e.interruptedRunId===t.interruptedRunId&&e.generation===t.generation&&vv(e.interruptIds,t.interruptIds)}function bv(e,t,n){let r=n.filter(e=>e.source!==`transport`),i=e=>t.includes(e)&&r.some(t=>yv(e,t)),a=e.filter(e=>!i(e)),o=t.filter(e=>!r.some(t=>yv(e,t)));return Object.freeze({rootErrors:Object.freeze([...a,...n]),submissionRootErrors:Object.freeze([...o,...r])})}function xv(e,t){if(e.threadId!==t.threadId||e.interruptedRunId!==t.interruptedRunId||e.generation!==t.generation)return!1;let n=t.resolutions.map(e=>e.interruptId);return e.scope===`item`?n.includes(e.interruptId):vv(e.interruptIds,n)}function Sv(e,t,n){let r=uv(e)??n?.responseSchemaHash;return V({v:1,kind:`generic`,interruptId:e.id,interruptedRunId:t.interruptedRunId,generation:t.generation,...r===void 0?{}:{responseSchemaHash:r},...e.expiresAt===void 0?{}:{expiresAt:e.expiresAt}})}function Cv(e,t){let n=V(e.descriptor),r=e.error===void 0?Object.freeze([]):Object.freeze([V(e.error)]),i=r[0];return{id:n.id,interruptId:n.id,reason:n.reason,...n.message===void 0?{}:{message:n.message},...n.responseSchema===void 0?{}:{responseSchema:n.responseSchema},...n.expiresAt===void 0?{}:{expiresAt:n.expiresAt},...n.metadata===void 0?{}:{metadata:n.metadata},threadId:t.threadId,interruptedRunId:t.interruptedRunId,generation:t.generation,status:e.status,errors:r,...i===void 0?{}:{error:i},canResolve:e.canResolve}}var wv=class{options;hydration;items=[];snapshot=Object.freeze([]);rootErrors=Object.freeze([]);submissionRootErrors=Object.freeze([]);state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:!1});activeTransaction;retrySubmission;resuming=!1;tools;interruptDefinitions;constructor(e){this.options=e,this.tools=e.tools;let t=new Map;for(let n of e.interrupts??[]){if(t.has(n.id))throw Error(`Duplicate interrupt definition id: ${n.id}`);t.set(n.id,n)}this.interruptDefinitions=t}updateTools(e){this.tools=e}hydrate(e,t=`live`){this.hydration={threadId:e.threadId,interruptedRunId:e.interruptedRunId,generation:e.generation,interrupts:V(e.interrupts)};let n=new Map;for(let t of e.interrupts){let e=av(t);e?.kind===`generic`&&e.definitionId!==void 0&&e.key!==void 0&&e.batchIndex!==void 0&&n.set(e.batchIndex,(n.get(e.batchIndex)??0)+1)}this.items=e.interrupts.map(t=>this.hydrateInterrupt(t,e,n)),this.rootErrors=Object.freeze([]),this.submissionRootErrors=Object.freeze([]),this.retrySubmission=void 0,this.resuming=!1,this.publish(t)}getInterrupts(){return this.snapshot}getState(){return this.state}getDescriptors(){return this.hydration?.interrupts??Object.freeze([])}hasValidatedFirstPartyGenericBatch(){return this.items.some(e=>e.kind===`generic`&&e.definition!==void 0)}reset(e){this.hydration=void 0,this.items=[],this.snapshot=Object.freeze([]),e?.preserveRootErrors!==!0&&(this.rootErrors=Object.freeze([]),this.submissionRootErrors=Object.freeze([])),this.retrySubmission=void 0,this.resuming=!1,this.state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:!1}),this.options.onChange?.(e?.source??`live`)}getInterruptErrors(){return this.rootErrors}getResuming(){return this.resuming}resolve(e){if(this.assertRootMutable(),typeof e==`boolean`){this.resolveBooleanBulk(e);return}this.resolveTransaction(e)}cancel(){this.assertRootMutable(),this.invalidateRetry();for(let e of this.items)X_(e)&&(e.validationGeneration++,e.resolution=Object.freeze(Z_(e,{interruptId:e.descriptor.id,status:`cancelled`})),e.status=`staged`,e.error=void 0);this.publish(),this.maybeSubmit()}retry(){if(this.resuming)throw Error(`Interrupt submission is already active.`);let e=this.retrySubmission;if(!e){this.addRootError(`transport`,`There is no retryable interrupt submission.`,!1);return}this.submitBatch(e)}resolveClientToolOutput(e,t){let n=this.items.find(t=>t.kind===`client-tool-execution`&&t.binding?.kind===`client-tool-execution`&&t.binding.toolCallId===e||t.kind===`generic`&&lv(t.descriptor.reason)&&t.descriptor.toolCallId===e&&rv(t.descriptor.metadata));return n?(this.resolveItem(n.descriptor.id,t),!0):!1}resolveToolApprovalDecision(e,t){let n=this.items.find(t=>t.descriptor.id===e&&(t.kind===`tool-approval`||t.kind===`generic`&&t.descriptor.reason===`approval_required`&&nv(t.descriptor.metadata)));return n?(this.resolveItem(n.descriptor.id,{approved:t}),!0):!1}hydrateInterrupt(e,t,n){let r=V(e),i=av(r),a=i===void 0&&iv(r);if(i===void 0&&!a)return ov(r)?{descriptor:r,binding:Sv(r,t,void 0),kind:`generic`,status:`error`,canResolve:!1,resumable:!1,error:this.itemError(r.id,`stale`,`The interrupt binding is invalid or incomplete.`),validationGeneration:0}:{descriptor:r,binding:void 0,kind:`unbound`,status:`pending`,canResolve:!1,resumable:!1,validationGeneration:0};let o=i!==void 0&&i.interruptId===r.id&&i.interruptedRunId===t.interruptedRunId&&i.generation===t.generation&&uv(r)===i.responseSchemaHash,s=i!==void 0&&i.interruptId===r.id&&i.interruptedRunId===t.interruptedRunId&&i.generation===t.generation&&i.responseSchemaHash===(uv(r)??i.responseSchemaHash);if(i!==void 0&&sv(r)&&(!s||i.kind!==`generic`||i.definitionId===void 0||i.key===void 0||i.batchIndex===void 0))return{descriptor:r,binding:Sv(r,t,i),kind:`generic`,status:`error`,canResolve:!1,resumable:!1,error:this.itemError(r.id,`stale`,`The interrupt binding does not match this interrupted run.`),validationGeneration:0};if(s&&i.kind===`tool-approval`){let e=this.tools?.find(e=>e.name===i.toolName);if(e?.needsApproval===!0&&r.toolCallId===i.toolCallId)try{let t=Cp(e.approvalSchema,e.inputSchema);if(wp(e.inputSchema)===i.inputSchemaHash&&t.approvalSchemaHash===i.approvalSchemaHash&&t.responseSchemaHash===i.responseSchemaHash)return{descriptor:r,binding:V(i),kind:`tool-approval`,status:`pending`,canResolve:!0,resumable:!0,tool:e,validationGeneration:0}}catch{}}if(s&&i.kind===`client-tool-execution`){let e=this.tools?.find(e=>e.name===i.toolName);if(e!==void 0&&r.toolCallId===i.toolCallId&&wp(e.outputSchema)===i.outputSchemaHash)return{descriptor:r,binding:V(i),kind:`client-tool-execution`,status:`pending`,canResolve:!0,resumable:!0,tool:e,validationGeneration:0}}if(i!==void 0&&i.kind===`generic`&&i.definitionId!==void 0&&i.key!==void 0&&i.batchIndex!==void 0&&i.key.length>0&&n.get(i.batchIndex)!==1)return{descriptor:r,binding:V(i),kind:`generic`,status:`error`,canResolve:!1,resumable:!1,error:this.itemError(r.id,`stale`,`Generic interrupt batch contains a duplicate batchIndex.`),validationGeneration:0};if(o&&i.kind===`generic`&&i.definitionId!==void 0&&i.key!==void 0&&i.batchIndex!==void 0&&i.key.length>0&&n.get(i.batchIndex)===1){let e=this.interruptDefinitions.get(i.definitionId);if(e!==void 0&&dv(e.responseSchema)===i.responseSchemaHash&&(e.payloadSchema===void 0?i.payloadSchemaHash===void 0:i.payloadSchemaHash===dv(e.payloadSchema))){let t=cv(r);return{descriptor:r,binding:V(i),definition:e,kind:`generic`,status:`pending`,canResolve:!0,resumable:!0,...t===void 0?{}:{payload:V(t)},validationGeneration:0}}}let c=a||i!==void 0&&i.interruptId===r.id&&i.interruptedRunId===t.interruptedRunId&&i.generation===t.generation&&(i.kind!==`generic`||uv(r)===void 0||i.responseSchemaHash===uv(r));return{descriptor:r,binding:Sv(r,t,i),kind:`generic`,status:`pending`,canResolve:c,resumable:c,validationGeneration:0}}buildSnapshot(e){let t=this.requireHydration(),n=this.items.filter(e=>e.kind!==`client-tool-execution`&&e.status!==`submitting`).map(n=>{let r=Cv(n,t);if(n.kind===`unbound`||n.binding===void 0){let e={...r,kind:`unbound`,canResolve:!1};return Object.freeze(e)}if(n.kind===`tool-approval`&&n.binding.kind===`tool-approval`){let t=V(n.binding),i={...r,kind:`tool-approval`,binding:t,toolName:n.binding.toolName,toolCallId:n.binding.toolCallId,originalArgs:V(n.binding.originalArgs),cancel:()=>this.cancelItem(n.descriptor.id,e),clearResolution:()=>this.clearItem(n.descriptor.id,e),resolveInterrupt:(t,r)=>{let i=tv(r)?r:void 0;this.resolveItem(n.descriptor.id,{approved:t,...t&&i?.editedArgs!==void 0?{editedArgs:i.editedArgs}:{},...i?.payload===void 0?{}:{payload:i.payload}},e)}};return Object.freeze(i)}let i=n.binding.kind===`generic`?V(n.binding):V({v:1,kind:`generic`,interruptId:n.descriptor.id,interruptedRunId:t.interruptedRunId,generation:t.generation,...typeof n.binding.responseSchemaHash==`string`?{responseSchemaHash:n.binding.responseSchemaHash}:{}});if(n.definition!==void 0&&n.binding.kind===`generic`){let t={...r,kind:`generic`,definitionId:n.definition.id,key:n.binding.key??``,payload:n.payload,binding:i,cancel:()=>this.cancelItem(n.descriptor.id,e),clearResolution:()=>this.clearItem(n.descriptor.id,e),resolveInterrupt:t=>this.resolveItem(n.descriptor.id,t,e)};return Object.freeze(t)}let a={...r,kind:`generic`,binding:i,cancel:()=>this.cancelItem(n.descriptor.id,e),clearResolution:()=>this.clearItem(n.descriptor.id,e),resolveInterrupt:t=>this.resolveItem(n.descriptor.id,t,e)};return Object.freeze(a)});return Object.freeze(n)}publish(e=`live`){if(!this.hydration){this.snapshot=Object.freeze([]),this.state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:this.resuming}),this.options.onChange?.(e);return}this.snapshot=this.buildSnapshot(),this.state=Object.freeze({interrupts:this.snapshot,pendingInterrupts:this.snapshot,interruptErrors:this.rootErrors,resuming:this.resuming}),this.options.onChange?.(e)}resolveItem(e,t,n){this.assertItemMutable(n);let r=this.findItem(e);if(this.invalidateRetry(),!r.canResolve){r.status=`error`,r.error=this.itemError(e,`invalid-response-schema`,`The interrupt response schema is invalid and cannot be resolved.`),n||this.publish();return}let i=++r.validationGeneration,a=this.validateCandidate(r,t);if(fv(a)){r.status=`validating`,r.error=void 0,n||this.publish(),Promise.resolve(a).then(e=>{i===r.validationGeneration&&this.applyValidation(r,e,n)}).catch(e=>{i===r.validationGeneration&&this.applyValidation(r,{code:this.validationCode(r),message:e instanceof Error?e.message:String(e)},n)});return}this.applyValidation(r,a,n)}cancelItem(e,t){this.assertItemMutable(t);let n=this.findItem(e);this.invalidateRetry(),n.validationGeneration++,n.resolution=Object.freeze(Z_(n,{interruptId:e,status:`cancelled`})),n.status=`staged`,n.error=void 0,t||(this.publish(),this.maybeSubmit())}clearItem(e,t){this.assertItemMutable(t);let n=this.findItem(e);this.invalidateRetry(),n.validationGeneration++,n.resolution=void 0,n.error=void 0,n.status=`pending`,t||this.publish()}maybeSubmit(){let e=this.items.some(e=>e.kind===`generic`),t=this.items.filter(t=>X_(t)&&!(e&&t.kind===`client-tool-execution`));if(t.length===0||t.some(e=>e.resolution===void 0||e.status!==`staged`))return;let n=this.requireHydration(),r=ip(t.map(e=>e.resolution).filter(e=>e!==void 0)),i=Object.freeze({threadId:n.threadId,interruptedRunId:n.interruptedRunId,generation:n.generation,resolutions:r.resolutions,canonicalResolutions:r.canonicalResolutions,fingerprint:r.fingerprint});this.submitBatch(i)}applyValidation(e,t,n){if(!(`valid`in t)){e.status=`error`;let r=this.itemError(e.descriptor.id,t.code,t.message,t.path);e.error=r,e.kind===`client-tool-execution`&&(this.rootErrors=Object.freeze([...this.rootErrors.filter(t=>!(t.code===`item-validation-failed`&&t.interruptIds.includes(e.descriptor.id))),Object.freeze({scope:`batch`,code:`item-validation-failed`,message:r.message,source:`client`,retryable:!1,interruptIds:Object.freeze([e.descriptor.id]),threadId:r.threadId,interruptedRunId:r.interruptedRunId,generation:r.generation})])),n||this.publish();return}e.resolution=V(Z_(e,{interruptId:e.descriptor.id,status:`resolved`,payload:t.payload})),e.status=`staged`,e.error=void 0,n||(this.publish(),this.maybeSubmit())}validateCandidate(e,t){if(e.kind===`generic`){let n=pv(e.definition?.responseSchema??e.descriptor.responseSchema,t,`invalid-payload`);if(e.definition===void 0)return n;let r=e=>`valid`in e?{valid:!0,payload:t}:e;return fv(n)?Promise.resolve(n).then(r):r(n)}return e.kind===`client-tool-execution`?pv(e.tool?.outputSchema,t,`invalid-tool-output`):this.validateApprovalCandidate(e,t)}validateApprovalCandidate(e,t){if(!tv(t)||typeof t.approved!=`boolean`)return{code:`invalid-payload`,message:`Tool approval resolutions require an approved boolean.`};let n=t.approved,r=t.editedArgs;if(!n&&r!==void 0)return{code:`invalid-edited-args`,message:`Rejected tool approvals cannot edit tool arguments.`};if(n&&r!==void 0){let n=pv(e.tool?.inputSchema,r,`invalid-edited-args`);return fv(n)?Promise.resolve(n).then(n=>`valid`in n?this.validateApprovalPayload(e,t,n.payload):n):`valid`in n?this.validateApprovalPayload(e,t,n.payload):n}return this.validateApprovalPayload(e,t,void 0)}validateApprovalPayload(e,t,n){let r=t.approved===!0,i=this.approvalBranchSchema(e.tool,r),a=t.payload;if(i===void 0&&a!==void 0)return{code:`invalid-payload`,message:`This approval branch does not accept a payload.`};if(i!==void 0&&a===void 0)return{code:`invalid-payload`,message:`This approval branch requires a payload.`};let o=pv(i,a,`invalid-payload`),s=e=>`valid`in e?{valid:!0,payload:{approved:r,...n===void 0?{}:{editedArgs:n},...i===void 0?{}:{payload:e.payload}}}:e;return fv(o)?Promise.resolve(o).then(s):s(o)}approvalBranchSchema(e,t){let n=e?.approvalSchema;return!tv(n)||!(`approve`in n||`reject`in n)?n:t?n.approve:n.reject}validationCode(e){return e.kind===`client-tool-execution`?`invalid-tool-output`:`invalid-payload`}resolveBooleanBulk(e){let t=this.items.filter(e=>X_(e)&&e.kind!==`client-tool-execution`);if(!t.every(t=>t.kind===`tool-approval`&&this.approvalBranchSchema(t.tool,e)===void 0)||t.length===0){this.addRootError(`unsupported-bulk-operation`,`Boolean bulk resolution requires payloadless tool approvals.`,!1);return}this.invalidateRetry();for(let n of t)n.validationGeneration++,n.resolution=V({interruptId:n.descriptor.id,status:`resolved`,payload:{approved:e}}),n.status=`staged`,n.error=void 0;this.publish(),this.maybeSubmit()}resolveTransaction(e){let t=this.items.map(e=>({status:e.status,...e.resolution===void 0?{}:{resolution:e.resolution},...e.error===void 0?{}:{error:e.error},validationGeneration:e.validationGeneration})),n={active:!0};this.activeTransaction=n;let r=this.buildSnapshot(n).filter(Q_),i;try{for(let t of r){let n=e(t);if(n!==void 0){i={code:fv(n)?`async-resolver`:`inactive-transaction`,message:fv(n)?`Interrupt transaction resolvers must be synchronous.`:`Interrupt transaction resolvers must return literal undefined.`};break}}i===void 0&&this.items.some(e=>X_(e)&&e.kind!==`client-tool-execution`&&(e.resolution===void 0||e.status!==`staged`))&&(i={code:`incomplete-batch`,message:`Interrupt transaction did not resolve every item.`})}catch(e){i={code:`item-validation-failed`,message:e instanceof Error?e.message:String(e)}}finally{n.active=!1,this.activeTransaction=void 0}if(i){this.restoreCheckpoints(t),this.addRootError(i.code,i.message,!1);return}this.publish(),this.maybeSubmit()}restoreCheckpoints(e){this.items.forEach((t,n)=>{let r=e[n];r&&(t.status=r.status,t.resolution=r.resolution,t.error=r.error,t.validationGeneration=r.validationGeneration+1)}),this.publish()}assertItemMutable(e){if(e&&!e.active||this.activeTransaction&&e!==this.activeTransaction)throw Error(`Interrupt transaction is inactive.`);if(this.resuming)throw Error(`Interrupts cannot be mutated while submitting.`)}assertRootMutable(){if(this.activeTransaction)throw Error(`Interrupt transaction is already active.`);if(this.resuming)throw Error(`Interrupts cannot be mutated while submitting.`)}invalidateRetry(){this.retrySubmission=void 0}submitBatch(e){this.resuming=!0,this.retrySubmission=void 0;for(let e of this.items)X_(e)&&(e.status=`submitting`);this.publish(),this.performSubmission(e)}async performSubmission(e){try{await this.options.submit(e)}catch(t){this.handleSubmissionFailure(t,e)}finally{this.resuming=!1,this.publish()}}handleSubmissionFailure(e,t){let n=_v(e);if(n.length===0){let n=e instanceof Error?e.message:String(e);this.addRootError(`transport`,n,!0,`transport`),this.retrySubmission=t;for(let e of this.items)X_(e)&&(e.status=`error`);return}let r=n.filter(e=>xv(e,t));r.length!==n.length&&this.addRootError(`protocol`,`Interrupt submission errors did not match the active batch.`,!1);let i=!1,a=!1,o=[];for(let e of r)if((e.code===`stale`||e.code===`expired`||e.code===`conflict`)&&(i=!0),a||=e.retryable,e.scope===`item`){let t=this.items.find(t=>X_(t)&&t.descriptor.id===e.interruptId);t&&(t.status=`error`,t.error=V(e))}else o.push(V(e));let s=bv(this.rootErrors,this.submissionRootErrors,o);this.rootErrors=s.rootErrors,this.submissionRootErrors=s.submissionRootErrors;for(let e of this.items)X_(e)&&e.status===`submitting`&&(e.status=`error`);this.retrySubmission=a&&!i?t:void 0}addRootError(e,t,n,r=`client`){let i=this.requireHydration();this.rootErrors=Object.freeze([...this.rootErrors,Object.freeze({scope:`batch`,code:e,message:t,source:r,retryable:n,interruptIds:Object.freeze(this.items.filter(X_).map(e=>e.descriptor.id)),threadId:i.threadId,interruptedRunId:i.interruptedRunId,generation:i.generation})]),this.publish()}findItem(e){let t=this.items.find(t=>t.descriptor.id===e);if(!t)throw Error(`Unknown interrupt: ${e}`);return t}requireHydration(){if(!this.hydration)throw Error(`InterruptManager is not hydrated.`);return this.hydration}itemError(e,t,n,r){let i=this.requireHydration();return Object.freeze({scope:`item`,interruptId:e,code:t,message:n,...r===void 0?{}:{path:Object.freeze([...r])},source:`client`,retryable:!1,threadId:i.threadId,interruptedRunId:i.interruptedRunId,generation:i.generation})}},Tv=class{clientId;constructor(e){this.clientId=e}clientCreated(e){this.emitEvent(`client:created`,{initialMessageCount:e})}loadingChanged(e){this.emitEvent(`client:loading:changed`,{isLoading:e})}errorChanged(e){this.emitEvent(`client:error:changed`,{error:e})}textUpdated(e,t,n,r){this.emitEvent(`text:chunk:content`,{streamId:e,messageId:t,content:n,...r})}toolCallStateChanged(e,t,n,r,i,a,o){this.emitEvent(`tools:call:updated`,{streamId:e,messageId:t,toolCallId:n,toolName:r,state:i,arguments:a,...o})}thinkingUpdated(e,t,n,r,i){this.emitEvent(`text:chunk:thinking`,{streamId:e,messageId:t,content:n,delta:r,...i})}structuredOutputChanged(e,t,n,r,i){this.emitEvent(e,{streamId:t,messageId:n,...r,...i})}approvalRequested(e,t,n,r,i,a,o){this.emitEvent(`tools:approval:requested`,{streamId:e,messageId:t,toolCallId:n,toolName:r,input:i,approvalId:a,...o})}messageAppended(e,t,n){let r=e.parts.filter(e=>e.type===`text`).map(e=>e.content).join(` `);this.emitEvent(`text:message:created`,{streamId:t,messageId:e.id,role:e.role,content:r,parts:e.parts,...n})}messageSent(e,t){let n=typeof t==`string`?t:t.filter(e=>e.type===`text`).map(e=>e.content).join(``);this.emitEvent(`text:message:created`,{messageId:e,role:`user`,content:n,...Array.isArray(t)&&{parts:t}}),this.emitEvent(`text:message:user`,{messageId:e,role:`user`,content:n,...Array.isArray(t)&&{parts:t}})}reloaded(e){this.emitEvent(`client:reloaded`,{fromMessageIndex:e})}stopped(){this.emitEvent(`client:stopped`)}messagesCleared(){this.emitEvent(`client:messages:cleared`)}toolResultAdded(e,t,n,r,i){this.emitEvent(`tools:result:added`,{toolCallId:e,toolName:t,output:n,state:r,...i})}toolApprovalResponded(e,t,n,r){this.emitEvent(`tools:approval:responded`,{approvalId:e,toolCallId:t,approved:n,...r})}toolFixtureApplied(e){this.emitEvent(`devtools:tool-fixture:applied`,{...e})}},Ev=class extends Tv{emitEvent(){}},Dv=class{events;constructor(e){this.events=new Ev(e.clientId)}emitRegistered(){}emitUpdated(){}emitSnapshot(){}emitToolsRegistered(){}emitRunLifecycle(e,t,n,r){}deactivate(){}supersede(){}dispose(){}mountWithTools(e){}notifyToolsChanged(){}setCurrentStreamId(e){}recordStreamId(e){}getCurrentStreamId(){return null}getLastStreamId(){return null}resolveStreamId(){return``}observeChunk(e){}recordMemoryState(e){}beginRun(e,t){}getCurrentRunEventContext(){}getCurrentOrLastRunEventContext(){}findToolCallContext(e){return{toolCallId:e}}async applyFixture(e){}},Ov=e=>new Dv(e);function kv(e){if(Array.isArray(e))return{messages:e};if(e&&Array.isArray(e.messages))return e}function Av(e){return`toolCallId`in e&&typeof e.toolCallId==`string`?e.toolCallId:void 0}function jv(e){return`messageId`in e&&typeof e.messageId==`string`?e.messageId:void 0}function Mv(e){return`parentMessageId`in e&&typeof e.parentMessageId==`string`?e.parentMessageId:void 0}var Nv=class{adapter;id;applyMessages;applyResume;skipNextPersist=!1;generation=0;queue=Promise.resolve();queuePending=!1;messagesGeneration=0;lastMessages=[];lastResume=null;clearedMessageIds=new Set;clearedRunIds=new Set;ignoredActiveRunIds=new Set;clearedToolCallIds=new Set;currentRunlessRunId=null;constructor(e,t,n,r){this.adapter=e,this.id=t,this.applyMessages=n,this.applyResume=r}writeState(){let e=[...this.lastMessages];if(e.length===0&&!this.lastResume){let e=this.generation;this.runOperation(()=>{if(e===this.generation)return this.adapter.removeItem(this.id)});return}let t=this.generation,n={messages:e,...this.lastResume?{resume:this.lastResume}:{}};this.runOperation(()=>{if(t===this.generation)return this.adapter.setItem(this.id,n)})}readInitial(){try{let e=this.adapter.getItem(this.id);if(e instanceof Promise)return e.then(kv).catch(()=>void 0);let t=kv(e);return t&&(this.lastMessages=t.messages,this.lastResume=t.resume??null),t}catch{return}}hydrateAsync(e){if(!(e instanceof Promise))return;let t=this.messagesGeneration;e.then(e=>{!e||this.messagesGeneration!==t||(this.lastResume=e.resume??null,this.lastMessages=e.messages,this.applyMessages(e.messages),e.resume&&this.applyResume&&this.applyResume(e.resume))}).catch(()=>{})}notifyMessagesChanged(e){if(this.messagesGeneration++,this.lastMessages=[...e],this.skipNextPersist){this.skipNextPersist=!1;return}this.writeState()}persistResumeSnapshot(e){this.lastResume=e,!this.skipNextPersist&&this.writeState()}remove(){this.lastMessages=[],this.lastResume=null;let e=++this.generation;this.runOperation(()=>{if(e===this.generation)return this.adapter.removeItem(this.id)})}runOperation(e){if(this.queuePending){let t=this.queue.then(e).catch(()=>{});this.queue=t,t.finally(()=>{this.queue===t&&(this.queuePending=!1)});return}try{let t=e();if(t instanceof Promise){this.queuePending=!0;let e=t.catch(()=>{});this.queue=e,e.finally(()=>{this.queue===e&&(this.queuePending=!1)})}}catch{}}snapshotClear(e){for(let t of e.messages)this.clearedMessageIds.add(t.id);for(let t of e.activeRunIds)this.clearedRunIds.add(t),this.ignoredActiveRunIds.add(t);e.currentRunId&&(this.clearedRunIds.add(e.currentRunId),this.ignoredActiveRunIds.add(e.currentRunId))}beginClear(){this.skipNextPersist=!0}shouldIgnoreChunk(e){let t=S_(e);if(t&&this.clearedRunIds.has(t))return e.type===`RUN_STARTED`&&(this.ignoredActiveRunIds.add(t),this.currentRunlessRunId=t),this.markIgnoredChunkIds(e),!0;if(t&&this.ignoredActiveRunIds.has(t)||this.isRunlessChunkFromIgnoredRun(e))return this.markIgnoredChunkIds(e),!0;let n=Av(e);if(n&&this.clearedToolCallIds.has(n))return!0;let r=Mv(e);if(r&&this.clearedMessageIds.has(r))return n&&this.clearedToolCallIds.add(n),!0;let i=jv(e);return i?!!this.clearedMessageIds.has(i):!1}onRunStarted(e){this.currentRunlessRunId=e}onRunSettled(e){this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId===e&&(this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null)}onSessionRunError(){this.ignoredActiveRunIds.clear(),this.currentRunlessRunId=null}resetIgnored(){this.ignoredActiveRunIds.clear()}takeRunlessRunId(){let e=this.currentRunlessRunId;return e?(this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null,e):null}markIgnoredChunkIds(e){let t=jv(e);t&&this.clearedMessageIds.add(t);let n=Av(e);n&&this.clearedToolCallIds.add(n)}isRunlessChunkFromIgnoredRun(e){return S_(e)||!this.currentRunlessRunId||!this.ignoredActiveRunIds.has(this.currentRunlessRunId)&&!this.clearedRunIds.has(this.currentRunlessRunId)?!1:e.type===`TEXT_MESSAGE_START`||e.type===`TEXT_MESSAGE_CONTENT`||e.type===`TOOL_CALL_START`||e.type===`TOOL_CALL_ARGS`||e.type===`TOOL_CALL_END`||e.type===`TOOL_CALL_RESULT`||e.type===`MESSAGES_SNAPSHOT`||e.type===`RUN_ERROR`}};function Pv(e){return`toolCallId`in e&&typeof e.toolCallId==`string`?e.toolCallId:void 0}function Fv(e){return`messageId`in e&&typeof e.messageId==`string`?e.messageId:void 0}function Iv(e){return`parentMessageId`in e&&typeof e.parentMessageId==`string`?e.parentMessageId:void 0}var Lv=class{clearedMessageIds=new Set;clearedRunIds=new Set;ignoredActiveRunIds=new Set;clearedToolCallIds=new Set;currentRunlessRunId=null;snapshotClear(e){for(let t of e.messages)this.clearedMessageIds.add(t.id);for(let t of e.activeRunIds)this.clearedRunIds.add(t),this.ignoredActiveRunIds.add(t);e.currentRunId&&(this.clearedRunIds.add(e.currentRunId),this.ignoredActiveRunIds.add(e.currentRunId))}shouldIgnoreChunk(e){let t=S_(e);if(t&&this.clearedRunIds.has(t))return e.type===`RUN_STARTED`&&(this.ignoredActiveRunIds.add(t),this.currentRunlessRunId=t),this.markIgnoredChunkIds(e),!0;if(t&&this.ignoredActiveRunIds.has(t)||this.isRunlessChunkFromIgnoredRun(e))return this.markIgnoredChunkIds(e),!0;let n=Pv(e);if(n&&this.clearedToolCallIds.has(n))return!0;let r=Iv(e);if(r&&this.clearedMessageIds.has(r))return n&&this.clearedToolCallIds.add(n),!0;let i=Fv(e);return!!(i&&this.clearedMessageIds.has(i))}onRunStarted(e){this.currentRunlessRunId=e}onRunSettled(e){this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId===e&&(this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null)}onSessionRunError(){this.ignoredActiveRunIds.clear(),this.currentRunlessRunId=null}resetActiveRuns(){this.ignoredActiveRunIds.clear(),this.currentRunlessRunId=null}takeRunlessRunId(){let e=this.currentRunlessRunId;return e?(this.ignoredActiveRunIds.delete(e),this.clearedRunIds.delete(e),this.currentRunlessRunId=this.ignoredActiveRunIds.values().next().value??null,e):null}markIgnoredChunkIds(e){let t=Fv(e);t&&this.clearedMessageIds.add(t);let n=Pv(e);n&&this.clearedToolCallIds.add(n)}isRunlessChunkFromIgnoredRun(e){return S_(e)||!this.currentRunlessRunId||!this.ignoredActiveRunIds.has(this.currentRunlessRunId)&&!this.clearedRunIds.has(this.currentRunlessRunId)?!1:e.type===`TEXT_MESSAGE_START`||e.type===`TEXT_MESSAGE_CONTENT`||e.type===`TOOL_CALL_START`||e.type===`TOOL_CALL_ARGS`||e.type===`TOOL_CALL_END`||e.type===`TOOL_CALL_RESULT`||e.type===`MESSAGES_SNAPSHOT`||e.type===`RUN_ERROR`}};function Rv(e){let t=new Set;for(let n of e??[]){if(t.has(n.id))throw Error(`Duplicate interrupt definition id: ${n.id}`);t.add(n.id)}}function zv(e){let{connection:t,fetcher:n}=e;if(t&&n)throw Error("ChatClient: pass either `connection` or `fetcher`, not both.");if(t)return t;if(n)return J_(n);throw Error("ChatClient: either `connection` or `fetcher` is required.")}function Bv(e){let t={whenBusy:`queue`,drain:`fifo`,onOverflow:`reject`};if(!e)return t;if(typeof e==`string`)return{...t,whenBusy:e};if(typeof e==`function`)return{...t,strategy:e};let n=e.maxSize;if(n!==void 0&&(!Number.isInteger(n)||n<0))throw Error(`ChatClient: queue.maxSize must be a non-negative integer`);return{whenBusy:e.whenBusy??`queue`,drain:e.drain??`fifo`,onOverflow:e.onOverflow??`reject`,...n===void 0?{}:{maxSize:n}}}function Vv(e){let t=e.at(-1)?.body,n=[];for(let t of e){if(typeof t.content!=`string`)break;n.push(t.content)}if(n.length===e.length)return{content:n.join(`
27
+ `),...t===void 0?{}:{body:t}};let r=[];for(let t of e)typeof t.content==`string`?r.push({type:`text`,content:t.content}):typeof t.content.content==`string`?r.push({type:`text`,content:t.content.content}):r.push(...t.content.content);return{content:{content:r},...t===void 0?{}:{body:t}}}function Hv(e){if(!(typeof e!=`object`||!e||Array.isArray(e))&&!(!(`approved`in e)||typeof e.approved!=`boolean`))return e.approved}function Uv(e){let t=e;if(typeof t!=`object`||!t||!(`resumeState`in t))return;let n=t.resumeState;if(!(typeof n!=`object`||!n||!(`threadId`in n)||typeof n.threadId!=`string`||n.threadId.length===0||!(`runId`in n)||typeof n.runId!=`string`||n.runId.length===0))return{threadId:n.threadId,runId:n.runId}}var Wv=2e3,Gv=new Set([`TEXT_MESSAGE_START`,`TEXT_MESSAGE_CONTENT`,`TOOL_CALL_START`,`MESSAGES_SNAPSHOT`]),Kv=class{processor;connection;uniqueId;threadId;persistor;clearedStreamTracker=new Lv;currentRunId=null;lastResume=null;rejoinedRunId=null;interruptManager;activeInterruptSubmission;interruptSubmissionFailure;joinedRunWaiters=new Map;pendingResumeParentRunId=null;pendingResumeThreadId=null;pendingResumeItems=null;activeResumeThreadId=null;activeResumeRunId=null;bodyOption={};forwardedPropsOption={};context=void 0;pendingMessageBody=void 0;queueConfig;messageQueue=[];sendInFlight=!1;messageQueueDraining=!1;stopMessageQueueDrain=!1;deliverClaim=!1;isLoading=!1;isSubscribed=!1;error=void 0;status=`ready`;connectionStatus=`disconnected`;abortController=null;clientToolsRef;devtoolsBridge;events;currentStreamId=null;currentMessageId=null;postStreamActions=[];pendingToolExecutions=new Map;activeClientTools=null;activeContext=void 0;continuationPending=!1;subscriptionAbortController=null;processingResolve=null;errorReportedGeneration=null;streamGeneration=0;continuationSkipped=!1;draining=!1;sessionGenerating=!1;activeRunIds=new Set;disposed=!1;tailing=!1;rejoinRunId;cachesMessages;devtoolsMounted=!1;callbacksRef;constructor(e){Rv(e.interrupts),this.threadId=e.threadId||``,this.uniqueId=this.threadId;let t=!0;if(e.persistence===!0){if(!e.threadId)throw Error("[TanStack AI] persistence needs a stable `threadId` to key on. Pass a threadId from your app (for example support-42).");t=!1}else if(e.persistence){if(!e.threadId)throw Error("[TanStack AI] persistence needs a stable `threadId` to key on. Pass a threadId from your app (for example support-42).");this.persistor=new Nv(e.persistence,e.threadId,e=>this.processor.setMessages(e),e=>this.applyPersistedResume(e))}if(this.bodyOption=e.body||{},this.forwardedPropsOption=e.forwardedProps||{},this.context=e.context,this.queueConfig=Bv(e.queue),this.connection=G_(zv(e)),this.clientToolsRef={current:new Map},e.tools)for(let t of e.tools)this.clientToolsRef.current.set(t.name,t);this.devtoolsBridge=(e.devtoolsBridgeFactory??Ov)(this.buildDevtoolsBridgeOptions(e.devtools)),this.events=this.devtoolsBridge.events,this.callbacksRef={current:{onResponse:e.onResponse||(()=>{}),onChunk:e.onChunk||(()=>{}),onFinish:e.onFinish||(()=>{}),onError:e.onError||(()=>{}),onMessagesChange:e.onMessagesChange||(()=>{}),onLoadingChange:e.onLoadingChange||(()=>{}),onErrorChange:e.onErrorChange||(()=>{}),onStatusChange:e.onStatusChange||(()=>{}),onSubscriptionChange:e.onSubscriptionChange||(()=>{}),onConnectionStatusChange:e.onConnectionStatusChange||(()=>{}),onSessionGeneratingChange:e.onSessionGeneratingChange||(()=>{}),onQueueChange:e.onQueueChange||(()=>{}),onResumeStateChange:e.onResumeStateChange||(()=>{}),onRunIdChange:e.onRunIdChange||(()=>{}),onInterruptStateChange:e.onInterruptStateChange||(()=>{}),onCustomEvent:e.onCustomEvent||(()=>{})}},this.interruptManager=new wv({...e.tools===void 0?{}:{tools:e.tools},...e.interrupts===void 0?{}:{interrupts:e.interrupts},submit:e=>this.submitInterruptBatch(e),onChange:e=>this.notifyResumeStateChange(e)}),e.initialResumeSnapshot&&this.applyResumeSnapshot(e.initialResumeSnapshot);let n=this.persistor?.readInitial(),r=n instanceof Promise?void 0:n,i=r?r.messages:e.initialMessages,a=null;if(r?.resume){let e=r.resume;Array.isArray(e.pendingInterrupts)&&e.pendingInterrupts.length>0?this.applyResumeSnapshot(e):e.resumeState.runId&&(a=e.resumeState.runId)}if(!a&&e.initialResumeSnapshot){let t=e.initialResumeSnapshot;!(Array.isArray(t.pendingInterrupts)&&t.pendingInterrupts.length>0)&&t.resumeState.runId&&(a=t.resumeState.runId)}this.processor=new wm({...e.streamProcessor?.chunkStrategy?{chunkStrategy:e.streamProcessor.chunkStrategy}:{},...i?{initialMessages:i}:{},events:{onMessagesChange:e=>{this.persistor?.notifyMessagesChanged(e),this.callbacksRef.current.onMessagesChange(e)},onStreamStart:()=>{this.setStatus(`streaming`);let e=this.processor.getCurrentAssistantMessageId();if(!e)return;let t=this.processor.getMessages().find(t=>t.id===e);t&&(this.currentMessageId=t.id,this.events.messageAppended(t,this.currentStreamId||void 0))},onStreamEnd:e=>{this.callbacksRef.current.onFinish(e),this.setStatus(`ready`),this.resolveProcessing()},onError:e=>{this.reportStreamError(e)},onTextUpdate:(e,t)=>{this.currentStreamId&&this.events.textUpdated(this.currentStreamId,e,t)},onThinkingUpdate:(e,t)=>{this.currentStreamId&&this.events.thinkingUpdated(this.currentStreamId,e,t,void 0)},onStructuredOutputChange:e=>{let t=this.devtoolsBridge.resolveStreamId(),n=e.phase===`start`?`structured-output:started`:e.phase===`complete`?`structured-output:completed`:e.phase===`error`?`structured-output:errored`:`structured-output:updated`;this.currentMessageId=e.messageId,this.events.structuredOutputChanged(n,t,e.messageId,{status:e.status,raw:e.raw,...e.partial===void 0?{}:{partial:e.partial},...e.data===void 0?{}:{data:e.data},...e.reasoning===void 0?{}:{reasoning:e.reasoning},...e.errorMessage===void 0?{}:{errorMessage:e.errorMessage},...e.delta===void 0?{}:{delta:e.delta}})},onToolCallStateChange:(e,t,n,r)=>{let i=this.processor.getMessages().find(t=>t.id===e)?.parts.find(e=>e.type===`tool-call`&&e.id===t)?.name||`unknown`;this.currentStreamId&&this.events.toolCallStateChanged(this.currentStreamId,e,t,i,n,r)},onToolCall:e=>{let t=(this.activeClientTools??this.clientToolsRef.current).get(e.toolName),n=t?.execute;if(n){let r=this.devtoolsBridge.getCurrentRunEventContext(),i=(async()=>{try{let i=this.activeClientTools===null?this.context:this.activeContext,a=await n(e.input,{toolCallId:e.toolCallId,context:i,emitCustomEvent:()=>{}});await this.addToolResultForClientTool({toolCallId:e.toolCallId,tool:e.toolName,output:a,state:`output-available`},t,r)}catch(n){await this.addToolResultForClientTool({toolCallId:e.toolCallId,tool:e.toolName,output:null,state:`output-error`,errorText:n.message},t,r)}finally{this.pendingToolExecutions.delete(e.toolCallId)}})();this.pendingToolExecutions.set(e.toolCallId,i)}},onApprovalRequest:e=>{let t=this.devtoolsBridge.resolveStreamId(),n=this.findMessageIdForToolCall(e.toolCallId)??this.currentMessageId??``;this.events.approvalRequested(t,n,e.toolCallId,e.toolName,e.input,e.approvalId)},onCustomEvent:(e,t,n)=>{e===`memory:state`&&this.devtoolsBridge.recordMemoryState(t),this.callbacksRef.current.onCustomEvent(e,t,n)}}}),this.persistor?.hydrateAsync(n),this.rejoinRunId=a,this.cachesMessages=t}attach(){this.disposed||this.tailing||(this.ensureThreadId(),this.tailing=!0,this.rejoinRunId&&this.maybeRejoinInFlight(this.rejoinRunId),!this.cachesMessages&&this.connection.hydrate&&this.hydrateFromServer())}detach(){this.tailing&&(this.tailing=!1,this.cancelInFlightStream({setReadyStatus:!0}),this.rejoinedRunId=null)}applyResumeSnapshot(e){let t=Uv(e);if(t===void 0){this.interruptManager.reset({source:`hydrate`});return}this.lastResume=t;let n=Array.isArray(e.pendingInterrupts)?e.pendingInterrupts:[];if(n.length===0){this.interruptManager.reset({source:`hydrate`});return}let r=this.interruptGeneration(n);this.interruptManager.hydrate({threadId:t.threadId,interruptedRunId:t.runId,generation:r,interrupts:n},`hydrate`)}applyPersistedResume(e){this.applyResumeSnapshot(e);let t=Array.isArray(e.pendingInterrupts)&&e.pendingInterrupts.length>0,n=e.resumeState?.runId;!t&&n&&this.maybeRejoinInFlight(n)}maybeRejoinInFlight(e){this.connection.joinRun&&(this.disposed||!this.tailing||this.rejoinedRunId!==e&&(this.isLoading||this.abortController||(this.rejoinedRunId=e,this.resumeInFlightRun(e))))}hydrateFromServer(){let e=this.connection.hydrate;e&&(this.isLoading||this.abortController||this.disposed||(async()=>{let t;try{t=await e(this.threadId)}catch{return}this.disposed||!this.tailing||this.isLoading||this.abortController||(t.messages.length>0&&this.processor.setMessages(t.messages),t.interrupts&&t.interrupts.pending.length>0?this.applyResumeSnapshot({resumeState:{threadId:this.threadId,runId:t.interrupts.runId},pendingInterrupts:t.interrupts.pending}):t.activeRun?.runId&&this.maybeRejoinInFlight(t.activeRun.runId))})())}mountDevtools(){this.ensureThreadId(),!this.devtoolsMounted&&(this.devtoolsMounted=!0,this.devtoolsBridge.mountWithTools(this.processor.getMessages().length))}ensureThreadId(){return this.threadId||=this.generateUniqueId(`thread`),this.uniqueId=this.threadId,this.threadId}drainIgnoredRunlessChunk(e){if(e.type!==`RUN_ERROR`)return;let t=this.clearedStreamTracker.takeRunlessRunId();t&&(this.activeRunIds.delete(t),this.setSessionGenerating(this.activeRunIds.size>0),this.resolveProcessing())}retireIgnoredClearedTerminalChunk(e){if(e.type!==`RUN_FINISHED`&&e.type!==`RUN_ERROR`)return;let t=S_(e)??this.clearedStreamTracker.takeRunlessRunId();t&&(this.activeRunIds.delete(t),this.setSessionGenerating(this.activeRunIds.size>0),S_(e)||this.resolveProcessing())}updateRunLifecycle(e,t){if(e.type===`RUN_STARTED`){let t=S_(e)??e.runId;this.activeResumeThreadId=`threadId`in e&&typeof e.threadId==`string`?e.threadId:this.activeResumeThreadId,this.activeResumeRunId=t,this.activeRunIds.add(t),this.clearedStreamTracker.onRunStarted(t),this.setSessionGenerating(!0),this.persistor&&this.connection.joinRun&&!this.lastResume&&this.persistResumeSnapshot({threadId:this.activeResumeThreadId??this.threadId,runId:t});return}if(e.type!==`RUN_FINISHED`&&e.type!==`RUN_ERROR`)return;let n=S_(e);n?(this.activeRunIds.delete(n),this.clearedStreamTracker.onRunSettled(n)):e.type===`RUN_ERROR`&&(this.activeRunIds.clear(),this.clearedStreamTracker.onSessionRunError()),this.setSessionGenerating(this.activeRunIds.size>0),t?.resolveProcessing!==!1&&this.resolveProcessing()}observeInterruptState(e){if(e.type!==`RUN_FINISHED`&&e.type!==`RUN_ERROR`||this.activeInterruptSubmission&&e.type===`RUN_ERROR`)return;let t=S_(e),n=`threadId`in e&&typeof e.threadId==`string`?e.threadId:this.activeResumeThreadId;if(e.type===`RUN_FINISHED`&&e.outcome?.type===`interrupt`){let r=this.currentRunId??t??this.activeResumeRunId??``;this.lastResume={threadId:n??this.threadId,runId:r},this.interruptManager.hydrate({threadId:this.lastResume.threadId,interruptedRunId:r,generation:this.interruptGeneration(e.outcome.interrupts),interrupts:e.outcome.interrupts},`live`);return}let r=e.type===`RUN_ERROR`&&!t,i=!!(t&&this.lastResume?.runId===t),a=!!(t&&this.currentRunId===t||this.currentRunId&&this.lastResume?.runId===this.currentRunId),o=!!(this.isLoading&&t&&(t===this.activeResumeRunId||t===this.currentRunId)),s=this.isLoading&&e.type===`RUN_FINISHED`&&!t,c=!!(this.activeInterruptSubmission&&this.isLoading&&e.type===`RUN_FINISHED`&&e.outcome?.type!==`interrupt`);if(r||i||a||o||s||c){this.lastResume=null,this.persistor?.persistResumeSnapshot(null),this.interruptManager.reset();return}this.notifyResumeStateChange(`live`)}getResumeState(){return this.lastResume?{...this.lastResume}:null}getCurrentRunId(){return this.currentRunId}setCurrentRunId(e){this.currentRunId!==e&&(this.currentRunId=e,this.callbacksRef.current.onRunIdChange(e))}getInterruptState(){return this.interruptManager.getState()}getInterrupts(){return this.interruptManager.getInterrupts()}getPendingInterrupts(){return this.interruptManager.getInterrupts()}resolveInterrupts(e){if(typeof e==`boolean`){this.interruptManager.resolve(e);return}this.interruptManager.resolve(e)}cancelInterrupts(){this.interruptManager.cancel()}retryInterrupts(){this.interruptManager.retry()}resumeInterruptsUnsafe(e,t){let n=t??this.lastResume;return n?this.isLoading?new Promise((t,r)=>{this.queuePostStreamAction(async()=>{try{t(await this.resumeInterruptsUnsafe(e,n))}catch(e){r(e)}})}):(this.pendingResumeThreadId=n.threadId,this.pendingResumeParentRunId=n.runId,this.pendingResumeItems=[...e],this.streamResponse()):Promise.resolve(!1)}resumeInterrupts(e,t){return this.resumeInterruptsUnsafe(e,t)}async submitInterruptBatch(e){this.activeInterruptSubmission=e,this.interruptSubmissionFailure=void 0;for(let t of e.resolutions){let e=Hv(t.payload);if(e===void 0)continue;let n=t.interruptId;this.processor.addToolApprovalResponse(n,e)}let t=await this.resumeInterruptsUnsafe([...e.resolutions],{threadId:e.threadId,runId:e.interruptedRunId}).finally(()=>{this.activeInterruptSubmission=void 0}),n=this.takeInterruptSubmissionFailure();if(n!==void 0)throw{errors:n.errors};if(!t)throw Error(`Interrupt continuation could not be started.`);this.lastResume?.runId===e.interruptedRunId&&(this.lastResume=null,this.interruptManager.reset())}takeInterruptSubmissionFailure(){let e=this.interruptSubmissionFailure;return this.interruptSubmissionFailure=void 0,e}interruptGeneration(e){let t;for(let n of e){let e=n.metadata?.[`tanstack:interruptBinding`];if(typeof e!=`object`||!e||!(`generation`in e)||typeof e.generation!=`number`||!Number.isInteger(e.generation)||e.generation<0||t!==void 0&&t!==e.generation)return 0;t=e.generation}return t??0}generateUniqueId(e){return`${e}-${Date.now()}-${Math.random().toString(36).substring(7)}`}setIsLoading(e){this.isLoading=e,this.callbacksRef.current.onLoadingChange(e),this.events.loadingChanged(e)}setStatus(e){this.status=e,this.callbacksRef.current.onStatusChange(e),this.devtoolsBridge.emitSnapshot()}setIsSubscribed(e){this.isSubscribed=e,this.callbacksRef.current.onSubscriptionChange(e),this.devtoolsBridge.emitSnapshot()}setConnectionStatus(e){this.connectionStatus=e,this.callbacksRef.current.onConnectionStatusChange(e),this.devtoolsBridge.emitSnapshot()}setSessionGenerating(e){this.sessionGenerating!==e&&(this.sessionGenerating=e,this.callbacksRef.current.onSessionGeneratingChange(e),this.devtoolsBridge.emitSnapshot())}notifyResumeStateChange(e){let t=this.getResumeState(),n=this.interruptManager.getState();this.persistResumeSnapshot(t),this.callbacksRef.current.onResumeStateChange(t,n.interrupts),this.callbacksRef.current.onInterruptStateChange(n,{source:e})}persistResumeSnapshot(e){if(!this.persistor)return;if(!e){this.persistor.persistResumeSnapshot(null);return}let t=this.interruptManager.getDescriptors();this.persistor.persistResumeSnapshot({resumeState:e,...t.length>0?{pendingInterrupts:[...t]}:{}})}resetSessionGenerating(e){this.activeRunIds.clear(),e?.preserveClearedStreamTracking||this.clearedStreamTracker.resetActiveRuns(),this.setSessionGenerating(!1)}setError(e){this.error=e,this.callbacksRef.current.onErrorChange(e),this.events.errorChanged(e?.message||null)}buildDevtoolsBridgeOptions(e){let t=this;return{get hookId(){return t.uniqueId},get clientId(){return t.uniqueId},get threadId(){return t.threadId},metadata:{hookName:e?.hookName??`useChat`,outputKind:e?.outputKind??`chat`,...e?.framework?{framework:e.framework}:{},...e?.name?{name:e.name}:{}},getSnapshot:()=>this.getDevtoolsSnapshot(),getTools:()=>this.clientToolsRef.current.values(),getMessages:()=>this.processor.getMessages(),setMessages:e=>{this.processor.setMessages(e)},addToolResult:(e,t,n)=>{this.processor.addToolResult(e,t,n)},generateId:e=>this.generateUniqueId(e)}}getDevtoolsSnapshot(){return{messages:this.processor.getMessages(),status:this.status,isLoading:this.isLoading,isSubscribed:this.isSubscribed,connectionStatus:this.connectionStatus,sessionGenerating:this.sessionGenerating,activeRunIds:Array.from(this.activeRunIds),queue:this.getQueue(),...this.error?{error:this.error.message}:{}}}findMessageIdForToolCall(e){let t=this.processor.getMessages();for(let n of t)if(n.parts.find(t=>t.type===`tool-call`&&t.id===e))return n.id}abortSubscriptionLoop(){this.subscriptionAbortController?.abort(),this.subscriptionAbortController=null}resolveProcessing(){this.processingResolve?.(),this.processingResolve=null}cancelInFlightStream(e){this.abortController?.abort(),this.abortController=null,e?.abortSubscription&&this.abortSubscriptionLoop(),this.resolveProcessing(),this.setIsLoading(!1),this.deliverClaim=!1,e?.setReadyStatus&&this.setStatus(`ready`)}reportStreamError(e){let t=this.errorReportedGeneration===this.streamGeneration;this.setError(e),(this.isLoading||this.status===`submitted`||this.status===`streaming`)&&this.setStatus(`error`),t||(this.errorReportedGeneration=this.streamGeneration,this.callbacksRef.current.onError(e))}startSubscription(){this.subscriptionAbortController=new AbortController;let e=this.subscriptionAbortController.signal;this.consumeSubscription(e).catch(e=>{e instanceof Error&&e.name!==`AbortError`&&(this.setConnectionStatus(`error`),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.reportStreamError(e)),this.resolveProcessing()}).finally(()=>{this.subscriptionAbortController?.signal===e&&(this.subscriptionAbortController=null,!e.aborted&&this.isSubscribed&&(this.setIsSubscribed(!1),this.connectionStatus!==`error`&&this.setConnectionStatus(`disconnected`)))})}async consumeSubscription(e){let t=this.connection.subscribe(e);for await(let n of t){if(e.aborted)break;await this.processIncomingChunk(n)}}resumeInFlightRun(e){let t=this.connection.joinRun;if(!t)return;let n=new AbortController;this.abortController=n,this.setCurrentRunId(e),this.lastResume={threadId:this.threadId,runId:e},this.setIsLoading(!0),this.setStatus(`streaming`),(async()=>{let r=!1,i=!1,a=!1,o=setTimeout(()=>{i||n.abort()},Wv);try{for await(let a of t(e,n.signal)){if(n.signal.aborted)break;i||(i=!0,clearTimeout(o)),!r&&Gv.has(a.type)&&(r=!0,this.dropTrailingInFlightAssistant()),await this.processIncomingChunk(a,{defer:!1})}this.pendingToolExecutions.size>0&&await Promise.all(this.pendingToolExecutions.values())}catch(e){let t=e instanceof Error&&(e.name===`AbortError`||e.name===`TimeoutError`);!i&&!t&&(a=!0),i&&!t&&this.reportStreamError(e instanceof Error?e:Error(String(e)))}finally{clearTimeout(o),!i&&a&&this.tailing&&!this.disposed&&(this.lastResume=null,this.persistor?.persistResumeSnapshot(null)),this.abortController===n&&(this.abortController=null,this.setIsLoading(!1),this.status===`streaming`&&this.setStatus(`ready`),await this.drainPostStreamActions())}})()}dropTrailingInFlightAssistant(){let e=this.processor.getMessages(),t=e[e.length-1];t&&t.role===`assistant`&&this.processor.setMessages(e.slice(0,-1))}async processIncomingChunk(e,t){if(e.type===`RUN_ERROR`&&this.isActiveInterruptSubmissionFailure(e)&&(this.interruptSubmissionFailure={errors:e[`tanstack:interruptErrors`]??[]}),this.connectionStatus===`connecting`&&this.setConnectionStatus(`connected`),this.clearedStreamTracker.shouldIgnoreChunk(e)){(e.type===`RUN_FINISHED`||e.type===`RUN_ERROR`)&&(S_(e)?this.updateRunLifecycle(e,{resolveProcessing:!1}):this.drainIgnoredRunlessChunk(e),this.retireIgnoredClearedTerminalChunk(e),this.resolveJoinedRun(e));return}this.callbacksRef.current.onChunk(e),this.devtoolsBridge.observeChunk(e),this.processor.processChunk(e),this.updateRunLifecycle(e),this.observeInterruptState(e),t?.defer!==!1&&(typeof document>`u`||!document.hidden)&&await new Promise(e=>setTimeout(e,0)),this.resolveJoinedRun(e)}isActiveInterruptSubmissionFailure(e){let t=this.activeInterruptSubmission,n=e[`tanstack:interruptErrors`];if(!t||!n||n.length===0)return!1;let r=S_(e);return r!==void 0&&r!==this.currentRunId||typeof e.threadId==`string`&&e.threadId!==t.threadId?!1:n.every(e=>e.threadId===t.threadId&&e.interruptedRunId===t.interruptedRunId&&e.generation===t.generation)}resolveJoinedRun(e){if(e.type!==`RUN_FINISHED`&&e.type!==`RUN_ERROR`)return;let t=S_(e);if(t===void 0)return;let n=this.joinedRunWaiters.get(t);n!==void 0&&(this.joinedRunWaiters.delete(t),n())}ensureSubscription(){if(!this.isSubscribed){this.subscribe();return}(!this.subscriptionAbortController||this.subscriptionAbortController.signal.aborted)&&this.subscribe({restart:!0})}waitForProcessing(){return this.resolveProcessing(),new Promise(e=>{this.processingResolve=e})}async sendMessage(e,t,n){if(this.mountDevtools(),!(typeof e==`string`&&!e.trim())){if(this.hasBlockingInterrupts())throw Error(`ChatClient: cannot send normal input while pending interrupts exist. Use resumeInterrupts() instead.`);if(this.isSendBusy()){let{action:r,id:i}=this.decideWhenBusy(e,n);if(r===`drop`)return;if(r===`queue`){this.enqueueMessage(e,t,i);return}this.stopMessageQueueDrain=!0,this.sendInFlight=!0,this.cancelInFlightStream({setReadyStatus:!0}),this.resetSessionGenerating()}else this.sendInFlight=!0;try{await this.deliverMessage(e,t)}finally{this.sendInFlight=!1}}}hasPendingInterrupts(){return this.interruptManager.getDescriptors().length>0}hasBlockingInterrupts(){return this.activeInterruptSubmission!==void 0||this.hasPendingInterrupts()}isSendBusy(){return this.isLoading||this.sendInFlight||this.messageQueueDraining}resolveBusyReason(){return this.isLoading?`streaming`:this.messageQueueDraining?`draining`:`sendInFlight`}async deliverMessage(e,t){if(this.isLoading||this.deliverClaim)return!1;this.deliverClaim=!0;try{let n=this.normalizeMessageInput(e);this.pendingMessageBody=t;let r=this.processor.addUserMessage(n.content,n.id);return this.events.messageSent(r.id,n.content),await this.streamResponse()}finally{this.deliverClaim=!1}}decideWhenBusy(e,t){let n=this.generateUniqueId(`queued`);if(t?.whenBusy)return{action:t.whenBusy,id:n};let{strategy:r,whenBusy:i}=this.queueConfig;if(r){let{action:t}=r({pending:{id:n,content:e,createdAt:Date.now()},busyReason:this.resolveBusyReason(),queued:this.getQueue()});return{action:t,id:n}}return{action:i,id:n}}enqueueMessage(e,t,n){let{maxSize:r,onOverflow:i}=this.queueConfig;if(r!==void 0&&this.messageQueue.length>=r){if(i===`reject`||r===0)return;this.messageQueue.shift()}this.messageQueue.push({id:n??this.generateUniqueId(`queued`),content:e,createdAt:Date.now(),...t===void 0?{}:{body:t}}),this.emitQueueChange()}normalizeMessageInput(e){return typeof e==`string`?{content:e.trim()}:{content:e.content,id:e.id}}async append(e){if(this.mountDevtools(),this.hasBlockingInterrupts())throw Error(`ChatClient: cannot append normal input while pending interrupts exist. Use resumeInterrupts() instead.`);let t=im(e,am);if(t.role===`system`)return;let n=t;this.events.messageAppended(n);let r=this.processor.getMessages();if(this.processor.setMessages([...r,n]),this.devtoolsBridge.emitSnapshot(),this.isLoading){this.queuePostStreamAction(async()=>{await this.streamResponse()});return}await this.streamResponse()}async streamResponse(){if(this.isLoading)return!1;let e=++this.streamGeneration,t=this.pendingResumeThreadId,n=this.pendingResumeParentRunId,r=this.pendingResumeItems;this.pendingResumeThreadId=null,this.pendingResumeParentRunId=null,this.pendingResumeItems=null;let i=`run-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this.setCurrentRunId(i),this.activeResumeThreadId=t??this.threadId,this.activeResumeRunId=i,this.setIsLoading(!0),this.deliverClaim=!1,this.setStatus(`submitted`),this.setError(void 0),this.errorReportedGeneration=null,this.abortController=new AbortController;let a=this.abortController.signal;this.pendingToolExecutions.clear();let o=!1,s=null,c=!1;try{let l=this.processor.getMessages(),u=new Map(this.clientToolsRef.current),d=this.context;if(await this.callbacksRef.current.onResponse(),a.aborted)return!1;let f={...this.bodyOption,...this.forwardedPropsOption,...this.pendingMessageBody};this.pendingMessageBody=void 0,this.currentStreamId=this.generateUniqueId(`stream`),this.devtoolsBridge.setCurrentStreamId(this.currentStreamId),this.currentMessageId=null,this.activeClientTools=u,this.activeContext=d,this.processor.prepareAssistantMessage(),this.ensureSubscription();let p=this.waitForProcessing(),m={threadId:t??this.threadId,runId:i,...n===null?{}:{parentRunId:n},clientTools:Array.from(u.values()).map(e=>({name:e.name,description:e.description,parameters:e.inputSchema?fp(e.inputSchema):{type:`object`}})),forwardedProps:{...f},...r?{resume:r}:{}};if(this.devtoolsBridge.beginRun(m.runId,m.threadId),s=m.runId,this.devtoolsBridge.emitRunLifecycle(`run:created`,m.runId,`created`),this.devtoolsBridge.emitRunLifecycle(`run:started`,m.runId,`started`),this.devtoolsBridge.emitSnapshot(),await this.connection.send(l,f,a,m),e!==this.streamGeneration||a.aborted||(await p,e!==this.streamGeneration))return!1;if(this.status===`error`)return s&&(this.devtoolsBridge.emitRunLifecycle(`run:errored`,s,`errored`,this.error?{error:this.error.message}:{}),c=!0),!1;this.pendingToolExecutions.size>0&&await Promise.all(this.pendingToolExecutions.values()),this.processor.finalizeStream(),o=!0}catch(t){if(t instanceof Error){if(t.name===`AbortError`)return s&&(this.devtoolsBridge.emitRunLifecycle(`run:cancelled`,s,`cancelled`),c=!0),!1;e===this.streamGeneration&&(this.reportStreamError(t),s&&(this.devtoolsBridge.emitRunLifecycle(`run:errored`,s,`errored`,{error:t.message}),c=!0))}}finally{if(e===this.streamGeneration){if(this.currentStreamId=null,this.devtoolsBridge.setCurrentStreamId(null),this.currentMessageId=null,this.setCurrentRunId(null),this.activeClientTools=null,this.activeContext=void 0,this.abortController=null,this.setIsLoading(!1),this.pendingMessageBody=void 0,s&&!c&&(o?this.devtoolsBridge.emitRunLifecycle(`run:completed`,s,`completed`):a.aborted&&this.devtoolsBridge.emitRunLifecycle(`run:cancelled`,s,`cancelled`)),await this.drainPostStreamActions(),o){let e=this.processor.getMessages().at(-1)?.parts.at(-1),{finishReason:t}=this.processor.getState();if(e?.type===`tool-result`&&t!==`stop`&&this.shouldAutoSend())try{await this.checkForContinuation()}catch(e){console.error(`Failed to continue flow after tool result:`,e),await this.drainQueue()}else this.status!==`ready`&&this.setStatus(`ready`),this.messageQueueDraining||await this.drainQueue()}else this.flushQueue()}}return o}subscribe(e){let t=e?.restart===!0;this.isSubscribed&&!t||(this.isSubscribed&&t&&this.abortSubscriptionLoop(),this.setIsSubscribed(!0),this.setConnectionStatus(`connecting`),this.startSubscription())}unsubscribe(){this.cancelInFlightStream({setReadyStatus:!0,abortSubscription:!0}),this.discardPendingSends(),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.setConnectionStatus(`disconnected`)}async reload(){let e=this.processor.getMessages();if(e.length===0)return;let t=e.findLastIndex(e=>e.role===`user`);t!==-1&&(this.isLoading&&this.cancelInFlightStream(),this.discardPendingSends(),this.events.reloaded(t),this.processor.removeMessagesAfter(t),this.devtoolsBridge.emitSnapshot(),await this.streamResponse())}stop(){let e=this.abortController!==null;this.cancelInFlightStream({setReadyStatus:!0}),this.discardPendingSends(),e&&this.resetSessionGenerating(),this.events.stopped()}clear(){let e=this.abortController!==null;this.clearedStreamTracker.snapshotClear({messages:this.processor.getMessages(),activeRunIds:this.activeRunIds,currentRunId:this.currentRunId}),this.isLoading||e?(this.cancelInFlightStream({setReadyStatus:!0}),this.resetSessionGenerating({preserveClearedStreamTracking:!0})):this.activeRunIds.size>0&&this.resetSessionGenerating({preserveClearedStreamTracking:!0}),this.persistor?.beginClear(),this.processor.clearMessages(),this.discardPendingSends(),this.persistor?.remove(),this.lastResume=null,this.interruptManager.reset(),this.pendingResumeThreadId=null,this.pendingResumeParentRunId=null,this.pendingResumeItems=null,this.setError(void 0),this.events.messagesCleared()}async addToolResult(e){let t=this.clientToolsRef.current.get(e.tool);await this.addToolResultForClientTool(e,t)}async addToolResultForClientTool(e,t,n){if(t&&e.state!==`output-error`)try{e={...e,output:this.validateClientToolOutput(t,e.output)}}catch(t){e={...e,output:null,state:`output-error`,errorText:t.message}}if(this.events.toolResultAdded(e.toolCallId,e.tool,e.output,e.state||`output-available`,n),this.processor.addToolResult(e.toolCallId,e.output,e.state===`output-error`?e.errorText||`Tool execution failed`:void 0),this.devtoolsBridge.emitSnapshot(),!this.interruptManager.resolveClientToolOutput(e.toolCallId,e.state===`output-error`?{error:e.errorText||`Tool execution failed`}:e.output)){if(this.isLoading){this.queuePostStreamAction(()=>this.checkForContinuation());return}await this.checkForContinuation()}}validateClientToolOutput(e,t){return e.outputSchema&&cp(e.outputSchema)?mp(e.outputSchema,t):t}async addToolApprovalResponse(e){if(this.processor.addToolApprovalResponse(e.id,e.approved),this.devtoolsBridge.emitSnapshot(),this.interruptManager.resolveToolApprovalDecision(e.id,e.approved))return;let t=this.processor.getMessages(),n;for(let r of t){let t=r.parts.find(t=>t.type===`tool-call`&&t.approval?.id===e.id);if(t){n=t.id;break}}if(n&&this.events.toolApprovalResponded(e.id,n,e.approved),this.processor.addToolApprovalResponse(e.id,e.approved),this.devtoolsBridge.emitSnapshot(),this.isLoading){this.queuePostStreamAction(()=>this.checkForContinuation());return}await this.checkForContinuation()}queuePostStreamAction(e){this.postStreamActions.push(e)}async drainPostStreamActions(){if(!this.draining){this.draining=!0;try{let e;for(;(e=this.postStreamActions.shift())!==void 0;)await e()}finally{this.draining=!1}}}async checkForContinuation(){if(!this.hasPendingInterrupts()){if(this.continuationPending||this.isLoading){this.continuationSkipped=!0;return}if(this.shouldAutoSend()){this.continuationPending=!0,this.continuationSkipped=!1;let e=!1;try{e=await this.streamResponse()}finally{this.continuationPending=!1}this.continuationSkipped&&e&&(this.continuationSkipped=!1,await this.checkForContinuation())}}}shouldAutoSend(){if(this.lastResume||this.activeInterruptSubmission&&this.hasPendingInterrupts()||this.interruptManager.getInterrupts().length>0)return!1;let e=this.processor.getMessages().findLast(e=>e.role===`assistant`);return!e||!e.parts.some(e=>e.type===`tool-call`)?!1:this.processor.areAllToolsComplete()}getMessages(){return this.processor.getMessages()}shouldAbortMessageQueueDrain(){return this.isLoading||this.stopMessageQueueDrain}async drainQueue(){if(!(this.messageQueueDraining||this.isLoading||this.messageQueue.length===0)){this.messageQueueDraining=!0,this.stopMessageQueueDrain=!1;try{if(this.queueConfig.drain===`batch`){for(;this.messageQueue.length>0;){if(this.shouldAbortMessageQueueDrain())return;let e=this.messageQueue.splice(0);this.emitQueueChange();let t=Vv(e);if(!await this.deliverMessage(t.content,t.body)||this.shouldAbortMessageQueueDrain())return}return}for(;this.messageQueue.length>0;){if(this.shouldAbortMessageQueueDrain())return;let e=this.messageQueue.shift();if(e===void 0||(this.emitQueueChange(),!await this.deliverMessage(e.content,e.body)||this.shouldAbortMessageQueueDrain()))return}}finally{this.messageQueueDraining=!1,this.stopMessageQueueDrain=!1}}}discardPendingSends(){this.sendInFlight=!1,this.flushQueue()}getQueue(){return this.messageQueue.map(({id:e,content:t,createdAt:n})=>({id:e,content:t,createdAt:n}))}emitQueueChange(){this.callbacksRef.current.onQueueChange(this.getQueue()),this.devtoolsBridge.emitSnapshot()}cancelQueued(e){let t=this.messageQueue.findIndex(t=>t.id===e);t!==-1&&(this.messageQueue.splice(t,1),this.emitQueueChange())}flushQueue(){this.messageQueue.length!==0&&(this.messageQueue=[],this.emitQueueChange())}getIsLoading(){return this.isLoading}getStatus(){return this.status}getIsSubscribed(){return this.isSubscribed}getConnectionStatus(){return this.connectionStatus}getSessionGenerating(){return this.sessionGenerating}getError(){return this.error}setMessagesManually(e){this.processor.setMessages(e),this.devtoolsBridge.emitSnapshot()}updateOptions(e){if(e.connection!==void 0||e.fetcher!==void 0){let t=this.isSubscribed;this.isLoading?this.cancelInFlightStream({setReadyStatus:!0,abortSubscription:!0}):t&&this.abortSubscriptionLoop(),this.resetSessionGenerating(),this.setIsSubscribed(!1),this.setConnectionStatus(`disconnected`),this.connection=G_(zv({connection:e.connection,fetcher:e.fetcher})),t&&this.subscribe()}if(e.body!==void 0&&(this.bodyOption=e.body),e.forwardedProps!==void 0&&(this.forwardedPropsOption=e.forwardedProps),`context`in e&&(this.context=e.context),e.tools!==void 0){this.interruptManager.updateTools(e.tools),this.clientToolsRef.current=new Map;for(let t of e.tools)this.clientToolsRef.current.set(t.name,t);this.devtoolsBridge.notifyToolsChanged()}e.queue!==void 0&&(this.queueConfig=Bv(e.queue)),e.onResponse!==void 0&&(this.callbacksRef.current.onResponse=e.onResponse),e.onChunk!==void 0&&(this.callbacksRef.current.onChunk=e.onChunk),e.onFinish!==void 0&&(this.callbacksRef.current.onFinish=e.onFinish),e.onError!==void 0&&(this.callbacksRef.current.onError=e.onError),e.onSubscriptionChange!==void 0&&(this.callbacksRef.current.onSubscriptionChange=e.onSubscriptionChange),e.onConnectionStatusChange!==void 0&&(this.callbacksRef.current.onConnectionStatusChange=e.onConnectionStatusChange),e.onSessionGeneratingChange!==void 0&&(this.callbacksRef.current.onSessionGeneratingChange=e.onSessionGeneratingChange),e.onQueueChange!==void 0&&(this.callbacksRef.current.onQueueChange=e.onQueueChange),e.onResumeStateChange!==void 0&&(this.callbacksRef.current.onResumeStateChange=e.onResumeStateChange),e.onRunIdChange!==void 0&&(this.callbacksRef.current.onRunIdChange=e.onRunIdChange),e.onInterruptStateChange!==void 0&&(this.callbacksRef.current.onInterruptStateChange=e.onInterruptStateChange),e.onCustomEvent!==void 0&&(this.callbacksRef.current.onCustomEvent=e.onCustomEvent)}dispose(){this.disposed=!0,this.unsubscribe(),this.devtoolsBridge.dispose(),this.devtoolsMounted=!1}};function qv(){return{name:`streaming`,transformDocument(e){let t=Jv(e.children);return t===e.children?e:{...e,children:t}}}}function Jv(e){let t=e.at(-1);if(!t)return e;let n=Yv(t);return n===t?e:n?[...e.slice(0,-1),n]:e.slice(0,-1)}function Yv(e){if(e.type===`heading`&&e.children.length===0)return;if(e.type===`blockquote`){let t=Jv(e.children);return t.length===0?void 0:t===e.children?e:{...e,children:t}}if(e.type!==`list`)return e;let t=e.items.at(-1);if(!t)return;let n=Xv(t);if(n===t)return e;let r=n?[...e.items.slice(0,-1),n]:e.items.slice(0,-1);return r.length===0?void 0:{...e,items:r}}function Xv(e){let t=Jv(e.children);if(t.length!==0)return t===e.children?e:{...e,children:t}}var Zv={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`};function Qv(e){return e.replace(/^\uFEFF/,``).replace(/\r\n?/g,`
28
+ `)}function $v(e){return e.replace(/[&<>"']/g,e=>Zv[e])}function $(e){return $v(e).replace(/`/g,`&#96;`)}function ey(e){return/^\s*$/.test(e)}function ty(e,t){let n=0;for(;n<e.length&&n<t&&e[n]===` `;)n++;return e.slice(n)}function ny(e){let t=``;for(let n of e)n.type===`text`||n.type===`inlineCode`?t+=n.value:`children`in n?t+=ny(n.children):n.type===`image`&&(t+=n.alt);return t}function ry(){let e=new Map;return t=>{let n=t.toLowerCase().normalize(`NFKD`).replace(/[\u0300-\u036f]/g,``).replace(/&[a-z0-9#]+;/gi,``).replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`section`,r=e.get(n)??0;return e.set(n,r+1),r===0?n:`${n}-${r+1}`}}function iy(e){let t=e.trim().replace(/[\u0000-\u001F\u007F\s]+/g,``);return t?/^(#|\/|\.\/|\.\.\/)/.test(t)||/^(https?:|mailto:|tel:)/i.test(t)?t:/^[a-z][a-z0-9+.-]*:/i.test(t)?``:t:``}function ay(e){return e.trim().toLowerCase()}function oy(e){return ay(e).replace(/[^a-z0-9_-]+/g,`-`).replace(/^-+|-+$/g,``)}function sy(e,t={}){let n=Dy(uy(e,t));for(let e of t.extensions??[])n=e.transformInline?.(n,{options:t})??n;return n}var cy=32,ly=16;function uy(e,t,n={scans:Math.max(e.length*ly,1024),depth:0}){if(n.depth>=cy)return e?[{type:`text`,value:e}]:[];n.depth++;let r=[],i=0,a=``,o=()=>{a&&=(r.push({type:`text`,value:a}),``)};for(;i<e.length;){let s=e[i],c=e[i+1];if(s===`\\`){if(c===`
29
+ `){o(),r.push({type:`break`}),i+=2;continue}if(c&&/[\\`*_[\]{}()#+\-.!|~<>]/.test(c)){a+=c,i+=2;continue}}if(s==="`"){let t=gy(e,i,"`"),s=_y(e,i+t,"`",t,n);if(s!==-1){o(),r.push({type:`inlineCode`,value:e.slice(i+t,s).replace(/\s+/g,` `).trim()}),i=s+t;continue}a+=e.slice(i,i+t),i+=t;continue}if(s===`!`&&c===`[`){let a=fy(e,i+1,t,n);if(a){o(),r.push({type:`image`,src:iy(a.href),alt:Ey(a.label,n),...a.title?{title:a.title}:{}}),i=a.end;continue}}if(s===`[`){let a=dy(e,i,t,n);if(a){o(),r.push(a.node),i=a.end;continue}let s=fy(e,i,t,n);if(s){let e=iy(s.href);o(),e?r.push({type:`link`,href:e,...s.title?{title:s.title}:{},children:uy(s.label,t,n)}):r.push(...uy(s.label,t,n)),i=s.end;continue}}if(s===`*`&&c===`*`&&e[i+2]===`*`){let a=vy(e,i+3,`***`,n);if(a!==-1){o(),r.push({type:`emphasis`,children:uy(e.slice(i+1,a+2),t,n)}),i=a+3;continue}}if(s===`*`&&c===`*`||s===`_`&&c===`_`){let l=s===`_`&&!Sy(e,i,2,!0)?-1:vy(e,i+2,s+s,n);if(l!==-1){o(),r.push({type:`strong`,children:uy(e.slice(i+2,l),t,n)}),i=l+2;continue}a+=s+c,i+=2;continue}if(s===`~`&&c===`~`&&e[i+2]===`~`){let t=gy(e,i,`~`);a+=e.slice(i,i+t),i+=t;continue}if(s===`~`&&c===`~`){let s=vy(e,i+2,`~~`,n);if(s!==-1){o(),r.push({type:`strike`,children:uy(e.slice(i+2,s),t,n)}),i=s+2;continue}a+=`~~`,i+=2;continue}if(s===`~`){let a=yy(e,i+1,n);if(a!==-1){o(),r.push({type:`strike`,children:uy(e.slice(i+1,a),t,n)}),i=a+1;continue}}if(s===`*`||s===`_`){let a=s===`_`&&!Sy(e,i,1,!0)?-1:vy(e,i+1,s,n);if(a!==-1){o(),r.push({type:`emphasis`,children:uy(e.slice(i+1,a),t,n)}),i=a+1;continue}}if(s===`<`&&t.allowHtml){let t=by(e,i+1,`>`,n);if(t!==-1&&py(e.slice(i,t+1))){o(),r.push({type:`inlineHtml`,value:e.slice(i,t+1)}),i=t+1;continue}}a+=s,i++}return o(),n.depth--,r}function dy(e,t,n,r){if(e[t+1]!==`^`)return;let i=by(e,t+2,`]`,r);if(i===-1)return;let a=ay(e.slice(t+2,i)),o=n.footnotes?.[a];if(!o||!n.footnoteOrder)return;let s=n.footnoteOrder.indexOf(a);s===-1&&(n.footnoteOrder.push(a),s=n.footnoteOrder.length-1);let c=(n.footnoteCounts?.[a]??0)+1;return n.footnoteCounts&&(n.footnoteCounts[a]=c),{node:{type:`footnoteReference`,id:o.id??(oy(o.label)||`footnote`),number:s+1,...c>1?{referenceIndex:c}:{}},end:i+1}}function fy(e,t,n,r){let i=hy(e,t,`[`,`]`,r);if(i===-1)return;let a=e.slice(t+1,i);if(e[i+1]===`(`){let t=hy(e,i+1,`(`,`)`,r);if(t===-1)return;let n=my(e.slice(i+2,t).trim());return n?{label:a,href:n.href,...n.title?{title:n.title}:{},end:t+1}:void 0}if(e[i+1]===`[`){let t=hy(e,i+1,`[`,`]`,r);if(t===-1)return;let o=e.slice(i+2,t),s=n.references?.[ay(o||a)];return s?{label:a,href:s.href,...s.title?{title:s.title}:{},end:t+1}:void 0}let o=n.references?.[ay(a)];if(o)return{label:a,href:o.href,...o.title?{title:o.title}:{},end:i+1}}function py(e){return/^<!--(?:[\s\S]*--|-?)>$/.test(e)||/^<\?[\s\S]*\?>$/.test(e)||/^<![A-Z][\s\S]*>$/.test(e)||/^<!\[CDATA\[[\s\S]*\]\]>$/.test(e)||/^<\/[A-Za-z][\w:-]*\s*>$/.test(e)?!0:/^<[A-Za-z][\w:-]*(?:\s+[A-Za-z_:][\w:.-]*(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+))?)*\s*\/?>$/.test(e)}function my(e){let t=e.match(/^(\S+)(?:\s+["']([^"']*)["'])?$/);return t?{href:t[1].replace(/^<|>$/g,``),...t[2]?{title:t[2]}:{}}:{href:e}}function hy(e,t,n,r,i){let a=0;for(let o=t;o<e.length;o++){if(!xy(i))return-1;if(e[o-1]!==`\\`&&(e[o]===n&&a++,e[o]===r&&(a--,a===0)))return o}return-1}function gy(e,t,n,r){let i=0;for(;e[t+i]===n&&!(r&&!xy(r));)i++;return i}function _y(e,t,n,r,i){for(let a=t;a<e.length;a++){if(!xy(i))return-1;if(e[a]===n&&gy(e,a,n,i)>=r)return a}return-1}function vy(e,t,n,r){for(let i=t;i<e.length;i++){if(!xy(r))return-1;if(e[i-1]!==`\\`&&e.startsWith(n,i)){if(e[i+1]===n){let t=vy(e,i+2,n+n,r);if(t>i+2){i=t+1;continue}}if((n!==`~~`||e[i-1]!==`~`&&e[i+2]!==`~`)&&!(n[0]===`_`&&!Sy(e,i,n.length,!1)))return i}}return-1}function yy(e,t,n){if(Ty(e[t]??``)||/\d/.test(e[t]??``))return-1;for(let r=t;r<e.length;r++){if(!xy(n))return-1;if(e[r-1]!==`\\`&&e[r]===`~`&&e[r-1]!==`~`&&e[r+1]!==`~`)return Ty(e[r-1]??``)?-1:r}return-1}function by(e,t,n,r){for(let i=t;i<e.length;i++){if(!xy(r))return-1;if(e[i]===n)return i}return-1}function xy(e){return e.scans<=0?!1:(e.scans--,!0)}function Sy(e,t,n,r){let i=e[t-1],a=e[t+n],o=!Cy(a)&&(!wy(a)||Cy(i)||wy(i)),s=!Cy(i)&&(!wy(i)||Cy(a)||wy(a));return r?o&&(!s||wy(i)):s&&(!o||wy(a))}function Cy(e){return e===void 0||/\s/.test(e)}function wy(e){return e!==void 0&&/[^\p{L}\p{N}\s]/u.test(e)}function Ty(e){return/\s/.test(e)}function Ey(e,t){return uy(e,{},t).map(e=>e.type===`text`||e.type===`inlineCode`?e.value:``).join(``)}function Dy(e){let t=[];for(let n of e){let e=t.at(-1);e?.type===`text`&&n.type===`text`?e.value+=n.value:t.push(n)}return t}var Oy=64;function ky(e,t={}){let n=Qv(e),r=t.frontmatter!==!1,i=n.split(`
30
30
  `),a;if(r&&i[0]===`---`){let e=i.findIndex((e,t)=>t>0&&e===`---`);e>0&&(a=i.slice(1,e).join(`
31
- `),i=i.slice(e+1))}let o=Ay(i);i=o.lines;let s=[],c=Object.create(null),l=Object.keys(o.references).length>0,u=Object.keys(o.footnotes).length>0,d=l||u?{...t,...l?{references:o.references}:{},...u?{footnotes:o.footnotes,footnoteOrder:s,footnoteCounts:c}:{}}:t,f=new Oy(i,d,ty()).parse();u&&s.length>0&&f.push(jy(o.footnotes,s,d));let p=a===void 0?{type:`root`,children:f}:{type:`root`,frontmatter:a,children:f};for(let e of d.extensions??[])p=e.transformDocument?.(p,{options:d})??p;return p}var Oy=class e{lines;options;slugger;budget;index=0;constructor(e,t,n,r={depth:0}){this.lines=e,this.options=t,this.slugger=n,this.budget=r}parse(){if(this.budget.depth>=Ey){let e=this.lines.slice(this.index).join(`
32
- `);return this.index=this.lines.length,e?[{type:`paragraph`,children:ay(e,this.options)}]:[]}this.budget.depth++;let e=[];for(;this.index<this.lines.length;){if(Qv(this.current())){this.index++;continue}let t=this.parseExtensionBlock();if(t){e.push(t);continue}let n=this.parseFence()??this.parseHeading()??this.parseThematicBreak()??this.parseBlockquote()??this.parseList()??this.parseTable()??this.parseHtmlBlock()??this.parseParagraph();e.push(n)}return this.budget.depth--,e}parseExtensionBlock(){for(let t of this.options.extensions??[]){let n=0,r=t.parseBlock?.({lines:this.lines,index:this.index,options:this.options,parseInline:e=>ay(e,this.options),parseBlocks:t=>new e(Xv(t).split(`
31
+ `),i=i.slice(e+1))}let o=My(i);i=o.lines;let s=[],c=Object.create(null),l=Object.keys(o.references).length>0,u=Object.keys(o.footnotes).length>0,d=l||u?{...t,...l?{references:o.references}:{},...u?{footnotes:o.footnotes,footnoteOrder:s,footnoteCounts:c}:{}}:t,f=new Ay(i,d,ry()).parse();u&&s.length>0&&f.push(Ny(o.footnotes,s,d));let p=a===void 0?{type:`root`,children:f}:{type:`root`,frontmatter:a,children:f};for(let e of d.extensions??[])p=e.transformDocument?.(p,{options:d})??p;return p}var Ay=class e{lines;options;slugger;budget;index=0;constructor(e,t,n,r={depth:0}){this.lines=e,this.options=t,this.slugger=n,this.budget=r}parse(){if(this.budget.depth>=Oy){let e=this.lines.slice(this.index).join(`
32
+ `);return this.index=this.lines.length,e?[{type:`paragraph`,children:sy(e,this.options)}]:[]}this.budget.depth++;let e=[];for(;this.index<this.lines.length;){if(ey(this.current())){this.index++;continue}let t=this.parseExtensionBlock();if(t){e.push(t);continue}let n=this.parseFence()??this.parseHeading()??this.parseThematicBreak()??this.parseBlockquote()??this.parseList()??this.parseTable()??this.parseHtmlBlock()??this.parseParagraph();e.push(n)}return this.budget.depth--,e}parseExtensionBlock(){for(let t of this.options.extensions??[]){let n=0,r=t.parseBlock?.({lines:this.lines,index:this.index,options:this.options,parseInline:e=>sy(e,this.options),parseBlocks:t=>new e(Qv(t).split(`
33
33
  `),this.options,this.slugger,this.budget).parse(),consume:e=>{n=e}});if(r)return this.index+=Math.max(n,1),r}}parseFence(){let e=this.current().match(/^ {0,3}(`{3,}|~{3,})(.*)$/);if(!e)return;let t=e[1],n=t[0],r=t.length,i=e[2].trim(),a=[];for(this.index++;this.index<this.lines.length;){let e=this.current(),t=e.match(/^ {0,3}(`{3,}|~{3,})\s*$/);if(t&&t[1][0]===n&&t[1].length>=r){this.index++;break}a.push(e),this.index++}return{type:`code`,value:a.join(`
34
- `),...ky(i)}}parseHeading(){let e=this.current().match(/^ {0,3}(#{1,6})(?:[ \t]+(.*)|[ \t]*)$/);if(!e)return;let t=e[1].length,n=e[2]??``,r=ay((/^#+[ \t]*$/.test(n)?``:n.replace(/[ \t]+#+[ \t]*$/,``)).trim(),this.options),i=this.createHeadingId(r);return this.index++,i?{type:`heading`,depth:t,id:i,children:r}:{type:`heading`,depth:t,children:r}}parseThematicBreak(){if(/^ {0,3}([-*_])(?:\s*\1){2,}\s*$/.test(this.current()))return this.index++,{type:`thematicBreak`}}parseBlockquote(){if(!/^ {0,3}>\s?/.test(this.current()))return;let t=[];for(;this.index<this.lines.length;){let e=this.current();if(Qv(e)){t.push(``),this.index++;continue}let n=e.match(/^ {0,3}>\s?(.*)$/);if(!n)break;t.push(n[1]),this.index++}return{type:`blockquote`,children:new e(t,this.options,this.slugger,this.budget).parse()}}parseList(){let t=Ny(this.current());if(!t)return;let n=[],r=t.ordered,i=t.indent,a=r?t.number:void 0,o=!1;for(;this.index<this.lines.length;){let r=Ny(this.current());if(!r||!Py(r,t)||r.indent!==i)break;let a=r.content,s=a.match(/^\[([ xX])\]\s+(.*)$/),c=s?s[1].toLowerCase()===`x`:void 0;s&&(a=s[2]);let l=[a];for(this.index++;this.index<this.lines.length;){let e=this.current(),n=Ny(e);if(n&&n.indent===i)break;if(Qv(e)){let e=this.index;for(;e<this.lines.length&&Qv(this.lines[e]);)e++;let n=this.lines[e];if(n===void 0)break;let a=Ny(n);if(a?.indent===i){if(!Py(a,t))break;o=!0,this.index=e;break}if(Fy(n)<r.contentIndent)break;o=!0,l.push(``),this.index=e;continue}if(Fy(e)>=r.contentIndent){l.push($v(e,r.contentIndent)),this.index++;continue}if(Iy(e,this.next()))break;l.push(e.trimStart()),this.index++}let u={type:`listItem`,children:new e(l,this.options,this.slugger,this.budget).parse()};c!==void 0&&(u.checked=c),n.push(u)}return{type:`list`,ordered:r,...r&&a!==void 0?{start:a}:{},...o&&{loose:!0},items:n}}parseTable(){let e=this.current(),t=this.next();if(!t||!Ly(e,t))return;let n=Ry(e),r=Ry(t).map(zy),i=n.length,a=[];for(this.index+=2;this.index<this.lines.length;){let e=this.current();if(Qv(e)||Iy(e,this.next()))break;let t=Ry(e);a.push(Array.from({length:i},(e,n)=>By(t[n]??``,this.options))),this.index++}return{type:`table`,align:r,header:n.map(e=>By(e,this.options)),rows:a}}parseHtmlBlock(){if(!this.options.allowHtml||!/^ {0,3}<([A-Za-z][\w:-]*|!--|\/[A-Za-z])/.test(this.current()))return;let e=[];if(/^ {0,3}<!--/.test(this.current())){for(;this.index<this.lines.length;){let t=this.current();if(e.push(t),this.index++,t.includes(`-->`))break}return{type:`html`,value:e.join(`
35
- `)}}for(;this.index<this.lines.length&&!Qv(this.current());)e.push(this.current()),this.index++;return{type:`html`,value:e.join(`
36
- `)}}parseParagraph(){let e=[];for(;this.index<this.lines.length;){let t=this.current();if(Qv(t)||e.length>0&&Iy(t,this.next()))break;e.push(t.trim()),this.index++}return{type:`paragraph`,children:ay(e.join(`
37
- `),this.options)}}createHeadingId(e){if(this.options.headingIds===!1)return;let t=ey(e);return typeof this.options.headingIds==`function`?this.options.headingIds(t,this.index):this.slugger(t)}current(){return this.lines[this.index]??``}next(){return this.lines[this.index+1]}};function ky(e){if(!e)return{};let t=e.match(/^([A-Za-z0-9_+.#-]+)/)?.[1],n=t?e.slice(t.length).trim():e,r=n.match(/(?:^|\s)(?:title|file)=(?:"([^"]+)"|'([^']+)'|([^\s}]+))/),i=n.match(/(?:^|\s)framework=(?:"([^"]+)"|'([^']+)'|([^\s}]+))/),a=n.match(/\{([^}]+)\}|(?:^|\s)lines=([^\s]+)/),o=My(a?.[1]??a?.[2]??``),s=r?r[1]??r[2]??r[3]:void 0,c=i?i[1]??i[2]??i[3]:void 0;return{...t?{lang:t}:{},...n?{meta:n}:{},...s?{title:s,file:s}:{},...c?{framework:c.toLowerCase()}:{},...o.length?{highlightLines:o}:{}}}function Ay(e){let t=Object.create(null),n=Object.create(null),r=new Map,i=[],a,o=0,s=0;for(;s<e.length;){let c=e[s],l=c.match(/^ {0,3}(`{3,}|~{3,})/);if(l){let e=l[1][0];a?e===a&&l[1].length>=o&&(a=void 0,o=0):(a=e,o=l[1].length),i.push(c),s++;continue}if(!a){let i=c.match(/^ {0,3}\[\^([^\]\n]+)\]:[ \t]*(.*)$/);if(i){let t=i[1],a=[i[2]??``];for(s++;s<e.length;){let t=e[s];if(!/^(?: {4,}|\t)/.test(t))break;a.push(t.replace(/^(?: {4}|\t)/,``)),s++}let o=ry(t);if(!n[o]){let e=iy(t)||`footnote`,i=(r.get(e)??0)+1;r.set(e,i),n[o]={label:t,content:a.join(`
38
- `),id:i===1?e:`${e}-${i}`}}continue}let a=c.match(/^ {0,3}\[([^\]\n]+)\]:[ \t]*(\S+)(?:[ \t]+(?:"([^"]*)"|'([^']*)'|\(([^)]*)\)))?[ \t]*$/);if(a){let e=a[3]??a[4]??a[5];t[ry(a[1])]={href:a[2].replace(/^<|>$/g,``),...e===void 0?{}:{title:e}},s++;continue}}i.push(c),s++}return{lines:i,references:t,footnotes:n}}function jy(e,t,n){let r=[];for(let i=0;i<t.length;i++){let a=e[t[i]];a&&r.push({id:a.id??(iy(a.label)||`footnote`),number:i+1,children:new Oy(Xv(a.content).split(`
39
- `),n,ty()).parse()})}for(let e of r){let r=n.footnoteCounts?.[t[e.number-1]]??1;r>1&&(e.referenceCount=r)}return{type:`footnotes`,items:r}}function My(e){let t=new Set;for(let n of e.split(`,`)){let e=n.trim().match(/^(\d+)(?:-(\d+))?$/);if(!e)continue;let r=Number(e[1]),i=Number(e[2]??e[1]);for(let e=r;e<=i&&e<r+1e3;e++)t.add(e)}return[...t].sort((e,t)=>e-t)}function Ny(e){let t=e.match(/^(\s{0,8})([-+*]|\d{1,9}[.)])(?:([ \t]+)(.*))?$/);if(!t)return;let n=t[2],r=/\d/.test(n[0]);return{ordered:r,...r?{number:Number.parseInt(n,10)}:{},indent:t[1].length,marker:r?n.at(-1):n,contentIndent:t[1].length+n.length+(t[3]?.length??1),content:t[4]??``}}function Py(e,t){return e.ordered===t.ordered&&e.marker===t.marker}function Fy(e){return e.match(/^ */)?.[0].length??0}function Iy(e,t){let n=Ny(e);return/^ {0,3}(`{3,}|~{3,})/.test(e)||/^ {0,3}#{1,6}(?:\s+|$)/.test(e)||/^ {0,3}([-*_])(?:\s*\1){2,}\s*$/.test(e)||/^ {0,3}>\s?/.test(e)||n!==void 0&&(!n.ordered||n.number===1)||!!t&&Ly(e,t)}function Ly(e,t){if(!e.includes(`|`))return!1;let n=Ry(t);return n.length===Ry(e).length&&n.every(e=>/^:?-+:?$/.test(e.trim()))}function Ry(e){let t=e.trim();t.startsWith(`|`)&&(t=t.slice(1)),t.endsWith(`|`)&&(t=t.slice(0,-1));let n=[],r=``;for(let e=0;e<t.length;e++){let i=t[e];if(i===`\\`&&t[e+1]===`|`){r+=`|`,e++;continue}if(i===`|`){n.push(r.trim()),r=``;continue}r+=i}return n.push(r.trim()),n}function zy(e){let t=e.trim();if(t.startsWith(`:`)&&t.endsWith(`:`))return`center`;if(t.endsWith(`:`))return`right`;if(t.startsWith(`:`))return`left`}function By(e,t){return{type:`tableCell`,children:ay(e,t)}}function Vy(e,t={}){return(typeof e==`string`?Dy(e,t):e).children.map(e=>Hy(e,t)).join(`
40
- `)}function Hy(e,t={}){let n=eb(e,t);if(n!==void 0)return n;switch(e.type){case`heading`:{let n=e.id?` id="${$(e.id)}"`:``,r=e.framework?` data-framework="${$(e.framework)}"`:``;return`<h${e.depth}${n}${r}>${Wy(e.children,t)}${tb(e.id,t)}</h${e.depth}>`}case`paragraph`:return`<p>${Wy(e.children,t)}</p>`;case`code`:return Gy(e,t);case`list`:{let n=e.ordered?`ol`:`ul`;return`<${n}${e.ordered&&e.start&&e.start!==1?` start="${e.start}"`:``}>\n${e.items.map(n=>`<li>${Ky(n.children,n.checked,e.loose,t)}</li>`).join(`
41
- `)}\n</${n}>`}case`blockquote`:return`<blockquote>\n${e.children.map(e=>Hy(e,t)).join(`
42
- `)}\n</blockquote>`;case`table`:return`<table>${`<thead><tr>${e.header.map((n,r)=>$y(`th`,n,e.align[r],t)).join(``)}</tr></thead>`}${e.rows.length?`<tbody>${e.rows.map(n=>`<tr>${n.map((n,r)=>$y(`td`,n,e.align[r],t)).join(``)}</tr>`).join(``)}</tbody>`:``}</table>`;case`footnotes`:return Jy(e.items,t);case`thematicBreak`:return`<hr>`;case`html`:return t.allowHtml?e.value:Zv(e.value);case`callout`:return qy(e,t);case`component`:return Qy(e,t)}}function Uy(e,t={}){let n=eb(e,t);if(n!==void 0)return n;switch(e.type){case`text`:return Zv(e.value);case`inlineCode`:return`<code>${Zv(e.value)}</code>`;case`strong`:return`<strong>${Wy(e.children,t)}</strong>`;case`emphasis`:return`<em>${Wy(e.children,t)}</em>`;case`strike`:return`<del>${Wy(e.children,t)}</del>`;case`footnoteReference`:return`<sup><a id="user-content-fnref-${$(Zy(e))}" data-footnote-ref="" aria-describedby="footnote-label" href="#user-content-fn-${$(e.id)}">${e.number}</a></sup>`;case`link`:return`<a href="${$(e.href)}"${e.title?` title="${$(e.title)}"`:``}>${Wy(e.children,t)}</a>`;case`image`:return`<img src="${$(e.src)}" alt="${$(e.alt)}"${e.title?` title="${$(e.title)}"`:``}>`;case`break`:return`<br>`;case`inlineHtml`:return t.allowHtml?e.value:Zv(e.value)}}function Wy(e,t){return e.map(e=>Uy(e,t)).join(``)}function Gy(e,t){let n=e.lang??`plaintext`,r=[`class="tm-code${t.codeLineNumbers?` tm-code--line-numbers`:``}"`,`data-lang="${$(n)}"`,e.title?`data-code-title="${$(e.title)}"`:``,e.file?`data-filename="${$(e.file)}"`:``,e.framework?`data-framework="${$(e.framework)}"`:``].filter(Boolean).join(` `),i=t.highlighter?.(e.value,n,{...e.highlightLines&&{highlightLines:e.highlightLines},...t.codeLineNumbers!==void 0&&{lineNumbers:t.codeLineNumbers}})??Zv(e.value),a=`<pre ${r}><code class="language-${$(n)}">${i}</code></pre>`;return e.title?`<figure class="tm-code-frame" data-lang="${$(n)}"><figcaption>${Zv(e.title)}</figcaption>${a}</figure>`:a}function Ky(e,t,n,r){let i=e[0],a=t===void 0?``:`<input type="checkbox" disabled${t?` checked`:``}> `;if(i?.type===`paragraph`){let t=`${a}${Wy(i.children,r)}`,o=e.length>1?`\n${e.slice(1).map(e=>Hy(e,r)).join(`
43
- `)}`:``;return`${n?`<p>${t}</p>`:t}${o}`}return`${a}${e.map(e=>Hy(e,r)).join(`
44
- `)}`}function qy(e,t){let n=e.kind.toLowerCase(),r=e.children.map(e=>Hy(e,t)).join(`
45
- `);return`<div class="markdown-alert markdown-alert-${$(n)}"><p class="markdown-alert-title">${Zv(e.title)}</p><div class="markdown-alert-content">${r}</div></div>`}function Jy(e,t){let n=e.map(e=>`<li id="user-content-fn-${$(e.id)}">\n${Yy(e,t)}\n</li>`).join(`
46
- `);return`<section data-footnotes="" class="footnotes"><h2 id="footnote-label" class="sr-only">Footnotes${tb(`footnote-label`,t)}</h2>\n<ol>\n${n}\n</ol>\n</section>`}function Yy(e,t){let n=Xy(e),r=e.children.length-1;return r<0?`<p>${n.trimStart()}</p>`:e.children.map((e,i)=>i===r&&e.type===`paragraph`?`<p>${Wy(e.children,t)}${n}</p>`:Hy(e,t)).join(`
47
- `)}function Xy(e){let t=``;for(let n=1;n<=(e.referenceCount??1);n++){let r=n===1?e.id:`${e.id}-${n}`,i=n===1?`${e.number}`:`${e.number}-${n}`;t+=` <a data-footnote-backref="" aria-label="Back to reference ${i}" class="data-footnote-backref" href="#user-content-fnref-${$(r)}">&#8617;</a>`}return t}function Zy(e){return e.referenceIndex&&e.referenceIndex>1?`${e.id}-${e.referenceIndex}`:e.id}function Qy(e,t){let n=e.tagName??`md-comment-component`;return`<${n}${nb(e)}>${e.children.map(e=>Hy(e,t)).join(`
48
- `)}</${n}>`}function $y(e,t,n,r){return`<${e}${n?` style="text-align:${n}"`:``}>${Wy(t.children,r)}</${e}>`}function eb(e,t){for(let n of t.extensions??[]){let r=n.renderHtml?.(e,{options:t,renderBlock:e=>Hy(e,t),renderInline:e=>Uy(e,t)});if(r!==void 0)return r}}function tb(e,t){let n=t.headingAnchors;if(!e||!n)return``;let r=typeof n==`object`?n:{};return`<a href="#${$(e)}" aria-hidden="${r.ariaHidden??!0}" class="${$(r.className??`anchor-heading anchor-heading-link`)}" tabindex="${r.tabIndex??-1}">${Zv(r.content??`#`)}</a>`}function nb(e){let t={...e.properties};e.tagName||(t[`data-component`]=e.name,t[`data-attributes`]||=JSON.stringify(e.attributes));let n=Object.entries(t);return n.length?` ${n.map(([e,t])=>`${e}="${$(t)}"`).join(` `)}`:``}var rb=async e=>{let{replicache:n,spriteId:r,spriteBuildId:i,signal:a}=e;return a?.aborted?Error(`Publish sprite aborted`):t(async()=>(await n.mutate.spriteBuild_publish_v2({spriteBuildId:i,context:{actionedAt:Date.now()}}),await n.push({now:!0}),{spriteId:r,spriteBuildId:i}))},ib=new Set([`$$slots`,`$$events`,`$$legacy`,`$$host`]);function ab(e,t){let n=l.rest_props(t,ib),r=[[`path`,{d:`M21 12a9 9 0 1 1-6.219-8.56`}]];l_(e,l.spread_props({name:`loader-circle`},()=>n,{get iconNode(){return r}}))}l.create_custom_element(ab,{},[],[],{mode:`open`});var ob=l.from_html(`<span class="loader-circle svelte-galthg" aria-hidden="true"><!></span>`),sb={hash:`svelte-galthg`,code:`.loader-circle.svelte-galthg {display:inline-flex;
34
+ `),...jy(i)}}parseHeading(){let e=this.current().match(/^ {0,3}(#{1,6})(?:[ \t]+(.*)|[ \t]*)$/);if(!e)return;let t=e[1].length,n=e[2]??``,r=sy((/^#+[ \t]*$/.test(n)?``:n.replace(/[ \t]+#+[ \t]*$/,``)).trim(),this.options),i=this.createHeadingId(r);return this.index++,i?{type:`heading`,depth:t,id:i,children:r}:{type:`heading`,depth:t,children:r}}parseThematicBreak(){if(/^ {0,3}([-*_])(?:\s*\1){2,}\s*$/.test(this.current()))return this.index++,{type:`thematicBreak`}}parseBlockquote(){if(!/^ {0,3}>\s?/.test(this.current()))return;let t=[];for(;this.index<this.lines.length;){let e=this.current();if(ey(e)){t.push(``),this.index++;continue}let n=e.match(/^ {0,3}>\s?(.*)$/);if(!n)break;t.push(n[1]),this.index++}return{type:`blockquote`,children:new e(t,this.options,this.slugger,this.budget).parse()}}parseList(){let t=Fy(this.current());if(!t)return;let n=[],r=t.ordered,i=t.indent,a=r?t.number:void 0,o=!1;for(;this.index<this.lines.length;){let r=Fy(this.current());if(!r||!Iy(r,t)||r.indent!==i)break;let a=r.content,s=a.match(/^\[([ xX])\]\s+(.*)$/),c=s?s[1].toLowerCase()===`x`:void 0;s&&(a=s[2]);let l=[a];for(this.index++;this.index<this.lines.length;){let e=this.current(),n=Fy(e);if(n&&n.indent===i)break;if(ey(e)){let e=this.index;for(;e<this.lines.length&&ey(this.lines[e]);)e++;let n=this.lines[e];if(n===void 0)break;let a=Fy(n);if(a?.indent===i){if(!Iy(a,t))break;o=!0,this.index=e;break}if(Ly(n)<r.contentIndent)break;o=!0,l.push(``),this.index=e;continue}if(Ly(e)>=r.contentIndent){l.push(ty(e,r.contentIndent)),this.index++;continue}if(Ry(e,this.next()))break;l.push(e.trimStart()),this.index++}let u={type:`listItem`,children:new e(l,this.options,this.slugger,this.budget).parse()};c!==void 0&&(u.checked=c),n.push(u)}return{type:`list`,ordered:r,...r&&a!==void 0?{start:a}:{},...o&&{loose:!0},items:n}}parseTable(){let e=this.current(),t=this.next();if(!t||!zy(e,t))return;let n=By(e),r=By(t).map(Vy),i=n.length,a=[];for(this.index+=2;this.index<this.lines.length;){let e=this.current();if(ey(e)||Ry(e,this.next()))break;let t=By(e);a.push(Array.from({length:i},(e,n)=>Hy(t[n]??``,this.options))),this.index++}return{type:`table`,align:r,header:n.map(e=>Hy(e,this.options)),rows:a}}parseHtmlBlock(){if(!this.options.allowHtml||!/^ {0,3}<([A-Za-z][\w:-]*|!--|\/[A-Za-z])/.test(this.current()))return;let e=[];if(/^ {0,3}<!--/.test(this.current())){for(;this.index<this.lines.length;){let t=this.current();if(e.push(t),this.index++,t.includes(`-->`))break}return{type:`html`,value:e.join(`
35
+ `)}}for(;this.index<this.lines.length&&!ey(this.current());)e.push(this.current()),this.index++;return{type:`html`,value:e.join(`
36
+ `)}}parseParagraph(){let e=[];for(;this.index<this.lines.length;){let t=this.current();if(ey(t)||e.length>0&&Ry(t,this.next()))break;e.push(t.trim()),this.index++}return{type:`paragraph`,children:sy(e.join(`
37
+ `),this.options)}}createHeadingId(e){if(this.options.headingIds===!1)return;let t=ny(e);return typeof this.options.headingIds==`function`?this.options.headingIds(t,this.index):this.slugger(t)}current(){return this.lines[this.index]??``}next(){return this.lines[this.index+1]}};function jy(e){if(!e)return{};let t=e.match(/^([A-Za-z0-9_+.#-]+)/)?.[1],n=t?e.slice(t.length).trim():e,r=n.match(/(?:^|\s)(?:title|file)=(?:"([^"]+)"|'([^']+)'|([^\s}]+))/),i=n.match(/(?:^|\s)framework=(?:"([^"]+)"|'([^']+)'|([^\s}]+))/),a=n.match(/\{([^}]+)\}|(?:^|\s)lines=([^\s]+)/),o=Py(a?.[1]??a?.[2]??``),s=r?r[1]??r[2]??r[3]:void 0,c=i?i[1]??i[2]??i[3]:void 0;return{...t?{lang:t}:{},...n?{meta:n}:{},...s?{title:s,file:s}:{},...c?{framework:c.toLowerCase()}:{},...o.length?{highlightLines:o}:{}}}function My(e){let t=Object.create(null),n=Object.create(null),r=new Map,i=[],a,o=0,s=0;for(;s<e.length;){let c=e[s],l=c.match(/^ {0,3}(`{3,}|~{3,})/);if(l){let e=l[1][0];a?e===a&&l[1].length>=o&&(a=void 0,o=0):(a=e,o=l[1].length),i.push(c),s++;continue}if(!a){let i=c.match(/^ {0,3}\[\^([^\]\n]+)\]:[ \t]*(.*)$/);if(i){let t=i[1],a=[i[2]??``];for(s++;s<e.length;){let t=e[s];if(!/^(?: {4,}|\t)/.test(t))break;a.push(t.replace(/^(?: {4}|\t)/,``)),s++}let o=ay(t);if(!n[o]){let e=oy(t)||`footnote`,i=(r.get(e)??0)+1;r.set(e,i),n[o]={label:t,content:a.join(`
38
+ `),id:i===1?e:`${e}-${i}`}}continue}let a=c.match(/^ {0,3}\[([^\]\n]+)\]:[ \t]*(\S+)(?:[ \t]+(?:"([^"]*)"|'([^']*)'|\(([^)]*)\)))?[ \t]*$/);if(a){let e=a[3]??a[4]??a[5];t[ay(a[1])]={href:a[2].replace(/^<|>$/g,``),...e===void 0?{}:{title:e}},s++;continue}}i.push(c),s++}return{lines:i,references:t,footnotes:n}}function Ny(e,t,n){let r=[];for(let i=0;i<t.length;i++){let a=e[t[i]];a&&r.push({id:a.id??(oy(a.label)||`footnote`),number:i+1,children:new Ay(Qv(a.content).split(`
39
+ `),n,ry()).parse()})}for(let e of r){let r=n.footnoteCounts?.[t[e.number-1]]??1;r>1&&(e.referenceCount=r)}return{type:`footnotes`,items:r}}function Py(e){let t=new Set;for(let n of e.split(`,`)){let e=n.trim().match(/^(\d+)(?:-(\d+))?$/);if(!e)continue;let r=Number(e[1]),i=Number(e[2]??e[1]);for(let e=r;e<=i&&e<r+1e3;e++)t.add(e)}return[...t].sort((e,t)=>e-t)}function Fy(e){let t=e.match(/^(\s{0,8})([-+*]|\d{1,9}[.)])(?:([ \t]+)(.*))?$/);if(!t)return;let n=t[2],r=/\d/.test(n[0]);return{ordered:r,...r?{number:Number.parseInt(n,10)}:{},indent:t[1].length,marker:r?n.at(-1):n,contentIndent:t[1].length+n.length+(t[3]?.length??1),content:t[4]??``}}function Iy(e,t){return e.ordered===t.ordered&&e.marker===t.marker}function Ly(e){return e.match(/^ */)?.[0].length??0}function Ry(e,t){let n=Fy(e);return/^ {0,3}(`{3,}|~{3,})/.test(e)||/^ {0,3}#{1,6}(?:\s+|$)/.test(e)||/^ {0,3}([-*_])(?:\s*\1){2,}\s*$/.test(e)||/^ {0,3}>\s?/.test(e)||n!==void 0&&(!n.ordered||n.number===1)||!!t&&zy(e,t)}function zy(e,t){if(!e.includes(`|`))return!1;let n=By(t);return n.length===By(e).length&&n.every(e=>/^:?-+:?$/.test(e.trim()))}function By(e){let t=e.trim();t.startsWith(`|`)&&(t=t.slice(1)),t.endsWith(`|`)&&(t=t.slice(0,-1));let n=[],r=``;for(let e=0;e<t.length;e++){let i=t[e];if(i===`\\`&&t[e+1]===`|`){r+=`|`,e++;continue}if(i===`|`){n.push(r.trim()),r=``;continue}r+=i}return n.push(r.trim()),n}function Vy(e){let t=e.trim();if(t.startsWith(`:`)&&t.endsWith(`:`))return`center`;if(t.endsWith(`:`))return`right`;if(t.startsWith(`:`))return`left`}function Hy(e,t){return{type:`tableCell`,children:sy(e,t)}}function Uy(e,t={}){return(typeof e==`string`?ky(e,t):e).children.map(e=>Wy(e,t)).join(`
40
+ `)}function Wy(e,t={}){let n=nb(e,t);if(n!==void 0)return n;switch(e.type){case`heading`:{let n=e.id?` id="${$(e.id)}"`:``,r=e.framework?` data-framework="${$(e.framework)}"`:``;return`<h${e.depth}${n}${r}>${Ky(e.children,t)}${rb(e.id,t)}</h${e.depth}>`}case`paragraph`:return`<p>${Ky(e.children,t)}</p>`;case`code`:return qy(e,t);case`list`:{let n=e.ordered?`ol`:`ul`;return`<${n}${e.ordered&&e.start&&e.start!==1?` start="${e.start}"`:``}>\n${e.items.map(n=>`<li>${Jy(n.children,n.checked,e.loose,t)}</li>`).join(`
41
+ `)}\n</${n}>`}case`blockquote`:return`<blockquote>\n${e.children.map(e=>Wy(e,t)).join(`
42
+ `)}\n</blockquote>`;case`table`:return`<table>${`<thead><tr>${e.header.map((n,r)=>tb(`th`,n,e.align[r],t)).join(``)}</tr></thead>`}${e.rows.length?`<tbody>${e.rows.map(n=>`<tr>${n.map((n,r)=>tb(`td`,n,e.align[r],t)).join(``)}</tr>`).join(``)}</tbody>`:``}</table>`;case`footnotes`:return Xy(e.items,t);case`thematicBreak`:return`<hr>`;case`html`:return t.allowHtml?e.value:$v(e.value);case`callout`:return Yy(e,t);case`component`:return eb(e,t)}}function Gy(e,t={}){let n=nb(e,t);if(n!==void 0)return n;switch(e.type){case`text`:return $v(e.value);case`inlineCode`:return`<code>${$v(e.value)}</code>`;case`strong`:return`<strong>${Ky(e.children,t)}</strong>`;case`emphasis`:return`<em>${Ky(e.children,t)}</em>`;case`strike`:return`<del>${Ky(e.children,t)}</del>`;case`footnoteReference`:return`<sup><a id="user-content-fnref-${$($y(e))}" data-footnote-ref="" aria-describedby="footnote-label" href="#user-content-fn-${$(e.id)}">${e.number}</a></sup>`;case`link`:return`<a href="${$(e.href)}"${e.title?` title="${$(e.title)}"`:``}>${Ky(e.children,t)}</a>`;case`image`:return`<img src="${$(e.src)}" alt="${$(e.alt)}"${e.title?` title="${$(e.title)}"`:``}>`;case`break`:return`<br>`;case`inlineHtml`:return t.allowHtml?e.value:$v(e.value)}}function Ky(e,t){return e.map(e=>Gy(e,t)).join(``)}function qy(e,t){let n=e.lang??`plaintext`,r=[`class="tm-code${t.codeLineNumbers?` tm-code--line-numbers`:``}"`,`data-lang="${$(n)}"`,e.title?`data-code-title="${$(e.title)}"`:``,e.file?`data-filename="${$(e.file)}"`:``,e.framework?`data-framework="${$(e.framework)}"`:``].filter(Boolean).join(` `),i=t.highlighter?.(e.value,n,{...e.highlightLines&&{highlightLines:e.highlightLines},...t.codeLineNumbers!==void 0&&{lineNumbers:t.codeLineNumbers}})??$v(e.value),a=`<pre ${r}><code class="language-${$(n)}">${i}</code></pre>`;return e.title?`<figure class="tm-code-frame" data-lang="${$(n)}"><figcaption>${$v(e.title)}</figcaption>${a}</figure>`:a}function Jy(e,t,n,r){let i=e[0],a=t===void 0?``:`<input type="checkbox" disabled${t?` checked`:``}> `;if(i?.type===`paragraph`){let t=`${a}${Ky(i.children,r)}`,o=e.length>1?`\n${e.slice(1).map(e=>Wy(e,r)).join(`
43
+ `)}`:``;return`${n?`<p>${t}</p>`:t}${o}`}return`${a}${e.map(e=>Wy(e,r)).join(`
44
+ `)}`}function Yy(e,t){let n=e.kind.toLowerCase(),r=e.children.map(e=>Wy(e,t)).join(`
45
+ `);return`<div class="markdown-alert markdown-alert-${$(n)}"><p class="markdown-alert-title">${$v(e.title)}</p><div class="markdown-alert-content">${r}</div></div>`}function Xy(e,t){let n=e.map(e=>`<li id="user-content-fn-${$(e.id)}">\n${Zy(e,t)}\n</li>`).join(`
46
+ `);return`<section data-footnotes="" class="footnotes"><h2 id="footnote-label" class="sr-only">Footnotes${rb(`footnote-label`,t)}</h2>\n<ol>\n${n}\n</ol>\n</section>`}function Zy(e,t){let n=Qy(e),r=e.children.length-1;return r<0?`<p>${n.trimStart()}</p>`:e.children.map((e,i)=>i===r&&e.type===`paragraph`?`<p>${Ky(e.children,t)}${n}</p>`:Wy(e,t)).join(`
47
+ `)}function Qy(e){let t=``;for(let n=1;n<=(e.referenceCount??1);n++){let r=n===1?e.id:`${e.id}-${n}`,i=n===1?`${e.number}`:`${e.number}-${n}`;t+=` <a data-footnote-backref="" aria-label="Back to reference ${i}" class="data-footnote-backref" href="#user-content-fnref-${$(r)}">&#8617;</a>`}return t}function $y(e){return e.referenceIndex&&e.referenceIndex>1?`${e.id}-${e.referenceIndex}`:e.id}function eb(e,t){let n=e.tagName??`md-comment-component`;return`<${n}${ib(e)}>${e.children.map(e=>Wy(e,t)).join(`
48
+ `)}</${n}>`}function tb(e,t,n,r){return`<${e}${n?` style="text-align:${n}"`:``}>${Ky(t.children,r)}</${e}>`}function nb(e,t){for(let n of t.extensions??[]){let r=n.renderHtml?.(e,{options:t,renderBlock:e=>Wy(e,t),renderInline:e=>Gy(e,t)});if(r!==void 0)return r}}function rb(e,t){let n=t.headingAnchors;if(!e||!n)return``;let r=typeof n==`object`?n:{};return`<a href="#${$(e)}" aria-hidden="${r.ariaHidden??!0}" class="${$(r.className??`anchor-heading anchor-heading-link`)}" tabindex="${r.tabIndex??-1}">${$v(r.content??`#`)}</a>`}function ib(e){let t={...e.properties};e.tagName||(t[`data-component`]=e.name,t[`data-attributes`]||=JSON.stringify(e.attributes));let n=Object.entries(t);return n.length?` ${n.map(([e,t])=>`${e}="${$(t)}"`).join(` `)}`:``}var ab=async e=>{let{replicache:n,spriteId:r,spriteBuildId:i,signal:a}=e;return a?.aborted?Error(`Publish sprite aborted`):t(async()=>(await n.mutate.spriteBuild_publish_v2({spriteBuildId:i,context:{actionedAt:Date.now()}}),await n.push({now:!0}),{spriteId:r,spriteBuildId:i}))},ob=new Set([`$$slots`,`$$events`,`$$legacy`,`$$host`]);function sb(e,t){let n=l.rest_props(t,ob),r=[[`path`,{d:`M21 12a9 9 0 1 1-6.219-8.56`}]];d_(e,l.spread_props({name:`loader-circle`},()=>n,{get iconNode(){return r}}))}l.create_custom_element(sb,{},[],[],{mode:`open`});var cb=l.from_html(`<span class="loader-circle svelte-galthg" aria-hidden="true"><!></span>`),lb={hash:`svelte-galthg`,code:`.loader-circle.svelte-galthg {display:inline-flex;
49
49
  animation: svelte-galthg-spin 700ms linear infinite;}
50
50
 
51
51
  @keyframes svelte-galthg-spin {
52
52
  to {
53
53
  transform: rotate(360deg);
54
54
  }
55
- }`};function cb(e){l.append_styles(e,sb);var t=ob();ab(l.child(t),{size:16}),l.reset(t),l.append(e,t)}l.create_custom_element(cb,{},[],[],{mode:`open`});var lb=e=>{let t=l.state(e.value);return l.user_effect(()=>Ve(`watch(${e.name})`,()=>{l.set(t,e.value)})),{get _(){return l.get(t)}}};lb.undefined={_:void 0},lb.lit=e=>({_:e});var ub=l.from_html(`<div class="summary dots svelte-qp0d57">Planning</div>`),db=l.from_html(`<span class="svelte-qp0d57">Done</span>`),fb=l.from_html(`<span class="cancel-duration svelte-qp0d57"> </span>`),pb=l.from_html(`<span class="cancel-label svelte-qp0d57"><span class="svelte-qp0d57">Canceled</span> <!></span>`),mb=l.from_html(`<span class="svelte-qp0d57">Failed</span>`),hb=l.from_html(`<span class="chip svelte-qp0d57"> </span>`),gb=l.from_html(`<span class="svelte-qp0d57"> </span> <!>`,1),_b=l.from_html(`<span class="phase svelte-qp0d57"> </span>`),vb=l.from_html(`<div class="trailing svelte-qp0d57"><!></div>`),yb=l.from_html(`<span class="dots svelte-qp0d57"></span>`),bb=l.from_html(`<div class="summary svelte-qp0d57"> <!></div>`),xb=l.from_html(`<div class="summary placeholder svelte-qp0d57">Just getting started<span class="dots svelte-qp0d57"></span></div>`),Sb=l.from_html(`<div class="top svelte-qp0d57"><div class="label svelte-qp0d57"><!></div> <!></div> <!>`,1),Cb=l.from_html(`<div><!></div>`),wb={hash:`svelte-qp0d57`,code:`.card.svelte-qp0d57 {display:flex;gap:0.4rem;flex-direction:column;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-lg, 0.625rem);padding:0.75rem 1rem;background:var(--rough-card, white);box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));}.top.svelte-qp0d57 {display:flex;align-items:center;justify-content:space-between;gap:0.75rem;color:var(--rough-muted-foreground, oklch(0.556 0 0));font-weight:600;}.label.svelte-qp0d57 {display:inline-flex;align-items:center;gap:0.5rem;min-width:0;}.trailing.svelte-qp0d57 {display:inline-flex;align-items:center;gap:0.5rem;color:var(--rough-muted-foreground, oklch(0.556 0 0));}.chip.svelte-qp0d57 {max-width:16rem;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-sm, 0.25rem);padding:0.1rem 0.45rem;overflow:hidden;background:var(--rough-muted, oklch(0.97 0 0));color:var(--rough-muted-foreground, oklch(0.556 0 0));font-family:ui-monospace, SFMono-Regular, Menlo, monospace;font-size:0.75rem;font-weight:500;white-space:nowrap;text-overflow:ellipsis;}.phase.svelte-qp0d57 {text-transform:capitalize;}.cancel-label.svelte-qp0d57 {display:inline-flex;gap:0.25em;align-items:baseline;}.cancel-duration.svelte-qp0d57 {font-weight:400;}.summary.svelte-qp0d57 {color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:0.875rem;line-height:1.45;word-break:break-word;}.summary.placeholder.svelte-qp0d57 {color:color-mix(in oklch, var(--rough-muted-foreground, oklch(0.556 0 0)) 60%, transparent);}.terminal.svelte-qp0d57 .label:where(.svelte-qp0d57) {color:var(--rough-foreground, oklch(0.145 0 0));}.failed.svelte-qp0d57 .label:where(.svelte-qp0d57) {color:var(--rough-destructive, oklch(0.577 0.245 27.325));}.dots.svelte-qp0d57::after {content:'';
55
+ }`};function ub(e){l.append_styles(e,lb);var t=cb();sb(l.child(t),{size:16}),l.reset(t),l.append(e,t)}l.create_custom_element(ub,{},[],[],{mode:`open`});var db=e=>{let t=l.state(e.value);return l.user_effect(()=>Be(`watch(${e.name})`,()=>{l.set(t,e.value)})),{get _(){return l.get(t)}}};db.undefined={_:void 0},db.lit=e=>({_:e});var fb=l.from_html(`<div class="summary dots svelte-qp0d57">Planning</div>`),pb=l.from_html(`<span class="svelte-qp0d57">Done</span>`),mb=l.from_html(`<span class="cancel-duration svelte-qp0d57"> </span>`),hb=l.from_html(`<span class="cancel-label svelte-qp0d57"><span class="svelte-qp0d57">Canceled</span> <!></span>`),gb=l.from_html(`<span class="svelte-qp0d57">Failed</span>`),_b=l.from_html(`<span class="chip svelte-qp0d57"> </span>`),vb=l.from_html(`<span class="svelte-qp0d57"> </span> <!>`,1),yb=l.from_html(`<span class="phase svelte-qp0d57"> </span>`),bb=l.from_html(`<div class="trailing svelte-qp0d57"><!></div>`),xb=l.from_html(`<span class="dots svelte-qp0d57"></span>`),Sb=l.from_html(`<div class="summary svelte-qp0d57"> <!></div>`),Cb=l.from_html(`<div class="summary placeholder svelte-qp0d57">Just getting started<span class="dots svelte-qp0d57"></span></div>`),wb=l.from_html(`<div class="top svelte-qp0d57"><div class="label svelte-qp0d57"><!></div> <!></div> <!>`,1),Tb=l.from_html(`<div><!></div>`),Eb={hash:`svelte-qp0d57`,code:`.card.svelte-qp0d57 {display:flex;gap:0.4rem;flex-direction:column;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-lg, 0.625rem);padding:0.75rem 1rem;background:var(--rough-card, white);box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));}.top.svelte-qp0d57 {display:flex;align-items:center;justify-content:space-between;gap:0.75rem;color:var(--rough-muted-foreground, oklch(0.556 0 0));font-weight:600;}.label.svelte-qp0d57 {display:inline-flex;align-items:center;gap:0.5rem;min-width:0;}.trailing.svelte-qp0d57 {display:inline-flex;align-items:center;gap:0.5rem;color:var(--rough-muted-foreground, oklch(0.556 0 0));}.chip.svelte-qp0d57 {max-width:16rem;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-sm, 0.25rem);padding:0.1rem 0.45rem;overflow:hidden;background:var(--rough-muted, oklch(0.97 0 0));color:var(--rough-muted-foreground, oklch(0.556 0 0));font-family:ui-monospace, SFMono-Regular, Menlo, monospace;font-size:0.75rem;font-weight:500;white-space:nowrap;text-overflow:ellipsis;}.phase.svelte-qp0d57 {text-transform:capitalize;}.cancel-label.svelte-qp0d57 {display:inline-flex;gap:0.25em;align-items:baseline;}.cancel-duration.svelte-qp0d57 {font-weight:400;}.summary.svelte-qp0d57 {color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:0.875rem;line-height:1.45;word-break:break-word;}.summary.placeholder.svelte-qp0d57 {color:color-mix(in oklch, var(--rough-muted-foreground, oklch(0.556 0 0)) 60%, transparent);}.terminal.svelte-qp0d57 .label:where(.svelte-qp0d57) {color:var(--rough-foreground, oklch(0.145 0 0));}.failed.svelte-qp0d57 .label:where(.svelte-qp0d57) {color:var(--rough-destructive, oklch(0.577 0.245 27.325));}.dots.svelte-qp0d57::after {content:'';
56
56
  animation: svelte-qp0d57-ellipsis 1.5s steps(4, end) infinite;}
57
57
 
58
58
  @keyframes svelte-qp0d57-ellipsis {
@@ -60,7 +60,7 @@ ${zm(e)}`.trim()},Vm=e=>{let{messageList:t}=e,n=t.flatMap(e=>{if(e.role===`tool`
60
60
  25% { content: '.'; }
61
61
  50% { content: '..'; }
62
62
  75% { content: '...'; }
63
- }`};function Tb(e,t){l.push(t,!0),l.append_styles(e,wb);let n=l.prop(t,`activity`,7),r=l.prop(t,`summaryText`,7),i=l.derived(()=>n().status===`ready`||n().status===`error`||n().status===`canceled`),a=l.derived(()=>n().status===`error`||n().toolOutcome===`failed`||n().phase?.outcome===`failed`);var o={get activity(){return n()},set activity(e){n(e),l.flush()},get summaryText(){return r()},set summaryText(e){r(e),l.flush()}},s=Cb();let c;var u=l.child(s),d=e=>{var t=ub();l.append(e,t)},f=e=>{var t=Sb(),a=l.first_child(t),o=l.child(a),s=l.child(o),c=e=>{var t=db();l.append(e,t)},u=e=>{var t=pb(),r=l.sibling(l.child(t),2),i=e=>{var t=fb(),r=l.child(t);l.reset(t),l.template_effect(()=>l.set_text(r,`after ${n().elapsedSeconds??``} ${n().elapsedSeconds===1?`second`:`seconds`}`)),l.append(e,t)};l.if(r,e=>{n().elapsedSeconds!=null&&e(i)}),l.reset(t),l.append(e,t)},d=e=>{var t=mb();l.append(e,t)},f=e=>{var t=gb(),r=l.first_child(t),i=l.child(r,!0);l.reset(r);var a=l.sibling(r,2),o=e=>{var t=hb(),r=l.child(t,!0);l.reset(t),l.template_effect(()=>l.set_text(r,n().action.filename)),l.append(e,t)};l.if(a,e=>{n().action.filename&&e(o)}),l.template_effect(()=>l.set_text(i,n().action.verb)),l.append(e,t)},p=e=>{var t=_b(),r=l.child(t,!0);l.reset(t),l.template_effect(()=>l.set_text(r,n().phase.name)),l.append(e,t)};l.if(s,e=>{n().status===`ready`?e(c):n().status===`canceled`?e(u,1):n().status===`error`?e(d,2):n().action?e(f,3):n().phase&&e(p,4)}),l.reset(o);var m=l.sibling(o,2),h=e=>{var t=vb();cb(l.child(t),{}),l.reset(t),l.append(e,t)};l.if(m,e=>{n().status===`working`&&!n().toolOutcome&&!n().phase?.outcome&&e(h)}),l.reset(a);var g=l.sibling(a,2),_=e=>{var t=bb(),i=l.child(t,!0),a=l.sibling(i),o=e=>{var t=yb();l.append(e,t)};l.if(a,e=>{n().status===`working`&&e(o)}),l.reset(t),l.template_effect(()=>l.set_text(i,r())),l.append(e,t)},v=e=>{var t=xb();l.append(e,t)};l.if(g,e=>{r()&&!l.get(i)?e(_):n().status===`working`&&e(v,1)}),l.append(e,t)};return l.if(u,e=>{n().status===`idle`?e(d):e(f,-1)}),l.reset(s),l.template_effect(()=>c=l.set_class(s,1,`card svelte-qp0d57`,null,c,{terminal:l.get(i),failed:l.get(a)})),l.append(e,s),l.pop(o)}l.create_custom_element(Tb,{activity:{},summaryText:{}},[],[],{mode:`open`});var Eb=e=>{switch(e.name){case`edit`:return`Editing`;case`write`:return`Writing`;case`read`:return`Reading`;case`bash`:return`Running`;default:return`Using tool`}},Db=(e,t)=>{let{status:n,startedAt:r,stoppedAt:i}=t,a,o,s;for(let t of e){let e=t;switch(e.type){case`AGENT_TOOL_STARTED`:{let{toolCallId:t,tool:n}=e.detail;a={tool:n.name,toolCallId:t,verb:Eb(n),filename:`path`in n?n.path:n.command},o=void 0;break}case`AGENT_TOOL_COMPLETED`:a?.toolCallId===e.detail.toolCallId&&(o=`success`);break;case`AGENT_TOOL_FAILED`:a?.toolCallId===e.detail.toolCallId&&(o=`failed`);break;case`AGENT_STARTED`:s={name:`agent`,outcome:void 0};break;case`AGENT_COMPLETED`:s={name:`agent`,outcome:`success`}}}let c;c=n===`READY`?`ready`:n===`CANCELED`?`canceled`:n===`ERROR`?`error`:a||s?`working`:`idle`;let l=r!=null&&i!=null?Math.max(0,Math.round((i-r)/1e3)):void 0;return{activity:c===`ready`?{status:c}:c===`canceled`?{status:c,elapsedSeconds:l}:{status:c,action:a,toolOutcome:o,phase:s}}},Ob=l.from_html(`<div class="panel pending svelte-rsawb0"><!> <span>Waiting for build to start</span></div>`),kb=l.from_html(`<div class="build-log svelte-rsawb0"><!></div>`),Ab={hash:`svelte-rsawb0`,code:`.build-log.svelte-rsawb0 {display:flex;gap:0.5rem;flex-direction:column;width:100%;}.panel.svelte-rsawb0 {border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-lg, 0.625rem);padding:0.75rem 1rem;background:var(--rough-card, white);box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));}.pending.svelte-rsawb0 {display:flex;align-items:center;gap:0.5rem;color:var(--rough-muted-foreground, oklch(0.556 0 0));font-weight:500;}`};function jb(e,t){l.push(t,!0),l.append_styles(e,Ab);let n=l.prop(t,`client`,7),r=l.prop(t,`spriteBuild`,7),i=l.derived(()=>Xg(n()).store),a=l.derived(()=>lb(l.get(i).spriteBuildEvent.filter(`build-log:${r().id}`,e=>e.spriteBuildId===r().id))),o=l.derived(()=>l.get(a)._),s=l.derived(()=>l.get(o).toSorted((e,t)=>e.actionedAt-t.actionedAt||e.id.localeCompare(t.id)).slice(-100)),c=l.derived(()=>r().status),u=l.derived(()=>Db(l.get(s),r())),d=l.derived(()=>r().reasoningSummary??void 0),f=l.derived(()=>l.get(c)===`PENDING`);var p={get client(){return n()},set client(e){n(e),l.flush()},get spriteBuild(){return r()},set spriteBuild(e){r(e),l.flush()}},m=kb(),h=l.child(m),g=e=>{var t=Ob();cb(l.child(t),{}),l.next(2),l.reset(t),l.append(e,t)},_=e=>{Tb(e,{get activity(){return l.get(u).activity},get summaryText(){return l.get(d)}})};return l.if(h,e=>{l.get(f)?e(g):e(_,-1)}),l.reset(m),l.append(e,m),l.pop(p)}l.create_custom_element(jb,{client:{},spriteBuild:{}},[],[],{mode:`open`});var Mb=100,Nb=new Intl.NumberFormat(`en-US`,{style:`currency`,currency:`USD`,minimumFractionDigits:2,maximumFractionDigits:2}),Pb=e=>{let t=Math.round(e*Mb*10)/10;return Math.abs(t)<Mb?`${t.toFixed(1)}c`:Nb.format(e)},Fb=e=>e.toLowerCase().split(/[_-]+/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `),Ib=e=>{switch(e.name){case`edit`:case`read`:case`write`:return`${e.name} ${e.path}`;case`bash`:return e.command;default:return`tool call`}},Lb=e=>{switch(e?.name){case`bash`:return`command`;case`read`:case`edit`:case`write`:return`path`;default:return`plain`}},Rb=e=>{let t=new Intl.NumberFormat(`en-US`,{maximumFractionDigits:2}),{tokens:n}=e.detail;return[`${e.detail.provider}/${e.detail.model}`,`${t.format(n.input)} input`,`${t.format(n.output)} output`,`${t.format(n.cacheRead)} cache read`,`${t.format(n.cacheWrite)} cache write`,`${t.format(n.total)} total`,Pb(e.detail.estimatedCostUsd)].join(` · `)},zb=e=>{if(!(!e||typeof e!=`object`)){if(`message`in e&&typeof e.message==`string`)return e.message;if(`error`in e&&e.error&&typeof e.error==`object`){let t=zb(e.error);if(t)return t}if(`url`in e&&typeof e.url==`string`)return e.url;if(`command`in e&&typeof e.command==`string`)return e.command}},Bb=e=>{let t=new Map,n=new Map,r=new Map;return e.map(e=>{let i=e,a,o=`plain`,s=`neutral`;switch(i.type){case`STEP_STARTED`:a=Fb(i.detail.stepName),o=`xml-open`,s=`active`;break;case`STEP_COMPLETED`:a=Fb(i.detail.stepName),o=`xml-close`,s=`success`;break;case`STEP_FAILED`:a=zb(i.detail.error)??Fb(i.detail.stepName),s=`error`;break;case`EXEC_STARTED`:n.set(i.detail.execId,{command:i.detail.command,cwd:i.detail.cwd}),a=i.detail.command,o=`command`,s=`active`;break;case`EXEC_COMPLETED`:a=n.get(i.detail.execId)?.command,o=`command`,s=`success`;break;case`EXEC_FAILED`:a=n.get(i.detail.execId)?.command,o=`command`,s=`error`;break;case`FETCH_STARTED`:r.set(i.detail.fetchId,{url:i.detail.url}),a=i.detail.url,s=`active`;break;case`FETCH_COMPLETED`:a=r.get(i.detail.fetchId)?.url,s=`success`;break;case`FETCH_FAILED`:{let e=r.get(i.detail.fetchId);a=zb(i.detail.error)??e?.url,s=`error`;break}case`AGENT_STARTED`:s=`active`;break;case`AGENT_COMPLETED`:s=`success`;break;case`AGENT_USAGE`:a=Rb(i),s=`neutral`;break;case`AGENT_TOOL_STARTED`:t.set(i.detail.toolCallId,i.detail.tool),a=Ib(i.detail.tool),o=Lb(i.detail.tool),s=`active`;break;case`AGENT_TOOL_COMPLETED`:{let e=t.get(i.detail.toolCallId);a=e?Ib(e):i.detail.toolCallId,o=Lb(e),s=`success`;break}case`AGENT_TOOL_FAILED`:{let e=t.get(i.detail.toolCallId);a=e?Ib(e):i.detail.toolCallId,o=Lb(e),s=`error`;break}case`AGENT_META`:a=i.detail.message,s=`neutral`;break;case`AGENT_MESSAGE`:a=i.detail.message,s=`neutral`;break;case`AGENT_THOUGHT`:a=i.detail.message,s=`neutral`;break;default:a=zb(e.detail),s=`neutral`}return{id:e.id,actionedAt:e.actionedAt,type:e.type,detailText:a,detailStyle:o,tone:s}})},Vb=l.from_html(`<div class="polling-indicator svelte-5iw9fb"><!> <span>Live</span></div>`),Hb=l.from_html(`<div class="panel state-panel empty-panel svelte-5iw9fb"><div class="state-title svelte-5iw9fb"><!></div> <div class="state-detail"><!></div></div>`),Ub=l.from_html(`<code class="svelte-5iw9fb"><strong class="svelte-5iw9fb"> </strong> </code>`),Wb=l.from_html(`<code class="svelte-5iw9fb"> </code>`),Gb=l.from_html(`<div><!></div>`),Kb=l.from_html(`<span class="event-detail-empty svelte-5iw9fb">—</span>`),qb=l.from_html(`<li><time class="event-date svelte-5iw9fb"> </time> <div class="event-type-cell svelte-5iw9fb"><span class="event-type svelte-5iw9fb"> </span></div> <div class="event-detail-cell svelte-5iw9fb"><!></div></li>`),Jb=l.from_html(`<ol class="event-list svelte-5iw9fb"></ol>`),Yb=l.from_html(`<div class="detailed-build-log svelte-5iw9fb" aria-live="polite"><div class="header svelte-5iw9fb"><div><div class="eyebrow svelte-5iw9fb">Detailed logs</div> <div class="title svelte-5iw9fb">Build event stream</div></div> <!></div> <!></div>`),Xb={hash:`svelte-5iw9fb`,code:`.detailed-build-log.svelte-5iw9fb {border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-lg, 0.625rem);background:var(--rough-card, white);box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));color:var(--rough-card-foreground, oklch(0.145 0 0));}.header.svelte-5iw9fb {display:flex;align-items:center;justify-content:space-between;gap:1rem;border-bottom:1px solid var(--rough-border, oklch(0.922 0 0));padding:0.85rem 1rem;background:var(--rough-muted, oklch(0.97 0 0));}.eyebrow.svelte-5iw9fb {color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:0.72rem;font-weight:700;text-transform:uppercase;letter-spacing:0.05em;}.title.svelte-5iw9fb {margin-top:0.15rem;color:var(--rough-foreground, oklch(0.145 0 0));font-weight:600;}.polling-indicator.svelte-5iw9fb {display:inline-flex;align-items:center;gap:0.45rem;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:999px;padding:0.15rem 0.55rem;background:var(--rough-background, white);color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:0.8rem;font-weight:600;}.panel.svelte-5iw9fb {padding:0.85rem 1rem;}.state-panel.svelte-5iw9fb {display:flex;gap:0.35rem;flex-direction:column;color:var(--rough-muted-foreground, oklch(0.556 0 0));}.state-title.svelte-5iw9fb {color:var(--rough-foreground, oklch(0.145 0 0));font-weight:600;}.event-list.svelte-5iw9fb {display:grid;grid-template-columns:minmax(7.5rem, auto) minmax(12rem, auto) minmax(0, 1fr);margin:0;padding:0;list-style:none;}.event.svelte-5iw9fb {display:contents;}.event-date.svelte-5iw9fb,
63
+ }`};function Db(e,t){l.push(t,!0),l.append_styles(e,Eb);let n=l.prop(t,`activity`,7),r=l.prop(t,`summaryText`,7),i=l.derived(()=>n().status===`ready`||n().status===`error`||n().status===`canceled`),a=l.derived(()=>n().status===`error`||n().toolOutcome===`failed`||n().phase?.outcome===`failed`);var o={get activity(){return n()},set activity(e){n(e),l.flush()},get summaryText(){return r()},set summaryText(e){r(e),l.flush()}},s=Tb();let c;var u=l.child(s),d=e=>{var t=fb();l.append(e,t)},f=e=>{var t=wb(),a=l.first_child(t),o=l.child(a),s=l.child(o),c=e=>{var t=pb();l.append(e,t)},u=e=>{var t=hb(),r=l.sibling(l.child(t),2),i=e=>{var t=mb(),r=l.child(t);l.reset(t),l.template_effect(()=>l.set_text(r,`after ${n().elapsedSeconds??``} ${n().elapsedSeconds===1?`second`:`seconds`}`)),l.append(e,t)};l.if(r,e=>{n().elapsedSeconds!=null&&e(i)}),l.reset(t),l.append(e,t)},d=e=>{var t=gb();l.append(e,t)},f=e=>{var t=vb(),r=l.first_child(t),i=l.child(r,!0);l.reset(r);var a=l.sibling(r,2),o=e=>{var t=_b(),r=l.child(t,!0);l.reset(t),l.template_effect(()=>l.set_text(r,n().action.filename)),l.append(e,t)};l.if(a,e=>{n().action.filename&&e(o)}),l.template_effect(()=>l.set_text(i,n().action.verb)),l.append(e,t)},p=e=>{var t=yb(),r=l.child(t,!0);l.reset(t),l.template_effect(()=>l.set_text(r,n().phase.name)),l.append(e,t)};l.if(s,e=>{n().status===`ready`?e(c):n().status===`canceled`?e(u,1):n().status===`error`?e(d,2):n().action?e(f,3):n().phase&&e(p,4)}),l.reset(o);var m=l.sibling(o,2),h=e=>{var t=bb();ub(l.child(t),{}),l.reset(t),l.append(e,t)};l.if(m,e=>{n().status===`working`&&!n().toolOutcome&&!n().phase?.outcome&&e(h)}),l.reset(a);var g=l.sibling(a,2),_=e=>{var t=Sb(),i=l.child(t,!0),a=l.sibling(i),o=e=>{var t=xb();l.append(e,t)};l.if(a,e=>{n().status===`working`&&e(o)}),l.reset(t),l.template_effect(()=>l.set_text(i,r())),l.append(e,t)},v=e=>{var t=Cb();l.append(e,t)};l.if(g,e=>{r()&&!l.get(i)?e(_):n().status===`working`&&e(v,1)}),l.append(e,t)};return l.if(u,e=>{n().status===`idle`?e(d):e(f,-1)}),l.reset(s),l.template_effect(()=>c=l.set_class(s,1,`card svelte-qp0d57`,null,c,{terminal:l.get(i),failed:l.get(a)})),l.append(e,s),l.pop(o)}l.create_custom_element(Db,{activity:{},summaryText:{}},[],[],{mode:`open`});var Ob=e=>{switch(e.name){case`edit`:return`Editing`;case`write`:return`Writing`;case`read`:return`Reading`;case`bash`:return`Running`;default:return`Using tool`}},kb=(e,t)=>{let{status:n,startedAt:r,stoppedAt:i}=t,a,o,s;for(let t of e){let e=t;switch(e.type){case`AGENT_TOOL_STARTED`:{let{toolCallId:t,tool:n}=e.detail;a={tool:n.name,toolCallId:t,verb:Ob(n),filename:`path`in n?n.path:n.command},o=void 0;break}case`AGENT_TOOL_COMPLETED`:a?.toolCallId===e.detail.toolCallId&&(o=`success`);break;case`AGENT_TOOL_FAILED`:a?.toolCallId===e.detail.toolCallId&&(o=`failed`);break;case`AGENT_STARTED`:s={name:`agent`,outcome:void 0};break;case`AGENT_COMPLETED`:s={name:`agent`,outcome:`success`}}}let c;c=n===`READY`?`ready`:n===`CANCELED`?`canceled`:n===`ERROR`?`error`:a||s?`working`:`idle`;let l=r!=null&&i!=null?Math.max(0,Math.round((i-r)/1e3)):void 0;return{activity:c===`ready`?{status:c}:c===`canceled`?{status:c,elapsedSeconds:l}:{status:c,action:a,toolOutcome:o,phase:s}}},Ab=l.from_html(`<div class="panel pending svelte-rsawb0"><!> <span>Waiting for build to start</span></div>`),jb=l.from_html(`<div class="build-log svelte-rsawb0"><!></div>`),Mb={hash:`svelte-rsawb0`,code:`.build-log.svelte-rsawb0 {display:flex;gap:0.5rem;flex-direction:column;width:100%;}.panel.svelte-rsawb0 {border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-lg, 0.625rem);padding:0.75rem 1rem;background:var(--rough-card, white);box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));}.pending.svelte-rsawb0 {display:flex;align-items:center;gap:0.5rem;color:var(--rough-muted-foreground, oklch(0.556 0 0));font-weight:500;}`};function Nb(e,t){l.push(t,!0),l.append_styles(e,Mb);let n=l.prop(t,`client`,7),r=l.prop(t,`spriteBuild`,7),i=l.derived(()=>Qg(n()).store),a=l.derived(()=>db(l.get(i).spriteBuildEvent.filter(`build-log:${r().id}`,e=>e.spriteBuildId===r().id))),o=l.derived(()=>l.get(a)._),s=l.derived(()=>l.get(o).toSorted((e,t)=>e.actionedAt-t.actionedAt||e.id.localeCompare(t.id)).slice(-100)),c=l.derived(()=>r().status),u=l.derived(()=>kb(l.get(s),r())),d=l.derived(()=>r().reasoningSummary??void 0),f=l.derived(()=>l.get(c)===`PENDING`);var p={get client(){return n()},set client(e){n(e),l.flush()},get spriteBuild(){return r()},set spriteBuild(e){r(e),l.flush()}},m=jb(),h=l.child(m),g=e=>{var t=Ab();ub(l.child(t),{}),l.next(2),l.reset(t),l.append(e,t)},_=e=>{Db(e,{get activity(){return l.get(u).activity},get summaryText(){return l.get(d)}})};return l.if(h,e=>{l.get(f)?e(g):e(_,-1)}),l.reset(m),l.append(e,m),l.pop(p)}l.create_custom_element(Nb,{client:{},spriteBuild:{}},[],[],{mode:`open`});var Pb=100,Fb=new Intl.NumberFormat(`en-US`,{style:`currency`,currency:`USD`,minimumFractionDigits:2,maximumFractionDigits:2}),Ib=e=>{let t=Math.round(e*Pb*10)/10;return Math.abs(t)<Pb?`${t.toFixed(1)}c`:Fb.format(e)},Lb=e=>e.toLowerCase().split(/[_-]+/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `),Rb=e=>{switch(e.name){case`edit`:case`read`:case`write`:return`${e.name} ${e.path}`;case`bash`:return e.command;default:return`tool call`}},zb=e=>{switch(e?.name){case`bash`:return`command`;case`read`:case`edit`:case`write`:return`path`;default:return`plain`}},Bb=e=>{let t=new Intl.NumberFormat(`en-US`,{maximumFractionDigits:2}),{tokens:n}=e.detail;return[`${e.detail.provider}/${e.detail.model}`,`${t.format(n.input)} input`,`${t.format(n.output)} output`,`${t.format(n.cacheRead)} cache read`,`${t.format(n.cacheWrite)} cache write`,`${t.format(n.total)} total`,Ib(e.detail.estimatedCostUsd)].join(` · `)},Vb=e=>{if(!(!e||typeof e!=`object`)){if(`message`in e&&typeof e.message==`string`)return e.message;if(`error`in e&&e.error&&typeof e.error==`object`){let t=Vb(e.error);if(t)return t}if(`url`in e&&typeof e.url==`string`)return e.url;if(`command`in e&&typeof e.command==`string`)return e.command}},Hb=e=>{let t=new Map,n=new Map,r=new Map;return e.map(e=>{let i=e,a,o=`plain`,s=`neutral`;switch(i.type){case`STEP_STARTED`:a=Lb(i.detail.stepName),o=`xml-open`,s=`active`;break;case`STEP_COMPLETED`:a=Lb(i.detail.stepName),o=`xml-close`,s=`success`;break;case`STEP_FAILED`:a=Vb(i.detail.error)??Lb(i.detail.stepName),s=`error`;break;case`EXEC_STARTED`:n.set(i.detail.execId,{command:i.detail.command,cwd:i.detail.cwd}),a=i.detail.command,o=`command`,s=`active`;break;case`EXEC_COMPLETED`:a=n.get(i.detail.execId)?.command,o=`command`,s=`success`;break;case`EXEC_FAILED`:a=n.get(i.detail.execId)?.command,o=`command`,s=`error`;break;case`FETCH_STARTED`:r.set(i.detail.fetchId,{url:i.detail.url}),a=i.detail.url,s=`active`;break;case`FETCH_COMPLETED`:a=r.get(i.detail.fetchId)?.url,s=`success`;break;case`FETCH_FAILED`:{let e=r.get(i.detail.fetchId);a=Vb(i.detail.error)??e?.url,s=`error`;break}case`AGENT_STARTED`:s=`active`;break;case`AGENT_COMPLETED`:s=`success`;break;case`AGENT_USAGE`:a=Bb(i),s=`neutral`;break;case`AGENT_TOOL_STARTED`:t.set(i.detail.toolCallId,i.detail.tool),a=Rb(i.detail.tool),o=zb(i.detail.tool),s=`active`;break;case`AGENT_TOOL_COMPLETED`:{let e=t.get(i.detail.toolCallId);a=e?Rb(e):i.detail.toolCallId,o=zb(e),s=`success`;break}case`AGENT_TOOL_FAILED`:{let e=t.get(i.detail.toolCallId);a=e?Rb(e):i.detail.toolCallId,o=zb(e),s=`error`;break}case`AGENT_META`:a=i.detail.message,s=`neutral`;break;case`AGENT_MESSAGE`:a=i.detail.message,s=`neutral`;break;case`AGENT_THOUGHT`:a=i.detail.message,s=`neutral`;break;default:a=Vb(e.detail),s=`neutral`}return{id:e.id,actionedAt:e.actionedAt,type:e.type,detailText:a,detailStyle:o,tone:s}})},Ub=l.from_html(`<div class="polling-indicator svelte-5iw9fb"><!> <span>Live</span></div>`),Wb=l.from_html(`<div class="panel state-panel empty-panel svelte-5iw9fb"><div class="state-title svelte-5iw9fb"><!></div> <div class="state-detail"><!></div></div>`),Gb=l.from_html(`<code class="svelte-5iw9fb"><strong class="svelte-5iw9fb"> </strong> </code>`),Kb=l.from_html(`<code class="svelte-5iw9fb"> </code>`),qb=l.from_html(`<div><!></div>`),Jb=l.from_html(`<span class="event-detail-empty svelte-5iw9fb">—</span>`),Yb=l.from_html(`<li><time class="event-date svelte-5iw9fb"> </time> <div class="event-type-cell svelte-5iw9fb"><span class="event-type svelte-5iw9fb"> </span></div> <div class="event-detail-cell svelte-5iw9fb"><!></div></li>`),Xb=l.from_html(`<ol class="event-list svelte-5iw9fb"></ol>`),Zb=l.from_html(`<div class="detailed-build-log svelte-5iw9fb" aria-live="polite"><div class="header svelte-5iw9fb"><div><div class="eyebrow svelte-5iw9fb">Detailed logs</div> <div class="title svelte-5iw9fb">Build event stream</div></div> <!></div> <!></div>`),Qb={hash:`svelte-5iw9fb`,code:`.detailed-build-log.svelte-5iw9fb {border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-lg, 0.625rem);background:var(--rough-card, white);box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));color:var(--rough-card-foreground, oklch(0.145 0 0));}.header.svelte-5iw9fb {display:flex;align-items:center;justify-content:space-between;gap:1rem;border-bottom:1px solid var(--rough-border, oklch(0.922 0 0));padding:0.85rem 1rem;background:var(--rough-muted, oklch(0.97 0 0));}.eyebrow.svelte-5iw9fb {color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:0.72rem;font-weight:700;text-transform:uppercase;letter-spacing:0.05em;}.title.svelte-5iw9fb {margin-top:0.15rem;color:var(--rough-foreground, oklch(0.145 0 0));font-weight:600;}.polling-indicator.svelte-5iw9fb {display:inline-flex;align-items:center;gap:0.45rem;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:999px;padding:0.15rem 0.55rem;background:var(--rough-background, white);color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:0.8rem;font-weight:600;}.panel.svelte-5iw9fb {padding:0.85rem 1rem;}.state-panel.svelte-5iw9fb {display:flex;gap:0.35rem;flex-direction:column;color:var(--rough-muted-foreground, oklch(0.556 0 0));}.state-title.svelte-5iw9fb {color:var(--rough-foreground, oklch(0.145 0 0));font-weight:600;}.event-list.svelte-5iw9fb {display:grid;grid-template-columns:minmax(7.5rem, auto) minmax(12rem, auto) minmax(0, 1fr);margin:0;padding:0;list-style:none;}.event.svelte-5iw9fb {display:contents;}.event-date.svelte-5iw9fb,
64
64
  .event-type-cell.svelte-5iw9fb,
65
65
  .event-detail-cell.svelte-5iw9fb {border-top:1px solid var(--rough-border, oklch(0.922 0 0));padding-top:0.85rem;padding-bottom:0.85rem;}.event-date.svelte-5iw9fb {padding-left:1rem;color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:0.8rem;}.event-type-cell.svelte-5iw9fb,
66
66
  .event-detail-cell.svelte-5iw9fb {min-width:0;}.event-detail-cell.svelte-5iw9fb {padding-right:1rem;}.event.svelte-5iw9fb:first-child .event-date:where(.svelte-5iw9fb),
@@ -89,21 +89,21 @@ ${zm(e)}`.trim()},Vm=e=>{let{messageList:t}=e,n=t.flatMap(e=>{if(e.role===`tool`
89
89
  @media (max-width: 720px) {.event-list.svelte-5iw9fb {grid-template-columns:1fr;column-gap:0;}.event.svelte-5iw9fb {display:block;border-top:1px solid var(--rough-border, oklch(0.922 0 0));padding:0.85rem 0;}.event.svelte-5iw9fb:first-child {border-top:none;}.event-date.svelte-5iw9fb,
90
90
  .event-type-cell.svelte-5iw9fb,
91
91
  .event-detail-cell.svelte-5iw9fb {display:block;border-top:none;padding-top:0;padding-right:1rem;padding-bottom:0;padding-left:1rem;}.event-type-cell.svelte-5iw9fb {margin-top:0.35rem;}.event-detail-cell.svelte-5iw9fb {margin-top:0.55rem;}
92
- }`};function Zb(e,t){l.push(t,!0),l.append_styles(e,Xb);let n=l.prop(t,`client`,7),r=l.prop(t,`spriteBuild`,7),i=l.prop(t,`eventList`,7),a=l.derived(()=>Xg(n()).store),o=l.derived(()=>r().status),s=l.derived(()=>lb(l.get(a).spriteBuildEvent.filter(`detailed-build-log:${r().id}`,e=>e.spriteBuildId===r().id))),c=l.derived(()=>l.get(s)._),u=l.derived(()=>(i()??l.get(c)).toSorted((e,t)=>e.actionedAt-t.actionedAt||e.id.localeCompare(t.id)).slice(-500)),d=l.derived(()=>Bb(l.get(u))),f=l.derived(()=>l.get(o)===`PENDING`||l.get(o)===`IN_PROGRESS`),p=e=>new Intl.DateTimeFormat(void 0,{hour:`numeric`,minute:`2-digit`,second:`2-digit`}).format(new Date(e)),m=e=>{let t=e.trim(),n=t.match(/^(\S+)(?:\s+(.*))?$/);return n?{head:n[1]??t,tail:n[2]??``}:{head:t,tail:``}};var h={get client(){return n()},set client(e){n(e),l.flush()},get spriteBuild(){return r()},set spriteBuild(e){r(e),l.flush()},get eventList(){return i()},set eventList(e){i(e),l.flush()}},g=Yb(),_=l.child(g),v=l.sibling(l.child(_),2),y=e=>{var t=Vb();cb(l.child(t),{}),l.next(2),l.reset(t),l.append(e,t)};l.if(v,e=>{l.get(f)&&e(y)}),l.reset(_);var b=l.sibling(_,2),ee=e=>{var t=Hb(),n=l.child(t),r=l.child(n),i=e=>{var t=l.text(`Waiting for the build to emit logs`);l.append(e,t)},a=e=>{var t=l.text(`No build events yet`);l.append(e,t)};l.if(r,e=>{l.get(o)===`PENDING`?e(i):e(a,-1)}),l.reset(n);var s=l.sibling(n,2),c=l.child(s),u=e=>{var t=l.text(`Events will appear here as the build progresses.`);l.append(e,t)},d=e=>{var t=l.text(`This build did not record any events.`);l.append(e,t)};l.if(c,e=>{l.get(o)===`PENDING`||l.get(o)===`IN_PROGRESS`?e(u):e(d,-1)}),l.reset(s),l.reset(t),l.append(e,t)},te=e=>{var t=Jb();l.each(t,21,()=>l.get(d),e=>e.id,(e,t)=>{var n=qb(),r=l.child(n),i=l.child(r,!0);l.reset(r);var a=l.sibling(r,2),o=l.child(a),s=l.child(o,!0);l.reset(o),l.reset(a);var c=l.sibling(a,2),u=l.child(c),d=e=>{var n=Gb();let r;var i=l.child(n),a=e=>{let n=l.derived(()=>m(l.get(t).detailText));var r=Ub(),i=l.child(r),a=l.child(i,!0);l.reset(i);var o=l.sibling(i,1,!0);l.reset(r),l.template_effect(()=>{l.set_text(a,l.get(n).head),l.set_text(o,l.get(n).tail?` ${l.get(n).tail}`:``)}),l.append(e,r)},o=e=>{let n=l.derived(()=>m(l.get(t).detailText));var r=Ub(),i=l.child(r),a=l.child(i,!0);l.reset(i);var o=l.sibling(i,1,!0);l.reset(r),l.template_effect(()=>{l.set_text(a,l.get(n).head),l.set_text(o,l.get(n).tail?` ${l.get(n).tail}`:``)}),l.append(e,r)},s=e=>{var n=Wb(),r=l.child(n);l.reset(n),l.template_effect(e=>l.set_text(r,`<${e??``}>`),[()=>l.get(t).detailText.replaceAll(` `,``)]),l.append(e,n)},c=e=>{var n=Wb(),r=l.child(n);l.reset(n),l.template_effect(e=>l.set_text(r,`</${e??``}>`),[()=>l.get(t).detailText.replaceAll(` `,``)]),l.append(e,n)},u=e=>{var n=l.text();l.template_effect(()=>l.set_text(n,l.get(t).detailText)),l.append(e,n)};l.if(i,e=>{l.get(t).detailStyle===`command`?e(a):l.get(t).detailStyle===`path`?e(o,1):l.get(t).detailStyle===`xml-open`?e(s,2):l.get(t).detailStyle===`xml-close`?e(c,3):e(u,-1)}),l.reset(n),l.template_effect(()=>r=l.set_class(n,1,`event-detail svelte-5iw9fb`,null,r,{"event-detail-xml":l.get(t).detailStyle===`xml-open`||l.get(t).detailStyle===`xml-close`,"event-detail-command":l.get(t).detailStyle===`command`,"event-detail-path":l.get(t).detailStyle===`path`})),l.append(e,n)},f=e=>{var t=Kb();l.append(e,t)};l.if(u,e=>{l.get(t).detailText?e(d):e(f,-1)}),l.reset(c),l.reset(n),l.template_effect((e,a)=>{l.set_class(n,1,`event tone-${l.get(t).tone}`,`svelte-5iw9fb`),l.set_attribute(r,`datetime`,e),l.set_text(i,a),l.set_text(s,l.get(t).type)},[()=>new Date(l.get(t).actionedAt).toISOString(),()=>p(l.get(t).actionedAt)]),l.append(e,n)}),l.reset(t),l.append(e,t)};return l.if(b,e=>{l.get(d).length===0?e(ee):e(te,-1)}),l.reset(g),l.append(e,g),l.pop(h)}l.create_custom_element(Zb,{client:{},spriteBuild:{},eventList:{}},[],[],{mode:`open`});var Qb=l.from_html(`<p class="detail svelte-elh43j"> </p>`),$b=l.from_html(`<div class="error svelte-elh43j"><div class="error-label svelte-elh43j">Error</div> <div class="error-detail svelte-elh43j"> </div></div>`),ex=l.from_html(`<div class="overlay svelte-elh43j" role="dialog" aria-modal="true" aria-labelledby="confirm-overlay-title"><div class="panel svelte-elh43j"><h4 id="confirm-overlay-title" class="title svelte-elh43j"> </h4> <!> <!> <div class="actions svelte-elh43j"><!></div></div></div>`),tx={hash:`svelte-elh43j`,code:`.overlay.svelte-elh43j {position:absolute;inset:0;z-index:10;display:flex;align-items:center;justify-content:center;background:rgb(0 0 0 / 0.5);}.panel.svelte-elh43j {display:flex;gap:0.75rem;flex-direction:column;width:min(28rem, 90%);border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-lg, 0.625rem);padding:1.5rem;background:var(--rough-card, white);box-shadow:var(--rough-shadow-lg, 0 10px 15px -3px rgb(0 0 0 / 0.1));color:var(--rough-card-foreground, oklch(0.145 0 0));}.title.svelte-elh43j {margin:0;color:var(--rough-card-foreground, oklch(0.145 0 0));font-size:1.125rem;font-weight:600;line-height:1;}.detail.svelte-elh43j {margin:0;color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:0.875rem;line-height:1.45;}.error.svelte-elh43j {border:1px solid color-mix(in oklch, var(--rough-destructive, oklch(0.577 0.245 27.325)) 30%, transparent);border-radius:var(--rough-radius-md, 0.375rem);padding:0.75rem;background:color-mix(in oklch, var(--rough-destructive, oklch(0.577 0.245 27.325)) 10%, var(--rough-card, white));}.error-label.svelte-elh43j {color:var(--rough-destructive, oklch(0.577 0.245 27.325));font-size:0.75rem;font-weight:700;text-transform:uppercase;letter-spacing:0.05em;}.error-detail.svelte-elh43j {margin-top:0.25rem;color:var(--rough-foreground, oklch(0.145 0 0));font-size:0.875rem;}.actions.svelte-elh43j {display:flex;justify-content:flex-end;gap:0.5rem;margin-top:0.5rem;}`};function nx(e,t){l.push(t,!0),l.append_styles(e,tx);let n=l.prop(t,`title`,7),r=l.prop(t,`detail`,7),i=l.prop(t,`error`,7),a=l.prop(t,`actions`,7);var o={get title(){return n()},set title(e){n(e),l.flush()},get detail(){return r()},set detail(e){r(e),l.flush()},get error(){return i()},set error(e){i(e),l.flush()},get actions(){return a()},set actions(e){a(e),l.flush()}},s=ex(),c=l.child(s),u=l.child(c),d=l.child(u,!0);l.reset(u);var f=l.sibling(u,2),p=e=>{var t=Qb(),n=l.child(t,!0);l.reset(t),l.template_effect(()=>l.set_text(n,r())),l.append(e,t)};l.if(f,e=>{r()&&e(p)});var m=l.sibling(f,2),h=e=>{var t=$b(),n=l.sibling(l.child(t),2),r=l.child(n,!0);l.reset(n),l.reset(t),l.template_effect(()=>l.set_text(r,i().message)),l.append(e,t)};l.if(m,e=>{i()&&e(h)});var g=l.sibling(m,2),_=l.child(g);return l.snippet(_,a),l.reset(g),l.reset(c),l.reset(s),l.template_effect(()=>l.set_text(d,n())),l.append(e,s),l.pop(o)}l.create_custom_element(nx,{title:{},detail:{},error:{},actions:{}},[],[],{mode:`open`});var rx=e=>{let{client:t,spriteId:n,toolList:r,onStartBuild:i,onMessagesChange:a,onLoadingChange:o,onErrorChange:s}=e,c=Im.client(()=>r.map(e=>e.toJSON())),l,u=Lm.client(e=>i(e,l.getMessages()));return l=new Wv({threadId:n,persistence:!0,connection:G_(()=>Xg(t).buildUrl({path:`/api/v1/project/${encodeURIComponent(t.projectId)}/chat`}),async()=>({headers:{Authorization:`Bearer ${(await Xg(t).auth.getSessionToken()).token}`}})),tools:[c,u],queue:`drop`,onMessagesChange:e=>a([...e]),onLoadingChange:o,onErrorChange:s}),l},ix=l.from_html(`<button type="button" role="tab"> </button>`),ax=l.from_html(`<footer class="MobileTabBar svelte-17gs0md"><div class="tabs svelte-17gs0md" role="tablist"></div></footer>`),ox={hash:`svelte-17gs0md`,code:`.MobileTabBar.svelte-17gs0md {display:none;flex:none;border-top:1px solid var(--rough-border, oklch(0.922 0 0));padding:0.5rem 0.75rem calc(0.5rem + env(safe-area-inset-bottom));background:var(--rough-card, white);}.tabs.svelte-17gs0md {display:grid;grid-template-columns:repeat(var(--mobile-tab-count, 3), minmax(0, 1fr));gap:0.125rem;border-radius:var(--rough-radius-lg, 0.625rem);padding:0.1875rem;background:var(--rough-muted, oklch(0.97 0 0));color:var(--rough-muted-foreground, oklch(0.556 0 0));}.tab.svelte-17gs0md {appearance:none;height:2.25rem;min-width:0;border:1px solid transparent;border-radius:var(--rough-radius-md, 0.375rem);padding:0.25rem 0.5rem;background:transparent;color:inherit;font:inherit;font-size:0.875rem;font-weight:500;line-height:1;cursor:pointer;transition:background-color 120ms ease, border-color 120ms ease,
92
+ }`};function $b(e,t){l.push(t,!0),l.append_styles(e,Qb);let n=l.prop(t,`client`,7),r=l.prop(t,`spriteBuild`,7),i=l.prop(t,`eventList`,7),a=l.derived(()=>Qg(n()).store),o=l.derived(()=>r().status),s=l.derived(()=>db(l.get(a).spriteBuildEvent.filter(`detailed-build-log:${r().id}`,e=>e.spriteBuildId===r().id))),c=l.derived(()=>l.get(s)._),u=l.derived(()=>(i()??l.get(c)).toSorted((e,t)=>e.actionedAt-t.actionedAt||e.id.localeCompare(t.id)).slice(-500)),d=l.derived(()=>Hb(l.get(u))),f=l.derived(()=>l.get(o)===`PENDING`||l.get(o)===`IN_PROGRESS`),p=e=>new Intl.DateTimeFormat(void 0,{hour:`numeric`,minute:`2-digit`,second:`2-digit`}).format(new Date(e)),m=e=>{let t=e.trim(),n=t.match(/^(\S+)(?:\s+(.*))?$/);return n?{head:n[1]??t,tail:n[2]??``}:{head:t,tail:``}};var h={get client(){return n()},set client(e){n(e),l.flush()},get spriteBuild(){return r()},set spriteBuild(e){r(e),l.flush()},get eventList(){return i()},set eventList(e){i(e),l.flush()}},g=Zb(),_=l.child(g),v=l.sibling(l.child(_),2),y=e=>{var t=Ub();ub(l.child(t),{}),l.next(2),l.reset(t),l.append(e,t)};l.if(v,e=>{l.get(f)&&e(y)}),l.reset(_);var b=l.sibling(_,2),ee=e=>{var t=Wb(),n=l.child(t),r=l.child(n),i=e=>{var t=l.text(`Waiting for the build to emit logs`);l.append(e,t)},a=e=>{var t=l.text(`No build events yet`);l.append(e,t)};l.if(r,e=>{l.get(o)===`PENDING`?e(i):e(a,-1)}),l.reset(n);var s=l.sibling(n,2),c=l.child(s),u=e=>{var t=l.text(`Events will appear here as the build progresses.`);l.append(e,t)},d=e=>{var t=l.text(`This build did not record any events.`);l.append(e,t)};l.if(c,e=>{l.get(o)===`PENDING`||l.get(o)===`IN_PROGRESS`?e(u):e(d,-1)}),l.reset(s),l.reset(t),l.append(e,t)},x=e=>{var t=Xb();l.each(t,21,()=>l.get(d),e=>e.id,(e,t)=>{var n=Yb(),r=l.child(n),i=l.child(r,!0);l.reset(r);var a=l.sibling(r,2),o=l.child(a),s=l.child(o,!0);l.reset(o),l.reset(a);var c=l.sibling(a,2),u=l.child(c),d=e=>{var n=qb();let r;var i=l.child(n),a=e=>{let n=l.derived(()=>m(l.get(t).detailText));var r=Gb(),i=l.child(r),a=l.child(i,!0);l.reset(i);var o=l.sibling(i,1,!0);l.reset(r),l.template_effect(()=>{l.set_text(a,l.get(n).head),l.set_text(o,l.get(n).tail?` ${l.get(n).tail}`:``)}),l.append(e,r)},o=e=>{let n=l.derived(()=>m(l.get(t).detailText));var r=Gb(),i=l.child(r),a=l.child(i,!0);l.reset(i);var o=l.sibling(i,1,!0);l.reset(r),l.template_effect(()=>{l.set_text(a,l.get(n).head),l.set_text(o,l.get(n).tail?` ${l.get(n).tail}`:``)}),l.append(e,r)},s=e=>{var n=Kb(),r=l.child(n);l.reset(n),l.template_effect(e=>l.set_text(r,`<${e??``}>`),[()=>l.get(t).detailText.replaceAll(` `,``)]),l.append(e,n)},c=e=>{var n=Kb(),r=l.child(n);l.reset(n),l.template_effect(e=>l.set_text(r,`</${e??``}>`),[()=>l.get(t).detailText.replaceAll(` `,``)]),l.append(e,n)},u=e=>{var n=l.text();l.template_effect(()=>l.set_text(n,l.get(t).detailText)),l.append(e,n)};l.if(i,e=>{l.get(t).detailStyle===`command`?e(a):l.get(t).detailStyle===`path`?e(o,1):l.get(t).detailStyle===`xml-open`?e(s,2):l.get(t).detailStyle===`xml-close`?e(c,3):e(u,-1)}),l.reset(n),l.template_effect(()=>r=l.set_class(n,1,`event-detail svelte-5iw9fb`,null,r,{"event-detail-xml":l.get(t).detailStyle===`xml-open`||l.get(t).detailStyle===`xml-close`,"event-detail-command":l.get(t).detailStyle===`command`,"event-detail-path":l.get(t).detailStyle===`path`})),l.append(e,n)},f=e=>{var t=Jb();l.append(e,t)};l.if(u,e=>{l.get(t).detailText?e(d):e(f,-1)}),l.reset(c),l.reset(n),l.template_effect((e,a)=>{l.set_class(n,1,`event tone-${l.get(t).tone}`,`svelte-5iw9fb`),l.set_attribute(r,`datetime`,e),l.set_text(i,a),l.set_text(s,l.get(t).type)},[()=>new Date(l.get(t).actionedAt).toISOString(),()=>p(l.get(t).actionedAt)]),l.append(e,n)}),l.reset(t),l.append(e,t)};return l.if(b,e=>{l.get(d).length===0?e(ee):e(x,-1)}),l.reset(g),l.append(e,g),l.pop(h)}l.create_custom_element($b,{client:{},spriteBuild:{},eventList:{}},[],[],{mode:`open`});var ex=l.from_html(`<p class="detail svelte-elh43j"> </p>`),tx=l.from_html(`<div class="error svelte-elh43j"><div class="error-label svelte-elh43j">Error</div> <div class="error-detail svelte-elh43j"> </div></div>`),nx=l.from_html(`<div class="overlay svelte-elh43j" role="dialog" aria-modal="true" aria-labelledby="confirm-overlay-title"><div class="panel svelte-elh43j"><h4 id="confirm-overlay-title" class="title svelte-elh43j"> </h4> <!> <!> <div class="actions svelte-elh43j"><!></div></div></div>`),rx={hash:`svelte-elh43j`,code:`.overlay.svelte-elh43j {position:absolute;inset:0;z-index:10;display:flex;align-items:center;justify-content:center;background:rgb(0 0 0 / 0.5);}.panel.svelte-elh43j {display:flex;gap:0.75rem;flex-direction:column;width:min(28rem, 90%);border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-lg, 0.625rem);padding:1.5rem;background:var(--rough-card, white);box-shadow:var(--rough-shadow-lg, 0 10px 15px -3px rgb(0 0 0 / 0.1));color:var(--rough-card-foreground, oklch(0.145 0 0));}.title.svelte-elh43j {margin:0;color:var(--rough-card-foreground, oklch(0.145 0 0));font-size:1.125rem;font-weight:600;line-height:1;}.detail.svelte-elh43j {margin:0;color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:0.875rem;line-height:1.45;}.error.svelte-elh43j {border:1px solid color-mix(in oklch, var(--rough-destructive, oklch(0.577 0.245 27.325)) 30%, transparent);border-radius:var(--rough-radius-md, 0.375rem);padding:0.75rem;background:color-mix(in oklch, var(--rough-destructive, oklch(0.577 0.245 27.325)) 10%, var(--rough-card, white));}.error-label.svelte-elh43j {color:var(--rough-destructive, oklch(0.577 0.245 27.325));font-size:0.75rem;font-weight:700;text-transform:uppercase;letter-spacing:0.05em;}.error-detail.svelte-elh43j {margin-top:0.25rem;color:var(--rough-foreground, oklch(0.145 0 0));font-size:0.875rem;}.actions.svelte-elh43j {display:flex;justify-content:flex-end;gap:0.5rem;margin-top:0.5rem;}`};function ix(e,t){l.push(t,!0),l.append_styles(e,rx);let n=l.prop(t,`title`,7),r=l.prop(t,`detail`,7),i=l.prop(t,`error`,7),a=l.prop(t,`actions`,7);var o={get title(){return n()},set title(e){n(e),l.flush()},get detail(){return r()},set detail(e){r(e),l.flush()},get error(){return i()},set error(e){i(e),l.flush()},get actions(){return a()},set actions(e){a(e),l.flush()}},s=nx(),c=l.child(s),u=l.child(c),d=l.child(u,!0);l.reset(u);var f=l.sibling(u,2),p=e=>{var t=ex(),n=l.child(t,!0);l.reset(t),l.template_effect(()=>l.set_text(n,r())),l.append(e,t)};l.if(f,e=>{r()&&e(p)});var m=l.sibling(f,2),h=e=>{var t=tx(),n=l.sibling(l.child(t),2),r=l.child(n,!0);l.reset(n),l.reset(t),l.template_effect(()=>l.set_text(r,i().message)),l.append(e,t)};l.if(m,e=>{i()&&e(h)});var g=l.sibling(m,2),_=l.child(g);return l.snippet(_,a),l.reset(g),l.reset(c),l.reset(s),l.template_effect(()=>l.set_text(d,n())),l.append(e,s),l.pop(o)}l.create_custom_element(ix,{title:{},detail:{},error:{},actions:{}},[],[],{mode:`open`});var ax=e=>{let{client:t,spriteId:n,toolList:r,getSpriteBuildEventList:i,onStartBuild:a,onMessagesChange:o,onLoadingChange:s,onErrorChange:c}=e,l,u=Fm.client(()=>r.map(e=>e.toJSON())),d=Lm.client(e=>a(e,l.getMessages())),f=Im.client(({spriteBuildId:e})=>[...i(e)]);return l=new Kv({threadId:n,persistence:!0,connection:q_(()=>Qg(t).buildUrl({path:`/api/v1/project/${encodeURIComponent(t.projectId)}/chat`}),async()=>({headers:{Authorization:`Bearer ${(await Qg(t).auth.getSessionToken()).token}`}})),tools:[u,f,d],queue:`drop`,onMessagesChange:e=>o([...e]),onLoadingChange:s,onErrorChange:c}),l},ox=l.from_html(`<button type="button" role="tab"> </button>`),sx=l.from_html(`<footer class="MobileTabBar svelte-17gs0md"><div class="tabs svelte-17gs0md" role="tablist"></div></footer>`),cx={hash:`svelte-17gs0md`,code:`.MobileTabBar.svelte-17gs0md {display:none;flex:none;border-top:1px solid var(--rough-border, oklch(0.922 0 0));padding:0.5rem 0.75rem calc(0.5rem + env(safe-area-inset-bottom));background:var(--rough-card, white);}.tabs.svelte-17gs0md {display:grid;grid-template-columns:repeat(var(--mobile-tab-count, 3), minmax(0, 1fr));gap:0.125rem;border-radius:var(--rough-radius-lg, 0.625rem);padding:0.1875rem;background:var(--rough-muted, oklch(0.97 0 0));color:var(--rough-muted-foreground, oklch(0.556 0 0));}.tab.svelte-17gs0md {appearance:none;height:2.25rem;min-width:0;border:1px solid transparent;border-radius:var(--rough-radius-md, 0.375rem);padding:0.25rem 0.5rem;background:transparent;color:inherit;font:inherit;font-size:0.875rem;font-weight:500;line-height:1;cursor:pointer;transition:background-color 120ms ease, border-color 120ms ease,
93
93
  box-shadow 120ms ease, color 120ms ease;}.tab.svelte-17gs0md:hover {color:var(--rough-foreground, oklch(0.145 0 0));}.tab.active.svelte-17gs0md {border-color:var(--rough-border, oklch(0.922 0 0));background:var(--rough-background, white);box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));color:var(--rough-foreground, oklch(0.145 0 0));}.tab.svelte-17gs0md:focus-visible {border-color:var(--rough-ring, oklch(0.708 0 0));outline:none;box-shadow:0 0 0 3px color-mix(in oklch, var(--rough-ring, oklch(0.708 0 0)) 45%, transparent);}
94
94
 
95
95
  @media (max-width: 1000px) {.MobileTabBar.svelte-17gs0md {display:block;}
96
- }`};function sx(e,t){l.push(t,!0),l.append_styles(e,ox);let n=l.prop(t,`active`,15),r=l.prop(t,`tabs`,7),i=l.prop(t,`ariaLabel`,7,`Navigation`),a=e=>{let t=e.key;if(![`ArrowLeft`,`ArrowRight`,`Home`,`End`].includes(t))return;let n=e.currentTarget,r=n.closest(`[role="tablist"]`),i=Array.from(r?.querySelectorAll(`[role="tab"]`)??[]),a=i.indexOf(n);if(a===-1||i.length===0)return;e.preventDefault();let o=t===`Home`?0:t===`End`?i.length-1:t===`ArrowLeft`?(a-1+i.length)%i.length:(a+1)%i.length;i[o]?.focus(),i[o]?.click()};var o={get active(){return n()},set active(e){n(e),l.flush()},get tabs(){return r()},set tabs(e){r(e),l.flush()},get ariaLabel(){return i()},set ariaLabel(e=`Navigation`){i(e),l.flush()}},s=ax(),c=l.child(s);let u;return l.each(c,21,r,e=>e.key,(e,t)=>{var r=ix();let i;var o=l.child(r,!0);l.reset(r),l.template_effect(()=>{i=l.set_class(r,1,`tab svelte-17gs0md`,null,i,{active:n()===l.get(t).key}),l.set_attribute(r,`aria-selected`,n()===l.get(t).key),l.set_attribute(r,`tabindex`,n()===l.get(t).key?0:-1),l.set_text(o,l.get(t).label)}),l.delegated(`click`,r,()=>n(l.get(t).key)),l.delegated(`keydown`,r,a),l.append(e,r)}),l.reset(c),l.reset(s),l.template_effect(()=>{l.set_attribute(s,`aria-label`,i()),l.set_attribute(c,`aria-label`,i()),u=l.set_style(c,``,u,{"--mobile-tab-count":r().length})}),l.append(e,s),l.pop(o)}l.delegate([`click`,`keydown`]),l.create_custom_element(sx,{active:{},tabs:{},ariaLabel:{}},[],[],{mode:`open`});var cx=l.from_html(`<button><!></button>`),lx={hash:`svelte-om76s9`,code:`button.svelte-om76s9 {appearance:none;display:inline-flex;align-items:center;justify-content:center;gap:0.5rem;min-height:2.25rem;border:1px solid var(--rough-primary, oklch(0.205 0 0));border-radius:var(--rough-radius-md, 0.375rem);padding:0.5rem 1rem;background:var(--rough-primary, oklch(0.205 0 0));box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));color:var(--rough-primary-foreground, white);font:inherit;font-size:0.875rem;font-weight:500;line-height:1.25rem;white-space:nowrap;cursor:pointer;transition:background-color 120ms ease, border-color 120ms ease,
97
- box-shadow 120ms ease, opacity 120ms ease;}button.svelte-om76s9:hover:not(:disabled) {border-color:color-mix(in oklch, var(--rough-primary, oklch(0.205 0 0)) 90%, transparent);background:color-mix(in oklch, var(--rough-primary, oklch(0.205 0 0)) 90%, transparent);}button.svelte-om76s9:focus-visible {border-color:var(--rough-ring, oklch(0.708 0 0));outline:none;box-shadow:0 0 0 3px color-mix(in oklch, var(--rough-ring, oklch(0.708 0 0)) 45%, transparent);}button.svelte-om76s9:disabled {opacity:0.5;cursor:not-allowed;}.block.svelte-om76s9 {display:flex;width:100%;}.iconOnly.svelte-om76s9 {width:2.25rem;min-width:2.25rem;min-height:2.25rem;padding:0;}.alignStart.svelte-om76s9 {justify-content:flex-start;}`};function ux(e,t){l.push(t,!0),l.append_styles(e,lx);let n=l.prop(t,`children`,7),r=l.prop(t,`class`,7,``),i=l.prop(t,`type`,7,`button`),a=l.prop(t,`disabled`,7,!1),o=l.prop(t,`onclick`,7),s=l.prop(t,`role`,7),c=l.prop(t,`block`,7,!1),u=l.prop(t,`iconOnly`,7,!1),d=l.prop(t,`alignStart`,7,!1),f=l.prop(t,`aria-label`,7),p=l.prop(t,`aria-haspopup`,7),m=l.prop(t,`aria-expanded`,7);var h={get children(){return n()},set children(e){n(e),l.flush()},get class(){return r()},set class(e=``){r(e),l.flush()},get type(){return i()},set type(e=`button`){i(e),l.flush()},get disabled(){return a()},set disabled(e=!1){a(e),l.flush()},get onclick(){return o()},set onclick(e){o(e),l.flush()},get role(){return s()},set role(e){s(e),l.flush()},get block(){return c()},set block(e=!1){c(e),l.flush()},get iconOnly(){return u()},set iconOnly(e=!1){u(e),l.flush()},get alignStart(){return d()},set alignStart(e=!1){d(e),l.flush()},get"aria-label"(){return f()},set"aria-label"(e){f(e),l.flush()},get"aria-haspopup"(){return p()},set"aria-haspopup"(e){p(e),l.flush()},get"aria-expanded"(){return m()},set"aria-expanded"(e){m(e),l.flush()}},g=cx();let _;var v=l.child(g);return l.snippet(v,()=>n()??l.noop),l.reset(g),l.template_effect(()=>{l.set_attribute(g,`type`,i()),g.disabled=a(),l.set_attribute(g,`role`,s()),l.set_attribute(g,`aria-label`,f()),l.set_attribute(g,`aria-haspopup`,p()),l.set_attribute(g,`aria-expanded`,m()),_=l.set_class(g,1,l.clsx(r()),`svelte-om76s9`,_,{block:c(),iconOnly:u(),alignStart:d()})}),l.delegated(`click`,g,function(...e){o()?.apply(this,e)}),l.append(e,g),l.pop(h)}l.delegate([`click`]),l.create_custom_element(ux,{children:{},class:{},type:{},disabled:{},onclick:{},role:{},block:{},iconOnly:{},alignStart:{},"aria-label":{},"aria-haspopup":{},"aria-expanded":{}},[],[],{mode:`open`});var dx=e=>t=>{let n=e??window.document.body;return n.appendChild(t),t.hidden=!1,()=>{t.parentNode===n&&n.removeChild(t)}},fx=l.from_html(`<dialog class="svelte-1phmmvx"><!></dialog>`),px={hash:`svelte-1phmmvx`,code:`dialog.svelte-1phmmvx {position:fixed;inset:2rem;width:auto;height:auto;max-width:none;max-height:none;margin:0;border:none;padding:0;background:transparent;}dialog.svelte-1phmmvx::backdrop {background:rgb(0 0 0 / 0.5);}`};function mx(e,t){l.push(t,!0),l.append_styles(e,px);let n=l.prop(t,`isOpen`,15,!0),r=l.prop(t,`target`,7),i=l.prop(t,`onclose`,7),a=l.prop(t,`oncancel`,7),o=l.prop(t,`children`,7),s=l.state(void 0);l.user_effect(()=>{if(l.get(s)){if(n()&&!l.get(s).open){l.get(s).showModal();return}!n()&&l.get(s).open&&l.get(s).close()}});var c={get isOpen(){return n()},set isOpen(e=!0){n(e),l.flush()},get target(){return r()},set target(e){r(e),l.flush()},get onclose(){return i()},set onclose(e){i(e),l.flush()},get oncancel(){return a()},set oncancel(e){a(e),l.flush()},get children(){return o()},set children(e){o(e),l.flush()}},u=fx(),d=l.child(u);return l.snippet(d,()=>o()??l.noop),l.reset(u),l.bind_this(u,e=>l.set(s,e),()=>l.get(s)),l.attach(u,()=>dx(r())),l.event(`close`,u,()=>{n(!1),i()?.()}),l.event(`cancel`,u,function(...e){a()?.apply(this,e)}),l.append(e,u),l.pop(c)}l.create_custom_element(mx,{isOpen:{},target:{},onclose:{},oncancel:{},children:{}},[],[],{mode:`open`});var hx=l.from_html(`<button><!></button>`),gx={hash:`svelte-1yyy6r1`,code:`button.svelte-1yyy6r1 {appearance:none;display:inline-flex;align-items:center;justify-content:center;gap:0.5rem;min-height:2.25rem;border:1px solid transparent;border-radius:var(--rough-radius-md, 0.375rem);padding:0.5rem 1rem;background:var(--rough-secondary, oklch(0.97 0 0));box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));color:var(--rough-secondary-foreground, oklch(0.205 0 0));font:inherit;font-size:0.875rem;font-weight:500;line-height:1.25rem;white-space:nowrap;cursor:pointer;transition:background-color 120ms ease, border-color 120ms ease,
98
- box-shadow 120ms ease, opacity 120ms ease;}button.svelte-1yyy6r1:hover:not(:disabled) {background:color-mix(in oklch, var(--rough-secondary, oklch(0.97 0 0)) 80%, var(--rough-foreground, black));}button.svelte-1yyy6r1:focus-visible {border-color:var(--rough-ring, oklch(0.708 0 0));outline:none;box-shadow:0 0 0 3px color-mix(in oklch, var(--rough-ring, oklch(0.708 0 0)) 45%, transparent);}button.svelte-1yyy6r1:disabled {opacity:0.5;cursor:not-allowed;}.block.svelte-1yyy6r1 {display:flex;width:100%;}.iconOnly.svelte-1yyy6r1 {width:2.25rem;min-width:2.25rem;min-height:2.25rem;padding:0;}.alignStart.svelte-1yyy6r1 {justify-content:flex-start;}`};function _x(e,t){l.push(t,!0),l.append_styles(e,gx);let n=l.prop(t,`children`,7),r=l.prop(t,`class`,7,``),i=l.prop(t,`type`,7,`button`),a=l.prop(t,`disabled`,7,!1),o=l.prop(t,`onclick`,7),s=l.prop(t,`role`,7),c=l.prop(t,`block`,7,!1),u=l.prop(t,`iconOnly`,7,!1),d=l.prop(t,`alignStart`,7,!1),f=l.prop(t,`aria-label`,7),p=l.prop(t,`aria-haspopup`,7),m=l.prop(t,`aria-expanded`,7);var h={get children(){return n()},set children(e){n(e),l.flush()},get class(){return r()},set class(e=``){r(e),l.flush()},get type(){return i()},set type(e=`button`){i(e),l.flush()},get disabled(){return a()},set disabled(e=!1){a(e),l.flush()},get onclick(){return o()},set onclick(e){o(e),l.flush()},get role(){return s()},set role(e){s(e),l.flush()},get block(){return c()},set block(e=!1){c(e),l.flush()},get iconOnly(){return u()},set iconOnly(e=!1){u(e),l.flush()},get alignStart(){return d()},set alignStart(e=!1){d(e),l.flush()},get"aria-label"(){return f()},set"aria-label"(e){f(e),l.flush()},get"aria-haspopup"(){return p()},set"aria-haspopup"(e){p(e),l.flush()},get"aria-expanded"(){return m()},set"aria-expanded"(e){m(e),l.flush()}},g=hx();let _;var v=l.child(g);return l.snippet(v,()=>n()??l.noop),l.reset(g),l.template_effect(()=>{l.set_attribute(g,`type`,i()),g.disabled=a(),l.set_attribute(g,`role`,s()),l.set_attribute(g,`aria-label`,f()),l.set_attribute(g,`aria-haspopup`,p()),l.set_attribute(g,`aria-expanded`,m()),_=l.set_class(g,1,l.clsx(r()),`svelte-1yyy6r1`,_,{block:c(),iconOnly:u(),alignStart:d()})}),l.delegated(`click`,g,function(...e){o()?.apply(this,e)}),l.append(e,g),l.pop(h)}l.delegate([`click`]),l.create_custom_element(_x,{children:{},class:{},type:{},disabled:{},onclick:{},role:{},block:{},iconOnly:{},alignStart:{},"aria-label":{},"aria-haspopup":{},"aria-expanded":{}},[],[],{mode:`open`});var vx=e=>{let t=(e,n={})=>{let r=e?`[${e}] `:``,i=(e,t,i)=>{let a={...n,...i},o=`${r}${t}`,s=Object.keys(a).length>0;e===`info`?s?console.info(o,a):console.info(o):s?console.error(o,a):console.error(o)};return{info:(e,t)=>{i(`info`,e,t)},error:(e,t)=>{i(`error`,e,t)},child:(r,i={})=>{let a=e?`${e}:${r}`:r;return t(a,{...n,...i})}}};return t(e)},yx=`2.0.0`,bx=`app.rough.frame.server.port`,xx=(e,t)=>!!e&&typeof e==`object`&&`type`in e&&e.type===t&&`version`in e&&typeof e.version==`string`,Sx=class{serverWindow;getClientWindow;clientOrigin;createSession;createMessageChannel;logger;session;listening=!1;constructor(e){this.serverWindow=e.serverWindow,this.getClientWindow=e.getClientWindow,this.clientOrigin=e.clientOrigin,this.createSession=e.createSession,this.createMessageChannel=e.createMessageChannel??(()=>new MessageChannel),this.logger=(e.logger??vx()).child(`channel-server`)}start(){this.listening||=(this.serverWindow.addEventListener(`message`,this.onMessage),!0)}stop(){this.listening&&(this.serverWindow.removeEventListener(`message`,this.onMessage),this.listening=!1,this.disposeSession())}onMessage=e=>{if(this.clientOrigin!==`*`&&e.origin!==this.clientOrigin){this.logger.info(`message ignored`,{reason:`unexpected origin`,origin:e.origin});return}if(!xx(e.data,`app.rough.frame.client.ready`)){this.logger.info(`message ignored`,{reason:`unexpected type`,data:e.data});return}let t=this.getClientWindow();if(!t||e.source!==t){this.logger.info(`message ignored`,{reason:`unexpected source`});return}let n=this.createMessageChannel();this.disposeSession(),this.session=this.createSession(n.port1),t.postMessage({type:bx,version:yx},{targetOrigin:this.clientOrigin,transfer:[n.port2]})};disposeSession(){this.session&&=(this.session[Symbol.dispose]?.(),void 0)}},Cx=[{},{}],wx=e=>{let{store:t,iframeElement:n,onReportSize:r,getBridgeMethodDefinitions:i}=e;return{_internal:{reportSize(e){n&&(n.style.minHeight=`${e.height}px`),r?.(e)},getBridgeMethodDefinitions(){return i?.()??[]},state:{get(){return t.get()??Cx},set(e){t.set(e)},addListener(e){let n=e.dup(),r=t.addListener(n);return()=>{r(),n[Symbol.dispose]()}}}}}},Tx=class{containerElement;channelServer;iframeSrc;iframeElement;constructor(e){let{iframe:t,serverWindow:n=globalThis.window,clientOrigin:r=`*`,getTools:i,getBridgeMethodDefinitions:a,logger:o=vx(),store:s}=e,c;if(`contentWindow`in t)this.iframeElement=void 0,c=()=>t.contentWindow;else{let{containerElement:e,src:n,title:r,allow:i=[`fullscreen`,`camera`,`microphone`]}=t;this.containerElement=e,this.iframeElement=document.createElement(`iframe`),this.iframeSrc=n,this.iframeElement.width=`100%`,this.iframeElement.title=r,this.iframeElement.allow=i.join(`; `),this.iframeElement.style=`border: none;`,e.appendChild(this.iframeElement),c=()=>this.iframeElement?.contentWindow??void 0}let l=wx({store:s,iframeElement:this.iframeElement,onReportSize:t.onReportSize,getBridgeMethodDefinitions:a});this.channelServer=new Sx({getClientWindow:c,serverWindow:n,clientOrigin:r,logger:o,createSession:e=>{let t=i();return f(e,{...t,...l})}})}start(){this.channelServer.start(),this.iframeElement&&this.iframeSrc!==void 0&&(this.iframeElement.src=this.iframeSrc,this.iframeSrc=void 0)}stop(){this.channelServer.stop(),this.containerElement&&this.iframeElement&&(this.containerElement.removeChild(this.iframeElement),this.iframeElement=void 0)}},Ex=l.from_html(`<div><!></div>`);function Dx(e,t){l.push(t,!0);let n=l.prop(t,`handle`,7),r=l.prop(t,`children`,7),i=l.prop(t,`class`,7,``),a,s=l.derived(()=>[n().class,i()].filter(Boolean).join(` `));o(()=>{a&&n().destroy(a)});var c={get handle(){return n()},set handle(e){n(e),l.flush()},get children(){return r()},set children(e){r(e),l.flush()},get class(){return i()},set class(e=``){i(e),l.flush()}},u=Ex(),d=l.child(u);return l.snippet(d,()=>r()??l.noop),l.reset(u),l.bind_this(u,e=>a=e,()=>a),l.template_effect(()=>{l.set_class(u,1,l.clsx(l.get(s))),l.set_attribute(u,`role`,n().role),l.set_attribute(u,`aria-orientation`,n()[`aria-orientation`]),l.set_attribute(u,`aria-label`,n()[`aria-label`]),l.set_attribute(u,`title`,n().title)}),l.delegated(`pointerdown`,u,function(...e){n().onpointerdown?.apply(this,e)}),l.delegated(`pointermove`,u,function(...e){n().onpointermove?.apply(this,e)}),l.delegated(`pointerup`,u,function(...e){n().onpointerup?.apply(this,e)}),l.event(`pointercancel`,u,function(...e){n().onpointercancel?.apply(this,e)}),l.delegated(`dblclick`,u,function(...e){n().ondblclick?.apply(this,e)}),l.append(e,u),l.pop(c)}l.delegate([`pointerdown`,`pointermove`,`pointerup`,`dblclick`]),l.create_custom_element(Dx,{handle:{},children:{},class:{}},[],[],{mode:`open`});var Ox=e=>e.minHeight??100,kx=e=>e.maxHeight??2e3,Ax=(e,t)=>Math.min(kx(t),Math.max(Ox(t),Math.round(e))),jx={resized:`Resizable--resized`,handle:`Resizable__resize-handle`},Mx={triggerPx:60,maxSpeedPx:16},Nx=e=>{let t,n=0,r=()=>{t=void 0,!(!e.isActive()||n===0)&&(e.scrollBy(n),e.onScroll(),t=requestAnimationFrame(r))},i=e=>{n=e,t===void 0&&(t=requestAnimationFrame(r))},a=()=>{t!==void 0&&(cancelAnimationFrame(t),t=void 0),n=0};return{stop:a,updateForPointer:t=>{let n=e.getViewport(),r=n.bottom-t,o=t-n.top;if(r<Mx.triggerPx){let e=Math.min(1,1-r/Mx.triggerPx);i(Math.max(1,Math.round(Mx.maxSpeedPx*e)))}else o<=0?i(-Mx.maxSpeedPx):a()}}},Px=()=>{let e=document.documentElement,t=document.body;return Math.max(e.clientHeight,t?.offsetHeight??0,t?.scrollHeight??0)},Fx=()=>{let e,t,n=()=>{t!==void 0&&(cancelAnimationFrame(t),t=void 0)};return{lock:()=>{n();let t=document.documentElement;e={previous:e?.previous??t.style.minHeight,element:t},t.style.minHeight=`${t.scrollHeight}px`},growToContent:()=>{if(!e)return;let t=e.element,n=Number.parseFloat(t.style.minHeight),r=Math.max(Number.isFinite(n)?n:0,t.scrollHeight);t.style.minHeight=`${r}px`},release:(r=!0)=>{if(n(),!e)return;let i=e,a=i.element,o=a.scrollHeight,s=Number.parseFloat(i.previous),c=Math.max(Px(),Number.isFinite(s)?s:0);if(!r||c>=o){a.style.minHeight=i.previous,e=void 0;return}let l=performance.now(),u=n=>{let r=Math.min(1,(n-l)/180),s=1-(1-r)**3;if(a.style.minHeight=`${o+(c-o)*s}px`,r<1){t=requestAnimationFrame(u);return}a.style.minHeight=i.previous,e=void 0,t=void 0};t=requestAnimationFrame(u)}}},Ix=e=>{let t=e.parentElement;for(;t&&t!==document.body&&t!==document.documentElement;){let e=window.getComputedStyle(t);if((e.overflowY===`auto`||e.overflowY===`scroll`)&&t.scrollHeight>t.clientHeight)return t;t=t.parentElement}},Lx=e=>({...jx,...e.classNames}),Rx=(e={})=>{let t,n,r,i,a=Fx(),o=n=>{if(t){if(i&&=(t.classList.remove(i),void 0),typeof n==`number`){let r=Lx(e);t.style.height=`${n}px`,t.classList.add(r.resized),i=r.resized}else t.style.removeProperty(`height`)}},s=()=>{if(n?.scrollTarget){let e=n.scrollTarget.getBoundingClientRect();return{top:e.top,bottom:e.bottom}}return{top:0,bottom:window.innerHeight}},c=e=>{e!==0&&(n?.scrollTarget?n.scrollTarget.scrollTop+=e:window.scrollBy({top:e,left:0,behavior:`instant`}))},l=()=>{if(!n||!t)return;let r=t.getBoundingClientRect(),i=n.lastClientY-n.grabOffset;o(Ax(i-r.top,e)),a.growToContent()},u=Nx({getViewport:s,isActive:()=>n!==void 0,scrollBy:c,onScroll:l}),d=(e=!0)=>{n=void 0,r=void 0,u.stop(),a.release(e)},f=i=>{if(!t||i.button!==0&&i.pointerType===`mouse`)return;i.preventDefault();let s=i.currentTarget,c=t.getBoundingClientRect();n={pointerId:i.pointerId,grabOffset:i.clientY-c.bottom,lastClientY:i.clientY,scrollTarget:Ix(t)},r=s,o(Ax(c.height,e)),a.lock(),s.setPointerCapture(i.pointerId)},p=e=>{n?.pointerId===e.pointerId&&(n.lastClientY=e.clientY,l(),u.updateForPointer(e.clientY))},m=r=>{if(n?.pointerId!==r.pointerId)return;let i=r.currentTarget;if(d(),i.hasPointerCapture(r.pointerId)&&i.releasePointerCapture(r.pointerId),!t)return;let a=Number.parseFloat(t.style.height);Number.isFinite(a)&&e.heightStore?.set(a)},h=()=>{e.heightStore?.clear(),o(void 0)},g=e=>{r===e&&d(!1)},_=i=>(t=i,o(e.heightStore?.get()),()=>{u.stop(),a.release(!1),o(void 0),n=void 0,r=void 0,t=void 0});return _.handle=()=>({class:Lx(e).handle,role:`separator`,"aria-orientation":`horizontal`,"aria-label":e.label??`Resize`,title:e.title??`Drag to resize, double-click to reset`,onpointerdown:f,onpointermove:p,onpointerup:m,onpointercancel:m,ondblclick:h,destroy:g}),_},zx=()=>{let e=new Set;return{addListener(t){return e.add(t),()=>{e.delete(t)}},notify(t){for(let n of e)n(t)}}},Bx=e=>e,Vx=e=>e,Hx=e=>e,Ux=e=>({get:()=>Vx(e.get()),set:t=>{e.set(Hx(t))},addListener:t=>e.addListener(e=>{t(Bx(e))})}),Wx=()=>{let e=zx(),t;return{get:()=>t,set:n=>{t=n,e.notify(n)},addListener:e.addListener}},Gx=(e,t=globalThis.localStorage)=>{let n=zx(),r=`app.rough.feature/sprite/${e}`;return{get:()=>{let e=t.getItem(r);return e===null?void 0:JSON.parse(e)},set:e=>{t.setItem(r,JSON.stringify(e)),n.notify(e)},addListener:n.addListener}},Kx=({datastore:e,isMock:t,spriteInstanceId:n,storage:r})=>{if(e)return Ux(e);if(t)return Wx();if(n)return Gx(n,r);throw Error(`SpriteFrame is missing a spriteInstanceId.`)},qx=l.from_html(`<div class="SpriteFrame svelte-ncf2zx"><!></div>`),Jx={hash:`svelte-ncf2zx`,code:`.SpriteFrame.svelte-ncf2zx {position:relative;flex:1;width:100%;min-height:100px;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-lg, 0.625rem);overflow-y:auto;background:var(--rough-background, white);box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));
96
+ }`};function lx(e,t){l.push(t,!0),l.append_styles(e,cx);let n=l.prop(t,`active`,15),r=l.prop(t,`tabs`,7),i=l.prop(t,`ariaLabel`,7,`Navigation`),a=e=>{let t=e.key;if(![`ArrowLeft`,`ArrowRight`,`Home`,`End`].includes(t))return;let n=e.currentTarget,r=n.closest(`[role="tablist"]`),i=Array.from(r?.querySelectorAll(`[role="tab"]`)??[]),a=i.indexOf(n);if(a===-1||i.length===0)return;e.preventDefault();let o=t===`Home`?0:t===`End`?i.length-1:t===`ArrowLeft`?(a-1+i.length)%i.length:(a+1)%i.length;i[o]?.focus(),i[o]?.click()};var o={get active(){return n()},set active(e){n(e),l.flush()},get tabs(){return r()},set tabs(e){r(e),l.flush()},get ariaLabel(){return i()},set ariaLabel(e=`Navigation`){i(e),l.flush()}},s=sx(),c=l.child(s);let u;return l.each(c,21,r,e=>e.key,(e,t)=>{var r=ox();let i;var o=l.child(r,!0);l.reset(r),l.template_effect(()=>{i=l.set_class(r,1,`tab svelte-17gs0md`,null,i,{active:n()===l.get(t).key}),l.set_attribute(r,`aria-selected`,n()===l.get(t).key),l.set_attribute(r,`tabindex`,n()===l.get(t).key?0:-1),l.set_text(o,l.get(t).label)}),l.delegated(`click`,r,()=>n(l.get(t).key)),l.delegated(`keydown`,r,a),l.append(e,r)}),l.reset(c),l.reset(s),l.template_effect(()=>{l.set_attribute(s,`aria-label`,i()),l.set_attribute(c,`aria-label`,i()),u=l.set_style(c,``,u,{"--mobile-tab-count":r().length})}),l.append(e,s),l.pop(o)}l.delegate([`click`,`keydown`]),l.create_custom_element(lx,{active:{},tabs:{},ariaLabel:{}},[],[],{mode:`open`});var ux=l.from_html(`<button><!></button>`),dx={hash:`svelte-om76s9`,code:`button.svelte-om76s9 {appearance:none;display:inline-flex;align-items:center;justify-content:center;gap:0.5rem;min-height:2.25rem;border:1px solid var(--rough-primary, oklch(0.205 0 0));border-radius:var(--rough-radius-md, 0.375rem);padding:0.5rem 1rem;background:var(--rough-primary, oklch(0.205 0 0));box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));color:var(--rough-primary-foreground, white);font:inherit;font-size:0.875rem;font-weight:500;line-height:1.25rem;white-space:nowrap;cursor:pointer;transition:background-color 120ms ease, border-color 120ms ease,
97
+ box-shadow 120ms ease, opacity 120ms ease;}button.svelte-om76s9:hover:not(:disabled) {border-color:color-mix(in oklch, var(--rough-primary, oklch(0.205 0 0)) 90%, transparent);background:color-mix(in oklch, var(--rough-primary, oklch(0.205 0 0)) 90%, transparent);}button.svelte-om76s9:focus-visible {border-color:var(--rough-ring, oklch(0.708 0 0));outline:none;box-shadow:0 0 0 3px color-mix(in oklch, var(--rough-ring, oklch(0.708 0 0)) 45%, transparent);}button.svelte-om76s9:disabled {opacity:0.5;cursor:not-allowed;}.block.svelte-om76s9 {display:flex;width:100%;}.iconOnly.svelte-om76s9 {width:2.25rem;min-width:2.25rem;min-height:2.25rem;padding:0;}.alignStart.svelte-om76s9 {justify-content:flex-start;}`};function fx(e,t){l.push(t,!0),l.append_styles(e,dx);let n=l.prop(t,`children`,7),r=l.prop(t,`class`,7,``),i=l.prop(t,`type`,7,`button`),a=l.prop(t,`disabled`,7,!1),o=l.prop(t,`onclick`,7),s=l.prop(t,`role`,7),c=l.prop(t,`block`,7,!1),u=l.prop(t,`iconOnly`,7,!1),d=l.prop(t,`alignStart`,7,!1),f=l.prop(t,`aria-label`,7),p=l.prop(t,`aria-haspopup`,7),m=l.prop(t,`aria-expanded`,7);var h={get children(){return n()},set children(e){n(e),l.flush()},get class(){return r()},set class(e=``){r(e),l.flush()},get type(){return i()},set type(e=`button`){i(e),l.flush()},get disabled(){return a()},set disabled(e=!1){a(e),l.flush()},get onclick(){return o()},set onclick(e){o(e),l.flush()},get role(){return s()},set role(e){s(e),l.flush()},get block(){return c()},set block(e=!1){c(e),l.flush()},get iconOnly(){return u()},set iconOnly(e=!1){u(e),l.flush()},get alignStart(){return d()},set alignStart(e=!1){d(e),l.flush()},get"aria-label"(){return f()},set"aria-label"(e){f(e),l.flush()},get"aria-haspopup"(){return p()},set"aria-haspopup"(e){p(e),l.flush()},get"aria-expanded"(){return m()},set"aria-expanded"(e){m(e),l.flush()}},g=ux();let _;var v=l.child(g);return l.snippet(v,()=>n()??l.noop),l.reset(g),l.template_effect(()=>{l.set_attribute(g,`type`,i()),g.disabled=a(),l.set_attribute(g,`role`,s()),l.set_attribute(g,`aria-label`,f()),l.set_attribute(g,`aria-haspopup`,p()),l.set_attribute(g,`aria-expanded`,m()),_=l.set_class(g,1,l.clsx(r()),`svelte-om76s9`,_,{block:c(),iconOnly:u(),alignStart:d()})}),l.delegated(`click`,g,function(...e){o()?.apply(this,e)}),l.append(e,g),l.pop(h)}l.delegate([`click`]),l.create_custom_element(fx,{children:{},class:{},type:{},disabled:{},onclick:{},role:{},block:{},iconOnly:{},alignStart:{},"aria-label":{},"aria-haspopup":{},"aria-expanded":{}},[],[],{mode:`open`});var px=e=>t=>{let n=e??window.document.body;return n.appendChild(t),t.hidden=!1,()=>{t.parentNode===n&&n.removeChild(t)}},mx=l.from_html(`<dialog class="svelte-1phmmvx"><!></dialog>`),hx={hash:`svelte-1phmmvx`,code:`dialog.svelte-1phmmvx {position:fixed;inset:2rem;width:auto;height:auto;max-width:none;max-height:none;margin:0;border:none;padding:0;background:transparent;}dialog.svelte-1phmmvx::backdrop {background:rgb(0 0 0 / 0.5);}`};function gx(e,t){l.push(t,!0),l.append_styles(e,hx);let n=l.prop(t,`isOpen`,15,!0),r=l.prop(t,`target`,7),i=l.prop(t,`onclose`,7),a=l.prop(t,`oncancel`,7),o=l.prop(t,`children`,7),s=l.state(void 0);l.user_effect(()=>{if(l.get(s)){if(n()&&!l.get(s).open){l.get(s).showModal();return}!n()&&l.get(s).open&&l.get(s).close()}});var c={get isOpen(){return n()},set isOpen(e=!0){n(e),l.flush()},get target(){return r()},set target(e){r(e),l.flush()},get onclose(){return i()},set onclose(e){i(e),l.flush()},get oncancel(){return a()},set oncancel(e){a(e),l.flush()},get children(){return o()},set children(e){o(e),l.flush()}},u=mx(),d=l.child(u);return l.snippet(d,()=>o()??l.noop),l.reset(u),l.bind_this(u,e=>l.set(s,e),()=>l.get(s)),l.attach(u,()=>px(r())),l.event(`close`,u,()=>{n(!1),i()?.()}),l.event(`cancel`,u,function(...e){a()?.apply(this,e)}),l.append(e,u),l.pop(c)}l.create_custom_element(gx,{isOpen:{},target:{},onclose:{},oncancel:{},children:{}},[],[],{mode:`open`});var _x=l.from_html(`<button><!></button>`),vx={hash:`svelte-1yyy6r1`,code:`button.svelte-1yyy6r1 {appearance:none;display:inline-flex;align-items:center;justify-content:center;gap:0.5rem;min-height:2.25rem;border:1px solid transparent;border-radius:var(--rough-radius-md, 0.375rem);padding:0.5rem 1rem;background:var(--rough-secondary, oklch(0.97 0 0));box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));color:var(--rough-secondary-foreground, oklch(0.205 0 0));font:inherit;font-size:0.875rem;font-weight:500;line-height:1.25rem;white-space:nowrap;cursor:pointer;transition:background-color 120ms ease, border-color 120ms ease,
98
+ box-shadow 120ms ease, opacity 120ms ease;}button.svelte-1yyy6r1:hover:not(:disabled) {background:color-mix(in oklch, var(--rough-secondary, oklch(0.97 0 0)) 80%, var(--rough-foreground, black));}button.svelte-1yyy6r1:focus-visible {border-color:var(--rough-ring, oklch(0.708 0 0));outline:none;box-shadow:0 0 0 3px color-mix(in oklch, var(--rough-ring, oklch(0.708 0 0)) 45%, transparent);}button.svelte-1yyy6r1:disabled {opacity:0.5;cursor:not-allowed;}.block.svelte-1yyy6r1 {display:flex;width:100%;}.iconOnly.svelte-1yyy6r1 {width:2.25rem;min-width:2.25rem;min-height:2.25rem;padding:0;}.alignStart.svelte-1yyy6r1 {justify-content:flex-start;}`};function yx(e,t){l.push(t,!0),l.append_styles(e,vx);let n=l.prop(t,`children`,7),r=l.prop(t,`class`,7,``),i=l.prop(t,`type`,7,`button`),a=l.prop(t,`disabled`,7,!1),o=l.prop(t,`onclick`,7),s=l.prop(t,`role`,7),c=l.prop(t,`block`,7,!1),u=l.prop(t,`iconOnly`,7,!1),d=l.prop(t,`alignStart`,7,!1),f=l.prop(t,`aria-label`,7),p=l.prop(t,`aria-haspopup`,7),m=l.prop(t,`aria-expanded`,7);var h={get children(){return n()},set children(e){n(e),l.flush()},get class(){return r()},set class(e=``){r(e),l.flush()},get type(){return i()},set type(e=`button`){i(e),l.flush()},get disabled(){return a()},set disabled(e=!1){a(e),l.flush()},get onclick(){return o()},set onclick(e){o(e),l.flush()},get role(){return s()},set role(e){s(e),l.flush()},get block(){return c()},set block(e=!1){c(e),l.flush()},get iconOnly(){return u()},set iconOnly(e=!1){u(e),l.flush()},get alignStart(){return d()},set alignStart(e=!1){d(e),l.flush()},get"aria-label"(){return f()},set"aria-label"(e){f(e),l.flush()},get"aria-haspopup"(){return p()},set"aria-haspopup"(e){p(e),l.flush()},get"aria-expanded"(){return m()},set"aria-expanded"(e){m(e),l.flush()}},g=_x();let _;var v=l.child(g);return l.snippet(v,()=>n()??l.noop),l.reset(g),l.template_effect(()=>{l.set_attribute(g,`type`,i()),g.disabled=a(),l.set_attribute(g,`role`,s()),l.set_attribute(g,`aria-label`,f()),l.set_attribute(g,`aria-haspopup`,p()),l.set_attribute(g,`aria-expanded`,m()),_=l.set_class(g,1,l.clsx(r()),`svelte-1yyy6r1`,_,{block:c(),iconOnly:u(),alignStart:d()})}),l.delegated(`click`,g,function(...e){o()?.apply(this,e)}),l.append(e,g),l.pop(h)}l.delegate([`click`]),l.create_custom_element(yx,{children:{},class:{},type:{},disabled:{},onclick:{},role:{},block:{},iconOnly:{},alignStart:{},"aria-label":{},"aria-haspopup":{},"aria-expanded":{}},[],[],{mode:`open`});var bx=e=>{let t=(e,n={})=>{let r=e?`[${e}] `:``,i=(e,t,i)=>{let a={...n,...i},o=`${r}${t}`,s=Object.keys(a).length>0;e===`info`?s?console.info(o,a):console.info(o):s?console.error(o,a):console.error(o)};return{info:(e,t)=>{i(`info`,e,t)},error:(e,t)=>{i(`error`,e,t)},child:(r,i={})=>{let a=e?`${e}:${r}`:r;return t(a,{...n,...i})}}};return t(e)},xx=`2.0.0`,Sx=`app.rough.frame.server.port`,Cx=(e,t)=>!!e&&typeof e==`object`&&`type`in e&&e.type===t&&`version`in e&&typeof e.version==`string`,wx=class{serverWindow;getClientWindow;clientOrigin;createSession;createMessageChannel;logger;session;listening=!1;constructor(e){this.serverWindow=e.serverWindow,this.getClientWindow=e.getClientWindow,this.clientOrigin=e.clientOrigin,this.createSession=e.createSession,this.createMessageChannel=e.createMessageChannel??(()=>new MessageChannel),this.logger=(e.logger??bx()).child(`channel-server`)}start(){this.listening||=(this.serverWindow.addEventListener(`message`,this.onMessage),!0)}stop(){this.listening&&(this.serverWindow.removeEventListener(`message`,this.onMessage),this.listening=!1,this.disposeSession())}onMessage=e=>{if(this.clientOrigin!==`*`&&e.origin!==this.clientOrigin){this.logger.info(`message ignored`,{reason:`unexpected origin`,origin:e.origin});return}if(!Cx(e.data,`app.rough.frame.client.ready`)){this.logger.info(`message ignored`,{reason:`unexpected type`,data:e.data});return}let t=this.getClientWindow();if(!t||e.source!==t){this.logger.info(`message ignored`,{reason:`unexpected source`});return}let n=this.createMessageChannel();this.disposeSession(),this.session=this.createSession(n.port1),t.postMessage({type:Sx,version:xx},{targetOrigin:this.clientOrigin,transfer:[n.port2]})};disposeSession(){this.session&&=(this.session[Symbol.dispose]?.(),void 0)}},Tx=[{},{}],Ex=e=>{let{store:t,iframeElement:n,onReportSize:r,getBridgeMethodDefinitions:i}=e;return{_internal:{reportSize(e){n&&(n.style.minHeight=`${e.height}px`),r?.(e)},getBridgeMethodDefinitions(){return i?.()??[]},state:{get(){return t.get()??Tx},set(e){t.set(e)},addListener(e){let n=e.dup(),r=t.addListener(n);return()=>{r(),n[Symbol.dispose]()}}}}}},Dx=class{containerElement;channelServer;iframeSrc;iframeElement;constructor(e){let{iframe:t,serverWindow:n=globalThis.window,clientOrigin:r=`*`,getTools:i,getBridgeMethodDefinitions:a,logger:o=bx(),store:s}=e,c;if(`contentWindow`in t)this.iframeElement=void 0,c=()=>t.contentWindow;else{let{containerElement:e,src:n,title:r,allow:i=[`fullscreen`,`camera`,`microphone`]}=t;this.containerElement=e,this.iframeElement=document.createElement(`iframe`),this.iframeSrc=n,this.iframeElement.width=`100%`,this.iframeElement.title=r,this.iframeElement.allow=i.join(`; `),this.iframeElement.style=`border: none;`,e.appendChild(this.iframeElement),c=()=>this.iframeElement?.contentWindow??void 0}let l=Ex({store:s,iframeElement:this.iframeElement,onReportSize:t.onReportSize,getBridgeMethodDefinitions:a});this.channelServer=new wx({getClientWindow:c,serverWindow:n,clientOrigin:r,logger:o,createSession:e=>{let t=i();return f(e,{...t,...l})}})}start(){this.channelServer.start(),this.iframeElement&&this.iframeSrc!==void 0&&(this.iframeElement.src=this.iframeSrc,this.iframeSrc=void 0)}stop(){this.channelServer.stop(),this.containerElement&&this.iframeElement&&(this.containerElement.removeChild(this.iframeElement),this.iframeElement=void 0)}},Ox=l.from_html(`<div><!></div>`);function kx(e,t){l.push(t,!0);let n=l.prop(t,`handle`,7),r=l.prop(t,`children`,7),i=l.prop(t,`class`,7,``),a,s=l.derived(()=>[n().class,i()].filter(Boolean).join(` `));o(()=>{a&&n().destroy(a)});var c={get handle(){return n()},set handle(e){n(e),l.flush()},get children(){return r()},set children(e){r(e),l.flush()},get class(){return i()},set class(e=``){i(e),l.flush()}},u=Ox(),d=l.child(u);return l.snippet(d,()=>r()??l.noop),l.reset(u),l.bind_this(u,e=>a=e,()=>a),l.template_effect(()=>{l.set_class(u,1,l.clsx(l.get(s))),l.set_attribute(u,`role`,n().role),l.set_attribute(u,`aria-orientation`,n()[`aria-orientation`]),l.set_attribute(u,`aria-label`,n()[`aria-label`]),l.set_attribute(u,`title`,n().title)}),l.delegated(`pointerdown`,u,function(...e){n().onpointerdown?.apply(this,e)}),l.delegated(`pointermove`,u,function(...e){n().onpointermove?.apply(this,e)}),l.delegated(`pointerup`,u,function(...e){n().onpointerup?.apply(this,e)}),l.event(`pointercancel`,u,function(...e){n().onpointercancel?.apply(this,e)}),l.delegated(`dblclick`,u,function(...e){n().ondblclick?.apply(this,e)}),l.append(e,u),l.pop(c)}l.delegate([`pointerdown`,`pointermove`,`pointerup`,`dblclick`]),l.create_custom_element(kx,{handle:{},children:{},class:{}},[],[],{mode:`open`});var Ax=e=>e.minHeight??100,jx=e=>e.maxHeight??2e3,Mx=(e,t)=>Math.min(jx(t),Math.max(Ax(t),Math.round(e))),Nx={resized:`Resizable--resized`,handle:`Resizable__resize-handle`},Px={triggerPx:60,maxSpeedPx:16},Fx=e=>{let t,n=0,r=()=>{t=void 0,!(!e.isActive()||n===0)&&(e.scrollBy(n),e.onScroll(),t=requestAnimationFrame(r))},i=e=>{n=e,t===void 0&&(t=requestAnimationFrame(r))},a=()=>{t!==void 0&&(cancelAnimationFrame(t),t=void 0),n=0};return{stop:a,updateForPointer:t=>{let n=e.getViewport(),r=n.bottom-t,o=t-n.top;if(r<Px.triggerPx){let e=Math.min(1,1-r/Px.triggerPx);i(Math.max(1,Math.round(Px.maxSpeedPx*e)))}else o<=0?i(-Px.maxSpeedPx):a()}}},Ix=()=>{let e=document.documentElement,t=document.body;return Math.max(e.clientHeight,t?.offsetHeight??0,t?.scrollHeight??0)},Lx=()=>{let e,t,n=()=>{t!==void 0&&(cancelAnimationFrame(t),t=void 0)};return{lock:()=>{n();let t=document.documentElement;e={previous:e?.previous??t.style.minHeight,element:t},t.style.minHeight=`${t.scrollHeight}px`},growToContent:()=>{if(!e)return;let t=e.element,n=Number.parseFloat(t.style.minHeight),r=Math.max(Number.isFinite(n)?n:0,t.scrollHeight);t.style.minHeight=`${r}px`},release:(r=!0)=>{if(n(),!e)return;let i=e,a=i.element,o=a.scrollHeight,s=Number.parseFloat(i.previous),c=Math.max(Ix(),Number.isFinite(s)?s:0);if(!r||c>=o){a.style.minHeight=i.previous,e=void 0;return}let l=performance.now(),u=n=>{let r=Math.min(1,(n-l)/180),s=1-(1-r)**3;if(a.style.minHeight=`${o+(c-o)*s}px`,r<1){t=requestAnimationFrame(u);return}a.style.minHeight=i.previous,e=void 0,t=void 0};t=requestAnimationFrame(u)}}},Rx=e=>{let t=e.parentElement;for(;t&&t!==document.body&&t!==document.documentElement;){let e=window.getComputedStyle(t);if((e.overflowY===`auto`||e.overflowY===`scroll`)&&t.scrollHeight>t.clientHeight)return t;t=t.parentElement}},zx=e=>({...Nx,...e.classNames}),Bx=(e={})=>{let t,n,r,i,a=Lx(),o=n=>{if(t){if(i&&=(t.classList.remove(i),void 0),typeof n==`number`){let r=zx(e);t.style.height=`${n}px`,t.classList.add(r.resized),i=r.resized}else t.style.removeProperty(`height`)}},s=()=>{if(n?.scrollTarget){let e=n.scrollTarget.getBoundingClientRect();return{top:e.top,bottom:e.bottom}}return{top:0,bottom:window.innerHeight}},c=e=>{e!==0&&(n?.scrollTarget?n.scrollTarget.scrollTop+=e:window.scrollBy({top:e,left:0,behavior:`instant`}))},l=()=>{if(!n||!t)return;let r=t.getBoundingClientRect(),i=n.lastClientY-n.grabOffset;o(Mx(i-r.top,e)),a.growToContent()},u=Fx({getViewport:s,isActive:()=>n!==void 0,scrollBy:c,onScroll:l}),d=(e=!0)=>{n=void 0,r=void 0,u.stop(),a.release(e)},f=i=>{if(!t||i.button!==0&&i.pointerType===`mouse`)return;i.preventDefault();let s=i.currentTarget,c=t.getBoundingClientRect();n={pointerId:i.pointerId,grabOffset:i.clientY-c.bottom,lastClientY:i.clientY,scrollTarget:Rx(t)},r=s,o(Mx(c.height,e)),a.lock(),s.setPointerCapture(i.pointerId)},p=e=>{n?.pointerId===e.pointerId&&(n.lastClientY=e.clientY,l(),u.updateForPointer(e.clientY))},m=r=>{if(n?.pointerId!==r.pointerId)return;let i=r.currentTarget;if(d(),i.hasPointerCapture(r.pointerId)&&i.releasePointerCapture(r.pointerId),!t)return;let a=Number.parseFloat(t.style.height);Number.isFinite(a)&&e.heightStore?.set(a)},h=()=>{e.heightStore?.clear(),o(void 0)},g=e=>{r===e&&d(!1)},_=i=>(t=i,o(e.heightStore?.get()),()=>{u.stop(),a.release(!1),o(void 0),n=void 0,r=void 0,t=void 0});return _.handle=()=>({class:zx(e).handle,role:`separator`,"aria-orientation":`horizontal`,"aria-label":e.label??`Resize`,title:e.title??`Drag to resize, double-click to reset`,onpointerdown:f,onpointermove:p,onpointerup:m,onpointercancel:m,ondblclick:h,destroy:g}),_},Vx=()=>{let e=new Set;return{addListener(t){return e.add(t),()=>{e.delete(t)}},notify(t){for(let n of e)n(t)}}},Hx=e=>e,Ux=e=>e,Wx=e=>e,Gx=e=>({get:()=>Ux(e.get()),set:t=>{e.set(Wx(t))},addListener:t=>e.addListener(e=>{t(Hx(e))})}),Kx=()=>{let e=Vx(),t;return{get:()=>t,set:n=>{t=n,e.notify(n)},addListener:e.addListener}},qx=(e,t=globalThis.localStorage)=>{let n=Vx(),r=`app.rough.feature/sprite/${e}`;return{get:()=>{let e=t.getItem(r);return e===null?void 0:JSON.parse(e)},set:e=>{t.setItem(r,JSON.stringify(e)),n.notify(e)},addListener:n.addListener}},Jx=({datastore:e,isMock:t,spriteInstanceId:n,storage:r})=>{if(e)return Gx(e);if(t)return Kx();if(n)return qx(n,r);throw Error(`SpriteFrame is missing a spriteInstanceId.`)},Yx=l.from_html(`<div class="SpriteFrame svelte-ncf2zx"><!></div>`),Xx={hash:`svelte-ncf2zx`,code:`.SpriteFrame.svelte-ncf2zx {position:relative;flex:1;width:100%;min-height:100px;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-lg, 0.625rem);overflow-y:auto;background:var(--rough-background, white);box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));
99
99
  /* The frame's iframe sets its own min-height from reportSize, so tall
100
100
  content would push past the bounded preview viewport and clip at the
101
101
  modal. Scroll inside the frame instead. */}.SpriteFrame.svelte-ncf2zx.Resizable--resized {flex:none;overflow:hidden;}.SpriteFrame.svelte-ncf2zx.Resizable--resized iframe {height:100%;min-height:0 !important;}.SpriteFrame.svelte-ncf2zx .Resizable__resize-handle {position:absolute;right:0;bottom:0;left:0;z-index:1;height:10px;cursor:ns-resize;touch-action:none;}.SpriteFrame.svelte-ncf2zx .Resizable__resize-handle::after {content:'';position:absolute;bottom:3px;left:50%;width:3rem;height:3px;border-radius:999px;background:var(--rough-border, oklch(0.922 0 0));transform:translateX(-50%);transition:background-color 120ms ease, height 120ms ease;}.SpriteFrame.svelte-ncf2zx .Resizable__resize-handle:hover::after,
102
- .SpriteFrame.svelte-ncf2zx .Resizable__resize-handle:active::after {height:4px;background:var(--rough-ring, oklch(0.708 0 0));}`};function Yx(e,t){l.push(t,!0),l.append_styles(e,Jx);let n=l.prop(t,`client`,7),r=l.prop(t,`spriteBuildId`,7),i=l.prop(t,`artifactUrl`,7),a=l.prop(t,`toolList`,7),o=l.prop(t,`datastore`,7),s=l.prop(t,`isMock`,7),c=l.prop(t,`spriteInstanceId`,7),u=l.prop(t,`minHeight`,7,100),d=l.prop(t,`maxHeight`,7,2e3),f=l.derived(()=>n()?Xg(n()).store:void 0),p=l.derived(()=>l.get(f)?lb(l.get(f).spriteBuild.get(r())):lb.undefined),m=l.derived(()=>l.get(p)._),h=l.derived(()=>typeof i()==`string`?i():l.get(m)?.artifactUrl??void 0),g=l.state(void 0),_=l.derived(()=>Kx({datastore:o(),isMock:s(),spriteInstanceId:c()})),v=e=>{if(!e||s()){let e;return{get:()=>e,set:t=>{e=t},clear:()=>{e=void 0}}}let t=`app.rough.feature/sprite/${e}/height`;return{get:()=>{let e=localStorage.getItem(t);if(e!==null)try{let t=JSON.parse(e);return typeof t?.height==`number`?t.height:void 0}catch{return}},set:e=>{localStorage.setItem(t,JSON.stringify({height:e}))},clear:()=>{localStorage.removeItem(t)}}},y=l.derived(()=>v(c())),b=Rx({get minHeight(){return u()},get maxHeight(){return d()},get heightStore(){return l.get(y)},label:`Resize Rough feature`,title:`Drag to resize, double-click to reset`});l.user_effect(()=>{if(!l.get(h)||!l.get(g))return;let e=new Tx({iframe:{containerElement:l.get(g),src:l.get(h),title:`Sprite Frame`},getTools:()=>s()?re(a()):ne(a()),getBridgeMethodDefinitions:()=>a().map(e=>e.toJSON()),store:l.get(_)});return e.start(),()=>{e.stop()}});var ee={get client(){return n()},set client(e){n(e),l.flush()},get spriteBuildId(){return r()},set spriteBuildId(e){r(e),l.flush()},get artifactUrl(){return i()},set artifactUrl(e){i(e),l.flush()},get toolList(){return a()},set toolList(e){a(e),l.flush()},get datastore(){return o()},set datastore(e){o(e),l.flush()},get isMock(){return s()},set isMock(e){s(e),l.flush()},get spriteInstanceId(){return c()},set spriteInstanceId(e){c(e),l.flush()},get minHeight(){return u()},set minHeight(e=100){u(e),l.flush()},get maxHeight(){return d()},set maxHeight(e=2e3){d(e),l.flush()}},te=qx(),ie=l.child(te);{let e=l.derived(()=>b.handle());Dx(ie,{get handle(){return l.get(e)}})}return l.reset(te),l.bind_this(te,e=>l.set(g,e),()=>l.get(g)),l.attach(te,()=>b),l.append(e,te),l.pop(ee)}l.create_custom_element(Yx,{client:{},spriteBuildId:{},artifactUrl:{},toolList:{},datastore:{},isMock:{},spriteInstanceId:{},minHeight:{},maxHeight:{}},[],[],{mode:`open`});var Xx=l.from_html(`<button type="button" role="tab"> </button>`),Zx=l.from_html(`<div class="TabBar svelte-1jp57o0" role="tablist"></div>`),Qx={hash:`svelte-1jp57o0`,code:`.TabBar.svelte-1jp57o0 {display:inline-flex;align-items:center;justify-content:center;gap:0.125rem;flex-shrink:0;width:fit-content;margin:0.75rem;border-radius:var(--rough-radius-lg, 0.625rem);padding:0.1875rem;background:var(--rough-muted, oklch(0.97 0 0));color:var(--rough-muted-foreground, oklch(0.556 0 0));}.tab.svelte-1jp57o0 {appearance:none;height:2rem;border:1px solid transparent;border-radius:var(--rough-radius-md, 0.375rem);padding:0.25rem 0.75rem;background:transparent;color:inherit;font:inherit;font-size:0.875rem;font-weight:500;white-space:nowrap;cursor:pointer;transition:color 120ms ease, background-color 120ms ease,
103
- border-color 120ms ease, box-shadow 120ms ease;}.tab.svelte-1jp57o0:hover:not(:disabled) {color:var(--rough-foreground, oklch(0.145 0 0));}.tab.active.svelte-1jp57o0 {border-color:var(--rough-border, oklch(0.922 0 0));background:var(--rough-background, white);box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));color:var(--rough-foreground, oklch(0.145 0 0));}.tab.svelte-1jp57o0:focus-visible {border-color:var(--rough-ring, oklch(0.708 0 0));outline:none;box-shadow:0 0 0 3px color-mix(in oklch, var(--rough-ring, oklch(0.708 0 0)) 45%, transparent);}.tab.svelte-1jp57o0:disabled {opacity:0.5;cursor:not-allowed;}`};function $x(e,t){l.push(t,!0),l.append_styles(e,Qx);let n=l.prop(t,`active`,15),r=l.prop(t,`tabs`,7),i=e=>{e.disabled||n(e.key)},a=e=>{let t=e.key;if(![`ArrowLeft`,`ArrowRight`,`Home`,`End`].includes(t))return;let n=e.currentTarget,r=n.closest(`[role="tablist"]`),i=Array.from(r?.querySelectorAll(`[role="tab"]:not(:disabled)`)??[]),a=i.indexOf(n);if(a===-1||i.length===0)return;e.preventDefault();let o=t===`Home`?0:t===`End`?i.length-1:t===`ArrowLeft`?(a-1+i.length)%i.length:(a+1)%i.length;i[o]?.focus(),i[o]?.click()};var o={get active(){return n()},set active(e){n(e),l.flush()},get tabs(){return r()},set tabs(e){r(e),l.flush()}},s=Zx();return l.each(s,21,r,e=>e.key,(e,t)=>{var r=Xx();let o;var s=l.child(r,!0);l.reset(r),l.template_effect(()=>{o=l.set_class(r,1,`tab svelte-1jp57o0`,null,o,{active:n()===l.get(t).key}),l.set_attribute(r,`aria-selected`,n()===l.get(t).key),l.set_attribute(r,`tabindex`,n()===l.get(t).key?0:-1),r.disabled=l.get(t).disabled,l.set_text(s,l.get(t).label)}),l.delegated(`click`,r,()=>i(l.get(t))),l.delegated(`keydown`,r,a),l.append(e,r)}),l.reset(s),l.append(e,s),l.pop(o)}l.delegate([`click`,`keydown`]),l.create_custom_element($x,{active:{},tabs:{}},[],[],{mode:`open`});var eS=l.from_html(`<div role="tabpanel"><!></div>`),tS={hash:`svelte-1ermak1`,code:`.TabPanel.svelte-1ermak1 {display:none;min-width:0;min-height:0;}.TabPanel.isActive.svelte-1ermak1 {display:flex;flex:1;flex-direction:column;}`};function nS(e,t){l.push(t,!0),l.append_styles(e,tS);let n=l.prop(t,`isActive`,7),r=l.prop(t,`children`,7),i=l.prop(t,`class`,7,``);var a={get isActive(){return n()},set isActive(e){n(e),l.flush()},get children(){return r()},set children(e){r(e),l.flush()},get class(){return i()},set class(e=``){i(e),l.flush()}},o=eS();let s;var c=l.child(o);return l.snippet(c,()=>r()??l.noop),l.reset(o),l.template_effect(()=>{s=l.set_class(o,1,`TabPanel ${i()}`,`svelte-1ermak1`,s,{isActive:n()}),l.set_attribute(o,`aria-hidden`,!n()),o.inert=!n()}),l.append(e,o),l.pop(a)}l.create_custom_element(nS,{isActive:{},children:{},class:{}},[],[],{mode:`open`});var rS=new Set([`$$slots`,`$$events`,`$$legacy`,`$$host`]);function iS(e,t){let n=l.rest_props(t,rS),r=[[`path`,{d:`m6 9 6 6 6-6`}]];l_(e,l.spread_props({name:`chevron-down`},()=>n,{get iconNode(){return r}}))}l.create_custom_element(iS,{},[],[],{mode:`open`});var aS=l.from_html(`<div class="preview svelte-khztz9"><!></div>`),oS=l.from_html(`<details class="Accordion svelte-khztz9"><summary class="svelte-khztz9"><header class="svelte-khztz9"><span class="heading svelte-khztz9"><!></span> <span class="chevron svelte-khztz9"><!></span></header> <!></summary> <!></details>`),sS={hash:`svelte-khztz9`,code:`.Accordion.svelte-khztz9 {display:flex;gap:0.5rem;flex-direction:column;box-sizing:border-box;width:100%;max-width:420px;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-lg, 0.625rem);padding:0.75rem 0.85rem;background:var(--rough-card, white);box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));&[open] {
102
+ .SpriteFrame.svelte-ncf2zx .Resizable__resize-handle:active::after {height:4px;background:var(--rough-ring, oklch(0.708 0 0));}`};function Zx(e,t){l.push(t,!0),l.append_styles(e,Xx);let n=l.prop(t,`client`,7),r=l.prop(t,`spriteBuildId`,7),i=l.prop(t,`artifactUrl`,7),a=l.prop(t,`toolList`,7),o=l.prop(t,`datastore`,7),s=l.prop(t,`isMock`,7),c=l.prop(t,`spriteInstanceId`,7),u=l.prop(t,`minHeight`,7,100),d=l.prop(t,`maxHeight`,7,2e3),f=l.derived(()=>n()?Qg(n()).store:void 0),p=l.derived(()=>l.get(f)?db(l.get(f).spriteBuild.get(r())):db.undefined),m=l.derived(()=>l.get(p)._),h=l.derived(()=>typeof i()==`string`?i():l.get(m)?.artifactUrl??void 0),g=l.state(void 0),_=l.derived(()=>Jx({datastore:o(),isMock:s(),spriteInstanceId:c()})),v=e=>{if(!e||s()){let e;return{get:()=>e,set:t=>{e=t},clear:()=>{e=void 0}}}let t=`app.rough.feature/sprite/${e}/height`;return{get:()=>{let e=localStorage.getItem(t);if(e!==null)try{let t=JSON.parse(e);return typeof t?.height==`number`?t.height:void 0}catch{return}},set:e=>{localStorage.setItem(t,JSON.stringify({height:e}))},clear:()=>{localStorage.removeItem(t)}}},y=l.derived(()=>v(c())),b=Bx({get minHeight(){return u()},get maxHeight(){return d()},get heightStore(){return l.get(y)},label:`Resize Rough feature`,title:`Drag to resize, double-click to reset`});l.user_effect(()=>{if(!l.get(h)||!l.get(g))return;let e=new Dx({iframe:{containerElement:l.get(g),src:l.get(h),title:`Sprite Frame`},getTools:()=>s()?ne(a()):te(a()),getBridgeMethodDefinitions:()=>a().map(e=>e.toJSON()),store:l.get(_)});return e.start(),()=>{e.stop()}});var ee={get client(){return n()},set client(e){n(e),l.flush()},get spriteBuildId(){return r()},set spriteBuildId(e){r(e),l.flush()},get artifactUrl(){return i()},set artifactUrl(e){i(e),l.flush()},get toolList(){return a()},set toolList(e){a(e),l.flush()},get datastore(){return o()},set datastore(e){o(e),l.flush()},get isMock(){return s()},set isMock(e){s(e),l.flush()},get spriteInstanceId(){return c()},set spriteInstanceId(e){c(e),l.flush()},get minHeight(){return u()},set minHeight(e=100){u(e),l.flush()},get maxHeight(){return d()},set maxHeight(e=2e3){d(e),l.flush()}},x=Yx(),re=l.child(x);{let e=l.derived(()=>b.handle());kx(re,{get handle(){return l.get(e)}})}return l.reset(x),l.bind_this(x,e=>l.set(g,e),()=>l.get(g)),l.attach(x,()=>b),l.append(e,x),l.pop(ee)}l.create_custom_element(Zx,{client:{},spriteBuildId:{},artifactUrl:{},toolList:{},datastore:{},isMock:{},spriteInstanceId:{},minHeight:{},maxHeight:{}},[],[],{mode:`open`});var Qx=l.from_html(`<button type="button" role="tab"> </button>`),$x=l.from_html(`<div class="TabBar svelte-1jp57o0" role="tablist"></div>`),eS={hash:`svelte-1jp57o0`,code:`.TabBar.svelte-1jp57o0 {display:inline-flex;align-items:center;justify-content:center;gap:0.125rem;flex-shrink:0;width:fit-content;margin:0.75rem;border-radius:var(--rough-radius-lg, 0.625rem);padding:0.1875rem;background:var(--rough-muted, oklch(0.97 0 0));color:var(--rough-muted-foreground, oklch(0.556 0 0));}.tab.svelte-1jp57o0 {appearance:none;height:2rem;border:1px solid transparent;border-radius:var(--rough-radius-md, 0.375rem);padding:0.25rem 0.75rem;background:transparent;color:inherit;font:inherit;font-size:0.875rem;font-weight:500;white-space:nowrap;cursor:pointer;transition:color 120ms ease, background-color 120ms ease,
103
+ border-color 120ms ease, box-shadow 120ms ease;}.tab.svelte-1jp57o0:hover:not(:disabled) {color:var(--rough-foreground, oklch(0.145 0 0));}.tab.active.svelte-1jp57o0 {border-color:var(--rough-border, oklch(0.922 0 0));background:var(--rough-background, white);box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));color:var(--rough-foreground, oklch(0.145 0 0));}.tab.svelte-1jp57o0:focus-visible {border-color:var(--rough-ring, oklch(0.708 0 0));outline:none;box-shadow:0 0 0 3px color-mix(in oklch, var(--rough-ring, oklch(0.708 0 0)) 45%, transparent);}.tab.svelte-1jp57o0:disabled {opacity:0.5;cursor:not-allowed;}`};function tS(e,t){l.push(t,!0),l.append_styles(e,eS);let n=l.prop(t,`active`,15),r=l.prop(t,`tabs`,7),i=e=>{e.disabled||n(e.key)},a=e=>{let t=e.key;if(![`ArrowLeft`,`ArrowRight`,`Home`,`End`].includes(t))return;let n=e.currentTarget,r=n.closest(`[role="tablist"]`),i=Array.from(r?.querySelectorAll(`[role="tab"]:not(:disabled)`)??[]),a=i.indexOf(n);if(a===-1||i.length===0)return;e.preventDefault();let o=t===`Home`?0:t===`End`?i.length-1:t===`ArrowLeft`?(a-1+i.length)%i.length:(a+1)%i.length;i[o]?.focus(),i[o]?.click()};var o={get active(){return n()},set active(e){n(e),l.flush()},get tabs(){return r()},set tabs(e){r(e),l.flush()}},s=$x();return l.each(s,21,r,e=>e.key,(e,t)=>{var r=Qx();let o;var s=l.child(r,!0);l.reset(r),l.template_effect(()=>{o=l.set_class(r,1,`tab svelte-1jp57o0`,null,o,{active:n()===l.get(t).key}),l.set_attribute(r,`aria-selected`,n()===l.get(t).key),l.set_attribute(r,`tabindex`,n()===l.get(t).key?0:-1),r.disabled=l.get(t).disabled,l.set_text(s,l.get(t).label)}),l.delegated(`click`,r,()=>i(l.get(t))),l.delegated(`keydown`,r,a),l.append(e,r)}),l.reset(s),l.append(e,s),l.pop(o)}l.delegate([`click`,`keydown`]),l.create_custom_element(tS,{active:{},tabs:{}},[],[],{mode:`open`});var nS=l.from_html(`<div role="tabpanel"><!></div>`),rS={hash:`svelte-1ermak1`,code:`.TabPanel.svelte-1ermak1 {display:none;min-width:0;min-height:0;}.TabPanel.isActive.svelte-1ermak1 {display:flex;flex:1;flex-direction:column;}`};function iS(e,t){l.push(t,!0),l.append_styles(e,rS);let n=l.prop(t,`isActive`,7),r=l.prop(t,`children`,7),i=l.prop(t,`class`,7,``);var a={get isActive(){return n()},set isActive(e){n(e),l.flush()},get children(){return r()},set children(e){r(e),l.flush()},get class(){return i()},set class(e=``){i(e),l.flush()}},o=nS();let s;var c=l.child(o);return l.snippet(c,()=>r()??l.noop),l.reset(o),l.template_effect(()=>{s=l.set_class(o,1,`TabPanel ${i()}`,`svelte-1ermak1`,s,{isActive:n()}),l.set_attribute(o,`aria-hidden`,!n()),o.inert=!n()}),l.append(e,o),l.pop(a)}l.create_custom_element(iS,{isActive:{},children:{},class:{}},[],[],{mode:`open`});var aS=new Set([`$$slots`,`$$events`,`$$legacy`,`$$host`]);function oS(e,t){let n=l.rest_props(t,aS),r=[[`path`,{d:`m6 9 6 6 6-6`}]];d_(e,l.spread_props({name:`chevron-down`},()=>n,{get iconNode(){return r}}))}l.create_custom_element(oS,{},[],[],{mode:`open`});var sS=l.from_html(`<div class="preview svelte-khztz9"><!></div>`),cS=l.from_html(`<details class="Accordion svelte-khztz9"><summary class="svelte-khztz9"><header class="svelte-khztz9"><span class="heading svelte-khztz9"><!></span> <span class="chevron svelte-khztz9"><!></span></header> <!></summary> <!></details>`),lS={hash:`svelte-khztz9`,code:`.Accordion.svelte-khztz9 {display:flex;gap:0.5rem;flex-direction:column;box-sizing:border-box;width:100%;max-width:420px;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-lg, 0.625rem);padding:0.75rem 0.85rem;background:var(--rough-card, white);box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));&[open] {
104
104
  /* note: we must use strict descendant selectors here */
105
105
  /* otherwise nested Accordions will not be displayed correctly */& > summary:where(.svelte-khztz9) > header:where(.svelte-khztz9) > .chevron:where(.svelte-khztz9) {transform:rotate(0deg);}& > summary:where(.svelte-khztz9) > .preview:where(.svelte-khztz9) {display:none;}}}summary.svelte-khztz9 {display:flex;flex-direction:column;}summary.svelte-khztz9:focus-visible {outline:none;}summary.svelte-khztz9:focus-visible header:where(.svelte-khztz9) {border-color:var(--rough-ring, oklch(0.708 0 0));box-shadow:0 0 0 3px color-mix(in oklch, var(--rough-ring, oklch(0.708 0 0)) 45%, transparent);}header.svelte-khztz9 {display:flex;align-items:center;justify-content:space-between;gap:0.5rem;width:100%;border:1px solid transparent;border-radius:var(--rough-radius-md, 0.375rem);padding:0.25rem 0.35rem;background:none;font:inherit;text-align:left;cursor:pointer;transition:background-color 120ms ease, border-color 120ms ease,
106
- box-shadow 120ms ease;}header.svelte-khztz9:hover {background:var(--rough-accent, oklch(0.97 0 0));}.heading.svelte-khztz9 {color:var(--rough-foreground, oklch(0.145 0 0));font-size:0.875rem;font-weight:600;}.chevron.svelte-khztz9 {flex-shrink:0;transform:rotate(-90deg);color:var(--rough-muted-foreground, oklch(0.556 0 0));transition:transform 150ms ease;}.preview.svelte-khztz9 {margin:0;padding:0 0.35rem 0.25rem;color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:0.8rem;line-height:1.45;}`};function cS(e,t){l.push(t,!0),l.append_styles(e,sS);let n=l.prop(t,`heading`,7),r=l.prop(t,`preview`,7),i=l.prop(t,`children`,7);var a={get heading(){return n()},set heading(e){n(e),l.flush()},get preview(){return r()},set preview(e){r(e),l.flush()},get children(){return i()},set children(e){i(e),l.flush()}},o=oS(),s=l.child(o),c=l.child(s),u=l.child(c),d=l.child(u),f=e=>{var t=l.text();l.template_effect(()=>l.set_text(t,n())),l.append(e,t)},p=e=>{var t=l.comment(),r=l.first_child(t);l.snippet(r,n),l.append(e,t)};l.if(d,e=>{typeof n()==`string`?e(f):e(p,-1)}),l.reset(u);var m=l.sibling(u,2);iS(l.child(m),{size:14}),l.reset(m),l.reset(c);var h=l.sibling(c,2),g=e=>{var t=aS(),n=l.child(t);l.snippet(n,r),l.reset(t),l.append(e,t)};l.if(h,e=>{r()&&e(g)}),l.reset(s);var _=l.sibling(s,2);return l.snippet(_,()=>i()??l.noop),l.reset(o),l.append(e,o),l.pop(a)}l.create_custom_element(cS,{heading:{},preview:{},children:{}},[],[],{mode:`open`});var lS=l.from_html(`<div class="JsonViewer svelte-17yau2j"><andypf-json-viewer></andypf-json-viewer></div>`,2),uS={hash:`svelte-17yau2j`,code:`.JsonViewer.svelte-17yau2j {max-height:18rem;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-md, 0.375rem);padding:0.5rem;overflow:auto;background:var(--rough-muted, oklch(0.97 0 0));}.JsonViewer.svelte-17yau2j andypf-json-viewer {display:block;max-width:100%;font-size:0.8rem;}`};function dS(e,t){l.push(t,!0),l.append_styles(e,uS);let n=l.prop(t,`value`,7);var r={get value(){return n()},set value(e){n(e),l.flush()}},i=lS(),a=l.child(i);return l.template_effect(()=>l.set_custom_element_data(a,`data`,n())),l.set_custom_element_data(a,`expanded`,2),l.set_custom_element_data(a,`indent`,2),l.set_custom_element_data(a,`theme`,`default-light`),l.set_custom_element_data(a,`showDataTypes`,!1),l.set_custom_element_data(a,`showToolbar`,!1),l.set_custom_element_data(a,`showCopy`,!1),l.set_custom_element_data(a,`showSize`,!1),l.set_custom_element_data(a,`expandIconType`,`arrow`),l.set_custom_element_data(a,`expandEmpty`,!1),l.reset(i),l.append(e,i),l.pop(r)}l.create_custom_element(dS,{value:{}},[],[],{mode:`open`});var fS=l.from_html(`<div class="tool-desc svelte-15f985v"> </div>`),pS=l.from_html(`<div class="tool-list svelte-15f985v"></div>`),mS=l.from_html(`<!> <div class="arrows svelte-15f985v" aria-hidden="true"><span class="arrow svelte-15f985v">↓</span> <span class="arrow svelte-15f985v">↓</span> <span class="arrow svelte-15f985v">↓</span></div>`,1),hS=l.from_html(`<div class="arrows svelte-15f985v" aria-hidden="true"><span class="arrow svelte-15f985v">↓</span> <span class="arrow svelte-15f985v">↓</span> <span class="arrow svelte-15f985v">↓</span></div>`),gS=l.from_html(`<div class="tool-card svelte-15f985v"><div class="tool-name svelte-15f985v"> </div> <!></div>`),_S=l.from_html(`<div class="tool-list svelte-15f985v"><!> <div class="tool-card tool-card-builtin svelte-15f985v"><div class="tool-name svelte-15f985v">Save feature data</div> <div class="tool-desc svelte-15f985v">Features can save their own data that persists across sessions</div></div></div>`),vS=l.from_html(`<div class="diagram svelte-15f985v"><!> <div class="feature-node svelte-15f985v"><span class="feature-node-label svelte-15f985v">This is your feature, you can build anything here</span></div> <!> <!></div>`),yS={hash:`svelte-15f985v`,code:`.diagram.svelte-15f985v {display:flex;align-items:center;gap:1.25rem;flex-direction:column;min-height:0;padding:1.5rem;overflow-x:hidden;overflow-y:auto;overscroll-behavior:contain;background:var(--rough-background, white);}.feature-node.svelte-15f985v {flex-shrink:0;box-sizing:border-box;width:100%;max-width:420px;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-lg, 0.625rem);padding:0.85rem 1.25rem;background:var(--rough-primary, oklch(0.205 0 0));box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));text-align:center;}.feature-node-label.svelte-15f985v {color:var(--rough-primary-foreground, white);font-size:0.875rem;font-weight:600;}.tool-list.svelte-15f985v {display:flex;gap:0.5rem;flex-direction:column;}.tool-card.svelte-15f985v {display:flex;gap:0.35rem;flex-direction:column;box-sizing:border-box;width:100%;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-md, 0.375rem);padding:0.75rem;background:var(--rough-card, white);color:var(--rough-card-foreground, oklch(0.145 0 0));font:inherit;text-align:left;}.tool-card-builtin.svelte-15f985v {background:var(--rough-muted, oklch(0.97 0 0));}.tool-name.svelte-15f985v {color:var(--rough-foreground, oklch(0.145 0 0));font-size:0.875rem;font-weight:600;}.tool-desc.svelte-15f985v {color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:0.8rem;line-height:1.45;}.arrows.svelte-15f985v {display:flex;align-items:center;justify-content:space-evenly;width:100%;max-width:420px;}.arrow.svelte-15f985v {color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:1.25rem;line-height:1;}`};function bS(e,t){l.push(t,!0),l.append_styles(e,yS);let n=l.prop(t,`toolList`,7),r=l.derived(()=>n().filter(e=>e.type===`query`||e.type===`subscription`)),i=l.derived(()=>n().filter(e=>e.type===`mutation`));var a={get toolList(){return n()},set toolList(e){n(e),l.flush()}},o=vS(),s=l.child(o),c=e=>{var t=mS();cS(l.first_child(t),{heading:`Data this feature can see`,preview:e=>{l.next();var t=l.text();l.template_effect(e=>l.set_text(t,e),[()=>l.get(r).map(e=>e.name).join(`, `)]),l.append(e,t)},children:(e,t)=>{var n=pS();l.each(n,21,()=>l.get(r),e=>e.name,(e,t)=>{cS(e,{get heading(){return l.get(t).name},preview:e=>{var n=l.comment(),r=l.first_child(n),i=e=>{var n=fS(),r=l.child(n,!0);l.reset(n),l.template_effect(()=>l.set_text(r,l.get(t).description)),l.append(e,n)};l.if(r,e=>{l.get(t).description&&e(i)}),l.append(e,n)},children:(e,n)=>{var r=l.comment(),i=l.first_child(r),a=e=>{dS(e,{get value(){return l.get(t).outputSample}})};l.if(i,e=>{l.get(t).outputSample!=null&&e(a)}),l.append(e,r)},$$slots:{preview:!0,default:!0}})}),l.reset(n),l.append(e,n)},$$slots:{preview:!0,default:!0}}),l.next(2),l.append(e,t)};l.if(s,e=>{l.get(r).length>0&&e(c)});var u=l.sibling(s,4),d=e=>{var t=hS();l.append(e,t)};return l.if(u,e=>{l.get(r).length>0&&e(d)}),cS(l.sibling(u,2),{heading:`Changes you can make`,preview:e=>{l.next();var t=l.text();l.template_effect(e=>l.set_text(t,e),[()=>[...l.get(i).map(e=>e.name),`Save feature data`].join(`, `)]),l.append(e,t)},children:(e,t)=>{var n=_S(),r=l.child(n);l.each(r,17,()=>l.get(i),e=>e.name,(e,t)=>{var n=gS(),r=l.child(n),i=l.child(r,!0);l.reset(r);var a=l.sibling(r,2),o=e=>{var n=fS(),r=l.child(n,!0);l.reset(n),l.template_effect(()=>l.set_text(r,l.get(t).description)),l.append(e,n)};l.if(a,e=>{l.get(t).description&&e(o)}),l.reset(n),l.template_effect(()=>l.set_text(i,l.get(t).name)),l.append(e,n)}),l.next(2),l.reset(n),l.append(e,n)},$$slots:{preview:!0,default:!0}}),l.reset(o),l.append(e,o),l.pop(a)}l.create_custom_element(bS,{toolList:{}},[],[],{mode:`open`});var xS=100,SS=e=>{let t=e.keyStepPx??xS,n=l.state(void 0),r=l.derived(()=>l.get(n)===void 0?`1fr`:`${l.get(n)}px`),i=(t,n)=>{let r=n-e.minColumnPx-e.dividerWidthPx;return Math.max(e.minColumnPx,Math.min(r,t))},a=e=>{e.currentTarget.setPointerCapture(e.pointerId),e.preventDefault()},o=t=>{let r=e.getContainer();if(!t.currentTarget.hasPointerCapture(t.pointerId)||!r)return;let a=r.getBoundingClientRect(),o=t.clientX-a.left-e.dividerWidthPx/2;l.set(n,i(o,a.width),!0)},s=e=>{e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId)};return{get column(){return l.get(r)},get widthPx(){return l.get(n)},onpointerdown:a,onpointermove:o,onpointerup:s,onpointercancel:s,onkeydown:r=>{if(r.key!==`ArrowLeft`&&r.key!==`ArrowRight`)return;let a=e.getContainer();if(!a)return;r.preventDefault();let o=a.getBoundingClientRect(),s=l.get(n)??o.width*.25,c=r.key===`ArrowLeft`?-t:t;l.set(n,i(s+c,o.width),!0)}}},CS=l.from_html(`<p class="svelte-t9dwgq">Loading…</p>`),wS=l.from_html(`<div class="error svelte-t9dwgq"> </div>`),TS=l.from_html(`<div class="system-message-detail svelte-t9dwgq"> </div>`),ES=l.from_html(`<details class="system-message-raw svelte-t9dwgq"><summary class="svelte-t9dwgq">Details</summary> <pre class="svelte-t9dwgq"> </pre></details>`),DS=l.from_html(`<div class="system-message system-message-error svelte-t9dwgq"><div class="system-message-label svelte-t9dwgq"> </div> <!> <!></div>`),OS=l.from_html(`<span class="published-tag svelte-t9dwgq">Published</span>`),kS=l.from_html(`<div class="system-message system-message-ready svelte-t9dwgq"><button type="button" class="system-message-button svelte-t9dwgq"><span class="system-message-label svelte-t9dwgq"> <!></span></button></div>`),AS=l.from_html(`<div><!> <!></div>`),jS=l.from_html(`<div class="bubble-text svelte-t9dwgq"> </div>`),MS=l.from_html(`<div class="bubble svelte-t9dwgq"><span class="author svelte-t9dwgq"> </span> <!></div>`),NS=l.from_html(`<div></div>`),PS=l.from_html(`<p class="loading svelte-t9dwgq">Loading…</p>`),FS=l.from_html(`<div class="preview-placeholder svelte-t9dwgq">Your feature preview will appear here.</div>`),IS=l.from_html(`<div class="preview-placeholder svelte-t9dwgq">Build logs will appear here.</div>`),LS=l.from_html(`<div class="logs-panel svelte-t9dwgq"><!></div>`),RS=l.from_html(`<button type="button" class="send-button svelte-t9dwgq"><!></button>`),zS=l.from_html(`<button type="submit" class="send-button svelte-t9dwgq" aria-label="Send message"><!></button>`),BS=l.from_html(`<!> <!> <!>`,1),VS=l.from_html(`<div><div class="transcript svelte-t9dwgq"><div class="transcript-content svelte-t9dwgq"><!> <!> <!> <!></div></div> <div class="divider svelte-t9dwgq" role="slider" aria-label="Resize chat column" tabindex="0"></div> <div class="preview svelte-t9dwgq"><div class="desktop-preview-tabs svelte-t9dwgq"><!></div> <!> <!> <!> <!></div> <form class="composer svelte-t9dwgq"><div><textarea rows="1" placeholder="Describe what you want to generate" class="svelte-t9dwgq"></textarea> <!></div></form> <div class="preview-actions svelte-t9dwgq"><!></div> <!></div>`),HS=l.from_html(`<div><header class="surface-header svelte-t9dwgq"><h3 title="Option-click to toggle theme" class="svelte-t9dwgq"> </h3> <button type="button" class="close-button svelte-t9dwgq" aria-label="Close">×</button></header> <!> <!></div>`),US={hash:`svelte-t9dwgq`,code:`.surface.svelte-t9dwgq {display:flex;flex-direction:column;box-sizing:border-box;width:100%;height:100%;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-xl, 0.875rem);padding:0;overflow:hidden;background:var(--rough-card, white);box-shadow:var(--rough-shadow-lg, 0 10px 15px -3px rgb(0 0 0 / 0.1));color:var(--rough-card-foreground, oklch(0.145 0 0));}.surface-header.svelte-t9dwgq {display:flex;align-items:center;justify-content:space-between;gap:1rem;flex:none;border-bottom:1px solid var(--rough-border, oklch(0.922 0 0));padding:1rem 1.25rem;background:var(--rough-card, white);}h3.svelte-t9dwgq {margin:0;color:var(--rough-foreground, oklch(0.145 0 0));font-size:1.125rem;font-weight:600;line-height:1;}.close-button.svelte-t9dwgq {appearance:none;display:inline-flex;align-items:center;justify-content:center;width:2rem;height:2rem;border:1px solid transparent;border-radius:var(--rough-radius-md, 0.375rem);padding:0;background:transparent;color:var(--rough-muted-foreground, oklch(0.556 0 0));font:inherit;font-size:1.25rem;line-height:1;cursor:pointer;transition:background-color 120ms ease, color 120ms ease,
106
+ box-shadow 120ms ease;}header.svelte-khztz9:hover {background:var(--rough-accent, oklch(0.97 0 0));}.heading.svelte-khztz9 {color:var(--rough-foreground, oklch(0.145 0 0));font-size:0.875rem;font-weight:600;}.chevron.svelte-khztz9 {flex-shrink:0;transform:rotate(-90deg);color:var(--rough-muted-foreground, oklch(0.556 0 0));transition:transform 150ms ease;}.preview.svelte-khztz9 {margin:0;padding:0 0.35rem 0.25rem;color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:0.8rem;line-height:1.45;}`};function uS(e,t){l.push(t,!0),l.append_styles(e,lS);let n=l.prop(t,`heading`,7),r=l.prop(t,`preview`,7),i=l.prop(t,`children`,7);var a={get heading(){return n()},set heading(e){n(e),l.flush()},get preview(){return r()},set preview(e){r(e),l.flush()},get children(){return i()},set children(e){i(e),l.flush()}},o=cS(),s=l.child(o),c=l.child(s),u=l.child(c),d=l.child(u),f=e=>{var t=l.text();l.template_effect(()=>l.set_text(t,n())),l.append(e,t)},p=e=>{var t=l.comment(),r=l.first_child(t);l.snippet(r,n),l.append(e,t)};l.if(d,e=>{typeof n()==`string`?e(f):e(p,-1)}),l.reset(u);var m=l.sibling(u,2);oS(l.child(m),{size:14}),l.reset(m),l.reset(c);var h=l.sibling(c,2),g=e=>{var t=sS(),n=l.child(t);l.snippet(n,r),l.reset(t),l.append(e,t)};l.if(h,e=>{r()&&e(g)}),l.reset(s);var _=l.sibling(s,2);return l.snippet(_,()=>i()??l.noop),l.reset(o),l.append(e,o),l.pop(a)}l.create_custom_element(uS,{heading:{},preview:{},children:{}},[],[],{mode:`open`});var dS=l.from_html(`<div class="JsonViewer svelte-17yau2j"><andypf-json-viewer></andypf-json-viewer></div>`,2),fS={hash:`svelte-17yau2j`,code:`.JsonViewer.svelte-17yau2j {max-height:18rem;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-md, 0.375rem);padding:0.5rem;overflow:auto;background:var(--rough-muted, oklch(0.97 0 0));}.JsonViewer.svelte-17yau2j andypf-json-viewer {display:block;max-width:100%;font-size:0.8rem;}`};function pS(e,t){l.push(t,!0),l.append_styles(e,fS);let n=l.prop(t,`value`,7);var r={get value(){return n()},set value(e){n(e),l.flush()}},i=dS(),a=l.child(i);return l.template_effect(()=>l.set_custom_element_data(a,`data`,n())),l.set_custom_element_data(a,`expanded`,2),l.set_custom_element_data(a,`indent`,2),l.set_custom_element_data(a,`theme`,`default-light`),l.set_custom_element_data(a,`showDataTypes`,!1),l.set_custom_element_data(a,`showToolbar`,!1),l.set_custom_element_data(a,`showCopy`,!1),l.set_custom_element_data(a,`showSize`,!1),l.set_custom_element_data(a,`expandIconType`,`arrow`),l.set_custom_element_data(a,`expandEmpty`,!1),l.reset(i),l.append(e,i),l.pop(r)}l.create_custom_element(pS,{value:{}},[],[],{mode:`open`});var mS=l.from_html(`<div class="tool-desc svelte-15f985v"> </div>`),hS=l.from_html(`<div class="tool-list svelte-15f985v"></div>`),gS=l.from_html(`<!> <div class="arrows svelte-15f985v" aria-hidden="true"><span class="arrow svelte-15f985v">↓</span> <span class="arrow svelte-15f985v">↓</span> <span class="arrow svelte-15f985v">↓</span></div>`,1),_S=l.from_html(`<div class="arrows svelte-15f985v" aria-hidden="true"><span class="arrow svelte-15f985v">↓</span> <span class="arrow svelte-15f985v">↓</span> <span class="arrow svelte-15f985v">↓</span></div>`),vS=l.from_html(`<div class="tool-card svelte-15f985v"><div class="tool-name svelte-15f985v"> </div> <!></div>`),yS=l.from_html(`<div class="tool-list svelte-15f985v"><!> <div class="tool-card tool-card-builtin svelte-15f985v"><div class="tool-name svelte-15f985v">Save feature data</div> <div class="tool-desc svelte-15f985v">Features can save their own data that persists across sessions</div></div></div>`),bS=l.from_html(`<div class="diagram svelte-15f985v"><!> <div class="feature-node svelte-15f985v"><span class="feature-node-label svelte-15f985v">This is your feature, you can build anything here</span></div> <!> <!></div>`),xS={hash:`svelte-15f985v`,code:`.diagram.svelte-15f985v {display:flex;align-items:center;gap:1.25rem;flex-direction:column;min-height:0;padding:1.5rem;overflow-x:hidden;overflow-y:auto;overscroll-behavior:contain;background:var(--rough-background, white);}.feature-node.svelte-15f985v {flex-shrink:0;box-sizing:border-box;width:100%;max-width:420px;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-lg, 0.625rem);padding:0.85rem 1.25rem;background:var(--rough-primary, oklch(0.205 0 0));box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));text-align:center;}.feature-node-label.svelte-15f985v {color:var(--rough-primary-foreground, white);font-size:0.875rem;font-weight:600;}.tool-list.svelte-15f985v {display:flex;gap:0.5rem;flex-direction:column;}.tool-card.svelte-15f985v {display:flex;gap:0.35rem;flex-direction:column;box-sizing:border-box;width:100%;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-md, 0.375rem);padding:0.75rem;background:var(--rough-card, white);color:var(--rough-card-foreground, oklch(0.145 0 0));font:inherit;text-align:left;}.tool-card-builtin.svelte-15f985v {background:var(--rough-muted, oklch(0.97 0 0));}.tool-name.svelte-15f985v {color:var(--rough-foreground, oklch(0.145 0 0));font-size:0.875rem;font-weight:600;}.tool-desc.svelte-15f985v {color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:0.8rem;line-height:1.45;}.arrows.svelte-15f985v {display:flex;align-items:center;justify-content:space-evenly;width:100%;max-width:420px;}.arrow.svelte-15f985v {color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:1.25rem;line-height:1;}`};function SS(e,t){l.push(t,!0),l.append_styles(e,xS);let n=l.prop(t,`toolList`,7),r=l.derived(()=>n().filter(e=>e.type===`query`||e.type===`subscription`)),i=l.derived(()=>n().filter(e=>e.type===`mutation`));var a={get toolList(){return n()},set toolList(e){n(e),l.flush()}},o=bS(),s=l.child(o),c=e=>{var t=gS();uS(l.first_child(t),{heading:`Data this feature can see`,preview:e=>{l.next();var t=l.text();l.template_effect(e=>l.set_text(t,e),[()=>l.get(r).map(e=>e.name).join(`, `)]),l.append(e,t)},children:(e,t)=>{var n=hS();l.each(n,21,()=>l.get(r),e=>e.name,(e,t)=>{uS(e,{get heading(){return l.get(t).name},preview:e=>{var n=l.comment(),r=l.first_child(n),i=e=>{var n=mS(),r=l.child(n,!0);l.reset(n),l.template_effect(()=>l.set_text(r,l.get(t).description)),l.append(e,n)};l.if(r,e=>{l.get(t).description&&e(i)}),l.append(e,n)},children:(e,n)=>{var r=l.comment(),i=l.first_child(r),a=e=>{pS(e,{get value(){return l.get(t).outputSample}})};l.if(i,e=>{l.get(t).outputSample!=null&&e(a)}),l.append(e,r)},$$slots:{preview:!0,default:!0}})}),l.reset(n),l.append(e,n)},$$slots:{preview:!0,default:!0}}),l.next(2),l.append(e,t)};l.if(s,e=>{l.get(r).length>0&&e(c)});var u=l.sibling(s,4),d=e=>{var t=_S();l.append(e,t)};return l.if(u,e=>{l.get(r).length>0&&e(d)}),uS(l.sibling(u,2),{heading:`Changes you can make`,preview:e=>{l.next();var t=l.text();l.template_effect(e=>l.set_text(t,e),[()=>[...l.get(i).map(e=>e.name),`Save feature data`].join(`, `)]),l.append(e,t)},children:(e,t)=>{var n=yS(),r=l.child(n);l.each(r,17,()=>l.get(i),e=>e.name,(e,t)=>{var n=vS(),r=l.child(n),i=l.child(r,!0);l.reset(r);var a=l.sibling(r,2),o=e=>{var n=mS(),r=l.child(n,!0);l.reset(n),l.template_effect(()=>l.set_text(r,l.get(t).description)),l.append(e,n)};l.if(a,e=>{l.get(t).description&&e(o)}),l.reset(n),l.template_effect(()=>l.set_text(i,l.get(t).name)),l.append(e,n)}),l.next(2),l.reset(n),l.append(e,n)},$$slots:{preview:!0,default:!0}}),l.reset(o),l.append(e,o),l.pop(a)}l.create_custom_element(SS,{toolList:{}},[],[],{mode:`open`});var CS=100,wS=e=>{let t=e.keyStepPx??CS,n=l.state(void 0),r=l.derived(()=>l.get(n)===void 0?`1fr`:`${l.get(n)}px`),i=(t,n)=>{let r=n-e.minColumnPx-e.dividerWidthPx;return Math.max(e.minColumnPx,Math.min(r,t))},a=e=>{e.currentTarget.setPointerCapture(e.pointerId),e.preventDefault()},o=t=>{let r=e.getContainer();if(!t.currentTarget.hasPointerCapture(t.pointerId)||!r)return;let a=r.getBoundingClientRect(),o=t.clientX-a.left-e.dividerWidthPx/2;l.set(n,i(o,a.width),!0)},s=e=>{e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId)};return{get column(){return l.get(r)},get widthPx(){return l.get(n)},onpointerdown:a,onpointermove:o,onpointerup:s,onpointercancel:s,onkeydown:r=>{if(r.key!==`ArrowLeft`&&r.key!==`ArrowRight`)return;let a=e.getContainer();if(!a)return;r.preventDefault();let o=a.getBoundingClientRect(),s=l.get(n)??o.width*.25,c=r.key===`ArrowLeft`?-t:t;l.set(n,i(s+c,o.width),!0)}}},TS=l.from_html(`<p class="svelte-t9dwgq">Loading…</p>`),ES=l.from_html(`<div class="error svelte-t9dwgq"> </div>`),DS=l.from_html(`<div class="system-message-detail svelte-t9dwgq"> </div>`),OS=l.from_html(`<details class="system-message-raw svelte-t9dwgq"><summary class="svelte-t9dwgq">Details</summary> <pre class="svelte-t9dwgq"> </pre></details>`),kS=l.from_html(`<div class="system-message system-message-error svelte-t9dwgq"><div class="system-message-label svelte-t9dwgq"> </div> <!> <!></div>`),AS=l.from_html(`<span class="published-tag svelte-t9dwgq">Published</span>`),jS=l.from_html(`<div class="system-message system-message-ready svelte-t9dwgq"><button type="button" class="system-message-button svelte-t9dwgq"><span class="system-message-label svelte-t9dwgq"> <!></span></button></div>`),MS=l.from_html(`<div><!> <!></div>`),NS=l.from_html(`<div class="bubble-text svelte-t9dwgq"> </div>`),PS=l.from_html(`<div class="bubble svelte-t9dwgq"><span class="author svelte-t9dwgq"> </span> <!></div>`),FS=l.from_html(`<div></div>`),IS=l.from_html(`<p class="loading svelte-t9dwgq">Loading…</p>`),LS=l.from_html(`<div class="preview-placeholder svelte-t9dwgq">Your feature preview will appear here.</div>`),RS=l.from_html(`<div class="preview-placeholder svelte-t9dwgq">Build logs will appear here.</div>`),zS=l.from_html(`<div class="logs-panel svelte-t9dwgq"><!></div>`),BS=l.from_html(`<button type="button" class="send-button svelte-t9dwgq"><!></button>`),VS=l.from_html(`<button type="submit" class="send-button svelte-t9dwgq" aria-label="Send message"><!></button>`),HS=l.from_html(`<!> <!> <!>`,1),US=l.from_html(`<div><div class="transcript svelte-t9dwgq"><div class="transcript-content svelte-t9dwgq"><!> <!> <!> <!></div></div> <div class="divider svelte-t9dwgq" role="slider" aria-label="Resize chat column" tabindex="0"></div> <div class="preview svelte-t9dwgq"><div class="desktop-preview-tabs svelte-t9dwgq"><!></div> <!> <!> <!> <!></div> <form class="composer svelte-t9dwgq"><div><textarea rows="1" placeholder="Describe what you want to generate" class="svelte-t9dwgq"></textarea> <!></div></form> <div class="preview-actions svelte-t9dwgq"><!></div> <!></div>`),WS=l.from_html(`<div><header class="surface-header svelte-t9dwgq"><h3 title="Option-click to toggle theme" class="svelte-t9dwgq"> </h3> <button type="button" class="close-button svelte-t9dwgq" aria-label="Close">×</button></header> <!> <!></div>`),GS={hash:`svelte-t9dwgq`,code:`.surface.svelte-t9dwgq {display:flex;flex-direction:column;box-sizing:border-box;width:100%;height:100%;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-xl, 0.875rem);padding:0;overflow:hidden;background:var(--rough-card, white);box-shadow:var(--rough-shadow-lg, 0 10px 15px -3px rgb(0 0 0 / 0.1));color:var(--rough-card-foreground, oklch(0.145 0 0));}.surface-header.svelte-t9dwgq {display:flex;align-items:center;justify-content:space-between;gap:1rem;flex:none;border-bottom:1px solid var(--rough-border, oklch(0.922 0 0));padding:1rem 1.25rem;background:var(--rough-card, white);}h3.svelte-t9dwgq {margin:0;color:var(--rough-foreground, oklch(0.145 0 0));font-size:1.125rem;font-weight:600;line-height:1;}.close-button.svelte-t9dwgq {appearance:none;display:inline-flex;align-items:center;justify-content:center;width:2rem;height:2rem;border:1px solid transparent;border-radius:var(--rough-radius-md, 0.375rem);padding:0;background:transparent;color:var(--rough-muted-foreground, oklch(0.556 0 0));font:inherit;font-size:1.25rem;line-height:1;cursor:pointer;transition:background-color 120ms ease, color 120ms ease,
107
107
  border-color 120ms ease, box-shadow 120ms ease;}.close-button.svelte-t9dwgq:hover {background:var(--rough-accent, oklch(0.97 0 0));color:var(--rough-accent-foreground, oklch(0.205 0 0));}.close-button.svelte-t9dwgq:focus-visible {border-color:var(--rough-ring, oklch(0.708 0 0));outline:none;box-shadow:0 0 0 3px color-mix(in oklch, var(--rough-ring, oklch(0.708 0 0)) 45%, transparent);}.feature-builder.svelte-t9dwgq {display:grid;grid-template-columns:var(--chat-column, 1fr) 12px 3fr;grid-template-rows:1fr auto;column-gap:0;row-gap:0.75rem;flex:1;min-height:0;padding:1rem 1.25rem;background:var(--rough-background, white);}.error.svelte-t9dwgq {flex:1;padding:1rem 1.25rem;color:var(--rough-destructive, oklch(0.577 0.245 27.325));}.transcript.svelte-t9dwgq {grid-column:1;grid-row:1;min-height:0;overflow-y:auto;}
108
108
 
109
109
  /* Inner wrapper so the ResizeObserver can watch content growth separately
@@ -130,6 +130,6 @@ ${zm(e)}`.trim()},Vm=e=>{let{messageList:t}=e,n=t.flatMap(e=>{if(e.role===`tool`
130
130
  .feature-builder.tab-logs.svelte-t9dwgq .preview:where(.svelte-t9dwgq) {display:flex;grid-column:1;grid-row:1;}.feature-builder.tab-preview.svelte-t9dwgq .preview-actions:where(.svelte-t9dwgq),
131
131
  .feature-builder.tab-capabilities.svelte-t9dwgq .preview-actions:where(.svelte-t9dwgq),
132
132
  .feature-builder.tab-logs.svelte-t9dwgq .preview-actions:where(.svelte-t9dwgq) {display:flex;grid-column:1;grid-row:2;}
133
- }`};function WS(e,t){l.push(t,!0),l.append_styles(e,US);let n=e=>Vy(e,{allowHtml:!1,extensions:[Gv()],frontmatter:!1,headingIds:!1}),r=e=>e.type===`create`?`create:${e.surfaceId}`:`edit:${e.spriteId}`,i=l.prop(t,`client`,7),a=l.prop(t,`surface`,7),o=l.prop(t,`portalTarget`,7),c=l.prop(t,`onclose`,7),f=l.prop(t,`action`,7),p=St(),m=l.derived(()=>f().type===`edit`?f().spriteId:p),h=l.derived(()=>Xg(i())),g=l.derived(()=>l.get(h).store),_=l.derived(()=>a().tools),v=l.state(!0),y=l.state(void 0),b,ee=!1,te=!1,ne,re=async()=>{if(f().type!==`create`||te)return;let e=ne;if(e)return e;let t=f(),n=(async()=>{let e=await l.get(h).getReplicache();ee||=(await e.mutate.sprite_create_v2({spriteId:p,surfaceId:t.surfaceId,name:``,context:{actionedAt:Date.now()}}),!0),await e.push({now:!0}),te=!0})();ne=n;try{await n}finally{ne===n&&(ne=void 0)}};s(()=>{l.set(y,r(f()),!0)}),l.user_effect(()=>{let e=l.get(y);if(!e)return;let t=r(f());if(t===e){b=void 0;return}t!==b&&(b=t,console.error(`[Rough] FeatureBuilder does not support changing action after mount.`,{initialActionKey:e,currentActionKey:t}))});let ie=l.derived(()=>lb(l.get(g).meta.get($e))),ae=l.derived(()=>l.get(ie)._),oe=l.derived(()=>l.get(ae)?.state===`READY`),se=l.derived(()=>lb(l.get(g).sprite.get(l.get(m)))),ce=l.derived(()=>l.get(se)._),le=l.derived(()=>lb(l.get(g).spriteBuild.filter(`FeatureBuilder:spriteBuildList:${l.get(m)}`,e=>e.spriteId===l.get(m)))),ue=l.derived(()=>l.get(le)._),x=l.derived(()=>{if(l.get(ce))return e_({sprite:l.get(ce),spriteBuildList:l.get(ue)})}),S=l.derived(()=>f().type===`edit`&&!l.get(oe)),C=l.derived(()=>{if(!(f().type!==`edit`||!l.get(oe)||l.get(ce)))return Error(`Sprite "${f().spriteId}" not found`)}),de=l.state(!1),w=l.state(void 0),fe=l.state(void 0),pe=l.state(void 0),me=l.derived(()=>l.get(de)||l.get(w)!=null&&l.get(w).status!==`READY`&&l.get(w).status!==`ERROR`&&l.get(w).status!==`CANCELED`&&!l.get(pe)),he=e=>{l.set(w,e,!0),l.set(fe,e.id,!0),Xe.add(e.id)},ge=l.derived(()=>l.get(fe)?lb(l.get(g).spriteBuild.get(l.get(fe))):lb.undefined),_e=l.derived(()=>l.get(ge)._);l.user_effect(()=>{let e=l.get(_e);e&&(e.id===l.get(fe)&&JSON.stringify(l.get(w))!==JSON.stringify(e)&&l.set(w,e,!0),(e.status===`READY`||e.status===`ERROR`||e.status===`CANCELED`)&&l.set(fe,void 0))});let ve=[{key:`preview`,label:`Preview`},{key:`capabilities`,label:`Capabilities`},{key:`logs`,label:`Logs`}],ye=[{key:`chat`,label:`Chat`},...ve],be=l.state(`chat`),xe=l.state(`capabilities`),T=l.derived(()=>l.get(be)===`chat`),Se=l.derived(()=>l.get(be)===`capabilities`),Ce=l.derived(()=>l.get(be)===`preview`),we=l.derived(()=>l.get(be)===`logs`),Te=l.derived(()=>l.get(xe)===`capabilities`),Ee=l.derived(()=>l.get(xe)===`preview`),E=l.derived(()=>l.get(xe)===`logs`),De=l.state(``),Oe=l.state(void 0),ke=l.state(l.proxy([])),Ae=l.state(!1),je=l.state(void 0),Me=l.derived(()=>l.get(Ae)&&!l.get(me)),Ne=l.state(void 0),Pe=l.state(void 0),Fe=l.state(void 0),Ie=l.state(void 0),Le=l.state(void 0),Re=SS({getContainer:()=>l.get(Le),minColumnPx:280,dividerWidthPx:12}),ze=l.derived(()=>{if(Re.widthPx===void 0||!l.get(Le))return;let e=l.get(Le).getBoundingClientRect().width;if(e)return Math.round(Re.widthPx/e*100)}),Be=l.derived(()=>{let e=new u;for(let t of l.get(ue))e.set(t.id,t);return l.get(w)&&e.set(l.get(w).id,l.get(w)),[...e.values()].sort((e,t)=>e.id.localeCompare(t.id))}),Ve=!1,He=e=>{l.set(Pe,e,!0),Ve=!0,l.set(xe,`preview`),l.set(be,`preview`)},Ue=l.derived(()=>l.get(Be).findLast(e=>e.status===`READY`&&e.artifactUrl)),We=l.derived(()=>{if(l.get(Pe)){let e=l.get(Be).find(e=>e.id===l.get(Pe));if(e)return e}return l.get(Ue)??l.get(Be).at(-1)}),Ge=l.derived(()=>l.get(We)?.status===`READY`&&l.get(We).artifactUrl?l.get(We):void 0),Ke=l.derived(()=>l.get(Ge)??l.get(Ue)),qe=!1;l.user_effect(()=>{!qe&&l.get(Ue)&&(l.set(be,`preview`),l.set(xe,`preview`),qe=!0)}),l.user_effect(()=>{if(l.get(Be).length===0){l.set(Pe,void 0),Ve=!1;return}(!Ve||!l.get(Pe)||!l.get(Be).some(e=>e.id===l.get(Pe)))&&(l.set(Pe,l.get(Ue)?.id??l.get(Be).at(-1)?.id,!0),Ve=!1)});let Je=l.derived(()=>l.get(Ue)?.id),Ye=l.derived(()=>$g(l.get(ue))),Xe=new d,Ze=l.state(void 0),Qe=l.derived(()=>l.get(Ze)??l.get(Ye)?.id??void 0),et=l.derived(()=>!l.get(me)&&l.get(Ke)!=null&&l.get(Ke).id!==l.get(Qe)),tt=l.derived(()=>l.get(Qe)!==l.get(Je)),nt=l.state(!1),rt=l.state(void 0),it=l.state(!1),at=l.state(!1),ot=async()=>{if(!(!l.get(x)||!l.get(Ke)||l.get(nt))){l.set(nt,!0),l.set(rt,void 0);try{let e=await rb({replicache:await l.get(h).getReplicache(),spriteId:l.get(x).id,spriteBuildId:l.get(Ke).id});if(e instanceof Error){l.set(rt,e,!0);return}l.set(Ze,e.spriteBuildId,!0),l.set(it,!1)}finally{l.set(nt,!1)}}},st=()=>{l.set(v,!1)},ct=()=>{l.get(tt)?l.set(it,!0):st()},lt=()=>{l.set(it,!1),st()},ut=()=>{l.set(it,!1)},dt=e=>{if(e){if(typeof e.message==`string`)return e.message;if(typeof e.error==`string`)return e.error}},ft=e=>{let t=Lm.outputSchema.safeParse(e);return t.success?t.data:void 0},pt=l.derived(()=>l.get(w)?.cancelRequestedAt!=null),mt=l.derived(()=>!l.get(pt)&&(l.get(w)?.status===`PENDING`||l.get(w)?.status===`IN_PROGRESS`)),ht=async()=>{!l.get(x)||!l.get(w)||!l.get(mt)||await(await l.get(h).getReplicache()).mutate.spriteBuild_cancel_v1({spriteBuildId:l.get(w).id})},gt=async(e,t)=>{l.set(pe,void 0),l.set(de,!0);try{let n=e.trim();if(!n)throw Error(`Missing build prompt`);let r=Vm({messageList:Xp(t)});if(r instanceof Error)throw r;console.table([{"Frontend build plan (inactive)":n,"Backend build plan (active)":r}]);let i=await l.get(h).getReplicache(),a=St();await i.mutate.spriteBuild_create_v2({spriteBuildId:a,spriteId:l.get(m),parentSpriteBuildId:l.get(Je),prompt:r});let o=l.get(g).spriteBuild.get(a).value;return o?he(o):l.set(fe,a,!0),{spriteBuildId:a}}finally{l.set(de,!1)}};l.user_effect(()=>{if(l.get(S)||l.get(C))return;let e=rx({client:i(),spriteId:l.get(m),toolList:l.get(_),onStartBuild:({prompt:e},t)=>gt(e,t),onMessagesChange:e=>{l.set(ke,e,!0)},onLoadingChange:e=>{l.set(Ae,e,!0)},onErrorChange:e=>{l.set(je,e,!0)}});return l.set(Oe,e,!0),e.attach(),l.set(ke,e.getMessages(),!0),l.set(Ae,e.getIsLoading(),!0),l.set(je,e.getError(),!0),()=>{e.dispose(),l.get(Oe)===e&&l.set(Oe,void 0)}});let _t=l.derived(()=>l.get(Oe)!=null&&!l.get(me)&&!l.get(Ae)&&l.get(De).trim().length>0),vt=async e=>{e.preventDefault();let t=l.get(De).trim();if(!(!t||l.get(me)||l.get(Ae))){if(l.set(pe,void 0),l.set(je,void 0),!l.get(Oe)){l.set(pe,Error(`Feature builder chat is not ready`),!0);return}try{await re(),l.set(De,``),await l.get(Oe).sendMessage(t)}catch(e){l.set(pe,e instanceof Error?e:Error(String(e)),!0)}}},yt=e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),vt(e))};return l.user_effect(()=>{l.get(be)!==`chat`&&l.set(xe,l.get(be),!0)}),l.user_effect(()=>{let e=l.get(Ne);e&&(l.get(De),e.style.height=`auto`,e.style.height=`${e.scrollHeight}px`)}),l.user_effect(()=>{let e=l.get(Ie),t=l.get(Fe);if(!e||!t)return;let n=new ResizeObserver(()=>{t.scrollTop=t.scrollHeight});return n.observe(e),()=>n.disconnect()}),mx(e,{get target(){return o()},oncancel:ct,get onclose(){return c()},get isOpen(){return l.get(v)},set isOpen(e){l.set(v,e,!0)},children:(e,t)=>{var r=HS();let a;var o=l.child(r),s=l.child(o),c=l.child(s,!0);l.reset(s);var u=l.sibling(s,2);l.reset(o);var d=l.sibling(o,2),f=e=>{var t=CS();l.append(e,t)},p=e=>{var t=wS(),n=l.child(t,!0);l.reset(t),l.template_effect(()=>l.set_text(n,l.get(C).message)),l.append(e,t)},m=e=>{var t=VS();let r,a;{let e=(e,t=l.noop,n=l.noop,r=l.noop)=>{var i=DS(),a=l.child(i),o=l.child(a,!0);l.reset(a);var s=l.sibling(a,2),c=e=>{var t=TS(),r=l.child(t,!0);l.reset(t),l.template_effect(()=>l.set_text(r,n())),l.append(e,t)};l.if(s,e=>{n()&&e(c)});var u=l.sibling(s,2),d=e=>{var t=ES(),n=l.sibling(l.child(t),2),i=l.child(n,!0);l.reset(n),l.reset(t),l.template_effect(e=>l.set_text(i,e),[()=>JSON.stringify(r(),null,2)]),l.append(e,t)};l.if(u,e=>{r()&&e(d)}),l.reset(i),l.template_effect(()=>l.set_text(o,t())),l.append(e,i)},r=(t,n=l.noop)=>{let r=l.derived(()=>n().id===l.get(Qe)),a=l.derived(()=>l.get(Be).indexOf(n())+1);var o=AS();let s;var c=l.child(o),u=e=>{jb(e,{get client(){return i()},get spriteBuild(){return n()}})};l.if(c,e=>{n().status!==`READY`&&n().status!==`ERROR`&&e(u)});var d=l.sibling(c,2),f=e=>{var t=kS(),i=l.child(t),o=l.child(i),s=l.child(o),c=l.sibling(s),u=e=>{var t=OS();l.append(e,t)};l.if(c,e=>{l.get(r)&&e(u)}),l.reset(o),l.reset(i),l.reset(t),l.template_effect(()=>l.set_text(s,`Version ${l.get(a)??``} ready `)),l.delegated(`click`,i,()=>He(n().id)),l.append(e,t)},p=t=>{{let r=l.derived(()=>dt(n().error));e(t,()=>`Version ${l.get(a)} failed`,()=>l.get(r),()=>n().error)}};l.if(d,e=>{n().status===`READY`?e(f):n().status===`ERROR`&&e(p,1)}),l.reset(o),l.template_effect(()=>s=l.set_class(o,1,`turn svelte-t9dwgq`,null,s,{"turn-published":l.get(r)})),l.append(t,o)};var o=l.child(t),s=l.child(o),c=l.child(s);l.each(c,17,()=>l.get(ke),e=>e.id,(e,t)=>{var i=NS();let a;l.each(i,23,()=>l.get(t).parts,(e,n)=>`${l.get(t).id}-${n}`,(e,i)=>{var a=l.comment(),o=l.first_child(a),s=e=>{var r=MS(),a=l.child(r),o=l.child(a,!0);l.reset(a);var s=l.sibling(a,2),c=e=>{var t=l.comment(),r=l.first_child(t);l.html(r,()=>n(l.get(i).content)),l.append(e,t)},u=e=>{var t=jS(),n=l.child(t,!0);l.reset(t),l.template_effect(()=>l.set_text(n,l.get(i).content)),l.append(e,t)};l.if(s,e=>{l.get(t).role===`assistant`?e(c):e(u,-1)}),l.reset(r),l.template_effect(()=>l.set_text(o,l.get(t).role===`user`?`You`:`Rough`)),l.append(e,r)},c=e=>{let t=l.derived(()=>ft(l.get(i).output)),n=l.derived(()=>l.get(t)?l.get(Be).find(e=>e.id===l.get(t).spriteBuildId):void 0);var a=l.comment(),o=l.first_child(a),s=e=>{r(e,()=>l.get(n))};l.if(o,e=>{l.get(n)&&e(s)}),l.append(e,a)};l.if(o,e=>{l.get(i).type===`text`?e(s):l.get(i).type===`tool-call`&&l.get(i).name===`startBuild`&&e(c,1)}),l.append(e,a)}),l.reset(i),l.template_effect(()=>a=l.set_class(i,1,`chat-message svelte-t9dwgq`,null,a,{"chat-message-user":l.get(t).role===`user`,"chat-message-assistant":l.get(t).role===`assistant`})),l.append(e,i)});var u=l.sibling(c,2),d=e=>{var t=PS();l.append(e,t)};l.if(u,e=>{l.get(Me)&&e(d)});var f=l.sibling(u,2),p=t=>{e(t,()=>`Couldn't chat`,()=>l.get(je).message)};l.if(f,e=>{l.get(je)&&e(p)});var m=l.sibling(f,2),h=t=>{e(t,()=>`Couldn't send message`,()=>l.get(pe).message)};l.if(m,e=>{l.get(pe)&&e(h)}),l.reset(s),l.bind_this(s,e=>l.set(Ie,e),()=>l.get(Ie)),l.reset(o),l.bind_this(o,e=>l.set(Fe,e),()=>l.get(Fe));var g=l.sibling(o,2);l.set_attribute(g,`aria-valuemin`,0),l.set_attribute(g,`aria-valuemax`,100);var v=l.sibling(g,2),y=l.child(v);$x(l.child(y),{get tabs(){return ve},get active(){return l.get(xe)},set active(e){l.set(xe,e,!0)}}),l.reset(y);var b=l.sibling(y,2),ee=t=>{e(t,()=>`Couldn't publish version`,()=>l.get(rt).message)};l.if(b,e=>{l.get(rt)&&e(ee)});var te=l.sibling(b,2);nS(te,{get isActive(){return l.get(Te)},children:(e,t)=>{bS(e,{get toolList(){return l.get(_)}})},$$slots:{default:!0}});var ne=l.sibling(te,2);nS(ne,{get isActive(){return l.get(Ee)},children:(e,t)=>{var n=l.comment(),r=l.first_child(n),i=e=>{{let t=l.derived(()=>l.get(We).artifactUrl??void 0);Yx(e,{get toolList(){return l.get(_)},get spriteId(){return l.get(x).id},get spriteBuildId(){return l.get(We).id},get artifactUrl(){return l.get(t)},spriteInstanceId:void 0,isMock:!0})}},a=e=>{var t=FS();l.append(e,t)};l.if(r,e=>{l.get(x)&&l.get(We)?.status===`READY`&&l.get(We).artifactUrl?e(i):e(a,-1)}),l.append(e,n)},$$slots:{default:!0}}),nS(l.sibling(ne,2),{get isActive(){return l.get(E)},children:(e,t)=>{var n=LS(),r=l.child(n),a=e=>{Zb(e,{get client(){return i()},get spriteBuild(){return l.get(We)}})},o=e=>{var t=IS();l.append(e,t)};l.if(r,e=>{l.get(We)?e(a):e(o,-1)}),l.reset(n),l.append(e,n)},$$slots:{default:!0}}),l.reset(v);var re=l.sibling(v,2),ie=l.child(re);let a;var ae=l.child(ie);l.remove_textarea_child(ae),l.bind_this(ae,e=>l.set(Ne,e),()=>l.get(Ne));var oe=l.sibling(ae,2),se=e=>{var t=RS(),n=l.child(t),r=e=>{cb(e,{})},i=e=>{p_(e,{size:12,fill:`currentColor`,"aria-hidden":`true`})};l.if(n,e=>{l.get(pt)?e(r):e(i,-1)}),l.reset(t),l.template_effect(()=>{t.disabled=!l.get(mt),l.set_attribute(t,`aria-label`,l.get(pt)?`Stopping build`:`Stop build`)}),l.delegated(`click`,t,()=>void ht()),l.append(e,t)},ce=e=>{var t=zS();d_(l.child(t),{size:16,"aria-hidden":`true`}),l.reset(t),l.template_effect(()=>t.disabled=!l.get(_t)),l.append(e,t)};l.if(oe,e=>{l.get(me)?e(se):e(ce,-1)}),l.reset(ie),l.reset(re);var le=l.sibling(re,2),ue=l.child(le);{let e=l.derived(()=>!l.get(et)||l.get(nt));ux(ue,{get disabled(){return l.get(e)},onclick:()=>void ot(),children:(e,t)=>{l.next();var n=l.text();l.template_effect(()=>l.set_text(n,l.get(nt)?`Publishing…`:`Publish`)),l.append(e,n)},$$slots:{default:!0}})}l.reset(le);var S=l.sibling(le,2),C=e=>{nx(e,{title:`Publish before closing?`,detail:`You have iterations from this session that aren't published yet.`,get error(){return l.get(rt)},actions:e=>{var t=BS(),n=l.first_child(t);_x(n,{onclick:ut,children:(e,t)=>{l.next();var n=l.text(`Keep editing`);l.append(e,n)},$$slots:{default:!0}});var r=l.sibling(n,2);_x(r,{onclick:lt,children:(e,t)=>{l.next();var n=l.text(`Close anyway`);l.append(e,n)},$$slots:{default:!0}});var i=l.sibling(r,2);{let e=l.derived(()=>!l.get(et)||l.get(nt));ux(i,{get disabled(){return l.get(e)},onclick:()=>void ot(),children:(e,t)=>{l.next();var n=l.text();l.template_effect(()=>l.set_text(n,l.get(nt)?`Publishing…`:`Publish`)),l.append(e,n)},$$slots:{default:!0}})}l.append(e,t)},$$slots:{actions:!0}})};l.if(S,e=>{l.get(it)&&e(C)}),l.reset(t),l.bind_this(t,e=>l.set(Le,e),()=>l.get(Le)),l.template_effect(()=>{l.set_attribute(g,`aria-valuenow`,l.get(ze)),a=l.set_class(ie,1,`composer-input svelte-t9dwgq`,null,a,{isBuilding:l.get(me)})}),l.delegated(`pointerdown`,g,function(...e){Re.onpointerdown?.apply(this,e)}),l.delegated(`pointermove`,g,function(...e){Re.onpointermove?.apply(this,e)}),l.delegated(`pointerup`,g,function(...e){Re.onpointerup?.apply(this,e)}),l.event(`pointercancel`,g,function(...e){Re.onpointercancel?.apply(this,e)}),l.delegated(`keydown`,g,function(...e){Re.onkeydown?.apply(this,e)}),l.event(`submit`,re,vt),l.delegated(`keydown`,ae,yt),l.bind_value(ae,()=>l.get(De),e=>l.set(De,e))}l.template_effect(()=>{r=l.set_class(t,1,`feature-builder svelte-t9dwgq`,null,r,{"tab-chat":l.get(T),"tab-preview":l.get(Ce),"tab-capabilities":l.get(Se),"tab-logs":l.get(we)}),a=l.set_style(t,``,a,{"--chat-column":Re.column})}),l.append(e,t)};l.if(d,e=>{l.get(S)?e(f):l.get(C)?e(p,1):e(m,-1)}),sx(l.sibling(d,2),{get tabs(){return ye},ariaLabel:`Feature builder sections`,get active(){return l.get(be)},set active(e){l.set(be,e,!0)}}),l.reset(r),l.template_effect(()=>{a=l.set_class(r,1,`surface svelte-t9dwgq`,null,a,{"rough-dark":l.get(at)}),l.set_text(c,`⌥ ${l.get(x)?.name??`Rough`}`)}),l.delegated(`pointerup`,s,e=>{e.altKey&&l.set(at,!l.get(at))}),l.delegated(`click`,u,ct),l.append(e,r)},$$slots:{default:!0}}),l.pop({get client(){return i()},set client(e){i(e),l.flush()},get surface(){return a()},set surface(e){a(e),l.flush()},get portalTarget(){return o()},set portalTarget(e){o(e),l.flush()},get onclose(){return c()},set onclose(e){c(e),l.flush()},get action(){return f()},set action(e){f(e),l.flush()}})}l.delegate([`pointerup`,`click`,`pointerdown`,`pointermove`,`keydown`]),l.create_custom_element(WS,{client:{},surface:{},portalTarget:{},onclose:{},action:{}},[],[],{mode:`open`});function GS(e,t){l.push(t,!0);let n=l.prop(t,`client`,7),r=l.prop(t,`surface`,7),i=l.prop(t,`surfaceId`,7),a=l.prop(t,`portalTarget`,7),o=l.prop(t,`onclose`,7);var s={get client(){return n()},set client(e){n(e),l.flush()},get surface(){return r()},set surface(e){r(e),l.flush()},get surfaceId(){return i()},set surfaceId(e){i(e),l.flush()},get portalTarget(){return a()},set portalTarget(e){a(e),l.flush()},get onclose(){return o()},set onclose(e){o(e),l.flush()}};{let t=l.derived(()=>({type:`create`,surfaceId:i()}));WS(e,{get client(){return n()},get surface(){return r()},get portalTarget(){return a()},get action(){return l.get(t)},get onclose(){return o()}})}return l.pop(s)}customElements.define(`rough-create-modal`,l.create_custom_element(GS,{client:{},surface:{},surfaceId:{},portalTarget:{},onclose:{}},[],[]));var KS=async e=>{let{client:t,signal:n}=e,r=Xg(t);r.assertUsable();let i=Rt(e.surface),o=e.target??document.body,s=r.surfaces.acquire({surface:i}),l=new AbortController,u,d,f,p,m=()=>(p??=(async()=>{l.abort(new Tt(`Modal closed`));let e=u;u=void 0,e&&await c(e),d?.remove(),d=void 0,s.release(),f?.(),f=void 0})(),p);if(f=r.operations.register({label:`openRoughCreate(${i.key})`,close:m}),n){if(n.aborted)throw await m(),new Tt(`Modal opening was aborted`);n.addEventListener(`abort`,()=>void m(),{once:!0})}try{let e=await Promise.race([s.ready.then(e=>({type:`resolved`,resolution:e})),Nt(l.signal).then(()=>({type:`aborted`}))]);if(e.type===`aborted`||l.signal.aborted)throw new Tt(`The Rough client was destroyed before the create modal could open`);r.assertUsable(),d=document.createElement(`div`),o.appendChild(d),u=a(GS,{target:d,props:{client:t,surface:i,surfaceId:e.resolution.id,onclose:()=>{m()}}})}catch(e){throw await m(),e}return{close:m}};function qS(e,t){l.push(t,!0);let n=l.prop(t,`client`,7),r=l.prop(t,`surface`,7),i=l.prop(t,`spriteId`,7),a=l.prop(t,`portalTarget`,7),o=l.prop(t,`onclose`,7);var s={get client(){return n()},set client(e){n(e),l.flush()},get surface(){return r()},set surface(e){r(e),l.flush()},get spriteId(){return i()},set spriteId(e){i(e),l.flush()},get portalTarget(){return a()},set portalTarget(e){a(e),l.flush()},get onclose(){return o()},set onclose(e){o(e),l.flush()}};{let t=l.derived(()=>({type:`edit`,spriteId:i()}));WS(e,{get client(){return n()},get surface(){return r()},get portalTarget(){return a()},get action(){return l.get(t)},get onclose(){return o()}})}return l.pop(s)}customElements.define(`rough-edit-modal`,l.create_custom_element(qS,{client:{},surface:{},spriteId:{},portalTarget:{},onclose:{}},[],[]));var JS=l.from_html(`<!> <!>`,1);function YS(e,t){l.push(t,!0);let n=l.prop(t,`client`,7),r=l.prop(t,`surface`,7),i=l.prop(t,`spriteId`,7),a=l.prop(t,`label`,7,`Edit Rough Feature`),o=l.state(!1),s=()=>{l.set(o,!0)},c=()=>{l.set(o,!1)};var u={get client(){return n()},set client(e){n(e),l.flush()},get surface(){return r()},set surface(e){r(e),l.flush()},get spriteId(){return i()},set spriteId(e){i(e),l.flush()},get label(){return a()},set label(e=`Edit Rough Feature`){a(e),l.flush()}},d=JS(),f=l.first_child(d);ux(f,{onclick:s,children:(e,t)=>{l.next();var n=l.text();l.template_effect(()=>l.set_text(n,`⌥ ${a()??``}`)),l.append(e,n)},$$slots:{default:!0}});var p=l.sibling(f,2),m=e=>{qS(e,{get client(){return n()},get surface(){return r()},get spriteId(){return i()},onclose:c})};return l.if(p,e=>{l.get(o)&&e(m)}),l.append(e,d),l.pop(u)}customElements.define(`rough-edit-button`,l.create_custom_element(YS,{client:{},surface:{},spriteId:{},label:{}},[],[]));var XS=`data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='17441%2015570%20441%20441'%20fill='none'%20stroke='currentColor'%20stroke-linecap='square'%20stroke-linejoin='miter'%20%3e%3ctitle%3eRough%20logo%3c/title%3e%3cdefs%3e%3cclipPath%20id='rough-logo'%3e%3crect%20x='17501'%20y='15630'%20width='321'%20height='321'%20/%3e%3c/clipPath%3e%3c/defs%3e%3cg%20clip-path='url(%23rough-logo)'%3e%3cg%20transform='matrix(1,0,0,1,17606.5311,15766.3152)'%3e%3cpolygon%20fill='currentColor'%20stroke='none'%20points='17.41,-136.32%20173.47,179.78%20173.47,184.68%2088.38,184.68%20-63.53,-122.94%20-63.53,-136.32'%20/%3e%3c/g%3e%3cpath%20stroke-width='78.5'%20d='M%2017473%2015669.25%20L%2017543%2015669.25'%20/%3e%3cpath%20stroke-width='78.5'%20d='M%2017780%2015669.25%20L%2017750%2015669.25'%20/%3e%3cpath%20stroke-width='78.5'%20d='M%2017780%2015911.75%20L%2017850%2015911.75'%20/%3e%3c/g%3e%3c/svg%3e`,ZS=l.from_html(`<div class="chrome svelte-1aurlo0"><button class="badge svelte-1aurlo0" aria-label="Edit Rough Feature"><img alt="Rough Logo"/></button> <!></div> <!>`,1),QS={hash:`svelte-1aurlo0`,code:`.chrome.svelte-1aurlo0 {position:relative;isolation:isolate;}.badge.svelte-1aurlo0 {position:absolute;top:8px;right:8px;z-index:10;display:flex;align-items:center;justify-content:center;width:2rem;height:2rem;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-md, 0.375rem);padding:0.25rem;background:var(--rough-brand, #cb4b16);box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));opacity:0;cursor:pointer;pointer-events:none;transition:opacity 150ms ease, box-shadow 120ms ease;}.badge.svelte-1aurlo0:focus-visible {border-color:var(--rough-ring, oklch(0.708 0 0));outline:none;box-shadow:0 0 0 3px color-mix(in oklch, var(--rough-ring, oklch(0.708 0 0)) 45%, transparent);}.chrome.svelte-1aurlo0:hover .badge:where(.svelte-1aurlo0),
133
+ }`};function KS(e,t){l.push(t,!0),l.append_styles(e,GS);let n=e=>Uy(e,{allowHtml:!1,extensions:[qv()],frontmatter:!1,headingIds:!1}),r=e=>e.type===`create`?`create:${e.surfaceId}`:`edit:${e.spriteId}`,i=l.prop(t,`client`,7),a=l.prop(t,`surface`,7),o=l.prop(t,`portalTarget`,7),c=l.prop(t,`onclose`,7),f=l.prop(t,`action`,7),p=xt(),m=l.derived(()=>f().type===`edit`?f().spriteId:p),h=l.derived(()=>Qg(i())),g=l.derived(()=>l.get(h).store),_=l.derived(()=>a().tools),v=l.state(!0),y=l.state(void 0),b,ee=!1,x=!1,te,ne=async()=>{if(f().type!==`create`||x)return;let e=te;if(e)return e;let t=f(),n=(async()=>{let e=await l.get(h).getReplicache();ee||=(await e.mutate.sprite_create_v2({spriteId:p,surfaceId:t.surfaceId,name:``,context:{actionedAt:Date.now()}}),!0),await e.push({now:!0}),x=!0})();te=n;try{await n}finally{te===n&&(te=void 0)}};s(()=>{l.set(y,r(f()),!0)}),l.user_effect(()=>{let e=l.get(y);if(!e)return;let t=r(f());if(t===e){b=void 0;return}t!==b&&(b=t,console.error(`[Rough] FeatureBuilder does not support changing action after mount.`,{initialActionKey:e,currentActionKey:t}))});let re=l.derived(()=>db(l.get(g).meta.get(Qe))),ie=l.derived(()=>l.get(re)._),ae=l.derived(()=>l.get(ie)?.state===`READY`),oe=l.derived(()=>db(l.get(g).sprite.get(l.get(m)))),se=l.derived(()=>l.get(oe)._),ce=l.derived(()=>db(l.get(g).spriteBuild.filter(`FeatureBuilder:spriteBuildList:${l.get(m)}`,e=>e.spriteId===l.get(m)))),le=l.derived(()=>l.get(ce)._),S=l.derived(()=>db(l.get(g).spriteBuildEvent.filter(`FeatureBuilder:spriteBuildEventList:${l.get(m)}`,e=>l.get(le).some(t=>t.id===e.spriteBuildId)))),C=l.derived(()=>l.get(S)._),w=l.derived(()=>{if(l.get(se))return n_({sprite:l.get(se),spriteBuildList:l.get(le)})}),ue=l.derived(()=>f().type===`edit`&&!l.get(ae)),de=l.derived(()=>{if(!(f().type!==`edit`||!l.get(ae)||l.get(se)))return Error(`Sprite "${f().spriteId}" not found`)}),fe=l.state(!1),T=l.state(void 0),pe=l.state(void 0),me=l.state(void 0),he=l.derived(()=>l.get(fe)||l.get(T)!=null&&l.get(T).status!==`READY`&&l.get(T).status!==`ERROR`&&l.get(T).status!==`CANCELED`&&!l.get(me)),ge=e=>{l.set(T,e,!0),l.set(pe,e.id,!0),$e.add(e.id)},_e=l.derived(()=>l.get(pe)?db(l.get(g).spriteBuild.get(l.get(pe))):db.undefined),ve=l.derived(()=>l.get(_e)._);l.user_effect(()=>{let e=l.get(ve);e&&(e.id===l.get(pe)&&JSON.stringify(l.get(T))!==JSON.stringify(e)&&l.set(T,e,!0),(e.status===`READY`||e.status===`ERROR`||e.status===`CANCELED`)&&l.set(pe,void 0))});let ye=[{key:`preview`,label:`Preview`},{key:`capabilities`,label:`Capabilities`},{key:`logs`,label:`Logs`}],be=[{key:`chat`,label:`Chat`},...ye],E=l.state(`chat`),xe=l.state(`capabilities`),Se=l.derived(()=>l.get(E)===`chat`),Ce=l.derived(()=>l.get(E)===`capabilities`),we=l.derived(()=>l.get(E)===`preview`),Te=l.derived(()=>l.get(E)===`logs`),D=l.derived(()=>l.get(xe)===`capabilities`),Ee=l.derived(()=>l.get(xe)===`preview`),De=l.derived(()=>l.get(xe)===`logs`),Oe=l.state(``),ke=l.state(void 0),Ae=l.state(l.proxy([])),je=l.state(!1),Me=l.state(void 0),Ne=l.derived(()=>l.get(je)&&!l.get(he)),Pe=l.state(void 0),Fe=l.state(void 0),Ie=l.state(void 0),Le=l.state(void 0),Re=l.state(void 0),ze=wS({getContainer:()=>l.get(Re),minColumnPx:280,dividerWidthPx:12}),Be=l.derived(()=>{if(ze.widthPx===void 0||!l.get(Re))return;let e=l.get(Re).getBoundingClientRect().width;if(e)return Math.round(ze.widthPx/e*100)}),Ve=l.derived(()=>{let e=new u;for(let t of l.get(le))e.set(t.id,t);return l.get(T)&&e.set(l.get(T).id,l.get(T)),[...e.values()].sort((e,t)=>e.id.localeCompare(t.id))}),He=!1,Ue=e=>{l.set(Fe,e,!0),He=!0,l.set(xe,`preview`),l.set(E,`preview`)},We=l.derived(()=>l.get(Ve).findLast(e=>e.status===`READY`&&e.artifactUrl)),Ge=l.derived(()=>{if(l.get(Fe)){let e=l.get(Ve).find(e=>e.id===l.get(Fe));if(e)return e}return l.get(We)??l.get(Ve).at(-1)}),Ke=l.derived(()=>l.get(Ve).at(-1)),qe=l.derived(()=>l.get(Ge)?.status===`READY`&&l.get(Ge).artifactUrl?l.get(Ge):void 0),Je=l.derived(()=>l.get(qe)??l.get(We)),Ye=!1;l.user_effect(()=>{!Ye&&l.get(We)&&(l.set(E,`preview`),l.set(xe,`preview`),Ye=!0)}),l.user_effect(()=>{if(l.get(Ve).length===0){l.set(Fe,void 0),He=!1;return}(!He||!l.get(Fe)||!l.get(Ve).some(e=>e.id===l.get(Fe)))&&(l.set(Fe,l.get(We)?.id??l.get(Ve).at(-1)?.id,!0),He=!1)});let Xe=l.derived(()=>l.get(We)?.id),Ze=l.derived(()=>t_(l.get(le))),$e=new d,et=l.state(void 0),tt=l.derived(()=>l.get(et)??l.get(Ze)?.id??void 0),nt=l.derived(()=>!l.get(he)&&l.get(Je)!=null&&l.get(Je).id!==l.get(tt)),rt=l.derived(()=>l.get(tt)!==l.get(Xe)),it=l.state(!1),at=l.state(void 0),ot=l.state(!1),st=l.state(!1),ct=async()=>{if(!(!l.get(w)||!l.get(Je)||l.get(it))){l.set(it,!0),l.set(at,void 0);try{let e=await ab({replicache:await l.get(h).getReplicache(),spriteId:l.get(w).id,spriteBuildId:l.get(Je).id});if(e instanceof Error){l.set(at,e,!0);return}l.set(et,e.spriteBuildId,!0),l.set(ot,!1)}finally{l.set(it,!1)}}},lt=()=>{l.set(v,!1)},ut=()=>{l.get(rt)?l.set(ot,!0):lt()},dt=()=>{l.set(ot,!1),lt()},ft=()=>{l.set(ot,!1)},pt=e=>{if(e){if(typeof e.message==`string`)return e.message;if(typeof e.error==`string`)return e.error}},mt=e=>{let t=Lm.outputSchema.safeParse(e);return t.success?t.data:void 0},ht=l.derived(()=>l.get(T)?.cancelRequestedAt!=null),gt=l.derived(()=>!l.get(ht)&&(l.get(T)?.status===`PENDING`||l.get(T)?.status===`IN_PROGRESS`)),_t=async()=>{!l.get(w)||!l.get(T)||!l.get(gt)||await(await l.get(h).getReplicache()).mutate.spriteBuild_cancel_v1({spriteBuildId:l.get(T).id})},vt=async(e,t)=>{l.set(me,void 0),l.set(fe,!0);try{let n=e.trim();if(!n)throw Error(`Missing build prompt`);let r=Vm({messageList:Yp(t)});if(r instanceof Error)throw r;console.table([{"Frontend build plan (inactive)":n,"Backend build plan (active)":r}]);let i=await l.get(h).getReplicache(),a=xt();await i.mutate.spriteBuild_create_v2({spriteBuildId:a,spriteId:l.get(m),parentSpriteBuildId:l.get(Xe),prompt:r});let o=l.get(g).spriteBuild.get(a).value;return o?ge(o):l.set(pe,a,!0),{spriteBuildId:a}}finally{l.set(fe,!1)}};l.user_effect(()=>{if(l.get(ue)||l.get(de))return;let e=ax({client:i(),spriteId:l.get(m),toolList:l.get(_),getSpriteBuildEventList:e=>l.get(C).filter(t=>t.spriteBuildId===e),onStartBuild:({prompt:e},t)=>vt(e,t),onMessagesChange:e=>{l.set(Ae,e,!0)},onLoadingChange:e=>{l.set(je,e,!0)},onErrorChange:e=>{l.set(Me,e,!0)}});return l.set(ke,e,!0),e.attach(),l.set(Ae,e.getMessages(),!0),l.set(je,e.getIsLoading(),!0),l.set(Me,e.getError(),!0),()=>{e.dispose(),l.get(ke)===e&&l.set(ke,void 0)}});let yt=l.derived(()=>l.get(ke)!=null&&!l.get(he)&&!l.get(je)&&l.get(Oe).trim().length>0),bt=async e=>{e.preventDefault();let t=l.get(Oe).trim();if(!(!t||l.get(he)||l.get(je))){if(l.set(me,void 0),l.set(Me,void 0),!l.get(ke)){l.set(me,Error(`Feature builder chat is not ready`),!0);return}try{await ne(),l.set(Oe,``),await l.get(ke).sendMessage(t)}catch(e){l.set(me,e instanceof Error?e:Error(String(e)),!0)}}},St=e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),bt(e))};return l.user_effect(()=>{l.get(E)!==`chat`&&l.set(xe,l.get(E),!0)}),l.user_effect(()=>{let e=l.get(Pe);e&&(l.get(Oe),e.style.height=`auto`,e.style.height=`${e.scrollHeight}px`)}),l.user_effect(()=>{let e=l.get(Le),t=l.get(Ie);if(!e||!t)return;let n=new ResizeObserver(()=>{t.scrollTop=t.scrollHeight});return n.observe(e),()=>n.disconnect()}),gx(e,{get target(){return o()},oncancel:ut,get onclose(){return c()},get isOpen(){return l.get(v)},set isOpen(e){l.set(v,e,!0)},children:(e,t)=>{var r=WS();let a;var o=l.child(r),s=l.child(o),c=l.child(s,!0);l.reset(s);var u=l.sibling(s,2);l.reset(o);var d=l.sibling(o,2),f=e=>{var t=TS();l.append(e,t)},p=e=>{var t=ES(),n=l.child(t,!0);l.reset(t),l.template_effect(()=>l.set_text(n,l.get(de).message)),l.append(e,t)},m=e=>{var t=US();let r,a;{let e=(e,t=l.noop,n=l.noop,r=l.noop)=>{var i=kS(),a=l.child(i),o=l.child(a,!0);l.reset(a);var s=l.sibling(a,2),c=e=>{var t=DS(),r=l.child(t,!0);l.reset(t),l.template_effect(()=>l.set_text(r,n())),l.append(e,t)};l.if(s,e=>{n()&&e(c)});var u=l.sibling(s,2),d=e=>{var t=OS(),n=l.sibling(l.child(t),2),i=l.child(n,!0);l.reset(n),l.reset(t),l.template_effect(e=>l.set_text(i,e),[()=>JSON.stringify(r(),null,2)]),l.append(e,t)};l.if(u,e=>{r()&&e(d)}),l.reset(i),l.template_effect(()=>l.set_text(o,t())),l.append(e,i)},r=(t,n=l.noop)=>{let r=l.derived(()=>n().id===l.get(tt)),a=l.derived(()=>l.get(Ve).indexOf(n())+1);var o=MS();let s;var c=l.child(o),u=e=>{Nb(e,{get client(){return i()},get spriteBuild(){return n()}})};l.if(c,e=>{n().status!==`READY`&&n().status!==`ERROR`&&e(u)});var d=l.sibling(c,2),f=e=>{var t=jS(),i=l.child(t),o=l.child(i),s=l.child(o),c=l.sibling(s),u=e=>{var t=AS();l.append(e,t)};l.if(c,e=>{l.get(r)&&e(u)}),l.reset(o),l.reset(i),l.reset(t),l.template_effect(()=>l.set_text(s,`Version ${l.get(a)??``} ready `)),l.delegated(`click`,i,()=>Ue(n().id)),l.append(e,t)},p=t=>{{let r=l.derived(()=>pt(n().error));e(t,()=>`Version ${l.get(a)} failed`,()=>l.get(r),()=>n().error)}};l.if(d,e=>{n().status===`READY`?e(f):n().status===`ERROR`&&e(p,1)}),l.reset(o),l.template_effect(()=>s=l.set_class(o,1,`turn svelte-t9dwgq`,null,s,{"turn-published":l.get(r)})),l.append(t,o)};var o=l.child(t),s=l.child(o),c=l.child(s);l.each(c,17,()=>l.get(Ae),e=>e.id,(e,t)=>{var i=FS();let a;l.each(i,23,()=>l.get(t).parts,(e,n)=>`${l.get(t).id}-${n}`,(e,i)=>{var a=l.comment(),o=l.first_child(a),s=e=>{var r=PS(),a=l.child(r),o=l.child(a,!0);l.reset(a);var s=l.sibling(a,2),c=e=>{var t=l.comment(),r=l.first_child(t);l.html(r,()=>n(l.get(i).content)),l.append(e,t)},u=e=>{var t=NS(),n=l.child(t,!0);l.reset(t),l.template_effect(()=>l.set_text(n,l.get(i).content)),l.append(e,t)};l.if(s,e=>{l.get(t).role===`assistant`?e(c):e(u,-1)}),l.reset(r),l.template_effect(()=>l.set_text(o,l.get(t).role===`user`?`You`:`Rough`)),l.append(e,r)},c=e=>{let t=l.derived(()=>mt(l.get(i).output)),n=l.derived(()=>l.get(t)?l.get(Ve).find(e=>e.id===l.get(t).spriteBuildId):void 0);var a=l.comment(),o=l.first_child(a),s=e=>{r(e,()=>l.get(n))};l.if(o,e=>{l.get(n)&&e(s)}),l.append(e,a)};l.if(o,e=>{l.get(i).type===`text`?e(s):l.get(i).type===`tool-call`&&l.get(i).name===`startBuild`&&e(c,1)}),l.append(e,a)}),l.reset(i),l.template_effect(()=>a=l.set_class(i,1,`chat-message svelte-t9dwgq`,null,a,{"chat-message-user":l.get(t).role===`user`,"chat-message-assistant":l.get(t).role===`assistant`})),l.append(e,i)});var u=l.sibling(c,2),d=e=>{var t=IS();l.append(e,t)};l.if(u,e=>{l.get(Ne)&&e(d)});var f=l.sibling(u,2),p=t=>{e(t,()=>`Couldn't chat`,()=>l.get(Me).message)};l.if(f,e=>{l.get(Me)&&e(p)});var m=l.sibling(f,2),h=t=>{e(t,()=>`Couldn't send message`,()=>l.get(me).message)};l.if(m,e=>{l.get(me)&&e(h)}),l.reset(s),l.bind_this(s,e=>l.set(Le,e),()=>l.get(Le)),l.reset(o),l.bind_this(o,e=>l.set(Ie,e),()=>l.get(Ie));var g=l.sibling(o,2);l.set_attribute(g,`aria-valuemin`,0),l.set_attribute(g,`aria-valuemax`,100);var v=l.sibling(g,2),y=l.child(v);tS(l.child(y),{get tabs(){return ye},get active(){return l.get(xe)},set active(e){l.set(xe,e,!0)}}),l.reset(y);var b=l.sibling(y,2),ee=t=>{e(t,()=>`Couldn't publish version`,()=>l.get(at).message)};l.if(b,e=>{l.get(at)&&e(ee)});var x=l.sibling(b,2);iS(x,{get isActive(){return l.get(D)},children:(e,t)=>{SS(e,{get toolList(){return l.get(_)}})},$$slots:{default:!0}});var te=l.sibling(x,2);iS(te,{get isActive(){return l.get(Ee)},children:(e,t)=>{var n=l.comment(),r=l.first_child(n),i=e=>{{let t=l.derived(()=>l.get(Ge).artifactUrl??void 0);Zx(e,{get toolList(){return l.get(_)},get spriteId(){return l.get(w).id},get spriteBuildId(){return l.get(Ge).id},get artifactUrl(){return l.get(t)},spriteInstanceId:void 0,isMock:!0})}},a=e=>{var t=LS();l.append(e,t)};l.if(r,e=>{l.get(w)&&l.get(Ge)?.status===`READY`&&l.get(Ge).artifactUrl?e(i):e(a,-1)}),l.append(e,n)},$$slots:{default:!0}}),iS(l.sibling(te,2),{get isActive(){return l.get(De)},children:(e,t)=>{var n=zS(),r=l.child(n),a=e=>{$b(e,{get client(){return i()},get spriteBuild(){return l.get(Ke)}})},o=e=>{var t=RS();l.append(e,t)};l.if(r,e=>{l.get(Ke)?e(a):e(o,-1)}),l.reset(n),l.append(e,n)},$$slots:{default:!0}}),l.reset(v);var ne=l.sibling(v,2),re=l.child(ne);let a;var ie=l.child(re);l.remove_textarea_child(ie),l.bind_this(ie,e=>l.set(Pe,e),()=>l.get(Pe));var ae=l.sibling(ie,2),oe=e=>{var t=BS(),n=l.child(t),r=e=>{ub(e,{})},i=e=>{h_(e,{size:12,fill:`currentColor`,"aria-hidden":`true`})};l.if(n,e=>{l.get(ht)?e(r):e(i,-1)}),l.reset(t),l.template_effect(()=>{t.disabled=!l.get(gt),l.set_attribute(t,`aria-label`,l.get(ht)?`Stopping build`:`Stop build`)}),l.delegated(`click`,t,()=>void _t()),l.append(e,t)},se=e=>{var t=VS();p_(l.child(t),{size:16,"aria-hidden":`true`}),l.reset(t),l.template_effect(()=>t.disabled=!l.get(yt)),l.append(e,t)};l.if(ae,e=>{l.get(he)?e(oe):e(se,-1)}),l.reset(re),l.reset(ne);var ce=l.sibling(ne,2),le=l.child(ce);{let e=l.derived(()=>!l.get(nt)||l.get(it));fx(le,{get disabled(){return l.get(e)},onclick:()=>void ct(),children:(e,t)=>{l.next();var n=l.text();l.template_effect(()=>l.set_text(n,l.get(it)?`Publishing…`:`Publish`)),l.append(e,n)},$$slots:{default:!0}})}l.reset(ce);var S=l.sibling(ce,2),C=e=>{ix(e,{title:`Publish before closing?`,detail:`You have iterations from this session that aren't published yet.`,get error(){return l.get(at)},actions:e=>{var t=HS(),n=l.first_child(t);yx(n,{onclick:ft,children:(e,t)=>{l.next();var n=l.text(`Keep editing`);l.append(e,n)},$$slots:{default:!0}});var r=l.sibling(n,2);yx(r,{onclick:dt,children:(e,t)=>{l.next();var n=l.text(`Close anyway`);l.append(e,n)},$$slots:{default:!0}});var i=l.sibling(r,2);{let e=l.derived(()=>!l.get(nt)||l.get(it));fx(i,{get disabled(){return l.get(e)},onclick:()=>void ct(),children:(e,t)=>{l.next();var n=l.text();l.template_effect(()=>l.set_text(n,l.get(it)?`Publishing…`:`Publish`)),l.append(e,n)},$$slots:{default:!0}})}l.append(e,t)},$$slots:{actions:!0}})};l.if(S,e=>{l.get(ot)&&e(C)}),l.reset(t),l.bind_this(t,e=>l.set(Re,e),()=>l.get(Re)),l.template_effect(()=>{l.set_attribute(g,`aria-valuenow`,l.get(Be)),a=l.set_class(re,1,`composer-input svelte-t9dwgq`,null,a,{isBuilding:l.get(he)})}),l.delegated(`pointerdown`,g,function(...e){ze.onpointerdown?.apply(this,e)}),l.delegated(`pointermove`,g,function(...e){ze.onpointermove?.apply(this,e)}),l.delegated(`pointerup`,g,function(...e){ze.onpointerup?.apply(this,e)}),l.event(`pointercancel`,g,function(...e){ze.onpointercancel?.apply(this,e)}),l.delegated(`keydown`,g,function(...e){ze.onkeydown?.apply(this,e)}),l.event(`submit`,ne,bt),l.delegated(`keydown`,ie,St),l.bind_value(ie,()=>l.get(Oe),e=>l.set(Oe,e))}l.template_effect(()=>{r=l.set_class(t,1,`feature-builder svelte-t9dwgq`,null,r,{"tab-chat":l.get(Se),"tab-preview":l.get(we),"tab-capabilities":l.get(Ce),"tab-logs":l.get(Te)}),a=l.set_style(t,``,a,{"--chat-column":ze.column})}),l.append(e,t)};l.if(d,e=>{l.get(ue)?e(f):l.get(de)?e(p,1):e(m,-1)}),lx(l.sibling(d,2),{get tabs(){return be},ariaLabel:`Feature builder sections`,get active(){return l.get(E)},set active(e){l.set(E,e,!0)}}),l.reset(r),l.template_effect(()=>{a=l.set_class(r,1,`surface svelte-t9dwgq`,null,a,{"rough-dark":l.get(st)}),l.set_text(c,`⌥ ${l.get(w)?.name??`Rough`}`)}),l.delegated(`pointerup`,s,e=>{e.altKey&&l.set(st,!l.get(st))}),l.delegated(`click`,u,ut),l.append(e,r)},$$slots:{default:!0}}),l.pop({get client(){return i()},set client(e){i(e),l.flush()},get surface(){return a()},set surface(e){a(e),l.flush()},get portalTarget(){return o()},set portalTarget(e){o(e),l.flush()},get onclose(){return c()},set onclose(e){c(e),l.flush()},get action(){return f()},set action(e){f(e),l.flush()}})}l.delegate([`pointerup`,`click`,`pointerdown`,`pointermove`,`keydown`]),l.create_custom_element(KS,{client:{},surface:{},portalTarget:{},onclose:{},action:{}},[],[],{mode:`open`});function qS(e,t){l.push(t,!0);let n=l.prop(t,`client`,7),r=l.prop(t,`surface`,7),i=l.prop(t,`surfaceId`,7),a=l.prop(t,`portalTarget`,7),o=l.prop(t,`onclose`,7);var s={get client(){return n()},set client(e){n(e),l.flush()},get surface(){return r()},set surface(e){r(e),l.flush()},get surfaceId(){return i()},set surfaceId(e){i(e),l.flush()},get portalTarget(){return a()},set portalTarget(e){a(e),l.flush()},get onclose(){return o()},set onclose(e){o(e),l.flush()}};{let t=l.derived(()=>({type:`create`,surfaceId:i()}));KS(e,{get client(){return n()},get surface(){return r()},get portalTarget(){return a()},get action(){return l.get(t)},get onclose(){return o()}})}return l.pop(s)}customElements.define(`rough-create-modal`,l.create_custom_element(qS,{client:{},surface:{},surfaceId:{},portalTarget:{},onclose:{}},[],[]));var JS=async e=>{let{client:t,signal:n}=e,r=Qg(t);r.assertUsable();let i=Lt(e.surface),o=e.target??document.body,s=r.surfaces.acquire({surface:i}),l=new AbortController,u,d,f,p,m=()=>(p??=(async()=>{l.abort(new wt(`Modal closed`));let e=u;u=void 0,e&&await c(e),d?.remove(),d=void 0,s.release(),f?.(),f=void 0})(),p);if(f=r.operations.register({label:`openRoughCreate(${i.key})`,close:m}),n){if(n.aborted)throw await m(),new wt(`Modal opening was aborted`);n.addEventListener(`abort`,()=>void m(),{once:!0})}try{let e=await Promise.race([s.ready.then(e=>({type:`resolved`,resolution:e})),Mt(l.signal).then(()=>({type:`aborted`}))]);if(e.type===`aborted`||l.signal.aborted)throw new wt(`The Rough client was destroyed before the create modal could open`);r.assertUsable(),d=document.createElement(`div`),o.appendChild(d),u=a(qS,{target:d,props:{client:t,surface:i,surfaceId:e.resolution.id,onclose:()=>{m()}}})}catch(e){throw await m(),e}return{close:m}};function YS(e,t){l.push(t,!0);let n=l.prop(t,`client`,7),r=l.prop(t,`surface`,7),i=l.prop(t,`spriteId`,7),a=l.prop(t,`portalTarget`,7),o=l.prop(t,`onclose`,7);var s={get client(){return n()},set client(e){n(e),l.flush()},get surface(){return r()},set surface(e){r(e),l.flush()},get spriteId(){return i()},set spriteId(e){i(e),l.flush()},get portalTarget(){return a()},set portalTarget(e){a(e),l.flush()},get onclose(){return o()},set onclose(e){o(e),l.flush()}};{let t=l.derived(()=>({type:`edit`,spriteId:i()}));KS(e,{get client(){return n()},get surface(){return r()},get portalTarget(){return a()},get action(){return l.get(t)},get onclose(){return o()}})}return l.pop(s)}customElements.define(`rough-edit-modal`,l.create_custom_element(YS,{client:{},surface:{},spriteId:{},portalTarget:{},onclose:{}},[],[]));var XS=l.from_html(`<!> <!>`,1);function ZS(e,t){l.push(t,!0);let n=l.prop(t,`client`,7),r=l.prop(t,`surface`,7),i=l.prop(t,`spriteId`,7),a=l.prop(t,`label`,7,`Edit Rough Feature`),o=l.state(!1),s=()=>{l.set(o,!0)},c=()=>{l.set(o,!1)};var u={get client(){return n()},set client(e){n(e),l.flush()},get surface(){return r()},set surface(e){r(e),l.flush()},get spriteId(){return i()},set spriteId(e){i(e),l.flush()},get label(){return a()},set label(e=`Edit Rough Feature`){a(e),l.flush()}},d=XS(),f=l.first_child(d);fx(f,{onclick:s,children:(e,t)=>{l.next();var n=l.text();l.template_effect(()=>l.set_text(n,`⌥ ${a()??``}`)),l.append(e,n)},$$slots:{default:!0}});var p=l.sibling(f,2),m=e=>{YS(e,{get client(){return n()},get surface(){return r()},get spriteId(){return i()},onclose:c})};return l.if(p,e=>{l.get(o)&&e(m)}),l.append(e,d),l.pop(u)}customElements.define(`rough-edit-button`,l.create_custom_element(ZS,{client:{},surface:{},spriteId:{},label:{}},[],[]));var QS=`data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='17441%2015570%20441%20441'%20fill='none'%20stroke='currentColor'%20stroke-linecap='square'%20stroke-linejoin='miter'%20%3e%3ctitle%3eRough%20logo%3c/title%3e%3cdefs%3e%3cclipPath%20id='rough-logo'%3e%3crect%20x='17501'%20y='15630'%20width='321'%20height='321'%20/%3e%3c/clipPath%3e%3c/defs%3e%3cg%20clip-path='url(%23rough-logo)'%3e%3cg%20transform='matrix(1,0,0,1,17606.5311,15766.3152)'%3e%3cpolygon%20fill='currentColor'%20stroke='none'%20points='17.41,-136.32%20173.47,179.78%20173.47,184.68%2088.38,184.68%20-63.53,-122.94%20-63.53,-136.32'%20/%3e%3c/g%3e%3cpath%20stroke-width='78.5'%20d='M%2017473%2015669.25%20L%2017543%2015669.25'%20/%3e%3cpath%20stroke-width='78.5'%20d='M%2017780%2015669.25%20L%2017750%2015669.25'%20/%3e%3cpath%20stroke-width='78.5'%20d='M%2017780%2015911.75%20L%2017850%2015911.75'%20/%3e%3c/g%3e%3c/svg%3e`,$S=l.from_html(`<div class="chrome svelte-1aurlo0"><button class="badge svelte-1aurlo0" aria-label="Edit Rough Feature"><img alt="Rough Logo"/></button> <!></div> <!>`,1),eC={hash:`svelte-1aurlo0`,code:`.chrome.svelte-1aurlo0 {position:relative;isolation:isolate;}.badge.svelte-1aurlo0 {position:absolute;top:8px;right:8px;z-index:10;display:flex;align-items:center;justify-content:center;width:2rem;height:2rem;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-md, 0.375rem);padding:0.25rem;background:var(--rough-brand, #cb4b16);box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));opacity:0;cursor:pointer;pointer-events:none;transition:opacity 150ms ease, box-shadow 120ms ease;}.badge.svelte-1aurlo0:focus-visible {border-color:var(--rough-ring, oklch(0.708 0 0));outline:none;box-shadow:0 0 0 3px color-mix(in oklch, var(--rough-ring, oklch(0.708 0 0)) 45%, transparent);}.chrome.svelte-1aurlo0:hover .badge:where(.svelte-1aurlo0),
134
134
  .chrome.svelte-1aurlo0:focus-within .badge:where(.svelte-1aurlo0),
135
- .chrome.svelte-1aurlo0:active .badge:where(.svelte-1aurlo0) {opacity:1;pointer-events:auto;}`};function $S(e,t){l.push(t,!0),l.append_styles(e,QS);let n=l.prop(t,`client`,7),r=l.prop(t,`surface`,7),i=l.prop(t,`spriteId`,7),a=l.prop(t,`children`,7),o=l.state(!1),s=()=>{l.set(o,!0)},c=()=>{l.set(o,!1)};var u={get client(){return n()},set client(e){n(e),l.flush()},get surface(){return r()},set surface(e){r(e),l.flush()},get spriteId(){return i()},set spriteId(e){i(e),l.flush()},get children(){return a()},set children(e){a(e),l.flush()}},d=ZS(),f=l.first_child(d),p=l.child(f),m=l.child(p);l.reset(p);var h=l.sibling(p,2);l.snippet(h,a),l.reset(f);var g=l.sibling(f,2),_=e=>{qS(e,{get client(){return n()},get surface(){return r()},get spriteId(){return i()},onclose:c})};return l.if(g,e=>{l.get(o)&&e(_)}),l.template_effect(()=>l.set_attribute(m,`src`,XS)),l.delegated(`click`,p,s),l.append(e,d),l.pop(u)}l.delegate([`click`]),l.create_custom_element($S,{client:{},surface:{},spriteId:{},children:{}},[],[],{mode:`open`});function eC(e,t){l.push(t,!0);let n=l.prop(t,`client`,7),r=l.prop(t,`surface`,7),i=l.prop(t,`featureId`,7),a=l.prop(t,`buildId`,7),o=l.prop(t,`datastore`,7);return $S(e,{get client(){return n()},get surface(){return r()},get spriteId(){return i()},children:(e,t)=>{Yx(e,{get client(){return n()},get spriteId(){return i()},get spriteBuildId(){return a()},get spriteInstanceId(){return i()},get toolList(){return r().tools},get datastore(){return o()}})},$$slots:{default:!0}}),l.pop({get client(){return n()},set client(e){n(e),l.flush()},get surface(){return r()},set surface(e){r(e),l.flush()},get featureId(){return i()},set featureId(e){i(e),l.flush()},get buildId(){return a()},set buildId(e){a(e),l.flush()},get datastore(){return o()},set datastore(e){o(e),l.flush()}})}customElements.define(`rough-feature`,l.create_custom_element(eC,{client:{},surface:{},featureId:{},buildId:{},datastore:{}},[],[]));var tC=l.from_html(`<div class="surface svelte-1f41bpr"><div class="frame-container svelte-1f41bpr"></div></div>`),nC={hash:`svelte-1f41bpr`,code:`.surface.svelte-1f41bpr {flex:1;width:100%;border:1px dashed var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-lg, 0.625rem);padding:0.5rem;background:var(--rough-background, white);}.frame-container.svelte-1f41bpr {display:flex;gap:0.5rem;flex-direction:column;}`};function rC(e,t){l.push(t,!0),l.append_styles(e,nC);let n=l.prop(t,`client`,7),r=l.prop(t,`surface`,7),i=l.prop(t,`getDatastore`,7),a=l.state(l.proxy([]));s(()=>{let e=n_({client:n(),surface:r(),onFeatures:e=>{l.set(a,e,!0)},onError:e=>{console.error(`[Rough] Failed to load features`,e)}});return()=>{e.unsubscribe()}});var o={get client(){return n()},set client(e){n(e),l.flush()},get surface(){return r()},set surface(e){r(e),l.flush()},get getDatastore(){return i()},set getDatastore(e){i(e),l.flush()}},c=tC(),u=l.child(c);return l.each(u,21,()=>l.get(a),e=>e.id,(e,t)=>{let a=l.derived(()=>i()?.({spriteId:l.get(t).id,spriteInstanceId:l.get(t).id}));var o=l.comment(),s=l.first_child(o),c=e=>{eC(e,{get client(){return n()},get surface(){return r()},get featureId(){return l.get(t).id},get buildId(){return l.get(t).publishedSpriteBuildId},get datastore(){return l.get(a)}})};l.if(s,e=>{l.get(t).publishedSpriteBuildId&&e(c)}),l.append(e,o)}),l.reset(u),l.reset(c),l.append(e,c),l.pop(o)}customElements.define(`rough-surface`,l.create_custom_element(rC,{client:{},surface:{},getDatastore:{}},[],[]));var iC=l.from_html(`<div class="SpriteBuildMenuItem svelte-1uvsqdj" role="none"><div class="copy svelte-1uvsqdj"><h3 class="svelte-1uvsqdj"> </h3> <p class="svelte-1uvsqdj"> </p></div> <!></div>`),aC={hash:`svelte-1uvsqdj`,code:`.SpriteBuildMenuItem.svelte-1uvsqdj {display:flex;align-items:flex-start;justify-content:space-between;gap:1rem;border-radius:var(--rough-radius-sm, 0.25rem);padding:0.75rem;background:transparent;color:var(--rough-popover-foreground, oklch(0.145 0 0));}.SpriteBuildMenuItem.svelte-1uvsqdj:hover {background:var(--rough-accent, oklch(0.97 0 0));color:var(--rough-accent-foreground, oklch(0.205 0 0));}.copy.svelte-1uvsqdj {min-width:0;}.copy.svelte-1uvsqdj h3:where(.svelte-1uvsqdj) {margin:0;font-size:0.875rem;font-weight:600;}.copy.svelte-1uvsqdj p:where(.svelte-1uvsqdj) {margin:0.25rem 0 0;color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:0.8rem;line-height:1.45;}`};function oC(e,t){l.push(t,!0),l.append_styles(e,aC);let n=l.prop(t,`sprite`,7),r=l.prop(t,`spriteBuild`,7),i=l.prop(t,`onselect`,7),a=async()=>{i()?.(n(),r())};var o={get sprite(){return n()},set sprite(e){n(e),l.flush()},get spriteBuild(){return r()},set spriteBuild(e){r(e),l.flush()},get onselect(){return i()},set onselect(e){i(e),l.flush()}},s=iC(),c=l.child(s),u=l.child(c),d=l.child(u,!0);l.reset(u);var f=l.sibling(u,2),p=l.child(f,!0);return l.reset(f),l.reset(c),ux(l.sibling(c,2),{onclick:a,role:`menuitem`,children:(e,t)=>{l.next();var n=l.text(`Insert`);l.append(e,n)},$$slots:{default:!0}}),l.reset(s),l.template_effect(()=>{l.set_text(d,n().name),l.set_text(p,r().prompt)}),l.append(e,s),l.pop(o)}l.create_custom_element(oC,{sprite:{},spriteBuild:{},onselect:{}},[],[],{mode:`open`});var sC=l.from_html(`<!> Insert Existing Rough Feature`,1),cC=l.from_html(`<p class="svelte-17o42e2">Loading…</p>`),lC=l.from_html(`<div class="menu svelte-17o42e2" role="menu"><!></div>`),uC=l.from_html(`<div class="SpriteBuildMenu svelte-17o42e2"><!> <!></div>`),dC={hash:`svelte-17o42e2`,code:`.SpriteBuildMenu.svelte-17o42e2 {position:relative;}.menu.svelte-17o42e2 {position:absolute;top:calc(100% + 0.5rem);left:0;z-index:10;display:grid;gap:0.25rem;min-width:22rem;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-md, 0.375rem);padding:0.25rem;background:var(--rough-popover, white);box-shadow:var(--rough-shadow-md, 0 4px 6px -1px rgb(0 0 0 / 0.1));color:var(--rough-popover-foreground, oklch(0.145 0 0));}.menu.svelte-17o42e2 p:where(.svelte-17o42e2) {margin:0;padding:0.75rem;color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:0.875rem;}`};function fC(e,t){l.push(t,!0),l.append_styles(e,dC);let n=l.prop(t,`client`,7),r=l.prop(t,`surfaceId`,7),i=l.prop(t,`onselect`,7),a=l.derived(()=>Xg(n()).store),o=l.derived(()=>lb(l.get(a).meta.get($e))),s=l.derived(()=>l.get(o)._),c=l.derived(()=>lb(l.get(a).sprite.filter(`sprite-build-menu:${r()}`,e=>e.surfaceId===r()))),u=l.derived(()=>l.get(c)._),d=l.derived(()=>lb(l.get(a).spriteBuild.asList)),f=l.derived(()=>l.get(d)._),p=l.derived(()=>l.get(s)?.state===`READY`),m=l.derived(()=>l.get(u).flatMap(e=>{let t=$g(l.get(f).filter(t=>t.spriteId===e.id));return t?[{sprite:{id:e.id,name:e.name,ownedByPersonId:e.ownedByPersonId,publishedSpriteBuildId:t.id},spriteBuild:t}]:[]})),h=l.state(!1),g=()=>{l.set(h,!l.get(h))},_=(e,t)=>{l.set(h,!1),i()?.(e,t)};var v={get client(){return n()},set client(e){n(e),l.flush()},get surfaceId(){return r()},set surfaceId(e){r(e),l.flush()},get onselect(){return i()},set onselect(e){i(e),l.flush()}},y=uC(),b=l.child(y);_x(b,{onclick:g,"aria-haspopup":`menu`,get"aria-expanded"(){return l.get(h)},children:(e,t)=>{var n=sC();iS(l.first_child(n),{size:20}),l.next(),l.append(e,n)},$$slots:{default:!0}});var ee=l.sibling(b,2),te=e=>{var t=lC(),n=l.child(t),r=e=>{var t=cC();l.append(e,t)},i=e=>{var t=l.comment(),n=l.first_child(t);l.each(n,17,()=>l.get(m),e=>e.sprite.id,(e,t)=>{oC(e,{get sprite(){return l.get(t).sprite},get spriteBuild(){return l.get(t).spriteBuild},onselect:_})}),l.append(e,t)};l.if(n,e=>{l.get(p)?e(i,-1):e(r)}),l.reset(t),l.append(e,t)};return l.if(ee,e=>{l.get(h)&&e(te)}),l.reset(y),l.append(e,y),l.pop(v)}l.create_custom_element(fC,{client:{},surfaceId:{},onselect:{}},[],[],{mode:`open`});export{ae as Mutation,ux as PrimaryButton,oe as Query,Dx as ResizeHandle,Ot as RoughClientDestroyError,Tt as RoughClientDestroyedError,GS as RoughCreateModal,YS as RoughEditButton,eC as RoughFeature,kt as RoughInvalidClientError,Et as RoughReplicacheIdentityConflictError,rC as RoughSurface,Dt as RoughSurfaceContractConflictError,_x as SecondaryButton,fC as SpriteBuildMenu,Yx as SpriteFrame,se as Subscription,Zg as createRoughClient,It as defineRoughSurface,n_ as getRoughFeatures,KS as openRoughCreate,Qg as whenRoughClientReady};
135
+ .chrome.svelte-1aurlo0:active .badge:where(.svelte-1aurlo0) {opacity:1;pointer-events:auto;}`};function tC(e,t){l.push(t,!0),l.append_styles(e,eC);let n=l.prop(t,`client`,7),r=l.prop(t,`surface`,7),i=l.prop(t,`spriteId`,7),a=l.prop(t,`children`,7),o=l.state(!1),s=()=>{l.set(o,!0)},c=()=>{l.set(o,!1)};var u={get client(){return n()},set client(e){n(e),l.flush()},get surface(){return r()},set surface(e){r(e),l.flush()},get spriteId(){return i()},set spriteId(e){i(e),l.flush()},get children(){return a()},set children(e){a(e),l.flush()}},d=$S(),f=l.first_child(d),p=l.child(f),m=l.child(p);l.reset(p);var h=l.sibling(p,2);l.snippet(h,a),l.reset(f);var g=l.sibling(f,2),_=e=>{YS(e,{get client(){return n()},get surface(){return r()},get spriteId(){return i()},onclose:c})};return l.if(g,e=>{l.get(o)&&e(_)}),l.template_effect(()=>l.set_attribute(m,`src`,QS)),l.delegated(`click`,p,s),l.append(e,d),l.pop(u)}l.delegate([`click`]),l.create_custom_element(tC,{client:{},surface:{},spriteId:{},children:{}},[],[],{mode:`open`});function nC(e,t){l.push(t,!0);let n=l.prop(t,`client`,7),r=l.prop(t,`surface`,7),i=l.prop(t,`featureId`,7),a=l.prop(t,`buildId`,7),o=l.prop(t,`datastore`,7);return tC(e,{get client(){return n()},get surface(){return r()},get spriteId(){return i()},children:(e,t)=>{Zx(e,{get client(){return n()},get spriteId(){return i()},get spriteBuildId(){return a()},get spriteInstanceId(){return i()},get toolList(){return r().tools},get datastore(){return o()}})},$$slots:{default:!0}}),l.pop({get client(){return n()},set client(e){n(e),l.flush()},get surface(){return r()},set surface(e){r(e),l.flush()},get featureId(){return i()},set featureId(e){i(e),l.flush()},get buildId(){return a()},set buildId(e){a(e),l.flush()},get datastore(){return o()},set datastore(e){o(e),l.flush()}})}customElements.define(`rough-feature`,l.create_custom_element(nC,{client:{},surface:{},featureId:{},buildId:{},datastore:{}},[],[]));var rC=l.from_html(`<div class="surface svelte-1f41bpr"><div class="frame-container svelte-1f41bpr"></div></div>`),iC={hash:`svelte-1f41bpr`,code:`.surface.svelte-1f41bpr {flex:1;width:100%;border:1px dashed var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-lg, 0.625rem);padding:0.5rem;background:var(--rough-background, white);}.frame-container.svelte-1f41bpr {display:flex;gap:0.5rem;flex-direction:column;}`};function aC(e,t){l.push(t,!0),l.append_styles(e,iC);let n=l.prop(t,`client`,7),r=l.prop(t,`surface`,7),i=l.prop(t,`getDatastore`,7),a=l.state(l.proxy([]));s(()=>{let e=i_({client:n(),surface:r(),onFeatures:e=>{l.set(a,e,!0)},onError:e=>{console.error(`[Rough] Failed to load features`,e)}});return()=>{e.unsubscribe()}});var o={get client(){return n()},set client(e){n(e),l.flush()},get surface(){return r()},set surface(e){r(e),l.flush()},get getDatastore(){return i()},set getDatastore(e){i(e),l.flush()}},c=rC(),u=l.child(c);return l.each(u,21,()=>l.get(a),e=>e.id,(e,t)=>{let a=l.derived(()=>i()?.({spriteId:l.get(t).id,spriteInstanceId:l.get(t).id}));var o=l.comment(),s=l.first_child(o),c=e=>{nC(e,{get client(){return n()},get surface(){return r()},get featureId(){return l.get(t).id},get buildId(){return l.get(t).publishedSpriteBuildId},get datastore(){return l.get(a)}})};l.if(s,e=>{l.get(t).publishedSpriteBuildId&&e(c)}),l.append(e,o)}),l.reset(u),l.reset(c),l.append(e,c),l.pop(o)}customElements.define(`rough-surface`,l.create_custom_element(aC,{client:{},surface:{},getDatastore:{}},[],[]));var oC=l.from_html(`<div class="SpriteBuildMenuItem svelte-1uvsqdj" role="none"><div class="copy svelte-1uvsqdj"><h3 class="svelte-1uvsqdj"> </h3> <p class="svelte-1uvsqdj"> </p></div> <!></div>`),sC={hash:`svelte-1uvsqdj`,code:`.SpriteBuildMenuItem.svelte-1uvsqdj {display:flex;align-items:flex-start;justify-content:space-between;gap:1rem;border-radius:var(--rough-radius-sm, 0.25rem);padding:0.75rem;background:transparent;color:var(--rough-popover-foreground, oklch(0.145 0 0));}.SpriteBuildMenuItem.svelte-1uvsqdj:hover {background:var(--rough-accent, oklch(0.97 0 0));color:var(--rough-accent-foreground, oklch(0.205 0 0));}.copy.svelte-1uvsqdj {min-width:0;}.copy.svelte-1uvsqdj h3:where(.svelte-1uvsqdj) {margin:0;font-size:0.875rem;font-weight:600;}.copy.svelte-1uvsqdj p:where(.svelte-1uvsqdj) {margin:0.25rem 0 0;color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:0.8rem;line-height:1.45;}`};function cC(e,t){l.push(t,!0),l.append_styles(e,sC);let n=l.prop(t,`sprite`,7),r=l.prop(t,`spriteBuild`,7),i=l.prop(t,`onselect`,7),a=async()=>{i()?.(n(),r())};var o={get sprite(){return n()},set sprite(e){n(e),l.flush()},get spriteBuild(){return r()},set spriteBuild(e){r(e),l.flush()},get onselect(){return i()},set onselect(e){i(e),l.flush()}},s=oC(),c=l.child(s),u=l.child(c),d=l.child(u,!0);l.reset(u);var f=l.sibling(u,2),p=l.child(f,!0);return l.reset(f),l.reset(c),fx(l.sibling(c,2),{onclick:a,role:`menuitem`,children:(e,t)=>{l.next();var n=l.text(`Insert`);l.append(e,n)},$$slots:{default:!0}}),l.reset(s),l.template_effect(()=>{l.set_text(d,n().name),l.set_text(p,r().prompt)}),l.append(e,s),l.pop(o)}l.create_custom_element(cC,{sprite:{},spriteBuild:{},onselect:{}},[],[],{mode:`open`});var lC=l.from_html(`<!> Insert Existing Rough Feature`,1),uC=l.from_html(`<p class="svelte-17o42e2">Loading…</p>`),dC=l.from_html(`<div class="menu svelte-17o42e2" role="menu"><!></div>`),fC=l.from_html(`<div class="SpriteBuildMenu svelte-17o42e2"><!> <!></div>`),pC={hash:`svelte-17o42e2`,code:`.SpriteBuildMenu.svelte-17o42e2 {position:relative;}.menu.svelte-17o42e2 {position:absolute;top:calc(100% + 0.5rem);left:0;z-index:10;display:grid;gap:0.25rem;min-width:22rem;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-md, 0.375rem);padding:0.25rem;background:var(--rough-popover, white);box-shadow:var(--rough-shadow-md, 0 4px 6px -1px rgb(0 0 0 / 0.1));color:var(--rough-popover-foreground, oklch(0.145 0 0));}.menu.svelte-17o42e2 p:where(.svelte-17o42e2) {margin:0;padding:0.75rem;color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:0.875rem;}`};function mC(e,t){l.push(t,!0),l.append_styles(e,pC);let n=l.prop(t,`client`,7),r=l.prop(t,`surfaceId`,7),i=l.prop(t,`onselect`,7),a=l.derived(()=>Qg(n()).store),o=l.derived(()=>db(l.get(a).meta.get(Qe))),s=l.derived(()=>l.get(o)._),c=l.derived(()=>db(l.get(a).sprite.filter(`sprite-build-menu:${r()}`,e=>e.surfaceId===r()))),u=l.derived(()=>l.get(c)._),d=l.derived(()=>db(l.get(a).spriteBuild.asList)),f=l.derived(()=>l.get(d)._),p=l.derived(()=>l.get(s)?.state===`READY`),m=l.derived(()=>l.get(u).flatMap(e=>{let t=t_(l.get(f).filter(t=>t.spriteId===e.id));return t?[{sprite:{id:e.id,name:e.name,ownedByPersonId:e.ownedByPersonId,publishedSpriteBuildId:t.id},spriteBuild:t}]:[]})),h=l.state(!1),g=()=>{l.set(h,!l.get(h))},_=(e,t)=>{l.set(h,!1),i()?.(e,t)};var v={get client(){return n()},set client(e){n(e),l.flush()},get surfaceId(){return r()},set surfaceId(e){r(e),l.flush()},get onselect(){return i()},set onselect(e){i(e),l.flush()}},y=fC(),b=l.child(y);yx(b,{onclick:g,"aria-haspopup":`menu`,get"aria-expanded"(){return l.get(h)},children:(e,t)=>{var n=lC();oS(l.first_child(n),{size:20}),l.next(),l.append(e,n)},$$slots:{default:!0}});var ee=l.sibling(b,2),x=e=>{var t=dC(),n=l.child(t),r=e=>{var t=uC();l.append(e,t)},i=e=>{var t=l.comment(),n=l.first_child(t);l.each(n,17,()=>l.get(m),e=>e.sprite.id,(e,t)=>{cC(e,{get sprite(){return l.get(t).sprite},get spriteBuild(){return l.get(t).spriteBuild},onselect:_})}),l.append(e,t)};l.if(n,e=>{l.get(p)?e(i,-1):e(r)}),l.reset(t),l.append(e,t)};return l.if(ee,e=>{l.get(h)&&e(x)}),l.reset(y),l.append(e,y),l.pop(v)}l.create_custom_element(mC,{client:{},surfaceId:{},onselect:{}},[],[],{mode:`open`});export{ie as Mutation,fx as PrimaryButton,ae as Query,kx as ResizeHandle,Dt as RoughClientDestroyError,wt as RoughClientDestroyedError,qS as RoughCreateModal,ZS as RoughEditButton,nC as RoughFeature,Ot as RoughInvalidClientError,Tt as RoughReplicacheIdentityConflictError,aC as RoughSurface,Et as RoughSurfaceContractConflictError,yx as SecondaryButton,mC as SpriteBuildMenu,Zx as SpriteFrame,oe as Subscription,$g as createRoughClient,Ft as defineRoughSurface,i_ as getRoughFeatures,JS as openRoughCreate,e_ as whenRoughClientReady};