@roughapp/feature 0.3.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +40 -5
- package/README.md +206 -116
- package/index.d.ts +10 -1
- package/index.js +62 -17
- package/package.json +2 -2
package/index.js
CHANGED
|
@@ -1,21 +1,58 @@
|
|
|
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)}},S=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()},se=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})})},ce=`/`,C=e=>{let t=`${e}${ce}`,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})},w=e=>{let t=`${e}${ce}`,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]}${ce}`;case 2:return`${t}${e[0]}${ce}${e[1]}`;default:throw Error(`Unexpected number of ids: "${e}"`)}},isMatch:e=>e.startsWith(t),encode:(e,n)=>`${t}${e}${ce}${n}`,decode:e=>{if(!e.startsWith(t))throw Error(`Expected serialized to start with prefix "${t}", received "${e}"`);return e.substring(n).split(ce)},decodeWithoutPrefix:e=>e.split(ce)})},T={internal:C(`__internal`)(),apiToken:C(`apiToken`)(),asset:C(`asset`)(),backlogTask:C(`backlogTask`)(),block:C(`block`)(),comment:C(`comment`)(),content:C(`content`)(),document:C(`document`)(),draftContent:C(`draftContent`)(),event:C(`event`)(),filter:C(`filter`)(),filterRule:C(`filterRule`)(),fizzyAccount:C(`fizzyAccount`)(),fizzyBoard:C(`fizzyBoard`)(),fizzyIntegration:C(`fizzyIntegration`)(),invitation:C(`invitation`)(),inviteLink:C(`inviteLink`)(),label:C(`label`)(),note:C(`note`)(),notification:C(`notification`)(),person:C(`person`)(),project:C(`project`)(),projectAccount:C(`projectAccount`)(),reaction:C(`reaction`)(),reference:C(`reference`)(),sequence:C(`sequence`)(),signingKey:C(`signingKey`)(),sprite:C(`sprite`)(),spriteBuild:C(`spriteBuild`)(),spriteBuildEvent:C(`spriteBuildEvent`)(),surface:C(`surface`)(),task:C(`task`)(),vcsBranch:C(`vcsBranch`)(),vcsCommit:C(`vcsCommit`)(),vcsIntegration:C(`vcsIntegration`)(),vcsRepo:C(`vcsRepo`)(),vcsUser:C(`vcsUser`)(),watch:C(`watch`)(),workspace:C(`workspace`)(),blockUser:w(`blockUser`)(),documentUser:w(`documentUser`)(),sequenceDocument:w(`sequenceDocument`)(),signingKeyProject:w(`signingKeyProject`)(),vcsCommitDocument:w(`vcsCommitDocument`)(),noteLabel:w(`noteLabel`)(),spriteProjectAccount:w(`spriteProjectAccount`)(),taskLabel:w(`taskLabel`)(),relatedDocumentNote:w(`relatedDocumentNote`)(),relatedDocumentPair:w(`relatedDocumentPair`)(),relatedNotePair:w(`relatedNotePair`)(),relatedSpritePair:w(`relatedSpritePair`)(),stackTask:w(`stackTask`)(),workspaceUser:C(`workspaceUser`)()},le=(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},ue=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 de(e){return e&&typeof e==`object`&&`parents`in e}function fe(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 pe=(e,t)=>{if(e.children.remove(t)&&e.children.isEmpty&&de(e))for(let t=0,n=e.parents.length;t<n;t++)pe(e.parents[t],e)},me=(e,t)=>{if(e.children.add(t)&&de(e))for(let t=0,n=e.parents.length;t<n;t++)me(e.parents[t],e)};function he(e,t){return e===t||Object.is(e,t)||!!(e&&t&&typeof e.equals==`function`&&e.equals(t))}var ge=Object.freeze([]),_e=Symbol.for(`__signia__`),ve=globalThis;ve[_e]?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.`):ve[_e]=!0;var ye=class{constructor(e,t){this.below=e,this.child=t}offset=0;numNewParents=0;maybeRemoved},E=null;function be(e){E=new ye(E,e)}function xe(){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&&pe(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&&pe(n,e.child)}}}function Se(e){if(E){let t=E.child.parents.indexOf(e);if(t<0&&(E.numNewParents++,E.child.isActivelyListening&&me(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 Ce=Symbol(`RESET_VALUE`),we=class{constructor(e){this.capacity=e,this.buffer=Array(e)}index=0;buffer;pushEntry(e,t,n){if(n!==void 0){if(n===Ce){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 Ce;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 Ce}},D=0,Te=!1;function Ee(){D++}function De(e){if(Te)throw Error(`cannot change atoms during reaction cycle`);try{Te=!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{Te=!1}}function Oe(e,t){ke?ke.initialAtomValues.has(e)||ke.initialAtomValues.set(e,t):De([e])}var ke=null,Ae=class{constructor(e,t,n){this.name=e,this.current=t,this.isEqual=n?.isEqual??null,n&&(n.historyLength&&(this.historyBuffer=new we(n.historyLength)),this.computeDiff=n.computeDiff)}isEqual;computeDiff;lastChangedEpoch=D;children=new ue;historyBuffer;__unsafe__getWithoutCapture(){return this.current}get value(){return Se(this),this.current}set(e,t){if(this.isEqual?.(this.current,e)??he(this.current,e))return this.current;Ee(),this.historyBuffer&&this.historyBuffer.pushEntry(this.lastChangedEpoch,D,t??this.computeDiff?.(this.current,e,this.lastChangedEpoch,D)??Ce),this.lastChangedEpoch=D;let n=this.current;return this.current=e,Oe(this,n),e}update(e){return this.set(e(this.current))}getDiffSince(e){return Se(this),e>=this.lastChangedEpoch?ge:this.historyBuffer?.getChangesSince(e)??Ce}};function je(e,t,n){return new Ae(e,t,n)}var Me=Symbol(`UNINITIALIZED`),Ne=class{constructor(e,t){this.value=e,this.diff=t}},Pe=class{constructor(e,t,n){this.name=e,this.derive=t,n?.historyLength&&(this.historyBuffer=new we(n.historyLength)),this.computeDiff=n?.computeDiff,this.isEqual=n?.isEqual??he}lastChangedEpoch=-1;lastTraversedEpoch=-1;lastCheckedEpoch=-1;parents=[];parentEpochs=[];children=new ue;get isActivelyListening(){return!this.children.isEmpty}historyBuffer;state=Me;computeDiff;isEqual;__unsafe__getWithoutCapture(){let e=this.lastChangedEpoch===-1;if(!e&&(this.lastCheckedEpoch===D||!fe(this)))return this.lastCheckedEpoch=D,this.state;try{be(this);let t=this.derive(this.state,this.lastCheckedEpoch),n=t instanceof Ne?t.value:t;if(this.state===Me||!this.isEqual(n,this.state)){if(this.historyBuffer&&!e){let e=t instanceof Ne?t.diff:void 0;this.historyBuffer.pushEntry(this.lastChangedEpoch,D,e??this.computeDiff?.(this.state,n,this.lastCheckedEpoch,D)??Ce)}this.lastChangedEpoch=D,this.state=n}return this.lastCheckedEpoch=D,this.state}finally{xe()}}get value(){let e=this.__unsafe__getWithoutCapture();return Se(this),e}getDiffSince(e){return this.value,e>=this.lastChangedEpoch?ge:this.historyBuffer?.getChangesSince(e)??Ce}};function Fe(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 Pe(n,i.bind(this),e),Object.defineProperty(this,a,{enumerable:!1,configurable:!1,writable:!1,value:t})),t.value},r}function Ie(){if(arguments.length===1){let e=arguments[0];return(t,n,r)=>Fe(e,t,n,r)}return typeof arguments[0]==`string`?new Pe(arguments[0],arguments[1],arguments[2]):Fe(void 0,arguments[0],arguments[1],arguments[2])}var Le=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&&!fe(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++)me(this.parents[e],this)}detach(){this._isActivelyListening=!1;for(let e=0,t=this.parents.length;e<t;e++)pe(this.parents[e],this)}execute(){try{be(this);let e=this.runEffect(this.lastReactedEpoch);return this.lastReactedEpoch=D,e}finally{xe()}}};function Re(e,t,n){let r=new Le(e,t,n);return r.attach(),r.scheduleEffect(),()=>{r.detach()}}var ze=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)},Be=class{key;mapValue;name;atom;asRecord;asList;getCache=new Map;findCache=new Map;filterCache=new Map;mapCache=new Map;someCache=new Map;constructor(e){this.key=e.key,this.mapValue=e.mapValue,this.name=`Table(${this.key.name})`,this.atom=je(this.name,{},{historyLength:1}),this.asRecord=this.atom,this.asList=Ie(`${this.name}:values`,()=>Object.values(this.atom.value))}get(e){let t=e,n=this.getCache.get(t);return n||(n=Ie(`${this.name}:get(${t})`,()=>this.atom.value[t]),this.getCache.set(t,n)),n}find(e,t){let n=this.findCache.get(e);return n||(n=Ie(`${this.name}:find(${e})`,()=>this.asList.value.find(t)),this.findCache.set(e,n)),n}filter(e,t){let n=this.filterCache.get(e);return n||(n=Ie(`${this.name}:filter(${e})`,()=>this.asList.value.filter(t)),this.filterCache.set(e,n)),n}map(e,t){let n=this.mapCache.get(e);return n||(n=Ie(`${this.name}:map(${e})`,()=>this.asList.value.map(t)),this.mapCache.set(e,n)),n}some(e,t){let n=this.someCache.get(e);return n||(n=Ie(`${this.name}:some(${e})`,()=>this.asList.value.some(t)),this.someCache.set(e,n)),n}clear(){this.atom.set({},[])}set(e,t){let n=this.atom.__unsafe__getWithoutCapture(),r=Object.hasOwn(n,e);this.atom.set({...n,[e]:t},[]),r||this.getCache.delete(e)}pushDiffList(e){ze({diffList:e,source:this.atom,mapKey:e=>this.key.trimPrefix(e),mapValue:(e,t)=>this.mapValue(e,this.key.decode(t))})}},Ve=`store`,He=C(`meta`)(),Ue=()=>{let e={meta:new Be({key:He,mapValue:e=>e}),person:new Be({key:T.person,mapValue:(e,t)=>({id:t,name:e.name})}),surface:new Be({key:T.surface,mapValue:(e,t)=>({id:t,key:e.key,name:e.name,description:e.description})}),sprite:new Be({key:T.sprite,mapValue:(e,t)=>({id:t,name:e.name,surfaceId:e.surfaceId,ownedByPersonId:e.ownedByPersonId})}),spriteBuild:new Be({key:T.spriteBuild,mapValue:(e,t)=>({id:t,spriteId:e.spriteId,parentSpriteBuildId:e.parentSpriteBuildId,createdByPersonId:e.createdByPersonId,prompt:e.prompt,status:e.status,artifactUrl:e.artifactUrl,sourceUrl:null,startedAt:null,stoppedAt:null,error:e.error,reasoningSummary:e.reasoningSummary,publishedAt:e.publishedAt})}),spriteBuildEvent:new Be({key:T.spriteBuildEvent,mapValue:(e,t)=>({id:t,spriteBuildId:e.spriteBuildId,actionedAt:e.actionedAt,type:e.type,detail:e.detail})})},t={[T.person.name]:e.person,[T.surface.name]:e.surface,[T.spriteBuildEvent.name]:e.spriteBuildEvent,[T.spriteBuild.name]:e.spriteBuild,[T.sprite.name]:e.sprite},n=new Set,r,i=!1,a=()=>{e.meta.clear(),e.person.clear(),e.surface.clear(),e.sprite.clear(),e.spriteBuild.clear(),e.spriteBuildEvent.clear()},o=()=>{for(let e of n)e()},s=n=>{if(i)return;r?.(),a(),e.meta.set(Ve,{state:`LOADING`});let s=!1;r=n.experimentalWatch(n=>{let r=le(n,e=>e.key.match(/^(\w+)\//)?.[1]??``);for(let[e,n]of Object.entries(r))t[e]?.pushDiffList(n);s||(s=!0,e.meta.set(Ve,{state:`READY`})),o()},{initialValuesInFirstDiff:!0})},c=e=>(n.add(e),()=>{n.delete(e)}),l=async()=>{i=!0,r?.(),r=void 0,a(),n.clear()};return{...e,bind:s,subscribe:c,destroy:l}},We=y(((e,t)=>{var n=self.crypto;function r(e){let t=new Uint8Array(e);return n.getRandomValues(t),t}t.exports={randomBytes:r}})),Ge=y(((e,t)=>{var{randomBytes:n}=We(),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)}}})),Ke=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{}}})),qe=y(((e,t)=>{var{InvalidEpoch:n}=Ke(),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}}})),Je=y(((e,t)=>{var n=Ge(),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}}}})),Ye=y(((e,t)=>{var n=Ge(),r=qe(),{BaseId:i}=Je(),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}})),Xe=y(((e,t)=>{var{Ulid:n,setTime:r}=Ye(),i=Ge(),a=qe(),{ClockSequenceOverflow:o}=Ke(),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}})),Ze=y(((e,t)=>{var{BaseId:n}=Je(),r=Ge(),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}})),Qe=y(((e,t)=>{var{randomBytes:n}=We(),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}}})),$e=y(((e,t)=>{var n=Ge(),r=qe(),i=Qe(),{Uuid:a,setVariant:o,setVersion:s}=Ze(),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}})),et=y(((e,t)=>{var n=Ge(),{Uuid:r,setVariant:i,setVersion:a}=Ze();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)}}}})),tt=y(((e,t)=>{var n=Ge(),r=qe(),i=Qe(),{Uuid:a,setVariant:o,setVersion:s}=Ze(),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}})),nt=y(((e,t)=>{var n=Ge(),{Uuid:r,setVariant:i,setVersion:a}=Ze();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)}}}})),rt=y(((e,t)=>{var{InvalidEncoding:n,InvalidBytes:r}=Ke(),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)}}}})),it=y(((e,t)=>{var{BaseCoder:n}=rt(),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}}})),at=y(((e,t)=>{var{BaseCoder:n}=rt(),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}}})),ot=y(((e,t)=>{var{BaseCoder:n}=rt(),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]]}}})),st=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)}}}})),ct=y(((e,t)=>{var{IdFactory:n}=st(),{UnsupportedVersion:r}=Ke(),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()}}}})),lt=x(y(((e,t)=>{var{Ulid:n}=Ye(),{UlidMonotonic:r}=Xe(),{Uuid:i}=Ze(),{Uuid1:a}=$e(),{Uuid4:o}=et(),{Uuid6:s}=tt(),{UuidNil:c}=nt(),l=it(),u=at(),d=ot(),{IdFactory:f}=st(),{VersionedIdFactory:p}=ct(),m={idCompare:function(e,t){return e.compare(t)},idEqual:function(e,t){return e.equal(t)},Exception:Ke(),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),ut=e=>lt.default.UlidMonotonic.generate({time:e}).toCanonical(),dt=async(e,t)=>e.query(async e=>{for await(let[n,r]of e.scan({prefix:T.surface.prefix()}).entries())if(r.key===t)return{id:T.surface.decode(n),...r}}),ft=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=ut();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 dt(n,r)||Error(`Surface "${r}" missing from Replicache`)})},pt=class extends Error{name=`RoughClientDestroyedError`;constructor(e=`The Rough client has been destroyed`){super(e)}},mt=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}},ht=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}},gt=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}},_t=class extends Error{name=`RoughInvalidClientError`;constructor(e=`Expected a RoughClient created by createRoughClient()`){super(e)}},vt=e=>e instanceof Error?e:Error(String(e)),yt=e=>e.reason instanceof Error?e.reason:new pt,bt=e=>new Promise((t,n)=>{if(e.aborted){n(yt(e));return}e.addEventListener(`abort`,()=>n(yt(e)),{once:!0})}),xt=e=>new Promise(t=>{if(e.aborted){t();return}e.addEventListener(`abort`,()=>t(),{once:!0})}),St=Symbol(`rough.surface.definition`),Ct=(e,t)=>{if(typeof e!=`string`||e.trim()===``)throw TypeError(`defineRoughSurface: "${t}" must be a non-empty string`);return e},wt=e=>{let t=Ct(e.key,`key`),n=Ct(e.name,`name`),r=Ct(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,St,{value:!0,enumerable:!1,writable:!1,configurable:!1}),Object.freeze(i)},Tt=e=>typeof e==`object`&&!!e&&St in e&&e[St]===!0,Et=e=>{if(!Tt(e))throw TypeError(`Expected a surface created by defineRoughSurface(). Object literals are not accepted because the definition must be validated and frozen.`);return e},Dt=e=>JSON.stringify({key:e.key,name:e.name,description:e.description,tools:e.tools.map(e=>e.toJSON())}),Ot=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(),bt(n)]);r.assertUsable();let a=await ft({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=Et(e.surface);if(t().assertUsable(),r)throw new pt;let o=Dt(i),s=n.get(i.key);if(s&&s.registrationFingerprint!==o){if(s.activeOperationCount>0)throw new ht({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 pt);await Promise.allSettled(e.map(e=>e.resolution))},getActiveOperationCount:e=>n.get(e)?.activeOperationCount??0}},kt=()=>{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=vt(t);throw n.message=`${e.label}: ${n.message}`,n}}))).flatMap(e=>e.status===`rejected`?[vt(e.reason)]:[]);if(n.length>0)throw new gt({errors:n})},size:()=>e.size}},At=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?.()))}},jt=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()}},Mt={log(e,t,...n){console[e](...Pt(t),...n.map(Ft))}},Nt=class e extends jt{#e;#t;#n;constructor(e=`info`,t,n=Mt){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 Pt(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 Ft(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,It)}function It(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 Lt=class{_lockP=null;async lock(){let e=this._lockP,{promise:t,resolve:n}=O();return this._lockP=t,await e,n}withLock(e){return zt(this.lock(),e)}},Rt=class{_lock=new Lt;_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 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}=O();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 Bt=b({ValitaError:()=>Yt,array:()=>Gn,bigint:()=>In,boolean:()=>Bn,err:()=>Qt,lazy:()=>Jn,literal:()=>Hn,never:()=>En,null:()=>Mn,number:()=>Pn,object:()=>Un,ok:()=>Zt,record:()=>Wn,string:()=>Rn,tuple:()=>Kn,undefined:()=>An,union:()=>qn,unknown:()=>On});function Vt(e,t){return e?{ok:!1,code:`join`,left:e,right:t}:t}function Ht(e,t){return{ok:!1,code:`prepend`,key:e,tree:t}}function Ut(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 Wt(e,t=[],n=[]){for(;;)if(e.code===`join`)Wt(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(Ut(e,t)),n}function Gt(e,t){return e.length===0?`nothing`:e.length===1?e[0]:`${e.slice(0,-1).join(`, `)} ${t} ${e[e.length-1]}`}function Kt(e){return typeof e==`bigint`?`${e}n`:JSON.stringify(e)}function qt(e){let t=0;for(;;)if(e.code===`join`)t+=qt(e.left),e=e.right;else if(e.code===`prepend`)e=e.tree;else return t+1}function Jt(e){let t=``,n=0;for(;;)if(e.code===`join`)n+=qt(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 ${Gt(e.expected,`or`)}`;else if(e.code===`invalid_literal`)r=`expected ${Gt(e.expected.map(Kt),`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`} ${Gt(t.map(Kt),`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 Yt=class extends Error{constructor(e){super(Jt(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=Wt(this.issueTree)),this._issues}},Xt=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=Wt(this.issueTree)),this._issues}get message(){return this._message===void 0&&(this._message=Jt(this.issueTree)),this._message}throw(){throw new Yt(this.issueTree)}};function Zt(e){return{ok:!0,value:e}}function Qt(e){return new Xt({ok:!1,code:`custom_error`,error:e})}function $t(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var en=1,tn=2,nn=4,rn=class{optional(e){let t=new on(this);return e?new Cn(t,t=>t===void 0?{ok:!0,value:e()}:void 0):t}default(e){let t=Zt(e);return new Cn(this.optional(),e=>e===void 0?t:void 0)}assert(e,t){let n={ok:!1,code:`custom_error`,error:t};return new Cn(this,(t,r)=>e(t,r)?void 0:n)}map(e){return new Cn(this,(t,n)=>({ok:!0,value:e(t,n)}))}chain(e){return new Cn(this,(t,n)=>{let r=e(t,n);return r.ok?r:r.issueTree})}},k=class extends rn{nullable(){return new an(this)}toTerminals(e){e(this)}try(e,t){let n=en;t?.mode===`passthrough`?n=0:t?.mode===`strip`&&(n=tn);let r=this.func(e,n);return r===void 0?{ok:!0,value:e}:r.ok?{ok:!0,value:r.value}:new Xt(r)}parse(e,t){let n=en;t?.mode===`passthrough`?n=0:t?.mode===`strip`&&(n=tn);let r=this.func(e,n);if(r===void 0)return e;if(r.ok)return r.value;throw new Yt(r)}},an=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(jn),this.type.toTerminals(e)}nullable(){return this}},on=class extends rn{constructor(e){super(),this.type=e,this.name=`optional`}func(e,t){return e===void 0||t&nn?void 0:this.type.func(e,t)}toTerminals(e){e(this),e(kn),this.type.toTerminals(e)}optional(e){return e?new Cn(this,t=>t===void 0?{ok:!0,value:e()}:void 0):this}};function sn(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:sn([e,0],t)}function cn(e,t){return typeof e==`number`?t<32?e>>>t&1:0:e[t>>5]>>>t%32&1}var ln=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(!$t(e))return this._invalidType;let n=this._func;return n===void 0&&(n=un(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 un(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=>Ht(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&en||r&tn||t!==void 0)for(let n in e){let c=e[n],u=~l[n],_;if(u>=0)g++,h=sn(h,u),_=s[u].func(c,r);else if(t!==void 0)_=t.func(c,r);else{if(r&en)m===void 0?m=[n]:m.push(n);else if(r&tn&&p===void 0&&!i){f={},i=!0;for(let t=0;t<o;t++)if(cn(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=Vt(p,Ht(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&&cn(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(cn(h,n))continue;let l=a[n],m=e[l],g=r&-5;if(m===void 0&&!(l in e)){if(n<c){p=Vt(p,u[n]);continue}g|=nn}let _=s[n].func(m,g);if(_===void 0)i&&p===void 0&&!(g&nn)&&d(f,l,m);else if(!_.ok)p=Vt(p,Ht(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||cn(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(!cn(h,t)){let n=a[t];d(f,n,e[n])}}}d(f,l,_.value)}}if(m!==void 0&&(p=Vt(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 dn=class e extends k{constructor(e,t,n){super(),this.prefix=e,this.rest=t,this.suffix=n,this.name=`array`,this.restType=t??En(),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=Vt(s,Ht(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 fn(e){let t=typeof e;return t===`object`?e===null?`null`:Array.isArray(e)?`array`:t:t}function pn(e){return Array.from(new Set(e))}function mn(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 hn(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(fn(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(fn(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,pn(e.concat(i).sort(s)))),n.forEach((e,t)=>n.set(t,pn(e.concat(i)).sort(s))),{types:r,literals:n,unknowns:pn(i).sort(s),optionals:pn(a).sort(s),expectedTypes:pn(o)}}function gn(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}=hn(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=Ht(t,{ok:!1,code:`missing_value`}),l=Ht(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?.[fn(i)]??u?.get(i);return o?o.func(r,n):l}}function _n(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 mn(n)){let n=gn(t,e);if(n)return n}}function vn(e){let{expectedTypes:t,literals:n,types:r,unknowns:i,optionals:a}=hn(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&nn?a:c?.[fn(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?Vt(l,a):a,r++}return r>1?{ok:!1,code:`invalid_union`,tree:l}:l}}var yn=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=vn(e),r=_n(e);n=r?function(e,n){return $t(e)?r(e,n):t(e,n)}:t,this._func=n}return n(e,t)}},bn=Object.freeze({mode:`strict`}),xn=Object.freeze({mode:`strip`}),Sn=Object.freeze({mode:`passthrough`}),Cn=class e extends k{constructor(e,t){super(),this.transformed=e,this.transform=t,this.name=`transform`,this.undef=Zt(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&nn?(a=void 0,i=this.undef):a=t:a=i.value;let o=n&en?bn:n&tn?xn:Sn;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)}},wn=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}}},Tn=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 En(){return Tn}var Dn=new class extends k{constructor(){super(...arguments),this.name=`unknown`}func(e,t){}};function On(){return Dn}var kn=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 An(){return kn}var jn=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 Mn(){return jn}var Nn=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 Pn(){return Nn}var Fn=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 In(){return Fn}var Ln=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 Rn(){return Ln}var zn=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 Bn(){return zn}var Vn=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 Hn(e){return new Vn(e)}function Un(e){return new ln(e,void 0)}function Wn(e){return new ln({},e??On())}function Gn(e){return new dn([],e??On(),[])}function Kn(e){return new dn(e,void 0,[])}function qn(...e){return new yn(e)}function Jn(e){return new wn(e)}var Yn=Object.defineProperty,Xn=Object.getOwnPropertyDescriptor,Zn=Object.getOwnPropertyNames,Qn=Object.prototype.hasOwnProperty,$n=(e,t)=>{for(var n in t)Yn(e,n,{get:t[n],enumerable:!0})},er=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let i of Zn(t))!Qn.call(e,i)&&i!==n&&Yn(e,i,{get:()=>t[i],enumerable:!(r=Xn(t,i))||r.enumerable});return e},tr=(e,t,n)=>(er(e,t,`default`),n&&er(n,t,`default`)),nr=class extends Error{name=`AbortError`};function A(e,t=`Assertion failed`){if(!e)throw Error(t)}function j(e){ir(e,`string`)}function M(e){ir(e,`number`)}function rr(e){ir(e,`boolean`)}function ir(e,t){typeof e!==t&&sr(e,t)}function N(e){e===null&&sr(e,`object`),ir(e,`object`)}function ar(e){Array.isArray(e)||sr(e,`array`)}function or(e,t){let n=`Invalid type: `;return n+=e==null?e:`${typeof e} \`${e}\``,n+`, expected ${t}`}function sr(e,t){throw Error(or(e,t))}function cr(e){if(e===null)throw Error(`Expected non-null value`)}function lr(e,t=`Expected non undefined value`){if(e===void 0)throw Error(t)}function ur(e){throw Error(`Unreachable`)}function dr(){return typeof document<`u`?document:void 0}function fr(e,t,n){return e?new pr(e,t,n):new gr}var pr=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}},mr=Promise.resolve(),hr=new Promise(()=>{}),gr=class{visibilityState=`visible`;waitForVisible(){return mr}waitForHidden(){return hr}},_r=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}},vr=class extends _r{debounceDelay=0;get watchdogTimer(){return this.rep.pullInterval}},yr=class extends _r{get debounceDelay(){return this.rep.pushDelay}watchdogTimer=null},br=Promise.resolve();new Promise(()=>{});function xr(e,t){return e===0?br:new Promise((n,r)=>{let i;t&&(i=()=>{clearTimeout(a),r(new nr(`Aborted`))},t.addEventListener(`abort`,i,{once:!0}));let a=setTimeout(()=>{n(),t?.removeEventListener(`abort`,i)},e)})}var Sr=30,Cr=6e4,wr=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:Er()})}async send(e){if(this.#i)return{error:Er()};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,xr(e)]);for(;!this.#i;){a?.(kr(e)?`Last request failed. Trying again`:`Waiting for a send`);let c=[this.#e.promise],l=i.watchdogTimer;if(l!==null&&c.push(xr(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||kr(e)?(o=Dr(o,i,e),a?.(kr(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}),Ar(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}},Tr=9;function Er(){return Error(`Closed`)}function Dr(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>Tr;)n.shift();if(i&&!e.ok)return o}return Or(n.filter(({ok:e})=>e).map(({duration:e})=>e))/a|0}function Or(e){e.sort();let{length:t}=e,n=t>>1;return t%2==1?e[n]:(e[n-1]+e[n])/2}function kr(e){return e.length>0&&!e[e.length-1].ok}function Ar(e){return e.length>1&&!e[e.length-2].ok&&e[e.length-1].ok}var jr=process.env.NODE_ENV===`production`,Mr=Object.prototype.hasOwnProperty,Nr=Object.hasOwn||((e,t)=>Mr.call(e,t));function Pr(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(!Pr(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(Nr(e,r)){if(!Pr(e[r],t[r]))return!1;n++}let r=0;for(let e in t)Nr(t,e)&&r++;return n===r}function Fr(e){if(!jr){switch(typeof e){case`boolean`:case`number`:case`string`:return;case`object`:return e===null?void 0:Array.isArray(e)?Rr(e):Lr(e)}sr(e,`JSON value`)}}function Ir(e){N(e),Lr(e)}function Lr(e){for(let t in e)if(Nr(e,t)){let n=e[t];n!==void 0&&Fr(n)}}function Rr(e){for(let t of e)Fr(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)?Hr(e,t):Vr(e,t)}return!1}function Br(e,t){return typeof e!=`object`||!e?!1:Vr(e,t)}function Vr(e,t){for(let n in e)if(Nr(e,n)){t.push(n);let r=e[n];if(r!==void 0&&!zr(r,t))return!1;t.pop()}return!0}function Hr(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 Ur(e,t){return e===t?0:e<t?-1:1}function Wr(e,t){if(e===t)return 0;if(e===null)return-1;if(t===null)return 1;let n=Gr(e),r=Gr(t);return typeof n==`string`||typeof r==`string`?Ur(String(n),String(r)):n-r}function Gr(e){return typeof e==`string`||typeof e==`number`?e:e.order}function Kr(e){if(e!==null&&typeof e!=`string`&&typeof e!=`number`&&(Ir(e),typeof e.order!=`string`&&typeof e.order!=`number`))throw Error(`Invalid cookie`)}function*qr(...e){for(let t of e)yield*t}var Jr=Promise.resolve(!0),Yr=Promise.resolve(!1);Promise.resolve(void 0);var Xr=Promise.resolve(),Zr=1,Qr=4,$r=5,ei=8;function ti(e){switch(typeof e){case`string`:return Zr+Qr+e.length;case`number`:return ni(e)?e<=-(2**30)||e>=2**30-1?Zr+$r:Zr+Qr:Zr+ei;case`boolean`:return Zr;case`object`:if(e===null)return Zr;if(Array.isArray(e)){let t=2*Zr+Qr;for(let n of e)t+=ti(n);return t}{let t=e,n=2*Zr+Qr;for(let e in t)if(Nr(t,e)){let r=t[e];r!==void 0&&(n+=ti(e)+ti(r))}return n}}throw Error(`Invalid value. type: ${typeof e}, value: ${e}`)}function ni(e){return e===(e|0)}var ri=2*Zr+Qr+Zr+Qr;function ii(e,t){return ri+ti(e)+ti(t)}var ai=new WeakSet;function oi(e){return jr||si(e,[]),e}function si(e,t){switch(typeof e){case`undefined`:throw TypeError(`Unexpected value undefined`);case`boolean`:case`number`:case`string`:return;case`object`:if(e===null||ai.has(e))return;ai.add(e),t.includes(e)&&sr(e,`Cyclic JSON object`),t.push(e),Object.freeze(e),Array.isArray(e)?ci(e,t):li(e,t),t.pop();return;default:sr(e,`JSON value`)}}function ci(e,t){for(let n of e)si(n,t)}function li(e,t){for(let n in e)if(Nr(e,n)){let r=e[n];r!==void 0&&si(r,t)}}function ui(e){if(!jr&&!di(e,[]))throw Error(`Expected frozen object`)}function di(e,t){switch(typeof e){case`boolean`:case`number`:case`string`:return!0;case`object`:if(e===null||ai.has(e))return!0;if(!Object.isFrozen(e))return!1;if(t.includes(e)&&sr(e,`Cyclic JSON object`),t.push(e),Array.isArray(e)){for(let n of e)if(!di(n,t))return t.pop(),!1}else for(let n in e)if(Nr(e,n)){let r=e[n];if(r!==void 0&&!di(r,t))return t.pop(),!1}return ai.add(e),t.pop(),!0;default:sr(e,`JSON value`)}}function fi(e){if(e!==void 0)return oi(e)}function pi(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 mi=class{hash;data;meta;constructor(e,t,n){A(!n.includes(e),`Chunk cannot reference itself`),ui(t),this.hash=e,this.data=t,this.meta=n}};function hi(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 gi(e,t,n){return new mi(n(),e,t)}function _i(){throw Error(`unexpected call to compute chunk hash`)}function vi(){let e=Math.floor(Math.random()*4294967295),t=Math.floor(Math.random()*4294967295);return BigInt(e)<<32n|BigInt(t)}var P={};$n(P,{assert:()=>Ti,is:()=>wi,parse:()=>Ci,readonly:()=>Di,readonlyArray:()=>ki,readonlyObject:()=>Oi,readonlyRecord:()=>Ai,test:()=>Ei}),tr(P,Bt);function yi(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 bi(e,t){if(!t?.length)return yi(e);let n=e;for(let e of t)n=n[e];return yi(n)}function xi(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 Si(e,t){let n=e.issues[0],{path:r}=n,i=r?.length?` at ${r.join(`.`)}`:``;switch(n.code){case`invalid_type`:return`Expected ${xi(`or`,n.expected)}${i}. Got ${bi(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 ${xi(`or`,n.expected,yi)}${i} Got ${bi(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 ${xi(`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 ${bi(t,r)}`}}}function Ci(e,t,n){let r=Ei(e,t,n);if(!r.ok)throw TypeError(r.error);return r.value}function wi(e,t,n){return Ei(e,t,n).ok}function Ti(e,t,n){Ci(e,t,n)}function Ei(e,t,n){let r=t.try(e,n?{mode:n}:void 0);return r.ok?r:{ok:!1,error:Si(r,e)}}function Di(e){return e}function Oi(e){return Un(e)}function ki(e){return Gn(e)}function Ai(e){return Wn(e)}var ji=22,Mi=/^[0-9a-v-]+$/,F=`0`.repeat(ji),Ni=Fi();function Pi(e,t){return e.toString(32).slice(-t).padStart(t,`0`)}function Fi(){let e=``,t=0;return()=>{e||=Pi(vi(),12);let n=Pi(t++,10);return e+n}}function Ii(e){return typeof e==`string`&&Mi.test(e)}function Li(e){Ti(e,Ri)}var Ri=P.string().assert(Ii,`Invalid hash`);function zi(e,t,n){return new Bi(e,t,n).compute()}var Bi=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(!jr)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(jr||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}},Vi=class extends Error{name=`ChunkNotFoundError`;hash;constructor(e){super(`Chunk not found ${e}`),this.hash=e}};async function Hi(e,t){let n=await e.getChunk(t);if(n)return n;throw new Vi(t)}async function Ui(e,t){let n=await t.getHead(e);return A(n,`Missing head ${e}`),n}var Wi=class{#e=new Rt;#t=new Map;#n;#r;#i;t=new Map;n;h=new Map;m=new Map;constructor(e,t,n,r,i=ti){this.n=new qi(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 Gi(this.#t,this.t,this.n,this.#n,e,this.#i)}async write(){let e=await this.#e.write();return new Ki(this.#t,this.t,this.n,this.#n,this.h,this.m,e,this.#r,this.#i)}close(){return Xr}isCached(e){return this.n.getWithoutUpdatingLRU(e)!==void 0}withSuspendedSourceCacheEvictsAndDeletes(e){return this.n.withSuspendedEvictsAndDeletes(e)}},Gi=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 Hi(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}},Ki=class extends Gi{#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=gi(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}),Xr}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(qr(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)}},qi=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 Ji(e){return`c/${e}/d`}function Yi(e){return`c/${e}/m`}function Xi(e){return`c/${e}/r`}function Zi(e){return`h/${e}`}var Qi=class{#e;#t;#n;constructor(e,t,n){this.#e=e,this.#t=t,this.#n=n}async read(){return new $i(await this.#e.read(),this.#n)}async write(){return new ea(await this.#e.write(),this.#t,this.#n)}close(){return this.#e.close()}},$i=class{e;assertValidHash;constructor(e,t){this.e=e,this.assertValidHash=t}hasChunk(e){return this.e.has(Ji(e))}async getChunk(e){let t=await this.e.get(Ji(e));if(t===void 0)return;let n=await this.e.get(Yi(e)),r;return n===void 0?r=[]:(hi(n),r=n),new mi(e,t,r)}mustGetChunk(e){return Hi(this,e)}async getHead(e){let t=await this.e.get(Zi(e));if(t!==void 0)return Li(t),t}release(){this.e.release()}get closed(){return this.e.closed}},ea=class extends $i{#e;#t=new Set;#n=new Map;constructor(e,t,n){super(e,n),this.#e=t}createChunk=(e,t)=>gi(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=Ji(t),a=this.e.put(i,n),o;if(r.length>0){for(let e of r)this.assertValidHash(e);o=this.e.put(Yi(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=Zi(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(Xi(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(Yi(e));return t===void 0?[]:(hi(t),t)}async#i(e){let t=[];for(let[n,r]of e)if(r===0)t.push(this.#a(n));else{let e=Xi(n);t.push(this.e.put(e,r))}await Promise.all(t)}async#a(e){await Promise.all([this.e.del(Ji(e)),this.e.del(Yi(e)),this.e.del(Xi(e))]),this.#t.delete(e)}release(){this.e.release()}},I=`main`;function ta(e){return wa(e.meta)}function na(e){return Ca(e.meta)}function ra(e){return na(e)||ta(e)}function ia(e){return Aa(e.meta)}function aa(e){return ja(e.meta)}function oa(e){return ia(e)||aa(e)}var sa=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 ca(e,t,this.meta)}async getNextMutationID(e,t){return await this.getMutationID(e,t)+1}get indexes(){return this.chunk.data.indexes}};async function ca(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 ca(e,t,(await L(r,t)).meta)}default:ur(n)}}async function la(e,t){return(await va(e,t)).filter(e=>ra(e))}async function ua(e,t){return(await va(e,t)).filter(e=>na(e))}async function da(e,t,n){let r=[],i=new Map(Object.entries(t));for(;!oa(e)&&i.size>0;){if(na(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 fa(e,t){let n=await t.getHead(e);return A(n,`Missing head ${e}`),ma(n,t)}async function pa(e,t){return(await ma(e,t)).chunk.hash}async function ma(e,t){return ha(await L(e,t),t)}async function ha(e,t){for(;!oa(e);){let{meta:n}=e;if(Ca(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 ga(e,t){let n=e.meta;return Aa(n)?[n.lastMutationIDs[t]??0,n.cookieJSON]:[n.lastMutationID,n.cookieJSON]}function _a(e,t){return Wr(e.meta.cookieJSON,t.meta.cookieJSON)}async function va(e,t){let n=await L(e,t),r=[];for(;!oa(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 Ga(await t.mustGetChunk(e))}async function ya(e,t){return L(await Ui(e,t),t)}function ba(e){M(e.lastMutationID)}function xa(e){if(M(e.mutationID),j(e.mutatorName),!e.mutatorName)throw Error(`Missing mutator name`);Fr(e.mutatorArgsJSON),e.originalHash!==null&&Li(e.originalHash),M(e.timestamp)}function Sa(e){j(e.clientID),xa(e)}function Ca(e){return e.type===4}function wa(e){return e.type===2}function Ta(e){e.basisHash!==null&&Li(e.basisHash),Fr(e.cookieJSON)}function Ea(e){Ta(e),M(e.lastMutationID)}function Da(e){Ta(e),Oa(e.lastMutationIDs)}function Oa(e){N(e);for(let t of Object.values(e))M(t)}function ka(e){Da(e.meta)}function Aa(e){return e.type===5}function ja(e){return e.type===3}function Ma(e){switch(N(e),ui(e),e.basisHash!==null&&j(e.basisHash),M(e.type),e.type){case 1:ba(e);break;case 2:xa(e);break;case 4:Sa(e);break;case 3:Ea(e);break;case 5:Da(e);break;default:throw Error(`Invalid enum value ${e.type}`)}}function Na(e,t){return e.jsonPointer===t.jsonPointer&&(e.allowEmpty??!1)===(t.allowEmpty??!1)&&e.keyPrefix===t.keyPrefix}function Pa(e){N(e),ui(e),j(e.name),j(e.keyPrefix),j(e.jsonPointer),e.allowEmpty!==void 0&&rr(e.allowEmpty)}function Fa(e,t){return{name:e,keyPrefix:t.prefix??``,jsonPointer:t.jsonPointer,allowEmpty:t.allowEmpty??!1}}function Ia(e){N(e),ui(e),Pa(e.definition),j(e.valueHash)}function La(e){ar(e),ui(e);for(let t of e)Ia(t)}function Ra(e,t,n,r,i,a,o,s,c){return Ka(e,Ja({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 Ka(e,Ja({type:4,basisHash:t,baseSnapshotHash:n,mutationID:r,mutatorName:i,mutatorArgsJSON:a,originalHash:o,timestamp:l,clientID:u},s,c))}function Ba(e,t,n,r,i,a){return Ka(e,Ha(t,n,r,i,a))}function Va(e,t,n,r,i,a){return Ka(e,Ua(t,n,r,i,a))}function Ha(e,t,n,r,i){return Ja({type:3,basisHash:e,lastMutationID:t,cookieJSON:n},r,i)}function Ua(e,t,n,r,i){return Ja({type:5,basisHash:e,lastMutationIDs:t,cookieJSON:n},r,i)}function Wa(e,t,n,r,i){return Ka(e,Ja({type:1,basisHash:t,lastMutationID:n},r,i))}function Ga(e){return Xa(e),new sa(e)}function Ka(e,t){return new sa(e(t,qa(t)))}function qa(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:ur(n)}for(let n of e.indexes)t.add(n.valueHash);return pi(t)}function Ja(e,t,n){return oi({meta:e,valueHash:t,indexes:n})}function Ya(e){jr||(N(e),ui(e),Ma(e.meta),j(e.valueHash),La(e.indexes))}function Xa(e){let{data:t}=e;Ya(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 Za(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:Qa(to,ro(r,to),no,ro(i,no));n+=$a(r)}return n-r}function Qa(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 $a(e){return e>65535?2:1}var eo=()=>Array.from({length:4},()=>0),to=eo(),no=eo();function ro(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 io(e,t){return Za(e,t)>0}function ao(e,t){return Za(e,t)<0}function oo(e,t){return Za(e,t)<=0}function so(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 co(e){if(e!==(e|0)||e<4||e>7)throw Error(`Unsupported format version: ${e}`);return e}var lo=0,uo=1;function fo(e,t,n){return oi([e,n>=7?t:t.map(e=>e.slice(0,2))])}async function po(e,t,n,r){let i=await n.getNode(t);if(r!==n.rootHash)return po(e,n.rootHash,n,n.rootHash);if(To(i))return i;let{entries:a}=i,o=mo(e,a);o===a.length&&o--;let s=a[o];return po(e,s[1],n,r)}function mo(e,t){return so(t.length,n=>Za(e,t[n][0]))}function ho(e,t,n){return e!==t.length&&t[e][0]===n}function go(e,t,n){if(jr&&t>=7)return e;ar(e),ui(e),A(e.length>=2);let[r,i]=e;M(r),ar(i);let a=r>0?j:Fr;if(t>=7){for(let e of i)_o(e,a);return e}return[r,i.map(e=>vo(e,a,n))]}function _o(e,t){ar(e),A(e.length>=3),j(e[0]),t(e[1]),M(e[2])}function vo(e,t,n){ar(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 yo=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 bo(e,t){return fo(e.level,e.entries,t)}var xo=class extends yo{level=0;set(e,t,n,r){let i,a=mo(e,this.entries);return i=+!!ho(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=So(this.entries,t,n,...r);return e.newDataNodeImpl(i)}del(e,t){let n=mo(e,this.entries);return ho(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 So(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 Co=class e extends yo{level;constructor(e,t,n,r){super(e,t,r),this.level=n}async set(e,t,n,r){let i=mo(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=ko(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=qr((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=qr(n.entries,c.entries),o=t,s=2}else a=n.entries,o=t,s=1;let c=Eo(a,e=>e[2],e.minSize-e.chunkHeaderSize,e.maxSize-e.chunkHeaderSize),l=[];for(let t of c){let n=ko(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=So(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=So(this.entries,t,1,n);return e.newInternalNodeImpl(r,this.level)}async del(e,t){let n=mo(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=So(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=ko(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([],Ni(),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,Ni(),i-1,!0)}A(i===1);let o=[];for(let e of a)o.push(...e.entries);return new xo(o,Ni(),!0)}};function wo(e,t,n,r){return n===0?new xo(e,t,r):new Co(e,t,n,r)}function To(e){return e.level===0}function Eo(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 Do=fo(0,[],7),Oo=new xo([],F,!1);function ko(e,t){let n=e.maxKey(),r=e.hash;return[n,r,t(n,r)]}var Ao=-1,jo=0,Mo=1,No=2,Po=3,Fo=0,Io=1;function*Lo(e,t){let n=0,r=0,i;function a(e,t){e[Po]===Ao&&(e[Po]=t)}function o(){return[n,0,0,Ao]}for(;n<e.length&&r<t.length;)e[n][Fo]===t[r][Fo]?(Pr(e[n][Io],t[r][Io])?i&&=(a(i,0),yield i,void 0):(i||=o(),i[No]++,i[Mo]++,a(i,r)),n++,r++):e[n][Fo]<t[r][Fo]?(i||=o(),i[Mo]++,n++):(i||=o(),i[No]++,a(i,r),r++);r<t.length&&(i||=o(),i[No]+=t.length-r,a(i,r)),n<e.length&&(i||=o(),i[Mo]+=e.length-n),i&&(a(i,0),yield i)}var Ro=11,zo=class{p=new Map;l;u;rootHash;getEntrySize;chunkHeaderSize;constructor(e,t,n=F,r=ii,i=Ro){this.l=e,this.u=t,this.rootHash=n,this.getEntrySize=r,this.chunkHeaderSize=i}async getNode(e){if(e===F)return Oo;let t=this.p.get(e);if(t)return t;let n=go((await this.l.mustGetChunk(e)).data,this.u,this.getEntrySize),r=wo(n[uo],e,n[lo],!1);return this.p.set(e,r),r}async get(e){let t=await po(e,this.rootHash,this,this.rootHash),n=mo(e,t.entries);if(ho(n,t.entries,e))return t.entries[n][1]}async has(e){let t=await po(e,this.rootHash,this,this.rootHash);return ho(mo(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 Ho(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]:go((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*Bo(n,t,e,this)}};async function*Bo(e,t,n,r){if(e.level>t.level){yield*Bo(await e.getCompositeChildren(0,e.entries.length,n),t,n,r);return}if(t.level>e.level){yield*Bo(e,await t.getCompositeChildren(0,t.entries.length,r),n,r);return}if(To(e)&&To(t)){yield*Vo(e.entries,t.entries);return}let i=Lo(e.entries,t.entries);for(let a of i){let[i,o]=await Promise.all([e.getCompositeChildren(a[jo],a[Mo],n),t.getCompositeChildren(a[Po],a[No],r)]);yield*Bo(i,o,n,r)}}function*Vo(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?(Pr(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*Ho(e,t,n,r,i){if(n===F)return;let a=await i(n),o=a[uo],s=0;if(r&&(s=mo(r,o)),a[lo]>0)for(;s<o.length;s++)yield*Ho(e,t,o[s][1],r,i),r=``;else for(;s<o.length;s++){let n=t();if(e!==n){yield*Ho(n,t,n,o[s][0],i);return}yield o[s]}}async function Uo(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 Wo=class{meta;map;constructor(e,t){this.meta=e,this.map=t}},Go=class extends Wo{flush(){return this.map.flush()}clear(){return this.map.clear()}};async function Ko(e,t,n,r,i,a,o){try{for(let e of qo(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 qo(e,t,n,r){let i=$o(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(Xo([t,e]));else throw Error(`Unsupported target type`);return o}var Jo=`\0`,Yo=`\0`;function Xo(e){let t=e[0],n=e[1];if(t.includes(`\0`))throw Error(`Secondary key cannot contain null byte`);return Jo+t+Yo+n}function Zo(e,t){let n=Xo([e,t||``]);return t===void 0?n.slice(0,n.length-1):n}function Qo(e){if(e[0]!==Jo)throw Error(`Invalid version`);let t=Jo.length,n=Yo.length,r=e.indexOf(Yo,t);if(r===-1)throw Error(`Invalid formatting`);return[e.slice(t,r),e.slice(r+n)]}function $o(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 es=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 ts(e,t){return ns(I,e,t)}async function ns(e,t,n){return rs(await ya(e,t),t,n)}function rs(e,t,n){let r=is(e,t,n);return new es(t,new zo(t,n,e.valueHash),r)}function is(e,t,n){let r=new Map;for(let i of e.indexes)r.set(i.definition.name,new Wo(i,new zo(t,n,i.valueHash)));return r}async function as(e){let t=[];for await(let n of e)t.push(n);return t}function os(e){return e.indexName!==void 0}function ss(e){return typeof e==`string`?[e]:e}function cs(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 ls=class extends Error{constructor(){super(`Transaction is closed`)}};function us(e){if(e.closed)throw new ls}function ds(e){return e.closed?Promise.reject(new ls):void 0}var fs=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 ps(this.#i(e=>e[1]))}keys(){return new ps(this.#i(e=>e[0]))}entries(){return new ps(this.#i(e=>[e[0],e[1]]))}toArray(){return this.values().toArray()}#i(e){return ms(e,this.#e,this.#t,this.#n,this.#r)}},ps=class{#e;constructor(e){this.#e=e}next(){return this.#e.next()}[Symbol.asyncIterator](){return this.#e[Symbol.asyncIterator]()}toArray(){return as(this.#e)}};async function*ms(e,t,n,r,i){us(r);let{limit:a=1/0}=n,{prefix:o=``}=n,s=n.start?.exclusive,c=os(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(hs(t,n.start.key))continue}else if(gs(t,n.start.key))continue}if(yield e(r),--a===0){c||i(t);return}}}function hs(e,t){let[n,r]=ss(t),[i,a]=ss(e);return i===n?r===void 0||a===r:!1}function gs(e,t){return e===t}function _s(e){let{prefix:t,start:n}=e,r=``;if(t!==void 0&&(r=Zo(t,void 0)),!n)return r;let{key:i}=n,[a,o]=ss(i),s=Zo(a,o);return io(s,r)?s:r}var vs=0,ys=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`,vs++),this.environment=`client`,this.location=`client`}get(e){return ds(this.dbtx)||this.dbtx.get(e)}async has(e){return us(this.dbtx),this.dbtx.has(e)}async isEmpty(){return us(this.dbtx),this.dbtx.isEmpty()}scan(e){return xs(e,this.dbtx,bs)}};function bs(e){}function xs(e,t,n){return Es(ws(t,e),e??{},t,n)}var Ss=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:cs(e),inclusiveLimitKey:void 0};return this.#t.push(t),xs(e,this.#n.dbtx,e=>{t.inclusiveLimitKey=e})}get keys(){return this.#e}get scans(){return this.#t}},Cs=class extends ys{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){us(this.dbtx),await this.dbtx.put(this.d,e,oi(t))}del(e){return ds(this.dbtx)??this.dbtx.del(this.d,e)}};function ws(e,t){return t&&os(t)?Ds(e,t):e.map.scan(Ts(t))}function Ts(e){if(!e)return``;let{prefix:t=``,start:n}=e;return n&&io(n.key,t)?n.key:t}function Es(e,t,n,r){return new fs(e,t,n,r)}async function*Ds(e,t){let n=e.getMapForIndex(t.indexName);for await(let e of n.scan(_s(t)))yield[Qo(e[0]),e[1]]}function Os(e,t){return as(t.diff(e))}var ks=class extends zo{#e=new Lt;#t=new Map;minSize;maxSize;constructor(e,t,n=F,r=8192,i=16384,a=ii,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=Ni(),this.#n(e)}newInternalNodeImpl(e,t){let n=new Co(e,Ni(),t,!0);return this.#n(n),n}newDataNodeImpl(e){let t=new xo(e,Ni(),!0);return this.#n(t),t}newNodeImpl(e,t){let n=wo(e,Ni(),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=Eo(i.entries,e=>e[2],this.minSize-e,this.maxSize-e),{level:n}=i,r=t.map(e=>ko(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(Do,[]);return await e.putChunk(t),t.hash}let t=[],n=As(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 As(e,t,n,r,i){let a=r.get(e);if(a===void 0)return e;if(To(a)){let e=n(bo(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=As(c,t,n,r,i);l!==c&&(s[e]=[a[0],l,a[2]]),o.push(l)}let c=n(bo(a,i),pi(o));return t.push(c),c.hash}function js(e){let t;return()=>(t===void 0&&(t=e()),t)}var Ms=class extends Map{set(e,t){return t.length===0?this:super.set(e,t)}};async function Ns(e,t,n,r,i){let a=new Ms;if(!r.shouldComputeDiffs())return a;let o=await Os(new zo(n,i,e.valueHash),new zo(n,i,t.valueHash));return a.set(``,o),await Ps(e,t,n,a,r,i),a}async function Ps(e,t,n,r,i,a){let o=is(e,n,a),s=is(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 Os(t.map,n.map);s.delete(e),r.set(e,i)}else{let n=await Uo(t.map,`del`);r.set(e,n)}}for(let[e,t]of s){if(!i.shouldComputeDiffsForIndex(e))continue;let n=await Uo(t.map,`add`);r.set(e,n)}}var Fs=class extends es{#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=js(()=>this.map.get(t));await zs(e,this.indexes,t,r,n),await this.map.put(t,n)}getMutationID(){return ca(this.#r,this.#e,this.#n)}async del(e,t){if(this.#n.type===1)throw Error(`Not allowed`);let n=js(()=>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=Ra(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=za(this.#e.createChunk,i,await pa(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=Ba(this.#e.createChunk,i,a,o,e,t);break}case 5:{A(this.#i>5);let{basisHash:i,lastMutationIDs:a,cookieJSON:o}=r;n=Va(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=Wa(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 Ms;if(!e.shouldComputeDiffs())return t;let n=[];this.#t&&(n=await Os(new zo(this.#e,this.#i,this.#t.valueHash),this.map)),t.set(``,n);let r;r=this.#t?is(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?Os(a.map,i.map):Uo(i.map,`add`));t.set(n,o)}for(let[n,i]of r)if(!this.indexes.has(n)&&e.shouldComputeDiffsForIndex(n)){let e=await Uo(i.map,`del`);t.set(n,e)}return t}close(){this.#e.release()}};async function Is(e,t,n,r,i,a,o,s){let c=await L(e,i),l=new ks(i,s,c.valueHash),u=await c.getNextMutationID(o,i),d=Bs(c,i,s);return new Fs(i,l,c,s>=5?{type:4,basisHash:e,baseSnapshotHash:await pa(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 Ls(e,t,n,r,i,a,o){A(o<=4);let s=await L(e,r);return new Fs(r,new ks(r,o,s.valueHash),s,{basisHash:e,type:3,lastMutationID:t,cookieJSON:n},i,a,o)}async function Rs(e,t,n,r,i,a){let o=await L(e,r);return new Fs(r,new ks(r,a,o.valueHash),o,{basisHash:e,type:5,lastMutationIDs:t,cookieJSON:n},Bs(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(Ko(e,o.map,1,n,t,o.meta.definition.jsonPointer,o.meta.definition.allowEmpty??!1)),i!==void 0&&a.push(Ko(e,o.map,0,n,i,o.meta.definition.jsonPointer,o.meta.definition.allowEmpty??!1))}}await Promise.all(a)}function Bs(e,t,n){let r=new Map;for(let i of e.indexes)r.set(i.definition.name,new Go(i,new ks(t,n,i.valueHash)));return r}async function Vs(e,t,n,r,i,a,o){let s=new ks(t,o);for await(let t of n.scan(r)){let n=t[0];if(!n.startsWith(r))break;await Ko(e,s,0,n,t[1],i,a)}return s}async function Hs(e,t,n,r,i,a,o){let s=e.meta,c=s.mutatorName;Ca(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&&Sa(s);let p=await Is(n,c,d,e.chunk.hash,t,s.timestamp,a,o);return await u(new Cs(a,await p.getMutationID(),`rebase`,p,i),d),p}async function Us(e,t,n,r,i,a,o){return(await Hs(e,t,n,r,i,a,o)).putCommit()}async function Ws(e,t,n,r,i,a,o,s){return(await Hs(e,t,n,i,a,o,s)).commit(r)}function Gs(e,t){return typeof e==`object`&&!!e&&e.error===t}function Ks(e){return typeof e.error==`string`}function qs(e){return Gs(e,`ClientStateNotFound`)}function Js(e){if(!Gs(e,`VersionNotSupported`))return!1;let{versionType:t}=e;switch(t){case void 0:case`pull`:case`push`:case`schema`:return!0}return!1}function Ys(e){A(Js(e))}async function Xs(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 Zs(e){N(e),M(e.httpStatusCode),j(e.errorMessage)}function Qs(e){ar(e);for(let t of e)$s(t)}function $s(e){switch(N(e),e.op){case`put`:j(e.key),Fr(e.value);break;case`update`:if(j(e.key),e.merge!==void 0&&Ir(e.merge),e.constrain!==void 0){ar(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 ec(e){async function t(t,n){let[r,i]=await Xs(e.pullURL,e.auth,n,t);return r?{response:await r.json(),httpRequestInfo:i}:{httpRequestInfo:i}}return tc.add(t),t}var tc=new WeakSet;function nc(e){return tc.has(e)}function rc(e){if(N(e),qs(e)||Js(e))return;let t=e;t.cookie!==void 0&&Fr(t.cookie),M(t.lastMutationID),Qs(t.patch)}function ic(e){if(N(e),qs(e)||Js(e))return;let t=e;t.cookie!==void 0&&Kr(t.cookie),ac(t.lastMutationIDChanges),Qs(t.patch)}function ac(e){N(e);for(let[t,n]of Object.entries(e))j(t),M(n)}function oc(e){N(e),Zs(e.httpRequestInfo),e.response!==void 0&&ic(e.response)}function sc(e){N(e),Zs(e.httpRequestInfo),e.response!==void 0&&rc(e.response)}function cc(e){async function t(t,n){let[r,i]=await Xs(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(qs(o)||Js(o))&&(a.response=o),a}return lc.add(t),t}var lc=new WeakSet;function uc(e){return lc.has(e)}function dc(e=`info`,t=[Mt],n){return new Nt(e,n,t.length===1?t[0]:new At(t))}var fc=Ai(Oi({prefix:P.string().optional(),jsonPointer:P.string(),allowEmpty:P.boolean().optional()}));function pc(e,t){return e.jsonPointer===t.jsonPointer&&(e.allowEmpty??!1)===(t.allowEmpty??!1)&&(e.prefix??``)===(t.prefix??``)}function mc(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||!pc(r,e))return!1}return!0}var hc=Oi({headHash:Ri,mutatorNames:ki(P.string()),indexes:fc,mutationIDs:Ai(P.number()),lastServerAckdMutationIDs:P.record(P.number()),disabled:P.boolean()}),gc=`client-groups`;function _c(e){Ti(e,hc)}function vc(e){N(e);let t=new Map;for(let[n,r]of Object.entries(e))r!==void 0&&(_c(r),t.set(n,r));return t}function yc(e,t){let n={};for(let[r,i]of e.entries())t.assertValidHash(i.headHash),n[r]={...i,mutatorNames:[...i.mutatorNames.values()]};return oi(n)}async function bc(e,t){return vc((await t.getChunk(e))?.data)}async function xc(e){let t=await e.getHead(gc);return t?bc(t,e):new Map}async function Sc(e,t){let n=await xc(t);for(let[t,r]of e)wc(r,n.get(t));return Tc(e,t)}async function Cc(e,t,n){let r=await xc(n);wc(t,r.get(e));let i=new Map(r);return i.set(e,t),Tc(i,n)}function wc(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(mc(t.indexes,e.indexes),`A client group's index definitions must never change.`),A(Ec(n,t.mutatorNames),`A client group's mutatorNames must never change.`))}async function Tc(e,t){let n=yc(e,t),r=new Set;for(let t of e.values())r.add(t.headHash);let i=t.createChunk(n,pi(r));return await t.putChunk(i),await t.setHead(gc,i.hash),e}function Ec(e,t){if(t.length!==e.size)return!1;for(let n of t)if(!e.has(n))return!1;return!0}async function Dc(e,t){return(await xc(t)).get(e)}function Oc(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 kc(e,t){let n=await Dc(e,t);n&&await Cc(e,{...n,disabled:!0},t)}var Ac=P.string(),jc=P.string();function R(e,t){return Nc(e.read(),t)}function Mc(e,t){return Nc(e.write(),t)}function z(e,t){return Nc(e.write(),async e=>{let n=await t(e);return await e.commit(),n})}async function Nc(e,t){let n=await e;try{return await t(n)}finally{n.release()}}function Pc(){let e=vi(),t=vi();return(e<<64n|t).toString(32).slice(-18).padStart(18,`0`)}var Fc=Oi({heartbeatTimestampMs:P.number(),headHash:Ri,mutationID:P.number(),lastServerAckdMutationID:P.number()}),Ic=Oi({heartbeatTimestampMs:P.number(),headHash:Ri,tempRefreshHash:Ri.nullable(),clientGroupID:Ac}),Lc=Oi({heartbeatTimestampMs:P.number(),refreshHashes:ki(Ri),persistHash:Ri.nullable(),clientGroupID:Ac});function Rc(e){return e.refreshHashes!==void 0}function zc(e){return e.clientGroupID!==void 0}var Bc=`clients`,Vc=P.union(Fc,Ic,Lc);function Hc(e){Ti(e,Vc)}function Uc(e){Ti(e,Fc)}function Wc(e){Ti(e,Lc)}function Gc(e){N(e);let t=new Map;for(let n in e)if(Nr(e,n)){let r=e[n];r!==void 0&&(Hc(r),t.set(n,r))}return t}function Kc(e,t){for(let n of e.values())Rc(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 oi(Object.fromEntries(e))}async function qc(e){return Jc(await e.getHead(Bc),e)}async function Jc(e,t){return e?Gc((await t.getChunk(e))?.data):new Map}var Yc=class extends Error{name=`ClientStateNotFoundError`;id;constructor(e){super(`Client state not found, id: ${e}`),this.id=e}};async function Xc(e,t){if(!await Zc(e,t))throw new Yc(e)}async function Zc(e,t){return!!await Qc(e,t)}async function Qc(e,t){return(await qc(t)).get(e)}async function $c(e,t){let n=await Qc(e,t);if(!n)throw new Yc(e);return n}function el(e,t,n,r,i,a,o){return Mc(n,async n=>{async function s(t,a,o,s){let l=Ua(t,{},a,o,s),u=n.createChunk(l,qa(l)),d=Pc(),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),ul(p,n),Cc(d,m,n)]),await n.commit(),[f,u.hash,p,!0]}let c=await qc(n),l=await al(n,r,i);if(l.type===il){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 ul(a,n),await n.commit(),[i,r,a,!1]}if(!o||l.type===nl){let e=n.createChunk(Do,[]);await n.putChunk(e);let t=[];for(let[n,r]of Object.entries(i)){let i=Fa(n,r);t.push({definition:i,valueHash:e.hash})}return s(null,null,e.hash,t)}A(l.type===rl);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=tl(p,c);if(l)d.push({definition:c,valueHash:l.valueHash});else{let e=await Vs(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 tl(e,t){return e.find(e=>Na(e.definition,t))}var nl=0,rl=1,il=2;async function al(e,t,n){let r,i,a=new Set(t),o=await xc(e);for(let[t,s]of o){if(!s.disabled&&Ec(a,s.mutatorNames)&&mc(n,s.indexes))return{type:il,clientGroupID:t,headHash:s.headHash};let o=await ma(s.headHash,e);ka(o);let{cookieJSON:c}=o.meta;(r===void 0||Wr(c,r)>0)&&(r=c,i=o)}return i?{type:rl,snapshot:i}:{type:nl}}function ol(e){let t=new Set;for(let n of e.values())if(Rc(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 pi(t)}async function sl(e,t){let n=await cl(e,t);if(n)return Dc(n,t)}async function cl(e,t){let n=await Qc(e,t);if(!(!n||!zc(n)))return n.clientGroupID}async function ll(e,t,n){let r=await qc(n);return ul(new Map(r).set(e,t),n)}async function ul(e,t){let n=Kc(e,t),r=t.createChunk(n,ol(e));return await t.putChunk(r),await t.setHead(Bc,r.hash),r.hash}var dl=typeof navigator<`u`?navigator:void 0,fl=Symbol(),pl=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 fl:return Yr;default:return Jr}}async get(e){let t=this.r.get(e);switch(t){case fl:return;case void 0:return fi(await this.#e.get(e));default:return t}}put(e,t){return this.r.set(e,oi(t)),Xr}del(e){return this.r.set(e,fl),Xr}release(){this.#e.release()}get closed(){return this.#e.closed}},ml={durability:`relaxed`},hl=`chunks`,gl=class{#e;#t=!1;#n=!1;constructor(e){this.#e=Sl(e)}read(){return this.#r(bl)}write(){return this.#r(yl)}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;cr(t),t.abort(),this.#n=!0,r(new Cl(`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 Cl(`Replicache IndexedDB ${n.name} missing object store. Deleting db.`)}throw r}}},_l=class{#e;#t=!1;constructor(e){this.#e=e}has(e){return new Promise((t,n)=>{let r=xl(this.#e).count(e);r.onsuccess=()=>t(r.result>0),r.onerror=()=>n(r.error)})}get(e){return new Promise((t,n)=>{let r=xl(this.#e).get(e);r.onsuccess=()=>t(fi(r.result)),r.onerror=()=>n(r.error)})}release(){this.#t=!0}get closed(){return this.#t}},vl=class extends pl{#e;#t=!1;constructor(e){super(new _l(e)),this.#e=e}commit(){return this.r.size===0?Xr:new Promise((e,t)=>{let n=this.#e,r=xl(n);for(let[e,t]of this.r)t===fl?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 yl(e){return new vl(e.transaction(hl,`readwrite`,ml))}function bl(e){return new _l(e.transaction(hl,`readonly`))}function xl(e){return e.objectStore(hl)}function Sl(e){return new Promise((t,n)=>{let r=indexedDB.open(e);r.onupgradeneeded=()=>{r.result.createObjectStore(hl)},r.onsuccess=()=>{let e=r.result;e.onversionchange=()=>e.close(),t(e)},r.onerror=()=>n(r.error)})}var Cl=class extends Error{name=`IDBNotFoundError`},wl=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))}},Tl=class extends pl{#e;constructor(e,t){super(new wl(e,t)),this.#e=e}commit(){return this.r.forEach((e,t)=>{e===fl?this.#e.delete(t):this.#e.set(t,e)}),this.r.clear(),this.release(),Xr}},El=new Map;function Dl(e){return El.delete(e),Xr}var Ol=class{#e;#t;#n=!1;constructor(e){let t=El.get(e),n,r;t?{lock:n,map:r}=t:(n=new Rt,r=new Map,El.set(e,{lock:n,map:r})),this.#t=n,this.#e=r}async read(){let e=await this.#t.read();return new wl(this.#e,e)}async write(){let e=await this.#t.write();return new Tl(this.#e,e)}close(){return this.#n=!0,Xr}get closed(){return this.#n}},kl=class{#e;#t;#n;constructor(e,t){this.#e=e,this.#t=t,this.#n=new gl(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(Al(t))return this.#n instanceof gl&&(this.#e.info?.(`Switching to MemStore because of Firefox private browsing error`),this.#n=new Ol(this.#t)),e(this.#n);throw t}}close(){return this.#n.close()}get closed(){return this.#n.closed}};function Al(e){return jl()&&e instanceof DOMException&&e.name===`InvalidStateError`&&e.message===`A mutation operation was attempted on a database that did not allow mutations.`}function jl(){return dl?.userAgent.includes(`Firefox`)??!1}function Ml(e,t){return jl()?new kl(e,t):new gl(t)}function Nl(e){if(!jl())return Pl(e);try{return Pl(e)}catch(t){if(Al(t))return Dl(e)}return Xr}function Pl(e){return new Promise((t,n)=>{let r=indexedDB.deleteDatabase(e);r.onsuccess=()=>t(),r.onerror=()=>n(r.error)})}var Fl=e=>new cf(e),Il=401;function Ll(e,t){return Rl(e,t,7)}function Rl(e,t,n){let r=`rep:${e}:${n}`;return t?`${r}:${t}`:r}var zl=class{#e;constructor(e){this.#e=Fl(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 Ll(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()}},Bl=class extends Error{};function Vl(e){return new Ol(e)}function Hl(e,t){switch(t){case`idb`:case void 0:return{create:t=>Ml(e,t),drop:Nl};case`mem`:return{create:Vl,drop:e=>Dl(e)};default:return t}}function Ul(e){return e instanceof Error?e:Error(String(e))}async function Wl(e,t,n){for(let r of n)switch(r.op){case`put`:await t.put(e,r.key,oi(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,oi(Object.fromEntries(i)));break}case`del`:await t.del(e,r.key);break;case`clear`:await t.clear();break}}var Gl=class extends Error{name=`PullError`;causedBy;constructor(e){super(`Failed to pull`),this.causedBy=e}},Kl=`sync`,ql=0,Jl=1;function Yl(e){return e.pullVersion===Jl}async function Xl(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 ma(n,e),i=r.meta.cookieJSON;return[await r.getMutationID(t,e),i]}),{response:d,httpRequestInfo:f}=await Ql(s,r,{profileID:e,clientID:t,cookie:u,lastMutationID:l,pullVersion:ql,schemaVersion:n},i);if(!d)return{httpRequestInfo:f,syncHead:F};if(!c||Ks(d))return{httpRequestInfo:f,pullResponse:d,syncHead:F};let p=await $l(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 Zl(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 ma(t,e)).meta;return Da(n),n.cookieJSON}),{response:d,httpRequestInfo:f}=await Ql(c,i,{profileID:e,clientGroupID:n,cookie:u,pullVersion:Jl,schemaVersion:r},a);if(!d)return{httpRequestInfo:f,syncHead:F};if(!l||Ks(d))return{httpRequestInfo:f,pullResponse:d,syncHead:F};let p=await tu(c,o,u,d,t,s);return{httpRequestInfo:f,pullResponse:d,syncHead:p.type===0?p.syncHead:F}}async function Ql(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 Gl(Ul(e))}try{return Yl(n)?oc(a):sc(a),a}catch(e){throw new Bl(`Invalid puller result`,Ul(e))}}function $l(e,t,n,r,i,a){return Mc(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 ma(s,o),[l,u]=ga(c,i);if(!Pr(n,u))return{type:2};if(r.lastMutationID<l)throw Error(eu(`lastMutationID`,String(r.lastMutationID),String(l)));let d=oi(r.cookie??null);if(Pr(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 va(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 Ls(c.chunk.hash,r.lastMutationID,d,t,Bs(p,t,a),i,a);await Wl(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(Kl)}})}function eu(e,t,n){return`Received ${e} ${t} is < than last snapshot ${e} ${n}; ignoring client view`}function tu(e,t,n,r,i,a){return Mc(t,async t=>{let o=t,s=await o.getHead(I);if(s===void 0)throw Error(`Main head disappeared`);let c=await ma(s,o),l=c.meta;Da(l);let u=l.cookieJSON;if(!Pr(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(eu(`${e} lastMutationID`,String(t),String(n)))}let d=oi(r.cookie);if(Wr(d,u)<0)throw Error(eu(`cookie`,JSON.stringify(d),JSON.stringify(u)));if(Pr(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 Rs(c.chunk.hash,{...l.lastMutationIDs,...r.lastMutationIDChanges},d,t,i,a);return await Wl(e,f,r.patch),{type:0,syncHead:await f.commit(Kl)}})}function nu(e,t,n,r,i,a){return Mc(e,async e=>{let o=e,s=await o.getHead(Kl);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 ma(s,o),l=await o.getHead(I);if(l===void 0)throw Error(`Missing main head`);let u=await ma(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 la(l,o);for(let e of h){let t=r;na(e)&&(t=e.meta.clientID),await e.getMutationID(t,o)>await p.getMutationID(t,o)&&m.push(e)}m.reverse();let g=new Ms;if(m.length>0)return{syncHead:s,replayMutations:m,diffs:g};let _=await L(l,o);if(i.shouldComputeDiffs()){let e=await Os(new zo(o,a,_.valueHash),new zo(o,a,p.valueHash));g.set(``,e),await Ps(_,p,o,g,i,a)}if(await Promise.all([e.setHead(I,s),e.removeHead(Kl)]),await e.commit(),t.debug){let[e,n]=ga(u,r),[i,a]=ga(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 ru=[],iu=P.unknown().chain(e=>{if(jr)return Zt(e);let t=zr(e,ru)?Zt(e):Qt({message:`Not a JSON value`,path:ru.slice()});return ru.length=0,t});P.unknown().chain(e=>{if(jr)return Zt(e);let t=Br(e,ru)?Zt(e):Qt({message:`Not a JSON object`,path:ru.slice()});return ru.length=0,t});function au(e){N(e),Zs(e.httpRequestInfo),e.response!==void 0&&ou(e.response)}function ou(e){qs(e)||Ys(e)}var su=class extends Error{name=`PushError`;causedBy;constructor(e){super(`Failed to push`),this.causedBy=e}},cu=0,lu=1,uu=Oi({id:P.number(),name:P.string(),args:iu,timestamp:P.number()}),du=Oi({id:P.number(),name:P.string(),args:iu,timestamp:P.number(),clientID:jc});P.object({pushVersion:P.literal(0),schemaVersion:P.string(),profileID:P.string(),clientID:jc,mutations:P.array(uu)}),P.object({pushVersion:P.literal(1),schemaVersion:P.string(),profileID:P.string(),clientGroupID:Ac,mutations:P.array(du)});function fu(e){return{id:e.mutationID,name:e.mutatorName,args:e.mutatorArgsJSON,timestamp:e.timestamp}}function pu(e){return{id:e.mutationID,name:e.mutatorName,args:e.mutatorArgsJSON,timestamp:e.timestamp,clientID:e.clientID}}async function mu(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 la(t,e)});if(l.length===0)return;l.reverse();let u;if(c===lu){let e=[];for(let t of l)if(na(t))e.push(pu(t.meta));else throw Error(`Internal non local pending commit`);A(i),u={profileID:r,clientGroupID:i,mutations:e,pushVersion:lu,schemaVersion:s}}else{A(c===cu);let e=[];for(let t of l)if(ta(t))e.push(fu(t.meta));else throw Error(`Internal non local pending commit`);u={profileID:r,clientID:a,mutations:e,pushVersion:cu,schemaVersion:s}}n.debug?.(`Starting push...`);let d=Date.now(),f=await hu(o,u,e);return n.debug?.(`...Push complete in `,Date.now()-d,`ms`),f}async function hu(e,t,n){let r;try{r=await e(t,n)}catch(e){throw new su(Ul(e))}try{return au(r),r}catch(e){throw new Bl(`Invalid pusher result`,Ul(e))}}var gu=10*2**20,_u=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 xu(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 bu(e,this.#t,void 0,a)}}}catch(e){vu(e,o,u,l)}finally{o.debug?.(`End:`,u),this.#e=!1}return!0}};function vu(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},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:
|
|
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 yu(e,t,n,r,i,a){A(r.replicacheFormatVersion===4),Uc(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 Wi(n,gu,_i,Li);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)=>{lr(m);let a=await mu(e,m,n,await o.profileID,void 0,t,i,r.schemaVersion,cu);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 Xl(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&&_&&(qs(_)?s.debug?.(`Client ${f} cannot recover mutations for client ${t}. The client no longer exists on the server.`):Js(_)?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 qc(e),r=n.get(t);if(!r)return n;Uc(r);let i=async t=>(await ul(t,e),t);if(qs(_)||Js(_)){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){vu(e,s,p,o)}finally{await m.close(),s.debug?.(`End:`,p)}}async function bu(e,t,n,r){let i=new Qi(r(e.name),Ni,Li);try{await xu(e,t,i,n)}finally{await i.close()}}function xu(e,t,n,r){return e.replicacheFormatVersion>=5?Cu(e,t,n):Su(e,t,n,r)}async function Su(e,t,n,r){let{delegate:i,lc:a}=t,o=`Recovering mutations from db ${e.name}.`;a.debug?.(`Start:`,o);try{let s=co(e.replicacheFormatVersion),c=r||await R(n,e=>qc(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 yu(d,u,n,e,t,s),r))break}c=r}}catch(e){vu(e,a,o,i)}a.debug?.(`End:`,o)}async function Cu(e,t,n){let{delegate:r,lc:i}=t,a=`Recovering mutations from db ${e.name}.`;i.debug?.(`Start:`,a);try{let o=co(e.replicacheFormatVersion),s=await R(n,e=>xc(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 Eu(d,u,n,e,t,o),l))break}s=l}}catch(e){vu(e,i,a,r)}i.debug?.(`End:`,a)}function wu(e){return qs(e)||Js(e)}async function Tu(e,t,n,r,i){qs(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.`):Js(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=>kc(n,e))}async function Eu(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(lr(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 Wi(n,gu,_i,Li);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 mu(e,_,n,await o.profileID,t,m,i,r.schemaVersion,lu);return{result:a,httpRequestInfo:a?.httpRequestInfo}},f,s);if(!e)return!1;let a=e.response;return wu(a)?(await Tu(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 Zl(await o.profileID,m,t,r.schemaVersion,h,e,_,a,n,!1);return{result:i,httpRequestInfo:i.httpRequestInfo}},g,s),{pullResponse:i}=e;return wu(i)?(await Tu(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 xc(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 Sc(o,e),o})}catch(e){vu(e,s,g,o)}finally{await _.close(),s.debug?.(`End:`,g)}}var Du=class{name;onmessage=null;onmessageerror=null;constructor(e){this.name=e}addEventListener(){}removeEventListener(){}dispatchEvent(){return!1}close(){}postMessage(){}},Ou=typeof BroadcastChannel>`u`?Du:BroadcastChannel;function ku(e){return`replicache-new-client-group:${e}`}function Au(e){return`replicache-new-client-group-v1:${e}`}function ju(e){return typeof e==`object`&&typeof e.clientGroupID==`string`&&typeof e.idbName==`string`}function Mu(e,t,n,r,i,a,o){if(n.aborted)return;let s=new Ou(Au(e));if(i){s.postMessage({clientGroupID:r,idbName:t});let n=new Ou(ku(e));n.postMessage([r]),n.close()}s.onmessage=async e=>{let{data:n}=e;if(ju(n)){let{clientGroupID:e,idbName:i}=n;if(e!==r){if(i===t)await R(o,async t=>await Dc(e,t)!==void 0)&&a();else{a();return}}}},n.addEventListener(`abort`,()=>s.close(),{once:!0})}function Nu(e){return`replicache-on-persist:${e}`}function Pu(e){N(e),j(e.clientGroupID),j(e.clientID)}function Fu(e,t,n){if(t.aborted)return()=>{};let r=new Ou(Nu(e));return r.onmessage=e=>{let{data:t}=e;Pu(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 Iu(e){return(await ua(await Ui(I,e),e)).map(e=>({id:e.meta.mutationID,name:e.meta.mutatorName,args:e.meta.mutatorArgsJSON,clientID:e.meta.clientID})).reverse()}function Lu(e,t,n,r,i){Ru(e,t,n,r,i)}async function Ru(e,t,n,r,i){if(!i.aborted){for(r=r.withContext(`bgIntervalProcess`,e),r.debug?.(`Starting`);!i.aborted;){try{await xr(n(),i)}catch(e){if(!(e instanceof nr))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,Bu=3e5,Vu;function Hu(e,t,n,r,i,a){Lu(`ClientGC`,()=>(Vu=Uu(e,t,n),Vu),()=>r,i,a)}function Uu(e,t,n){return z(t,async t=>{let r=Date.now(),i=await qc(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 ul(o,t),o})}var Wu=3e5,Gu;function Ku(e,t,n){Lu(`ClientGroupGC`,()=>(Gu=qu(e),Gu),()=>Wu,t,n)}function qu(e){return z(e,async e=>{let t=await qc(e),n=new Set;for(let e of t.values())Wc(e),n.add(e.clientGroupID);let r=new Map;for(let[t,i]of await xc(e))(n.has(t)||Oc(i))&&r.set(t,i);return await Sc(r,e),r})}var Ju=`replicache-dbs-v0`,Yu=``;function Xu(){return Yu+Ju}var Zu=`dbs`,Qu=`profileId`;function $u(e){N(e);for(let[t,n]of Object.entries(e))j(t),ed(n),A(t===n.name)}function ed(e){N(e),j(e.name),j(e.replicacheName),M(e.replicacheFormatVersion),j(e.schemaVersion),e.lastOpenedTimestampMS!==void 0&&M(e.lastOpenedTimestampMS)}var td=class{#e;constructor(e){this.#e=e(Xu())}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 nd(t),[e.name]:e};return await t.put(Zu,n),n})}clearDatabases(){return z(this.#e,e=>e.del(Zu))}deleteDatabases(e){return z(this.#e,async t=>{let n={...await nd(t)};for(let t of e)delete n[t];await t.put(Zu,n)})}getDatabases(){return R(this.#e,nd)}close(){return this.#e.close()}getProfileID(){return z(this.#e,async e=>{let t=await e.get(Qu);return t===void 0&&(t=`p${Pc()}`,await e.put(Qu,t)),j(t),t})}};async function nd(e){let t=await e.get(Zu);return t||=oi({}),$u(t),t}var rd=432e5,id=2592e6,ad=3e5;function od(e,t,n,r,i,a,o,s){let c=!0;Lu(`CollectIDBDatabases`,async()=>{await sd(e,Date.now(),i,a,t)},()=>c?(c=!1,r):n,o,s)}async function sd(e,t,n,r,i,a=ud){let o=await e.getDatabases(),s=Object.values(o),{errors:c}=await ld(e,(await Promise.all(s.map(async e=>[e.name,await dd(e,t,n,r,a)]))).filter(e=>e[1]).map(e=>e[0]),i);if(c.length)throw c[0]}async function cd(e,t,n){await n(e),await t.deleteDatabases([e])}async function ld(e,t,n){let r=await Promise.allSettled(t.map(async t=>(await cd(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 ud(e){return new Qi(new gl(e),Ni,Li)}async function dd(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 pd(i(e.name)))}let a=i(e.name),o=await R(a,qc);return await a.close(),fd(o,t,n)}function fd(e,t,n){for(let r of e.values())if(t-r.heartbeatTimestampMs<n)return!1;return!0}async function pd(e){let t=await R(e,xc);for(let e of t.values())if(Oc(e))return!0;return!1}var md=6e4,hd;function gd(e,t,n,r,i,a){Lu(`Heartbeat`,async()=>{hd=_d(e,t);try{return await hd}catch(e){if(e instanceof Yc){n();return}throw e}},()=>r,i,a)}function _d(e,t){return z(t,async t=>{let n=await qc(t),r=n.get(e);if(!r)throw new Yc(e);let i={...r,heartbeatTimestampMs:Date.now()},a=new Map(n).set(e,i);return await ul(a,t),a})}var vd=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)))}},yd=class extends vd{#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):Xr}visitChunk(e){return this.#e.set(e.hash,e),super.visitChunk(e)}};async function bd(e,t,n,r,i,a,o,s=()=>Promise.resolve()){if(a())return;let[c,l,u]=await R(r,async e=>{await Xc(t,e);let n=await cl(t,e);A(n,`No main client group for clientID: ${t}`);let[,r]=await xd(e,n),i=await r.getMutationID(t,e),a=await ha(r,e);return ka(a),[i,a,n]});if(a())return;let[d,f,p]=await R(n,async e=>{let n=await ya(I,e),r=await da(n,{[t]:c||0},e),i=await ha(n,e);ka(i);let a;if(_a(i,l)>0){await s();let t=i.chunk.hash,n=new yd(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 xd(n,u),s=a.chunk.hash,c={...r.mutationIDs},{lastServerAckdMutationIDs:l}=r;if(p){let u=await $c(t,n);Wc(u);let d=await ha(a,n);if(ka(d),_a(f,d)>0){m=!0,await Promise.all(Array.from(p.values(),e=>n.putChunk(e))),await ll(t,{...u,persistHash:f.chunk.hash},n),s=f.chunk.hash;let a=await ua(r.headHash,n);l=f.meta.lastMutationIDs,c={...l},s=await Sd(a,s,n,i,c,e,o)}}s=await Sd(d,s,n,i,c,e,o);let h={...r,headHash:s,mutationIDs:c,lastServerAckdMutationIDs:l};await Cc(u,h,n)}),p&&m&&await z(n,e=>e.chunksPersisted([...p.keys()]))}async function xd(e,t){let n=await Dc(t,e);return A(n,`No client group for clientGroupID: ${t}`),[n,await L(n.headHash,e)]}async function Sd(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 Us(c,n,t,r,a,l.clientID,o)).chunk.hash)}return t}var Cd=class extends vd{#e=new Map;#t=0;#n;#r;#i;constructor(e,t,n,r=ti){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)?Xr: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)}},wd=5*2**20,Td=300;async function Ed(e,t,n,r,i,a,o,s){if(o())return;let c=await R(t,e=>fa(I,e));ka(c);let l=await t.withSuspendedSourceCacheEvictsAndDeletes(async()=>{let l=await z(n,async e=>{let n=await sl(r,e);if(!n)throw new Yc(r);let i=n.headHash,a=await(await L(i,e)).getMutationID(r,e),o=await $c(r,e);Wc(o);let s=await ma(i,e);if(ka(s),Dd(c,s,i))return;let l=new Cd(e,t,wd);await l.visit(i);let{gatheredChunks:u}=l,d=new Set(o.refreshHashes);return d.add(i),await ll(r,{...o,refreshHashes:[...d]},e),[i,s,a,u,o.refreshHashes]});if(o()||!l||(await xr(Td),o()))return{type:`aborted`};let[u,d,f,p,m]=l;return z(t,async t=>{let n=await ya(I,t),o=await ha(n,t);if(ka(o),Dd(o,d,u))return{type:`aborted`,refreshHashesForRevert:m};let c=await da(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 Us(c[n],t,h,i,e,c[n].meta.clientID,s)).chunk.hash;let g=await Ns(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 ll(r,{...await $c(r,t),refreshHashes:e},t)});if(l.type===`aborted`){l.refreshHashesForRevert&&await u(l.refreshHashesForRevert);return}return await u([l.newPerdagClientHeadHash]),l.diffs}function Dd(e,t,n){let r=_a(e,t);return r>0||r===0&&n===t.chunk.hash}function Od(e){return new Promise(t=>{typeof requestIdleCallback==`function`?requestIdleCallback(()=>t(),{timeout:e}):setTimeout(()=>t(),e)})}var kd=class{#e;#t;#n;#r;#i;#a=void 0;#o=void 0;#s=Promise.resolve();#c=Promise.resolve();constructor(e,t,n,r,i=Od){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i,this.#r.addEventListener(`abort`,()=>{let e=new nr(`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 nr(`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=Ad(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 Ad(e,t){try{await xr(e,t)}catch(e){A(e instanceof nr)}}function jd(e,t,n){let r=setInterval(e,t);n.addEventListener(`abort`,()=>{clearInterval(r)})}var Md=new Set,Nd=Symbol(),Pd=class{#e;#t;#n=Nd;#r=Md;#i=[];onError;onDone;#a;constructor(e,t,n,r,i=Pr){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(Rd(this.#r,this.#i,t,n))return!0;return!1}updateDeps(e,t){this.#r=e,this.#i=t}onData(e){(this.#n===Nd||!this.#a(this.#n,e))&&(this.#n=e,this.#t(e))}},Fd=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=Wd(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=>Id(e,Qo)):r(void 0,this.#t,e=>e.key,e=>Id(e,e=>e))}matches(e){let t=e.get(this.#n??``);return t!==void 0&&Ud(t,this.#t,this.#n)}updateDeps(e,t){}};function Id(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 Ld=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=Hd(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 Ss(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 Rd(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(Bd(e,t,r.key))return!0;return!1}function Bd(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)||Vd(e,n))||o&&(s&&oo(n,o)||ao(n,o)||Vd(e,n)));if(!a&&!o&&!c)return!0;let[l,u]=Qo(n);return!(a&&!l.startsWith(a)||c&&(s&&oo(l,c)||ao(l,c))||o&&(s&&oo(u,o)||ao(u,o)))}function Vd(e,t){let{inclusiveLimitKey:n}=e;return e.options.limit!==void 0&&n!==void 0&&io(t,n)}function*Hd(e,t){for(let n of e)n.matches(t)&&(yield n)}function Ud(e,t,n){if(t===``)return!0;let r=n?e=>Qo(e.key)[0]:e=>e.key,i=Wd(e,t,r);return i<e.length&&r(e[i]).startsWith(t)}function Wd(e,t,n){return so(e.length,r=>Za(t,n(e[r])))}function Gd(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 Kd=``;function qd(){if(Kd===``){let e=new Uint8Array(4);Gd(e),Kd=Array.from(e,e=>e.toString(16)).join(``)}return Kd}var Jd=new Map;function Yd(e){let t=Jd.get(e);return t?(t++,Jd.set(e,t)):(Jd.set(e,0),t=0),`${e}-${qd()}-${t}`}var Xd=`15.3.0`,Zd=8,Qd=1e3,$d=1e3,ef=500,tf=500,nf=100*2**20,rf=3e5,af=()=>{},of={type:`NewClientGroup`},sf=(e,t)=>new Ld(e,t),cf=class{pullURL;pushURL;auth;name;subscriptions;#e;isClientGroupDisabled=!1;#t;lastMutationID=0;get idbName(){return Ll(this.name,this.schemaVersion)}schemaVersion;get#n(){return{name:this.idbName,replicacheName:this.name,replicacheFormatVersion:7,schemaVersion:this.schemaVersion}}#r=!1;#i=!0;#a=Pc();#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 kd(()=>this.persist(),Qd,ef,this.#_.signal);#C;#w=new kd(()=>this.refresh(),$d,tf,this.#_.signal);get requestOptions(){return this.#m}onSync=null;onClientStateNotFound=df;onUpdateNeeded=df;getAuth=null;onPushInvoked=()=>{};onBeginPull=()=>{};onRecoverMutations=e=>e;constructor(e,t={}){ff(e);let{name:n,logLevel:r=`info`,logSinks:i=[Mt],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=sf,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??ec(this),this.pusher=m??cc(this),this.#y=v,this.#b=y,this.#x=b,this.#g=dc(r,i,{name:n}),this.#g.debug?.(`Constructing Replicache`,{name:n,"replicache version":Xd}),this.subscriptions=ee(this.#W,this.#g);let te=Hl(this.#g,e.kvStore);this.#t=te;let ne=te.create(this.idbName);this.#h=new td(te.create),this.perdag=new Qi(ne,Ni,Li),this.memdag=new Wi(this.perdag,nf,Ni,Li);let re=O();this.#o=re.promise;let{minDelayMs:ie=Sr,maxDelayMs:ae=Cr}=f;this.#m={maxDelayMs:ae,minDelayMs:ie};let oe=fr(dr(),0,this.#_.signal);this.#f=new wr(this.#g.withContext(`PULL`),new vr(this,()=>this.#O()),oe),this.#p=new wr(this.#g.withContext(`PUSH`),new yr(this,()=>this.#N())),this.mutate=this.#K(d);let S=O();this.#s=S.promise;let se=O();this.#c=se.promise,this.#e=new _u({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=Fu(this.name,this.#_.signal,e=>{this.#B(e)}),this.#T(h,x,g,S.resolve,se.resolve,re.resolve)}async#T(e,t,n,r,i,a){let{clientID:o}=this;await lf.get(this.name),await this.#h.getProfileID().then(r),await this.#h.putDatabase(this.#n);let[s,c,l,u]=await el(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(af),this.push().catch(af));let{signal:d}=this.#_;gd(o,this.perdag,()=>{this.#I(o)},md,this.#g,d),Hu(o,this.perdag,n,Bu,this.#g,d),od(this.#h,this.#t.drop,rd,ad,id,2*n,this.#g,d),Ku(this.perdag,this.#g,d),Mu(this.name,this.idbName,d,s.clientGroupID,u,()=>{this.#R(of)},this.perdag),jd(()=>this.recoverMutations(),rf,d),this.recoverMutations(l),dr()?.addEventListener(`visibilitychange`,this.#E)}#E=async()=>{this.#r||dr()?.visibilityState===`visible`&&await this.#D()};async#D(){let{clientID:e}=this,t=await R(this.perdag,t=>Zc(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();lf.set(this.name,e),this.#_.abort(),dr()?.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),lf.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 nu(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 Mc(this.memdag,a=>Ws(t,a,e,Kl,this.#l,r,Ca(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===``&&nc(this.puller)}async#A(e,t){let n=!0;try{return await e()}catch(e){return e instanceof su||e instanceof Gl?(n=!1,this.#g.debug?.(`${t} threw:
|
|
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:
|
|
8
8
|
`,e,`
|
|
9
9
|
with cause:
|
|
10
|
-
`,e.causedBy)):e instanceof
|
|
11
|
-
`,e),!1}finally{this.#i!==n&&(this.#i=n,this.onOnlineChange?.(n),n&&this.recoverMutations())}}async#j(e,t,n,r=af,i=af){let{clientID:a}=this,o=0,s;n=n.withContext(t);do{let c=Yd(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!==Il)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<Zd);return n.info?.(`Tried to reauthenticate too many times`),{result:s,authFailure:!0}}#M(){return this.isClientGroupDisabled||this.pushURL===``&&uc(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 mu(r,this.memdag,i,e,n,t,this.pusher,this.schemaVersion,lu);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 Js(i)?this.#P(i):qs(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 uf(this.#p.send(e))}pull({now:e=!1}={}){return uf(this.#f.send(e))}async poke(e){await this.#o;let{clientID:t}=this,n=Yd(t),r=this.#g.withContext(`handlePullResponse`).withContext(`requestID`,n),{pullResponse:i}=e;if(Js(i)){this.#P(i);return}if(qs(i)){await this.#L();return}let a=await tu(r,this.memdag,oi(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 Zl(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;Js(a)?this.#P(a):qs(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 bd(this.#g,e,this.memdag,this.perdag,this.#l,()=>this.closed,7)}catch(t){if(t instanceof Yc)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 Ed(this.#g,this.memdag,this.perdag,e,this.#l,this.subscriptions,()=>this.closed,7)}catch(t){if(t instanceof Yc)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=>kc(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 nr?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 Pd(e,n,r,i,a))}experimentalWatch(e,t){return this.subscriptions.add(new Fd(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 ma(t,e)).meta.cookieJSON;return Kr(n),n}))}#W=async e=>{await this.#o;let{clientID:t}=this;return R(this.memdag,async n=>{try{let r=await ts(n,7);return await e(new ys(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=oi(n??null);this.subscriptions.hasPendingSubscriptionRuns&&await Promise.resolve(),await this.#o;let{clientID:a}=this;return Mc(this.memdag,async o=>{try{let s=await Is(await Ui(I,o),e,i,null,o,r,a,7),c=await t(new Cs(a,await s.getMutationID(),`initial`,s,this.#g),n);us(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 Vi&&await this.#D()?new Yc(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,Iu)}},lf=new Map;async function uf(e){let t=await e;if(t)throw t.error}function df(){typeof location<`u`&&location.reload()}function ff(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(Bu,md);if(typeof n!=`number`||n<=e)throw TypeError(`clientAgeMaxMs must be a number larger than ${e}ms`)}}var pf={PENDING:`PENDING`,IN_PROGRESS:`IN_PROGRESS`,READY:`READY`,ERROR:`ERROR`},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:T.surface.prefix()}).entries())if(t.key===i){await n.set(e,s);return}await n.set(T.surface.encode(r),s)},project_ping_v1:async()=>{},sprite_create_v1:async(e,t)=>{let{tx:n,sessionPersonId:r}=e,{spriteId:i,spriteBuildId:a,prompt:o,name:s,surfaceId:c}=t,l=T.sprite.encode(i);if(await n.get(l))return Error(`Sprite "${i}" already exists`);let u=T.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:pf.PENDING,artifactUrl:null,error:null,reasoningSummary:null,publishedAt:null,createdByPersonId:r};await n.set(u,f)},spriteBuild_create_v1:async(e,t)=>{let{tx:n,sessionPersonId:r}=e,{spriteBuildId:i,spriteId:a,parentSpriteBuildId:o,prompt:s}=t,c=T.spriteBuild.encode(i);if(await n.get(c))return Error(`SpriteBuild "${i}" already exists`);let l={spriteId:a,parentSpriteBuildId:o,prompt:s,status:pf.PENDING,artifactUrl:null,error:null,reasoningSummary:null,publishedAt:null,createdByPersonId:r};await n.set(c,l)},spriteBuild_publish_v1:async(e,t)=>{let{tx:n,actionedAt:r}=e,{spriteBuildId:i}=t,a=T.spriteBuild.encode(i),o=await n.get(a);if(!o)return Error(`Could not find that build.`);if(o.status!==pf.READY)return Error(`Only ready builds can be published.`);await n.set(a,{...o,publishedAt:r})}};async function hf(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)!==gf&&e.push(n);v(e)}return}p++,(async()=>{try{let r=await e.value;if(d)return;let i=await t(r,n);i===gf&&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 gf=Symbol(`skip`),_f={concurrency:5,stopOnError:!1},vf=async(e,r,i=_f)=>{let{stopOnError:a}=i;return n(async()=>hf(e,async e=>{let n=await t(async()=>r(e));if(a&&n instanceof Error)throw n;return n},i))},yf=async(e,t,n)=>{let r=await vf(Object.entries(e),async([e,n])=>[e,await t(n,e)],n);return r instanceof Error?r:Object.fromEntries(r)},bf=async(e,t)=>yf(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}}),xf=`2026.07.02/1`,Sf=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:xf,name:t,pushURL:n,pullURL:r,auth:i,pullInterval:o,mutators:await bf({sessionPersonId:s},mf)});return c.getAuth=a,c},Cf=new Map,wf=e=>{let{clientId:t,replicacheName:n}=e,r=()=>{},i={clientId:t,state:`starting`,released:new Promise(e=>{r=e})};Cf.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,Cf.get(n)===i&&Cf.delete(n),r())}}},Tf=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=Cf.get(n);if(!e)return wf({clientId:t,replicacheName:n});if(e.state===`destroying`){await e.released;continue}throw new mt({replicacheName:n})}},Ef=e=>{let{baseUrl:t,personId:n,projectId:r}=e;return[`rough-feature`,t,r,n].join(`:`)},Df=e=>{let{auth:t,baseUrl:n,clientId:r,projectId:i,signal:a,store:o}=e,s,c,l=!1,u,d=()=>{if(a.aborted)throw yt(a)},f=async e=>{let{name:r}=e,{sessionToken:a}=e,o=a.personId,s=async()=>{t.invalidateToken(a.token);let e=await t.getSessionToken();if(e.personId!==o)throw Error(`Session person changed during auth refresh. Destroy this Rough client and create a new one.`);return a=e,`Bearer ${a.token}`},c=`/api/v1/project/${encodeURIComponent(i)}`;return Sf({name:r,pushURL:S({baseUrl:n,path:`${c}/replicache/push`}),pullURL:S({baseUrl:n,path:`${c}/replicache/pull`}),auth:`Bearer ${a.token}`,getAuth:s,pullInterval:5e3,sessionPersonId:o})},p=async()=>{if(typeof window>`u`)return;d();let e=await Promise.race([t.getSessionToken(),bt(a)]);d();let u=Ef({baseUrl:n,projectId:i,personId:e.personId});s=await Tf({clientId:r,replicacheName:u,signal:a}),l&&s.markDestroying(),d();let p=await f({name:u,sessionToken:e});if(p instanceof Error)throw p;if(l||a.aborted)throw await p.close(),new pt(`Replicache finished starting after the Rough client was destroyed`);c=p,s.markActive(),o.bind(p),await Promise.race([p.pull({now:!0}),bt(a)])},m=()=>c,h=()=>{l=!0,s?.markDestroying()};return{start:p,peek:m,markDestroying:h,destroy:()=>(u??=(async()=>{h();let e=c;c=void 0,await e?.close()})(),u),releaseIdentity:()=>{s?.release()}}},Of=e.enum([`ACTIVE`,`DELETED`]),kf=e.enum([`DOCUMENTS_ENABLED`,`TASKS_ENABLED`]),B=e.string();e.object({id:B,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:Of,deletedAt:e.number().nullable(),version:e.number(),flagList:kf.array()}),e.object({id:B,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:Of,deletedAt:e.number().optional().nullable(),version:e.number(),flagList:kf.array()}),e.object({id:B.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:Of.optional(),deletedAt:e.number().optional().nullable(),version:e.number().optional(),flagList:kf.array().optional()});var Af=e.string();e.object({id:Af,name:e.string(),url:e.string(),workspaceId:B,version:e.number(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:Af,name:e.string(),url:e.string(),workspaceId:B,version:e.number(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:Af.optional(),name:e.string().optional(),url:e.string().optional(),workspaceId:B.optional(),version:e.number().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var jf=e.enum([`authorization_code`,`client_credentials`,`refresh_token`]),Mf=e.enum([`read:workspace`,`write:workspace`,`create:sprite`,`read:sprite`]),Nf=e.string();e.object({id:Nf,name:e.string(),secret:e.string().nullable(),redirectUris:e.string().array(),allowedGrants:jf.array(),scopes:Mf.array(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:Nf,name:e.string(),secret:e.string().optional().nullable(),redirectUris:e.string().array(),allowedGrants:jf.array(),scopes:Mf.array(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:Nf.optional(),name:e.string().optional(),secret:e.string().optional().nullable(),redirectUris:e.string().array().optional(),allowedGrants:jf.array().optional(),scopes:Mf.array().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var Pf=e.enum([`UNKNOWN`]),V=e.string();e.object({id:V,workspaceId:B,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:Pf.array(),personMentionList:e.string().array()}),e.object({id:V,workspaceId:B,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:Pf.array(),personMentionList:e.string().array()}),e.object({id:V.optional(),workspaceId:B.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:Pf.array().optional(),personMentionList:e.string().array().optional()});var Ff=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}`},H=e.string().min(1).transform((t,n)=>{let r=Ff(t);return r instanceof Error?(n.issues.push({code:`custom`,message:r.message,input:t}),e.NEVER):r}).pipe(e.string()),If=e.enum([`WORKSPACE`,`USER`]),Lf=e.enum([`PENDING`,`UPLOADING`,`READY`,`ERROR`]),Rf=e.enum([`IMAGE`,`VIDEO`,`AUDIO`,`OTHER`]),zf=e.string();e.object({id:zf,scope:If,userId:e.lazy(()=>U),workspaceId:B.nullable(),storageBucket:e.string(),storageKey:e.string(),status:Lf,type:Rf,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:zf.nullable()}),e.object({id:zf,scope:If,userId:e.lazy(()=>U),workspaceId:B.optional().nullable(),storageBucket:e.string(),storageKey:e.string(),status:Lf,type:Rf,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:zf.optional().nullable()}),e.object({id:zf.optional(),scope:If.optional(),userId:e.lazy(()=>U.optional()),workspaceId:B.optional().nullable(),storageBucket:e.string().optional(),storageKey:e.string().optional(),status:Lf.optional(),type:Rf.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:zf.optional().nullable()});var U=e.string();e.object({id:U,name:e.string(),email:H,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:zf.nullable()}),e.object({id:U,name:e.string(),email:H,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:zf.optional().nullable()}),e.object({id:U.optional(),name:e.string().optional(),email:H.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:zf.optional().nullable()});var Bf=e.enum([`DRAFT`,`ACTIVE`]),W=e.string();e.object({id:W,name:e.string(),workspaceId:B,version:e.number(),createdAt:e.number(),updatedAt:e.number(),description:e.string(),avatarAssetId:zf.nullable()}),e.object({id:W,name:e.string(),workspaceId:B,version:e.number(),createdAt:e.number(),updatedAt:e.number(),description:e.string(),avatarAssetId:zf.optional().nullable()}),e.object({id:W.optional(),name:e.string().optional(),workspaceId:B.optional(),version:e.number().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),description:e.string().optional(),avatarAssetId:zf.optional().nullable()});var G=e.string();e.object({id:G,workspaceId:B,contentId:V,createdAt:e.number(),updatedAt:e.number(),userId:U,version:e.number(),lastModifiedAt:e.number(),status:Bf,personId:W,referenceId:Af.nullable(),publicId:e.number(),parentNoteId:G.nullable(),sortOrder:e.number(),transcriptContentId:V.nullable()}),e.object({id:G,workspaceId:B,contentId:V,createdAt:e.number(),updatedAt:e.number(),userId:U,version:e.number(),lastModifiedAt:e.number(),status:Bf,personId:W,referenceId:Af.optional().nullable(),publicId:e.number(),parentNoteId:G.optional().nullable(),sortOrder:e.number(),transcriptContentId:V.optional().nullable()}),e.object({id:G.optional(),workspaceId:B.optional(),contentId:V.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),userId:U.optional(),version:e.number().optional(),lastModifiedAt:e.number().optional(),status:Bf.optional(),personId:W.optional(),referenceId:Af.optional().nullable(),publicId:e.number().optional(),parentNoteId:G.optional().nullable(),sortOrder:e.number().optional(),transcriptContentId:V.optional().nullable()});var Vf=e.enum([`NOTE`,`TASK`]),Hf=e.string();e.object({id:Hf,workspaceId:B,name:e.string(),color:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),description:e.string(),type:Vf}),e.object({id:Hf,workspaceId:B,name:e.string(),color:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),description:e.string(),type:Vf}),e.object({id:Hf.optional(),workspaceId:B.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:Vf.optional()}),e.object({noteId:G,labelId:Hf,workspaceId:B,createdAt:e.number(),updatedAt:e.number(),version:e.number(),labelType:Vf}),e.object({noteId:G,labelId:Hf,workspaceId:B,createdAt:e.number(),updatedAt:e.number(),version:e.number(),labelType:Vf}),e.object({noteId:G.optional(),labelId:Hf.optional(),workspaceId:B.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),labelType:Vf.optional()});var Uf=e.string();e.object({code:Uf,redirectUri:e.string().nullable(),codeChallenge:e.string().nullable(),codeChallengeMethod:e.string().nullable(),expiresAt:e.number(),userId:U,workspaceId:B,oauthClientId:Nf,scopes:Mf.array(),createdAt:e.number(),updatedAt:e.number()}),e.object({code:Uf,redirectUri:e.string().optional().nullable(),codeChallenge:e.string().optional().nullable(),codeChallengeMethod:e.string().optional().nullable(),expiresAt:e.number(),userId:U,workspaceId:B,oauthClientId:Nf,scopes:Mf.array(),createdAt:e.number(),updatedAt:e.number()}),e.object({code:Uf.optional(),redirectUri:e.string().optional().nullable(),codeChallenge:e.string().optional().nullable(),codeChallengeMethod:e.string().optional().nullable(),expiresAt:e.number().optional(),userId:U.optional(),workspaceId:B.optional(),oauthClientId:Nf.optional(),scopes:Mf.array().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var Wf=e.string();e.object({accessToken:Wf,accessTokenExpiresAt:e.number(),refreshToken:e.string().nullable(),refreshTokenExpiresAt:e.number().nullable(),userId:U,workspaceId:B,oauthClientId:Nf,scopes:Mf.array(),originatingAuthCodeId:Uf.nullable(),createdAt:e.number(),updatedAt:e.number()}),e.object({accessToken:Wf,accessTokenExpiresAt:e.number(),refreshToken:e.string().optional().nullable(),refreshTokenExpiresAt:e.number().optional().nullable(),userId:U,workspaceId:B,oauthClientId:Nf,scopes:Mf.array(),originatingAuthCodeId:Uf.optional().nullable(),createdAt:e.number(),updatedAt:e.number()}),e.object({accessToken:Wf.optional(),accessTokenExpiresAt:e.number().optional(),refreshToken:e.string().optional().nullable(),refreshTokenExpiresAt:e.number().optional().nullable(),userId:U.optional(),workspaceId:B.optional(),oauthClientId:Nf.optional(),scopes:Mf.array().optional(),originatingAuthCodeId:Uf.optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var Gf=e.string();e.object({id:Gf,name:e.string(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:Gf,name:e.string(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:Gf.optional(),name:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var Kf=e.string();e.object({id:Kf,llmProviderId:Gf,providerModelId:e.string(),name:e.string(),releasedOn:e.iso.date(),selectable:e.boolean(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:Kf,llmProviderId:Gf,providerModelId:e.string(),name:e.string(),releasedOn:e.iso.date(),selectable:e.boolean(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:Kf.optional(),llmProviderId:Gf.optional(),providerModelId:e.string().optional(),name:e.string().optional(),releasedOn:e.iso.date().optional(),selectable:e.boolean().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var K=e.string();e.object({id:K,workspaceId:B,name:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),firstUsedViaApiAt:e.number().nullable(),publicId:e.string(),spriteLlmModelId:Kf.nullable()}),e.object({id:K,workspaceId:B,name:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),firstUsedViaApiAt:e.number().optional().nullable(),publicId:e.string(),spriteLlmModelId:Kf.optional().nullable()}),e.object({id:K.optional(),workspaceId:B.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:Kf.optional().nullable()});var qf=e.string();e.object({id:qf,createdAt:e.number(),updatedAt:e.number(),version:e.number(),workspaceId:B,projectId:K,personId:W,key:e.string(),name:e.string(),email:H.nullable().nullable(),lastSeenAt:e.number().nullable()}),e.object({id:qf,createdAt:e.number(),updatedAt:e.number(),version:e.number(),workspaceId:B,projectId:K,personId:W,key:e.string(),name:e.string(),email:H.nullable().optional().nullable(),lastSeenAt:e.number().optional().nullable()}),e.object({id:qf.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),workspaceId:B.optional(),projectId:K.optional(),personId:W.optional(),key:e.string().optional(),name:e.string().optional(),email:H.nullable().optional().nullable(),lastSeenAt:e.number().optional().nullable()});var q=e.string();e.object({id:q,createdAt:e.number(),updatedAt:e.number(),version:e.number(),workspaceId:B,projectId:K,key:e.string(),name:e.string(),lastSeenAt:e.number().nullable()}),e.object({id:q,createdAt:e.number(),updatedAt:e.number(),version:e.number(),workspaceId:B,projectId:K,key:e.string(),name:e.string(),lastSeenAt:e.number().optional().nullable()}),e.object({id:q.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),workspaceId:B.optional(),projectId:K.optional(),key:e.string().optional(),name:e.string().optional(),lastSeenAt:e.number().optional().nullable()});var Jf=e.string();e.object({id:Jf,publicId:e.string(),workspaceId:B,name:e.string(),publicKey:e.string(),createdByUserId:U,createdAt:e.number(),updatedAt:e.number(),version:e.number(),revokedAt:e.number().nullable(),revokedByUserId:U.nullable(),lastUsedAt:e.number().nullable()}),e.object({id:Jf,publicId:e.string(),workspaceId:B,name:e.string(),publicKey:e.string(),createdByUserId:U,createdAt:e.number(),updatedAt:e.number(),version:e.number(),revokedAt:e.number().optional().nullable(),revokedByUserId:U.optional().nullable(),lastUsedAt:e.number().optional().nullable()}),e.object({id:Jf.optional(),publicId:e.string().optional(),workspaceId:B.optional(),name:e.string().optional(),publicKey:e.string().optional(),createdByUserId:U.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),revokedAt:e.number().optional().nullable(),revokedByUserId:U.optional().nullable(),lastUsedAt:e.number().optional().nullable()});var Yf=e.string();e.object({id:Yf,workspaceId:B,projectId:K,projectUserId:qf,projectAccountId:q,signingKeyId:Jf,hash:e.instanceof(Uint8Array),createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number()}),e.object({id:Yf,workspaceId:B,projectId:K,projectUserId:qf,projectAccountId:q,signingKeyId:Jf,hash:e.instanceof(Uint8Array),createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number()}),e.object({id:Yf.optional(),workspaceId:B.optional(),projectId:K.optional(),projectUserId:qf.optional(),projectAccountId:q.optional(),signingKeyId:Jf.optional(),hash:e.instanceof(Uint8Array).optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),expiresAt:e.number().optional()});var Xf=e.enum([`PENDING`,`INSTALLED`]),Zf=e.string();e.object({id:Zf,fizzyIntegrationId:e.lazy(()=>Qf),fizzyAccountId:e.lazy(()=>$f),workspaceId:B,publicId:e.string(),name:e.string(),url:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:Zf,fizzyIntegrationId:e.lazy(()=>Qf),fizzyAccountId:e.lazy(()=>$f),workspaceId:B,publicId:e.string(),name:e.string(),url:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:Zf.optional(),fizzyIntegrationId:e.lazy(()=>Qf.optional()),fizzyAccountId:e.lazy(()=>$f.optional()),workspaceId:B.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 Qf=e.string();e.object({id:Qf,workspaceId:B,email:e.string(),state:Xf,pendingAuthenticationToken:e.string().nullable(),sessionToken:e.string().nullable(),defaultFizzyBoardId:Zf.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:Qf,workspaceId:B,email:e.string(),state:Xf,pendingAuthenticationToken:e.string().optional().nullable(),sessionToken:e.string().optional().nullable(),defaultFizzyBoardId:Zf.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:Qf.optional(),workspaceId:B.optional(),email:e.string().optional(),state:Xf.optional(),pendingAuthenticationToken:e.string().optional().nullable(),sessionToken:e.string().optional().nullable(),defaultFizzyBoardId:Zf.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 $f=e.string();e.object({id:$f,fizzyIntegrationId:Qf,workspaceId:B,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:$f,fizzyIntegrationId:Qf,workspaceId:B,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:$f.optional(),fizzyIntegrationId:Qf.optional(),workspaceId:B.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 ep=e.string();e.object({id:ep,userId:U.nullable(),workspaceId:B,pullCount:e.number(),projectUserId:qf.nullable(),projectAccountId:q.nullable()}),e.object({id:ep,userId:U.optional().nullable(),workspaceId:B,pullCount:e.number(),projectUserId:qf.optional().nullable(),projectAccountId:q.optional().nullable()}),e.object({id:ep.optional(),userId:U.optional().nullable(),workspaceId:B.optional(),pullCount:e.number().optional(),projectUserId:qf.optional().nullable(),projectAccountId:q.optional().nullable()});var tp=e.enum([`GITHUB`]),np=e.enum([`PENDING`,`INSTALLED`,`DELETED`]),J=e.string();e.object({id:J,createdAt:e.number(),updatedAt:e.number(),workspaceId:B,type:tp,state:np,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:B,type:tp,state:np,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:B.optional(),type:tp.optional(),state:np.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 rp=e.string();e.object({id:rp,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:B,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:rp,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:B,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:rp.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:B.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 ip=e.string();e.object({id:ip,createdAt:e.number(),updatedAt:e.number(),version:e.number(),vcsRepoId:rp,vcsIntegrationId:J,workspaceId:B,name:e.string(),commitSha:e.string()}),e.object({id:ip,createdAt:e.number(),updatedAt:e.number(),version:e.number(),vcsRepoId:rp,vcsIntegrationId:J,workspaceId:B,name:e.string(),commitSha:e.string()}),e.object({id:ip.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),vcsRepoId:rp.optional(),vcsIntegrationId:J.optional(),workspaceId:B.optional(),name:e.string().optional(),commitSha:e.string().optional()});var ap=e.enum([`SUGGESTED`,`APPROVED`,`REJECTED`]);e.object({noteIdA:G,noteIdB:G,workspaceId:B,createdAt:e.number(),updatedAt:e.number(),distance:e.number().nullable(),version:e.number(),status:ap,createdByUserId:U.nullable(),lastModifiedByUserId:U.nullable(),lastModifiedAt:e.number().nullable()}),e.object({noteIdA:G,noteIdB:G,workspaceId:B,createdAt:e.number(),updatedAt:e.number(),distance:e.number().optional().nullable(),version:e.number(),status:ap,createdByUserId:U.optional().nullable(),lastModifiedByUserId:U.optional().nullable(),lastModifiedAt:e.number().optional().nullable()}),e.object({noteIdA:G.optional(),noteIdB:G.optional(),workspaceId:B.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),distance:e.number().optional().nullable(),version:e.number().optional(),status:ap.optional(),createdByUserId:U.optional().nullable(),lastModifiedByUserId:U.optional().nullable(),lastModifiedAt:e.number().optional().nullable()});var op=e.string();e.object({id:op,workspaceId:B,projectId:K,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:op,workspaceId:B,projectId:K,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:op.optional(),workspaceId:B.optional(),projectId:K.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:B,version:e.number(),createdAt:e.number(),updatedAt:e.number(),name:e.string(),projectId:K,surfaceId:op,ownedByPersonId:W}),e.object({id:Y,workspaceId:B,version:e.number(),createdAt:e.number(),updatedAt:e.number(),name:e.string(),projectId:K,surfaceId:op,ownedByPersonId:W}),e.object({id:Y.optional(),workspaceId:B.optional(),version:e.number().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),name:e.string().optional(),projectId:K.optional(),surfaceId:op.optional(),ownedByPersonId:W.optional()});var sp=e.enum([`PENDING`,`IN_PROGRESS`,`READY`,`ERROR`]),cp=e.string();e.object({id:cp,workspaceId:B,version:e.number(),createdAt:e.number(),updatedAt:e.number(),spriteId:Y,parentSpriteBuildId:cp.nullable(),prompt:e.string(),artifactUrl:e.string().nullable(),sourceUrl:e.string().nullable(),status:sp,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:W,agentProvider:e.string(),agentModel:e.string(),agentInputTokens:e.number(),agentOutputTokens:e.number(),agentCacheReadTokens:e.number(),agentCacheWriteTokens:e.number(),agentEstimatedCostUsd:e.number()}),e.object({id:cp,workspaceId:B,version:e.number(),createdAt:e.number(),updatedAt:e.number(),spriteId:Y,parentSpriteBuildId:cp.optional().nullable(),prompt:e.string(),artifactUrl:e.string().optional().nullable(),sourceUrl:e.string().optional().nullable(),status:sp,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:W,agentProvider:e.string(),agentModel:e.string(),agentInputTokens:e.number(),agentOutputTokens:e.number(),agentCacheReadTokens:e.number(),agentCacheWriteTokens:e.number(),agentEstimatedCostUsd:e.number()}),e.object({id:cp.optional(),workspaceId:B.optional(),version:e.number().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),spriteId:Y.optional(),parentSpriteBuildId:cp.optional().nullable(),prompt:e.string().optional(),artifactUrl:e.string().optional().nullable(),sourceUrl:e.string().optional().nullable(),status:sp.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:W.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()});var lp=e.string();e.object({id:lp,workspaceId:B,createdAt:e.number(),updatedAt:e.number(),snapshot:e.record(e.string(),e.json()).nullable()}),e.object({id:lp,workspaceId:B,createdAt:e.number(),updatedAt:e.number(),snapshot:e.record(e.string(),e.json()).optional().nullable()}),e.object({id:lp.optional(),workspaceId:B.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),snapshot:e.record(e.string(),e.json()).optional().nullable()});var up=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(`.`)),dp=e.enum([`CANCELED`,`IDEA`,`DEVELOPMENT`,`RELEASED`,`DRAFT`,`ARCHIVED`]),X=e.string();e.object({id:X,title:e.string(),status:dp,createdAt:e.number(),updatedAt:e.number(),publicId:e.number(),createdByUserId:U,workspaceId:B,vcsTagList:e.string().array(),archivedAt:e.number().nullable(),archivedByUserId:U.nullable(),version:e.number(),lastModifiedAt:e.number(),releasedAt:e.number().nullable(),ownedByPersonId:W}),e.object({id:X,title:e.string(),status:dp,createdAt:e.number(),updatedAt:e.number(),publicId:e.number(),createdByUserId:U,workspaceId:B,vcsTagList:e.string().array(),archivedAt:e.number().optional().nullable(),archivedByUserId:U.optional().nullable(),version:e.number(),lastModifiedAt:e.number(),releasedAt:e.number().optional().nullable(),ownedByPersonId:W}),e.object({id:X.optional(),title:e.string().optional(),status:dp.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),publicId:e.number().optional(),createdByUserId:U.optional(),workspaceId:B.optional(),vcsTagList:e.string().array().optional(),archivedAt:e.number().optional().nullable(),archivedByUserId:U.optional().nullable(),version:e.number().optional(),lastModifiedAt:e.number().optional(),releasedAt:e.number().optional().nullable(),ownedByPersonId:W.optional()});var fp=e.enum([`USER`,`STATUS`,`WISH`]),pp=e.enum([`NONE`,`STATUS`]),Z=e.string();e.object({id:Z,createdAt:e.number(),updatedAt:e.number(),name:e.string(),workspaceId:B,publicId:e.string(),type:fp,status:dp.nullable().nullable(),version:e.number(),icon:e.string(),pinned:e.number().nullable(),groupBy:pp,ownedByPersonId:W.nullable()}),e.object({id:Z,createdAt:e.number(),updatedAt:e.number(),name:e.string(),workspaceId:B,publicId:e.string(),type:fp,status:dp.nullable().optional().nullable(),version:e.number(),icon:e.string(),pinned:e.number().optional().nullable(),groupBy:pp,ownedByPersonId:W.optional().nullable()}),e.object({id:Z.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),name:e.string().optional(),workspaceId:B.optional(),publicId:e.string().optional(),type:fp.optional(),status:dp.nullable().optional().nullable(),version:e.number().optional(),icon:e.string().optional(),pinned:e.number().optional().nullable(),groupBy:pp.optional(),ownedByPersonId:W.optional().nullable()});var mp=e.string();e.object({id:mp,workspaceId:B,type:up,detail:e.record(e.string(),e.json()),actionedAt:e.number(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),documentId:X.nullable(),noteId:G.nullable(),sequenceId:Z.nullable(),spriteId:Y.nullable(),actionedByPersonId:W}),e.object({id:mp,workspaceId:B,type:up,detail:e.record(e.string(),e.json()),actionedAt:e.number(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),documentId:X.optional().nullable(),noteId:G.optional().nullable(),sequenceId:Z.optional().nullable(),spriteId:Y.optional().nullable(),actionedByPersonId:W}),e.object({id:mp.optional(),workspaceId:B.optional(),type:up.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:G.optional().nullable(),sequenceId:Z.optional().nullable(),spriteId:Y.optional().nullable(),actionedByPersonId:W.optional()});var hp=e.enum([`DOCUMENT`,`NOTE`,`SEQUENCE`,`SPRITE`]),gp=e.enum([`TEXT`,`DRAWING`]),_p=e.enum([`UNKNOWN`]),vp=e.string();e.object({id:vp,sortOrder:e.number(),documentId:X,createdAt:e.number(),updatedAt:e.number(),type:gp,lockedAt:e.number().nullable(),version:e.number(),lastModifiedAt:e.number(),workspaceId:B,archivedAt:e.number().nullable(),archivedByUserId:U.nullable(),flagList:_p.array(),title:e.string(),contentId:V.nullable(),canvasId:lp.nullable(),lastModifiedByUserId:U}),e.object({id:vp,sortOrder:e.number(),documentId:X,createdAt:e.number(),updatedAt:e.number(),type:gp,lockedAt:e.number().optional().nullable(),version:e.number(),lastModifiedAt:e.number(),workspaceId:B,archivedAt:e.number().optional().nullable(),archivedByUserId:U.optional().nullable(),flagList:_p.array(),title:e.string(),contentId:V.optional().nullable(),canvasId:lp.optional().nullable(),lastModifiedByUserId:U}),e.object({id:vp.optional(),sortOrder:e.number().optional(),documentId:X.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),type:gp.optional(),lockedAt:e.number().optional().nullable(),version:e.number().optional(),lastModifiedAt:e.number().optional(),workspaceId:B.optional(),archivedAt:e.number().optional().nullable(),archivedByUserId:U.optional().nullable(),flagList:_p.array().optional(),title:e.string().optional(),contentId:V.optional().nullable(),canvasId:lp.optional().nullable(),lastModifiedByUserId:U.optional()});var Q=e.string();e.object({id:Q,createdAt:e.number(),updatedAt:e.number(),postedAt:e.number(),documentId:X.nullable(),userId:U,parentCommentId:Q.nullable(),onBlockId:vp.nullable(),resolvedAt:e.number().nullable(),resolvedByUserId:U.nullable(),sequenceId:Z.nullable(),workspaceId:B,version:e.number(),noteId:G.nullable(),contentId:V,onEventId:mp.nullable(),spriteId:Y.nullable()}),e.object({id:Q,createdAt:e.number(),updatedAt:e.number(),postedAt:e.number(),documentId:X.optional().nullable(),userId:U,parentCommentId:Q.optional().nullable(),onBlockId:vp.optional().nullable(),resolvedAt:e.number().optional().nullable(),resolvedByUserId:U.optional().nullable(),sequenceId:Z.optional().nullable(),workspaceId:B,version:e.number(),noteId:G.optional().nullable(),contentId:V,onEventId:mp.optional().nullable(),spriteId:Y.optional().nullable()}),e.object({id:Q.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),postedAt:e.number().optional(),documentId:X.optional().nullable(),userId:U.optional(),parentCommentId:Q.optional().nullable(),onBlockId:vp.optional().nullable(),resolvedAt:e.number().optional().nullable(),resolvedByUserId:U.optional().nullable(),sequenceId:Z.optional().nullable(),workspaceId:B.optional(),version:e.number().optional(),noteId:G.optional().nullable(),contentId:V.optional(),onEventId:mp.optional().nullable(),spriteId:Y.optional().nullable()});var yp=e.string();e.object({id:yp,workspaceId:B,userId:U,eventId:mp,readAt:e.number().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),type:hp,documentId:X.nullable(),noteId:G.nullable(),sequenceId:Z.nullable(),commentId:Q.nullable(),spriteId:Y.nullable()}),e.object({id:yp,workspaceId:B,userId:U,eventId:mp,readAt:e.number().optional().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),type:hp,documentId:X.optional().nullable(),noteId:G.optional().nullable(),sequenceId:Z.optional().nullable(),commentId:Q.optional().nullable(),spriteId:Y.optional().nullable()}),e.object({id:yp.optional(),workspaceId:B.optional(),userId:U.optional(),eventId:mp.optional(),readAt:e.number().optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),type:hp.optional(),documentId:X.optional().nullable(),noteId:G.optional().nullable(),sequenceId:Z.optional().nullable(),commentId:Q.optional().nullable(),spriteId:Y.optional().nullable()});var bp=e.string();e.object({id:bp,workspaceId:B,createdAt:e.number(),updatedAt:e.number(),version:e.number(),title:e.string(),contentId:V,completedAt:e.number().nullable(),createdByPersonId:W}),e.object({id:bp,workspaceId:B,createdAt:e.number(),updatedAt:e.number(),version:e.number(),title:e.string(),contentId:V,completedAt:e.number().optional().nullable(),createdByPersonId:W}),e.object({id:bp.optional(),workspaceId:B.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),title:e.string().optional(),contentId:V.optional(),completedAt:e.number().optional().nullable(),createdByPersonId:W.optional()});var xp=e.string();e.object({id:xp,userId:U,contentId:V,workspaceId:B,createdAt:e.number(),updatedAt:e.number(),version:e.number(),state:e.instanceof(Uint8Array)}),e.object({id:xp,userId:U,contentId:V,workspaceId:B,createdAt:e.number(),updatedAt:e.number(),version:e.number(),state:e.instanceof(Uint8Array)}),e.object({id:xp.optional(),userId:U.optional(),contentId:V.optional(),workspaceId:B.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),state:e.instanceof(Uint8Array).optional()});var Sp=e.string();e.object({id:Sp,createdAt:e.number(),record:e.record(e.string(),e.json())}),e.object({id:Sp,createdAt:e.number(),record:e.record(e.string(),e.json())}),e.object({id:Sp.optional(),createdAt:e.number().optional(),record:e.record(e.string(),e.json()).optional()}),e.object({spriteId:Y,projectAccountId:q,workspaceId:B,projectId:K,createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({spriteId:Y,projectAccountId:q,workspaceId:B,projectId:K,createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({spriteId:Y.optional(),projectAccountId:q.optional(),workspaceId:B.optional(),projectId:K.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()}),e.object({projectAccountId:q,projectUserId:qf,createdAt:e.number(),updatedAt:e.number(),version:e.number(),workspaceId:B,projectId:K}),e.object({projectAccountId:q,projectUserId:qf,createdAt:e.number(),updatedAt:e.number(),version:e.number(),workspaceId:B,projectId:K}),e.object({projectAccountId:q.optional(),projectUserId:qf.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),workspaceId:B.optional(),projectId:K.optional()});var Cp=e.string();e.object({id:Cp,workspaceId:B,userId:U,emoji:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),commentId:Q.nullable(),noteId:G.nullable()}),e.object({id:Cp,workspaceId:B,userId:U,emoji:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),commentId:Q.optional().nullable(),noteId:G.optional().nullable()}),e.object({id:Cp.optional(),workspaceId:B.optional(),userId:U.optional(),emoji:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),commentId:Q.optional().nullable(),noteId:G.optional().nullable()}),e.object({taskId:bp,workspaceId:B,createdAt:e.number(),updatedAt:e.number(),version:e.number(),sortOrder:e.number()}),e.object({taskId:bp,workspaceId:B,createdAt:e.number(),updatedAt:e.number(),version:e.number(),sortOrder:e.number()}),e.object({taskId:bp.optional(),workspaceId:B.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),sortOrder:e.number().optional()});var wp=e.string();e.object({id:wp,workspaceId:B,token:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:wp,workspaceId:B,token:e.string(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:wp.optional(),workspaceId:B.optional(),token:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()});var Tp=e.string();e.object({id:Tp,workspaceId:B,userId:U,hash:e.instanceof(Uint8Array),createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number()}),e.object({id:Tp,workspaceId:B,userId:U,hash:e.instanceof(Uint8Array),createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number()}),e.object({id:Tp.optional(),workspaceId:B.optional(),userId:U.optional(),hash:e.instanceof(Uint8Array).optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),expiresAt:e.number().optional()});var Ep=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`]),Dp=e.string();e.object({id:Dp,workspaceId:B,spriteBuildId:cp,createdAt:e.number(),updatedAt:e.number(),version:e.number(),type:Ep,detail:e.record(e.string(),e.json()),actionedAt:e.number()}),e.object({id:Dp,workspaceId:B,spriteBuildId:cp,createdAt:e.number(),updatedAt:e.number(),version:e.number(),type:Ep,detail:e.record(e.string(),e.json()),actionedAt:e.number()}),e.object({id:Dp.optional(),workspaceId:B.optional(),spriteBuildId:cp.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),type:Ep.optional(),detail:e.record(e.string(),e.json()).optional(),actionedAt:e.number().optional()}),e.object({blockId:vp,userId:U,workspaceId:B,lastReadAt:e.number(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({blockId:vp,userId:U,workspaceId:B,lastReadAt:e.number(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({blockId:vp.optional(),userId:U.optional(),workspaceId:B.optional(),lastReadAt:e.number().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()});var Op=e.enum([`NOTE`,`DOCUMENT`]),kp=e.string();e.object({id:kp,workspaceId:B,userId:U,type:Op,matchAll:e.boolean(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:kp,workspaceId:B,userId:U,type:Op,matchAll:e.boolean(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:kp.optional(),workspaceId:B.optional(),userId:U.optional(),type:Op.optional(),matchAll:e.boolean().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()});var Ap=e.enum([`ADMIN`,`GUEST`,`ARCHIVED`,`DEMO`]);e.object({workspaceId:B,userId:U,createdAt:e.number(),updatedAt:e.number(),role:Ap,version:e.number(),personId:W,lastReadNotificationsAt:e.number().nullable()}),e.object({workspaceId:B,userId:U,createdAt:e.number(),updatedAt:e.number(),role:Ap,version:e.number(),personId:W,lastReadNotificationsAt:e.number().optional().nullable()}),e.object({workspaceId:B.optional(),userId:U.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),role:Ap.optional(),version:e.number().optional(),personId:W.optional(),lastReadNotificationsAt:e.number().optional().nullable()});var jp=e.string();e.object({id:jp,workspaceId:B,name:e.string(),url:e.string(),secret:e.string(),eventTypeList:up.array(),createdByPersonId:W,createdAt:e.number(),updatedAt:e.number()}),e.object({id:jp,workspaceId:B,name:e.string(),url:e.string(),secret:e.string(),eventTypeList:up.array(),createdByPersonId:W,createdAt:e.number(),updatedAt:e.number()}),e.object({id:jp.optional(),workspaceId:B.optional(),name:e.string().optional(),url:e.string().optional(),secret:e.string().optional(),eventTypeList:up.array().optional(),createdByPersonId:W.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var Mp=e.enum([`FEATURE`,`FIX`,`RELEASE`,`CHORE`]),Np=e.string();e.object({id:Np,createdAt:e.number(),updatedAt:e.number(),version:e.number(),vcsIntegrationId:J,workspaceId:B,name:e.string(),email:e.string(),avatarUrl:e.string().nullable()}),e.object({id:Np,createdAt:e.number(),updatedAt:e.number(),version:e.number(),vcsIntegrationId:J,workspaceId:B,name:e.string(),email:e.string(),avatarUrl:e.string().optional().nullable()}),e.object({id:Np.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),vcsIntegrationId:J.optional(),workspaceId:B.optional(),name:e.string().optional(),email:e.string().optional(),avatarUrl:e.string().optional().nullable()});var Pp=e.string();e.object({id:Pp,createdAt:e.number(),updatedAt:e.number(),sha:e.string(),vcsRepoId:rp,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:B,type:Mp,subject:e.string(),scope:e.string().nullable(),authorId:Np.nullable(),committerId:Np.nullable()}),e.object({id:Pp,createdAt:e.number(),updatedAt:e.number(),sha:e.string(),vcsRepoId:rp,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:B,type:Mp,subject:e.string(),scope:e.string().optional().nullable(),authorId:Np.optional().nullable(),committerId:Np.optional().nullable()}),e.object({id:Pp.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),sha:e.string().optional(),vcsRepoId:rp.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:B.optional(),type:Mp.optional(),subject:e.string().optional(),scope:e.string().optional().nullable(),authorId:Np.optional().nullable(),committerId:Np.optional().nullable()}),e.object({vcsCommitId:Pp,documentId:X,createdAt:e.number(),updatedAt:e.number(),description:e.string(),version:e.number(),vcsIntegrationId:J,workspaceId:B}),e.object({vcsCommitId:Pp,documentId:X,createdAt:e.number(),updatedAt:e.number(),description:e.string(),version:e.number(),vcsIntegrationId:J,workspaceId:B}),e.object({vcsCommitId:Pp.optional(),documentId:X.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),description:e.string().optional(),version:e.number().optional(),vcsIntegrationId:J.optional(),workspaceId:B.optional()}),e.object({documentId:X,userId:U,workspaceId:B,lastReadAt:e.number(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({documentId:X,userId:U,workspaceId:B,lastReadAt:e.number(),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({documentId:X.optional(),userId:U.optional(),workspaceId:B.optional(),lastReadAt:e.number().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()}),e.object({personId:W,taskId:bp,workspaceId:B,createdAt:e.number(),updatedAt:e.number(),version:e.number(),sortOrder:e.number(),date:e.iso.date()}),e.object({personId:W,taskId:bp,workspaceId:B,createdAt:e.number(),updatedAt:e.number(),version:e.number(),sortOrder:e.number(),date:e.iso.date()}),e.object({personId:W.optional(),taskId:bp.optional(),workspaceId:B.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),sortOrder:e.number().optional(),date:e.iso.date().optional()});var Fp=e.enum([`DOCUMENT`,`NOTE`,`SEQUENCE`,`COMMENT`,`NEW_NOTE`,`SPRITE`]),Ip=e.string();e.object({id:Ip,workspaceId:B,userId:U,type:Fp,commentId:Q.nullable(),noteId:G.nullable(),documentId:X.nullable(),sequenceId:Z.nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),spriteId:Y.nullable()}),e.object({id:Ip,workspaceId:B,userId:U,type:Fp,commentId:Q.optional().nullable(),noteId:G.optional().nullable(),documentId:X.optional().nullable(),sequenceId:Z.optional().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),spriteId:Y.optional().nullable()}),e.object({id:Ip.optional(),workspaceId:B.optional(),userId:U.optional(),type:Fp.optional(),commentId:Q.optional().nullable(),noteId:G.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()});var Lp=e.string();e.object({id:Lp,workspaceId:B,email:H,lastSentAt:e.number().nullable(),invitedByUserId:U,createdAt:e.number(),updatedAt:e.number(),version:e.number(),token:e.string().nullable()}),e.object({id:Lp,workspaceId:B,email:H,lastSentAt:e.number().optional().nullable(),invitedByUserId:U,createdAt:e.number(),updatedAt:e.number(),version:e.number(),token:e.string().optional().nullable()}),e.object({id:Lp.optional(),workspaceId:B.optional(),email:H.optional(),lastSentAt:e.number().optional().nullable(),invitedByUserId:U.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),token:e.string().optional().nullable()});var Rp=e.string();e.object({id:Rp,clientGroupId:ep,lastMutationId:e.number(),version:e.number()}),e.object({id:Rp,clientGroupId:ep,lastMutationId:e.number(),version:e.number()}),e.object({id:Rp.optional(),clientGroupId:ep.optional(),lastMutationId:e.number().optional(),version:e.number().optional()}),e.object({documentIdA:X,documentIdB:X,workspaceId:B,createdAt:e.number(),updatedAt:e.number(),distance:e.number().nullable(),version:e.number(),status:ap,createdByUserId:U.nullable(),lastModifiedByUserId:U.nullable(),lastModifiedAt:e.number().nullable()}),e.object({documentIdA:X,documentIdB:X,workspaceId:B,createdAt:e.number(),updatedAt:e.number(),distance:e.number().optional().nullable(),version:e.number(),status:ap,createdByUserId:U.optional().nullable(),lastModifiedByUserId:U.optional().nullable(),lastModifiedAt:e.number().optional().nullable()}),e.object({documentIdA:X.optional(),documentIdB:X.optional(),workspaceId:B.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),distance:e.number().optional().nullable(),version:e.number().optional(),status:ap.optional(),createdByUserId:U.optional().nullable(),lastModifiedByUserId:U.optional().nullable(),lastModifiedAt:e.number().optional().nullable()});var zp=e.string();e.object({id:zp,userId:U,createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number(),twoFactorVerifiedAt:e.number().nullable()}),e.object({id:zp,userId:U,createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number(),twoFactorVerifiedAt:e.number().optional().nullable()}),e.object({id:zp.optional(),userId:U.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),expiresAt:e.number().optional(),twoFactorVerifiedAt:e.number().optional().nullable()});var Bp=e.string();e.object({id:Bp,workspaceId:B,hash:e.instanceof(Uint8Array),createdAt:e.number(),updatedAt:e.number(),contentHash:e.instanceof(Uint8Array),contentId:V,offset:e.number(),size:e.number(),tokenCount:e.number(),plaintext:e.string()}),e.object({id:Bp,workspaceId:B,hash:e.instanceof(Uint8Array),createdAt:e.number(),updatedAt:e.number(),contentHash:e.instanceof(Uint8Array),contentId:V,offset:e.number(),size:e.number(),tokenCount:e.number(),plaintext:e.string()}),e.object({id:Bp.optional(),workspaceId:B.optional(),hash:e.instanceof(Uint8Array).optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),contentHash:e.instanceof(Uint8Array).optional(),contentId:V.optional(),offset:e.number().optional(),size:e.number().optional(),tokenCount:e.number().optional(),plaintext:e.string().optional()}),e.object({llmProviderId:Gf,encryptedValue:e.string(),plaintextSuffix:e.string(),createdAt:e.number(),updatedAt:e.number()}),e.object({llmProviderId:Gf,encryptedValue:e.string(),plaintextSuffix:e.string(),createdAt:e.number(),updatedAt:e.number()}),e.object({llmProviderId:Gf.optional(),encryptedValue:e.string().optional(),plaintextSuffix:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var Vp=e.enum([`IS_IN`,`IS_NOT_IN`]),Hp=e.string();e.object({id:Hp,filterId:kp,workspaceId:B,field:e.string(),comparator:Vp,value:e.record(e.string(),e.json()),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:Hp,filterId:kp,workspaceId:B,field:e.string(),comparator:Vp,value:e.record(e.string(),e.json()),createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({id:Hp.optional(),filterId:kp.optional(),workspaceId:B.optional(),field:e.string().optional(),comparator:Vp.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:B,createdAt:e.number(),updatedAt:e.number(),distance:e.number().nullable(),version:e.number(),status:ap,createdByUserId:U.nullable(),lastModifiedByUserId:U.nullable(),lastModifiedAt:e.number().nullable()}),e.object({spriteIdA:Y,spriteIdB:Y,workspaceId:B,createdAt:e.number(),updatedAt:e.number(),distance:e.number().optional().nullable(),version:e.number(),status:ap,createdByUserId:U.optional().nullable(),lastModifiedByUserId:U.optional().nullable(),lastModifiedAt:e.number().optional().nullable()}),e.object({spriteIdA:Y.optional(),spriteIdB:Y.optional(),workspaceId:B.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),distance:e.number().optional().nullable(),version:e.number().optional(),status:ap.optional(),createdByUserId:U.optional().nullable(),lastModifiedByUserId:U.optional().nullable(),lastModifiedAt:e.number().optional().nullable()}),e.object({taskId:bp,labelId:Hf,labelType:Vf,workspaceId:B,createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({taskId:bp,labelId:Hf,labelType:Vf,workspaceId:B,createdAt:e.number(),updatedAt:e.number(),version:e.number()}),e.object({taskId:bp.optional(),labelId:Hf.optional(),labelType:Vf.optional(),workspaceId:B.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional()});var Up=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`]),Wp=e.string();e.object({id:Wp,type:Up,userId:U.nullable(),email:H.nullable().nullable(),clientAddress:e.string(),userAgent:e.string(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:Wp,type:Up,userId:U.optional().nullable(),email:H.nullable().optional().nullable(),clientAddress:e.string(),userAgent:e.string(),createdAt:e.number(),updatedAt:e.number()}),e.object({id:Wp.optional(),type:Up.optional(),userId:U.optional().nullable(),email:H.nullable().optional().nullable(),clientAddress:e.string().optional(),userAgent:e.string().optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var Gp=H;e.object({workspaceId:B,personId:W,email:Gp,createdAt:e.number(),updatedAt:e.number(),isPrimary:e.boolean()}),e.object({workspaceId:B,personId:W,email:Gp,createdAt:e.number(),updatedAt:e.number(),isPrimary:e.boolean()}),e.object({workspaceId:B.optional(),personId:W.optional(),email:Gp.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),isPrimary:e.boolean().optional()}),e.object({documentId:X,noteId:G,workspaceId:B,createdAt:e.number(),updatedAt:e.number(),distance:e.number().nullable(),version:e.number(),status:ap,createdByUserId:U.nullable(),lastModifiedByUserId:U.nullable(),lastModifiedAt:e.number().nullable()}),e.object({documentId:X,noteId:G,workspaceId:B,createdAt:e.number(),updatedAt:e.number(),distance:e.number().optional().nullable(),version:e.number(),status:ap,createdByUserId:U.optional().nullable(),lastModifiedByUserId:U.optional().nullable(),lastModifiedAt:e.number().optional().nullable()}),e.object({documentId:X.optional(),noteId:G.optional(),workspaceId:B.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),distance:e.number().optional().nullable(),version:e.number().optional(),status:ap.optional(),createdByUserId:U.optional().nullable(),lastModifiedByUserId:U.optional().nullable(),lastModifiedAt:e.number().optional().nullable()});var Kp=e.string();e.object({id:Kp,workspaceId:B,name:e.string(),hash:e.instanceof(Uint8Array),createdByUserId:U,lastUsedAt:e.number().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),scopeList:Mf.array()}),e.object({id:Kp,workspaceId:B,name:e.string(),hash:e.instanceof(Uint8Array),createdByUserId:U,lastUsedAt:e.number().optional().nullable(),createdAt:e.number(),updatedAt:e.number(),version:e.number(),scopeList:Mf.array()}),e.object({id:Kp.optional(),workspaceId:B.optional(),name:e.string().optional(),hash:e.instanceof(Uint8Array).optional(),createdByUserId:U.optional(),lastUsedAt:e.number().optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional(),version:e.number().optional(),scopeList:Mf.array().optional()});var qp=e.enum([`MXBAI_EMBED_LARGE_V1`,`TEST`,`STELLA_EN_400M_V5`,`GTE_MULTILINGUAL_BASE`]),Jp=e.enum([`DIM_1024`,`DIM_768`]),Yp=e.string();e.object({id:Yp,createdAt:e.number(),updatedAt:e.number(),hash:e.instanceof(Uint8Array),model:qp,dimension:Jp,vector1024:e.array(e.number()).nullable(),vector768:e.array(e.number()).nullable()}),e.object({id:Yp,createdAt:e.number(),updatedAt:e.number(),hash:e.instanceof(Uint8Array),model:qp,dimension:Jp,vector1024:e.array(e.number()).optional().nullable(),vector768:e.array(e.number()).optional().nullable()}),e.object({id:Yp.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional(),hash:e.instanceof(Uint8Array).optional(),model:qp.optional(),dimension:Jp.optional(),vector1024:e.array(e.number()).optional().nullable(),vector768:e.array(e.number()).optional().nullable()});var Xp=e.string(),Zp=e.string(),Qp=e.string();e.object({tableName:Xp,idA:Zp,idB:Qp,workspaceId:B,deletedAt:e.number(),version:e.number()}),e.object({tableName:Xp,idA:Zp,idB:Qp,workspaceId:B,deletedAt:e.number(),version:e.number()}),e.object({tableName:Xp.optional(),idA:Zp.optional(),idB:Qp.optional(),workspaceId:B.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:B}),e.object({sequenceId:Z,documentId:X,createdAt:e.number(),updatedAt:e.number(),sortOrder:e.number(),version:e.number(),workspaceId:B}),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:B.optional()});var $p=e.enum([`SPRITE_BUILD`]);e.object({useCase:$p,llmModelId:Kf,createdAt:e.number(),updatedAt:e.number()}),e.object({useCase:$p,llmModelId:Kf,createdAt:e.number(),updatedAt:e.number()}),e.object({useCase:$p.optional(),llmModelId:Kf.optional(),createdAt:e.number().optional(),updatedAt:e.number().optional()}),e.object({spriteId:Y,workspaceId:B,hash:e.instanceof(Uint8Array),version:e.number(),updatedAt:e.number(),plaintext:e.string()}),e.object({spriteId:Y,workspaceId:B,hash:e.instanceof(Uint8Array),version:e.number(),updatedAt:e.number(),plaintext:e.string()}),e.object({spriteId:Y.optional(),workspaceId:B.optional(),hash:e.instanceof(Uint8Array).optional(),version:e.number().optional(),updatedAt:e.number().optional(),plaintext:e.string().optional()});var em=e.enum([`SIGNUP`,`PASSWORD_RESET`]),tm=e.string();e.object({id:tm,type:em,userId:U.nullable(),email:H,tokenHash:e.string(),createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number(),verifiedAt:e.number().nullable(),retryCount:e.number()}),e.object({id:tm,type:em,userId:U.optional().nullable(),email:H,tokenHash:e.string(),createdAt:e.number(),updatedAt:e.number(),expiresAt:e.number(),verifiedAt:e.number().optional().nullable(),retryCount:e.number()}),e.object({id:tm.optional(),type:em.optional(),userId:U.optional().nullable(),email:H.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({clientId:e.string(),tableName:e.string(),idA:e.string(),idB:e.string(),version:e.number()}),e.object({id:W,name:e.string(),workspaceId:B,version:e.number(),createdAt:e.number(),updatedAt:e.number(),avatarAssetId:zf.nullable(),description:e.string(),emailList:H.array()}),e.enum([`PENDING`,`CREATED`,`FINISHED`,`TERMINATED`]);var nm=e.number();e.object({id:nm,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:nm.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:nm.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 rm=e.number();e.object({id:rm,ts:e.date(),breaking:e.boolean()}),e.object({id:rm,ts:e.date().optional(),breaking:e.boolean().optional()}),e.object({id:rm.optional(),ts:e.date().optional(),breaking:e.boolean().optional()});var im=e.enum([`IN_PROGRESS`,`SUCCESS`,`ERROR`]),am=e.string();e.object({id:am,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:im,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:am,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:im,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:am.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:im.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 om=e.number();e.object({id:om,identifier:e.string()}),e.object({id:om.optional(),identifier:e.string()}),e.object({id:om.optional(),identifier:e.string().optional()});var sm=e.enum([`MISSING_HEARTBEAT`,`STALE_HEARTBEAT`,`STOPPED_WITH_LOCKS`,`ALREADY_RECOVERED_WITH_LOCKS`]),cm=e.string();e.object({workerPoolId:cm,serviceName:e.string(),machineId:e.string(),startedAt:e.number().nullable(),lastHeartbeatAt:e.number().nullable(),stoppedAt:e.number().nullable(),recoveredAt:e.number().nullable(),recoveryReason:sm.nullable().nullable(),recoveredJobCount:e.number().nullable(),createdAt:e.number(),updatedAt:e.number()}),e.object({workerPoolId:cm,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:sm.nullable().optional().nullable(),recoveredJobCount:e.number().optional().nullable(),createdAt:e.number(),updatedAt:e.number()}),e.object({workerPoolId:cm.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:sm.nullable().optional().nullable(),recoveredJobCount:e.number().optional().nullable(),createdAt:e.number().optional(),updatedAt:e.number().optional()});var lm=e.string();e.object({identifier:lm,knownSince:e.date(),lastExecution:e.date().nullable()}),e.object({identifier:lm,knownSince:e.date(),lastExecution:e.date().optional().nullable()}),e.object({identifier:lm.optional(),knownSince:e.date().optional(),lastExecution:e.date().optional().nullable()});var um=e.number();e.object({id:um,queueName:e.string(),lockedAt:e.date().nullable(),lockedBy:e.string().nullable(),isAvailable:e.boolean()}),e.object({id:um.optional(),queueName:e.string(),lockedAt:e.date().optional().nullable(),lockedBy:e.string().optional().nullable(),isAvailable:e.boolean()}),e.object({id:um.optional(),queueName:e.string().optional(),lockedAt:e.date().optional().nullable(),lockedBy:e.string().optional().nullable(),isAvailable:e.boolean().optional()}),e.object({id:nm,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 dm=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:W}),fm=(e,t=Date.now())=>{let n=dm(t).safeParse(e);return n.success?n.data:Error(r.prettifyError(n.error))},pm=class extends Error{status;constructor(e,t){super(t),this.name=`GatewayHttpError`,this.status=e}},mm=r.object({message:r.string()}),hm=async e=>{let t=`Gateway request failed with status ${e.status}`;try{let n=await e.json(),r=mm.safeParse(n);r.success&&(t=r.data.message)}catch{}return new pm(e.status,t)},gm=async e=>{try{return await e.json()}catch{return Error(`Gateway returned an invalid JSON response`)}},_m=async e=>{let{baseUrl:n,projectId:r,userToken:i}=e,a=await t(()=>fetch(S({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 hm(a);let o=await gm(a);return o instanceof Error?o:fm(o)},vm=r.object({token:r.string(),expiresAt:r.number(),personId:r.string()}),ym=e=>vm.safeParse(e).success,bm=1e3,xm=3e4,Sm=6e4,Cm=e=>Math.min(bm*2**Math.max(e-1,0),xm),wm=(e,t)=>t>=e.expiresAt-Sm,Tm=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()+Cm(a)),e}).finally(()=>{c===s&&(i=void 0)}),i};return{getSessionToken:()=>r&&!wm(r,n())?Promise.resolve(r):i===void 0?u():i,invalidateToken:l,reset:c}},Em=e=>{let{baseUrl:t,projectId:n,fetchUserToken:r,exchangeIdentityTokenForSessionToken:i=_m}=e,a=Tm({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(ym(e)){let t=fm(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()}}},Dm=Symbol(`rough.client.runtime`),Om=e=>{let t=e?.[Dm];if(!t)throw new _t;return t},km=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=Em({baseUrl:r,fetchUserToken:t,projectId:n}),l=Ue(),u=kt(),d=Ot({getRuntime:()=>h}),f=Df({auth:c,baseUrl:r,clientId:i,projectId:n,signal:a.signal,store:l}),p=()=>{if(o===`destroying`||o===`destroyed`)throw new pt},m=(async()=>{await f.start();let e=f.peek();if(!e||a.signal.aborted)return;let t=await se({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`),vt(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=>S({baseUrl:r,...e})},g=async()=>{let e=[],t=async(t,n)=>{try{await n()}catch(n){let r=vt(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 gt({errors:e})},_={get projectId(){return n},destroy:()=>s||(o=`destroying`,f.markDestroying(),a.abort(new pt),s=g(),s)};return Object.defineProperty(_,Dm,{value:h,enumerable:!1,writable:!1,configurable:!1}),Object.freeze(_)},Am=async e=>{await Om(e.client).whenReady()},jm=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,Mm=e=>{let{sprite:t,spriteBuildList:n}=e;return{id:t.id,name:t.name,ownedByPersonId:t.ownedByPersonId,publishedSpriteBuildId:jm(n)?.id??null}},Nm=(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=Mm({sprite:i,spriteBuildList:n.get(i.id)??[]});e.publishedSpriteBuildId&&r.push(e)}return r.toSorted((e,t)=>t.id.localeCompare(e.id))},Pm=e=>{let{client:t,onError:n,onFeatures:r,signal:i}=e,a=Om(t);a.assertUsable();let o=Et(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})),xt(c.signal).then(()=>({type:`aborted`}))]);if(e.type===`aborted`||c.signal.aborted)return;let t=e.resolution.id,n=()=>{c.signal.aborted||r(Nm(a.store,t))};l=a.store.subscribe(n),n()})();f.catch(e=>{c.signal.aborted||n?.(vt(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}},Fm={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`},Im=e=>{for(let t in e)if(t.startsWith(`aria-`)||t===`role`||t===`title`)return!0;return!1},Lm=Symbol(`lucide-context`),Rm=()=>i(Lm),zm=new Set([`$$slots`,`$$events`,`$$legacy`,`$$host`,`name`,`color`,`size`,`strokeWidth`,`absoluteStrokeWidth`,`iconNode`,`children`]),Bm=l.from_svg(`<svg><!><!></svg>`);function Vm(e,t){l.push(t,!0);let n=Rm()??{},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,zm),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=Bm();l.attribute_effect(m,e=>({...Fm,...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()&&!Im(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(Vm,{name:{},color:{},size:{},strokeWidth:{},absoluteStrokeWidth:{},iconNode:{},children:{}},[],[],{mode:`open`});var Hm=new Set([`$$slots`,`$$events`,`$$legacy`,`$$host`]);function Um(e,t){let n=l.rest_props(t,Hm),r=[[`path`,{d:`m5 12 7-7 7 7`}],[`path`,{d:`M12 19V5`}]];Vm(e,l.spread_props({name:`arrow-up`},()=>n,{get iconNode(){return r}}))}l.create_custom_element(Um,{},[],[],{mode:`open`});var Wm=async e=>{let{replicache:n,name:r,prompt:i,toolList:a,surfaceId:o,signal:s}=e;return s?.aborted?Error(`Create sprite aborted`):t(async()=>{let e=ut(),t=ut(),s=r?.trim().length?r:``;return await n.mutate.sprite_create_v1({spriteId:e,spriteBuildId:t,prompt:i,surfaceId:o,name:s,toolList:a.map(e=>e.toJSON()),context:{actionedAt:Date.now()}}),await n.push({now:!0}),{spriteId:e,spriteBuildId:t}})},Gm=async e=>{let{replicache:n,spriteId:r,parentSpriteBuildId:i,prompt:a,signal:o}=e;return o?.aborted?Error(`Create sprite build aborted`):t(async()=>{let e=ut();return await n.mutate.spriteBuild_create_v1({spriteBuildId:e,spriteId:r,parentSpriteBuildId:i,prompt:a}),{spriteBuildId:e}})},Km=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_v1({spriteId:r,spriteBuildId:i,context:{actionedAt:Date.now()}}),await n.push({now:!0}),{spriteId:r,spriteBuildId:i}))},qm=new Set([`$$slots`,`$$events`,`$$legacy`,`$$host`]);function Jm(e,t){let n=l.rest_props(t,qm),r=[[`path`,{d:`M21 12a9 9 0 1 1-6.219-8.56`}]];Vm(e,l.spread_props({name:`loader-circle`},()=>n,{get iconNode(){return r}}))}l.create_custom_element(Jm,{},[],[],{mode:`open`});var Ym=l.from_html(`<span class="loader-circle svelte-galthg" aria-hidden="true"><!></span>`),Xm={hash:`svelte-galthg`,code:`.loader-circle.svelte-galthg {display:inline-flex;
|
|
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(`
|
|
13
|
+
`)},zm=e=>`${e.role}:\n${e.text}`,Bm=(e,t)=>{let n=`
|
|
14
|
+
|
|
15
|
+
---
|
|
16
|
+
|
|
17
|
+
`;return`
|
|
18
|
+
${t.length?`
|
|
19
|
+
# chat history
|
|
20
|
+
|
|
21
|
+
${t.map(zm).join(n)}${n}
|
|
22
|
+
`.trim():``}
|
|
23
|
+
# current user message
|
|
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={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`};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,```)}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(`
|
|
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(`
|
|
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)}">↩</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;
|
|
12
49
|
animation: svelte-galthg-spin 700ms linear infinite;}
|
|
13
50
|
|
|
14
51
|
@keyframes svelte-galthg-spin {
|
|
15
52
|
to {
|
|
16
53
|
transform: rotate(360deg);
|
|
17
54
|
}
|
|
18
|
-
}`};function
|
|
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:'';
|
|
19
56
|
animation: svelte-qp0d57-ellipsis 1.5s steps(4, end) infinite;}
|
|
20
57
|
|
|
21
58
|
@keyframes svelte-qp0d57-ellipsis {
|
|
@@ -23,7 +60,7 @@ with cause:
|
|
|
23
60
|
25% { content: '.'; }
|
|
24
61
|
50% { content: '..'; }
|
|
25
62
|
75% { content: '...'; }
|
|
26
|
-
}`};function dh(e,t){l.push(t,!0),l.append_styles(e,uh);let n=l.prop(t,`activity`,7),r=l.prop(t,`summaryText`,7),i=l.derived(()=>n().status===`ready`||n().status===`error`),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=lh();let c;var u=l.child(s),d=e=>{var t=Qm();l.append(e,t)},f=e=>{var t=ch(),i=l.first_child(t),a=l.child(i),o=l.child(a),s=e=>{var t=$m();l.append(e,t)},c=e=>{var t=eh();l.append(e,t)},u=e=>{var t=nh(),r=l.first_child(t),i=l.child(r,!0);l.reset(r);var a=l.sibling(r,2),o=e=>{var t=th(),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)},d=e=>{var t=rh(),r=l.child(t,!0);l.reset(t),l.template_effect(()=>l.set_text(r,n().phase.name)),l.append(e,t)};l.if(o,e=>{n().status===`ready`?e(s):n().status===`error`?e(c,1):n().action?e(u,2):n().phase&&e(d,3)}),l.reset(a);var f=l.sibling(a,2),p=e=>{var t=ih();Zm(l.child(t),{}),l.reset(t),l.append(e,t)};l.if(f,e=>{n().status===`working`&&!n().toolOutcome&&!n().phase?.outcome&&e(p)}),l.reset(i);var m=l.sibling(i,2),h=e=>{var t=oh(),i=l.child(t,!0),a=l.sibling(i),o=e=>{var t=ah();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)},g=e=>{var t=sh();l.append(e,t)};l.if(m,e=>{r()?e(h):n().status===`working`&&e(g,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(dh,{activity:{},summaryText:{}},[],[],{mode:`open`});var fh=e=>{switch(e.name){case`edit`:return`Editing`;case`write`:return`Writing`;case`read`:return`Reading`;case`bash`:return`Running`;default:return`Using tool`}},ph=(e,t)=>{let n,r,i;for(let t of e){let e=t;switch(e.type){case`AGENT_TOOL_STARTED`:{let{toolCallId:t,tool:i}=e.detail;n={tool:i.name,toolCallId:t,verb:fh(i),filename:`path`in i?i.path:i.command},r=void 0;break}case`AGENT_TOOL_COMPLETED`:n?.toolCallId===e.detail.toolCallId&&(r=`success`);break;case`AGENT_TOOL_FAILED`:n?.toolCallId===e.detail.toolCallId&&(r=`failed`);break;case`AGENT_STARTED`:i={name:`agent`,outcome:void 0};break;case`AGENT_COMPLETED`:i={name:`agent`,outcome:`success`}}}let a;return a=t===`READY`?`ready`:t===`ERROR`?`error`:n||i?`working`:`idle`,{activity:a===`ready`?{status:a}:{status:a,action:n,toolOutcome:r,phase:i}}},mh=l.from_html(`<div class="panel pending svelte-rsawb0"><!> <span>Waiting for build to start</span></div>`),hh=l.from_html(`<div class="build-log svelte-rsawb0"><!></div>`),gh={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 _h(e,t){l.push(t,!0),l.append_styles(e,gh);let n=l.prop(t,`client`,7),r=l.prop(t,`spriteBuild`,7),i=l.derived(()=>Om(n()).store),a=l.derived(()=>$(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(()=>ph(l.get(s),l.get(c))),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=hh(),h=l.child(m),g=e=>{var t=mh();Zm(l.child(t),{}),l.next(2),l.reset(t),l.append(e,t)},_=e=>{dh(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(_h,{client:{},spriteBuild:{}},[],[],{mode:`open`});var vh=100,yh=new Intl.NumberFormat(`en-US`,{style:`currency`,currency:`USD`,minimumFractionDigits:2,maximumFractionDigits:2}),bh=e=>{let t=Math.round(e*vh*10)/10;return Math.abs(t)<vh?`${t.toFixed(1)}c`:yh.format(e)},xh=e=>e.toLowerCase().split(/[_-]+/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `),Sh=e=>{switch(e.name){case`edit`:case`read`:case`write`:return`${e.name} ${e.path}`;case`bash`:return e.command;default:return`tool call`}},Ch=e=>{switch(e?.name){case`bash`:return`command`;case`read`:case`edit`:case`write`:return`path`;default:return`plain`}},wh=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`,bh(e.detail.estimatedCostUsd)].join(` · `)},Th=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=Th(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}},Eh=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=xh(i.detail.stepName),o=`xml-open`,s=`active`;break;case`STEP_COMPLETED`:a=xh(i.detail.stepName),o=`xml-close`,s=`success`;break;case`STEP_FAILED`:a=Th(i.detail.error)??xh(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=Th(i.detail.error)??e?.url,s=`error`;break}case`AGENT_STARTED`:s=`active`;break;case`AGENT_COMPLETED`:s=`success`;break;case`AGENT_USAGE`:a=wh(i),s=`neutral`;break;case`AGENT_TOOL_STARTED`:t.set(i.detail.toolCallId,i.detail.tool),a=Sh(i.detail.tool),o=Ch(i.detail.tool),s=`active`;break;case`AGENT_TOOL_COMPLETED`:{let e=t.get(i.detail.toolCallId);a=e?Sh(e):i.detail.toolCallId,o=Ch(e),s=`success`;break}case`AGENT_TOOL_FAILED`:{let e=t.get(i.detail.toolCallId);a=e?Sh(e):i.detail.toolCallId,o=Ch(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=Th(e.detail),s=`neutral`}return{id:e.id,actionedAt:e.actionedAt,type:e.type,detailText:a,detailStyle:o,tone:s}})},Dh=l.from_html(`<div class="polling-indicator svelte-5iw9fb"><!> <span>Live</span></div>`),Oh=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>`),kh=l.from_html(`<code class="svelte-5iw9fb"><strong class="svelte-5iw9fb"> </strong> </code>`),Ah=l.from_html(`<code class="svelte-5iw9fb"> </code>`),jh=l.from_html(`<div><!></div>`),Mh=l.from_html(`<span class="event-detail-empty svelte-5iw9fb">—</span>`),Nh=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>`),Ph=l.from_html(`<ol class="event-list svelte-5iw9fb"></ol>`),Fh=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>`),Ih={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 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,
|
|
27
64
|
.event-type-cell.svelte-5iw9fb,
|
|
28
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,
|
|
29
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),
|
|
@@ -52,27 +89,35 @@ with cause:
|
|
|
52
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,
|
|
53
90
|
.event-type-cell.svelte-5iw9fb,
|
|
54
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;}
|
|
55
|
-
}`};function
|
|
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,
|
|
56
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);}
|
|
57
94
|
|
|
58
95
|
@media (max-width: 1000px) {.MobileTabBar.svelte-17gs0md {display:block;}
|
|
59
|
-
}`};function
|
|
60
|
-
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
|
|
61
|
-
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 ng(e,t){l.push(t,!0),l.append_styles(e,tg);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=eg();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(ng,{children:{},class:{},type:{},disabled:{},onclick:{},role:{},block:{},iconOnly:{},alignStart:{},"aria-label":{},"aria-haspopup":{},"aria-expanded":{}},[],[],{mode:`open`});var rg=`2.0.0`,ig=`app.rough.frame.server.port`,ag=(e,t)=>!!e&&typeof e==`object`&&`type`in e&&e.type===t&&`version`in e&&typeof e.version==`string`,og=class{serverWindow;getClientWindow;clientOrigin;createSession;createMessageChannel;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)}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){console.warn(`ignoring message from unexpected origin: "${e.origin}"`);return}if(!ag(e.data,`app.rough.frame.client.ready`)){console.warn(`ignoring message with unexpected type: "${e.data.type}"`);return}let t=this.getClientWindow();if(!t||e.source!==t){console.warn(`ignoring message from unexpected source`);return}let n=this.createMessageChannel();this.disposeSession(),this.session=this.createSession(n.port1),t.postMessage({type:ig,version:rg},{targetOrigin:this.clientOrigin,transfer:[n.port2]})};disposeSession(){this.session&&=(this.session[Symbol.dispose]?.(),void 0)}},sg=[{},{}],cg=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()??sg},set(e){t.set(e)},addListener(e){let n=e.dup(),r=t.addListener(n);return()=>{r(),n[Symbol.dispose]()}}}}}},lg=class{containerElement;channelServer;iframeSrc;iframeElement;constructor(e){let{iframe:t,serverWindow:n=globalThis.window,clientOrigin:r=`*`,getTools:i,getBridgeMethodDefinitions:a,store:o}=e,s;if(`contentWindow`in t)this.iframeElement=void 0,s=()=>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),s=()=>this.iframeElement?.contentWindow??void 0}let c=cg({store:o,iframeElement:this.iframeElement,onReportSize:t.onReportSize,getBridgeMethodDefinitions:a});this.channelServer=new og({getClientWindow:s,serverWindow:n,clientOrigin:r,createSession:e=>{let t=i();return f(e,{...t,...c})}})}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)}},ug=l.from_html(`<div><!></div>`);function dg(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=ug(),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(dg,{handle:{},children:{},class:{}},[],[],{mode:`open`});var fg=e=>e.minHeight??100,pg=e=>e.maxHeight??2e3,mg=(e,t)=>Math.min(pg(t),Math.max(fg(t),Math.round(e))),hg={resized:`Resizable--resized`,handle:`Resizable__resize-handle`},gg={triggerPx:60,maxSpeedPx:16},_g=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<gg.triggerPx){let e=Math.min(1,1-r/gg.triggerPx);i(Math.max(1,Math.round(gg.maxSpeedPx*e)))}else o<=0?i(-gg.maxSpeedPx):a()}}},vg=()=>{let e=document.documentElement,t=document.body;return Math.max(e.clientHeight,t?.offsetHeight??0,t?.scrollHeight??0)},yg=()=>{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(vg(),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)}}},bg=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}},xg=e=>({...hg,...e.classNames}),Sg=(e={})=>{let t,n,r,i,a=yg(),o=n=>{if(t){if(i&&=(t.classList.remove(i),void 0),typeof n==`number`){let r=xg(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(mg(i-r.top,e)),a.growToContent()},u=_g({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:bg(t)},r=s,o(mg(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:xg(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}),_},Cg=()=>{let e=new Set;return{addListener(t){return e.add(t),()=>{e.delete(t)}},notify(t){for(let n of e)n(t)}}},wg=e=>e,Tg=e=>e,Eg=e=>e,Dg=e=>({get:()=>Tg(e.get()),set:t=>{e.set(Eg(t))},addListener:t=>e.addListener(e=>{t(wg(e))})}),Og=()=>{let e=Cg(),t;return{get:()=>t,set:n=>{t=n,e.notify(n)},addListener:e.addListener}},kg=(e,t=globalThis.localStorage)=>{let n=Cg(),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}},Ag=({datastore:e,isMock:t,spriteInstanceId:n,storage:r})=>{if(e)return Dg(e);if(t)return Og();if(n)return kg(n,r);throw Error(`SpriteFrame is missing a spriteInstanceId.`)},jg=l.from_html(`<div class="SpriteFrame svelte-ncf2zx"><!></div>`),Mg={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 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));
|
|
62
99
|
/* The frame's iframe sets its own min-height from reportSize, so tall
|
|
63
100
|
content would push past the bounded preview viewport and clip at the
|
|
64
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,
|
|
65
|
-
.SpriteFrame.svelte-ncf2zx .Resizable__resize-handle:active::after {height:4px;background:var(--rough-ring, oklch(0.708 0 0));}`};function
|
|
66
|
-
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
|
|
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] {
|
|
67
104
|
/* note: we must use strict descendant selectors here */
|
|
68
|
-
/* otherwise nested Accordions will not be displayed correctly
|
|
69
|
-
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 Kg(e,t){l.push(t,!0),l.append_styles(e,Gg);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=Wg(),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);Hg(l.child(m),{size:14}),l.reset(m),l.reset(c);var h=l.sibling(c,2),g=e=>{var t=Ug(),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(Kg,{heading:{},preview:{},children:{}},[],[],{mode:`open`});var qg=l.from_html(`<div class="JsonViewer svelte-17yau2j"><andypf-json-viewer></andypf-json-viewer></div>`,2),Jg={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 Yg(e,t){l.push(t,!0),l.append_styles(e,Jg);let n=l.prop(t,`value`,7);var r={get value(){return n()},set value(e){n(e),l.flush()}},i=qg(),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(Yg,{value:{}},[],[],{mode:`open`});var Xg=l.from_html(`<div class="tool-desc svelte-15f985v"> </div>`),Zg=l.from_html(`<div class="tool-list svelte-15f985v"></div>`),Qg=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),$g=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>`),e_=l.from_html(`<div class="tool-card svelte-15f985v"><div class="tool-name svelte-15f985v"> </div> <!></div>`),t_=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>`),n_=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>`),r_={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 i_(e,t){l.push(t,!0),l.append_styles(e,r_);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=n_(),s=l.child(o),c=e=>{var t=Qg();Kg(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=Zg();l.each(n,21,()=>l.get(r),e=>e.name,(e,t)=>{Kg(e,{get heading(){return l.get(t).name},preview:e=>{var n=l.comment(),r=l.first_child(n),i=e=>{var n=Xg(),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=>{Yg(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=$g();l.append(e,t)};return l.if(u,e=>{l.get(r).length>0&&e(d)}),Kg(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=t_(),r=l.child(n);l.each(r,17,()=>l.get(i),e=>e.name,(e,t)=>{var n=e_(),r=l.child(n),i=l.child(r,!0);l.reset(r);var a=l.sibling(r,2),o=e=>{var n=Xg(),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(i_,{toolList:{}},[],[],{mode:`open`});var a_=100,o_=e=>{let t=e.keyStepPx??a_,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)}}},s_=l.from_html(`<p class="svelte-t9dwgq">Loading…</p>`),c_=l.from_html(`<div class="error svelte-t9dwgq"> </div>`),l_=l.from_html(`<div class="system-message-detail svelte-t9dwgq"> </div>`),u_=l.from_html(`<details class="system-message-raw svelte-t9dwgq"><summary class="svelte-t9dwgq">Details</summary> <pre class="svelte-t9dwgq"> </pre></details>`),d_=l.from_html(`<div class="system-message system-message-error svelte-t9dwgq"><div class="system-message-label svelte-t9dwgq"> </div> <!> <!></div>`),f_=l.from_html(`<p class="loading svelte-t9dwgq">Loading…</p>`),p_=l.from_html(`<div class="bubble svelte-t9dwgq"><span class="author svelte-t9dwgq"> </span> <pre class="svelte-t9dwgq"> </pre></div>`),m_=l.from_html(`<span class="published-tag svelte-t9dwgq">Published</span>`),h_=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>`),g_=l.from_html(`<div><!> <!> <!></div>`),__=l.from_html(`<!> <!>`,1),v_=l.from_html(`<div class="preview-placeholder svelte-t9dwgq">Your feature preview will appear here.</div>`),y_=l.from_html(`<div class="preview-placeholder svelte-t9dwgq">Build logs will appear here.</div>`),b_=l.from_html(`<div class="logs-panel svelte-t9dwgq"><!></div>`),x_=l.from_html(`<!> <!> <!>`,1),S_=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> <button type="submit" class="send-button svelte-t9dwgq"><!></button></div></form> <div class="preview-actions svelte-t9dwgq"><!></div> <!></div>`),C_=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>`),w_={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,
|
|
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,
|
|
70
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;}
|
|
71
108
|
|
|
72
109
|
/* Inner wrapper so the ResizeObserver can watch content growth separately
|
|
73
110
|
from the outer scroll container; needed to auto-scroll on streaming logs. */.transcript-content.svelte-t9dwgq {display:flex;gap:1rem;flex-direction:column;padding:0.25rem 0;}.composer.svelte-t9dwgq {display:flex;gap:0.5rem;flex-direction:column;grid-column:1;grid-row:2;}.divider.svelte-t9dwgq {position:relative;grid-column:2;grid-row:1 / span 2;background:transparent;cursor:col-resize;touch-action:none;}.divider.svelte-t9dwgq::before {content:'';position:absolute;top:0;bottom:0;left:50%;width:1px;background:var(--rough-border, oklch(0.922 0 0));transform:translateX(-50%);transition:width 120ms ease, background-color 120ms ease;}.divider.svelte-t9dwgq:hover::before,
|
|
74
111
|
.divider.svelte-t9dwgq:active::before,
|
|
75
|
-
.divider.svelte-t9dwgq:focus-visible::before {width:3px;background:var(--rough-ring, oklch(0.708 0 0));}.divider.svelte-t9dwgq:focus-visible {outline:none;}.preview.svelte-t9dwgq {display:flex;flex-direction:column;grid-column:3;grid-row:1;min-width:0;min-height:0;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-lg, 0.625rem);overflow:hidden;background:var(--rough-card, white);box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));}.preview-actions.svelte-t9dwgq {display:flex;align-items:center;justify-content:flex-end;grid-column:3;grid-row:2;}.desktop-preview-tabs.svelte-t9dwgq {flex:none;}.published-tag.svelte-t9dwgq {display:inline-flex;align-items:center;margin-left:0.5rem;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-sm, 0.25rem);padding:0.05rem 0.4rem;background:var(--rough-secondary, oklch(0.97 0 0));color:var(--rough-secondary-foreground, oklch(0.205 0 0));font-size:0.7rem;font-weight:700;text-transform:uppercase;letter-spacing:0.05em;}.turn-published.svelte-t9dwgq .system-message-ready:where(.svelte-t9dwgq) {border-color:var(--rough-success-border, color-mix(in srgb, #15803d 45%, var(--rough-border, oklch(0.922 0 0))));}.preview-placeholder.svelte-t9dwgq {display:flex;align-items:center;justify-content:center;flex:1;padding:1rem;color:var(--rough-muted-foreground, oklch(0.556 0 0));text-align:center;}.logs-panel.svelte-t9dwgq {display:flex;flex:1;flex-direction:column;min-height:0;padding:0.75rem;overflow:auto;}.turn.svelte-t9dwgq
|
|
112
|
+
.divider.svelte-t9dwgq:focus-visible::before {width:3px;background:var(--rough-ring, oklch(0.708 0 0));}.divider.svelte-t9dwgq:focus-visible {outline:none;}.preview.svelte-t9dwgq {display:flex;flex-direction:column;grid-column:3;grid-row:1;min-width:0;min-height:0;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-lg, 0.625rem);overflow:hidden;background:var(--rough-card, white);box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));}.preview-actions.svelte-t9dwgq {display:flex;align-items:center;justify-content:flex-end;grid-column:3;grid-row:2;}.desktop-preview-tabs.svelte-t9dwgq {flex:none;}.published-tag.svelte-t9dwgq {display:inline-flex;align-items:center;margin-left:0.5rem;border:1px solid var(--rough-border, oklch(0.922 0 0));border-radius:var(--rough-radius-sm, 0.25rem);padding:0.05rem 0.4rem;background:var(--rough-secondary, oklch(0.97 0 0));color:var(--rough-secondary-foreground, oklch(0.205 0 0));font-size:0.7rem;font-weight:700;text-transform:uppercase;letter-spacing:0.05em;}.turn-published.svelte-t9dwgq .system-message-ready:where(.svelte-t9dwgq) {border-color:var(--rough-success-border, color-mix(in srgb, #15803d 45%, var(--rough-border, oklch(0.922 0 0))));}.preview-placeholder.svelte-t9dwgq {display:flex;align-items:center;justify-content:center;flex:1;padding:1rem;color:var(--rough-muted-foreground, oklch(0.556 0 0));text-align:center;}.logs-panel.svelte-t9dwgq {display:flex;flex:1;flex-direction:column;min-height:0;padding:0.75rem;overflow:auto;}.turn.svelte-t9dwgq,
|
|
113
|
+
.chat-message.svelte-t9dwgq {display:flex;gap:0.5rem;flex-direction:column;}.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) {align-self:flex-start;background:var(--rough-muted, oklch(0.97 0 0));color:var(--rough-foreground, oklch(0.145 0 0));font-size:0.875rem;line-height:1.45;overflow-wrap:anywhere;}.chat-message-assistant.svelte-t9dwgq .author:where(.svelte-t9dwgq) {color:var(--rough-muted-foreground, oklch(0.556 0 0));}.bubble.svelte-t9dwgq {display:flex;align-self:flex-end;gap:0.35rem;flex-direction:column;max-width:85%;border-radius:var(--rough-radius-lg, 0.625rem);padding:0.65rem 0.85rem;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);}.author.svelte-t9dwgq {color:color-mix(in oklch, var(--rough-primary-foreground, white) 75%, transparent);font-size:0.75rem;}.bubble-text.svelte-t9dwgq {color:inherit;font-size:0.875rem;line-height:1.45;white-space:pre-wrap;overflow-wrap:anywhere;}.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) p {margin:0.5rem 0;}.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) h1,
|
|
114
|
+
.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) h2,
|
|
115
|
+
.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) h3,
|
|
116
|
+
.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) h4,
|
|
117
|
+
.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) h5,
|
|
118
|
+
.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) h6 {margin:0.75rem 0 0.35rem;font-size:1em;}.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) h1 {font-size:1.25em;}.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) h2 {font-size:1.15em;}.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) ul,
|
|
119
|
+
.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) ol {margin:0.5rem 0;padding-left:1.25rem;}.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) a {color:var(--rough-primary, oklch(0.205 0 0));text-decoration:underline;text-underline-offset:0.15em;}.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) blockquote {margin:0.5rem 0;border-left:3px solid var(--rough-border, oklch(0.922 0 0));padding-left:0.75rem;color:var(--rough-muted-foreground, oklch(0.556 0 0));}.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) table {width:100%;margin:0.5rem 0;border-collapse:collapse;font-size:0.8125rem;}.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) th,
|
|
120
|
+
.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) td {border:1px solid var(--rough-border, oklch(0.922 0 0));padding:0.3rem 0.45rem;text-align:left;}.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) th {background:var(--rough-background, white);}.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) code {border-radius:var(--rough-radius-sm, 0.25rem);padding:0.1em 0.25em;background:var(--rough-background, white);font-family:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;font-size:0.85em;}.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) pre {margin:0.5rem 0;border-radius:var(--rough-radius-md, 0.375rem);padding:0.75rem;overflow-x:auto;background:var(--rough-background, white);}.chat-message-assistant.svelte-t9dwgq .bubble:where(.svelte-t9dwgq) pre code {padding:0;background:transparent;}.system-message.svelte-t9dwgq {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));}.system-message-button.svelte-t9dwgq {appearance:none;width:100%;border:none;padding:0;background:transparent;font:inherit;text-align:left;cursor:pointer;}.system-message-button.svelte-t9dwgq:focus-visible {border-radius:var(--rough-radius-md, 0.375rem);outline:none;box-shadow:0 0 0 3px color-mix(in oklch, var(--rough-ring, oklch(0.708 0 0)) 45%, transparent);}.system-message-label.svelte-t9dwgq {color:var(--rough-foreground, oklch(0.145 0 0));font-weight:600;}.system-message-ready.svelte-t9dwgq {border-color:var(--rough-success-border, color-mix(in srgb, #15803d 45%, var(--rough-border, oklch(0.922 0 0))));background:var(--rough-success-background, color-mix(in srgb, #15803d 12%, var(--rough-card, white)));}.system-message-ready.svelte-t9dwgq .system-message-label:where(.svelte-t9dwgq) {color:var(--rough-success, #15803d);}.system-message-error.svelte-t9dwgq {border-color:color-mix(in oklch, var(--rough-destructive, oklch(0.577 0.245 27.325)) 35%, var(--rough-border, oklch(0.922 0 0)));background:color-mix(in oklch, var(--rough-destructive, oklch(0.577 0.245 27.325)) 8%, var(--rough-card, white));}.system-message-error.svelte-t9dwgq .system-message-label:where(.svelte-t9dwgq) {color:var(--rough-destructive, oklch(0.577 0.245 27.325));}.system-message-detail.svelte-t9dwgq {color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:0.875rem;line-height:1.45;word-break:break-word;}.system-message-raw.svelte-t9dwgq {font-size:0.85rem;}.system-message-raw.svelte-t9dwgq summary:where(.svelte-t9dwgq) {color:var(--rough-muted-foreground, oklch(0.556 0 0));cursor:pointer;}.system-message-raw.svelte-t9dwgq pre:where(.svelte-t9dwgq) {margin:0.4rem 0 0;border-radius:var(--rough-radius-md, 0.375rem);padding:0.5rem 0.65rem;overflow-x:auto;background:var(--rough-muted, oklch(0.97 0 0));color:var(--rough-foreground, oklch(0.145 0 0));font-size:0.8rem;white-space:pre-wrap;word-break:break-word;}.composer-input.svelte-t9dwgq {display:flex;align-items:flex-end;gap:0.5rem;border:1px solid var(--rough-input, oklch(0.922 0 0));border-radius:var(--rough-radius-lg, 0.625rem);padding:0.5rem 0.5rem 0.5rem 0.85rem;background:var(--rough-background, white);box-shadow:var(--rough-shadow-xs, 0 1px 2px rgb(0 0 0 / 0.05));transition:border-color 120ms ease, box-shadow 120ms ease;}.composer-input.svelte-t9dwgq:focus-within {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);}.composer-input.isBuilding.svelte-t9dwgq textarea:where(.svelte-t9dwgq) {opacity:0.75;}textarea.svelte-t9dwgq {flex:1;min-width:0;min-height:1.5rem;max-height:12rem;border:none;outline:none;padding:0.35rem 0;overflow-y:auto;background:transparent;color:var(--rough-foreground, oklch(0.145 0 0));font:inherit;font-size:0.875rem;line-height:1.45;resize:none;}textarea.svelte-t9dwgq::placeholder {color:var(--rough-muted-foreground, oklch(0.556 0 0));}.send-button.svelte-t9dwgq {display:inline-flex;align-items:center;justify-content:center;flex:none;width:2.25rem;height:2.25rem;border:1px solid var(--rough-primary, oklch(0.205 0 0));border-radius:999px;padding:0;background:var(--rough-primary, oklch(0.205 0 0));color:var(--rough-primary-foreground, white);cursor:pointer;transition:background-color 120ms ease, border-color 120ms ease,
|
|
76
121
|
box-shadow 120ms ease, transform 120ms ease, opacity 120ms ease;}.send-button.svelte-t9dwgq:hover:not(:disabled) {background:color-mix(in oklch, var(--rough-primary, oklch(0.205 0 0)) 90%, transparent);}.send-button.svelte-t9dwgq:active:not(:disabled) {transform:scale(0.95);}.send-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);}.send-button.svelte-t9dwgq:disabled {opacity:0.5;cursor:not-allowed;}.loading.svelte-t9dwgq {margin:0;color:var(--rough-muted-foreground, oklch(0.556 0 0));font-size:0.875rem;}.surface.svelte-t9dwgq > p:where(.svelte-t9dwgq) {flex:1;margin:0;padding:1rem 1.25rem;color:var(--rough-muted-foreground, oklch(0.556 0 0));}
|
|
77
122
|
|
|
78
123
|
@media (max-width: 1000px) {.feature-builder.svelte-t9dwgq {grid-template-columns:1fr;}.desktop-preview-tabs.svelte-t9dwgq,
|
|
@@ -85,6 +130,6 @@ with cause:
|
|
|
85
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),
|
|
86
131
|
.feature-builder.tab-capabilities.svelte-t9dwgq .preview-actions:where(.svelte-t9dwgq),
|
|
87
132
|
.feature-builder.tab-logs.svelte-t9dwgq .preview-actions:where(.svelte-t9dwgq) {display:flex;grid-column:1;grid-row:2;}
|
|
88
|
-
}`};function T_(e,t){l.push(t,!0),l.append_styles(e,w_);let n=l.prop(t,`client`,7),r=l.prop(t,`surface`,7),i=l.prop(t,`portalTarget`,7),a=l.prop(t,`onclose`,7),o=l.prop(t,`action`,7),s=l.derived(()=>Om(n())),c=l.derived(()=>l.get(s).store),f=l.derived(()=>r().tools),p=l.state(!0),m=l.state(void 0),h=l.derived(()=>$(l.get(c).meta.get(Ve))),g=l.derived(()=>l.get(h)._),_=l.derived(()=>l.get(g)?.state===`READY`),v=l.derived(()=>o().type===`edit`?o().spriteId:l.get(m)),y=l.derived(()=>l.get(v)?$(l.get(c).sprite.get(l.get(v))):$.undefined),b=l.derived(()=>l.get(y)._),ee=l.derived(()=>$(l.get(c).person.asList)),x=l.derived(()=>l.get(ee)._),te=l.derived(()=>l.get(v)?$(l.get(c).spriteBuild.filter(`sprite:${l.get(v)}`,e=>e.spriteId===l.get(v))):$.lit([])),ne=l.derived(()=>l.get(te)._),re=l.derived(()=>{if(l.get(b))return Mm({sprite:l.get(b),spriteBuildList:l.get(ne)})}),ie=l.derived(()=>o().type===`edit`&&!l.get(_)),ae=l.derived(()=>{if(!(o().type!==`edit`||!l.get(_)||l.get(b)))return Error(`Sprite "${o().spriteId}" not found`)}),oe=l.state(!1),S=l.state(void 0),se=l.state(void 0),ce=l.state(void 0),C=l.derived(()=>l.get(oe)||l.get(S)!=null&&l.get(S).status!==`READY`&&l.get(S).status!==`ERROR`&&!l.get(ce)),w=e=>{l.set(S,e,!0),l.set(se,e.id,!0),Le.add(e.id)},T=l.derived(()=>l.get(se)?$(l.get(c).spriteBuild.get(l.get(se))):$.undefined),le=l.derived(()=>l.get(T)._);l.user_effect(()=>{let e=l.get(le);e&&(e.id===l.get(se)&&JSON.stringify(l.get(S))!==JSON.stringify(e)&&l.set(S,e,!0),(e.status===`READY`||e.status===`ERROR`)&&l.set(se,void 0))});let ue=[{key:`preview`,label:`Preview`},{key:`capabilities`,label:`Capabilities`},{key:`logs`,label:`Logs`}],de=[{key:`chat`,label:`Chat`},...ue],fe=l.state(`chat`),pe=l.state(`capabilities`),me=l.derived(()=>l.get(fe)===`chat`),he=l.derived(()=>l.get(fe)===`capabilities`),ge=l.derived(()=>l.get(fe)===`preview`),_e=l.derived(()=>l.get(fe)===`logs`),ve=l.derived(()=>l.get(pe)===`capabilities`),ye=l.derived(()=>l.get(pe)===`preview`),E=l.derived(()=>l.get(pe)===`logs`),be=l.state(``),xe=l.state(void 0),Se=l.state(void 0),Ce=l.state(void 0),we=l.state(void 0),D=l.state(void 0),Te=o_({getContainer:()=>l.get(D),minColumnPx:280,dividerWidthPx:12}),Ee=l.derived(()=>{if(Te.widthPx===void 0||!l.get(D))return;let e=l.get(D).getBoundingClientRect().width;if(e)return Math.round(Te.widthPx/e*100)}),De=l.derived(()=>{let e=new u;for(let t of l.get(ne))e.set(t.id,t);return l.get(S)&&e.set(l.get(S).id,l.get(S)),[...e.values()].sort((e,t)=>e.id.localeCompare(t.id))}),Oe=!1,ke=e=>{l.set(Se,e,!0),Oe=!0,l.set(pe,`preview`),l.set(fe,`preview`)},Ae=l.derived(()=>l.get(De).findLast(e=>e.status===`READY`&&e.artifactUrl)),je=l.derived(()=>{if(l.get(Se)){let e=l.get(De).find(e=>e.id===l.get(Se));if(e)return e}return l.get(Ae)??l.get(De).at(-1)}),Me=l.derived(()=>l.get(je)?.status===`READY`&&l.get(je).artifactUrl?l.get(je):void 0),Ne=l.derived(()=>l.get(Me)??l.get(Ae)),Pe=!1;l.user_effect(()=>{!Pe&&l.get(Ae)&&(l.set(fe,`preview`),l.set(pe,`preview`),Pe=!0)}),l.user_effect(()=>{if(l.get(De).length===0){l.set(Se,void 0),Oe=!1;return}(!Oe||!l.get(Se)||!l.get(De).some(e=>e.id===l.get(Se)))&&(l.set(Se,l.get(Ae)?.id??l.get(De).at(-1)?.id,!0),Oe=!1)});let Fe=l.derived(()=>l.get(Ae)?.id),Ie=l.derived(()=>jm(l.get(ne))),Le=new d,Re=l.state(void 0),ze=l.derived(()=>l.get(Re)??l.get(Ie)?.id??void 0),Be=l.derived(()=>!l.get(C)&&l.get(Ne)!=null&&l.get(Ne).id!==l.get(ze)),He=l.derived(()=>l.get(ze)!==l.get(Fe)),Ue=l.state(!1),We=l.state(void 0),Ge=l.state(!1),Ke=l.state(!1),qe=async()=>{if(!(!l.get(re)||!l.get(Ne)||l.get(Ue))){l.set(Ue,!0),l.set(We,void 0);try{let e=await Km({replicache:await l.get(s).getReplicache(),spriteId:l.get(re).id,spriteBuildId:l.get(Ne).id});if(e instanceof Error){l.set(We,e,!0);return}l.set(Re,e.spriteBuildId,!0),l.set(Ge,!1)}finally{l.set(Ue,!1)}}},Je=()=>{l.set(p,!1)},Ye=()=>{l.get(He)?l.set(Ge,!0):Je()},Xe=()=>{l.set(Ge,!1),Je()},Ze=()=>{l.set(Ge,!1)},Qe=e=>{if(e){if(typeof e.message==`string`)return e.message;if(typeof e.error==`string`)return e.error}},$e=e=>l.get(x).find(t=>t.id===e.createdByPersonId)?.name??``,et=l.derived(()=>!l.get(C)&&l.get(be).trim().length>0),tt=async e=>{e.preventDefault();let t=l.get(be).trim();if(!(!t||l.get(C))){l.set(be,``),l.set(ce,void 0),l.set(oe,!0);try{let e=await l.get(s).getReplicache();if(o().type===`create`&&!l.get(re)){let n=await Wm({replicache:e,toolList:l.get(f),prompt:t,surfaceId:o().surfaceId});if(n instanceof Error){l.set(ce,n,!0);return}l.set(m,n.spriteId,!0);let r=l.get(c).spriteBuild.get(n.spriteBuildId).value;r?w(r):l.set(se,n.spriteBuildId,!0);return}if(!l.get(Fe)){l.set(ce,Error(`Missing parent build id`),!0);return}if(!l.get(re)){l.set(ce,Error(`No sprite?`),!0);return}let n=await Gm({replicache:e,spriteId:l.get(re).id,parentSpriteBuildId:l.get(Fe),prompt:t});if(n instanceof Error){l.set(ce,n,!0);return}let r=l.get(c).spriteBuild.get(n.spriteBuildId).value;r?w(r):l.set(se,n.spriteBuildId,!0)}finally{l.set(oe,!1)}}},nt=e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),tt(e))};return l.user_effect(()=>{l.get(fe)!==`chat`&&l.set(pe,l.get(fe),!0)}),l.user_effect(()=>{let e=l.get(xe);e&&(l.get(be),e.style.height=`auto`,e.style.height=`${e.scrollHeight}px`)}),l.user_effect(()=>{let e=l.get(we),t=l.get(Ce);if(!e||!t)return;let n=new ResizeObserver(()=>{t.scrollTop=t.scrollHeight});return n.observe(e),()=>n.disconnect()}),$h(e,{get target(){return i()},oncancel:Ye,get onclose(){return a()},get isOpen(){return l.get(p)},set isOpen(e){l.set(p,e,!0)},children:(e,t)=>{var r=C_();let i;var a=l.child(r),o=l.child(a),s=l.child(o,!0);l.reset(o);var c=l.sibling(o,2);l.reset(a);var u=l.sibling(a,2),d=e=>{var t=s_();l.append(e,t)},p=e=>{var t=c_(),n=l.child(t,!0);l.reset(t),l.template_effect(()=>l.set_text(n,l.get(ae).message)),l.append(e,t)},m=e=>{var t=S_();let r,i;{let e=(e,t=l.noop,n=l.noop,r=l.noop)=>{var i=d_(),a=l.child(i),o=l.child(a,!0);l.reset(a);var s=l.sibling(a,2),c=e=>{var t=l_(),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=u_(),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)};var a=l.child(t),o=l.child(a),s=l.child(o),c=e=>{var t=f_();l.append(e,t)},u=t=>{var r=__(),i=l.first_child(r);l.each(i,19,()=>l.get(De),e=>e.id,(t,r,i)=>{let a=l.derived(()=>l.get(r).id===l.get(ze));var o=g_();let s;var c=l.child(o),u=e=>{var t=p_(),n=l.child(t),i=l.child(n,!0);l.reset(n);var a=l.sibling(n,2),o=l.child(a,!0);l.reset(a),l.reset(t),l.template_effect(e=>{l.set_text(i,e),l.set_text(o,l.get(r).prompt)},[()=>$e(l.get(r))]),l.append(e,t)};l.if(c,e=>{l.get(r).prompt&&e(u)});var d=l.sibling(c,2);_h(d,{get client(){return n()},get spriteBuild(){return l.get(r)}});var f=l.sibling(d,2),p=e=>{var t=h_(),n=l.child(t),o=l.child(n),s=l.child(o),c=l.sibling(s),u=e=>{var t=m_();l.append(e,t)};l.if(c,e=>{l.get(a)&&e(u)}),l.reset(o),l.reset(n),l.reset(t),l.template_effect(()=>l.set_text(s,`Version ${l.get(i)+1} ready `)),l.delegated(`click`,n,()=>ke(l.get(r).id)),l.append(e,t)},m=t=>{{let n=l.derived(()=>Qe(l.get(r).error));e(t,()=>`Version ${l.get(i)+1} failed`,()=>l.get(n),()=>l.get(r).error)}};l.if(f,e=>{l.get(r).status===`READY`?e(p):l.get(r).status===`ERROR`&&e(m,1)}),l.reset(o),l.template_effect(()=>s=l.set_class(o,1,`turn svelte-t9dwgq`,null,s,{"turn-published":l.get(a)})),l.append(t,o)});var a=l.sibling(i,2),o=t=>{e(t,()=>`Couldn't send message`,()=>l.get(ce).message)};l.if(a,e=>{l.get(ce)&&e(o)}),l.append(t,r)};l.if(s,e=>{l.get(De).length===0&&l.get(oe)?e(c):e(u,-1)}),l.reset(o),l.bind_this(o,e=>l.set(we,e),()=>l.get(we)),l.reset(a),l.bind_this(a,e=>l.set(Ce,e),()=>l.get(Ce));var d=l.sibling(a,2);l.set_attribute(d,`aria-valuemin`,0),l.set_attribute(d,`aria-valuemax`,100);var p=l.sibling(d,2),m=l.child(p);Lg(l.child(m),{get tabs(){return ue},get active(){return l.get(pe)},set active(e){l.set(pe,e,!0)}}),l.reset(m);var h=l.sibling(m,2),g=t=>{e(t,()=>`Couldn't publish version`,()=>l.get(We).message)};l.if(h,e=>{l.get(We)&&e(g)});var _=l.sibling(h,2);Bg(_,{get isActive(){return l.get(ve)},children:(e,t)=>{i_(e,{get toolList(){return l.get(f)}})},$$slots:{default:!0}});var v=l.sibling(_,2);Bg(v,{get isActive(){return l.get(ye)},children:(e,t)=>{var n=l.comment(),r=l.first_child(n),i=e=>{{let t=l.derived(()=>l.get(je).artifactUrl??void 0);Ng(e,{get toolList(){return l.get(f)},get spriteId(){return l.get(re).id},get spriteBuildId(){return l.get(je).id},get artifactUrl(){return l.get(t)},spriteInstanceId:void 0,isMock:!0})}},a=e=>{var t=v_();l.append(e,t)};l.if(r,e=>{l.get(re)&&l.get(je)?.status===`READY`&&l.get(je).artifactUrl?e(i):e(a,-1)}),l.append(e,n)},$$slots:{default:!0}}),Bg(l.sibling(v,2),{get isActive(){return l.get(E)},children:(e,t)=>{var r=b_(),i=l.child(r),a=e=>{Lh(e,{get client(){return n()},get spriteBuild(){return l.get(je)}})},o=e=>{var t=y_();l.append(e,t)};l.if(i,e=>{l.get(je)?e(a):e(o,-1)}),l.reset(r),l.append(e,r)},$$slots:{default:!0}}),l.reset(p);var y=l.sibling(p,2),b=l.child(y);let r;var ee=l.child(b);l.remove_textarea_child(ee),l.bind_this(ee,e=>l.set(xe,e),()=>l.get(xe));var x=l.sibling(ee,2),te=l.child(x),ne=e=>{Zm(e,{})},ie=e=>{Um(e,{size:16,"aria-hidden":`true`})};l.if(te,e=>{l.get(C)?e(ne):e(ie,-1)}),l.reset(x),l.reset(b),l.reset(y);var ae=l.sibling(y,2),S=l.child(ae);{let e=l.derived(()=>!l.get(Be)||l.get(Ue));Yh(S,{get disabled(){return l.get(e)},onclick:()=>void qe(),children:(e,t)=>{l.next();var n=l.text();l.template_effect(()=>l.set_text(n,l.get(Ue)?`Publishing…`:`Publish`)),l.append(e,n)},$$slots:{default:!0}})}l.reset(ae);var se=l.sibling(ae,2),w=e=>{Hh(e,{title:`Publish before closing?`,detail:`You have iterations from this session that aren't published yet.`,get error(){return l.get(We)},actions:e=>{var t=x_(),n=l.first_child(t);ng(n,{onclick:Ze,children:(e,t)=>{l.next();var n=l.text(`Keep editing`);l.append(e,n)},$$slots:{default:!0}});var r=l.sibling(n,2);ng(r,{onclick:Xe,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(Be)||l.get(Ue));Yh(i,{get disabled(){return l.get(e)},onclick:()=>void qe(),children:(e,t)=>{l.next();var n=l.text();l.template_effect(()=>l.set_text(n,l.get(Ue)?`Publishing…`:`Publish`)),l.append(e,n)},$$slots:{default:!0}})}l.append(e,t)},$$slots:{actions:!0}})};l.if(se,e=>{l.get(Ge)&&e(w)}),l.reset(t),l.bind_this(t,e=>l.set(D,e),()=>l.get(D)),l.template_effect(()=>{l.set_attribute(d,`aria-valuenow`,l.get(Ee)),r=l.set_class(b,1,`composer-input svelte-t9dwgq`,null,r,{isBuilding:l.get(C)}),ee.disabled=l.get(C),x.disabled=!l.get(et),l.set_attribute(x,`aria-label`,l.get(C)?`Building`:`Send message`)}),l.delegated(`pointerdown`,d,function(...e){Te.onpointerdown?.apply(this,e)}),l.delegated(`pointermove`,d,function(...e){Te.onpointermove?.apply(this,e)}),l.delegated(`pointerup`,d,function(...e){Te.onpointerup?.apply(this,e)}),l.event(`pointercancel`,d,function(...e){Te.onpointercancel?.apply(this,e)}),l.delegated(`keydown`,d,function(...e){Te.onkeydown?.apply(this,e)}),l.event(`submit`,y,tt),l.delegated(`keydown`,ee,nt),l.bind_value(ee,()=>l.get(be),e=>l.set(be,e))}l.template_effect(()=>{r=l.set_class(t,1,`feature-builder svelte-t9dwgq`,null,r,{"tab-chat":l.get(me),"tab-preview":l.get(ge),"tab-capabilities":l.get(he),"tab-logs":l.get(_e)}),i=l.set_style(t,``,i,{"--chat-column":Te.column})}),l.append(e,t)};l.if(u,e=>{l.get(ie)?e(d):l.get(ae)?e(p,1):e(m,-1)}),Kh(l.sibling(u,2),{get tabs(){return de},ariaLabel:`Feature builder sections`,get active(){return l.get(fe)},set active(e){l.set(fe,e,!0)}}),l.reset(r),l.template_effect(()=>{i=l.set_class(r,1,`surface svelte-t9dwgq`,null,i,{"rough-dark":l.get(Ke)}),l.set_text(s,`⌥ ${l.get(re)?.name??`Rough`}`)}),l.delegated(`pointerup`,o,e=>{e.altKey&&l.set(Ke,!l.get(Ke))}),l.delegated(`click`,c,Ye),l.append(e,r)},$$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 portalTarget(){return i()},set portalTarget(e){i(e),l.flush()},get onclose(){return a()},set onclose(e){a(e),l.flush()},get action(){return o()},set action(e){o(e),l.flush()}})}l.delegate([`pointerup`,`click`,`pointerdown`,`pointermove`,`keydown`]),l.create_custom_element(T_,{client:{},surface:{},portalTarget:{},onclose:{},action:{}},[],[],{mode:`open`});function E_(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()}));T_(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(E_,{client:{},surface:{},surfaceId:{},portalTarget:{},onclose:{}},[],[]));var D_=async e=>{let{client:t,signal:n}=e,r=Om(t);r.assertUsable();let i=Et(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 pt(`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 pt(`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})),xt(l.signal).then(()=>({type:`aborted`}))]);if(e.type===`aborted`||l.signal.aborted)throw new pt(`The Rough client was destroyed before the create modal could open`);r.assertUsable(),d=document.createElement(`div`),o.appendChild(d),u=a(E_,{target:d,props:{client:t,surface:i,surfaceId:e.resolution.id,onclose:()=>{m()}}})}catch(e){throw await m(),e}return{close:m}};function O_(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()}));T_(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(O_,{client:{},surface:{},spriteId:{},portalTarget:{},onclose:{}},[],[]));var k_=l.from_html(`<!> <!>`,1);function A_(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=k_(),f=l.first_child(d);Yh(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=>{O_(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(A_,{client:{},surface:{},spriteId:{},label:{}},[],[]));var j_=`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`,M_=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),N_={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 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),
|
|
89
134
|
.chrome.svelte-1aurlo0:focus-within .badge:where(.svelte-1aurlo0),
|
|
90
|
-
.chrome.svelte-1aurlo0:active .badge:where(.svelte-1aurlo0) {opacity:1;pointer-events:auto;}`};function
|
|
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};
|