@spikonado/sprocket 0.3.5 → 0.3.6
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/package.json +6 -6
- package/web/_app/immutable/chunks/{BXqRSpcY.js → B3_FWG8N.js} +1 -1
- package/web/_app/immutable/chunks/BAh8Fpli.js +1 -0
- package/web/_app/immutable/chunks/{Cg61rval.js → BS_wiDNx.js} +1 -1
- package/web/_app/immutable/chunks/CRHDxlx_.js +1 -0
- package/web/_app/immutable/chunks/{8ja8ideL.js → CU6m3OBu.js} +1 -1
- package/web/_app/immutable/chunks/{BCyOt2Hb.js → DZvbIz22.js} +1 -1
- package/web/_app/immutable/entry/{app.p09_6ljP.js → app.B9ssF-vY.js} +2 -2
- package/web/_app/immutable/entry/start.Cno7DLMd.js +1 -0
- package/web/_app/immutable/nodes/{0.DNlVkUTR.js → 0.DyTUEcgT.js} +1 -1
- package/web/_app/immutable/nodes/{1.C8vYwV-q.js → 1.0Sp3BLHM.js} +1 -1
- package/web/_app/immutable/nodes/2.BkRttGcw.js +129 -0
- package/web/_app/immutable/nodes/{3.CFC3g_PW.js → 3.CTqAObMQ.js} +1 -1
- package/web/_app/immutable/nodes/{4.CdEG0mau.js → 4.BPSJjhC0.js} +1 -1
- package/web/_app/version.json +1 -1
- package/web/callback.html +12 -12
- package/web/index.html +10 -10
- package/web/pair.html +12 -12
- package/web/_app/immutable/assets/2.CMU7pdv8.css +0 -1
- package/web/_app/immutable/chunks/OfCZdkp2.js +0 -1
- package/web/_app/immutable/chunks/lkANnrdY.js +0 -1
- package/web/_app/immutable/entry/start.DcnYmsm2.js +0 -1
- package/web/_app/immutable/nodes/2.Dn01jiUT.js +0 -129
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@spikonado/sprocket",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.6",
|
|
4
4
|
"description": "Agentic platform for streamlining hardware and software development",
|
|
5
5
|
"license": "FSL-1.1-ALv2",
|
|
6
6
|
"type": "module",
|
|
@@ -30,10 +30,10 @@
|
|
|
30
30
|
"access": "public"
|
|
31
31
|
},
|
|
32
32
|
"optionalDependencies": {
|
|
33
|
-
"@spikonado/sprocket-linux-x64-gnu": "0.3.
|
|
34
|
-
"@spikonado/sprocket-linux-arm64-gnu": "0.3.
|
|
35
|
-
"@spikonado/sprocket-darwin-x64": "0.3.
|
|
36
|
-
"@spikonado/sprocket-darwin-arm64": "0.3.
|
|
37
|
-
"@spikonado/sprocket-win32-x64-msvc": "0.3.
|
|
33
|
+
"@spikonado/sprocket-linux-x64-gnu": "0.3.6",
|
|
34
|
+
"@spikonado/sprocket-linux-arm64-gnu": "0.3.6",
|
|
35
|
+
"@spikonado/sprocket-darwin-x64": "0.3.6",
|
|
36
|
+
"@spikonado/sprocket-darwin-arm64": "0.3.6",
|
|
37
|
+
"@spikonado/sprocket-win32-x64-msvc": "0.3.6"
|
|
38
38
|
}
|
|
39
39
|
}
|
|
@@ -61,7 +61,7 @@ var e;function t(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod
|
|
|
61
61
|
|
|
62
62
|
`)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},o,s=g,l=!i.jitless,u=l&&re.value,d=t.catchall,f;e._zod.parse=(i,c)=>{f??=r.value;let p=i.value;return s(p)?l&&u&&c?.async===!1&&c.jitless!==!0?(o||=a(t.shape),i=o(i,c),d?fn([],p,i,c,f,e):i):n(i,c):(i.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),i)}});function hn(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!x(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>w(e,r,a())))}),t)}var gn=t(`$ZodUnion`,(e,t)=>{A.init(e,t),p(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),p(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),p(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),p(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>u(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>hn(t,r,e,i)):hn(o,r,e,i)}}),_n=t(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=!1,gn.init(e,t);let n=e._zod.parse;p(e._zod,`propValues`,()=>{let e={};for(let n of t.options){let r=n._zod.propValues;if(!r||Object.keys(r).length===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(let[t,n]of Object.entries(r)){e[t]||(e[t]=new Set);for(let r of n)e[t].add(r)}}return e});let r=c(()=>{let e=t.options,n=new Map;for(let r of e){let e=r._zod.propValues?.[t.discriminator];if(!e||e.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(let t of e){if(n.has(t))throw Error(`Duplicate discriminator value "${String(t)}"`);n.set(t,r)}}return n});e._zod.parse=(i,a)=>{let o=i.value;if(!g(o))return i.issues.push({code:`invalid_type`,expected:`object`,input:o,inst:e}),i;let s=r.value.get(o?.[t.discriminator]);return s?s._zod.run(i,a):t.unionFallback||a.direction===`backward`?n(i,a):(i.issues.push({code:`invalid_union`,errors:[],note:`No matching discriminator`,discriminator:t.discriminator,options:Array.from(r.value.keys()),input:o,path:[t.discriminator],inst:e}),i)}}),vn=t(`$ZodIntersection`,(e,t)=>{A.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>bn(e,t,n)):bn(e,i,a)}});function yn(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(_(e)&&_(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=yn(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=yn(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function bn(e,t,n){let r=new Map,i;for(let n of t.issues)if(n.code===`unrecognized_keys`){i??=n;for(let e of n.keys)r.has(e)||r.set(e,{}),r.get(e).l=!0}else e.issues.push(n);for(let t of n.issues)if(t.code===`unrecognized_keys`)for(let e of t.keys)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(t);let a=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(a.length&&i&&e.issues.push({...i,keys:a}),x(e))return e;let o=yn(t.value,n.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}var xn=t(`$ZodRecord`,(e,t)=>{A.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!_(i))return n.issues.push({expected:`record`,code:`invalid_type`,input:i,inst:e}),n;let o=[],s=t.keyType._zod.values;if(s){n.value={};let c=new Set;for(let l of s)if(typeof l==`string`||typeof l==`number`||typeof l==`symbol`){c.add(typeof l==`number`?l.toString():l);let s=t.keyType._zod.run({value:l,issues:[]},r);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(s.issues.length){n.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>w(e,r,a())),input:l,path:[l],inst:e});continue}let u=s.value,d=t.valueType._zod.run({value:i[l],issues:[]},r);d instanceof Promise?o.push(d.then(e=>{e.issues.length&&n.issues.push(...S(l,e.issues)),n.value[u]=e.value})):(d.issues.length&&n.issues.push(...S(l,d.issues)),n.value[u]=d.value)}let l;for(let e in i)c.has(e)||(l??=[],l.push(e));l&&l.length>0&&n.issues.push({code:`unrecognized_keys`,input:i,inst:e,keys:l})}else{n.value={};for(let s of Reflect.ownKeys(i)){if(s===`__proto__`||!Object.prototype.propertyIsEnumerable.call(i,s))continue;let c=t.keyType._zod.run({value:s,issues:[]},r);if(c instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof s==`string`&&st.test(s)&&c.issues.length){let e=t.keyType._zod.run({value:Number(s),issues:[]},r);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(c=e)}if(c.issues.length){t.mode===`loose`?n.value[s]=i[s]:n.issues.push({code:`invalid_key`,origin:`record`,issues:c.issues.map(e=>w(e,r,a())),input:s,path:[s],inst:e});continue}let l=t.valueType._zod.run({value:i[s],issues:[]},r);l instanceof Promise?o.push(l.then(e=>{e.issues.length&&n.issues.push(...S(s,e.issues)),n.value[c.value]=e.value})):(l.issues.length&&n.issues.push(...S(s,l.issues)),n.value[c.value]=l.value)}}return o.length?Promise.all(o).then(()=>n):n}}),Sn=t(`$ZodEnum`,(e,t)=>{A.init(e,t);let n=o(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=RegExp(`^(${n.filter(e=>ae.has(typeof e)).map(e=>typeof e==`string`?v(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),Cn=t(`$ZodLiteral`,(e,t)=>{if(A.init(e,t),t.values.length===0)throw Error(`Cannot create literal schema with no valid values`);let n=new Set(t.values);e._zod.values=n,e._zod.pattern=RegExp(`^(${t.values.map(e=>typeof e==`string`?v(e):e?v(e.toString()):String(e)).join(`|`)})$`),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}}),wn=t(`$ZodTransform`,(e,t)=>{A.init(e,t),e._zod.optin=`optional`,e._zod.parse=(i,a)=>{if(a.direction===`backward`)throw new r(e.constructor.name);let o=t.transform(i.value,i);if(a.async)return(o instanceof Promise?o:Promise.resolve(o)).then(e=>(i.value=e,i.fallback=!0,i));if(o instanceof Promise)throw new n;return i.value=o,i.fallback=!0,i}});function Tn(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}var En=t(`$ZodOptional`,(e,t)=>{A.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,p(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),p(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${u(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(t.innerType._zod.optin===`optional`){let r=e.value,i=t.innerType._zod.run(e,n);return i instanceof Promise?i.then(e=>Tn(e,r)):Tn(i,r)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),Dn=t(`$ZodExactOptional`,(e,t)=>{En.init(e,t),p(e._zod,`values`,()=>t.innerType._zod.values),p(e._zod,`pattern`,()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),On=t(`$ZodNullable`,(e,t)=>{A.init(e,t),p(e._zod,`optin`,()=>t.innerType._zod.optin),p(e._zod,`optout`,()=>t.innerType._zod.optout),p(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${u(e.source)}|null)$`):void 0}),p(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),kn=t(`$ZodDefault`,(e,t)=>{A.init(e,t),e._zod.optin=`optional`,p(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>An(e,t)):An(r,t)}});function An(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var jn=t(`$ZodPrefault`,(e,t)=>{A.init(e,t),e._zod.optin=`optional`,p(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Mn=t(`$ZodNonOptional`,(e,t)=>{A.init(e,t),p(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>Nn(t,e)):Nn(i,e)}});function Nn(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}var Pn=t(`$ZodCatch`,(e,t)=>{A.init(e,t),e._zod.optin=`optional`,p(e._zod,`optout`,()=>t.innerType._zod.optout),p(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>w(e,n,a()))},input:e.value}),e.issues=[],e.fallback=!0),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>w(e,n,a()))},input:e.value}),e.issues=[],e.fallback=!0),e)}}),Fn=t(`$ZodPipe`,(e,t)=>{A.init(e,t),p(e._zod,`values`,()=>t.in._zod.values),p(e._zod,`optin`,()=>t.in._zod.optin),p(e._zod,`optout`,()=>t.out._zod.optout),p(e._zod,`propValues`,()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>N(e,t.in,n)):N(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>N(e,t.out,n)):N(r,t.out,n)}});function N(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}var In=t(`$ZodReadonly`,(e,t)=>{A.init(e,t),p(e._zod,`propValues`,()=>t.innerType._zod.propValues),p(e._zod,`values`,()=>t.innerType._zod.values),p(e._zod,`optin`,()=>t.innerType?._zod?.optin),p(e._zod,`optout`,()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(Ln):Ln(r)}});function Ln(e){return e.value=Object.freeze(e.value),e}var Rn=t(`$ZodCustom`,(e,t)=>{O.init(e,t),A.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>zn(t,n,r,e));zn(i,n,r,e)}});function zn(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(T(e))}}var Bn,Vn=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function Hn(){return new Vn}(Bn=globalThis).__zod_globalRegistry??(Bn.__zod_globalRegistry=Hn());var P=globalThis.__zod_globalRegistry;function Un(e,t){return new e({type:`string`,...b(t)})}function Wn(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...b(t)})}function Gn(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...b(t)})}function Kn(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...b(t)})}function qn(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...b(t)})}function Jn(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...b(t)})}function Yn(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...b(t)})}function Xn(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...b(t)})}function Zn(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...b(t)})}function Qn(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...b(t)})}function $n(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...b(t)})}function er(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...b(t)})}function tr(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...b(t)})}function nr(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...b(t)})}function rr(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...b(t)})}function ir(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...b(t)})}function ar(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...b(t)})}function or(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...b(t)})}function sr(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...b(t)})}function cr(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...b(t)})}function lr(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...b(t)})}function ur(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...b(t)})}function dr(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...b(t)})}function fr(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...b(t)})}function pr(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...b(t)})}function mr(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...b(t)})}function hr(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...b(t)})}function gr(e,t){return new e({type:`number`,checks:[],...b(t)})}function _r(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...b(t)})}function vr(e,t){return new e({type:`boolean`,...b(t)})}function yr(e,t){return new e({type:`null`,...b(t)})}function br(e){return new e({type:`unknown`})}function xr(e,t){return new e({type:`never`,...b(t)})}function Sr(e,t){return new pt({check:`less_than`,...b(t),value:e,inclusive:!1})}function Cr(e,t){return new pt({check:`less_than`,...b(t),value:e,inclusive:!0})}function wr(e,t){return new mt({check:`greater_than`,...b(t),value:e,inclusive:!1})}function Tr(e,t){return new mt({check:`greater_than`,...b(t),value:e,inclusive:!0})}function Er(e,t){return new ht({check:`multiple_of`,...b(t),value:e})}function Dr(e,t){return new _t({check:`max_length`,...b(t),maximum:e})}function Or(e,t){return new vt({check:`min_length`,...b(t),minimum:e})}function kr(e,t){return new yt({check:`length_equals`,...b(t),length:e})}function Ar(e,t){return new bt({check:`string_format`,format:`regex`,...b(t),pattern:e})}function jr(e){return new xt({check:`string_format`,format:`lowercase`,...b(e)})}function Mr(e){return new St({check:`string_format`,format:`uppercase`,...b(e)})}function Nr(e,t){return new Ct({check:`string_format`,format:`includes`,...b(t),includes:e})}function Pr(e,t){return new wt({check:`string_format`,format:`starts_with`,...b(t),prefix:e})}function Fr(e,t){return new Tt({check:`string_format`,format:`ends_with`,...b(t),suffix:e})}function F(e){return new Et({check:`overwrite`,tx:e})}function Ir(e){return F(t=>t.normalize(e))}function Lr(){return F(e=>e.trim())}function Rr(){return F(e=>e.toLowerCase())}function zr(){return F(e=>e.toUpperCase())}function Br(){return F(e=>te(e))}function Vr(e,t,n){return new e({type:`array`,element:t,...b(n)})}function Hr(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...b(n)})}function Ur(e,t){let n=Wr(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(T(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=t.value,r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(T(r))}},e(t.value,t)),t);return n}function Wr(e,t){let n=new O({check:`custom`,...b(t)});return n._zod.check=e,n}function Gr(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??P,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,external:e?.external??void 0}}function I(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o);let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,I(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),t.io===`input`&&L(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function Kr(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${a}`}}if(t[1]===n)return{ref:`#`};let i=`#/${r}/`,a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+a}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
|
|
63
63
|
|
|
64
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}}function qr(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:R(t,`input`,e.processors),output:R(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function L(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return L(r.element,n);if(r.type===`set`)return L(r.valueType,n);if(r.type===`lazy`)return L(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`)return L(r.innerType,n);if(r.type===`intersection`)return L(r.left,n)||L(r.right,n);if(r.type===`record`||r.type===`map`)return L(r.keyType,n)||L(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:L(r.in,n)||L(r.out,n);if(r.type===`object`){for(let e in r.shape)if(L(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(L(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(L(e,n))return!0;return!!(r.rest&&L(r.rest,n))}return!1}var Jr=(e,t={})=>n=>{let r=Gr({...n,processors:t});return I(e,r),Kr(r,e),qr(r,e)},R=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=Gr({...i??{},target:a,io:t,processors:n});return I(e,o),Kr(o,e),qr(o,e)},Yr={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Xr=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Yr[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},Zr=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;i.type=typeof s==`string`&&s.includes(`int`)?`integer`:`number`;let d=typeof u==`number`&&u>=(a??-1/0),f=typeof l==`number`&&l<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(i.multipleOf=c)},Qr=(e,t,n,r)=>{n.type=`boolean`},$r=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},ei=(e,t,n,r)=>{n.not={}},ti=(e,t,n,r)=>{let i=e._zod.def,a=o(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},ni=(e,t,n,r)=>{let i=e._zod.def,a=[];for(let e of i.values)if(e===void 0){if(t.unrepresentable===`throw`)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof e==`bigint`){if(t.unrepresentable===`throw`)throw Error(`BigInt literals cannot be represented in JSON Schema`);a.push(Number(e))}else a.push(e);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},ri=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},ii=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},ai=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=I(a.element,t,{...r,path:[...r.path,`items`]})},oi=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=I(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=I(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},si=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>I(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},ci=(e,t,n,r)=>{let i=e._zod.def,a=I(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=I(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},li=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=I(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)i.patternProperties[t.source]=e}else(t.target===`draft-07`||t.target===`draft-2020-12`)&&(i.propertyNames=I(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=I(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]});let c=o._zod.values;if(c){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e)}},ui=(e,t,n,r)=>{let i=e._zod.def,a=I(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},di=(e,t,n,r)=>{let i=e._zod.def;I(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},fi=(e,t,n,r)=>{let i=e._zod.def;I(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},pi=(e,t,n,r)=>{let i=e._zod.def;I(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},mi=(e,t,n,r)=>{let i=e._zod.def;I(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},hi=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;I(o,t,r);let s=t.seen.get(e);s.ref=o},gi=(e,t,n,r)=>{let i=e._zod.def;I(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},_i=(e,t,n,r)=>{let i=e._zod.def;I(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},vi=t(`ZodISODateTime`,(e,t)=>{Vt.init(e,t),U.init(e,t)});function yi(e){return fr(vi,e)}var bi=t(`ZodISODate`,(e,t)=>{Ht.init(e,t),U.init(e,t)});function xi(e){return pr(bi,e)}var Si=t(`ZodISOTime`,(e,t)=>{Ut.init(e,t),U.init(e,t)});function Ci(e){return mr(Si,e)}var wi=t(`ZodISODuration`,(e,t)=>{Wt.init(e,t),U.init(e,t)});function Ti(e){return hr(wi,e)}var z=t(`ZodError`,(e,t)=>{ve.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>xe(e,t)},flatten:{value:t=>be(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,s,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,s,2)}},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),Ei=Se(z),Di=Ce(z),Oi=E(z),ki=D(z),Ai=Ee(z),ji=De(z),Mi=Oe(z),Ni=ke(z),Pi=Ae(z),Fi=je(z),Ii=Me(z),Li=Ne(z),Ri=new WeakMap;function B(e,t,n){let r=Object.getPrototypeOf(e),i=Ri.get(r);if(i||(i=new Set,Ri.set(r,i)),!i.has(t)){i.add(t);for(let e in n){let t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){let n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}var V=t(`ZodType`,(e,t)=>(A.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:R(e,`input`),output:R(e,`output`)}}),e.toJSONSchema=Jr(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>Ei(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Oi(e,t,n),e.parseAsync=async(t,n)=>Di(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>ki(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>Ai(e,t,n),e.decode=(t,n)=>ji(e,t,n),e.encodeAsync=async(t,n)=>Mi(e,t,n),e.decodeAsync=async(t,n)=>Ni(e,t,n),e.safeEncode=(t,n)=>Pi(e,t,n),e.safeDecode=(t,n)=>Fi(e,t,n),e.safeEncodeAsync=async(t,n)=>Ii(e,t,n),e.safeDecodeAsync=async(t,n)=>Li(e,t,n),B(e,`ZodType`,{check(...e){let t=this.def;return this.clone(h(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return y(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Ya(e,t))},superRefine(e,t){return this.check(Xa(e,t))},overwrite(e){return this.check(F(e))},optional(){return ja(this)},exactOptional(){return Na(this)},nullable(){return Fa(this)},nullish(){return ja(Fa(this))},nonoptional(e){return Va(this,e)},array(){return X(this)},or(e){return va([this,e])},and(e){return Sa(this,e)},transform(e){return Ga(this,ka(e))},default(e){return La(this,e)},prefault(e){return za(this,e)},catch(e){return Ua(this,e)},pipe(e){return Ga(this,e)},readonly(){return qa(this)},describe(e){let t=this.clone();return P.add(t,{description:e}),t},meta(...e){if(e.length===0)return P.get(this);let t=this.clone();return P.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,"description",{get(){return P.get(e)?.description},configurable:!0}),e)),zi=t(`_ZodString`,(e,t)=>{kt.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xr(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,B(e,`_ZodString`,{regex(...e){return this.check(Ar(...e))},includes(...e){return this.check(Nr(...e))},startsWith(...e){return this.check(Pr(...e))},endsWith(...e){return this.check(Fr(...e))},min(...e){return this.check(Or(...e))},max(...e){return this.check(Dr(...e))},length(...e){return this.check(kr(...e))},nonempty(...e){return this.check(Or(1,...e))},lowercase(e){return this.check(jr(e))},uppercase(e){return this.check(Mr(e))},trim(){return this.check(Lr())},normalize(...e){return this.check(Ir(...e))},toLowerCase(){return this.check(Rr())},toUpperCase(){return this.check(zr())},slugify(){return this.check(Br())}})}),Bi=t(`ZodString`,(e,t)=>{kt.init(e,t),zi.init(e,t),e.email=t=>e.check(Wn(Vi,t)),e.url=t=>e.check(Xn(Wi,t)),e.jwt=t=>e.check(dr(aa,t)),e.emoji=t=>e.check(Zn(Gi,t)),e.guid=t=>e.check(Gn(Ui,t)),e.uuid=t=>e.check(Kn(W,t)),e.uuidv4=t=>e.check(qn(W,t)),e.uuidv6=t=>e.check(Jn(W,t)),e.uuidv7=t=>e.check(Yn(W,t)),e.nanoid=t=>e.check(Qn(Ki,t)),e.guid=t=>e.check(Gn(Ui,t)),e.cuid=t=>e.check($n(qi,t)),e.cuid2=t=>e.check(er(Ji,t)),e.ulid=t=>e.check(tr(Yi,t)),e.base64=t=>e.check(cr(na,t)),e.base64url=t=>e.check(lr(ra,t)),e.xid=t=>e.check(nr(Xi,t)),e.ksuid=t=>e.check(rr(Zi,t)),e.ipv4=t=>e.check(ir(Qi,t)),e.ipv6=t=>e.check(ar($i,t)),e.cidrv4=t=>e.check(or(ea,t)),e.cidrv6=t=>e.check(sr(ta,t)),e.e164=t=>e.check(ur(ia,t)),e.datetime=t=>e.check(yi(t)),e.date=t=>e.check(xi(t)),e.time=t=>e.check(Ci(t)),e.duration=t=>e.check(Ti(t))});function H(e){return Un(Bi,e)}var U=t(`ZodStringFormat`,(e,t)=>{j.init(e,t),zi.init(e,t)}),Vi=t(`ZodEmail`,(e,t)=>{Mt.init(e,t),U.init(e,t)});function Hi(e){return Wn(Vi,e)}var Ui=t(`ZodGUID`,(e,t)=>{At.init(e,t),U.init(e,t)}),W=t(`ZodUUID`,(e,t)=>{jt.init(e,t),U.init(e,t)}),Wi=t(`ZodURL`,(e,t)=>{Nt.init(e,t),U.init(e,t)});function G(e){return Xn(Wi,e)}var Gi=t(`ZodEmoji`,(e,t)=>{Pt.init(e,t),U.init(e,t)}),Ki=t(`ZodNanoID`,(e,t)=>{Ft.init(e,t),U.init(e,t)}),qi=t(`ZodCUID`,(e,t)=>{It.init(e,t),U.init(e,t)}),Ji=t(`ZodCUID2`,(e,t)=>{Lt.init(e,t),U.init(e,t)}),Yi=t(`ZodULID`,(e,t)=>{Rt.init(e,t),U.init(e,t)}),Xi=t(`ZodXID`,(e,t)=>{zt.init(e,t),U.init(e,t)}),Zi=t(`ZodKSUID`,(e,t)=>{Bt.init(e,t),U.init(e,t)}),Qi=t(`ZodIPv4`,(e,t)=>{Gt.init(e,t),U.init(e,t)}),$i=t(`ZodIPv6`,(e,t)=>{Kt.init(e,t),U.init(e,t)}),ea=t(`ZodCIDRv4`,(e,t)=>{qt.init(e,t),U.init(e,t)}),ta=t(`ZodCIDRv6`,(e,t)=>{Jt.init(e,t),U.init(e,t)}),na=t(`ZodBase64`,(e,t)=>{Xt.init(e,t),U.init(e,t)}),ra=t(`ZodBase64URL`,(e,t)=>{Qt.init(e,t),U.init(e,t)}),ia=t(`ZodE164`,(e,t)=>{$t.init(e,t),U.init(e,t)}),aa=t(`ZodJWT`,(e,t)=>{tn.init(e,t),U.init(e,t)}),oa=t(`ZodNumber`,(e,t)=>{nn.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zr(e,t,n,r),B(e,`ZodNumber`,{gt(e,t){return this.check(wr(e,t))},gte(e,t){return this.check(Tr(e,t))},min(e,t){return this.check(Tr(e,t))},lt(e,t){return this.check(Sr(e,t))},lte(e,t){return this.check(Cr(e,t))},max(e,t){return this.check(Cr(e,t))},int(e){return this.check(q(e))},safe(e){return this.check(q(e))},positive(e){return this.check(wr(0,e))},nonnegative(e){return this.check(Tr(0,e))},negative(e){return this.check(Sr(0,e))},nonpositive(e){return this.check(Cr(0,e))},multipleOf(e,t){return this.check(Er(e,t))},step(e,t){return this.check(Er(e,t))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function K(e){return gr(oa,e)}var sa=t(`ZodNumberFormat`,(e,t)=>{rn.init(e,t),oa.init(e,t)});function q(e){return _r(sa,e)}var ca=t(`ZodBoolean`,(e,t)=>{an.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Qr(e,t,n,r)});function J(e){return vr(ca,e)}var la=t(`ZodNull`,(e,t)=>{on.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$r(e,t,n,r)});function ua(e){return yr(la,e)}var da=t(`ZodUnknown`,(e,t)=>{sn.init(e,t),V.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function Y(){return br(da)}var fa=t(`ZodNever`,(e,t)=>{cn.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ei(e,t,n,r)});function pa(e){return xr(fa,e)}var ma=t(`ZodArray`,(e,t)=>{un.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ai(e,t,n,r),e.element=t.element,B(e,`ZodArray`,{min(e,t){return this.check(Or(e,t))},nonempty(e){return this.check(Or(1,e))},max(e,t){return this.check(Dr(e,t))},length(e,t){return this.check(kr(e,t))},unwrap(){return this.element}})});function X(e,t){return Vr(ma,e,t)}var ha=t(`ZodObject`,(e,t)=>{mn.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>oi(e,t,n,r),p(e,`shape`,()=>t.shape),B(e,`ZodObject`,{keyof(){return Q(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:Y()})},loose(){return this.clone({...this._zod.def,catchall:Y()})},strict(){return this.clone({...this._zod.def,catchall:pa()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return ue(this,e)},safeExtend(e){return de(this,e)},merge(e){return fe(this,e)},pick(e){return ce(this,e)},omit(e){return le(this,e)},partial(...e){return pe(Aa,this,e[0])},required(...e){return me(Ba,this,e[0])}})});function Z(e,t){return new ha({type:`object`,shape:e??{},...b(t)})}function ga(e,t){return new ha({type:`object`,shape:e,catchall:Y(),...b(t)})}var _a=t(`ZodUnion`,(e,t)=>{gn.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>si(e,t,n,r),e.options=t.options});function va(e,t){return new _a({type:`union`,options:e,...b(t)})}var ya=t(`ZodDiscriminatedUnion`,(e,t)=>{_a.init(e,t),_n.init(e,t)});function ba(e,t,n){return new ya({type:`union`,options:t,discriminator:e,...b(n)})}var xa=t(`ZodIntersection`,(e,t)=>{vn.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ci(e,t,n,r)});function Sa(e,t){return new xa({type:`intersection`,left:e,right:t})}var Ca=t(`ZodRecord`,(e,t)=>{xn.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>li(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function wa(e,t,n){return!t||!t._zod?new Ca({type:`record`,keyType:H(),valueType:e,...b(t)}):new Ca({type:`record`,keyType:e,valueType:t,...b(n)})}var Ta=t(`ZodEnum`,(e,t)=>{Sn.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ti(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new Ta({...t,checks:[],...b(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new Ta({...t,checks:[],...b(r),entries:i})}});function Q(e,t){return new Ta({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...b(t)})}var Ea=t(`ZodLiteral`,(e,t)=>{Cn.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ni(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Da(e,t){return new Ea({type:`literal`,values:Array.isArray(e)?e:[e],...b(t)})}var Oa=t(`ZodTransform`,(e,t)=>{wn.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ii(e,t,n,r),e._zod.parse=(n,i)=>{if(i.direction===`backward`)throw new r(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(T(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(T(t))}};let a=t.transform(n.value,n);return a instanceof Promise?a.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=a,n.fallback=!0,n)}});function ka(e){return new Oa({type:`transform`,transform:e})}var Aa=t(`ZodOptional`,(e,t)=>{En.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_i(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function ja(e){return new Aa({type:`optional`,innerType:e})}var Ma=t(`ZodExactOptional`,(e,t)=>{Dn.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_i(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Na(e){return new Ma({type:`optional`,innerType:e})}var Pa=t(`ZodNullable`,(e,t)=>{On.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ui(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Fa(e){return new Pa({type:`nullable`,innerType:e})}var Ia=t(`ZodDefault`,(e,t)=>{kn.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function La(e,t){return new Ia({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():ie(t)}})}var Ra=t(`ZodPrefault`,(e,t)=>{jn.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function za(e,t){return new Ra({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():ie(t)}})}var Ba=t(`ZodNonOptional`,(e,t)=>{Mn.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>di(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Va(e,t){return new Ba({type:`nonoptional`,innerType:e,...b(t)})}var Ha=t(`ZodCatch`,(e,t)=>{Pn.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>mi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Ua(e,t){return new Ha({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}var Wa=t(`ZodPipe`,(e,t)=>{Fn.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>hi(e,t,n,r),e.in=t.in,e.out=t.out});function Ga(e,t){return new Wa({type:`pipe`,in:e,out:t})}var Ka=t(`ZodReadonly`,(e,t)=>{In.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>gi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function qa(e){return new Ka({type:`readonly`,innerType:e})}var Ja=t(`ZodCustom`,(e,t)=>{Rn.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ri(e,t,n,r)});function Ya(e,t={}){return Hr(Ja,e,t)}function Xa(e,t){return Ur(e,t)}var Za=Z({error:H().optional()}),Qa=Z({authenticated:J().optional()}),$a=Z({httpBaseUrl:G(),desktopLoginCallbackUrl:G().optional(),pairingCredential:H()}),eo=Z({parentPath:H(),entries:X(Z({name:H(),fullPath:H()})),volumeList:J().optional()}),to=Z({skills:X(Z({name:H(),description:H()})),warnings:X(H())}),no=Z({workspacePath:H(),displayName:H(),repositoryKey:H()}),ro=Z({workspacePath:H(),repositoryKey:H(),displayName:H(),availability:Q([`available`,`unavailable`]),lastValidatedAt:q(),lastUsedAt:q(),unavailableReason:H().optional(),previousRepositoryKey:H().optional()}),io=Z({runId:H(),threadId:H()}),ao=Z({storageId:H(),name:H(),mediaType:H(),size:q(),url:G().optional()}),oo=va([Z({storageId:H(),name:H(),mediaType:H(),size:K(),url:H()}),Z({error:H()})]);function so(e){let t=`userId=${encodeURIComponent(e.userId)}&name=${encodeURIComponent(e.name)}`;return e.threadId&&(t+=`&threadId=${encodeURIComponent(e.threadId)}`),`/api/transcript/upload?${t}`}var co=Z({id:H(),threadId:H(),runId:H(),userId:H(),type:Q([`prompt`,`response`]),text:H(),attachments:X(ao),parts:X(Y()),runStatus:Q([`queued`,`running`,`awaiting_executor`,`completed`,`failed`,`cancelled`]),runStartedAt:q(),sourceNumbers:X(q()),streamIds:X(H()),detailsLoaded:J()}),lo=Z({number:q().nonnegative(),kind:Q([`prompt`,`completion`,`tool`]),message:co.nullable()}),uo=Z({threadId:H(),totalParts:q(),historyFromNumber:q(),stale:J(),parts:X(lo),nextBefore:q().optional()}),fo=Z({eventType:H(),totalParts:q().optional(),stale:J()}),po=Z({threadId:H(),runId:H(),runStatus:Q([`queued`,`running`,`awaiting_executor`,`completed`,`failed`,`cancelled`]),streamId:H().optional(),text:H(),parts:X(Y()),runStartedAt:q()}),mo=ba(`eventType`,[Z({eventType:Da(`updated`),live:po}),Z({eventType:Da(`cleared`)})]),ho=Z({_id:H(),_creationTime:K(),userId:H(),submissionId:H(),repositoryKey:H(),title:H().optional(),selectedModel:H(),reasoningEffort:Q([`none`,`low`,`medium`,`high`,`xhigh`,`max`]),serviceTier:Q([`standard`,`fast`]),contextSummary:H().optional(),contextSummaryThroughRunId:H().optional(),lastMessageAt:K(),archivedAt:K().optional(),status:Q([`queued`,`running`,`awaiting_executor`,`completed`,`failed`,`cancelled`])}),go=Z({status:Q([`loading`,`live`,`reconnecting`,`offline`,`error`]),lastSyncedAt:q().nullable()}),_o=go.extend({threads:X(ho)}),vo=Q([`thread`,`project`]),yo=Z({artifacts:X(Z({_id:H(),userId:H(),scope:vo,repositoryKey:H(),threadId:H().optional(),localPath:H().optional(),content:H(),type:Q([`markdown`,`html`,`react`]),title:H(),revision:K(),createdAt:K(),updatedAt:K(),localError:H().optional()})),stale:J(),error:H().optional()});function $(e){return e}function bo(e){return e}function xo(e){return{threadId:$(e.threadId),totalParts:e.totalParts,historyFromNumber:e.historyFromNumber,stale:e.stale,nextBefore:e.nextBefore,parts:e.parts.map(So)}}function So(e){return{number:e.number,kind:e.kind,message:e.message?Co(e.message):null}}function Co(e){return{_id:e.id,threadId:$(e.threadId),runId:$(e.runId),userId:e.userId,type:e.type,text:e.text,attachments:e.attachments.map(e=>({storageId:$(e.storageId),name:e.name,mediaType:e.mediaType,size:e.size,url:e.url??null})),parts:e.parts,runStatus:e.runStatus,runStartedAt:e.runStartedAt,sourceNumbers:e.sourceNumbers,streamIds:e.streamIds,detailsLoaded:e.detailsLoaded}}function wo(e){return{threadId:$(e.threadId),runId:$(e.runId),runStatus:e.runStatus,streamId:e.streamId,text:e.text,parts:e.parts,runStartedAt:e.runStartedAt}}function To(e){return{...e,_id:$(e._id),contextSummaryThroughRunId:e.contextSummaryThroughRunId?$(e.contextSummaryThroughRunId):void 0}}function Eo(e){return{status:e.status,lastSyncedAt:e.lastSyncedAt}}function Do(e){return{...Eo(e),threads:e.threads.map(To)}}function Oo(e){return e.eventType===`updated`?{eventType:`updated`,live:wo(e.live)}:{eventType:`cleared`}}function ko(e){let{threadId:t,...n}=e;return e.scope===`thread`&&t?{...n,threadId:t}:n}function Ao(e){return{artifacts:e.artifacts.map(ko),stale:e.stale,error:e.error}}async function jo(e,t,n){if(!e.body)return;let r=e.body.getReader(),i=new TextDecoder,a=``;try{for(;!t.aborted;){let{done:e,value:o}=await r.read();if(e)break;a+=i.decode(o,{stream:!0});let s=a.indexOf(`
|
|
64
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}}function qr(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:R(t,`input`,e.processors),output:R(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function L(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return L(r.element,n);if(r.type===`set`)return L(r.valueType,n);if(r.type===`lazy`)return L(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`)return L(r.innerType,n);if(r.type===`intersection`)return L(r.left,n)||L(r.right,n);if(r.type===`record`||r.type===`map`)return L(r.keyType,n)||L(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:L(r.in,n)||L(r.out,n);if(r.type===`object`){for(let e in r.shape)if(L(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(L(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(L(e,n))return!0;return!!(r.rest&&L(r.rest,n))}return!1}var Jr=(e,t={})=>n=>{let r=Gr({...n,processors:t});return I(e,r),Kr(r,e),qr(r,e)},R=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=Gr({...i??{},target:a,io:t,processors:n});return I(e,o),Kr(o,e),qr(o,e)},Yr={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Xr=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Yr[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},Zr=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;i.type=typeof s==`string`&&s.includes(`int`)?`integer`:`number`;let d=typeof u==`number`&&u>=(a??-1/0),f=typeof l==`number`&&l<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(i.multipleOf=c)},Qr=(e,t,n,r)=>{n.type=`boolean`},$r=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},ei=(e,t,n,r)=>{n.not={}},ti=(e,t,n,r)=>{let i=e._zod.def,a=o(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},ni=(e,t,n,r)=>{let i=e._zod.def,a=[];for(let e of i.values)if(e===void 0){if(t.unrepresentable===`throw`)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof e==`bigint`){if(t.unrepresentable===`throw`)throw Error(`BigInt literals cannot be represented in JSON Schema`);a.push(Number(e))}else a.push(e);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},ri=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},ii=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},ai=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=I(a.element,t,{...r,path:[...r.path,`items`]})},oi=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=I(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=I(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},si=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>I(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},ci=(e,t,n,r)=>{let i=e._zod.def,a=I(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=I(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},li=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=I(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)i.patternProperties[t.source]=e}else(t.target===`draft-07`||t.target===`draft-2020-12`)&&(i.propertyNames=I(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=I(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]});let c=o._zod.values;if(c){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e)}},ui=(e,t,n,r)=>{let i=e._zod.def,a=I(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},di=(e,t,n,r)=>{let i=e._zod.def;I(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},fi=(e,t,n,r)=>{let i=e._zod.def;I(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},pi=(e,t,n,r)=>{let i=e._zod.def;I(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},mi=(e,t,n,r)=>{let i=e._zod.def;I(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},hi=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;I(o,t,r);let s=t.seen.get(e);s.ref=o},gi=(e,t,n,r)=>{let i=e._zod.def;I(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},_i=(e,t,n,r)=>{let i=e._zod.def;I(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},vi=t(`ZodISODateTime`,(e,t)=>{Vt.init(e,t),U.init(e,t)});function yi(e){return fr(vi,e)}var bi=t(`ZodISODate`,(e,t)=>{Ht.init(e,t),U.init(e,t)});function xi(e){return pr(bi,e)}var Si=t(`ZodISOTime`,(e,t)=>{Ut.init(e,t),U.init(e,t)});function Ci(e){return mr(Si,e)}var wi=t(`ZodISODuration`,(e,t)=>{Wt.init(e,t),U.init(e,t)});function Ti(e){return hr(wi,e)}var z=t(`ZodError`,(e,t)=>{ve.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>xe(e,t)},flatten:{value:t=>be(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,s,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,s,2)}},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),Ei=Se(z),Di=Ce(z),Oi=E(z),ki=D(z),Ai=Ee(z),ji=De(z),Mi=Oe(z),Ni=ke(z),Pi=Ae(z),Fi=je(z),Ii=Me(z),Li=Ne(z),Ri=new WeakMap;function B(e,t,n){let r=Object.getPrototypeOf(e),i=Ri.get(r);if(i||(i=new Set,Ri.set(r,i)),!i.has(t)){i.add(t);for(let e in n){let t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){let n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}var V=t(`ZodType`,(e,t)=>(A.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:R(e,`input`),output:R(e,`output`)}}),e.toJSONSchema=Jr(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>Ei(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Oi(e,t,n),e.parseAsync=async(t,n)=>Di(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>ki(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>Ai(e,t,n),e.decode=(t,n)=>ji(e,t,n),e.encodeAsync=async(t,n)=>Mi(e,t,n),e.decodeAsync=async(t,n)=>Ni(e,t,n),e.safeEncode=(t,n)=>Pi(e,t,n),e.safeDecode=(t,n)=>Fi(e,t,n),e.safeEncodeAsync=async(t,n)=>Ii(e,t,n),e.safeDecodeAsync=async(t,n)=>Li(e,t,n),B(e,`ZodType`,{check(...e){let t=this.def;return this.clone(h(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return y(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Ya(e,t))},superRefine(e,t){return this.check(Xa(e,t))},overwrite(e){return this.check(F(e))},optional(){return ja(this)},exactOptional(){return Na(this)},nullable(){return Fa(this)},nullish(){return ja(Fa(this))},nonoptional(e){return Va(this,e)},array(){return X(this)},or(e){return va([this,e])},and(e){return Sa(this,e)},transform(e){return Ga(this,ka(e))},default(e){return La(this,e)},prefault(e){return za(this,e)},catch(e){return Ua(this,e)},pipe(e){return Ga(this,e)},readonly(){return qa(this)},describe(e){let t=this.clone();return P.add(t,{description:e}),t},meta(...e){if(e.length===0)return P.get(this);let t=this.clone();return P.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,"description",{get(){return P.get(e)?.description},configurable:!0}),e)),zi=t(`_ZodString`,(e,t)=>{kt.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xr(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,B(e,`_ZodString`,{regex(...e){return this.check(Ar(...e))},includes(...e){return this.check(Nr(...e))},startsWith(...e){return this.check(Pr(...e))},endsWith(...e){return this.check(Fr(...e))},min(...e){return this.check(Or(...e))},max(...e){return this.check(Dr(...e))},length(...e){return this.check(kr(...e))},nonempty(...e){return this.check(Or(1,...e))},lowercase(e){return this.check(jr(e))},uppercase(e){return this.check(Mr(e))},trim(){return this.check(Lr())},normalize(...e){return this.check(Ir(...e))},toLowerCase(){return this.check(Rr())},toUpperCase(){return this.check(zr())},slugify(){return this.check(Br())}})}),Bi=t(`ZodString`,(e,t)=>{kt.init(e,t),zi.init(e,t),e.email=t=>e.check(Wn(Vi,t)),e.url=t=>e.check(Xn(Wi,t)),e.jwt=t=>e.check(dr(aa,t)),e.emoji=t=>e.check(Zn(Gi,t)),e.guid=t=>e.check(Gn(Ui,t)),e.uuid=t=>e.check(Kn(W,t)),e.uuidv4=t=>e.check(qn(W,t)),e.uuidv6=t=>e.check(Jn(W,t)),e.uuidv7=t=>e.check(Yn(W,t)),e.nanoid=t=>e.check(Qn(Ki,t)),e.guid=t=>e.check(Gn(Ui,t)),e.cuid=t=>e.check($n(qi,t)),e.cuid2=t=>e.check(er(Ji,t)),e.ulid=t=>e.check(tr(Yi,t)),e.base64=t=>e.check(cr(na,t)),e.base64url=t=>e.check(lr(ra,t)),e.xid=t=>e.check(nr(Xi,t)),e.ksuid=t=>e.check(rr(Zi,t)),e.ipv4=t=>e.check(ir(Qi,t)),e.ipv6=t=>e.check(ar($i,t)),e.cidrv4=t=>e.check(or(ea,t)),e.cidrv6=t=>e.check(sr(ta,t)),e.e164=t=>e.check(ur(ia,t)),e.datetime=t=>e.check(yi(t)),e.date=t=>e.check(xi(t)),e.time=t=>e.check(Ci(t)),e.duration=t=>e.check(Ti(t))});function H(e){return Un(Bi,e)}var U=t(`ZodStringFormat`,(e,t)=>{j.init(e,t),zi.init(e,t)}),Vi=t(`ZodEmail`,(e,t)=>{Mt.init(e,t),U.init(e,t)});function Hi(e){return Wn(Vi,e)}var Ui=t(`ZodGUID`,(e,t)=>{At.init(e,t),U.init(e,t)}),W=t(`ZodUUID`,(e,t)=>{jt.init(e,t),U.init(e,t)}),Wi=t(`ZodURL`,(e,t)=>{Nt.init(e,t),U.init(e,t)});function G(e){return Xn(Wi,e)}var Gi=t(`ZodEmoji`,(e,t)=>{Pt.init(e,t),U.init(e,t)}),Ki=t(`ZodNanoID`,(e,t)=>{Ft.init(e,t),U.init(e,t)}),qi=t(`ZodCUID`,(e,t)=>{It.init(e,t),U.init(e,t)}),Ji=t(`ZodCUID2`,(e,t)=>{Lt.init(e,t),U.init(e,t)}),Yi=t(`ZodULID`,(e,t)=>{Rt.init(e,t),U.init(e,t)}),Xi=t(`ZodXID`,(e,t)=>{zt.init(e,t),U.init(e,t)}),Zi=t(`ZodKSUID`,(e,t)=>{Bt.init(e,t),U.init(e,t)}),Qi=t(`ZodIPv4`,(e,t)=>{Gt.init(e,t),U.init(e,t)}),$i=t(`ZodIPv6`,(e,t)=>{Kt.init(e,t),U.init(e,t)}),ea=t(`ZodCIDRv4`,(e,t)=>{qt.init(e,t),U.init(e,t)}),ta=t(`ZodCIDRv6`,(e,t)=>{Jt.init(e,t),U.init(e,t)}),na=t(`ZodBase64`,(e,t)=>{Xt.init(e,t),U.init(e,t)}),ra=t(`ZodBase64URL`,(e,t)=>{Qt.init(e,t),U.init(e,t)}),ia=t(`ZodE164`,(e,t)=>{$t.init(e,t),U.init(e,t)}),aa=t(`ZodJWT`,(e,t)=>{tn.init(e,t),U.init(e,t)}),oa=t(`ZodNumber`,(e,t)=>{nn.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zr(e,t,n,r),B(e,`ZodNumber`,{gt(e,t){return this.check(wr(e,t))},gte(e,t){return this.check(Tr(e,t))},min(e,t){return this.check(Tr(e,t))},lt(e,t){return this.check(Sr(e,t))},lte(e,t){return this.check(Cr(e,t))},max(e,t){return this.check(Cr(e,t))},int(e){return this.check(q(e))},safe(e){return this.check(q(e))},positive(e){return this.check(wr(0,e))},nonnegative(e){return this.check(Tr(0,e))},negative(e){return this.check(Sr(0,e))},nonpositive(e){return this.check(Cr(0,e))},multipleOf(e,t){return this.check(Er(e,t))},step(e,t){return this.check(Er(e,t))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function K(e){return gr(oa,e)}var sa=t(`ZodNumberFormat`,(e,t)=>{rn.init(e,t),oa.init(e,t)});function q(e){return _r(sa,e)}var ca=t(`ZodBoolean`,(e,t)=>{an.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Qr(e,t,n,r)});function J(e){return vr(ca,e)}var la=t(`ZodNull`,(e,t)=>{on.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$r(e,t,n,r)});function ua(e){return yr(la,e)}var da=t(`ZodUnknown`,(e,t)=>{sn.init(e,t),V.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function Y(){return br(da)}var fa=t(`ZodNever`,(e,t)=>{cn.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ei(e,t,n,r)});function pa(e){return xr(fa,e)}var ma=t(`ZodArray`,(e,t)=>{un.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ai(e,t,n,r),e.element=t.element,B(e,`ZodArray`,{min(e,t){return this.check(Or(e,t))},nonempty(e){return this.check(Or(1,e))},max(e,t){return this.check(Dr(e,t))},length(e,t){return this.check(kr(e,t))},unwrap(){return this.element}})});function X(e,t){return Vr(ma,e,t)}var ha=t(`ZodObject`,(e,t)=>{mn.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>oi(e,t,n,r),p(e,`shape`,()=>t.shape),B(e,`ZodObject`,{keyof(){return Q(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:Y()})},loose(){return this.clone({...this._zod.def,catchall:Y()})},strict(){return this.clone({...this._zod.def,catchall:pa()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return ue(this,e)},safeExtend(e){return de(this,e)},merge(e){return fe(this,e)},pick(e){return ce(this,e)},omit(e){return le(this,e)},partial(...e){return pe(Aa,this,e[0])},required(...e){return me(Ba,this,e[0])}})});function Z(e,t){return new ha({type:`object`,shape:e??{},...b(t)})}function ga(e,t){return new ha({type:`object`,shape:e,catchall:Y(),...b(t)})}var _a=t(`ZodUnion`,(e,t)=>{gn.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>si(e,t,n,r),e.options=t.options});function va(e,t){return new _a({type:`union`,options:e,...b(t)})}var ya=t(`ZodDiscriminatedUnion`,(e,t)=>{_a.init(e,t),_n.init(e,t)});function ba(e,t,n){return new ya({type:`union`,options:t,discriminator:e,...b(n)})}var xa=t(`ZodIntersection`,(e,t)=>{vn.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ci(e,t,n,r)});function Sa(e,t){return new xa({type:`intersection`,left:e,right:t})}var Ca=t(`ZodRecord`,(e,t)=>{xn.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>li(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function wa(e,t,n){return!t||!t._zod?new Ca({type:`record`,keyType:H(),valueType:e,...b(t)}):new Ca({type:`record`,keyType:e,valueType:t,...b(n)})}var Ta=t(`ZodEnum`,(e,t)=>{Sn.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ti(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new Ta({...t,checks:[],...b(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new Ta({...t,checks:[],...b(r),entries:i})}});function Q(e,t){return new Ta({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...b(t)})}var Ea=t(`ZodLiteral`,(e,t)=>{Cn.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ni(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Da(e,t){return new Ea({type:`literal`,values:Array.isArray(e)?e:[e],...b(t)})}var Oa=t(`ZodTransform`,(e,t)=>{wn.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ii(e,t,n,r),e._zod.parse=(n,i)=>{if(i.direction===`backward`)throw new r(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(T(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(T(t))}};let a=t.transform(n.value,n);return a instanceof Promise?a.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=a,n.fallback=!0,n)}});function ka(e){return new Oa({type:`transform`,transform:e})}var Aa=t(`ZodOptional`,(e,t)=>{En.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_i(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function ja(e){return new Aa({type:`optional`,innerType:e})}var Ma=t(`ZodExactOptional`,(e,t)=>{Dn.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_i(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Na(e){return new Ma({type:`optional`,innerType:e})}var Pa=t(`ZodNullable`,(e,t)=>{On.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ui(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Fa(e){return new Pa({type:`nullable`,innerType:e})}var Ia=t(`ZodDefault`,(e,t)=>{kn.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function La(e,t){return new Ia({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():ie(t)}})}var Ra=t(`ZodPrefault`,(e,t)=>{jn.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function za(e,t){return new Ra({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():ie(t)}})}var Ba=t(`ZodNonOptional`,(e,t)=>{Mn.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>di(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Va(e,t){return new Ba({type:`nonoptional`,innerType:e,...b(t)})}var Ha=t(`ZodCatch`,(e,t)=>{Pn.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>mi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Ua(e,t){return new Ha({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}var Wa=t(`ZodPipe`,(e,t)=>{Fn.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>hi(e,t,n,r),e.in=t.in,e.out=t.out});function Ga(e,t){return new Wa({type:`pipe`,in:e,out:t})}var Ka=t(`ZodReadonly`,(e,t)=>{In.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>gi(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function qa(e){return new Ka({type:`readonly`,innerType:e})}var Ja=t(`ZodCustom`,(e,t)=>{Rn.init(e,t),V.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ri(e,t,n,r)});function Ya(e,t={}){return Hr(Ja,e,t)}function Xa(e,t){return Ur(e,t)}var Za=Z({error:H().optional()}),Qa=Z({authenticated:J().optional()}),$a=Z({httpBaseUrl:G(),desktopLoginCallbackUrl:G().optional(),pairingCredential:H()}),eo=Z({parentPath:H(),entries:X(Z({name:H(),fullPath:H()})),volumeList:J().optional()}),to=Z({skills:X(Z({name:H(),description:H()})),warnings:X(H())}),no=Z({workspacePath:H(),displayName:H(),repositoryKey:H()}),ro=Z({workspacePath:H(),repositoryKey:H(),displayName:H(),availability:Q([`available`,`unavailable`]),lastValidatedAt:q(),lastUsedAt:q(),unavailableReason:H().optional(),previousRepositoryKey:H().optional()}),io=Z({runId:H(),threadId:H()}),ao=Z({storageId:H(),name:H(),mediaType:H(),size:q(),url:G().optional()}),oo=va([Z({storageId:H(),name:H(),mediaType:H(),size:K(),url:H()}),Z({error:H()})]);function so(e){let t=`userId=${encodeURIComponent(e.userId)}&name=${encodeURIComponent(e.name)}`;return e.threadId&&(t+=`&threadId=${encodeURIComponent(e.threadId)}`),`/api/transcript/upload?${t}`}var co=Z({id:H(),threadId:H(),runId:H(),userId:H(),type:Q([`prompt`,`response`]),text:H(),attachments:X(ao),parts:X(Y()),runStatus:Q([`queued`,`running`,`awaiting_executor`,`completed`,`failed`,`cancelled`]),runStartedAt:q(),sourceNumbers:X(q()),streamIds:X(H()),detailsLoaded:J()}),lo=Z({number:q().nonnegative(),kind:Q([`prompt`,`completion`,`tool`]),message:co.nullable()}),uo=Z({threadId:H(),totalParts:q(),historyFromNumber:q(),stale:J(),parts:X(lo),nextBefore:q().optional()}),fo=Z({eventType:H(),totalParts:q().optional(),stale:J()}),po=Z({threadId:H(),runId:H(),runStatus:Q([`queued`,`running`,`awaiting_executor`,`completed`,`failed`,`cancelled`]),streamId:H().optional(),text:H(),parts:X(Y()),runStartedAt:q()}),mo=ba(`eventType`,[Z({eventType:Da(`updated`),live:po}),Z({eventType:Da(`cleared`)})]),ho=Z({_id:H(),_creationTime:K(),userId:H(),submissionId:H(),repositoryKey:H(),title:H().optional(),selectedModel:H(),reasoningEffort:Q([`none`,`low`,`medium`,`high`,`xhigh`,`max`]),fastMode:J(),contextSummary:H().optional(),contextSummaryThroughRunId:H().optional(),lastMessageAt:K(),archivedAt:K().optional(),status:Q([`queued`,`running`,`awaiting_executor`,`completed`,`failed`,`cancelled`]).optional()}),go=Z({status:Q([`loading`,`live`,`reconnecting`,`offline`,`error`]),lastSyncedAt:q().nullable()}),_o=go.extend({threads:X(ho)}),vo=Q([`thread`,`project`]),yo=Z({artifacts:X(Z({_id:H(),userId:H(),scope:vo,repositoryKey:H(),threadId:H().optional(),localPath:H().optional(),content:H(),type:Q([`markdown`,`html`,`react`]),title:H(),revision:K(),createdAt:K(),updatedAt:K(),localError:H().optional()})),stale:J(),error:H().optional()});function $(e){return e}function bo(e){return e}function xo(e){return{threadId:$(e.threadId),totalParts:e.totalParts,historyFromNumber:e.historyFromNumber,stale:e.stale,nextBefore:e.nextBefore,parts:e.parts.map(So)}}function So(e){return{number:e.number,kind:e.kind,message:e.message?Co(e.message):null}}function Co(e){return{_id:e.id,threadId:$(e.threadId),runId:$(e.runId),userId:e.userId,type:e.type,text:e.text,attachments:e.attachments.map(e=>({storageId:$(e.storageId),name:e.name,mediaType:e.mediaType,size:e.size,url:e.url??null})),parts:e.parts,runStatus:e.runStatus,runStartedAt:e.runStartedAt,sourceNumbers:e.sourceNumbers,streamIds:e.streamIds,detailsLoaded:e.detailsLoaded}}function wo(e){return{threadId:$(e.threadId),runId:$(e.runId),runStatus:e.runStatus,streamId:e.streamId,text:e.text,parts:e.parts,runStartedAt:e.runStartedAt}}function To(e){return{...e,_id:$(e._id),contextSummaryThroughRunId:e.contextSummaryThroughRunId?$(e.contextSummaryThroughRunId):void 0}}function Eo(e){return{status:e.status,lastSyncedAt:e.lastSyncedAt}}function Do(e){return{...Eo(e),threads:e.threads.map(To)}}function Oo(e){return e.eventType===`updated`?{eventType:`updated`,live:wo(e.live)}:{eventType:`cleared`}}function ko(e){let{threadId:t,...n}=e;return e.scope===`thread`&&t?{...n,threadId:t}:n}function Ao(e){return{artifacts:e.artifacts.map(ko),stale:e.stale,error:e.error}}async function jo(e,t,n){if(!e.body)return;let r=e.body.getReader(),i=new TextDecoder,a=``;try{for(;!t.aborted;){let{done:e,value:o}=await r.read();if(e)break;a+=i.decode(o,{stream:!0});let s=a.indexOf(`
|
|
65
65
|
|
|
66
66
|
`);for(;s>=0;){let e=a.slice(0,s);a=a.slice(s+2);let r=e.split(`
|
|
67
67
|
`).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trimStart());r.length>0&&!t.aborted&&n(r.join(`
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{F as e,I as t,L as n,Q as r,X as i,n as a,ot as o,t as s}from"./CirtoWSJ.js";import"./mWKhuXx1.js";var c=class{constructor(e,t){this.status=e,this.body=typeof t==`string`?{message:t}:t||{message:`Error: ${e}`}}toString(){return JSON.stringify(this.body)}},l=class{constructor(e,t){try{new Headers({location:t})}catch{throw Error(`Invalid redirect location ${JSON.stringify(t)}: this string contains characters that cannot be used in HTTP headers`)}this.status=e,this.location=t}},u=class extends Error{constructor(e,t,n){super(n),this.status=e,this.text=t}};new URL(`sveltekit-internal://`);function d(e,t){return e===`/`||t===`ignore`?e:t===`never`?e.endsWith(`/`)?e.slice(0,-1):e:t===`always`&&!e.endsWith(`/`)?e+`/`:e}function f(e){return e.split(`%25`).map(decodeURI).join(`%25`)}function p(e){for(let t in e)e[t]=decodeURIComponent(e[t]);return e}function m({href:e}){return e.split(`#`)[0]}function ee(e,t,n,r=!1){let i=new URL(e);Object.defineProperty(i,"searchParams",{value:new Proxy(i.searchParams,{get(e,r){if(r===`get`||r===`getAll`||r===`has`)return(t,...i)=>(n(t),e[r](t,...i));t();let i=Reflect.get(e,r);return typeof i==`function`?i.bind(e):i}}),enumerable:!0,configurable:!0});let a=[`href`,`pathname`,`search`,`toString`,`toJSON`];r&&a.push(`hash`);for(let n of a)Object.defineProperty(i,n,{get(){return t(),e[n]},enumerable:!0,configurable:!0});return i}function h(){}function g(...e){let t=5381;for(let n of e)if(typeof n==`string`){let e=n.length;for(;e;)t=t*33^n.charCodeAt(--e)}else if(ArrayBuffer.isView(n)){let e=new Uint8Array(n.buffer,n.byteOffset,n.byteLength),r=e.length;for(;r;)t=t*33^e[--r]}else throw TypeError(`value must be a string or TypedArray`);return(t>>>0).toString(36)}new TextEncoder;function _(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}var te=window.fetch;window.fetch=(e,t)=>((e instanceof Request?e.method:t?.method||`GET`)!==`GET`&&v.delete(b(e)),te(e,t));var v=new Map;function y(e,t){let n=b(e,t),r=document.querySelector(n);if(r?.textContent){r.remove();let{body:e,...t}=JSON.parse(r.textContent);r.getAttribute(`data-b64`)!==null&&(e=_(e));let i=r.getAttribute(`data-ttl`);return i&&v.set(n,{body:e,init:t,ttl:1e3*Number(i)}),Promise.resolve(new Response(e,t))}return window.fetch(e,t)}function ne(e,t,n){if(v.size>0){let t=b(e,n),r=v.get(t);if(r){if(performance.now()<r.ttl&&[`default`,`force-cache`,`only-if-cached`,void 0].includes(n?.cache))return new Response(r.body,r.init);v.delete(t)}}return window.fetch(t,n)}function b(e,t){let n=`script[data-sveltekit-fetched][data-url=${JSON.stringify(e instanceof Request?e.url:e)}]`;if(t?.headers||t?.body){let e=[];t.headers&&e.push([...new Headers(t.headers)].join(`,`)),t.body&&(typeof t.body==`string`||ArrayBuffer.isView(t.body))&&e.push(t.body),n+=`[data-hash="${g(...e)}"]`}return n}var re=/^(\[)?(\.\.\.)?(\w+)(?:=(\w+))?(\])?$/,ie=/^\/\((?:[^)]+)\)$/;function ae(e){let t=[];return{pattern:e===`/`||ie.test(e)?/^\/$/:RegExp(`^${se(e).map(e=>{let n=/^\[\.\.\.(\w+)(?:=(\w+))?\]$/.exec(e);if(n)return t.push({name:n[1],matcher:n[2],optional:!1,rest:!0,chained:!0}),`(?:/([^]*))?`;let r=/^\[\[(\w+)(?:=(\w+))?\]\]$/.exec(e);if(r)return t.push({name:r[1],matcher:r[2],optional:!0,rest:!1,chained:!0}),`(?:/([^/]+))?`;if(!e)return;let i=e.split(/\[(.+?)\](?!\])/);return`/`+i.map((e,n)=>{if(n%2){if(e.startsWith(`x+`))return le(String.fromCharCode(parseInt(e.slice(2),16)));if(e.startsWith(`u+`))return le(String.fromCharCode(...e.slice(2).split(`-`).map(e=>parseInt(e,16))));let[,r,a,o,s]=re.exec(e);return t.push({name:o,matcher:s,optional:!!r,rest:!!a,chained:a?n===1&&i[0]===``:!1}),a?`([^]*?)`:r?`([^/]*)?`:`([^/]+?)`}return le(e)}).join(``)}).join(``)}/?$`),params:t}}function oe(e){return e!==``&&!/^\([^)]+\)$/.test(e)}function se(e){return e.slice(1).split(`/`).filter(oe)}function ce(e,t,n){let r={},i=e.slice(1),a=i.filter(e=>e!==void 0),o=0;for(let e=0;e<t.length;e+=1){let s=t[e],c=i[e-o];if(s.chained&&s.rest&&o&&(c=i.slice(e-o,e+1).filter(e=>e).join(`/`),o=0),c===void 0){if(s.rest)c=``;else continue}if(!s.matcher||n[s.matcher](c)){r[s.name]=c;let n=t[e+1],l=i[e+1];n&&!n.rest&&n.optional&&l&&s.chained&&(o=0),!n&&!l&&Object.keys(r).length===a.length&&(o=0);continue}if(s.optional&&s.chained){o++;continue}return}if(!o)return r}function le(e){return e.normalize().replace(/[[\]]/g,`\\$&`).replace(/%/g,`%25`).replace(/\//g,`%2[Ff]`).replace(/\?/g,`%3[Ff]`).replace(/#/g,`%23`).replace(/[.*+?^${}()|\\]/g,`\\$&`)}var ue=/\[(\[)?(\.\.\.)?(\w+?)(?:=(\w+))?\]\]?/g;function de(e,t){let n=se(e),r=e!=`/`&&e.endsWith(`/`);return`/`+n.map(n=>n.replace(ue,(n,r,i,a)=>{let o=t[a];if(!o){if(r||i&&o!==void 0)return``;throw Error(`Missing parameter '${a}' in route ${e}`)}if(o.startsWith(`/`)||o.endsWith(`/`))throw Error(`Parameter '${a}' in route ${e} cannot start or end with a slash -- this would cause an invalid route like foo//bar`);return o})).filter(Boolean).join(`/`)+(r?`/`:``)}function fe({nodes:e,server_loads:t,dictionary:n,matchers:r}){let i=new Set(t);return Object.entries(n).map(([t,[n,i,s]])=>{let{pattern:c,params:l}=ae(t),u={id:t,exec:e=>{let t=c.exec(e);if(t)return ce(t,l,r)},errors:[1,...s||[]].map(t=>e[t]),layouts:[0,...i||[]].map(o),leaf:a(n)};return u.errors.length=u.layouts.length=Math.max(u.errors.length,u.layouts.length),u});function a(t){let n=t<0;return n&&(t=~t),[n,e[t]]}function o(t){return t===void 0?t:[i.has(t),e[t]]}}function pe(e,t=JSON.parse){try{return t(sessionStorage[e])}catch{}}function me(e,t,n=JSON.stringify){let r=n(t);try{sessionStorage[e]=r}catch{}}var x=globalThis.__sveltekit_msi048?.base??``,he=globalThis.__sveltekit_msi048?.assets??x??``,ge=``;function _e(...e){if(!e[0].startsWith(`/`))throw Error(`Cannot use \`resolve(...)\` with a non-absolute pathname or route ID (got "${e[0]}"). \`resolve\` is only for internal pathnames and route IDs; external URLs should be used directly.`);return x+ge+de(e[0],e[1])}var ve=`1789152407843`,ye=`sveltekit:snapshot`,be=`sveltekit:scroll`,xe=`sveltekit:states`,S=`sveltekit:history`,C=`sveltekit:navigation`,w={tap:1,hover:2,viewport:3,eager:4,off:-1,false:-1},Se=location.origin;function Ce(e){if(e instanceof URL)return e;let t=document.baseURI;if(!t){let e=document.getElementsByTagName(`base`);t=e.length?e[0].href:document.URL}return new URL(e,t)}function T(){return{x:pageXOffset,y:pageYOffset}}function E(e,t){return e.getAttribute(`data-sveltekit-${t}`)}var we={...w,"":w.hover};function Te(e){let t=e.assignedSlot??e.parentNode;return t?.nodeType===11&&(t=t.host),t}function Ee(e,t){for(;e&&e!==t;){if(e.nodeName.toUpperCase()===`A`&&e.hasAttribute(`href`))return e;e=Te(e)}}function De(e,t,n){let r;try{if(r=new URL(e instanceof SVGAElement?e.href.baseVal:e.href,document.baseURI),n&&r.hash.match(/^#[^/]/)){let e=location.hash.split(`#`)[1]||`/`;r.hash=`#${e}${r.hash}`}}catch{}let i=e instanceof SVGAElement?e.target.baseVal:e.target,a=!r||!!i||D(r,t,n)||(e.getAttribute(`rel`)||``).split(/\s+/).includes(`external`),o=r?.origin===Se&&e.hasAttribute(`download`);return{url:r,external:a,target:i,download:o}}function Oe(e){let t=null,n=null,r=null,i=null,a=null,o=null,s=e;for(;s&&s!==document.documentElement;)r===null&&(r=E(s,`preload-code`)),i===null&&(i=E(s,`preload-data`)),t===null&&(t=E(s,`keepfocus`)),n===null&&(n=E(s,`noscroll`)),a===null&&(a=E(s,`reload`)),o===null&&(o=E(s,`replacestate`)),s=Te(s);function c(e){switch(e){case``:case`true`:return!0;case`off`:case`false`:return!1;default:return}}return{preload_code:we[r??`off`],preload_data:we[i??`off`],keepfocus:c(t),noscroll:c(n),reload:c(a),replace_state:c(o)}}function ke(e){let t=o(e),n=!0;function r(){n=!0,t.update(e=>e)}function i(e){n=!1,t.set(e)}function a(e){let r;return t.subscribe(t=>{(r===void 0||n&&t!==r)&&e(r=t)})}return{notify:r,set:i,subscribe:a}}var Ae={v:h};function je(){let{set:e,subscribe:t}=o(!1),n;async function r(){clearTimeout(n);try{let t=await fetch(`${he}/_app/version.json`,{headers:{pragma:`no-cache`,"cache-control":`no-cache`}});if(!t.ok)return!1;let r=(await t.json()).version!==ve;return r&&(e(!0),Ae.v(),clearTimeout(n)),r}catch{return!1}}return{subscribe:t,check:r}}function D(e,t,n){return e.origin!==Se||!e.pathname.startsWith(t)?!0:n?e.pathname!==location.pathname:!1}function Me(e){}var Ne=new Set([`load`,`prerender`,`csr`,`ssr`,`trailingSlash`,`config`]);[...Ne],[...new Set([...Ne])];function Pe(e){return e.filter(e=>e!=null)}function O(e,t){return e+`/`+t}function Fe(e){return e instanceof c||e instanceof u?e.status:500}function Ie(e){return e instanceof u?e.text:`Internal Error`}var k,A,Le,Re=a.toString().includes(`$$`)||/function \w+\(\) \{\}/.test(a.toString()),ze=`a:`;Re?(k={data:{},form:null,error:null,params:{},route:{id:null},state:{},status:-1,url:new URL(ze)},A={current:null},Le={current:!1}):(k=new class{#e=r({});get data(){return e(this.#e)}set data(e){i(this.#e,e)}#t=r(null);get form(){return e(this.#t)}set form(e){i(this.#t,e)}#n=r(null);get error(){return e(this.#n)}set error(e){i(this.#n,e)}#r=r({});get params(){return e(this.#r)}set params(e){i(this.#r,e)}#i=r({id:null});get route(){return e(this.#i)}set route(e){i(this.#i,e)}#a=r({});get state(){return e(this.#a)}set state(e){i(this.#a,e)}#o=r(-1);get status(){return e(this.#o)}set status(e){i(this.#o,e)}#s=r(new URL(ze));get url(){return e(this.#s)}set url(e){i(this.#s,e)}},A=new class{#e=r(null);get current(){return e(this.#e)}set current(e){i(this.#e,e)}},Le=new class{#e=r(!1);get current(){return e(this.#e)}set current(e){i(this.#e,e)}},Ae.v=()=>Le.current=!0);function Be(e){Object.assign(k,e)}var Ve={spanContext(){return He},setAttribute(){return this},setAttributes(){return this},addEvent(){return this},setStatus(){return this},updateName(){return this},end(){return this},isRecording(){return!1},recordException(){return this},addLink(){return this},addLinks(){return this}},He={traceId:``,spanId:``,traceFlags:0},{onMount:Ue,tick:We}=s,Ge=new Set([`icon`,`shortcut icon`,`apple-touch-icon`]),j=null,M=pe(`sveltekit:scroll`)??{},N=pe(`sveltekit:snapshot`)??{},P={url:ke({}),page:ke({}),navigating:o(null),updated:je()};function Ke(e){M[e]=T()}function qe(e,t){let n=e+1;for(;M[n];)delete M[n],n+=1;for(n=t+1;N[n];)delete N[n],n+=1}function F(e,t=!1){return t?location.replace(e.href):location.href=e.href,new Promise(h)}async function Je(){if(`serviceWorker`in navigator){let e=await navigator.serviceWorker.getRegistration(x||`/`);e&&await e.update()}}var Ye,Xe,I,L,Ze,R,Qe={},$e={},z=[],B=[],V=null;function H(){V?.fork?.then(e=>e?.discard()),V=null,Q={element:void 0,href:void 0}}var et=new Map,tt=new Set,nt=new Set,U=new Set,W={branch:[],error:null,url:null,nav:null},rt=!1,it=!1,at=!0,G=!1,K=!1,ot=!1,st=!1,ct,q,J,Y,lt=new Set,ut=new Map,dt=new Map;async function ft(e,t,n){if(globalThis.__sveltekit_msi048.data){let{q:e={},p:t={},l:n={},f:r={}}=globalThis.__sveltekit_msi048.data;for(let t in e)Qe[t]=e[t];for(let e in n)Qe[e]=n[e];for(let e in r)Qe[e]=r[e];for(let e in t)$e[e]=t[e]}document.URL!==location.href&&(location.href=location.href),R=e,await e.hooks.init?.(),Ye=fe(e),L=document.documentElement,Ze=t,Xe=e.nodes[0],I=e.nodes[1],Xe(),I(),q=history.state?.[S],J=history.state?.[C],q||(q=J=Date.now(),history.replaceState({...history.state,[S]:q,[C]:J},``));let r=M[q];function i(){r&&(history.scrollRestoration=`manual`,scrollTo(r.x,r.y))}n?(i(),await Bt(Ze,n)):(await Z({type:`enter`,url:Ce(R.hash?Kt(new URL(location.href)):location.href),replace_state:!0}),i()),zt()}function pt(){z.length=0,st=!1}function mt(e){B.some(e=>e?.snapshot)&&(N[e]=B.map(e=>e?.snapshot?.capture()))}function ht(e){N[e]?.forEach((e,t)=>{B[t]?.snapshot?.restore(e)})}function gt(){Ke(q),me(be,M),mt(J),me(ye,N)}async function _t(e,t,r,i){let a,o;t.invalidateAll&&H(),await Z({type:`goto`,url:Ce(e),keepfocus:t.keepFocus,noscroll:t.noScroll,replace_state:t.replaceState,state:t.state,redirect_count:r,nav_token:i,accept:()=>{if(t.invalidateAll){st=!0,a=new Set;for(let[e,t]of ut)for(let[n,r]of t)r.resource?.reset(),a.add(O(e,n));o=new Set;for(let[e,t]of dt)for(let n of t.keys())o.add(O(e,n))}t.invalidate&&t.invalidate.forEach(Rt)}}),t.invalidateAll&&n().then(n).then(()=>{for(let[e,t]of ut)for(let[n,{resource:r}]of t)a?.has(O(e,n))&&r.start();for(let[e,t]of dt)for(let[n,{resource:r}]of t)o?.has(O(e,n))&&r.reconnect()})}async function vt(e){if(e.id!==V?.id){H();let t={};lt.add(t),V={id:e.id,token:t,promise:Ot({...e,preload:t}).then(e=>(lt.delete(t),e.type===`loaded`&&e.state.error&&H(),e)),fork:null}}return V.promise}async function yt(e){let t=(await X(e,!1))?.route;t&&await Promise.all([...t.layouts,t.leaf].filter(Boolean).map(e=>e[1]()))}async function bt(e,t,n){let r={params:W.params,route:{id:W.route?.id??null},url:new URL(location.href)};if(W={...e.state,nav:r},Be(e.props.page),ct=new R.root({target:t,props:{...e.props,stores:P,components:B},hydrate:n,sync:!1,transformError:void 0}),await Promise.resolve(),n){let e={from:null,to:{...r,scroll:M[q]??T()},willUnload:!1,type:`enter`,complete:Promise.resolve()};U.forEach(t=>t(e))}ht(J),it=!0}async function xt({url:e,params:t,branch:n,errors:r,status:i,error:a,route:o,form:s}){let c=`never`;if(x&&(e.pathname===x||e.pathname===x+`/`))c=`always`;else for(let e of n)e?.slash!==void 0&&(c=e.slash);e.pathname=d(e.pathname,c),e.search=e.search;let l={type:`loaded`,state:{url:e,params:t,branch:n,error:a,route:o},props:{constructors:Pe(n).map(e=>e.node.component),page:Gt(k)}};s!==void 0&&(l.props.form=s);let u={},f=!k,p=0;for(let e=0;e<Math.max(n.length,W.branch.length);e+=1){let t=n[e],r=W.branch[e];t?.data!==r?.data&&(f=!0),t&&(u={...u,...t.data},f&&(l.props[`data_${p}`]=u),p+=1)}return(!W.url||e.href!==W.url.href||W.error!==a||s!==void 0&&s!==k.form||f)&&(l.props.page={error:a,params:t,route:{id:o?.id??null},state:{},status:i,url:new URL(e),form:s??null,data:f?u:k.data}),l}async function St({loader:e,parent:t,url:n,params:r,route:i,server_data_node:a}){let o=null,s=!0,c={dependencies:new Set,params:new Set,parent:!1,route:!1,url:!1,search_params:new Set},l=await e();if(l.universal?.load){function e(...e){for(let t of e){let{href:e}=new URL(t,n);c.dependencies.add(e)}}let u={tracing:{enabled:!1,root:Ve,current:Ve},route:new Proxy(i,{get:(e,t)=>(s&&(c.route=!0),e[t])}),params:new Proxy(r,{get:(e,t)=>(s&&c.params.add(t),e[t])}),data:a?.data??null,url:ee(n,()=>{s&&(c.url=!0)},e=>{s&&c.search_params.add(e)},R.hash),async fetch(t,r){t instanceof Request&&(r={body:t.method===`GET`||t.method===`HEAD`?void 0:await t.blob(),cache:t.cache,credentials:t.credentials,headers:[...t.headers].length>0?t?.headers:void 0,integrity:t.integrity,keepalive:t.keepalive,method:t.method,mode:t.mode,redirect:t.redirect,referrer:t.referrer,referrerPolicy:t.referrerPolicy,signal:t.signal,...r});let{resolved:i,promise:a}=Ct(t,r,n);return s&&e(i.href),a},setHeaders:h,depends:e,parent(){return s&&(c.parent=!0),t()},untrack(e){s=!1;try{return e()}finally{s=!0}}};o=await l.universal.load.call(null,u)??null}return{node:l,loader:e,server:a,universal:l.universal?.load?{type:`data`,data:o,uses:c}:null,data:o??a?.data??null,slash:l.universal?.trailingSlash??a?.slash}}function Ct(e,t,n){let r=e instanceof Request?e.url:e,i=new URL(r,n);return i.origin===n.origin&&(r=i.href.slice(n.origin.length)),{resolved:i,promise:it?ne(r,i.href,t):y(r,t)}}function wt(e,t,n,r,i,a){if(st)return!0;if(!i)return!1;if(i.parent&&e||i.route&&t||i.url&&n)return!0;for(let e of i.search_params)if(r.has(e))return!0;for(let e of i.params)if(a[e]!==W.params[e])return!0;for(let e of i.dependencies)if(z.some(t=>t(new URL(e))))return!0;return!1}function Tt(e,t){return e?.type===`data`?e:e?.type===`skip`?t??null:null}function Et(e,t){if(!e)return new Set(t.searchParams.keys());let n=new Set([...e.searchParams.keys(),...t.searchParams.keys()]);for(let r of n){let i=e.searchParams.getAll(r),a=t.searchParams.getAll(r);i.every(e=>a.includes(e))&&a.every(e=>i.includes(e))&&n.delete(r)}return n}function Dt({error:e,url:t,route:n,params:r}){return{type:`loaded`,state:{error:e,url:t,route:n,params:r,branch:[]},props:{page:Gt(k),constructors:[]}}}async function Ot({id:e,invalidating:t,url:n,params:r,route:i,preload:a}){if(V?.id===e)return lt.delete(V.token),V.promise;let{errors:o,layouts:s,leaf:u}=i,d=[...s,u];o.forEach(e=>e?.().catch(h)),d.forEach(e=>e?.[1]().catch(h));let f=W.url?e!==Nt(W.url):!1,p=W.route?i.id!==W.route.id:!1,m=Et(W.url,n),ee=!1,g=d.map(async(e,t)=>{if(!e)return;let a=W.branch[t];return e[1]===a?.loader&&!wt(ee,p,f,m,a.universal?.uses,r)?a:(ee=!0,St({loader:e[1],url:n,params:r,route:i,parent:async()=>{let e={};for(let n=0;n<t;n+=1)Object.assign(e,(await g[n])?.data);return e},server_data_node:Tt(e[0]?{type:`skip`}:null,e[0]?a?.server:void 0)}))});for(let e of g)e.catch(h);let _=[];for(let e=0;e<d.length;e+=1)if(d[e])try{_.push(await g[e])}catch(t){if(t instanceof l)return{type:`redirect`,location:t.location};if(a&<.has(a))return Dt({error:await $(t,{params:r,url:n,route:{id:i.id}}),url:n,params:r,route:i});let s=Fe(t),u;if(t instanceof c)u=t.body;else{if(await P.updated.check())return await Je(),await F(n);u=await $(t,{params:r,url:n,route:{id:i.id}})}let d=await kt(e,_,o);return d?xt({url:n,params:r,branch:_.slice(0,d.idx).concat(d.node),errors:o,status:s,error:u,route:i}):await Ft(n,{id:i.id},u,s)}else _.push(void 0);return xt({url:n,params:r,branch:_,errors:o,status:200,error:null,route:i,form:t?void 0:null})}async function kt(e,t,n){for(;e--;)if(n[e]){let r=e;for(;!t[r];)--r;try{return{idx:r+1,node:{node:await n[e](),loader:n[e],data:{},server:null,universal:null}}}catch{continue}}}async function At({status:e,error:t,url:n,route:r}){let i={};try{return xt({url:n,params:i,branch:[await St({loader:Xe,url:n,params:i,route:r,parent:()=>Promise.resolve({}),server_data_node:Tt(null)}),{node:await I(),loader:I,universal:null,server:null,data:null}],status:e,error:t,errors:[],route:null})}catch(t){if(t instanceof l){await _t(new URL(t.location,location.href),{},0);return}let a=await R.get_error_template(),o=await $(t,{url:n,params:i,route:r}),s=a({status:e,message:String(o?.message??``).replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`)}),c=new DOMParser().parseFromString(s,`text/html`);throw document.documentElement.replaceChild(document.adoptNode(c.head),document.head),document.documentElement.replaceChild(document.adoptNode(c.body),document.body),t}}async function jt(e){let t=e.href;if(et.has(t))return et.get(t);let n;try{let r=(async()=>{let t=await R.hooks.reroute({url:new URL(e),fetch:async(t,n)=>Ct(t,n,e).promise})??e;if(typeof t==`string`){let n=new URL(e);R.hash?n.hash=t:n.pathname=t,t=n}return t})();et.set(t,r),n=await r}catch{et.delete(t);return}return n}async function X(e,t){if(e&&!D(e,x,R.hash)){let n=await jt(e);if(!n)return;let r=Mt(n);for(let n of Ye){let i=n.exec(r);if(i)return{id:Nt(e),invalidating:t,route:n,params:p(i),url:e}}}}function Mt(e){return f(R.hash?e.hash.replace(/^#/,``).replace(/[?#].+/,``):e.pathname.slice(x.length))||`/`}function Nt(e){return(R.hash?e.hash.replace(/^#/,``):e.pathname)+e.search}function Pt({url:e,type:t,intent:n,delta:r,event:i,scroll:a}){let o=!1,s=Wt(W,n,e,t,a??null);r!==void 0&&(s.navigation.delta=r),i!==void 0&&(s.navigation.event=i);let c={...s.navigation,cancel:()=>{o=!0,s.reject(Error(`navigation cancelled`))}};return G||tt.forEach(e=>e(c)),o?null:s}async function Z({type:e,url:r,popped:i,keepfocus:a,noscroll:o,replace_state:s,state:c={},redirect_count:l=0,nav_token:d={},accept:f=h,block:p=h,event:m}){let ee=Y;Y=d;let g=await X(r,!1),_=e===`enter`?Wt(W,g,r,e):Pt({url:r,type:e,delta:i?.delta,intent:g,scroll:i?.scroll,event:m});if(!_){p(),Y===d&&(Y=ee);return}let te=q,v=J;f(),G=!0,it&&_.navigation.type!==`enter`&&P.navigating.set(A.current=_.navigation);let y=g&&await Ot(g);if(!y){if(D(r,x,R.hash))return await F(r,s);y=await Ft(r,{id:null},await $(new u(404,`Not Found`,`Not found: ${r.pathname}`),{url:r,params:{},route:{id:null}}),404,s)}if(r=g?.url||r,Y!==d){_.reject(Error(`navigation aborted`));return}if(!y)return;if(y.type===`redirect`){if(l<20){await Z({type:e,url:new URL(y.location,r),popped:i,keepfocus:a,noscroll:o,replace_state:s,state:c,redirect_count:l+1,nav_token:d}),_.fulfil(void 0);return}if(y=await At({status:500,error:await $(Error(`Redirect loop`),{url:r,params:{},route:{id:null}}),url:r,route:{id:null}}),!y)return}else if(y.props.page.status>=400&&await P.updated.check())return await Je(),await F(r,s);if(pt(),Ke(te),mt(v),y.props.page.url.pathname!==r.pathname&&(r.pathname=y.props.page.url.pathname),c=i?i.state:c,!i){let e=+!s,t={[S]:q+=e,[C]:J+=e,[xe]:c};(s?history.replaceState:history.pushState).call(history,t,``,r),s||qe(q,J)}let ne=g&&V?.id===g.id?V.fork:null;V?.fork&&!ne?H():(V=null,Q={element:void 0,href:void 0}),y.props.page.state=c;let b;if(it){let e=(await Promise.all(Array.from(nt,e=>e(_.navigation)))).filter(e=>typeof e==`function`);if(e.length>0){function t(){e.forEach(e=>{U.delete(e)})}e.push(t),e.forEach(e=>{U.add(e)})}let n=_.navigation.to;W={...y.state,nav:{params:n.params,route:n.route,url:n.url}},y.props.page&&(y.props.page.url=r),!a&&document.activeElement instanceof HTMLElement&&document.activeElement!==document.body&&document.activeElement.blur();let i=ne&&await ne;i?b=i.commit():(j=null,ct.$set(y.props),j&&Object.assign(y.props.page,j),Be(y.props.page),b=t?.()),ot=!0}else await bt(y,Ze,!1);let{activeElement:re}=document;if(await b,await n(),await n(),Y!==d){_.reject(Error(`navigation aborted`));return}y.props.page&&j&&Object.assign(y.props.page,j);let ie=null;if(at){let e=i?i.scroll:o?T():null;e?scrollTo(e.x,e.y):(ie=r.hash&&document.getElementById(qt(r)))?ie.scrollIntoView():scrollTo(0,0)}let ae=document.activeElement!==re&&document.activeElement!==document.body;!a&&!ae&&Ut(r,!ie),at=!0,G=!1,_.fulfil(void 0),_.navigation.to&&(_.navigation.to.scroll=T()),U.forEach(e=>e(_.navigation)),e===`popstate`&&ht(J),P.navigating.set(A.current=null)}async function Ft(e,t,n,r,i){return e.origin===Se&&e.pathname===location.pathname&&!rt?await At({status:r,error:n,url:e,route:t}):await F(e,i)}var Q={element:void 0,href:void 0};function It(){let e,t;L.addEventListener(`mousemove`,t=>{let n=t.target;clearTimeout(e),e=setTimeout(()=>{i(n,w.hover)},20)});function n(e){e.defaultPrevented||i(e.composedPath()[0],w.tap)}L.addEventListener(`mousedown`,n),L.addEventListener(`touchstart`,n,{passive:!0});let r=new IntersectionObserver(e=>{for(let t of e)t.isIntersecting&&(yt(new URL(t.target.href)),r.unobserve(t.target))},{threshold:0});async function i(e,n){let r=Ee(e,L),i=r===Q.element&&r?.href===Q.href&&n>=t;if(!r||i)return;let{url:a,external:o,download:s}=De(r,x,R.hash);if(o||s)return;let c=Oe(r),l=a&&Nt(W.url)===Nt(a);if(!(c.reload||l)){if(n<=c.preload_data){Q={element:r,href:r.href},t=w.tap;let e=await X(a,!1);if(!e)return;vt(e)}else n<=c.preload_code&&(Q={element:r,href:r.href},t=n,yt(a))}}function a(){r.disconnect();for(let e of L.querySelectorAll(`a`)){let{url:t,external:n,download:i}=De(e,x,R.hash);if(n||i)continue;let a=Oe(e);a.reload||(a.preload_code===w.viewport&&r.observe(e),a.preload_code===w.eager&&yt(t))}}U.add(a),a()}function $(e,t){if(e instanceof c)return e.body;let n=Fe(e),r=Ie(e);return R.hooks.handleError({error:e,event:t,status:n,message:r})??{message:r}}function Lt(e,t={}){return e=new URL(Ce(e)),e.origin===Se?_t(e,t,0):Promise.reject(Error(`goto: invalid URL`))}function Rt(e){if(typeof e==`function`)z.push(e);else{let{href:t}=new URL(e,location.href);z.push(e=>e.href===t)}}function zt(){history.scrollRestoration=`manual`,addEventListener(`beforeunload`,e=>{let t=!1;if(gt(),!G){let e=Wt(W,void 0,null,`leave`),n={...e.navigation,cancel:()=>{t=!0,e.reject(Error(`navigation cancelled`))}};tt.forEach(e=>e(n))}t?(e.preventDefault(),e.returnValue=``):history.scrollRestoration=`auto`}),addEventListener(`visibilitychange`,()=>{document.visibilityState===`hidden`&>()}),navigator.connection?.saveData||It(),L.addEventListener(`click`,async t=>{if(t.button||t.which!==1||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||t.defaultPrevented)return;let n=Ee(t.composedPath()[0],L);if(!n)return;let{url:r,external:i,target:a,download:o}=De(n,x,R.hash);if(!r)return;if(a===`_parent`||a===`_top`){if(window.parent!==window)return}else if(a&&a!==`_self`)return;let s=Oe(n);if(!(n instanceof SVGAElement)&&r.protocol!==location.protocol&&r.protocol!==`https:`&&r.protocol!==`http:`||o)return;let[c,l]=(R.hash?r.hash.replace(/^#/,``):r.href).split(`#`),u=c===m(location);if(i||s.reload&&(!u||!l)){Pt({url:r,type:`link`,event:t})?G=!0:t.preventDefault();return}if(l!==void 0&&u){let[,i]=W.url.href.split(`#`);if(i===l){if(t.preventDefault(),l===``||l===`top`&&n.ownerDocument.getElementById(`top`)===null)scrollTo({top:0});else{let e=n.ownerDocument.getElementById(decodeURIComponent(l));e&&(e.scrollIntoView(),e.focus())}return}if(K=!0,Ke(q),e(r),!s.replace_state)return;K=!1}t.preventDefault(),await new Promise(e=>{requestAnimationFrame(()=>{setTimeout(e,0)}),setTimeout(e,100)}),await Z({type:`link`,url:r,keepfocus:s.keepfocus,noscroll:s.noscroll,replace_state:s.replace_state??r.href===location.href,event:t})}),L.addEventListener(`submit`,e=>{if(e.defaultPrevented)return;let t=HTMLFormElement.prototype.cloneNode.call(e.target),n=e.submitter;if((n?.formTarget||t.target)===`_blank`||(n?.formMethod||t.method)!==`get`)return;let r=new URL(n?.hasAttribute(`formaction`)&&n?.formAction||t.action);if(D(r,x,!1))return;let i=e.target,a=Oe(i);if(a.reload)return;e.preventDefault(),e.stopPropagation();let o=new FormData(i,n);r.search=new URLSearchParams(o).toString(),Z({type:`form`,url:r,keepfocus:a.keepfocus,noscroll:a.noscroll,replace_state:a.replace_state??r.href===location.href,event:e})}),addEventListener(`popstate`,async t=>{if(!Ht){if(t.state?.[`sveltekit:history`]){let n=t.state[S];if(Y={},n===q)return;let r=M[n],i=t.state[`sveltekit:states`]??{},a=new URL(t.state[`sveltekit:pageurl`]??location.href),o=t.state[C],s=W.url?m(location)===m(W.url):!1;if(o===J&&(ot||s)){i!==k.state&&(k.state=i),e(a),M[q]=T(),r&&scrollTo(r.x,r.y),q=n;return}let c=n-q;await Z({type:`popstate`,url:a,popped:{state:i,scroll:r,delta:c},accept:()=>{q=n,J=o},block:()=>{history.go(-c)},nav_token:Y,event:t})}else K||(e(new URL(location.href)),R.hash&&location.reload())}}),addEventListener(`hashchange`,()=>{K&&(K=!1,history.replaceState({...history.state,[S]:++q,[C]:J},``,location.href))});for(let e of document.querySelectorAll(`link`))Ge.has(e.rel)&&(e.href=e.href);addEventListener(`pageshow`,e=>{e.persisted&&P.navigating.set(A.current=null)});function e(e){W.url=k.url=e,P.page.set(Gt(k)),P.page.notify()}}async function Bt(e,{status:t=200,error:n,node_ids:r,params:i,route:a,server_route:o,data:s,form:c}){rt=!0;let u=new URL(location.href),d;({params:i={},route:a={id:null}}=await X(u,!1)||{}),d=Ye.find(({id:e})=>e===a.id);let f,p=!0;try{let e=r.map(async(t,n)=>{let r=s[n];return r?.uses&&(r.uses=Vt(r.uses)),St({loader:R.nodes[t],url:u,params:i,route:a,parent:async()=>{let t={};for(let r=0;r<n;r+=1)Object.assign(t,(await e[r]).data);return t},server_data_node:Tt(r)})}),o=await Promise.all(e);if(d){let e=d.layouts;for(let t=0;t<e.length;t++)e[t]||o.splice(t,0,void 0)}f=await xt({url:u,params:i,branch:o,status:t,error:n,errors:d?.errors,form:c,route:d??null})}catch(t){if(t instanceof l)return await F(new URL(t.location,location.href));f=await At({status:Fe(t),error:await $(t,{url:u,params:i,route:a}),url:u,route:a}),e.textContent=``,p=!1}f&&(f.props.page&&(f.props.page.state={}),await bt(f,e,p))}function Vt(e){return{dependencies:new Set(e?.dependencies??[]),params:new Set(e?.params??[]),parent:!!e?.parent,route:!!e?.route,url:!!e?.url,search_params:new Set(e?.search_params??[])}}var Ht=!1;function Ut(e,t=!0){let n=document.querySelector(`[autofocus]`);if(n)n.focus();else{let n=qt(e);if(n&&document.getElementById(n)){let{x:r,y:i}=T();setTimeout(()=>{let a=history.state;Ht=!0,location.replace(new URL(`#${n}`,location.href)),history.replaceState(a,``,e),t&&scrollTo(r,i),Ht=!1})}else{let e=document.body,t=e.getAttribute(`tabindex`);e.tabIndex=-1,e.focus({preventScroll:!0,focusVisible:!1}),t===null?e.removeAttribute(`tabindex`):e.setAttribute(`tabindex`,t)}let r=getSelection();if(r&&r.type!==`None`){let e=[];for(let t=0;t<r.rangeCount;t+=1)e.push(r.getRangeAt(t));setTimeout(()=>{if(r.rangeCount===e.length){for(let t=0;t<r.rangeCount;t+=1){let n=e[t],i=r.getRangeAt(t);if(n.commonAncestorContainer!==i.commonAncestorContainer||n.startContainer!==i.startContainer||n.endContainer!==i.endContainer||n.startOffset!==i.startOffset||n.endOffset!==i.endOffset)return}r.removeAllRanges()}})}}}function Wt(e,t,n,r,i=null){let a,o,s=new Promise((e,t)=>{a=e,o=t});return s.catch(h),{navigation:{from:{params:e.params,route:{id:e.route?.id??null},url:e.url,scroll:T()},to:n&&{params:t?.params??null,route:{id:t?.route?.id??null},url:n,scroll:i},willUnload:!t,type:r,complete:s},fulfil:a,reject:o}}function Gt(e){return{data:e.data,error:e.error,form:e.form,params:e.params,route:e.route,state:e.state,status:e.status,url:e.url}}function Kt(e){let t=new URL(e);return t.hash=decodeURIComponent(e.hash),t}function qt(e){let t;if(R.hash){let[,,n]=e.hash.split(`#`,3);t=n??``}else t=e.hash.slice(1);return decodeURIComponent(t)}export{k as a,_e as c,A as i,ft as n,Le as o,P as r,Me as s,Lt as t};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{at as e,it as t,ot as n}from"./CirtoWSJ.js";import"./mWKhuXx1.js";import{C as r,S as i,_ as a,a as o,b as s,h as c,l,m as ee,r as te}from"./BXqRSpcY.js";var ne=`localhost`;`${ne}`;function re(e){let t=new URL(e);return t.hostname!==`127.0.0.1`&&t.hostname!==`[::1]`?null:(t.hostname=ne,t.toString())}function ie(e,t){return t||[`127.0.0.1`,`localhost`,`[::1]`].includes(e)}var u=Symbol.for(`functionName`),ae=Symbol.for(`toReferencePath`);function oe(e){return e[ae]??null}function se(e){return e.startsWith(`function://`)}function ce(e){let t;if(typeof e==`string`)t=se(e)?{functionHandle:e}:{name:e};else if(e[u])t={name:e[u]};else{let n=oe(e);if(!n)throw Error(`${e} is not a functionReference`);t={reference:n}}return t}function le(e){let t=ce(e);if(t.name===void 0)throw t.functionHandle===void 0?t.reference===void 0?Error(`Expected function reference like "api.file.func" or "internal.file.func", but received ${JSON.stringify(t)}`):Error(`Expected function reference in the current component like "api.file.func" or "internal.file.func", but received reference ${t.reference}`):Error(`Expected function reference like "api.file.func" or "internal.file.func", but received function handle ${t.functionHandle}`);if(typeof e==`string`)return e;let n=e[u];if(!n)throw Error(`${e} is not a functionReference`);return n}function ue(e=[]){return new Proxy({},{get(t,n){if(typeof n==`string`)return ue([...e,n]);if(n===u){if(e.length<2){let t=[`api`,...e].join(`.`);throw Error(`API path is expected to be of the form \`api.moduleName.functionName\`. Found: \`${t}\``)}let t=e.slice(0,-1).join(`/`),n=e[e.length-1];return n==="default"?t:t+`:`+n}if(n===Symbol.toStringTag)return`FunctionReference`}})}var de=ue();function fe(e,t){return new Proxy({},{get(n,r){if(typeof r==`string`)return fe(e,[...t,r]);if(r===ae){if(t.length<1){let n=[e,...t].join(`.`);throw Error(`API path is expected to be of the form \`${e}.childComponent.functionName\`. Found: \`${n}\``)}return`_reference/childComponent/`+t.join(`/`)}}})}var pe=()=>fe(`components`,[]),me=e=>{throw TypeError(e)},he=(e,t,n)=>t.has(e)||me(`Cannot `+n),d=(e,t,n)=>(he(e,t,`read from private field`),n?n.call(e):t.get(e)),f=(e,t,n)=>t.has(e)?me(`Cannot add the same private member more than once`):t instanceof WeakSet?t.add(e):t.set(e,n),p=(e,t,n,r)=>(he(e,t,`write to private field`),r?r.call(e,n):t.set(e,n),n),m=(e,t,n)=>(he(e,t,`access private method`),n),ge=class extends Error{constructor(){super(...arguments),this.status=500,this.name=`NoClientIdProvidedException`,this.message=`Missing Client ID. Pass it to the constructor (createClient("client_01HXRMBQ9BJ3E7QSTQ9X2PHVB7"))`}};function _e(e,t){if(!t.has(`code`))return!1;let{pathname:n}=window.location,r=new URL(e).pathname;return n===r||n===`${r}/`}function ve(){let e={};function t(t,n){e[t]=n}function n(t){return e[t]}function r(t){delete e[t]}function i(){e={}}return{setItem:t,getItem:n,removeItem:r,reset:i}}var h=ve();async function ye(){let e=be();return{codeVerifier:e,codeChallenge:await xe(e)}}function be(){return Se(crypto.getRandomValues(new Uint32Array(96)))}async function xe(e){return Se(await Ce(e))}function Se(e){return btoa(Array.from(new Uint8Array(e),e=>String.fromCharCode(e)).join(``)).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function Ce(e){let t=new TextEncoder().encode(e);return crypto.subtle.digest(`SHA-256`,t)}function we(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`),n=`=`.repeat((4-t.length%4)%4);return atob(t+n)}function Te(e){let t=e.split(`.`);if(t.length!==3)throw Error(`Invalid JWT format`);try{return{header:JSON.parse(we(t[0])),payload:JSON.parse(we(t[1]))}}catch(e){throw Error(`Failed to decode JWT: ${e instanceof Error?e.message:String(e)}`)}}var g={codeVerifier:`workos:code-verifier`,user:`workos:user`,accessToken:`workos:access-token`,refreshToken:`workos:refresh-token`,expiresAt:`workos:expires-at`,authenticationMethod:`workos:authentication-method`};function Ee(e){return Te(e).payload}function De(e){return`${g.refreshToken}:${e}`}function Oe(e,{devMode:t=!1,clientId:n}){let{user:r,accessToken:i,refreshToken:a,authenticationMethod:o}=e;h.setItem(g.user,r),h.setItem(g.accessToken,i),h.setItem(g.authenticationMethod,o),(t?window.localStorage:h).setItem(De(n),a);let{exp:s,iat:c}=Ee(i),l=s-c,ee=Date.now()+l*1e3;h.setItem(g.expiresAt,ee)}function ke({devMode:e=!1,clientId:t}){h.removeItem(g.user),h.removeItem(g.accessToken),h.removeItem(g.authenticationMethod);let n=e?window.localStorage:h;n.removeItem(De(t)),n.removeItem(g.refreshToken)}function Ae({devMode:e=!1,clientId:t}){let n=e?window.localStorage:h,r=n.getItem(De(t))??n.getItem(g.refreshToken);return typeof r==`string`?r:void 0}function je(e){let t=new URLSearchParams,n=Object.keys(e).sort();for(let r of n){let n=e[r];n&&t.append(r,n)}return t.toString()}var _=class extends Error{},v=class extends _{constructor(e,t={}){super(e,t.cause==null?void 0:{cause:t.cause}),this.name=`RefreshError`,this.status=t.status,this.error=t.error,this.isTransient=t.isTransient??!1}},Me=class extends _{},Ne=class extends _{constructor(){super(...arguments),this.message=`No access token available`}},y=class extends v{constructor(e=`Timed out waiting to refresh the session.`,t){super(e,{cause:t?.cause,isTransient:!0}),this.name=`RefreshTimeoutError`}},Pe=class extends _{constructor(){super(...arguments),this.message=`SignOut() called without an active session. Provide a returnTo URL to redirect anyway.`}},Fe=class e{constructor(){this.locked=new Map,this.addToLocked=(e,t)=>{let n=this.locked.get(e);n===void 0?t===void 0?this.locked.set(e,[]):this.locked.set(e,[t]):t!==void 0&&(n.unshift(t),this.locked.set(e,n))},this.isLocked=e=>this.locked.has(e),this.lock=e=>new Promise((t,n)=>{this.isLocked(e)?this.addToLocked(e,t):(this.addToLocked(e),t())}),this.unlock=e=>{let t=this.locked.get(e);if(t===void 0||t.length===0){this.locked.delete(e);return}let n=t.pop();this.locked.set(e,t),n!==void 0&&setTimeout(n,0)}}static getInstance(){return e.instance===void 0&&(e.instance=new e),e.instance}};function b(){return Fe.getInstance()}var Ie=`browser-tabs-lock-key`,x={key:async e=>{throw Error(`Unsupported`)},getItem:async e=>{throw Error(`Unsupported`)},clear:async()=>window.localStorage.clear(),removeItem:async e=>{throw Error(`Unsupported`)},setItem:async(e,t)=>{throw Error(`Unsupported`)},keySync:e=>window.localStorage.key(e),getItemSync:e=>window.localStorage.getItem(e),clearSync:()=>window.localStorage.clear(),removeItemSync:e=>window.localStorage.removeItem(e),setItemSync:(e,t)=>window.localStorage.setItem(e,t)};function Le(e){return new Promise(t=>setTimeout(t,e))}function Re(e){let t=``;for(let n=0;n<e;n++){let e=Math.floor(Math.random()*61);t+=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz`[e]}return t}function ze(){return Date.now().toString()+Re(15)}var Be=class e{constructor(t){this.acquiredIatSet=new Set,this.storageHandler=void 0,this.id=ze(),this.acquireLock=this.acquireLock.bind(this),this.releaseLock=this.releaseLock.bind(this),this.releaseLock__private__=this.releaseLock__private__.bind(this),this.waitForSomethingToChange=this.waitForSomethingToChange.bind(this),this.refreshLockWhileAcquired=this.refreshLockWhileAcquired.bind(this),this.storageHandler=t,e.waiters===void 0&&(e.waiters=[])}async acquireLock(t,n=5e3){let r=Date.now()+Re(4),i=Date.now()+n,a=`${Ie}-${t}`,o=this.storageHandler===void 0?x:this.storageHandler;for(;Date.now()<i;){if(await Le(30),o.getItemSync(a)===null){let e=`${this.id}-${t}-${r}`;await Le(Math.floor(Math.random()*25)),o.setItemSync(a,JSON.stringify({id:this.id,iat:r,timeoutKey:e,timeAcquired:Date.now(),timeRefreshed:Date.now()})),await Le(30);let n=o.getItemSync(a);if(n!==null){let e=JSON.parse(n);if(e.id===this.id&&e.iat===r)return this.acquiredIatSet.add(r),this.refreshLockWhileAcquired(a,r),!0}}else e.lockCorrector(this.storageHandler===void 0?x:this.storageHandler),await this.waitForSomethingToChange(i);r=Date.now()+Re(4)}return!1}async refreshLockWhileAcquired(e,t){setTimeout(async()=>{if(await b().lock(t),!this.acquiredIatSet.has(t)){b().unlock(t);return}let n=this.storageHandler===void 0?x:this.storageHandler,r=n.getItemSync(e);if(r!==null){let i=JSON.parse(r);i.timeRefreshed=Date.now(),n.setItemSync(e,JSON.stringify(i)),b().unlock(t)}else{b().unlock(t);return}this.refreshLockWhileAcquired(e,t)},1e3)}async waitForSomethingToChange(t){await new Promise(n=>{let r=!1,i=Date.now(),a=!1;function o(){if(a||=(window.removeEventListener(`storage`,o),e.removeFromWaiting(o),clearTimeout(s),!0),!r){r=!0;let e=50-(Date.now()-i);e>0?setTimeout(n,e):n(null)}}window.addEventListener(`storage`,o),e.addToWaiting(o);let s=setTimeout(o,Math.max(0,t-Date.now()))})}static addToWaiting(t){this.removeFromWaiting(t),e.waiters!==void 0&&e.waiters.push(t)}static removeFromWaiting(t){e.waiters!==void 0&&(e.waiters=e.waiters.filter(e=>e!==t))}static notifyWaiters(){e.waiters!==void 0&&[...e.waiters].forEach(e=>e())}async releaseLock(e){return await this.releaseLock__private__(e)}async releaseLock__private__(t){let n=this.storageHandler===void 0?x:this.storageHandler,r=`${Ie}-${t}`,i=n.getItemSync(r);if(i===null)return;let a=JSON.parse(i);a.id===this.id&&(await b().lock(a.iat),this.acquiredIatSet.delete(a.iat),n.removeItemSync(r),b().unlock(a.iat),e.notifyWaiters())}static lockCorrector(t){let n=Date.now()-5e3,r=t,i=[],a=0;for(;;){let e=r.keySync(a);if(e===null)break;i.push(e),a++}let o=!1;for(let e=0;e<i.length;e++){let t=i[e];if(t.includes(Ie)){let e=r.getItemSync(t);if(e!==null){let i=JSON.parse(e);(i.timeRefreshed===void 0&&i.timeAcquired<n||i.timeRefreshed!==void 0&&i.timeRefreshed<n)&&(r.removeItemSync(t),o=!0)}}}o&&e.notifyWaiters()}};Be.waiters=void 0;var Ve=Be,He=1e4;function Ue(e,t,{timeout:n=He}={}){if(!e)throw TypeError(`lockName is required and must be a non-empty string.`);return`locks`in navigator?We(e,t,n):Ge(e,t,n)}async function We(e,t,n){try{return await navigator.locks.request(e,{signal:AbortSignal.timeout(n)},t)}catch(t){if(t instanceof DOMException)switch(t.name){case`TimeoutError`:case`AbortError`:throw new Ke(`AcquisitionTimeoutError`,e,`Native`)}throw t}}async function Ge(e,t,n){let r=new Ve;try{if(await r.acquireLock(e,n))return await t();throw new Ke(`AcquisitionTimeoutError`,e,`Vendor`)}finally{await r.releaseLock(e)}}var Ke=class extends Error{constructor(e,t,n){super(`Lock acquisition timed out for "${t}" (${n})`),this.name=e,this.lockName=t}},qe=e=>({object:e.object,id:e.id,email:e.email,emailVerified:e.email_verified,firstName:e.first_name,profilePictureUrl:e.profile_picture_url,lastName:e.last_name,lastSignInAt:e.last_sign_in_at,externalId:e.external_id,createdAt:e.created_at,updatedAt:e.updated_at}),Je=e=>{let{user:t,organization_id:n,access_token:r,refresh_token:i,authentication_method:a,impersonator:o,...s}=e;return{user:qe(t),organizationId:n,accessToken:r,refreshToken:i,authenticationMethod:a,impersonator:o,...s}},Ye=`api.workos.com`,Xe=new Set([408,429,500,502,503,504]),S,C,w,Ze,Qe,$e=class{constructor({clientId:e,hostname:t=Ye,port:n,https:r=!0}){f(this,w),f(this,S),f(this,C),p(this,S,`${r?`https`:`http`}://${t}${n?`:${n}`:``}`),p(this,C,e)}async authenticateWithRefreshToken({refreshToken:e,organizationId:t,useCookie:n}){let r=await m(this,w,Qe).call(this,`/user_management/authenticate`,{useCookie:n,body:{client_id:d(this,C),grant_type:`refresh_token`,...!n&&{refresh_token:e},organization_id:t}});if(r.ok)return Je(await r.json());let{status:i}=r,a=await m(this,w,Ze).call(this,r);throw new v(a.error_description,{status:i,error:a.error,isTransient:Xe.has(i)})}async authenticateWithCode({code:e,codeVerifier:t,useCookie:n}){let r=await m(this,w,Qe).call(this,`/user_management/authenticate`,{useCookie:n,body:{code:e,client_id:d(this,C),grant_type:`authorization_code`,code_verifier:t}});if(r.ok)return Je(await r.json());throw new Me((await r.json()).error_description)}getAuthorizationUrl({connectionId:e,context:t,domainHint:n,loginHint:r,organizationId:i,provider:a=`authkit`,redirectUri:o,state:s,screenHint:c,passwordResetToken:l,invitationToken:ee,codeChallenge:te,codeChallengeMethod:ne}){if(!a&&!e&&!i)throw TypeError(`Incomplete arguments. Need to specify either a 'connectionId', 'organizationId', or 'provider'.`);if(a!==`authkit`&&c)throw TypeError(`'screenHint' is only supported for 'authkit' provider`);t&&console.warn("`context` is deprecated. We previously required initiate login endpoints to return the\n`context` query parameter when getting the authorization URL. This is no longer necessary.");let re=je({connection_id:e,organization_id:i,domain_hint:n,login_hint:r,provider:a,client_id:d(this,C),redirect_uri:o,response_type:`code`,state:s,screen_hint:c,invitation_token:ee,password_reset_token:l,code_challenge:te,code_challenge_method:ne});return`${d(this,S)}/user_management/authorize?${re}`}getLogoutUrl({sessionId:e,returnTo:t}){let n=new URL(`/user_management/sessions/logout`,d(this,S));return n.searchParams.set(`session_id`,e),t&&n.searchParams.set(`return_to`,t),n}};S=new WeakMap,C=new WeakMap,w=new WeakSet,Ze=async function(e){try{return await e.json()}catch{return{}}},Qe=function(e,{body:t,useCookie:n}){return fetch(new URL(e,d(this,S)),{method:`POST`,...n&&{credentials:`include`},headers:{Accept:`application/json, text/plain, */*`,"Content-Type":`application/json`},body:JSON.stringify(t)})};var et=`workos_organization_id`;function T(e){return`workos-org-id:${e}`}var tt=`WORKOS_REFRESH_SESSION`;function nt(e){let t=document.cookie.match(/(?:^|;\s*)workos-has-session=([^;]*)/);if(!t)return!1;let n=t[1];return n===`1`||n.split(`.`).includes(e)}var E,D,O,k,A,j,M,N,P,F,I,L,rt,it,R,z,at,ot,B,V,st,ct,lt,ut=class{constructor(e,{apiHostname:t,https:n,port:r,redirectUri:i=window.origin,devMode:a=location.hostname===`localhost`||location.hostname===`127.0.0.1`,onBeforeAutoRefresh:o=()=>!document.hidden,onRedirectCallback:s=e=>{},onRefresh:c,onRefreshFailure:l,refreshBufferInterval:ee=10}={}){if(f(this,L),f(this,E),f(this,D),f(this,O),f(this,k),f(this,A),f(this,j),f(this,M),f(this,N),f(this,P),f(this,F),f(this,I),!e)throw new ge;p(this,O,e),p(this,k,new $e({clientId:e,hostname:t,port:r,https:n})),p(this,j,a),p(this,A,i),p(this,E,{tag:`INITIAL`}),p(this,M,o),p(this,N,s),p(this,P,c),p(this,F,l),p(this,I,ee)}async initialize(){if(d(this,E).tag!==`INITIAL`)return;let e=new URLSearchParams(window.location.search);if(_e(d(this,A),e))await m(this,L,rt).call(this);else if(nt(d(this,O))||Ae({devMode:d(this,j),clientId:d(this,O)}))try{await m(this,L,z).call(this),m(this,L,R).call(this)}catch{m(this,L,it).call(this)}}async getSignInUrl(e={}){return await m(this,L,B).call(this,{...e})}async getSignUpUrl(e={}){return await m(this,L,B).call(this,{...e,screenHint:`sign-up`})}async signIn(e={}){let t=await m(this,L,B).call(this,{...e});window.location.assign(t)}async signUp(e={}){let t=await m(this,L,B).call(this,{...e,screenHint:`sign-up`});window.location.assign(t)}signOut(e={navigate:!0}){let{navigate:t=!0,returnTo:n}=e,r=h.getItem(g.accessToken);if(typeof r!=`string`){if(t)throw new Pe;return Promise.reject(new Pe)}let{sid:i}=Ee(r),a=d(this,k).getLogoutUrl({sessionId:i,returnTo:n});if(a){if(ke({devMode:d(this,j),clientId:d(this,O)}),sessionStorage.removeItem(T(d(this,O))),sessionStorage.removeItem(et),t)window.location.assign(a);else return new Promise(async e=>{fetch(a,{mode:`no-cors`,credentials:`include`}).catch(e=>{console.warn(`AuthKit: Failed to send logout request`,e)}).finally(e)})}}async getAccessToken(e){if(e?.forceRefresh||m(this,L,ot).call(this))try{await m(this,L,z).call(this)}catch(t){if(t instanceof y){let t=e?.forceRefresh?void 0:m(this,L,st).call(this);if(t)return t;try{await m(this,L,z).call(this)}catch(e){throw e instanceof y?e:e instanceof v?e.isTransient?e:new Ne:e}}else if(t instanceof v){if(t.isTransient){let n=e?.forceRefresh?void 0:m(this,L,st).call(this);if(n)return n;throw t}throw new Ne}else throw t}let t=m(this,L,V).call(this);if(!t)throw new Ne;return t}getUser(){return h.getItem(g.user)||null}dispose(){clearTimeout(d(this,D)),h.reset()}async switchToOrganization({organizationId:e,signInOpts:t={}}){try{await m(this,L,z).call(this,{organizationId:e})}catch(n){if(n instanceof y)console.warn(`Couldn't switch organization: lock acquisition timed out.`);else if(n instanceof v){if(n.isTransient)throw n;this.signIn({...t,organizationId:e})}else throw n}}};E=new WeakMap,D=new WeakMap,O=new WeakMap,k=new WeakMap,A=new WeakMap,j=new WeakMap,M=new WeakMap,N=new WeakMap,P=new WeakMap,F=new WeakMap,I=new WeakMap,L=new WeakSet,rt=async function(){if(d(this,E).tag!==`INITIAL`)return;let e=new URL(window.location.href),t=e.searchParams.get(`code`),n=e.searchParams.get(`state`),r;if(n)try{r=JSON.parse(n)}catch{console.warn("AuthKit: ignoring malformed `state` parameter")}let i=window.sessionStorage.getItem(g.codeVerifier);if(t){if(i)try{p(this,E,{tag:`AUTHENTICATING`,response:d(this,k).authenticateWithCode({code:t,codeVerifier:i,useCookie:d(this,L,ct)})});let e=await d(this,E).response;e&&(p(this,E,{tag:`AUTHENTICATED`}),m(this,L,R).call(this),Oe(e,{devMode:d(this,j),clientId:d(this,O)}),m(this,L,lt).call(this,e),d(this,N).call(this,{state:r,...e}))}catch(e){p(this,E,{tag:`ERROR`}),console.error(e)}else p(this,E,{tag:`ERROR`}),console.error(`Couldn't exchange code.
|
|
1
|
+
import{at as e,it as t,ot as n}from"./CirtoWSJ.js";import"./mWKhuXx1.js";import{C as r,S as i,_ as a,a as o,b as s,h as c,l,m as ee,r as te}from"./B3_FWG8N.js";var ne=`localhost`;`${ne}`;function re(e){let t=new URL(e);return t.hostname!==`127.0.0.1`&&t.hostname!==`[::1]`?null:(t.hostname=ne,t.toString())}function ie(e,t){return t||[`127.0.0.1`,`localhost`,`[::1]`].includes(e)}var u=Symbol.for(`functionName`),ae=Symbol.for(`toReferencePath`);function oe(e){return e[ae]??null}function se(e){return e.startsWith(`function://`)}function ce(e){let t;if(typeof e==`string`)t=se(e)?{functionHandle:e}:{name:e};else if(e[u])t={name:e[u]};else{let n=oe(e);if(!n)throw Error(`${e} is not a functionReference`);t={reference:n}}return t}function le(e){let t=ce(e);if(t.name===void 0)throw t.functionHandle===void 0?t.reference===void 0?Error(`Expected function reference like "api.file.func" or "internal.file.func", but received ${JSON.stringify(t)}`):Error(`Expected function reference in the current component like "api.file.func" or "internal.file.func", but received reference ${t.reference}`):Error(`Expected function reference like "api.file.func" or "internal.file.func", but received function handle ${t.functionHandle}`);if(typeof e==`string`)return e;let n=e[u];if(!n)throw Error(`${e} is not a functionReference`);return n}function ue(e=[]){return new Proxy({},{get(t,n){if(typeof n==`string`)return ue([...e,n]);if(n===u){if(e.length<2){let t=[`api`,...e].join(`.`);throw Error(`API path is expected to be of the form \`api.moduleName.functionName\`. Found: \`${t}\``)}let t=e.slice(0,-1).join(`/`),n=e[e.length-1];return n==="default"?t:t+`:`+n}if(n===Symbol.toStringTag)return`FunctionReference`}})}var de=ue();function fe(e,t){return new Proxy({},{get(n,r){if(typeof r==`string`)return fe(e,[...t,r]);if(r===ae){if(t.length<1){let n=[e,...t].join(`.`);throw Error(`API path is expected to be of the form \`${e}.childComponent.functionName\`. Found: \`${n}\``)}return`_reference/childComponent/`+t.join(`/`)}}})}var pe=()=>fe(`components`,[]),me=e=>{throw TypeError(e)},he=(e,t,n)=>t.has(e)||me(`Cannot `+n),d=(e,t,n)=>(he(e,t,`read from private field`),n?n.call(e):t.get(e)),f=(e,t,n)=>t.has(e)?me(`Cannot add the same private member more than once`):t instanceof WeakSet?t.add(e):t.set(e,n),p=(e,t,n,r)=>(he(e,t,`write to private field`),r?r.call(e,n):t.set(e,n),n),m=(e,t,n)=>(he(e,t,`access private method`),n),ge=class extends Error{constructor(){super(...arguments),this.status=500,this.name=`NoClientIdProvidedException`,this.message=`Missing Client ID. Pass it to the constructor (createClient("client_01HXRMBQ9BJ3E7QSTQ9X2PHVB7"))`}};function _e(e,t){if(!t.has(`code`))return!1;let{pathname:n}=window.location,r=new URL(e).pathname;return n===r||n===`${r}/`}function ve(){let e={};function t(t,n){e[t]=n}function n(t){return e[t]}function r(t){delete e[t]}function i(){e={}}return{setItem:t,getItem:n,removeItem:r,reset:i}}var h=ve();async function ye(){let e=be();return{codeVerifier:e,codeChallenge:await xe(e)}}function be(){return Se(crypto.getRandomValues(new Uint32Array(96)))}async function xe(e){return Se(await Ce(e))}function Se(e){return btoa(Array.from(new Uint8Array(e),e=>String.fromCharCode(e)).join(``)).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function Ce(e){let t=new TextEncoder().encode(e);return crypto.subtle.digest(`SHA-256`,t)}function we(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`),n=`=`.repeat((4-t.length%4)%4);return atob(t+n)}function Te(e){let t=e.split(`.`);if(t.length!==3)throw Error(`Invalid JWT format`);try{return{header:JSON.parse(we(t[0])),payload:JSON.parse(we(t[1]))}}catch(e){throw Error(`Failed to decode JWT: ${e instanceof Error?e.message:String(e)}`)}}var g={codeVerifier:`workos:code-verifier`,user:`workos:user`,accessToken:`workos:access-token`,refreshToken:`workos:refresh-token`,expiresAt:`workos:expires-at`,authenticationMethod:`workos:authentication-method`};function Ee(e){return Te(e).payload}function De(e){return`${g.refreshToken}:${e}`}function Oe(e,{devMode:t=!1,clientId:n}){let{user:r,accessToken:i,refreshToken:a,authenticationMethod:o}=e;h.setItem(g.user,r),h.setItem(g.accessToken,i),h.setItem(g.authenticationMethod,o),(t?window.localStorage:h).setItem(De(n),a);let{exp:s,iat:c}=Ee(i),l=s-c,ee=Date.now()+l*1e3;h.setItem(g.expiresAt,ee)}function ke({devMode:e=!1,clientId:t}){h.removeItem(g.user),h.removeItem(g.accessToken),h.removeItem(g.authenticationMethod);let n=e?window.localStorage:h;n.removeItem(De(t)),n.removeItem(g.refreshToken)}function Ae({devMode:e=!1,clientId:t}){let n=e?window.localStorage:h,r=n.getItem(De(t))??n.getItem(g.refreshToken);return typeof r==`string`?r:void 0}function je(e){let t=new URLSearchParams,n=Object.keys(e).sort();for(let r of n){let n=e[r];n&&t.append(r,n)}return t.toString()}var _=class extends Error{},v=class extends _{constructor(e,t={}){super(e,t.cause==null?void 0:{cause:t.cause}),this.name=`RefreshError`,this.status=t.status,this.error=t.error,this.isTransient=t.isTransient??!1}},Me=class extends _{},Ne=class extends _{constructor(){super(...arguments),this.message=`No access token available`}},y=class extends v{constructor(e=`Timed out waiting to refresh the session.`,t){super(e,{cause:t?.cause,isTransient:!0}),this.name=`RefreshTimeoutError`}},Pe=class extends _{constructor(){super(...arguments),this.message=`SignOut() called without an active session. Provide a returnTo URL to redirect anyway.`}},Fe=class e{constructor(){this.locked=new Map,this.addToLocked=(e,t)=>{let n=this.locked.get(e);n===void 0?t===void 0?this.locked.set(e,[]):this.locked.set(e,[t]):t!==void 0&&(n.unshift(t),this.locked.set(e,n))},this.isLocked=e=>this.locked.has(e),this.lock=e=>new Promise((t,n)=>{this.isLocked(e)?this.addToLocked(e,t):(this.addToLocked(e),t())}),this.unlock=e=>{let t=this.locked.get(e);if(t===void 0||t.length===0){this.locked.delete(e);return}let n=t.pop();this.locked.set(e,t),n!==void 0&&setTimeout(n,0)}}static getInstance(){return e.instance===void 0&&(e.instance=new e),e.instance}};function b(){return Fe.getInstance()}var Ie=`browser-tabs-lock-key`,x={key:async e=>{throw Error(`Unsupported`)},getItem:async e=>{throw Error(`Unsupported`)},clear:async()=>window.localStorage.clear(),removeItem:async e=>{throw Error(`Unsupported`)},setItem:async(e,t)=>{throw Error(`Unsupported`)},keySync:e=>window.localStorage.key(e),getItemSync:e=>window.localStorage.getItem(e),clearSync:()=>window.localStorage.clear(),removeItemSync:e=>window.localStorage.removeItem(e),setItemSync:(e,t)=>window.localStorage.setItem(e,t)};function Le(e){return new Promise(t=>setTimeout(t,e))}function Re(e){let t=``;for(let n=0;n<e;n++){let e=Math.floor(Math.random()*61);t+=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz`[e]}return t}function ze(){return Date.now().toString()+Re(15)}var Be=class e{constructor(t){this.acquiredIatSet=new Set,this.storageHandler=void 0,this.id=ze(),this.acquireLock=this.acquireLock.bind(this),this.releaseLock=this.releaseLock.bind(this),this.releaseLock__private__=this.releaseLock__private__.bind(this),this.waitForSomethingToChange=this.waitForSomethingToChange.bind(this),this.refreshLockWhileAcquired=this.refreshLockWhileAcquired.bind(this),this.storageHandler=t,e.waiters===void 0&&(e.waiters=[])}async acquireLock(t,n=5e3){let r=Date.now()+Re(4),i=Date.now()+n,a=`${Ie}-${t}`,o=this.storageHandler===void 0?x:this.storageHandler;for(;Date.now()<i;){if(await Le(30),o.getItemSync(a)===null){let e=`${this.id}-${t}-${r}`;await Le(Math.floor(Math.random()*25)),o.setItemSync(a,JSON.stringify({id:this.id,iat:r,timeoutKey:e,timeAcquired:Date.now(),timeRefreshed:Date.now()})),await Le(30);let n=o.getItemSync(a);if(n!==null){let e=JSON.parse(n);if(e.id===this.id&&e.iat===r)return this.acquiredIatSet.add(r),this.refreshLockWhileAcquired(a,r),!0}}else e.lockCorrector(this.storageHandler===void 0?x:this.storageHandler),await this.waitForSomethingToChange(i);r=Date.now()+Re(4)}return!1}async refreshLockWhileAcquired(e,t){setTimeout(async()=>{if(await b().lock(t),!this.acquiredIatSet.has(t)){b().unlock(t);return}let n=this.storageHandler===void 0?x:this.storageHandler,r=n.getItemSync(e);if(r!==null){let i=JSON.parse(r);i.timeRefreshed=Date.now(),n.setItemSync(e,JSON.stringify(i)),b().unlock(t)}else{b().unlock(t);return}this.refreshLockWhileAcquired(e,t)},1e3)}async waitForSomethingToChange(t){await new Promise(n=>{let r=!1,i=Date.now(),a=!1;function o(){if(a||=(window.removeEventListener(`storage`,o),e.removeFromWaiting(o),clearTimeout(s),!0),!r){r=!0;let e=50-(Date.now()-i);e>0?setTimeout(n,e):n(null)}}window.addEventListener(`storage`,o),e.addToWaiting(o);let s=setTimeout(o,Math.max(0,t-Date.now()))})}static addToWaiting(t){this.removeFromWaiting(t),e.waiters!==void 0&&e.waiters.push(t)}static removeFromWaiting(t){e.waiters!==void 0&&(e.waiters=e.waiters.filter(e=>e!==t))}static notifyWaiters(){e.waiters!==void 0&&[...e.waiters].forEach(e=>e())}async releaseLock(e){return await this.releaseLock__private__(e)}async releaseLock__private__(t){let n=this.storageHandler===void 0?x:this.storageHandler,r=`${Ie}-${t}`,i=n.getItemSync(r);if(i===null)return;let a=JSON.parse(i);a.id===this.id&&(await b().lock(a.iat),this.acquiredIatSet.delete(a.iat),n.removeItemSync(r),b().unlock(a.iat),e.notifyWaiters())}static lockCorrector(t){let n=Date.now()-5e3,r=t,i=[],a=0;for(;;){let e=r.keySync(a);if(e===null)break;i.push(e),a++}let o=!1;for(let e=0;e<i.length;e++){let t=i[e];if(t.includes(Ie)){let e=r.getItemSync(t);if(e!==null){let i=JSON.parse(e);(i.timeRefreshed===void 0&&i.timeAcquired<n||i.timeRefreshed!==void 0&&i.timeRefreshed<n)&&(r.removeItemSync(t),o=!0)}}}o&&e.notifyWaiters()}};Be.waiters=void 0;var Ve=Be,He=1e4;function Ue(e,t,{timeout:n=He}={}){if(!e)throw TypeError(`lockName is required and must be a non-empty string.`);return`locks`in navigator?We(e,t,n):Ge(e,t,n)}async function We(e,t,n){try{return await navigator.locks.request(e,{signal:AbortSignal.timeout(n)},t)}catch(t){if(t instanceof DOMException)switch(t.name){case`TimeoutError`:case`AbortError`:throw new Ke(`AcquisitionTimeoutError`,e,`Native`)}throw t}}async function Ge(e,t,n){let r=new Ve;try{if(await r.acquireLock(e,n))return await t();throw new Ke(`AcquisitionTimeoutError`,e,`Vendor`)}finally{await r.releaseLock(e)}}var Ke=class extends Error{constructor(e,t,n){super(`Lock acquisition timed out for "${t}" (${n})`),this.name=e,this.lockName=t}},qe=e=>({object:e.object,id:e.id,email:e.email,emailVerified:e.email_verified,firstName:e.first_name,profilePictureUrl:e.profile_picture_url,lastName:e.last_name,lastSignInAt:e.last_sign_in_at,externalId:e.external_id,createdAt:e.created_at,updatedAt:e.updated_at}),Je=e=>{let{user:t,organization_id:n,access_token:r,refresh_token:i,authentication_method:a,impersonator:o,...s}=e;return{user:qe(t),organizationId:n,accessToken:r,refreshToken:i,authenticationMethod:a,impersonator:o,...s}},Ye=`api.workos.com`,Xe=new Set([408,429,500,502,503,504]),S,C,w,Ze,Qe,$e=class{constructor({clientId:e,hostname:t=Ye,port:n,https:r=!0}){f(this,w),f(this,S),f(this,C),p(this,S,`${r?`https`:`http`}://${t}${n?`:${n}`:``}`),p(this,C,e)}async authenticateWithRefreshToken({refreshToken:e,organizationId:t,useCookie:n}){let r=await m(this,w,Qe).call(this,`/user_management/authenticate`,{useCookie:n,body:{client_id:d(this,C),grant_type:`refresh_token`,...!n&&{refresh_token:e},organization_id:t}});if(r.ok)return Je(await r.json());let{status:i}=r,a=await m(this,w,Ze).call(this,r);throw new v(a.error_description,{status:i,error:a.error,isTransient:Xe.has(i)})}async authenticateWithCode({code:e,codeVerifier:t,useCookie:n}){let r=await m(this,w,Qe).call(this,`/user_management/authenticate`,{useCookie:n,body:{code:e,client_id:d(this,C),grant_type:`authorization_code`,code_verifier:t}});if(r.ok)return Je(await r.json());throw new Me((await r.json()).error_description)}getAuthorizationUrl({connectionId:e,context:t,domainHint:n,loginHint:r,organizationId:i,provider:a=`authkit`,redirectUri:o,state:s,screenHint:c,passwordResetToken:l,invitationToken:ee,codeChallenge:te,codeChallengeMethod:ne}){if(!a&&!e&&!i)throw TypeError(`Incomplete arguments. Need to specify either a 'connectionId', 'organizationId', or 'provider'.`);if(a!==`authkit`&&c)throw TypeError(`'screenHint' is only supported for 'authkit' provider`);t&&console.warn("`context` is deprecated. We previously required initiate login endpoints to return the\n`context` query parameter when getting the authorization URL. This is no longer necessary.");let re=je({connection_id:e,organization_id:i,domain_hint:n,login_hint:r,provider:a,client_id:d(this,C),redirect_uri:o,response_type:`code`,state:s,screen_hint:c,invitation_token:ee,password_reset_token:l,code_challenge:te,code_challenge_method:ne});return`${d(this,S)}/user_management/authorize?${re}`}getLogoutUrl({sessionId:e,returnTo:t}){let n=new URL(`/user_management/sessions/logout`,d(this,S));return n.searchParams.set(`session_id`,e),t&&n.searchParams.set(`return_to`,t),n}};S=new WeakMap,C=new WeakMap,w=new WeakSet,Ze=async function(e){try{return await e.json()}catch{return{}}},Qe=function(e,{body:t,useCookie:n}){return fetch(new URL(e,d(this,S)),{method:`POST`,...n&&{credentials:`include`},headers:{Accept:`application/json, text/plain, */*`,"Content-Type":`application/json`},body:JSON.stringify(t)})};var et=`workos_organization_id`;function T(e){return`workos-org-id:${e}`}var tt=`WORKOS_REFRESH_SESSION`;function nt(e){let t=document.cookie.match(/(?:^|;\s*)workos-has-session=([^;]*)/);if(!t)return!1;let n=t[1];return n===`1`||n.split(`.`).includes(e)}var E,D,O,k,A,j,M,N,P,F,I,L,rt,it,R,z,at,ot,B,V,st,ct,lt,ut=class{constructor(e,{apiHostname:t,https:n,port:r,redirectUri:i=window.origin,devMode:a=location.hostname===`localhost`||location.hostname===`127.0.0.1`,onBeforeAutoRefresh:o=()=>!document.hidden,onRedirectCallback:s=e=>{},onRefresh:c,onRefreshFailure:l,refreshBufferInterval:ee=10}={}){if(f(this,L),f(this,E),f(this,D),f(this,O),f(this,k),f(this,A),f(this,j),f(this,M),f(this,N),f(this,P),f(this,F),f(this,I),!e)throw new ge;p(this,O,e),p(this,k,new $e({clientId:e,hostname:t,port:r,https:n})),p(this,j,a),p(this,A,i),p(this,E,{tag:`INITIAL`}),p(this,M,o),p(this,N,s),p(this,P,c),p(this,F,l),p(this,I,ee)}async initialize(){if(d(this,E).tag!==`INITIAL`)return;let e=new URLSearchParams(window.location.search);if(_e(d(this,A),e))await m(this,L,rt).call(this);else if(nt(d(this,O))||Ae({devMode:d(this,j),clientId:d(this,O)}))try{await m(this,L,z).call(this),m(this,L,R).call(this)}catch{m(this,L,it).call(this)}}async getSignInUrl(e={}){return await m(this,L,B).call(this,{...e})}async getSignUpUrl(e={}){return await m(this,L,B).call(this,{...e,screenHint:`sign-up`})}async signIn(e={}){let t=await m(this,L,B).call(this,{...e});window.location.assign(t)}async signUp(e={}){let t=await m(this,L,B).call(this,{...e,screenHint:`sign-up`});window.location.assign(t)}signOut(e={navigate:!0}){let{navigate:t=!0,returnTo:n}=e,r=h.getItem(g.accessToken);if(typeof r!=`string`){if(t)throw new Pe;return Promise.reject(new Pe)}let{sid:i}=Ee(r),a=d(this,k).getLogoutUrl({sessionId:i,returnTo:n});if(a){if(ke({devMode:d(this,j),clientId:d(this,O)}),sessionStorage.removeItem(T(d(this,O))),sessionStorage.removeItem(et),t)window.location.assign(a);else return new Promise(async e=>{fetch(a,{mode:`no-cors`,credentials:`include`}).catch(e=>{console.warn(`AuthKit: Failed to send logout request`,e)}).finally(e)})}}async getAccessToken(e){if(e?.forceRefresh||m(this,L,ot).call(this))try{await m(this,L,z).call(this)}catch(t){if(t instanceof y){let t=e?.forceRefresh?void 0:m(this,L,st).call(this);if(t)return t;try{await m(this,L,z).call(this)}catch(e){throw e instanceof y?e:e instanceof v?e.isTransient?e:new Ne:e}}else if(t instanceof v){if(t.isTransient){let n=e?.forceRefresh?void 0:m(this,L,st).call(this);if(n)return n;throw t}throw new Ne}else throw t}let t=m(this,L,V).call(this);if(!t)throw new Ne;return t}getUser(){return h.getItem(g.user)||null}dispose(){clearTimeout(d(this,D)),h.reset()}async switchToOrganization({organizationId:e,signInOpts:t={}}){try{await m(this,L,z).call(this,{organizationId:e})}catch(n){if(n instanceof y)console.warn(`Couldn't switch organization: lock acquisition timed out.`);else if(n instanceof v){if(n.isTransient)throw n;this.signIn({...t,organizationId:e})}else throw n}}};E=new WeakMap,D=new WeakMap,O=new WeakMap,k=new WeakMap,A=new WeakMap,j=new WeakMap,M=new WeakMap,N=new WeakMap,P=new WeakMap,F=new WeakMap,I=new WeakMap,L=new WeakSet,rt=async function(){if(d(this,E).tag!==`INITIAL`)return;let e=new URL(window.location.href),t=e.searchParams.get(`code`),n=e.searchParams.get(`state`),r;if(n)try{r=JSON.parse(n)}catch{console.warn("AuthKit: ignoring malformed `state` parameter")}let i=window.sessionStorage.getItem(g.codeVerifier);if(t){if(i)try{p(this,E,{tag:`AUTHENTICATING`,response:d(this,k).authenticateWithCode({code:t,codeVerifier:i,useCookie:d(this,L,ct)})});let e=await d(this,E).response;e&&(p(this,E,{tag:`AUTHENTICATED`}),m(this,L,R).call(this),Oe(e,{devMode:d(this,j),clientId:d(this,O)}),m(this,L,lt).call(this,e),d(this,N).call(this,{state:r,...e}))}catch(e){p(this,E,{tag:`ERROR`}),console.error(e)}else p(this,E,{tag:`ERROR`}),console.error(`Couldn't exchange code.
|
|
2
2
|
|
|
3
3
|
An authorization_code was supplied for a login which did not originate at the application. This could happen for various reasons:
|
|
4
4
|
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./BAh8Fpli.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./CirtoWSJ.js";import{a as e,r as t}from"./
|
|
1
|
+
import"./CirtoWSJ.js";import{a as e,r as t}from"./BAh8Fpli.js";var n={get data(){return e.data},get error(){return e.error},get form(){return e.form},get params(){return e.params},get route(){return e.route},get state(){return e.state},get status(){return e.status},get url(){return e.url}};t.updated.check;var r=n;export{r as t};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{$ as e,F as t,H as n,J as r,Q as i,R as a,X as o,pt as s,st as c,ut as l}from"./CirtoWSJ.js";import{_ as u}from"./
|
|
1
|
+
import{$ as e,F as t,H as n,J as r,Q as i,R as a,X as o,pt as s,st as c,ut as l}from"./CirtoWSJ.js";import{_ as u}from"./BS_wiDNx.js";for(var d=`1.45.0`,f=[],p=[],m=Uint8Array,h=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,g=0,_=h.length;g<_;++g)f[g]=h[g],p[h.charCodeAt(g)]=g;p[45]=62,p[95]=63;function v(e){var t=e.length;if(t%4>0)throw Error(`Invalid string. Length must be a multiple of 4`);var n=e.indexOf(`=`);n===-1&&(n=t);var r=n===t?0:4-n%4;return[n,r]}function ee(e,t,n){return(t+n)*3/4-n}function y(e){var t,n=v(e),r=n[0],i=n[1],a=new m(ee(e,r,i)),o=0,s=i>0?r-4:r,c;for(c=0;c<s;c+=4)t=p[e.charCodeAt(c)]<<18|p[e.charCodeAt(c+1)]<<12|p[e.charCodeAt(c+2)]<<6|p[e.charCodeAt(c+3)],a[o++]=t>>16&255,a[o++]=t>>8&255,a[o++]=t&255;return i===2&&(t=p[e.charCodeAt(c)]<<2|p[e.charCodeAt(c+1)]>>4,a[o++]=t&255),i===1&&(t=p[e.charCodeAt(c)]<<10|p[e.charCodeAt(c+1)]<<4|p[e.charCodeAt(c+2)]>>2,a[o++]=t>>8&255,a[o++]=t&255),a}function b(e){return f[e>>18&63]+f[e>>12&63]+f[e>>6&63]+f[e&63]}function te(e,t,n){for(var r,i=[],a=t;a<n;a+=3)r=(e[a]<<16&16711680)+(e[a+1]<<8&65280)+(e[a+2]&255),i.push(b(r));return i.join(``)}function x(e){for(var t,n=e.length,r=n%3,i=[],a=16383,o=0,s=n-r;o<s;o+=a)i.push(te(e,o,o+a>s?s:o+a));return r===1?(t=e[n-1],i.push(f[t>>2]+f[t<<4&63]+`==`)):r===2&&(t=(e[n-2]<<8)+e[n-1],i.push(f[t>>10]+f[t>>4&63]+f[t<<2&63]+`=`)),i.join(``)}function S(e){if(e===void 0)return{};if(!re(e))throw Error(`The arguments to a Convex function must be an object. Received: ${e}`);return e}function ne(e){if(e===void 0)throw Error(`Client created with undefined deployment address. If you used an environment variable, check that it's set.`);if(typeof e!=`string`)throw Error(`Invalid deployment address: found ${e}".`);if(!(e.startsWith(`http:`)||e.startsWith(`https:`)))throw Error(`Invalid deployment address: Must start with "https://" or "http://". Found "${e}".`);try{new URL(e)}catch{throw Error(`Invalid deployment address: "${e}" is not a valid URL. If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}if(e.endsWith(`.convex.site`))throw Error(`Invalid deployment address: "${e}" ends with .convex.site, which is used for HTTP Actions. Convex deployment URLs typically end with .convex.cloud? If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}function re(e){let t=typeof e==`object`,n=Object.getPrototypeOf(e),r=n===null||n===Object.prototype||n?.constructor?.name===`Object`;return t&&r}var ie=!0,C=BigInt(`-9223372036854775808`),w=BigInt(`9223372036854775807`),ae=BigInt(`0`),oe=BigInt(`8`),se=BigInt(`256`),ce=`This commit timestamp is unresolved: its value is assigned when the mutation commits. Read the document after the mutation completes to get its value.`,le=class{[Symbol.toPrimitive](e){if(e===`string`)return this.toString();throw Error(ce)}valueOf(){throw Error(ce)}toJSON(){throw Error(ce)}toString(){return`[unresolved commit timestamp]`}},ue=new le;function de(e){return Number.isNaN(e)||!Number.isFinite(e)||Object.is(e,-0)}function fe(e){e<ae&&(e-=C+C);let t=e.toString(16);t.length%2==1&&(t=`0`+t);let n=new Uint8Array(new ArrayBuffer(8)),r=0;for(let i of t.match(/.{2}/g).reverse())n.set([parseInt(i,16)],r++),e>>=oe;return x(n)}function pe(e){let t=y(e);if(t.byteLength!==8)throw Error(`Received ${t.byteLength} bytes, expected 8 for $integer`);let n=ae,r=ae;for(let e of t)n+=BigInt(e)*se**r,r++;return n>w&&(n+=C+C),n}function me(e){if(e<C||w<e)throw Error(`BigInt ${e} does not fit into a 64-bit signed integer.`);let t=new ArrayBuffer(8);return new DataView(t).setBigInt64(0,e,!0),x(new Uint8Array(t))}function he(e){let t=y(e);if(t.byteLength!==8)throw Error(`Received ${t.byteLength} bytes, expected 8 for $integer`);return new DataView(t.buffer).getBigInt64(0,!0)}var ge=DataView.prototype.setBigInt64?me:fe,_e=DataView.prototype.getBigInt64?he:pe,ve=1024;function ye(e){if(e.length>ve)throw Error(`Field name ${e} exceeds maximum field name length ${ve}.`);if(e.startsWith(`$`))throw Error(`Field name ${e} starts with a '$', which is reserved.`);for(let t=0;t<e.length;t+=1){let n=e.charCodeAt(t);if(n<32||n>=127)throw Error(`Field name ${e} has invalid character '${e[t]}': Field names can only contain non-control ASCII characters`)}}function T(e){if(e===null||typeof e==`boolean`||typeof e==`number`||typeof e==`string`)return e;if(Array.isArray(e))return e.map(e=>T(e));if(typeof e!=`object`)throw Error(`Unexpected type of ${e}`);let t=Object.entries(e);if(t.length===1){let n=t[0][0];if(n===`$bytes`){if(typeof e.$bytes!=`string`)throw Error(`Malformed $bytes field on ${e}`);return y(e.$bytes).buffer}if(n===`$integer`){if(typeof e.$integer!=`string`)throw Error(`Malformed $integer field on ${e}`);return _e(e.$integer)}if(n===`$float`){if(typeof e.$float!=`string`)throw Error(`Malformed $float field on ${e}`);let t=y(e.$float);if(t.byteLength!==8)throw Error(`Received ${t.byteLength} bytes, expected 8 for $float`);let n=new DataView(t.buffer).getFloat64(0,ie);if(!de(n))throw Error(`Float ${n} should be encoded as a number`);return n}if(n===`$commitTs`){if(e.$commitTs!==null)throw Error(`Malformed $commitTs field on ${e}`);return ue}if(n===`$set`)throw Error(`Received a Set which is no longer supported as a Convex type.`);if(n===`$map`)throw Error(`Received a Map which is no longer supported as a Convex type.`)}let n={};for(let[t,r]of Object.entries(e))ye(t),n[t]=T(r);return n}var be=16384;function E(e){let t=JSON.stringify(e,(e,t)=>t===void 0?`undefined`:typeof t==`bigint`?`${t.toString()}n`:t);if(t.length>be){let e=16370,n=t.codePointAt(e-1);return n!==void 0&&n>65535&&--e,t.substring(0,e)+`[...truncated]`}return t}function D(e,t,n,r){if(e===void 0){let e=n&&` (present at path ${n} in original object ${E(t)})`;throw Error(`undefined is not a valid Convex value${e}. To learn about Convex's supported types, see https://docs.convex.dev/using/types.`)}if(e===null)return e;if(typeof e==`bigint`){if(e<C||w<e)throw Error(`BigInt ${e} does not fit into a 64-bit signed integer.`);return{$integer:ge(e)}}if(typeof e==`number`){if(de(e)){let t=new ArrayBuffer(8);return new DataView(t).setFloat64(0,e,ie),{$float:x(new Uint8Array(t))}}return e}if(typeof e==`boolean`||typeof e==`string`)return e;if(e instanceof ArrayBuffer)return{$bytes:x(new Uint8Array(e))};if(e instanceof le)return{$commitTs:null};if(Array.isArray(e))return e.map((e,r)=>D(e,t,n+`[${r}]`,!1));if(e instanceof Set)throw Error(xe(n,`Set`,[...e],t));if(e instanceof Map)throw Error(xe(n,`Map`,[...e],t));if(!re(e)){let r=e?.constructor?.name,i=r?`${r} `:``;throw Error(xe(n,i,e,t))}let i={},a=Object.entries(e);a.sort(([e,t],[n,r])=>e===n?0:e<n?-1:1);for(let[e,o]of a)o===void 0?r&&(ye(e),i[e]=Se(o,t,n+`.${e}`)):(ye(e),i[e]=D(o,t,n+`.${e}`,!1));return i}function xe(e,t,n,r){return e?`${t}${E(n)} is not a supported Convex type (present at path ${e} in original object ${E(r)}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`:`${t}${E(n)} is not a supported Convex type.`}function Se(e,t,n){if(e===void 0)return{$undefined:null};if(t===void 0)throw Error(`Programming error. Current value is ${E(e)} but original value is undefined`);return D(e,t,n,!1)}function O(e){return D(e,e,``,!1)}var Ce=Object.defineProperty,we=(e,t,n)=>t in e?Ce(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Te=(e,t,n)=>we(e,typeof t==`symbol`?t:t+``,n),Ee,De,Oe=Symbol.for(`ConvexError`),k=class extends (De=Error,Ee=Oe,De){constructor(e){super(typeof e==`string`?e:E(e)),Te(this,`name`,`ConvexError`),Te(this,`data`),Te(this,Ee,!0),this.data=e}},ke=Object.defineProperty,Ae=(e,t,n)=>t in e?ke(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,je=(e,t,n)=>Ae(e,typeof t==`symbol`?t:t+``,n),Me=`color:rgb(0, 145, 255)`;function Ne(e){switch(e){case`query`:return`Q`;case`mutation`:return`M`;case`action`:return`A`;case`any`:return`?`}}var Pe=class{constructor(e){je(this,`_onLogLineFuncs`),je(this,`_verbose`),this._onLogLineFuncs={},this._verbose=e.verbose}addLogLineListener(e){let t=Math.random().toString(36).substring(2,15);for(let e=0;e<10&&this._onLogLineFuncs[t]!==void 0;e++)t=Math.random().toString(36).substring(2,15);return this._onLogLineFuncs[t]=e,()=>{delete this._onLogLineFuncs[t]}}logVerbose(...e){if(this._verbose)for(let t of Object.values(this._onLogLineFuncs))t(`debug`,`${new Date().toISOString()}`,...e)}log(...e){for(let t of Object.values(this._onLogLineFuncs))t(`info`,...e)}warn(...e){for(let t of Object.values(this._onLogLineFuncs))t(`warn`,...e)}error(...e){for(let t of Object.values(this._onLogLineFuncs))t(`error`,...e)}};function Fe(e){let t=new Pe(e);return t.addLogLineListener((e,...t)=>{switch(e){case`debug`:console.debug(...t);break;case`info`:console.log(...t);break;case`warn`:console.warn(...t);break;case`error`:console.error(...t);break;default:console.log(...t)}}),t}function Ie(e){return new Pe(e)}function A(e,t,n,r,i){let a=Ne(n);if(typeof i==`object`&&(i=`ConvexError ${JSON.stringify(i.errorData,null,2)}`),t===`info`){let t=i.match(/^\[.*?\] /);if(t===null){e.error(`[CONVEX ${a}(${r})] Could not parse console.log`);return}let n=i.slice(1,t[0].length-2),o=i.slice(t[0].length);e.log(`%c[CONVEX ${a}(${r})] [${n}]`,Me,o)}else e.error(`[CONVEX ${a}(${r})] ${i}`)}function Le(e,t){let n=`[CONVEX FATAL ERROR] ${t}`;return e.error(n),Error(n)}function j(e,t,n){return`[CONVEX ${Ne(e)}(${t})] ${n.errorMessage}
|
|
2
2
|
Called by client`}function M(e,t){return t.data=e.errorData,t}function N(e){let t=e.split(`:`),n,r;return t.length===1?(n=t[0],r=`default`):(n=t.slice(0,t.length-1).join(`:`),r=t[t.length-1]),n.endsWith(`.js`)&&(n=n.slice(0,-3)),`${n}:${r}`}function P(e,t){return JSON.stringify({udfPath:N(e),args:O(t)})}function Re(e,t,n){let{initialNumItems:r,id:i}=n;return JSON.stringify({type:`paginated`,udfPath:N(e),args:O(t),options:O({initialNumItems:r,id:i})})}function ze(e){return JSON.parse(e).type===`paginated`}var Be=Object.defineProperty,Ve=(e,t,n)=>t in e?Be(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,F=(e,t,n)=>Ve(e,typeof t==`symbol`?t:t+``,n),He=class{constructor(){F(this,`nextQueryId`),F(this,`querySetVersion`),F(this,`querySet`),F(this,`queryIdToToken`),F(this,`identityVersion`),F(this,`auth`),F(this,`outstandingQueriesOlderThanRestart`),F(this,`outstandingAuthOlderThanRestart`),F(this,`paused`),F(this,`pendingQuerySetModifications`),this.nextQueryId=0,this.querySetVersion=0,this.identityVersion=0,this.querySet=new Map,this.queryIdToToken=new Map,this.outstandingQueriesOlderThanRestart=new Set,this.outstandingAuthOlderThanRestart=!1,this.paused=!1,this.pendingQuerySetModifications=new Map}hasSyncedPastLastReconnect(){return this.outstandingQueriesOlderThanRestart.size===0&&!this.outstandingAuthOlderThanRestart}markAuthCompletion(){this.outstandingAuthOlderThanRestart=!1}subscribe(e,t,n,r){let i=N(e),a=P(i,t),o=this.querySet.get(a);if(o!==void 0)return o.numSubscribers+=1,{queryToken:a,modification:null,unsubscribe:()=>this.removeSubscriber(a)};{let e=this.nextQueryId++,o={id:e,canonicalizedUdfPath:i,args:t,numSubscribers:1,journal:n,componentPath:r};this.querySet.set(a,o),this.queryIdToToken.set(e,a);let s=this.querySetVersion,c=this.querySetVersion+1,l={type:`Add`,queryId:e,udfPath:i,args:[O(t)],journal:n,componentPath:r};return this.paused?this.pendingQuerySetModifications.set(e,l):this.querySetVersion=c,{queryToken:a,modification:{type:`ModifyQuerySet`,baseVersion:s,newVersion:c,modifications:[l]},unsubscribe:()=>this.removeSubscriber(a)}}}transition(e){for(let t of e.modifications)switch(t.type){case`QueryUpdated`:case`QueryFailed`:{this.outstandingQueriesOlderThanRestart.delete(t.queryId);let e=t.journal;if(e!==void 0){let n=this.queryIdToToken.get(t.queryId);n!==void 0&&(this.querySet.get(n).journal=e)}break}case`QueryRemoved`:this.outstandingQueriesOlderThanRestart.delete(t.queryId);break;default:throw Error(`Invalid modification ${t.type}`)}}queryId(e,t){let n=P(N(e),t),r=this.querySet.get(n);return r===void 0?null:r.id}isCurrentOrNewerAuthVersion(e){return e>=this.identityVersion}getAuth(){return this.auth}setAuth(e){this.auth={tokenType:`User`,value:e};let t=this.identityVersion;return this.paused||(this.identityVersion=t+1),{type:`Authenticate`,baseVersion:t,...this.auth}}setAdminAuth(e,t){let n={tokenType:`Admin`,value:e,impersonating:t};this.auth=n;let r=this.identityVersion;return this.paused||(this.identityVersion=r+1),{type:`Authenticate`,baseVersion:r,...n}}clearAuth(){this.auth=void 0,this.markAuthCompletion();let e=this.identityVersion;return this.paused||(this.identityVersion=e+1),{type:`Authenticate`,tokenType:`None`,baseVersion:e}}hasAuth(){return!!this.auth}isNewAuth(e){return this.auth?.value!==e}queryPath(e){let t=this.queryIdToToken.get(e);return t?this.querySet.get(t).canonicalizedUdfPath:null}queryArgs(e){let t=this.queryIdToToken.get(e);return t?this.querySet.get(t).args:null}queryToken(e){return this.queryIdToToken.get(e)??null}queryJournal(e){return this.querySet.get(e)?.journal}restart(){this.unpause(),this.outstandingQueriesOlderThanRestart.clear();let e=[];for(let t of this.querySet.values()){let n={type:`Add`,queryId:t.id,udfPath:t.canonicalizedUdfPath,args:[O(t.args)],journal:t.journal,componentPath:t.componentPath};e.push(n),this.outstandingQueriesOlderThanRestart.add(t.id)}this.querySetVersion=1;let t={type:`ModifyQuerySet`,baseVersion:0,newVersion:1,modifications:e};if(!this.auth)return this.identityVersion=0,[t,void 0];this.outstandingAuthOlderThanRestart=!0;let n={type:`Authenticate`,baseVersion:0,...this.auth};return this.identityVersion=1,[t,n]}pause(){this.paused=!0}resume(){let e=this.pendingQuerySetModifications.size>0?{type:`ModifyQuerySet`,baseVersion:this.querySetVersion,newVersion:++this.querySetVersion,modifications:Array.from(this.pendingQuerySetModifications.values())}:void 0,t=this.auth===void 0?void 0:{type:`Authenticate`,baseVersion:this.identityVersion++,...this.auth};return this.unpause(),[e,t]}unpause(){this.paused=!1,this.pendingQuerySetModifications.clear()}removeSubscriber(e){let t=this.querySet.get(e);if(t.numSubscribers>1)return--t.numSubscribers,null;{this.querySet.delete(e),this.queryIdToToken.delete(t.id),this.outstandingQueriesOlderThanRestart.delete(t.id);let n=this.querySetVersion,r=this.querySetVersion+1,i={type:`Remove`,queryId:t.id};return this.paused?this.pendingQuerySetModifications.has(t.id)?this.pendingQuerySetModifications.delete(t.id):this.pendingQuerySetModifications.set(t.id,i):this.querySetVersion=r,{type:`ModifyQuerySet`,baseVersion:n,newVersion:r,modifications:[i]}}}},Ue=Object.defineProperty,We=(e,t,n)=>t in e?Ue(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,I=(e,t,n)=>We(e,typeof t==`symbol`?t:t+``,n),Ge=class{constructor(e,t){this.logger=e,this.markConnectionStateDirty=t,I(this,`inflightRequests`),I(this,`requestsOlderThanRestart`),I(this,`inflightMutationsCount`,0),I(this,`inflightActionsCount`,0),this.inflightRequests=new Map,this.requestsOlderThanRestart=new Set}request(e,t){let n=new Promise(n=>{let r=t?`Requested`:`NotSent`;this.inflightRequests.set(e.requestId,{message:e,status:{status:r,requestedAt:new Date,onResult:n}}),e.type===`Mutation`?this.inflightMutationsCount++:e.type===`Action`&&this.inflightActionsCount++});return this.markConnectionStateDirty(),n}onResponse(e){let t=this.inflightRequests.get(e.requestId);if(t===void 0||t.status.status===`Completed`)return null;let n=t.message.type===`Mutation`?`mutation`:`action`,r=t.message.udfPath;for(let t of e.logLines)A(this.logger,`info`,n,r,t);let i=t.status,a,o;if(e.success)a={success:!0,logLines:e.logLines,value:T(e.result)},o=()=>i.onResult(a);else{let t=e.result,{errorData:s}=e;A(this.logger,`error`,n,r,t),a={success:!1,errorMessage:t,errorData:s===void 0?void 0:T(s),logLines:e.logLines},o=()=>i.onResult(a)}return e.type===`ActionResponse`||!e.success?(o(),this.inflightRequests.delete(e.requestId),this.requestsOlderThanRestart.delete(e.requestId),t.message.type===`Action`?this.inflightActionsCount--:t.message.type===`Mutation`&&this.inflightMutationsCount--,this.markConnectionStateDirty(),{requestId:e.requestId,result:a}):(t.status={status:`Completed`,result:a,ts:e.ts,onResolve:o},null)}removeCompleted(e){let t=new Map;for(let[n,r]of this.inflightRequests.entries()){let i=r.status;i.status===`Completed`&&i.ts.lessThanOrEqual(e)&&(i.onResolve(),t.set(n,i.result),r.message.type===`Mutation`?this.inflightMutationsCount--:r.message.type===`Action`&&this.inflightActionsCount--,this.inflightRequests.delete(n),this.requestsOlderThanRestart.delete(n))}return t.size>0&&this.markConnectionStateDirty(),t}restart(){this.requestsOlderThanRestart=new Set(this.inflightRequests.keys());let e=[];for(let[t,n]of this.inflightRequests){if(n.status.status===`NotSent`){n.status.status=`Requested`,e.push(n.message);continue}if(n.message.type===`Mutation`)e.push(n.message);else if(n.message.type===`Action`){if(this.inflightRequests.delete(t),this.requestsOlderThanRestart.delete(t),this.inflightActionsCount--,n.status.status===`Completed`)throw Error(`Action should never be in 'Completed' state`);n.status.onResult({success:!1,errorMessage:`Connection lost while action was in flight`,logLines:[]})}}return this.markConnectionStateDirty(),e}resume(){let e=[];for(let[,t]of this.inflightRequests)if(t.status.status===`NotSent`){t.status.status=`Requested`,e.push(t.message);continue}return e}hasIncompleteRequests(){for(let e of this.inflightRequests.values())if(e.status.status===`Requested`)return!0;return!1}hasInflightRequests(){return this.inflightRequests.size>0}hasSyncedPastLastReconnect(){return this.requestsOlderThanRestart.size===0}timeOfOldestInflightRequest(){if(this.inflightRequests.size===0)return null;let e=Date.now();for(let t of this.inflightRequests.values())t.status.status!==`Completed`&&t.status.requestedAt.getTime()<e&&(e=t.status.requestedAt.getTime());return new Date(e)}inflightMutations(){return this.inflightMutationsCount}inflightActions(){return this.inflightActionsCount}},Ke=Object.defineProperty,qe=(e,t,n)=>t in e?Ke(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,L=(e,t,n)=>qe(e,typeof t==`symbol`?t:t+``,n),Je=class e{constructor(e){L(this,`queryResults`),L(this,`modifiedQueries`),this.queryResults=e,this.modifiedQueries=[]}getQuery(t,...n){let r=S(n[0]),i=u(t),a=this.queryResults.get(P(i,r));if(a!==void 0)return e.queryValue(a.result)}getAllQueries(t){let n=[],r=u(t);for(let t of this.queryResults.values())t.udfPath===N(r)&&n.push({args:t.args,value:e.queryValue(t.result)});return n}setQuery(e,t,n){let r=S(t),i=u(e),a=P(i,r),o;o=n===void 0?void 0:{success:!0,value:n,logLines:[]};let s={udfPath:i,args:r,result:o};this.queryResults.set(a,s),this.modifiedQueries.push(a)}static queryValue(e){if(e!==void 0&&e.success)return e.value}},Ye=class{constructor(){L(this,`queryResults`),L(this,`optimisticUpdates`),this.queryResults=new Map,this.optimisticUpdates=[]}ingestQueryResultsFromServer(e,t){this.optimisticUpdates=this.optimisticUpdates.filter(e=>!t.has(e.mutationId));let n=this.queryResults;this.queryResults=new Map(e);let r=new Je(this.queryResults);for(let e of this.optimisticUpdates)e.update(r);let i=[];for(let[e,t]of this.queryResults){let r=n.get(e);(r===void 0||r.result!==t.result)&&i.push(e)}return i}applyOptimisticUpdate(e,t){this.optimisticUpdates.push({update:e,mutationId:t});let n=new Je(this.queryResults);return e(n),n.modifiedQueries}rawQueryResult(e){let t=this.queryResults.get(e);if(t!==void 0)return t.result}queryResult(e){let t=this.queryResults.get(e);if(t===void 0)return;let n=t.result;if(n!==void 0){if(n.success)return n.value;throw n.errorData===void 0?Error(j(`query`,t.udfPath,n)):M(n,new k(j(`query`,t.udfPath,n)))}}hasQueryResult(e){return this.queryResults.get(e)!==void 0}queryLogs(e){return this.queryResults.get(e)?.result?.logLines}},Xe=Object.defineProperty,Ze=(e,t,n)=>t in e?Xe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,R=(e,t,n)=>Ze(e,typeof t==`symbol`?t:t+``,n),z=class e{constructor(e,t){R(this,`low`),R(this,`high`),R(this,`__isUnsignedLong__`),this.low=e|0,this.high=t|0,this.__isUnsignedLong__=!0}static isLong(e){return(e&&e.__isUnsignedLong__)===!0}static fromBytesLE(t){return new e(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24)}toBytesLE(){let e=this.high,t=this.low;return[t&255,t>>>8&255,t>>>16&255,t>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]}static fromNumber(t){return isNaN(t)||t<0?Qe:t>=et?tt:new e(t%B|0,t/B|0)}toString(){return(BigInt(this.high)*BigInt(B)+BigInt(this.low)).toString()}equals(t){return e.isLong(t)||(t=e.fromValue(t)),this.high>>>31==1&&t.high>>>31==1?!1:this.high===t.high&&this.low===t.low}notEquals(e){return!this.equals(e)}comp(t){return e.isLong(t)||(t=e.fromValue(t)),this.equals(t)?0:t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1}lessThanOrEqual(e){return this.comp(e)<=0}static fromValue(t){return typeof t==`number`?e.fromNumber(t):new e(t.low,t.high)}},Qe=new z(0,0),$e=65536,B=$e*$e,et=B*B,tt=new z(-1,-1),nt=Object.defineProperty,rt=(e,t,n)=>t in e?nt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,V=(e,t,n)=>rt(e,typeof t==`symbol`?t:t+``,n),it=class{constructor(e,t){V(this,`version`),V(this,`remoteQuerySet`),V(this,`queryPath`),V(this,`logger`),this.version={querySet:0,ts:z.fromNumber(0),identity:0},this.remoteQuerySet=new Map,this.queryPath=e,this.logger=t}transition(e){let t=e.startVersion;if(this.version.querySet!==t.querySet||this.version.ts.notEquals(t.ts)||this.version.identity!==t.identity)throw Error(`Invalid start version: ${t.ts.toString()}:${t.querySet}:${t.identity}, transitioning from ${this.version.ts.toString()}:${this.version.querySet}:${this.version.identity}`);for(let t of e.modifications)switch(t.type){case`QueryUpdated`:{let e=this.queryPath(t.queryId);if(e)for(let n of t.logLines)A(this.logger,`info`,`query`,e,n);let n=T(t.value??null);this.remoteQuerySet.set(t.queryId,{success:!0,value:n,logLines:t.logLines});break}case`QueryFailed`:{let e=this.queryPath(t.queryId);if(e)for(let n of t.logLines)A(this.logger,`info`,`query`,e,n);let{errorData:n}=t;this.remoteQuerySet.set(t.queryId,{success:!1,errorMessage:t.errorMessage,errorData:n===void 0?void 0:T(n),logLines:t.logLines});break}case`QueryRemoved`:this.remoteQuerySet.delete(t.queryId);break;default:throw Error(`Invalid modification ${t.type}`)}this.version=e.endVersion}remoteQueryResults(){return this.remoteQuerySet}timestamp(){return this.version.ts}};function at(e){let t=y(e);return z.fromBytesLE(Array.from(t))}function ot(e){return x(new Uint8Array(e.toBytesLE()))}function st(e){switch(e.type){case`FatalError`:case`AuthError`:case`ActionResponse`:case`TransitionChunk`:case`Ping`:return{...e};case`MutationResponse`:return e.success?{...e,ts:at(e.ts)}:{...e};case`Transition`:return{...e,startVersion:{...e.startVersion,ts:at(e.startVersion.ts)},endVersion:{...e.endVersion,ts:at(e.endVersion.ts)}}}}function ct(e){switch(e.type){case`Authenticate`:case`ModifyQuerySet`:case`Mutation`:case`Action`:case`Event`:return{...e};case`Connect`:return e.maxObservedTimestamp===void 0?{...e,maxObservedTimestamp:void 0}:{...e,maxObservedTimestamp:ot(e.maxObservedTimestamp)}}}var lt=Object.defineProperty,ut=(e,t,n)=>t in e?lt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,H=(e,t,n)=>ut(e,typeof t==`symbol`?t:t+``,n),dt=1e3,ft=1001,pt=1005,mt=4040,U;function W(){return U===void 0&&(U=Date.now()),typeof performance>`u`||!performance.now?Date.now():Math.round(U+performance.now())}function ht(){return`t=${Math.round((W()-U)/100)/10}s`}var gt={InternalServerError:{timeout:1e3},SubscriptionsWorkerFullError:{timeout:3e3},TooManyConcurrentRequests:{timeout:3e3},CommitterFullError:{timeout:3e3},AwsTooManyRequestsException:{timeout:3e3},ExecuteFullError:{timeout:3e3},SystemTimeoutError:{timeout:3e3},ExpiredInQueue:{timeout:3e3},VectorIndexesUnavailable:{timeout:1e3},SearchIndexesUnavailable:{timeout:1e3},TableSummariesUnavailable:{timeout:1e3},VectorIndexTooLarge:{timeout:3e3},SearchIndexTooLarge:{timeout:3e3},TooManyWritesInTimePeriod:{timeout:3e3}};function _t(e){if(e===void 0)return`Unknown`;for(let t of Object.keys(gt))if(e.startsWith(t))return t;return`Unknown`}var vt=class{constructor(e,t,n,r,i,a){this.markConnectionStateDirty=i,this.debug=a,H(this,`socket`),H(this,`connectionCount`),H(this,`_hasEverConnected`,!1),H(this,`lastCloseReason`),H(this,`transitionChunkBuffer`,null),H(this,`defaultInitialBackoff`),H(this,`maxBackoff`),H(this,`retries`),H(this,`serverInactivityThreshold`),H(this,`reconnectDueToServerInactivityTimeout`),H(this,`scheduledReconnect`,null),H(this,`networkOnlineHandler`,null),H(this,`pendingNetworkRecoveryInfo`,null),H(this,`uri`),H(this,`onOpen`),H(this,`onResume`),H(this,`onMessage`),H(this,`webSocketConstructor`),H(this,`logger`),H(this,`onServerDisconnectError`),this.webSocketConstructor=n,this.socket={state:`disconnected`},this.connectionCount=0,this.lastCloseReason=`InitialConnect`,this.defaultInitialBackoff=1e3,this.maxBackoff=16e3,this.retries=0,this.serverInactivityThreshold=6e4,this.reconnectDueToServerInactivityTimeout=null,this.uri=e,this.onOpen=t.onOpen,this.onResume=t.onResume,this.onMessage=t.onMessage,this.onServerDisconnectError=t.onServerDisconnectError,this.logger=r,this.setupNetworkListener(),this.connect()}setSocketState(e){this.socket=e,this._logVerbose(`socket state changed: ${this.socket.state}, paused: ${`paused`in this.socket?this.socket.paused:void 0}`),this.markConnectionStateDirty()}setupNetworkListener(){typeof window>`u`||typeof window.addEventListener!=`function`||this.networkOnlineHandler===null&&(this.networkOnlineHandler=()=>{this._logVerbose(`network online event detected`),this.tryReconnectImmediately()},window.addEventListener(`online`,this.networkOnlineHandler),this._logVerbose(`network online event listener registered`))}cleanupNetworkListener(){this.networkOnlineHandler&&typeof window<`u`&&typeof window.removeEventListener==`function`&&(window.removeEventListener(`online`,this.networkOnlineHandler),this.networkOnlineHandler=null,this._logVerbose(`network online event listener removed`))}assembleTransition(e){if(e.partNumber<0||e.partNumber>=e.totalParts||e.totalParts===0||this.transitionChunkBuffer&&(this.transitionChunkBuffer.totalParts!==e.totalParts||this.transitionChunkBuffer.transitionId!==e.transitionId))throw this.transitionChunkBuffer=null,Error(`Invalid TransitionChunk`);if(this.transitionChunkBuffer===null&&(this.transitionChunkBuffer={chunks:[],totalParts:e.totalParts,transitionId:e.transitionId}),e.partNumber!==this.transitionChunkBuffer.chunks.length){let t=this.transitionChunkBuffer.chunks.length;throw this.transitionChunkBuffer=null,Error(`TransitionChunk received out of order: expected part ${t}, got ${e.partNumber}`)}if(this.transitionChunkBuffer.chunks.push(e.chunk),this.transitionChunkBuffer.chunks.length===e.totalParts){let e=this.transitionChunkBuffer.chunks.join(``);this.transitionChunkBuffer=null;let t=st(JSON.parse(e));if(t.type!==`Transition`)throw Error(`Expected Transition, got ${t.type} after assembling chunks`);return t}return null}connect(){if(this.socket.state===`terminated`)return;if(this.socket.state!==`disconnected`&&this.socket.state!==`stopped`)throw Error(`Didn't start connection from disconnected state: `+this.socket.state);let e=new this.webSocketConstructor(this.uri);this._logVerbose(`constructed WebSocket`),this.setSocketState({state:`connecting`,ws:e,paused:`no`}),this.resetServerInactivityTimeout(),e.onopen=()=>{if(this.logger.logVerbose(`begin ws.onopen`),this.socket.state!==`connecting`)throw Error(`onopen called with socket not in connecting state`);if(this.setSocketState({state:`ready`,ws:e,paused:this.socket.paused===`yes`?`uninitialized`:`no`}),this.resetServerInactivityTimeout(),this.socket.paused===`no`&&(this._hasEverConnected=!0,this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:W()})),this.lastCloseReason!==`InitialConnect`&&(this.lastCloseReason?this.logger.log(`WebSocket reconnected at`,ht(),`after disconnect due to`,this.lastCloseReason):this.logger.log(`WebSocket reconnected at`,ht())),this.connectionCount+=1,this.lastCloseReason=null,this.pendingNetworkRecoveryInfo!==null){let{timeSavedMs:e}=this.pendingNetworkRecoveryInfo;this.pendingNetworkRecoveryInfo=null,this.sendMessage({type:`Event`,eventType:`NetworkRecoveryReconnect`,event:{timeSavedMs:e}}),this.logger.log(`Network recovery reconnect saved ~${Math.round(e/1e3)}s of waiting`)}},e.onerror=e=>{this.transitionChunkBuffer=null;let t=e.message;t&&this.logger.log(`WebSocket error message: ${t}`)},e.onmessage=e=>{this.resetServerInactivityTimeout();let t=e.data.length,n=st(JSON.parse(e.data));if(this._logVerbose(`received ws message with type ${n.type}`),n.type!==`Ping`){if(n.type===`TransitionChunk`){let e=this.assembleTransition(n);if(!e)return;n=e,this._logVerbose(`assembled full ws message of type ${n.type}`)}this.transitionChunkBuffer!==null&&(this.transitionChunkBuffer=null,this.logger.log(`Received unexpected ${n.type} while buffering TransitionChunks`)),n.type===`Transition`&&this.reportLargeTransition({messageLength:t,transition:n}),this.onMessage(n).hasSyncedPastLastReconnect&&(this.retries=0,this.markConnectionStateDirty())}},e.onclose=e=>{if(this._logVerbose(`begin ws.onclose`),this.transitionChunkBuffer=null,this.lastCloseReason===null&&(this.lastCloseReason=e.reason||`closed with code ${e.code}`),e.code!==dt&&e.code!==ft&&e.code!==pt&&e.code!==mt){let t=`WebSocket closed with code ${e.code}`;e.reason&&(t+=`: ${e.reason}`),this.logger.log(t),this.onServerDisconnectError&&e.reason&&this.onServerDisconnectError(t)}let t=_t(e.reason);this.scheduleReconnect(t)}}socketState(){return this.socket.state}sendMessage(e){let t={type:e.type,...e.type===`Authenticate`&&e.tokenType===`User`?{value:`...${e.value.slice(-7)}`}:{}};if(this.socket.state===`ready`&&this.socket.paused===`no`){let n=ct(e),r=JSON.stringify(n),i=!1;try{this.socket.ws.send(r),i=!0}catch(e){this.logger.log(`Failed to send message on WebSocket, reconnecting: ${e}`),this.closeAndReconnect(`FailedToSendMessage`)}return this._logVerbose(`${i?`sent`:`failed to send`} message with type ${e.type}: ${JSON.stringify(t)}`),!0}return this._logVerbose(`message not sent (socket state: ${this.socket.state}, paused: ${`paused`in this.socket?this.socket.paused:void 0}): ${JSON.stringify(t)}`),!1}resetServerInactivityTimeout(){this.socket.state!==`terminated`&&(this.reconnectDueToServerInactivityTimeout!==null&&(clearTimeout(this.reconnectDueToServerInactivityTimeout),this.reconnectDueToServerInactivityTimeout=null),this.reconnectDueToServerInactivityTimeout=setTimeout(()=>{this.closeAndReconnect(`InactiveServer`)},this.serverInactivityThreshold))}scheduleReconnect(e){this.scheduledReconnect&&=(clearTimeout(this.scheduledReconnect.timeout),null),this.socket={state:`disconnected`};let t=this.nextBackoff(e);this.markConnectionStateDirty(),this.logger.log(`Attempting reconnect in ${Math.round(t)}ms`);let n=W(),r=setTimeout(()=>{this.scheduledReconnect?.timeout===r&&(this.scheduledReconnect=null,this.connect())},t);this.scheduledReconnect={timeout:r,scheduledAt:n,backoffMs:t}}closeAndReconnect(e){switch(this._logVerbose(`begin closeAndReconnect with reason ${e}`),this.socket.state){case`disconnected`:case`terminated`:case`stopped`:return;case`connecting`:case`ready`:this.lastCloseReason=e,this.close(),this.scheduleReconnect(`client`);return;default:this.socket}}close(){switch(this.transitionChunkBuffer=null,this.socket.state){case`disconnected`:case`terminated`:case`stopped`:return Promise.resolve();case`connecting`:{let e=this.socket.ws;return e.onmessage=e=>{this._logVerbose(`Ignoring message received after close`)},new Promise(t=>{e.onclose=()=>{this._logVerbose(`Closed after connecting`),t()},e.onopen=()=>{this._logVerbose(`Opened after connecting`),e.close()}})}case`ready`:{this._logVerbose(`ws.close called`);let e=this.socket.ws;e.onmessage=e=>{this._logVerbose(`Ignoring message received after close`)};let t=new Promise(t=>{e.onclose=()=>{t()}});return e.close(),t}default:return this.socket,Promise.resolve()}}terminate(){switch(this.reconnectDueToServerInactivityTimeout&&clearTimeout(this.reconnectDueToServerInactivityTimeout),this.scheduledReconnect&&=(clearTimeout(this.scheduledReconnect.timeout),null),this.cleanupNetworkListener(),this.socket.state){case`terminated`:case`stopped`:case`disconnected`:case`connecting`:case`ready`:{let e=this.close();return this.setSocketState({state:`terminated`}),e}default:throw this.socket,Error(`Invalid websocket state: ${this.socket.state}`)}}stop(){switch(this.socket.state){case`terminated`:return Promise.resolve();case`connecting`:case`stopped`:case`disconnected`:case`ready`:{this.cleanupNetworkListener();let e=this.close();return this.socket={state:`stopped`},e}default:return this.socket,Promise.resolve()}}tryRestart(){switch(this.socket.state){case`stopped`:break;case`terminated`:case`connecting`:case`ready`:case`disconnected`:this.logger.logVerbose(`Restart called without stopping first`);return;default:this.socket}this.setupNetworkListener(),this.connect()}pause(){switch(this.socket.state){case`disconnected`:case`stopped`:case`terminated`:return;case`connecting`:case`ready`:this.socket={...this.socket,paused:`yes`};return;default:this.socket;return}}tryReconnectImmediately(){if(this._logVerbose(`tryReconnectImmediately called`),this.socket.state!==`disconnected`){this._logVerbose(`tryReconnectImmediately called but socket state is ${this.socket.state}, no action taken`);return}let e=null;if(this.scheduledReconnect){let t=W()-this.scheduledReconnect.scheduledAt;e=Math.max(0,this.scheduledReconnect.backoffMs-t),this._logVerbose(`would have waited ${Math.round(e)}ms more (backoff was ${Math.round(this.scheduledReconnect.backoffMs)}ms, elapsed ${Math.round(t)}ms)`),clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null,this._logVerbose(`canceled scheduled reconnect`)}this.logger.log(`Network recovery detected, reconnecting immediately`),this.pendingNetworkRecoveryInfo=e===null?null:{timeSavedMs:e},this.connect()}resume(){switch(this.socket.state){case`connecting`:this.socket={...this.socket,paused:`no`};return;case`ready`:this.socket.paused===`uninitialized`?(this.socket={...this.socket,paused:`no`},this._hasEverConnected=!0,this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:W()})):this.socket.paused===`yes`&&(this.socket={...this.socket,paused:`no`},this.onResume());return;case`terminated`:case`stopped`:case`disconnected`:return;default:this.socket}this.connect()}connectionState(){return{isConnected:this.socket.state===`ready`,hasEverConnected:this._hasEverConnected,connectionCount:this.connectionCount,connectionRetries:this.retries}}_logVerbose(e){this.logger.logVerbose(e)}nextBackoff(e){let t=(e===`client`?100:e===`Unknown`?this.defaultInitialBackoff:gt[e].timeout)*2**this.retries;this.retries+=1;let n=Math.min(t,this.maxBackoff);return n+n*(Math.random()-.5)}reportLargeTransition({transition:e,messageLength:t}){if(e.clientClockSkew===void 0||e.serverTs===void 0)return;let n=W()-e.clientClockSkew-e.serverTs/1e6,r=`${Math.round(n)}ms`,i=`${Math.round(t/1e4)/100}MB`,a=t/(n/1e3),o=`${Math.round(a/1e4)/100}MB per second`;this._logVerbose(`received ${i} transition in ${r} at ${o}`),t>2e7?this.logger.log(`received query results totaling more that 20MB (${i}) which will take a long time to download on slower connections`):n>2e4&&this.logger.log(`received query results totaling ${i} which took more than 20s to arrive (${r})`),this.debug&&this.sendMessage({type:`Event`,eventType:`ClientReceivedTransition`,event:{transitionTransitTime:n,messageLength:t}})}};function yt(){return bt()}function bt(){return`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}var G=class extends Error{};G.prototype.name=`InvalidTokenError`;function xt(e){return decodeURIComponent(atob(e).replace(/(.)/g,(e,t)=>{let n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n=`0`+n),`%`+n}))}function St(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`);switch(t.length%4){case 0:break;case 2:t+=`==`;break;case 3:t+=`=`;break;default:throw Error(`base64 string is not of the correct length`)}try{return xt(t)}catch{return atob(t)}}function Ct(e,t){if(typeof e!=`string`)throw new G(`Invalid token specified: must be a string`);t||={};let n=t.header===!0?0:1,r=e.split(`.`)[n];if(typeof r!=`string`)throw new G(`Invalid token specified: missing part #${n+1}`);let i;try{i=St(r)}catch(e){throw new G(`Invalid token specified: invalid base64 for part #${n+1} (${e.message})`)}try{return JSON.parse(i)}catch(e){throw new G(`Invalid token specified: invalid json for part #${n+1} (${e.message})`)}}var wt=Object.defineProperty,Tt=(e,t,n)=>t in e?wt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,K=(e,t,n)=>Tt(e,typeof t==`symbol`?t:t+``,n),Et=1728e6,Dt=2,Ot=class{constructor(e,t,n){K(this,`authState`,{state:`noAuth`}),K(this,`configVersion`,0),K(this,`syncState`),K(this,`authenticate`),K(this,`stopSocket`),K(this,`tryRestartSocket`),K(this,`pauseSocket`),K(this,`resumeSocket`),K(this,`clearAuth`),K(this,`logger`),K(this,`refreshTokenLeewaySeconds`),K(this,`initialAuthTokenReuse`),K(this,`lastRefreshChange`),K(this,`tokenConfirmationAttempts`,0),this.syncState=e,this.authenticate=t.authenticate,this.stopSocket=t.stopSocket,this.tryRestartSocket=t.tryRestartSocket,this.pauseSocket=t.pauseSocket,this.resumeSocket=t.resumeSocket,this.clearAuth=t.clearAuth,this.logger=n.logger,this.refreshTokenLeewaySeconds=n.refreshTokenLeewaySeconds,this.initialAuthTokenReuse=n.initialAuthTokenReuse,this.lastRefreshChange=!1}notifyRefreshChange(e){this.authState.state!==`noAuth`&&this.authState.state!==`initialRefetch`&&this.authState.config.onRefreshChange&&this.lastRefreshChange!==e&&(this.lastRefreshChange=e,this.authState.config.onRefreshChange(e))}async setConfig(e,t,n){this.resetAuthState(),this._logVerbose(`pausing WS for auth token fetch`),this.pauseSocket();let r=await this.fetchTokenAndGuardAgainstRace(e,{forceRefreshToken:!1});if(r.isFromOutdatedConfig)return;let i={fetchToken:e,onAuthChange:t,onRefreshChange:n};r.value?(this.setAuthState({state:`waitingForServerConfirmationOfCachedToken`,config:i,hasRetried:!1}),this.authenticate(r.value)):(this.setAuthState({state:`initialRefetch`,config:i}),await this.refetchToken()),this._logVerbose(`resuming WS after auth token fetch`),this.resumeSocket()}onTransition(e){if(this.syncState.isCurrentOrNewerAuthVersion(e.endVersion.identity)&&!(e.endVersion.identity<=e.startVersion.identity)){if(this._logVerbose(`auth state is ${this.authState.state} when handling transition`),this.syncState.markAuthCompletion(),this.authState.state===`waitingForServerConfirmationOfCachedToken`){this._logVerbose(`server confirmed auth token is valid`);let t=this.syncState.getAuth()?.value;this.initialAuthTokenReuse&&t?this.scheduleTokenRefetch(t,e.clientClockSkew):this.refetchToken(),this.authState.config.onAuthChange(!0);return}this.authState.state===`waitingForServerConfirmationOfFreshToken`&&(this._logVerbose(`server confirmed new auth token is valid`),this.notifyRefreshChange(!1),this.scheduleTokenRefetch(this.authState.token),this.tokenConfirmationAttempts=0,this.authState.hadAuth||this.authState.config.onAuthChange(!0))}}onAuthError(e){if(e.authUpdateAttempted===!1&&(this.authState.state===`waitingForServerConfirmationOfFreshToken`||this.authState.state===`waitingForServerConfirmationOfCachedToken`)){this._logVerbose(`ignoring non-auth token expired error`);return}let{baseVersion:t}=e;if(!this.syncState.isCurrentOrNewerAuthVersion(t+1)){this._logVerbose(`ignoring auth error for previous auth attempt`);return}this.tryToReauthenticate(e)}async tryToReauthenticate(e){if(this._logVerbose(`attempting to reauthenticate: ${e.error}`),this.authState.state===`noAuth`||this.authState.state===`waitingForServerConfirmationOfFreshToken`&&this.tokenConfirmationAttempts>=Dt){this.logger.error(`Failed to authenticate: "${e.error}", check your server auth config`),this.syncState.hasAuth()&&this.syncState.clearAuth(),this.authState.state!==`noAuth`&&this.setAndReportAuthFailed(this.authState.config.onAuthChange);return}if(this.authState.state===`waitingForServerConfirmationOfFreshToken`&&(this.tokenConfirmationAttempts++,this._logVerbose(`retrying reauthentication, ${Dt-this.tokenConfirmationAttempts} attempts remaining`)),this.notifyRefreshChange(!0),await this.stopSocket(),this.authState.state===`noAuth`)return;let t=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});t.isFromOutdatedConfig||(t.value&&this.syncState.isNewAuth(t.value)?(this.authenticate(t.value),this.setAuthState({state:`waitingForServerConfirmationOfFreshToken`,config:this.authState.config,token:t.value,hadAuth:this.authState.state===`notRefetching`||this.authState.state===`waitingForScheduledRefetch`})):(this._logVerbose(`reauthentication failed, could not fetch a new token`),this.syncState.hasAuth()&&this.syncState.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this.tryRestartSocket())}async refetchToken(){if(this.authState.state===`noAuth`)return;this._logVerbose(`refetching auth token`);let e=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});e.isFromOutdatedConfig||(e.value?this.syncState.isNewAuth(e.value)?(this.setAuthState({state:`waitingForServerConfirmationOfFreshToken`,hadAuth:this.syncState.hasAuth(),token:e.value,config:this.authState.config}),this.authenticate(e.value)):this.setAuthState({state:`notRefetching`,config:this.authState.config}):(this._logVerbose(`refetching token failed`),this.syncState.hasAuth()&&this.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this._logVerbose(`restarting WS after auth token fetch (if currently stopped)`),this.tryRestartSocket())}scheduleTokenRefetch(e,t){if(this.authState.state===`noAuth`)return;let n=this.decodeToken(e);if(!n){this.logger.error(`Auth token is not a valid JWT, cannot refetch the token`);return}let{iat:r,exp:i}=n;if(!r||!i){this.logger.error(`Auth token does not have required fields, cannot refetch the token`);return}let a=i-r;if(a<=2){this.logger.error(`Auth token does not live long enough, cannot refetch the token`);return}let o;t===void 0?o=a:(o=i-(Date.now()-t)/1e3,o<=0&&(o=0));let s=Math.min(Et,(o-this.refreshTokenLeewaySeconds)*1e3);s<=0&&(this.logger.warn(`Refetching auth token immediately, configured leeway ${this.refreshTokenLeewaySeconds}s is larger than the token's lifetime ${o}s`),s=0);let c=setTimeout(()=>{this._logVerbose(`running scheduled token refetch`),this.refetchToken()},s);this.setAuthState({state:`waitingForScheduledRefetch`,refetchTokenTimeoutId:c,config:this.authState.config}),this._logVerbose(`scheduled preemptive auth token refetching in ${s}ms`)}async fetchTokenAndGuardAgainstRace(e,t){let n=++this.configVersion;this._logVerbose(`fetching token with config version ${n}`);let r=await e(t);return this.configVersion===n?{isFromOutdatedConfig:!1,value:r}:(this._logVerbose(`stale config version, expected ${n}, got ${this.configVersion}`),{isFromOutdatedConfig:!0})}stop(){this.resetAuthState(),this.configVersion++,this._logVerbose(`config version bumped to ${this.configVersion}`)}setAndReportAuthFailed(e){e(!1),this.resetAuthState()}resetAuthState(){this.notifyRefreshChange(!1),this.setAuthState({state:`noAuth`})}setAuthState(e){let t=e.state===`waitingForServerConfirmationOfFreshToken`?{hadAuth:e.hadAuth,state:e.state,token:`...${e.token.slice(-7)}`}:{state:e.state};switch(this._logVerbose(`setting auth state to ${JSON.stringify(t)}`),e.state){case`waitingForScheduledRefetch`:case`notRefetching`:case`noAuth`:this.tokenConfirmationAttempts=0}this.authState.state===`waitingForScheduledRefetch`&&clearTimeout(this.authState.refetchTokenTimeoutId),this.authState=e}decodeToken(e){try{return Ct(e)}catch(e){return this._logVerbose(`Error decoding token: ${e instanceof Error?e.message:`Unknown error`}`),null}}_logVerbose(e){this.logger.logVerbose(`${e} [v${this.configVersion}]`)}},kt=[`convexClientConstructed`,`convexWebSocketOpen`,`convexFirstMessageReceived`];function At(e,t){let n={sessionId:t};typeof performance>`u`||!performance.mark||performance.mark(e,{detail:n})}function jt(e){let t=e.name.slice(6);return t=t.charAt(0).toLowerCase()+t.slice(1),{name:t,startTime:e.startTime}}function Mt(e){if(typeof performance>`u`||!performance.getEntriesByName)return[];let t=[];for(let n of kt){let r=performance.getEntriesByName(n).filter(e=>e.entryType===`mark`).filter(t=>t.detail.sessionId===e);t.push(...r)}return t.map(jt)}var Nt=Object.defineProperty,Pt=(e,t,n)=>t in e?Nt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,q=(e,t,n)=>Pt(e,typeof t==`symbol`?t:t+``,n),Ft=class{constructor(e,t,n){if(q(this,`address`),q(this,`state`),q(this,`requestManager`),q(this,`webSocketManager`),q(this,`authenticationManager`),q(this,`remoteQuerySet`),q(this,`optimisticQueryResults`),q(this,`_transitionHandlerCounter`,0),q(this,`_nextRequestId`),q(this,`_onTransitionFns`,new Map),q(this,`_sessionId`),q(this,`firstMessageReceived`,!1),q(this,`debug`),q(this,`logger`),q(this,`maxObservedTimestamp`),q(this,`connectionStateSubscribers`,new Map),q(this,`nextConnectionStateSubscriberId`,0),q(this,`_lastPublishedConnectionState`),q(this,`markConnectionStateDirty`,()=>{Promise.resolve().then(()=>{let e=this.connectionState();if(JSON.stringify(e)!==JSON.stringify(this._lastPublishedConnectionState)){this._lastPublishedConnectionState=e;for(let t of this.connectionStateSubscribers.values())t(e)}})}),q(this,`mark`,e=>{this.debug&&At(e,this.sessionId)}),typeof e==`object`)throw Error(`Passing a ClientConfig object is no longer supported. Pass the URL of the Convex deployment as a string directly.`);n?.skipConvexDeploymentUrlCheck!==!0&&ne(e),n={...n};let r=n.authRefreshTokenLeewaySeconds??10,i=n.webSocketConstructor;if(!i&&typeof WebSocket>`u`)throw Error(`No WebSocket global variable defined! To use Convex in an environment without WebSocket try the HTTP client: https://docs.convex.dev/api/classes/browser.ConvexHttpClient`);i||=WebSocket,this.debug=n.reportDebugInfoToConvex??!1,this.address=e,this.logger=n.logger===!1?Ie({verbose:n.verbose??!1}):n.logger!==!0&&n.logger?n.logger:Fe({verbose:n.verbose??!1});let a=e.search(`://`);if(a===-1)throw Error(`Provided address was not an absolute URL.`);let o=e.substring(a+3),s=e.substring(0,a),c;if(s===`http`)c=`ws`;else if(s===`https`)c=`wss`;else throw Error(`Unknown parent protocol ${s}`);let l=`${c}://${o}/api/${d}/sync`;this.state=new He,this.remoteQuerySet=new it(e=>this.state.queryPath(e),this.logger),this.requestManager=new Ge(this.logger,this.markConnectionStateDirty);let u=()=>{this.webSocketManager.pause(),this.state.pause()};this.authenticationManager=new Ot(this.state,{authenticate:e=>{let t=this.state.setAuth(e);return this.webSocketManager.sendMessage(t),t.baseVersion},stopSocket:()=>this.webSocketManager.stop(),tryRestartSocket:()=>this.webSocketManager.tryRestart(),pauseSocket:u,resumeSocket:()=>this.webSocketManager.resume(),clearAuth:()=>{this.clearAuth()}},{logger:this.logger,refreshTokenLeewaySeconds:r,initialAuthTokenReuse:n.initialAuthTokenReuse??!1}),this.optimisticQueryResults=new Ye,this.addOnTransitionHandler(e=>{t(e.queries.map(e=>e.token))}),this._nextRequestId=0,this._sessionId=yt();let{unsavedChangesWarning:f}=n;if(typeof window>`u`||window.addEventListener===void 0){if(f===!0)throw Error(`unsavedChangesWarning requested, but window.addEventListener not found! Remove {unsavedChangesWarning: true} from Convex client options.`)}else f!==!1&&window.addEventListener(`beforeunload`,e=>{if(this.requestManager.hasIncompleteRequests()){e.preventDefault();let t=`Are you sure you want to leave? Your changes may not be saved.`;return(e||window.event).returnValue=t,t}});this.webSocketManager=new vt(l,{onOpen:e=>{this.mark(`convexWebSocketOpen`),this.webSocketManager.sendMessage({...e,type:`Connect`,sessionId:this._sessionId,maxObservedTimestamp:this.maxObservedTimestamp}),this.remoteQuerySet=new it(e=>this.state.queryPath(e),this.logger);let[t,n]=this.state.restart();n&&this.webSocketManager.sendMessage(n),this.webSocketManager.sendMessage(t);for(let e of this.requestManager.restart())this.webSocketManager.sendMessage(e)},onResume:()=>{let[e,t]=this.state.resume();t&&this.webSocketManager.sendMessage(t),e&&this.webSocketManager.sendMessage(e);for(let e of this.requestManager.resume())this.webSocketManager.sendMessage(e)},onMessage:e=>{switch(this.firstMessageReceived||(this.firstMessageReceived=!0,this.mark(`convexFirstMessageReceived`),this.reportMarks()),e.type){case`Transition`:{this.observedTimestamp(e.endVersion.ts),this.authenticationManager.onTransition(e),this.remoteQuerySet.transition(e),this.state.transition(e);let t=this.requestManager.removeCompleted(this.remoteQuerySet.timestamp());this.notifyOnQueryResultChanges(t);break}case`MutationResponse`:{e.success&&this.observedTimestamp(e.ts);let t=this.requestManager.onResponse(e);t!==null&&this.notifyOnQueryResultChanges(new Map([[t.requestId,t.result]]));break}case`ActionResponse`:this.requestManager.onResponse(e);break;case`AuthError`:this.authenticationManager.onAuthError(e);break;case`FatalError`:{let t=Le(this.logger,e.error);throw this.webSocketManager.terminate(),t}}return{hasSyncedPastLastReconnect:this.hasSyncedPastLastReconnect()}},onServerDisconnectError:n.onServerDisconnectError},i,this.logger,this.markConnectionStateDirty,this.debug),this.mark(`convexClientConstructed`),n.expectAuth&&u()}hasSyncedPastLastReconnect(){return this.requestManager.hasSyncedPastLastReconnect()&&this.state.hasSyncedPastLastReconnect()}observedTimestamp(e){(this.maxObservedTimestamp===void 0||this.maxObservedTimestamp.lessThanOrEqual(e))&&(this.maxObservedTimestamp=e)}getMaxObservedTimestamp(){return this.maxObservedTimestamp}notifyOnQueryResultChanges(e){let t=this.remoteQuerySet.remoteQueryResults(),n=new Map;for(let[e,r]of t){let t=this.state.queryToken(e);if(t!==null){let i={result:r,udfPath:this.state.queryPath(e),args:this.state.queryArgs(e)};n.set(t,i)}}let r=this.optimisticQueryResults.ingestQueryResultsFromServer(n,new Set(e.keys()));this.handleTransition({queries:r.map(e=>({token:e,modification:{kind:`Updated`,result:this.optimisticQueryResults.rawQueryResult(e)}})),reflectedMutations:Array.from(e).map(([e,t])=>({requestId:e,result:t})),timestamp:this.remoteQuerySet.timestamp()})}handleTransition(e){for(let t of this._onTransitionFns.values())t(e)}addOnTransitionHandler(e){let t=this._transitionHandlerCounter++;return this._onTransitionFns.set(t,e),()=>this._onTransitionFns.delete(t)}getCurrentAuthClaims(){let e=this.state.getAuth(),t={};if(e&&e.tokenType===`User`)try{t=e?Ct(e.value):{}}catch{t={}}else return;return{token:e.value,decoded:t}}setAuth(e,t,n){this.authenticationManager.setConfig(e,t,n)}hasAuth(){return this.state.hasAuth()}setAdminAuth(e,t){let n=this.state.setAdminAuth(e,t);this.webSocketManager.sendMessage(n)}clearAuth(){let e=this.state.clearAuth();this.webSocketManager.sendMessage(e)}subscribe(e,t,n){let r=S(t),{modification:i,queryToken:a,unsubscribe:o}=this.state.subscribe(e,r,n?.journal,n?.componentPath);return i!==null&&this.webSocketManager.sendMessage(i),{queryToken:a,unsubscribe:()=>{let e=o();e&&this.webSocketManager.sendMessage(e)}}}localQueryResult(e,t){let n=P(e,S(t));return this.optimisticQueryResults.queryResult(n)}localQueryResultByToken(e){return this.optimisticQueryResults.queryResult(e)}hasLocalQueryResultByToken(e){return this.optimisticQueryResults.hasQueryResult(e)}localQueryLogs(e,t){let n=P(e,S(t));return this.optimisticQueryResults.queryLogs(n)}queryJournal(e,t){let n=P(e,S(t));return this.state.queryJournal(n)}connectionState(){let e=this.webSocketManager.connectionState();return{hasInflightRequests:this.requestManager.hasInflightRequests(),isWebSocketConnected:e.isConnected,hasEverConnected:e.hasEverConnected,connectionCount:e.connectionCount,connectionRetries:e.connectionRetries,timeOfOldestInflightRequest:this.requestManager.timeOfOldestInflightRequest(),inflightMutations:this.requestManager.inflightMutations(),inflightActions:this.requestManager.inflightActions()}}subscribeToConnectionState(e){let t=this.nextConnectionStateSubscriberId++;return this.connectionStateSubscribers.set(t,e),()=>{this.connectionStateSubscribers.delete(t)}}async mutation(e,t,n){let r=await this.mutationInternal(e,t,n);if(!r.success)throw r.errorData===void 0?Error(j(`mutation`,e,r)):M(r,new k(j(`mutation`,e,r)));return r.value}async mutationInternal(e,t,n,r){let{mutationPromise:i}=this.enqueueMutation(e,t,n,r);return i}enqueueMutation(e,t,n,r){let i=S(t);this.tryReportLongDisconnect();let a=this.nextRequestId;if(this._nextRequestId++,n!==void 0){let e=n.optimisticUpdate;if(e!==void 0){let t=this.optimisticQueryResults.applyOptimisticUpdate(t=>{e(t,i)instanceof Promise&&this.logger.warn(`Optimistic update handler returned a Promise. Optimistic updates should be synchronous.`)},a).map(e=>{let t=this.localQueryResultByToken(e);return{token:e,modification:{kind:`Updated`,result:t===void 0?void 0:{success:!0,value:t,logLines:[]}}}});this.handleTransition({queries:t,reflectedMutations:[],timestamp:this.remoteQuerySet.timestamp()})}}let o={type:`Mutation`,requestId:a,udfPath:e,componentPath:r,args:[O(i)]},s=this.webSocketManager.sendMessage(o);return{requestId:a,mutationPromise:this.requestManager.request(o,s)}}async action(e,t){let n=await this.actionInternal(e,t);if(!n.success)throw n.errorData===void 0?Error(j(`action`,e,n)):M(n,new k(j(`action`,e,n)));return n.value}async actionInternal(e,t,n){let r=S(t),i=this.nextRequestId;this._nextRequestId++,this.tryReportLongDisconnect();let a={type:`Action`,requestId:i,udfPath:e,componentPath:n,args:[O(r)]},o=this.webSocketManager.sendMessage(a);return this.requestManager.request(a,o)}async close(){return this.authenticationManager.stop(),this.webSocketManager.terminate()}get url(){return this.address}get nextRequestId(){return this._nextRequestId}get sessionId(){return this._sessionId}reportMarks(){if(this.debug){let e=Mt(this.sessionId);this.webSocketManager.sendMessage({type:`Event`,eventType:`ClientConnect`,event:e})}}tryReportLongDisconnect(){if(!this.debug)return;let e=this.connectionState().timeOfOldestInflightRequest;if(e===null||Date.now()-e.getTime()<=6e4)return;let t=`${this.address}/api/debug_event`;fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`,"Convex-Client":`npm-${d}`},body:JSON.stringify({event:`LongWebsocketDisconnect`})}).then(e=>{e.ok||this.logger.warn(`Analytics request failed with response:`,e.body)}).catch(e=>{this.logger.warn(`Analytics response failed with error:`,e)})}};function J(e){if(typeof e!=`object`||!e||!Array.isArray(e.page)||typeof e.isDone!=`boolean`||typeof e.continueCursor!=`string`)throw Error(`Not a valid paginated query result: ${e?.toString()}`);return e}var It=Object.defineProperty,Lt=(e,t,n)=>t in e?It(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Rt=(e,t,n)=>Lt(e,typeof t==`symbol`?t:t+``,n),zt=class{constructor(e,t){this.client=e,this.onTransition=t,Rt(this,`paginatedQuerySet`,new Map),Rt(this,`lastTransitionTs`),this.lastTransitionTs=z.fromNumber(0),this.client.addOnTransitionHandler(e=>this.onBaseTransition(e))}subscribe(e,t,n){let r=N(e),i=Re(r,t,n),a=()=>this.removePaginatedQuerySubscriber(i),o=this.paginatedQuerySet.get(i);return o?(o.numSubscribers+=1,{paginatedQueryToken:i,unsubscribe:a}):(this.paginatedQuerySet.set(i,{token:i,canonicalizedUdfPath:r,args:t,numSubscribers:1,options:{initialNumItems:n.initialNumItems},nextPageKey:0,pageKeys:[],pageKeyToQuery:new Map,ongoingSplits:new Map,skip:!1,id:n.id}),this.addPageToPaginatedQuery(i,null,n.initialNumItems),{paginatedQueryToken:i,unsubscribe:a})}localQueryResult(e,t,n){let r=Re(N(e),t,n);return this.localQueryResultByToken(r)}localQueryResultByToken(e){let t=this.paginatedQuerySet.get(e);if(!t)return;let n=this.activePageQueryTokens(t);if(n.length===0)return{results:[],status:`LoadingFirstPage`,loadMore:t=>this.loadMoreOfPaginatedQuery(e,t)};let r=[],i=!1,a=!1;for(let e of n){let t=this.client.localQueryResultByToken(e);if(t===void 0){i=!0,a=!1;continue}let n=J(t);r=r.concat(n.page),a=!!n.isDone}let o;return o=i?r.length===0?`LoadingFirstPage`:`LoadingMore`:a?`Exhausted`:`CanLoadMore`,{results:r,status:o,loadMore:t=>this.loadMoreOfPaginatedQuery(e,t)}}onBaseTransition(e){let t=e.queries.map(e=>e.token),n=this.queriesContainingTokens(t),r=[];n.length>0&&(this.processPaginatedQuerySplits(n,e=>this.client.localQueryResultByToken(e)),r=n.map(e=>({token:e,modification:{kind:`Updated`,result:this.localQueryResultByToken(e)}})));let i={...e,paginatedQueries:r};this.onTransition(i)}loadMoreOfPaginatedQuery(e,t){this.mustGetPaginatedQuery(e);let n=this.queryTokenForLastPageOfPaginatedQuery(e),r=this.client.localQueryResultByToken(n);if(!r)return!1;let i=J(r);if(i.isDone)return!1;this.addPageToPaginatedQuery(e,i.continueCursor,t);let a={timestamp:this.lastTransitionTs,reflectedMutations:[],queries:[],paginatedQueries:[{token:e,modification:{kind:`Updated`,result:this.localQueryResultByToken(e)}}]};return this.onTransition(a),!0}queriesContainingTokens(e){if(e.length===0)return[];let t=[],n=new Set(e);for(let[e,r]of this.paginatedQuerySet)for(let i of this.allQueryTokens(r))if(n.has(i)){t.push(e);break}return t}processPaginatedQuerySplits(e,t){for(let n of e){let e=this.mustGetPaginatedQuery(n),{ongoingSplits:r,pageKeyToQuery:i,pageKeys:a}=e;for(let[n,[a,o]]of r)t(i.get(a).queryToken)!==void 0&&t(i.get(o).queryToken)!==void 0&&this.completePaginatedQuerySplit(e,n,a,o);for(let n of a){if(r.has(n))continue;let a=i.get(n);if(!a)throw Error(`No page query for active pageKey ${n}`);let o=t(a.queryToken);if(!o)continue;let s=J(o);s.splitCursor&&(s.pageStatus===`SplitRecommended`||s.pageStatus===`SplitRequired`||s.page.length>e.options.initialNumItems*2)&&this.splitPaginatedQueryPage(e,n,a.cursor,s.splitCursor,s.continueCursor)}}}splitPaginatedQueryPage(e,t,n,r,i){let a=e.nextPageKey++,o=e.nextPageKey++,s={numItems:e.options.initialNumItems,id:e.id},c=this.client.subscribe(e.canonicalizedUdfPath,{...e.args,paginationOpts:{...s,cursor:n,endCursor:r}});e.pageKeyToQuery.set(a,{...c,cursor:n});let l=this.client.subscribe(e.canonicalizedUdfPath,{...e.args,paginationOpts:{...s,cursor:r,endCursor:i}});e.pageKeyToQuery.set(o,{...l,cursor:r}),e.ongoingSplits.set(t,[a,o])}addPageToPaginatedQuery(e,t,n){let r=this.mustGetPaginatedQuery(e),i=r.nextPageKey++,a={cursor:t,numItems:n,id:r.id},o={...r.args,paginationOpts:a},s=this.client.subscribe(r.canonicalizedUdfPath,o);return r.pageKeys.push(i),r.pageKeyToQuery.set(i,{...s,cursor:t}),s}removePaginatedQuerySubscriber(e){let t=this.paginatedQuerySet.get(e);if(t&&(--t.numSubscribers,!(t.numSubscribers>0))){for(let e of t.pageKeyToQuery.values())e.unsubscribe();this.paginatedQuerySet.delete(e)}}completePaginatedQuerySplit(e,t,n,r){let i=e.pageKeyToQuery.get(t);e.pageKeyToQuery.delete(t);let a=e.pageKeys.indexOf(t);e.pageKeys.splice(a,1,n,r),e.ongoingSplits.delete(t),i.unsubscribe()}activePageQueryTokens(e){return e.pageKeys.map(t=>e.pageKeyToQuery.get(t).queryToken)}allQueryTokens(e){return Array.from(e.pageKeyToQuery.values()).map(e=>e.queryToken)}queryTokenForLastPageOfPaginatedQuery(e){let t=this.mustGetPaginatedQuery(e),n=t.pageKeys[t.pageKeys.length-1];if(n===void 0)throw Error(`No pages for paginated query ${e}`);return t.pageKeyToQuery.get(n).queryToken}mustGetPaginatedQuery(e){let t=this.paginatedQuerySet.get(e);if(!t)throw Error(`paginated query no longer exists for token `+e);return t}},Bt=Object.defineProperty,Vt=(e,t,n)=>t in e?Bt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Y=(e,t,n)=>Vt(e,typeof t==`symbol`?t:t+``,n),Ht,Ut=class{constructor(e,t={}){Y(this,`listeners`),Y(this,`_client`),Y(this,`_paginatedClient`),Y(this,`callNewListenersWithCurrentValuesTimer`),Y(this,`_closed`),Y(this,`_disabled`),t.skipConvexDeploymentUrlCheck!==!0&&ne(e);let{disabled:n,...r}=t;this._closed=!1,this._disabled=!!n,Ht&&!(`webSocketConstructor`in r)&&typeof WebSocket>`u`&&(r.webSocketConstructor=Ht),typeof window>`u`&&!(`unsavedChangesWarning`in r)&&(r.unsavedChangesWarning=!1),this.disabled||(this._client=new Ft(e,()=>{},r),this._paginatedClient=new zt(this._client,e=>this._transition(e))),this.listeners=new Set}get closed(){return this._closed}get client(){if(this._client)return this._client;throw Error(`ConvexClient is disabled`)}get paginatedClient(){if(this._paginatedClient)return this._paginatedClient;throw Error(`ConvexClient is disabled`)}get disabled(){return this._disabled}onUpdate(e,t,n,r){if(this.disabled)return this.createDisabledUnsubscribe();let{queryToken:i,unsubscribe:a}=this.client.subscribe(u(e),t),o={queryToken:i,callback:n,onError:r,unsubscribe:a,hasEverRun:!1,query:e,args:t,paginationOptions:void 0};this.listeners.add(o),this.queryResultReady(i)&&this.callNewListenersWithCurrentValuesTimer===void 0&&(this.callNewListenersWithCurrentValuesTimer=setTimeout(()=>this.callNewListenersWithCurrentValues(),0));let s={unsubscribe:()=>{this.closed||(this.listeners.delete(o),a())},getCurrentValue:()=>this.client.localQueryResultByToken(i),getQueryLogs:()=>this.client.localQueryLogs(i)},c=s.unsubscribe;return Object.assign(c,s),c}onPaginatedUpdate_experimental(e,t,n,r,i){if(this.disabled)return this.createDisabledUnsubscribe();let a={initialNumItems:n.initialNumItems,id:-1},{paginatedQueryToken:o,unsubscribe:s}=this.paginatedClient.subscribe(u(e),t,a),c={queryToken:o,callback:r,onError:i,unsubscribe:s,hasEverRun:!1,query:e,args:t,paginationOptions:a};this.listeners.add(c),this.paginatedClient.localQueryResultByToken(o)&&this.callNewListenersWithCurrentValuesTimer===void 0&&(this.callNewListenersWithCurrentValuesTimer=setTimeout(()=>this.callNewListenersWithCurrentValues(),0));let l={unsubscribe:()=>{this.closed||(this.listeners.delete(c),s())},getCurrentValue:()=>this.paginatedClient.localQueryResult(u(e),t,a),getQueryLogs:()=>[]},d=l.unsubscribe;return Object.assign(d,l),d}callNewListenersWithCurrentValues(){this.callNewListenersWithCurrentValuesTimer=void 0,this._transition({queries:[],paginatedQueries:[]},!0)}queryResultReady(e){return this.client.hasLocalQueryResultByToken(e)}createDisabledUnsubscribe(){let e=(()=>{});return Object.assign(e,{unsubscribe:e,getCurrentValue:()=>void 0,getQueryLogs:()=>void 0}),e}async close(){if(!this.disabled)return this.listeners.clear(),this._closed=!0,this._paginatedClient&&=void 0,this.client.close()}getAuth(){if(!this.disabled)return this.client.getCurrentAuthClaims()}setAuth(e,t){this.disabled||this.client.setAuth(e,t??(()=>{}))}setAdminAuth(e,t){if(this.closed)throw Error(`ConvexClient has already been closed.`);this.disabled||this.client.setAdminAuth(e,t)}_transition({queries:e,paginatedQueries:t},n=!1){let r=[...e.map(e=>e.token),...t.map(e=>e.token)];for(let e of this.listeners){let{callback:t,queryToken:i,onError:a,hasEverRun:o}=e,s=ze(i),c=s?!!this.paginatedClient.localQueryResultByToken(i):this.client.hasLocalQueryResultByToken(i);if(r.includes(i)||n&&!o&&c){e.hasEverRun=!0;let n;try{n=s?this.paginatedClient.localQueryResultByToken(i):this.client.localQueryResultByToken(i)}catch(e){if(!(e instanceof Error))throw e;a?a(e,`Second argument to onUpdate onError is reserved for later use`):Promise.reject(e);continue}t(n,`Second argument to onUpdate callback is reserved for later use`)}}}async mutation(e,t,n){if(this.disabled)throw Error(`ConvexClient is disabled`);return await this.client.mutation(u(e),t,n)}async action(e,t){if(this.disabled)throw Error(`ConvexClient is disabled`);return await this.client.action(u(e),t)}async query(e,t){if(this.disabled)throw Error(`ConvexClient is disabled`);let n=this.client.localQueryResult(u(e),t);return n===void 0?new Promise((n,r)=>{let{unsubscribe:i}=this.onUpdate(e,t,e=>{i(),n(e)},e=>{i(),r(e)})}):Promise.resolve(n)}connectionState(){if(this.disabled)throw Error(`ConvexClient is disabled`);return this.client.connectionState()}subscribeToConnectionState(e){return this.disabled?()=>{}:this.client.subscribeToConnectionState(e)}},X=Symbol(`convex.useQuery.skip`);function Wt(e){return typeof e==`function`&&(e=e()),e===`skip`?{skip:!0,args:void 0}:{skip:!1,args:e}}function Gt(e,t){return JSON.stringify(O(e))===JSON.stringify(O(t))}function Kt(e,t){return e===X&&t===X?!0:e===X||t===X?!1:Gt(e,t)}function Z(e){let{skip:t,args:n}=Wt(e);return t?X:s(n)}var Q=null,qt=null,Jt=[];function Yt(){if(Jt===null)return;let e=Jt;Jt=null;for(let t of e)t()}function Xt(){return Q?.closed?(Q=null,qt=null,null):Q}function Zt(){return qt}function Qt(e,t){qt=e,Q=t}function $t(){let e=Xt();if(!e)throw Error(`Convex client not initialized. Call setupConvex() or initConvex() first.`);return e}function en(e){return!e.disabled&&!e.closed}var tn=`$$_convexClient`,nn=`$$_convexAuth`,rn=()=>{let e=c(tn);if(!e)throw Error(`No ConvexClient was found in Svelte context. Did you forget to call setupConvex() in a parent component?`);return e},an=e=>l(tn,e),on=(e,t={})=>{if(!e||typeof e!=`string`)throw Error(`Expected string url property for setupConvex`);let n=Xt();if(n&&Zt()!==e)throw Error(`setupConvex() was called with ${e}, but the Convex client is already initialized for ${Zt()}. Only one deployment per app is supported. Call closeConvex() first to switch deployments.`);let r=n??new Ut(e,{disabled:!1,...t});return n||Qt(e,r),an(r),queueMicrotask(()=>Yt()),r};function sn(i,o={},c={}){let l=rn();if(typeof i==`string`)throw Error(`Query must be a functionReference object, not a string`);let d=r({result:$(c).initialData,lastResult:void 0,argsForLastResult:void 0,haveArgsEverChanged:!1});n(()=>{let e=Z(o);if(e===X){d.result=void 0,d.argsForLastResult=X;return}if(en(l))return l.onUpdate(i,e,t=>{let n=structuredClone(t);d.result=n,d.argsForLastResult=e,d.lastResult=n},t=>{d.result=t,d.argsForLastResult=e;let n=structuredClone(t);d.lastResult=n})});let f=e(()=>Z(o)),p=Z(o),m=e(()=>d.argsForLastResult!==void 0&&t(f)!==X&&d.argsForLastResult!==X&&Gt(d.argsForLastResult,t(f))),h=e(()=>!!($(c).keepPreviousData&&d.lastResult)),g=e(()=>t(f)===X);n(()=>{if(!a(()=>d.haveArgsEverChanged)){let e=Z(o);if(!Kt(p,e)){d.haveArgsEverChanged=!0;let e=$(c);e.initialData!==void 0&&(d.argsForLastResult=p===X?X:s(p),d.lastResult=e.initialData)}}});let _=e(()=>{if(t(g))return;if($(c).initialData&&!d.haveArgsEverChanged)return d.result;let e;try{e=en(l)?l.client.localQueryResult(u(i),t(f)):void 0}catch(t){if(!(t instanceof Error))throw console.error(`threw non-Error instance`,t),t;e=t}return d.result,e}),v=e(()=>t(_)===void 0?t(h)?d.lastResult:void 0:t(_)),ee=e(()=>!t(g)&&t(_)===void 0&&t(h)&&!t(m)&&t(v)!==void 0),y=e(()=>{if(!(t(v)instanceof Error))return t(v)}),b=e(()=>{if(t(v)instanceof Error)return t(v)});return{get data(){return t(y)},get isLoading(){return!t(g)&&t(b)===void 0&&t(y)===void 0},get error(){return t(b)},get isStale(){return!t(g)&&t(ee)}}}function $(e){return typeof e==`function`&&(e=e()),s(e)}function cn(e,s){let c=rn(),u=s?.initialState!==void 0,d=i(r(u?!!s.initialState.isAuthenticated:null)),f=!1,p,m=!1;if(u&&s.initialState?.isAuthenticated){let{fetchAccessToken:t}=e();m=!0,c.setAuth(t,e=>{o(d,e,!0)})}Yt(),n(()=>{let{isLoading:n,isAuthenticated:r,fetchAccessToken:i}=e();n||(f=!0);let s=a(()=>t(d));if(p=r,m)return r?(m=!1,()=>{c.setAuth(async()=>null,()=>{})}):void 0;if(n&&s!==null&&f&&o(d,null),!n&&!r&&s!==!1&&o(d,!1),r){s===!1&&o(d,null);let e=!0;return c.setAuth(i,t=>{e&&o(d,t,!0)}),()=>{e=!1,c.setAuth(async()=>null,()=>{})}}}),l(nn,{get isLoading(){return t(d)===null||t(d)===!1&&p!==void 0&&a(()=>e().isAuthenticated)!==p},get isAuthenticated(){let n=t(d);return!f&&u?n===!0:n===!0||a(()=>e().isAuthenticated)&&(n??!1)}})}function ln(){let e=c(nn);if(!e)throw Error(`useAuth() requires setupAuth() to be called in a parent component. If you are using an auth adapter (e.g. convex-better-auth-svelte), make sure its setup function is called before useAuth().`);return{get isLoading(){return e.isLoading},get isAuthenticated(){return e.isAuthenticated}}}function un(e){return(t,n)=>$t().mutation(e,t,n)}function dn(e){return t=>$t().action(e,t)}export{rn as a,k as c,ln as i,O as l,on as n,un as o,dn as r,sn as s,cn as t};
|