@phpsandbox/sdk 0.6.0-canary.7 → 0.6.0-canary.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -533,6 +533,21 @@ Inspect deployment, runtime and routing outcomes for each selected app; a partia
533
533
 
534
534
  Shared managed-resource creation currently starts with one app. After creation, update the resource definition to `reuse` with the catalog resource ID before attaching other apps. Simultaneous first-time shared-resource creation is unsupported.
535
535
 
536
+ #### Custom domains
537
+
538
+ For a healthy Laravel Cloud publication, choose the DNS setup when creating the domain:
539
+
540
+ ```ts
541
+ const publication = await client.publications.get('PUBLICATION_ID');
542
+ const domain = await publication.domains.create('app.example.com', {
543
+ cloudflareStrategy: 'dns_proxy',
544
+ allowDowntime: false,
545
+ });
546
+ console.log(domain.dnsInstructions);
547
+ ```
548
+
549
+ Use `none` for another DNS provider, `dns` for Cloudflare DNS only, or `dns_proxy` for Cloudflare's orange-cloud proxy. `allowDowntime: false` prepares verification before traffic moves; `true` allows routing first. Omitted options preserve the existing `none` / uninterrupted defaults. These optional settings require an API version that supports domain DNS and transfer choices. Existing provider domains are inspected rather than reconfigured.
550
+
536
551
  #### Browser publishing streams through your backend
537
552
 
538
553
  Keep service-account credentials on your server. After authorizing project access and checking the requested publishing attempt, open the original SSE bytes with `publication.stream()`. Return the SDK's standard `Response` directly from your framework:
@@ -19952,8 +19952,12 @@ var PublicationDomains = class {
19952
19952
  async list() {
19953
19953
  return (await this.client.get(this.path())).data;
19954
19954
  }
19955
- async create(hostname3) {
19956
- return (await this.client.post(this.path(), { hostname: hostname3 })).data;
19955
+ async create(hostname3, options = {}) {
19956
+ return (await this.client.post(this.path(), {
19957
+ hostname: hostname3,
19958
+ cloudflareStrategy: options.cloudflareStrategy,
19959
+ allowDowntime: options.allowDowntime
19960
+ })).data;
19957
19961
  }
19958
19962
  async refresh(id) {
19959
19963
  return (await this.client.post(`${this.path()}/${encodeURIComponent(id)}/refresh`)).data;
@@ -64,7 +64,7 @@ var Rf=Object.defineProperty;var Jl=r=>{throw TypeError(r)};var ne=(r,e)=>{for(v
64
64
 
65
65
  Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let a of r.seen.entries()){let s=a[1];if(e===a[0]){o(a);continue}if(r.external){let u=r.external.registry.get(a[0])?.id;if(e!==a[0]&&u){o(a);continue}}if(r.metadataRegistry.get(a[0])?.id){o(a);continue}if(s.cycle){o(a);continue}if(s.count>1&&r.reused==="ref"){o(a);continue}}}function $e(r,e){let n=r.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let i=s=>{let c=r.seen.get(s);if(c.ref===null)return;let u=c.def??c.schema,d={...u},m=c.ref;if(c.ref=null,m){i(m);let g=r.seen.get(m),k=g.schema;if(k.$ref&&(r.target==="draft-07"||r.target==="draft-04"||r.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(k)):Object.assign(u,k),Object.assign(u,d),s._zod.parent===m)for(let P in u)P==="$ref"||P==="allOf"||P in d||delete u[P];if(k.$ref&&g.def)for(let P in u)P==="$ref"||P==="allOf"||P in g.def&&JSON.stringify(u[P])===JSON.stringify(g.def[P])&&delete u[P]}let h=s._zod.parent;if(h&&h!==m){i(h);let g=r.seen.get(h);if(g?.schema.$ref&&(u.$ref=g.schema.$ref,g.def))for(let k in u)k==="$ref"||k==="allOf"||k in g.def&&JSON.stringify(u[k])===JSON.stringify(g.def[k])&&delete u[k]}r.override({zodSchema:s,jsonSchema:u,path:c.path??[]})};for(let s of[...r.seen.entries()].reverse())i(s[0]);let t={};if(r.target==="draft-2020-12"?t.$schema="https://json-schema.org/draft/2020-12/schema":r.target==="draft-07"?t.$schema="http://json-schema.org/draft-07/schema#":r.target==="draft-04"?t.$schema="http://json-schema.org/draft-04/schema#":r.target,r.external?.uri){let s=r.external.registry.get(e)?.id;if(!s)throw new Error("Schema is missing an `id` property");t.$id=r.external.uri(s)}Object.assign(t,n.def??n.schema);let o=r.metadataRegistry.get(e)?.id;o!==void 0&&t.id===o&&delete t.id;let a=r.external?.defs??{};for(let s of r.seen.entries()){let c=s[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,a[c.defId]=c.def)}r.external||Object.keys(a).length>0&&(r.target==="draft-2020-12"?t.$defs=a:t.definitions=a);try{let s=JSON.parse(JSON.stringify(t));return Object.defineProperty(s,"~standard",{value:{...e["~standard"],jsonSchema:{input:ft(e,"input",r.processors),output:ft(e,"output",r.processors)}},enumerable:!1,writable:!1}),s}catch{throw new Error("Error converting schema to JSON.")}}function V(r,e){let n=e??{seen:new Set};if(n.seen.has(r))return!1;n.seen.add(r);let i=r._zod.def;if(i.type==="transform")return!0;if(i.type==="array")return V(i.element,n);if(i.type==="set")return V(i.valueType,n);if(i.type==="lazy")return V(i.getter(),n);if(i.type==="promise"||i.type==="optional"||i.type==="nonoptional"||i.type==="nullable"||i.type==="readonly"||i.type==="default"||i.type==="prefault")return V(i.innerType,n);if(i.type==="intersection")return V(i.left,n)||V(i.right,n);if(i.type==="record"||i.type==="map")return V(i.keyType,n)||V(i.valueType,n);if(i.type==="pipe")return r._zod.traits.has("$ZodCodec")?!0:V(i.in,n)||V(i.out,n);if(i.type==="object"){for(let t in i.shape)if(V(i.shape[t],n))return!0;return!1}if(i.type==="union"){for(let t of i.options)if(V(t,n))return!0;return!1}if(i.type==="tuple"){for(let t of i.items)if(V(t,n))return!0;return!!(i.rest&&V(i.rest,n))}return!1}var pc=(r,e={})=>n=>{let i=xe({...n,processors:e});return z(r,i),ke(i,r),$e(i,r)},ft=(r,e,n={})=>i=>{let{libraryOptions:t,target:o}=i??{},a=xe({...t??{},target:o,io:e,processors:n});return z(r,a),ke(a,r),$e(a,r)};var cv={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},mc=(r,e,n,i)=>{let t=n;t.type="string";let{minimum:o,maximum:a,format:s,patterns:c,contentEncoding:u}=r._zod.bag;if(typeof o=="number"&&(t.minLength=o),typeof a=="number"&&(t.maxLength=a),s&&(t.format=cv[s]??s,t.format===""&&delete t.format,s==="time"&&delete t.format),u&&(t.contentEncoding=u),c&&c.size>0){let d=[...c];d.length===1?t.pattern=d[0].source:d.length>1&&(t.allOf=[...d.map(m=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:m.source}))])}},fc=(r,e,n,i)=>{let t=n,{minimum:o,maximum:a,format:s,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:d}=r._zod.bag;typeof s=="string"&&s.includes("int")?t.type="integer":t.type="number";let m=typeof d=="number"&&d>=(o??Number.NEGATIVE_INFINITY),h=typeof u=="number"&&u<=(a??Number.POSITIVE_INFINITY),g=e.target==="draft-04"||e.target==="openapi-3.0";m?g?(t.minimum=d,t.exclusiveMinimum=!0):t.exclusiveMinimum=d:typeof o=="number"&&(t.minimum=o),h?g?(t.maximum=u,t.exclusiveMaximum=!0):t.exclusiveMaximum=u:typeof a=="number"&&(t.maximum=a),typeof c=="number"&&(t.multipleOf=c)},gc=(r,e,n,i)=>{n.type="boolean"},hc=(r,e,n,i)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},vc=(r,e,n,i)=>{if(e.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},bc=(r,e,n,i)=>{e.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},yc=(r,e,n,i)=>{if(e.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},xc=(r,e,n,i)=>{if(e.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},kc=(r,e,n,i)=>{n.not={}},$c=(r,e,n,i)=>{},wc=(r,e,n,i)=>{},_c=(r,e,n,i)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},Sc=(r,e,n,i)=>{let t=r._zod.def,o=Ot(t.entries);o.every(a=>typeof a=="number")&&(n.type="number"),o.every(a=>typeof a=="string")&&(n.type="string"),n.enum=o},Ic=(r,e,n,i)=>{let t=r._zod.def,o=[];for(let a of t.values)if(a===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof a=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");o.push(Number(a))}else o.push(a);if(o.length!==0)if(o.length===1){let a=o[0];n.type=a===null?"null":typeof a,e.target==="draft-04"||e.target==="openapi-3.0"?n.enum=[a]:n.const=a}else o.every(a=>typeof a=="number")&&(n.type="number"),o.every(a=>typeof a=="string")&&(n.type="string"),o.every(a=>typeof a=="boolean")&&(n.type="boolean"),o.every(a=>a===null)&&(n.type="null"),n.enum=o},Pc=(r,e,n,i)=>{if(e.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},zc=(r,e,n,i)=>{let t=n,o=r._zod.pattern;if(!o)throw new Error("Pattern not found in template literal");t.type="string",t.pattern=o.source},Ec=(r,e,n,i)=>{let t=n,o={type:"string",format:"binary",contentEncoding:"binary"},{minimum:a,maximum:s,mime:c}=r._zod.bag;a!==void 0&&(o.minLength=a),s!==void 0&&(o.maxLength=s),c?c.length===1?(o.contentMediaType=c[0],Object.assign(t,o)):(Object.assign(t,o),t.anyOf=c.map(u=>({contentMediaType:u}))):Object.assign(t,o)},Tc=(r,e,n,i)=>{n.type="boolean"},Dc=(r,e,n,i)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},Uc=(r,e,n,i)=>{if(e.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},Rc=(r,e,n,i)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},Oc=(r,e,n,i)=>{if(e.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},Ac=(r,e,n,i)=>{if(e.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},Cc=(r,e,n,i)=>{let t=n,o=r._zod.def,{minimum:a,maximum:s}=r._zod.bag;typeof a=="number"&&(t.minItems=a),typeof s=="number"&&(t.maxItems=s),t.type="array",t.items=z(o.element,e,{...i,path:[...i.path,"items"]})},jc=(r,e,n,i)=>{let t=n,o=r._zod.def;t.type="object",t.properties={};let a=o.shape;for(let u in a)t.properties[u]=z(a[u],e,{...i,path:[...i.path,"properties",u]});let s=new Set(Object.keys(a)),c=new Set([...s].filter(u=>{let d=o.shape[u]._zod;return e.io==="input"?d.optin===void 0:d.optout===void 0}));c.size>0&&(t.required=Array.from(c)),o.catchall?._zod.def.type==="never"?t.additionalProperties=!1:o.catchall?o.catchall&&(t.additionalProperties=z(o.catchall,e,{...i,path:[...i.path,"additionalProperties"]})):e.io==="output"&&(t.additionalProperties=!1)},Vn=(r,e,n,i)=>{let t=r._zod.def,o=t.inclusive===!1,a=t.options.map((s,c)=>z(s,e,{...i,path:[...i.path,o?"oneOf":"anyOf",c]}));o?n.oneOf=a:n.anyOf=a},Nc=(r,e,n,i)=>{let t=r._zod.def,o=z(t.left,e,{...i,path:[...i.path,"allOf",0]}),a=z(t.right,e,{...i,path:[...i.path,"allOf",1]}),s=u=>"allOf"in u&&Object.keys(u).length===1,c=[...s(o)?o.allOf:[o],...s(a)?a.allOf:[a]];n.allOf=c},Lc=(r,e,n,i)=>{let t=n,o=r._zod.def;t.type="array";let a=e.target==="draft-2020-12"?"prefixItems":"items",s=e.target==="draft-2020-12"||e.target==="openapi-3.0"?"items":"additionalItems",c=o.items.map((h,g)=>z(h,e,{...i,path:[...i.path,a,g]})),u=o.rest?z(o.rest,e,{...i,path:[...i.path,s,...e.target==="openapi-3.0"?[o.items.length]:[]]}):null;e.target==="draft-2020-12"?(t.prefixItems=c,u&&(t.items=u)):e.target==="openapi-3.0"?(t.items={anyOf:c},u&&t.items.anyOf.push(u),t.minItems=c.length,u||(t.maxItems=c.length)):(t.items=c,u&&(t.additionalItems=u));let{minimum:d,maximum:m}=r._zod.bag;typeof d=="number"&&(t.minItems=d),typeof m=="number"&&(t.maxItems=m)},Zc=(r,e,n,i)=>{let t=n,o=r._zod.def;t.type="object";let a=o.keyType,c=a._zod.bag?.patterns;if(o.mode==="loose"&&c&&c.size>0){let d=z(o.valueType,e,{...i,path:[...i.path,"patternProperties","*"]});t.patternProperties={};for(let m of c)t.patternProperties[m.source]=d}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(t.propertyNames=z(o.keyType,e,{...i,path:[...i.path,"propertyNames"]})),t.additionalProperties=z(o.valueType,e,{...i,path:[...i.path,"additionalProperties"]});let u=a._zod.values;if(u){let d=[...u].filter(m=>typeof m=="string"||typeof m=="number");d.length>0&&(t.required=d)}},Fc=(r,e,n,i)=>{let t=r._zod.def,o=z(t.innerType,e,i),a=e.seen.get(r);e.target==="openapi-3.0"?(a.ref=t.innerType,n.nullable=!0):n.anyOf=[o,{type:"null"}]},Mc=(r,e,n,i)=>{let t=r._zod.def;z(t.innerType,e,i);let o=e.seen.get(r);o.ref=t.innerType},Bc=(r,e,n,i)=>{let t=r._zod.def;z(t.innerType,e,i);let o=e.seen.get(r);o.ref=t.innerType,n.default=JSON.parse(JSON.stringify(t.defaultValue))},Gc=(r,e,n,i)=>{let t=r._zod.def;z(t.innerType,e,i);let o=e.seen.get(r);o.ref=t.innerType,e.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(t.defaultValue)))},Wc=(r,e,n,i)=>{let t=r._zod.def;z(t.innerType,e,i);let o=e.seen.get(r);o.ref=t.innerType;let a;try{a=t.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=a},Vc=(r,e,n,i)=>{let t=r._zod.def,o=t.in._zod.traits.has("$ZodTransform"),a=e.io==="input"?o?t.out:t.in:t.out;z(a,e,i);let s=e.seen.get(r);s.ref=a},Jc=(r,e,n,i)=>{let t=r._zod.def;z(t.innerType,e,i);let o=e.seen.get(r);o.ref=t.innerType,n.readOnly=!0},Kc=(r,e,n,i)=>{let t=r._zod.def;z(t.innerType,e,i);let o=e.seen.get(r);o.ref=t.innerType},Jn=(r,e,n,i)=>{let t=r._zod.def;z(t.innerType,e,i);let o=e.seen.get(r);o.ref=t.innerType},qc=(r,e,n,i)=>{let t=r._zod.innerType;z(t,e,i);let o=e.seen.get(r);o.ref=t},Wn={string:mc,number:fc,boolean:gc,bigint:hc,symbol:vc,null:bc,undefined:yc,void:xc,never:kc,any:$c,unknown:wc,date:_c,enum:Sc,literal:Ic,nan:Pc,template_literal:zc,file:Ec,success:Tc,custom:Dc,function:Uc,transform:Rc,map:Oc,set:Ac,array:Cc,object:jc,union:Vn,intersection:Nc,tuple:Lc,record:Zc,nullable:Fc,nonoptional:Mc,default:Bc,prefault:Gc,catch:Wc,pipe:Vc,readonly:Jc,promise:Kc,optional:Jn,lazy:qc};function Kn(r,e){if("_idmap"in r){let i=r,t=xe({...e,processors:Wn}),o={};for(let c of i._idmap.entries()){let[u,d]=c;z(d,t)}let a={},s={registry:i,uri:e?.uri,defs:o};t.external=s;for(let c of i._idmap.entries()){let[u,d]=c;ke(t,d),a[u]=$e(t,d)}if(Object.keys(o).length>0){let c=t.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[c]:o}}return{schemas:a}}let n=xe({...e,processors:Wn});return z(r,n),ke(n,r),$e(n,r)}var qn=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(e){this.ctx.counter=e}get seen(){return this.ctx.seen}constructor(e){let n=e?.target??"draft-2020-12";n==="draft-4"&&(n="draft-04"),n==="draft-7"&&(n="draft-07"),this.ctx=xe({processors:Wn,target:n,...e?.metadata&&{metadata:e.metadata},...e?.unrepresentable&&{unrepresentable:e.unrepresentable},...e?.override&&{override:e.override},...e?.io&&{io:e.io}})}process(e,n={path:[],schemaPath:[]}){return z(e,this.ctx,n)}emit(e,n){n&&(n.cycles&&(this.ctx.cycles=n.cycles),n.reused&&(this.ctx.reused=n.reused),n.external&&(this.ctx.external=n.external)),ke(this.ctx,e);let i=$e(this.ctx,e),{"~standard":t,...o}=i;return o}};var Ip={};var Yt={};ne(Yt,{ZodAny:()=>yu,ZodArray:()=>wu,ZodBase64:()=>hi,ZodBase64URL:()=>vi,ZodBigInt:()=>$t,ZodBigIntFormat:()=>xi,ZodBoolean:()=>kt,ZodCIDRv4:()=>fi,ZodCIDRv6:()=>gi,ZodCUID:()=>si,ZodCUID2:()=>ci,ZodCatch:()=>Wu,ZodCodec:()=>lr,ZodCustom:()=>dr,ZodCustomStringFormat:()=>yt,ZodDate:()=>or,ZodDefault:()=>Lu,ZodDiscriminatedUnion:()=>Su,ZodE164:()=>bi,ZodEmail:()=>ii,ZodEmoji:()=>oi,ZodEnum:()=>vt,ZodExactOptional:()=>Cu,ZodFile:()=>Ou,ZodFunction:()=>tl,ZodGUID:()=>er,ZodIPv4:()=>pi,ZodIPv6:()=>mi,ZodIntersection:()=>Iu,ZodJWT:()=>yi,ZodKSUID:()=>di,ZodLazy:()=>Yu,ZodLiteral:()=>Ru,ZodMAC:()=>pu,ZodMap:()=>Du,ZodNaN:()=>Ju,ZodNanoID:()=>ai,ZodNever:()=>ku,ZodNonOptional:()=>Ii,ZodNull:()=>vu,ZodNullable:()=>Nu,ZodNumber:()=>xt,ZodNumberFormat:()=>Ce,ZodObject:()=>sr,ZodOptional:()=>Si,ZodPipe:()=>ur,ZodPrefault:()=>Fu,ZodPreprocess:()=>Ku,ZodPromise:()=>el,ZodReadonly:()=>qu,ZodRecord:()=>ht,ZodSet:()=>Uu,ZodString:()=>bt,ZodStringFormat:()=>D,ZodSuccess:()=>Gu,ZodSymbol:()=>gu,ZodTemplateLiteral:()=>Xu,ZodTransform:()=>Au,ZodTuple:()=>zu,ZodType:()=>S,ZodULID:()=>ui,ZodURL:()=>ir,ZodUUID:()=>se,ZodUndefined:()=>hu,ZodUnion:()=>cr,ZodUnknown:()=>xu,ZodVoid:()=>$u,ZodXID:()=>li,ZodXor:()=>_u,_ZodString:()=>ni,_default:()=>Zu,_function:()=>Am,any:()=>pm,array:()=>ar,base64:()=>qp,base64url:()=>Hp,bigint:()=>sm,boolean:()=>fu,catch:()=>Vu,check:()=>Cm,cidrv4:()=>Jp,cidrv6:()=>Kp,codec:()=>Dm,cuid:()=>Lp,cuid2:()=>Zp,custom:()=>jm,date:()=>fm,describe:()=>Nm,discriminatedUnion:()=>xm,e164:()=>Xp,email:()=>Ep,emoji:()=>jp,enum:()=>wi,exactOptional:()=>ju,file:()=>Pm,float32:()=>nm,float64:()=>im,function:()=>Am,guid:()=>Tp,hash:()=>rm,hex:()=>tm,hostname:()=>em,httpUrl:()=>Cp,instanceof:()=>Zm,int:()=>ti,int32:()=>om,int64:()=>cm,intersection:()=>Pu,invertCodec:()=>Um,ipv4:()=>Gp,ipv6:()=>Vp,json:()=>Mm,jwt:()=>Yp,keyof:()=>gm,ksuid:()=>Bp,lazy:()=>Qu,literal:()=>Im,looseObject:()=>bm,looseRecord:()=>$m,mac:()=>Wp,map:()=>wm,meta:()=>Lm,nan:()=>Tm,nanoid:()=>Np,nativeEnum:()=>Sm,never:()=>ki,nonoptional:()=>Bu,null:()=>bu,nullable:()=>rr,nullish:()=>zm,number:()=>mu,object:()=>hm,optional:()=>tr,partialRecord:()=>km,pipe:()=>ri,prefault:()=>Mu,preprocess:()=>Bm,promise:()=>Om,readonly:()=>Hu,record:()=>Tu,refine:()=>rl,set:()=>_m,strictObject:()=>vm,string:()=>Qt,stringFormat:()=>Qp,stringbool:()=>Fm,success:()=>Em,superRefine:()=>nl,symbol:()=>lm,templateLiteral:()=>Rm,transform:()=>_i,tuple:()=>Eu,uint32:()=>am,uint64:()=>um,ulid:()=>Fp,undefined:()=>dm,union:()=>$i,unknown:()=>Ae,url:()=>Ap,uuid:()=>Dp,uuidv4:()=>Up,uuidv6:()=>Rp,uuidv7:()=>Op,void:()=>mm,xid:()=>Mp,xor:()=>ym});var Hn={};ne(Hn,{endsWith:()=>at,gt:()=>oe,gte:()=>W,includes:()=>it,length:()=>Oe,lowercase:()=>rt,lt:()=>ie,lte:()=>Y,maxLength:()=>Re,maxSize:()=>ye,mime:()=>st,minLength:()=>ue,minSize:()=>ae,multipleOf:()=>be,negative:()=>Fn,nonnegative:()=>Bn,nonpositive:()=>Mn,normalize:()=>ct,overwrite:()=>re,positive:()=>Zn,property:()=>Gn,regex:()=>tt,size:()=>Ue,slugify:()=>pt,startsWith:()=>ot,toLowerCase:()=>lt,toUpperCase:()=>dt,trim:()=>ut,uppercase:()=>nt});var gt={};ne(gt,{ZodISODate:()=>Yn,ZodISODateTime:()=>Xn,ZodISODuration:()=>ei,ZodISOTime:()=>Qn,date:()=>Xc,datetime:()=>Hc,duration:()=>Qc,time:()=>Yc});var Xn=p("ZodISODateTime",(r,e)=>{Pa.init(r,e),D.init(r,e)});function Hc(r){return Ds(Xn,r)}var Yn=p("ZodISODate",(r,e)=>{za.init(r,e),D.init(r,e)});function Xc(r){return Us(Yn,r)}var Qn=p("ZodISOTime",(r,e)=>{Ea.init(r,e),D.init(r,e)});function Yc(r){return Rs(Qn,r)}var ei=p("ZodISODuration",(r,e)=>{Ta.init(r,e),D.init(r,e)});function Qc(r){return Os(ei,r)}var Pp=(r,e)=>{Lt.init(r,e),r.name="ZodError",Object.defineProperties(r,{format:{value:n=>Ft(r,n)},flatten:{value:n=>Zt(r,n)},addIssue:{value:n=>{r.issues.push(n),r.message=JSON.stringify(r.issues,Ve,2)}},addIssues:{value:n=>{r.issues.push(...n),r.message=JSON.stringify(r.issues,Ve,2)}},isEmpty:{get(){return r.issues.length===0}}})},lv=p("ZodError",Pp),q=p("ZodError",Pp,{Parent:Error});var eu=qe(q),tu=He(q),ru=Xe(q),nu=Ye(q),iu=Jr(q),ou=Kr(q),au=qr(q),su=Hr(q),cu=Xr(q),uu=Yr(q),lu=Qr(q),du=en(q);var zp=new WeakMap;function nr(r,e,n){let i=Object.getPrototypeOf(r),t=zp.get(i);if(t||(t=new Set,zp.set(i,t)),!t.has(e)){t.add(e);for(let o in n){let a=n[o];Object.defineProperty(i,o,{configurable:!0,enumerable:!1,get(){let s=a.bind(this);return Object.defineProperty(this,o,{configurable:!0,writable:!0,enumerable:!0,value:s}),s},set(s){Object.defineProperty(this,o,{configurable:!0,writable:!0,enumerable:!0,value:s})}})}}}var S=p("ZodType",(r,e)=>(_.init(r,e),Object.assign(r["~standard"],{jsonSchema:{input:ft(r,"input"),output:ft(r,"output")}}),r.toJSONSchema=pc(r,{}),r.def=e,r.type=e.type,Object.defineProperty(r,"_def",{value:e}),r.parse=(n,i)=>eu(r,n,i,{callee:r.parse}),r.safeParse=(n,i)=>ru(r,n,i),r.parseAsync=async(n,i)=>tu(r,n,i,{callee:r.parseAsync}),r.safeParseAsync=async(n,i)=>nu(r,n,i),r.spa=r.safeParseAsync,r.encode=(n,i)=>iu(r,n,i),r.decode=(n,i)=>ou(r,n,i),r.encodeAsync=async(n,i)=>au(r,n,i),r.decodeAsync=async(n,i)=>su(r,n,i),r.safeEncode=(n,i)=>cu(r,n,i),r.safeDecode=(n,i)=>uu(r,n,i),r.safeEncodeAsync=async(n,i)=>lu(r,n,i),r.safeDecodeAsync=async(n,i)=>du(r,n,i),nr(r,"ZodType",{check(...n){let i=this.def;return this.clone(y.mergeDefs(i,{checks:[...i.checks??[],...n.map(t=>typeof t=="function"?{_zod:{check:t,def:{check:"custom"},onattach:[]}}:t)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,i){return B(this,n,i)},brand(){return this},register(n,i){return n.add(this,i),this},refine(n,i){return this.check(rl(n,i))},superRefine(n,i){return this.check(nl(n,i))},overwrite(n){return this.check(re(n))},optional(){return tr(this)},exactOptional(){return ju(this)},nullable(){return rr(this)},nullish(){return tr(rr(this))},nonoptional(n){return Bu(this,n)},array(){return ar(this)},or(n){return $i([this,n])},and(n){return Pu(this,n)},transform(n){return ri(this,_i(n))},default(n){return Zu(this,n)},prefault(n){return Mu(this,n)},catch(n){return Vu(this,n)},pipe(n){return ri(this,n)},readonly(){return Hu(this)},describe(n){let i=this.clone();return Z.add(i,{description:n}),i},meta(...n){if(n.length===0)return Z.get(this);let i=this.clone();return Z.add(i,n[0]),i},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(r,"description",{get(){return Z.get(r)?.description},configurable:!0}),r)),ni=p("_ZodString",(r,e)=>{De.init(r,e),S.init(r,e),r._zod.processJSONSchema=(i,t,o)=>mc(r,i,t,o);let n=r._zod.bag;r.format=n.format??null,r.minLength=n.minimum??null,r.maxLength=n.maximum??null,nr(r,"_ZodString",{regex(...i){return this.check(tt(...i))},includes(...i){return this.check(it(...i))},startsWith(...i){return this.check(ot(...i))},endsWith(...i){return this.check(at(...i))},min(...i){return this.check(ue(...i))},max(...i){return this.check(Re(...i))},length(...i){return this.check(Oe(...i))},nonempty(...i){return this.check(ue(1,...i))},lowercase(i){return this.check(rt(i))},uppercase(i){return this.check(nt(i))},trim(){return this.check(ut())},normalize(...i){return this.check(ct(...i))},toLowerCase(){return this.check(lt())},toUpperCase(){return this.check(dt())},slugify(){return this.check(pt())}})}),bt=p("ZodString",(r,e)=>{De.init(r,e),ni.init(r,e),r.email=n=>r.check(xn(ii,n)),r.url=n=>r.check(Xt(ir,n)),r.jwt=n=>r.check(Ln(yi,n)),r.emoji=n=>r.check(Sn(oi,n)),r.guid=n=>r.check(Ht(er,n)),r.uuid=n=>r.check(kn(se,n)),r.uuidv4=n=>r.check($n(se,n)),r.uuidv6=n=>r.check(wn(se,n)),r.uuidv7=n=>r.check(_n(se,n)),r.nanoid=n=>r.check(In(ai,n)),r.guid=n=>r.check(Ht(er,n)),r.cuid=n=>r.check(Pn(si,n)),r.cuid2=n=>r.check(zn(ci,n)),r.ulid=n=>r.check(En(ui,n)),r.base64=n=>r.check(Cn(hi,n)),r.base64url=n=>r.check(jn(vi,n)),r.xid=n=>r.check(Tn(li,n)),r.ksuid=n=>r.check(Dn(di,n)),r.ipv4=n=>r.check(Un(pi,n)),r.ipv6=n=>r.check(Rn(mi,n)),r.cidrv4=n=>r.check(On(fi,n)),r.cidrv6=n=>r.check(An(gi,n)),r.e164=n=>r.check(Nn(bi,n)),r.datetime=n=>r.check(Hc(n)),r.date=n=>r.check(Xc(n)),r.time=n=>r.check(Yc(n)),r.duration=n=>r.check(Qc(n))});function Qt(r){return Ps(bt,r)}var D=p("ZodStringFormat",(r,e)=>{T.init(r,e),ni.init(r,e)}),ii=p("ZodEmail",(r,e)=>{ba.init(r,e),D.init(r,e)});function Ep(r){return xn(ii,r)}var er=p("ZodGUID",(r,e)=>{ha.init(r,e),D.init(r,e)});function Tp(r){return Ht(er,r)}var se=p("ZodUUID",(r,e)=>{va.init(r,e),D.init(r,e)});function Dp(r){return kn(se,r)}function Up(r){return $n(se,r)}function Rp(r){return wn(se,r)}function Op(r){return _n(se,r)}var ir=p("ZodURL",(r,e)=>{ya.init(r,e),D.init(r,e)});function Ap(r){return Xt(ir,r)}function Cp(r){return Xt(ir,{protocol:X.httpProtocol,hostname:X.domain,...y.normalizeParams(r)})}var oi=p("ZodEmoji",(r,e)=>{xa.init(r,e),D.init(r,e)});function jp(r){return Sn(oi,r)}var ai=p("ZodNanoID",(r,e)=>{ka.init(r,e),D.init(r,e)});function Np(r){return In(ai,r)}var si=p("ZodCUID",(r,e)=>{$a.init(r,e),D.init(r,e)});function Lp(r){return Pn(si,r)}var ci=p("ZodCUID2",(r,e)=>{wa.init(r,e),D.init(r,e)});function Zp(r){return zn(ci,r)}var ui=p("ZodULID",(r,e)=>{_a.init(r,e),D.init(r,e)});function Fp(r){return En(ui,r)}var li=p("ZodXID",(r,e)=>{Sa.init(r,e),D.init(r,e)});function Mp(r){return Tn(li,r)}var di=p("ZodKSUID",(r,e)=>{Ia.init(r,e),D.init(r,e)});function Bp(r){return Dn(di,r)}var pi=p("ZodIPv4",(r,e)=>{Da.init(r,e),D.init(r,e)});function Gp(r){return Un(pi,r)}var pu=p("ZodMAC",(r,e)=>{Ra.init(r,e),D.init(r,e)});function Wp(r){return Es(pu,r)}var mi=p("ZodIPv6",(r,e)=>{Ua.init(r,e),D.init(r,e)});function Vp(r){return Rn(mi,r)}var fi=p("ZodCIDRv4",(r,e)=>{Oa.init(r,e),D.init(r,e)});function Jp(r){return On(fi,r)}var gi=p("ZodCIDRv6",(r,e)=>{Aa.init(r,e),D.init(r,e)});function Kp(r){return An(gi,r)}var hi=p("ZodBase64",(r,e)=>{ja.init(r,e),D.init(r,e)});function qp(r){return Cn(hi,r)}var vi=p("ZodBase64URL",(r,e)=>{Na.init(r,e),D.init(r,e)});function Hp(r){return jn(vi,r)}var bi=p("ZodE164",(r,e)=>{La.init(r,e),D.init(r,e)});function Xp(r){return Nn(bi,r)}var yi=p("ZodJWT",(r,e)=>{Za.init(r,e),D.init(r,e)});function Yp(r){return Ln(yi,r)}var yt=p("ZodCustomStringFormat",(r,e)=>{Fa.init(r,e),D.init(r,e)});function Qp(r,e,n={}){return mt(yt,r,e,n)}function em(r){return mt(yt,"hostname",X.hostname,r)}function tm(r){return mt(yt,"hex",X.hex,r)}function rm(r,e){let n=e?.enc??"hex",i=`${r}_${n}`,t=X[i];if(!t)throw new Error(`Unrecognized hash format: ${i}`);return mt(yt,i,t,e)}var xt=p("ZodNumber",(r,e)=>{ln.init(r,e),S.init(r,e),r._zod.processJSONSchema=(i,t,o)=>fc(r,i,t,o),nr(r,"ZodNumber",{gt(i,t){return this.check(oe(i,t))},gte(i,t){return this.check(W(i,t))},min(i,t){return this.check(W(i,t))},lt(i,t){return this.check(ie(i,t))},lte(i,t){return this.check(Y(i,t))},max(i,t){return this.check(Y(i,t))},int(i){return this.check(ti(i))},safe(i){return this.check(ti(i))},positive(i){return this.check(oe(0,i))},nonnegative(i){return this.check(W(0,i))},negative(i){return this.check(ie(0,i))},nonpositive(i){return this.check(Y(0,i))},multipleOf(i,t){return this.check(be(i,t))},step(i,t){return this.check(be(i,t))},finite(){return this}});let n=r._zod.bag;r.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,r.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,r.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),r.isFinite=!0,r.format=n.format??null});function mu(r){return As(xt,r)}var Ce=p("ZodNumberFormat",(r,e)=>{Ma.init(r,e),xt.init(r,e)});function ti(r){return js(Ce,r)}function nm(r){return Ns(Ce,r)}function im(r){return Ls(Ce,r)}function om(r){return Zs(Ce,r)}function am(r){return Fs(Ce,r)}var kt=p("ZodBoolean",(r,e)=>{Wt.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>gc(r,n,i,t)});function fu(r){return Ms(kt,r)}var $t=p("ZodBigInt",(r,e)=>{dn.init(r,e),S.init(r,e),r._zod.processJSONSchema=(i,t,o)=>hc(r,i,t,o),r.gte=(i,t)=>r.check(W(i,t)),r.min=(i,t)=>r.check(W(i,t)),r.gt=(i,t)=>r.check(oe(i,t)),r.gte=(i,t)=>r.check(W(i,t)),r.min=(i,t)=>r.check(W(i,t)),r.lt=(i,t)=>r.check(ie(i,t)),r.lte=(i,t)=>r.check(Y(i,t)),r.max=(i,t)=>r.check(Y(i,t)),r.positive=i=>r.check(oe(BigInt(0),i)),r.negative=i=>r.check(ie(BigInt(0),i)),r.nonpositive=i=>r.check(Y(BigInt(0),i)),r.nonnegative=i=>r.check(W(BigInt(0),i)),r.multipleOf=(i,t)=>r.check(be(i,t));let n=r._zod.bag;r.minValue=n.minimum??null,r.maxValue=n.maximum??null,r.format=n.format??null});function sm(r){return Gs($t,r)}var xi=p("ZodBigIntFormat",(r,e)=>{Ba.init(r,e),$t.init(r,e)});function cm(r){return Vs(xi,r)}function um(r){return Js(xi,r)}var gu=p("ZodSymbol",(r,e)=>{Ga.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>vc(r,n,i,t)});function lm(r){return Ks(gu,r)}var hu=p("ZodUndefined",(r,e)=>{Wa.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>yc(r,n,i,t)});function dm(r){return qs(hu,r)}var vu=p("ZodNull",(r,e)=>{Va.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>bc(r,n,i,t)});function bu(r){return Hs(vu,r)}var yu=p("ZodAny",(r,e)=>{Ja.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>$c(r,n,i,t)});function pm(){return Xs(yu)}var xu=p("ZodUnknown",(r,e)=>{Ka.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>wc(r,n,i,t)});function Ae(){return Ys(xu)}var ku=p("ZodNever",(r,e)=>{qa.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>kc(r,n,i,t)});function ki(r){return Qs(ku,r)}var $u=p("ZodVoid",(r,e)=>{Ha.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>xc(r,n,i,t)});function mm(r){return ec($u,r)}var or=p("ZodDate",(r,e)=>{Xa.init(r,e),S.init(r,e),r._zod.processJSONSchema=(i,t,o)=>_c(r,i,t,o),r.min=(i,t)=>r.check(W(i,t)),r.max=(i,t)=>r.check(Y(i,t));let n=r._zod.bag;r.minDate=n.minimum?new Date(n.minimum):null,r.maxDate=n.maximum?new Date(n.maximum):null});function fm(r){return tc(or,r)}var wu=p("ZodArray",(r,e)=>{Ya.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Cc(r,n,i,t),r.element=e.element,nr(r,"ZodArray",{min(n,i){return this.check(ue(n,i))},nonempty(n){return this.check(ue(1,n))},max(n,i){return this.check(Re(n,i))},length(n,i){return this.check(Oe(n,i))},unwrap(){return this.element}})});function ar(r,e){return ic(wu,r,e)}function gm(r){let e=r._zod.def.shape;return wi(Object.keys(e))}var sr=p("ZodObject",(r,e)=>{Qa.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>jc(r,n,i,t),y.defineLazy(r,"shape",()=>e.shape),nr(r,"ZodObject",{keyof(){return wi(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:Ae()})},loose(){return this.clone({...this._zod.def,catchall:Ae()})},strict(){return this.clone({...this._zod.def,catchall:ki()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return y.extend(this,n)},safeExtend(n){return y.safeExtend(this,n)},merge(n){return y.merge(this,n)},pick(n){return y.pick(this,n)},omit(n){return y.omit(this,n)},partial(...n){return y.partial(Si,this,n[0])},required(...n){return y.required(Ii,this,n[0])}})});function hm(r,e){let n={type:"object",shape:r??{},...y.normalizeParams(e)};return new sr(n)}function vm(r,e){return new sr({type:"object",shape:r,catchall:ki(),...y.normalizeParams(e)})}function bm(r,e){return new sr({type:"object",shape:r,catchall:Ae(),...y.normalizeParams(e)})}var cr=p("ZodUnion",(r,e)=>{Vt.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Vn(r,n,i,t),r.options=e.options});function $i(r,e){return new cr({type:"union",options:r,...y.normalizeParams(e)})}var _u=p("ZodXor",(r,e)=>{cr.init(r,e),es.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Vn(r,n,i,t),r.options=e.options});function ym(r,e){return new _u({type:"union",options:r,inclusive:!1,...y.normalizeParams(e)})}var Su=p("ZodDiscriminatedUnion",(r,e)=>{cr.init(r,e),ts.init(r,e)});function xm(r,e,n){return new Su({type:"union",options:e,discriminator:r,...y.normalizeParams(n)})}var Iu=p("ZodIntersection",(r,e)=>{rs.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Nc(r,n,i,t)});function Pu(r,e){return new Iu({type:"intersection",left:r,right:e})}var zu=p("ZodTuple",(r,e)=>{pn.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Lc(r,n,i,t),r.rest=n=>r.clone({...r._zod.def,rest:n})});function Eu(r,e,n){let i=e instanceof _,t=i?n:e,o=i?e:null;return new zu({type:"tuple",items:r,rest:o,...y.normalizeParams(t)})}var ht=p("ZodRecord",(r,e)=>{ns.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Zc(r,n,i,t),r.keyType=e.keyType,r.valueType=e.valueType});function Tu(r,e,n){return!e||!e._zod?new ht({type:"record",keyType:Qt(),valueType:r,...y.normalizeParams(e)}):new ht({type:"record",keyType:r,valueType:e,...y.normalizeParams(n)})}function km(r,e,n){let i=B(r);return i._zod.values=void 0,new ht({type:"record",keyType:i,valueType:e,...y.normalizeParams(n)})}function $m(r,e,n){return new ht({type:"record",keyType:r,valueType:e,mode:"loose",...y.normalizeParams(n)})}var Du=p("ZodMap",(r,e)=>{is.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Oc(r,n,i,t),r.keyType=e.keyType,r.valueType=e.valueType,r.min=(...n)=>r.check(ae(...n)),r.nonempty=n=>r.check(ae(1,n)),r.max=(...n)=>r.check(ye(...n)),r.size=(...n)=>r.check(Ue(...n))});function wm(r,e,n){return new Du({type:"map",keyType:r,valueType:e,...y.normalizeParams(n)})}var Uu=p("ZodSet",(r,e)=>{os.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Ac(r,n,i,t),r.min=(...n)=>r.check(ae(...n)),r.nonempty=n=>r.check(ae(1,n)),r.max=(...n)=>r.check(ye(...n)),r.size=(...n)=>r.check(Ue(...n))});function _m(r,e){return new Uu({type:"set",valueType:r,...y.normalizeParams(e)})}var vt=p("ZodEnum",(r,e)=>{as.init(r,e),S.init(r,e),r._zod.processJSONSchema=(i,t,o)=>Sc(r,i,t,o),r.enum=e.entries,r.options=Object.values(e.entries);let n=new Set(Object.keys(e.entries));r.extract=(i,t)=>{let o={};for(let a of i)if(n.has(a))o[a]=e.entries[a];else throw new Error(`Key ${a} not found in enum`);return new vt({...e,checks:[],...y.normalizeParams(t),entries:o})},r.exclude=(i,t)=>{let o={...e.entries};for(let a of i)if(n.has(a))delete o[a];else throw new Error(`Key ${a} not found in enum`);return new vt({...e,checks:[],...y.normalizeParams(t),entries:o})}});function wi(r,e){let n=Array.isArray(r)?Object.fromEntries(r.map(i=>[i,i])):r;return new vt({type:"enum",entries:n,...y.normalizeParams(e)})}function Sm(r,e){return new vt({type:"enum",entries:r,...y.normalizeParams(e)})}var Ru=p("ZodLiteral",(r,e)=>{ss.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Ic(r,n,i,t),r.values=new Set(e.values),Object.defineProperty(r,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function Im(r,e){return new Ru({type:"literal",values:Array.isArray(r)?r:[r],...y.normalizeParams(e)})}var Ou=p("ZodFile",(r,e)=>{cs.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Ec(r,n,i,t),r.min=(n,i)=>r.check(ae(n,i)),r.max=(n,i)=>r.check(ye(n,i)),r.mime=(n,i)=>r.check(st(Array.isArray(n)?n:[n],i))});function Pm(r){return oc(Ou,r)}var Au=p("ZodTransform",(r,e)=>{us.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Rc(r,n,i,t),r._zod.parse=(n,i)=>{if(i.direction==="backward")throw new me(r.constructor.name);n.addIssue=o=>{if(typeof o=="string")n.issues.push(y.issue(o,n.value,e));else{let a=o;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=n.value),a.inst??(a.inst=r),n.issues.push(y.issue(a))}};let t=e.transform(n.value,n);return t instanceof Promise?t.then(o=>(n.value=o,n.fallback=!0,n)):(n.value=t,n.fallback=!0,n)}});function _i(r){return new Au({type:"transform",transform:r})}var Si=p("ZodOptional",(r,e)=>{mn.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Jn(r,n,i,t),r.unwrap=()=>r._zod.def.innerType});function tr(r){return new Si({type:"optional",innerType:r})}var Cu=p("ZodExactOptional",(r,e)=>{ls.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Jn(r,n,i,t),r.unwrap=()=>r._zod.def.innerType});function ju(r){return new Cu({type:"optional",innerType:r})}var Nu=p("ZodNullable",(r,e)=>{ds.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Fc(r,n,i,t),r.unwrap=()=>r._zod.def.innerType});function rr(r){return new Nu({type:"nullable",innerType:r})}function zm(r){return tr(rr(r))}var Lu=p("ZodDefault",(r,e)=>{ps.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Bc(r,n,i,t),r.unwrap=()=>r._zod.def.innerType,r.removeDefault=r.unwrap});function Zu(r,e){return new Lu({type:"default",innerType:r,get defaultValue(){return typeof e=="function"?e():y.shallowClone(e)}})}var Fu=p("ZodPrefault",(r,e)=>{ms.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Gc(r,n,i,t),r.unwrap=()=>r._zod.def.innerType});function Mu(r,e){return new Fu({type:"prefault",innerType:r,get defaultValue(){return typeof e=="function"?e():y.shallowClone(e)}})}var Ii=p("ZodNonOptional",(r,e)=>{fs.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Mc(r,n,i,t),r.unwrap=()=>r._zod.def.innerType});function Bu(r,e){return new Ii({type:"nonoptional",innerType:r,...y.normalizeParams(e)})}var Gu=p("ZodSuccess",(r,e)=>{gs.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Tc(r,n,i,t),r.unwrap=()=>r._zod.def.innerType});function Em(r){return new Gu({type:"success",innerType:r})}var Wu=p("ZodCatch",(r,e)=>{hs.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Wc(r,n,i,t),r.unwrap=()=>r._zod.def.innerType,r.removeCatch=r.unwrap});function Vu(r,e){return new Wu({type:"catch",innerType:r,catchValue:typeof e=="function"?e:()=>e})}var Ju=p("ZodNaN",(r,e)=>{vs.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Pc(r,n,i,t)});function Tm(r){return nc(Ju,r)}var ur=p("ZodPipe",(r,e)=>{fn.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Vc(r,n,i,t),r.in=e.in,r.out=e.out});function ri(r,e){return new ur({type:"pipe",in:r,out:e})}var lr=p("ZodCodec",(r,e)=>{ur.init(r,e),Jt.init(r,e)});function Dm(r,e,n){return new lr({type:"pipe",in:r,out:e,transform:n.decode,reverseTransform:n.encode})}function Um(r){let e=r._zod.def;return new lr({type:"pipe",in:e.out,out:e.in,transform:e.reverseTransform,reverseTransform:e.transform})}var Ku=p("ZodPreprocess",(r,e)=>{ur.init(r,e),bs.init(r,e)}),qu=p("ZodReadonly",(r,e)=>{ys.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Jc(r,n,i,t),r.unwrap=()=>r._zod.def.innerType});function Hu(r){return new qu({type:"readonly",innerType:r})}var Xu=p("ZodTemplateLiteral",(r,e)=>{xs.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>zc(r,n,i,t)});function Rm(r,e){return new Xu({type:"template_literal",parts:r,...y.normalizeParams(e)})}var Yu=p("ZodLazy",(r,e)=>{ws.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>qc(r,n,i,t),r.unwrap=()=>r._zod.def.getter()});function Qu(r){return new Yu({type:"lazy",getter:r})}var el=p("ZodPromise",(r,e)=>{$s.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Kc(r,n,i,t),r.unwrap=()=>r._zod.def.innerType});function Om(r){return new el({type:"promise",innerType:r})}var tl=p("ZodFunction",(r,e)=>{ks.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Uc(r,n,i,t)});function Am(r){return new tl({type:"function",input:Array.isArray(r?.input)?Eu(r?.input):r?.input??ar(Ae()),output:r?.output??Ae()})}var dr=p("ZodCustom",(r,e)=>{_s.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Dc(r,n,i,t)});function Cm(r){let e=new U({check:"custom"});return e._zod.check=r,e}function jm(r,e){return ac(dr,r??(()=>!0),e)}function rl(r,e={}){return sc(dr,r,e)}function nl(r,e){return cc(r,e)}var Nm=uc,Lm=lc;function Zm(r,e={}){let n=new dr({type:"custom",check:"custom",fn:i=>i instanceof r,abort:!0,...y.normalizeParams(e)});return n._zod.bag.Class=r,n._zod.check=i=>{i.value instanceof r||i.issues.push({code:"invalid_type",expected:r.name,input:i.value,inst:n,path:[...n._zod.def.path??[]]})},n}var Fm=(...r)=>dc({Codec:lr,Boolean:kt,String:bt},...r);function Mm(r){let e=Qu(()=>$i([Qt(r),mu(),fu(),bu(),ar(e),Tu(Qt(),e)]));return e}function Bm(r,e){return new Ku({type:"pipe",in:_i(r),out:e})}var pv={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function mv(r){A({customError:r})}function fv(){return A().customError}var il;il||(il={});var $={...Yt,...Hn,iso:gt},gv=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function hv(r,e){let n=r.$schema;return n==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":n==="http://json-schema.org/draft-07/schema#"?"draft-7":n==="http://json-schema.org/draft-04/schema#"?"draft-4":e??"draft-2020-12"}function vv(r,e){if(!r.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let n=r.slice(1).split("/").filter(Boolean);if(n.length===0)return e.rootSchema;let i=e.version==="draft-2020-12"?"$defs":"definitions";if(n[0]===i){let t=n[1];if(!t||!e.defs[t])throw new Error(`Reference not found: ${r}`);return e.defs[t]}throw new Error(`Reference not found: ${r}`)}function Gm(r,e){if(r.not!==void 0){if(typeof r.not=="object"&&Object.keys(r.not).length===0)return $.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(r.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(r.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(r.if!==void 0||r.then!==void 0||r.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(r.dependentSchemas!==void 0||r.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(r.$ref){let t=r.$ref;if(e.refs.has(t))return e.refs.get(t);if(e.processing.has(t))return $.lazy(()=>{if(!e.refs.has(t))throw new Error(`Circular reference not resolved: ${t}`);return e.refs.get(t)});e.processing.add(t);let o=vv(t,e),a=M(o,e);return e.refs.set(t,a),e.processing.delete(t),a}if(r.enum!==void 0){let t=r.enum;if(e.version==="openapi-3.0"&&r.nullable===!0&&t.length===1&&t[0]===null)return $.null();if(t.length===0)return $.never();if(t.length===1)return $.literal(t[0]);if(t.every(a=>typeof a=="string"))return $.enum(t);let o=t.map(a=>$.literal(a));return o.length<2?o[0]:$.union([o[0],o[1],...o.slice(2)])}if(r.const!==void 0)return $.literal(r.const);let n=r.type;if(Array.isArray(n)){let t=n.map(o=>{let a={...r,type:o};return Gm(a,e)});return t.length===0?$.never():t.length===1?t[0]:$.union(t)}if(!n)return $.any();let i;switch(n){case"string":{let t=$.string();if(r.format){let o=r.format;o==="email"?t=t.check($.email()):o==="uri"||o==="uri-reference"?t=t.check($.url()):o==="uuid"||o==="guid"?t=t.check($.uuid()):o==="date-time"?t=t.check($.iso.datetime()):o==="date"?t=t.check($.iso.date()):o==="time"?t=t.check($.iso.time()):o==="duration"?t=t.check($.iso.duration()):o==="ipv4"?t=t.check($.ipv4()):o==="ipv6"?t=t.check($.ipv6()):o==="mac"?t=t.check($.mac()):o==="cidr"?t=t.check($.cidrv4()):o==="cidr-v6"?t=t.check($.cidrv6()):o==="base64"?t=t.check($.base64()):o==="base64url"?t=t.check($.base64url()):o==="e164"?t=t.check($.e164()):o==="jwt"?t=t.check($.jwt()):o==="emoji"?t=t.check($.emoji()):o==="nanoid"?t=t.check($.nanoid()):o==="cuid"?t=t.check($.cuid()):o==="cuid2"?t=t.check($.cuid2()):o==="ulid"?t=t.check($.ulid()):o==="xid"?t=t.check($.xid()):o==="ksuid"&&(t=t.check($.ksuid()))}typeof r.minLength=="number"&&(t=t.min(r.minLength)),typeof r.maxLength=="number"&&(t=t.max(r.maxLength)),r.pattern&&(t=t.regex(new RegExp(r.pattern))),i=t;break}case"number":case"integer":{let t=n==="integer"?$.number().int():$.number();typeof r.minimum=="number"&&(t=t.min(r.minimum)),typeof r.maximum=="number"&&(t=t.max(r.maximum)),typeof r.exclusiveMinimum=="number"?t=t.gt(r.exclusiveMinimum):r.exclusiveMinimum===!0&&typeof r.minimum=="number"&&(t=t.gt(r.minimum)),typeof r.exclusiveMaximum=="number"?t=t.lt(r.exclusiveMaximum):r.exclusiveMaximum===!0&&typeof r.maximum=="number"&&(t=t.lt(r.maximum)),typeof r.multipleOf=="number"&&(t=t.multipleOf(r.multipleOf)),i=t;break}case"boolean":{i=$.boolean();break}case"null":{i=$.null();break}case"object":{let t={},o=r.properties||{},a=new Set(r.required||[]);for(let[c,u]of Object.entries(o)){let d=M(u,e);t[c]=a.has(c)?d:d.optional()}if(r.propertyNames){let c=M(r.propertyNames,e),u=r.additionalProperties&&typeof r.additionalProperties=="object"?M(r.additionalProperties,e):$.any();if(Object.keys(t).length===0){i=$.record(c,u);break}let d=$.object(t).passthrough(),m=$.looseRecord(c,u);i=$.intersection(d,m);break}if(r.patternProperties){let c=r.patternProperties,u=Object.keys(c),d=[];for(let h of u){let g=M(c[h],e),k=$.string().regex(new RegExp(h));d.push($.looseRecord(k,g))}let m=[];if(Object.keys(t).length>0&&m.push($.object(t).passthrough()),m.push(...d),m.length===0)i=$.object({}).passthrough();else if(m.length===1)i=m[0];else{let h=$.intersection(m[0],m[1]);for(let g=2;g<m.length;g++)h=$.intersection(h,m[g]);i=h}break}let s=$.object(t);r.additionalProperties===!1?i=s.strict():typeof r.additionalProperties=="object"?i=s.catchall(M(r.additionalProperties,e)):i=s.passthrough();break}case"array":{let t=r.prefixItems,o=r.items;if(t&&Array.isArray(t)){let a=t.map(c=>M(c,e)),s=o&&typeof o=="object"&&!Array.isArray(o)?M(o,e):void 0;s?i=$.tuple(a).rest(s):i=$.tuple(a),typeof r.minItems=="number"&&(i=i.check($.minLength(r.minItems))),typeof r.maxItems=="number"&&(i=i.check($.maxLength(r.maxItems)))}else if(Array.isArray(o)){let a=o.map(c=>M(c,e)),s=r.additionalItems&&typeof r.additionalItems=="object"?M(r.additionalItems,e):void 0;s?i=$.tuple(a).rest(s):i=$.tuple(a),typeof r.minItems=="number"&&(i=i.check($.minLength(r.minItems))),typeof r.maxItems=="number"&&(i=i.check($.maxLength(r.maxItems)))}else if(o!==void 0){let a=M(o,e),s=$.array(a);typeof r.minItems=="number"&&(s=s.min(r.minItems)),typeof r.maxItems=="number"&&(s=s.max(r.maxItems)),i=s}else i=$.array($.any());break}default:throw new Error(`Unsupported type: ${n}`)}return i}function M(r,e){if(typeof r=="boolean")return r?$.any():$.never();let n=Gm(r,e),i=r.type||r.enum!==void 0||r.const!==void 0;if(r.anyOf&&Array.isArray(r.anyOf)){let s=r.anyOf.map(u=>M(u,e)),c=$.union(s);n=i?$.intersection(n,c):c}if(r.oneOf&&Array.isArray(r.oneOf)){let s=r.oneOf.map(u=>M(u,e)),c=$.xor(s);n=i?$.intersection(n,c):c}if(r.allOf&&Array.isArray(r.allOf))if(r.allOf.length===0)n=i?n:$.any();else{let s=i?n:M(r.allOf[0],e),c=i?0:1;for(let u=c;u<r.allOf.length;u++)s=$.intersection(s,M(r.allOf[u],e));n=s}r.nullable===!0&&e.version==="openapi-3.0"&&(n=$.nullable(n)),r.readOnly===!0&&(n=$.readonly(n)),r.default!==void 0&&(n=n.default(r.default));let t={},o=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let s of o)s in r&&(t[s]=r[s]);let a=["contentEncoding","contentMediaType","contentSchema"];for(let s of a)s in r&&(t[s]=r[s]);for(let s of Object.keys(r))gv.has(s)||(t[s]=r[s]);return Object.keys(t).length>0&&e.registry.add(n,t),r.description&&(n=n.describe(r.description)),n}function Wm(r,e){if(typeof r=="boolean")return r?$.any():$.never();let n;try{n=JSON.parse(JSON.stringify(r))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let i=hv(n,e?.defaultTarget),t=n.$defs||n.definitions||{},o={version:i,defs:t,refs:new Map,processing:new Set,rootSchema:n,registry:e?.registry??Z};return M(n,o)}var ol={};ne(ol,{bigint:()=>kv,boolean:()=>xv,date:()=>$v,number:()=>yv,string:()=>bv});function bv(r){return zs(bt,r)}function yv(r){return Cs(xt,r)}function xv(r){return Bs(kt,r)}function kv(r){return Ws($t,r)}function $v(r){return rc(or,r)}A(gn());var Pi=l.string().trim().min(1).max(100),al=l.object({funnel:l.object({title:l.string().trim().min(1).max(100),stages:l.array(l.discriminatedUnion("measure",[l.object({id:l.string().regex(/^[a-zA-Z0-9_-]+$/).max(50),label:l.string().trim().min(1).max(100),measure:l.literal("event"),event:Pi}),l.object({id:l.string().regex(/^[a-zA-Z0-9_-]+$/).max(50),label:l.string().trim().min(1).max(100),measure:l.literal("first_payment")}),l.object({id:l.string().regex(/^[a-zA-Z0-9_-]+$/).max(50),label:l.string().trim().min(1).max(100),measure:l.literal("event_after_payment"),event:Pi})])).max(12)}).nullable(),followUp:l.object({label:l.string().trim().min(1).max(100),triggerEvent:Pi,prerequisiteEvent:Pi.nullable(),stopOnPayment:l.boolean()}).nullable()}),Km=l.enum(["test","live"]),pr=l.object({id:l.string(),externalId:l.string(),email:l.string(),name:l.string().nullable(),source:l.string().nullable(),marketingSubscribed:l.boolean(),communicationBasis:l.enum(["unknown","legacy_account","explicit_opt_in","unsubscribed"]).optional(),legacyPolicy:l.string().nullable().optional(),joinedAt:l.string().nullable().optional(),importedAt:l.string().nullable().optional(),lastActiveAt:l.string().nullable().optional(),billingStatus:l.enum(["unknown","free","paid"]).optional(),suppressionReason:l.string().nullable(),activatedAt:l.string().nullable(),createdAt:l.string().nullable()}),we=l.object({id:l.string(),mode:Km,enabled:l.boolean(),senderName:l.string().nullable(),senderEmail:l.string().nullable(),replyTo:l.string().nullable(),senderVerified:l.boolean(),domainRecords:l.string().nullable(),configuration:al.optional(),emailTemplate:l.string().nullable().optional(),provisionedAt:l.string().nullable().optional(),lastRequestAt:l.string().nullable().optional(),processedAt:l.string().nullable().optional()}),Vm=l.object({enabled:l.boolean(),subject:l.string(),body:l.string(),delayMinutes:l.number(),activationEvent:l.string()}),qm=Vm.extend({kind:l.enum(["welcome","setup","purchase","credit_limit"]),version:l.number().int().optional(),startsAt:l.string().nullable().optional(),draft:Vm.nullable().optional()}),sl=l.object({id:l.string(),customerId:l.string().nullable(),recipient:l.string(),subject:l.string(),body:l.string(),status:l.string(),error:l.string().nullable(),dueAt:l.string().nullable().optional(),attemptedAt:l.string().nullable().optional(),receivedAt:l.string().nullable().optional(),journeyKind:l.enum(["welcome","setup","purchase","credit_limit"]).nullable().optional(),journeyVersion:l.number().int().nullable().optional(),category:l.enum(["marketing","service"]).optional(),from:l.string().nullable().optional(),replyTo:l.string().nullable().optional(),renderedText:l.string().nullable().optional(),renderedHtml:l.string().nullable().optional(),unsubscribeUrl:l.string().nullable().optional(),createdAt:l.string().nullable()}),wv=l.object({funnel:l.object({title:l.string(),stages:l.array(l.object({id:l.string(),label:l.string(),count:l.number()}))}).nullable().optional(),space:we.nullable(),customers:l.array(pr),journeys:l.array(qm),messages:l.array(sl),total:l.number(),messageTotal:l.number().optional(),events:l.array(l.string()).optional()}),Jm=l.object({id:l.string(),externalId:l.string(),name:l.string(),ownerCustomerId:l.string(),firstPaidAt:l.string().nullable(),activatedAt:l.string().nullable()}),mr=class{constructor(e){this.client=e}async configure(e){let n=al.parse(e);return al.parse((await this.client.put("/platform/customers/runtime/configuration",{...n,...e.emailTemplate!==void 0?{emailTemplate:e.emailTemplate}:{}})).data)}async context(){return l.object({id:l.string(),projectId:l.string(),notebookId:l.string(),mode:Km}).parse((await this.client.get("/platform/customers/runtime/context")).data)}async pendingFollowUps(){return l.array(l.object({messageId:l.string(),organizationExternalId:l.string(),actorExternalId:l.string()})).parse((await this.client.get("/platform/customers/runtime/follow-ups")).data)}async resolveFollowUp(e,n){return sl.parse((await this.client.post(`/platform/customers/runtime/follow-ups/${encodeURIComponent(e)}/resolve`,{resolution:n})).data)}async organization(e){return Jm.parse((await this.client.put("/platform/customers/runtime/organizations",e)).data)}async confirmPayment(e,n){return Jm.parse((await this.client.post(`/platform/customers/runtime/organizations/${encodeURIComponent(e)}/payments`,n)).data)}async identify(e){return pr.parse((await this.client.post("/platform/customers/runtime/identify",e)).data)}async linkIdentity(e,n){return pr.parse((await this.client.post(`/platform/customers/runtime/${encodeURIComponent(e)}/identities`,{externalId:n})).data)}async get(e){return pr.parse((await this.client.get(`/platform/customers/runtime/${encodeURIComponent(e)}`)).data)}async event(e,n){return l.object({id:l.string(),name:l.string()}).parse((await this.client.post(`/platform/customers/runtime/${encodeURIComponent(e)}/events`,n)).data)}async preferences(e,n){return pr.parse((await this.client.put(`/platform/customers/runtime/${encodeURIComponent(e)}/preferences`,n)).data)}async send(e,n){return sl.parse((await this.client.post(`/platform/customers/runtime/${encodeURIComponent(e)}/messages`,n)).data)}},zi=class{constructor(e){this.client=e;this.runtime=new mr(e)}forProject(e){return new cl(e,this.client)}},cl=class{constructor(e,n){this.projectId=e;this.client=n}async list(e="test",n={}){return wv.parse((await this.client.get(`${this.path(e)}?${new URLSearchParams(Object.entries(n).map(([i,t])=>[i,String(t)])).toString()}`)).data)}async connect(e="test"){return we.parse((await this.client.put(this.path(e),{})).data)}async provision(e="test"){return we.parse((await this.client.post(`${this.path(e)}/provision`,{})).data)}async disable(e="test"){return we.parse((await this.client.post(`${this.path(e)}/disable`,{})).data)}async resume(e="test"){return we.parse((await this.client.post(`${this.path(e)}/resume`,{})).data)}async rotate(e="test"){return we.parse((await this.client.post(`${this.path(e)}/rotate`,{})).data)}async sender(e,n="test"){return we.parse((await this.client.put(`${this.path(n)}/sender`,e)).data)}async verifySender(e="test"){return we.parse((await this.client.post(`${this.path(e)}/sender/verify`,{})).data)}async journey(e,n,i="test"){return qm.parse((await this.client.put(`${this.path(i)}/journeys/${e}`,n)).data)}path(e){return`/platform/projects/${encodeURIComponent(this.projectId)}/customers/${e}`}};var Yk="/api/phpsandbox-payments/events",Ei=l.enum(["test","live"]),ul=l.object({id:l.string(),mode:Ei,chargesEnabled:l.boolean(),payoutsEnabled:l.boolean(),detailsSubmitted:l.boolean(),requirements:l.array(l.string()),disabledReason:l.string().nullable()}),_v=l.object({subscribed:l.boolean(),liveAllowed:l.boolean(),testConfigured:l.boolean(),liveConfigured:l.boolean(),feeBasisPoints:l.number().int().min(0).max(1e4).nullable(),canRead:l.boolean(),canManage:l.boolean(),canRefund:l.boolean(),recoveryEndsAt:l.string().nullable().default(null)}),Sv=l.object({notebookId:l.string(),applications:l.array(l.object({id:l.string(),url:l.string().nullable(),healthy:l.boolean(),passwordProtected:l.boolean(),deployedAt:l.string().datetime().nullable()}))}),wt=l.object({target:l.enum(["preview","publication"]).optional(),id:l.string(),projectId:l.string(),applicationId:l.string().nullable(),mode:Ei,revision:l.number().int(),accountId:l.string(),enabled:l.boolean(),callbackUrl:l.string().nullable(),originUrl:l.string().nullable(),runtimeConfigured:l.boolean()}),Ti=l.object({billingInterval:l.enum(["month","year"]).nullable().default(null),id:l.string(),name:l.string(),amount:l.number().int(),currency:l.string(),bindingId:l.string()}),_t=l.object({subscriptionId:l.string().nullable().default(null),periodStart:l.string().datetime({offset:!0}).nullable().default(null),periodEnd:l.string().datetime({offset:!0}).nullable().default(null),id:l.string(),bindingId:l.string(),orderId:l.string(),priceId:l.string(),amount:l.number().int(),currency:l.string(),feeAmount:l.number().int(),revision:l.number().int(),refundedAmount:l.number().int(),status:l.enum(["pending","paid","failed","refunded","partially_refunded"]),checkoutUrl:l.string().nullable(),deliveredAt:l.string().nullable()}),_e=l.object({id:l.string(),bindingId:l.string(),priceId:l.string(),orderId:l.string(),status:l.enum(["pending","incomplete","incomplete_expired","trialing","active","past_due","canceled","unpaid","paused"]),billingInterval:l.enum(["month","year"]),paidThrough:l.string().datetime({offset:!0}).nullable(),cancelAtPeriodEnd:l.boolean(),checkoutUrl:l.string().nullable(),revision:l.number().int()}),Hm=l.object({url:l.string().url()}),Iv=_t.extend({refund:l.object({id:l.string(),amount:l.number().int().positive(),status:l.enum(["pending","succeeded","failed","canceled","requires_action"])})}),Pv=l.object({revision:l.number().int(),reviewId:l.string(),expiresAt:l.string(),blockers:l.array(l.string()),binding:wt,account:ul,feeBasisPoints:l.number().int().nullable(),prices:l.array(Ti)}),Di=class{constructor(e){this.client=e;this.runtime=new fr(e)}forProject(e){return new ll(e,this.client)}async applications(e){return Sv.parse((await this.client.get(`/platform/payments/projects/${encodeURIComponent(e)}/applications`)).data)}async access(){return _v.parse((await this.client.get("/platform/payments/access")).data)}async accounts(){return l.array(ul).parse((await this.client.get("/platform/payments/accounts")).data)}async createAccount(e,n){return ul.parse((await this.client.put(`/platform/payments/accounts/${e}`,{country:n})).data)}async onboarding(e){return l.object({url:l.string().url(),expiresAt:l.string()}).parse((await this.client.post(`/platform/payments/accounts/${e}/onboarding`,{})).data)}},ll=class{constructor(e,n){this.projectId=e;this.client=n}path(e){return`/platform/payments/projects/${encodeURIComponent(this.projectId)}/${e}`}async get(e="test"){return wt.nullable().parse((await this.client.get(this.path(e))).data)}async configure(e,n="test"){return wt.parse((await this.client.put(this.path(n),e)).data)}async provision(e="test"){return wt.parse((await this.client.post(`${this.path(e)}/provision`,{})).data)}async prices(e="test"){return l.array(Ti).parse((await this.client.get(`${this.path(e)}/prices`)).data)}async createPrice(e,n="test"){return Ti.parse((await this.client.post(`${this.path(n)}/prices`,e)).data)}async prepareActivation(e="test"){return Pv.parse((await this.client.post(`${this.path(e)}/activation`,{})).data)}async activate(e,n="test"){return wt.parse((await this.client.post(`${this.path(n)}/activate`,{reviewId:e})).data)}async disable(e="test"){return wt.parse((await this.client.post(`${this.path(e)}/disable`,{})).data)}async checkout(e,n="test"){return _t.parse((await this.client.post(`${this.path(n)}/checkouts`,e)).data)}async subscribe(e,n="test"){return _e.parse((await this.client.post(`${this.path(n)}/subscriptions`,e)).data)}async subscriptions(e="test"){return l.array(_e).parse((await this.client.get(`${this.path(e)}/subscriptions`)).data)}async subscription(e,n="test"){return _e.parse((await this.client.get(`${this.path(n)}/subscriptions/${encodeURIComponent(e)}`)).data)}async cancelSubscription(e,n="test"){return _e.parse((await this.client.post(`${this.path(n)}/subscriptions/${encodeURIComponent(e)}/cancel`,{})).data)}async subscriptionPortal(e,n,i="test"){return Hm.parse((await this.client.post(`${this.path(i)}/subscriptions/${encodeURIComponent(e)}/portal`,n)).data)}async transactions(e="test"){return l.array(_t).parse((await this.client.get(`${this.path(e)}/transactions`)).data)}async refund(e,n,i="test"){return Iv.parse((await this.client.post(`${this.path(i)}/transactions/${encodeURIComponent(e)}/refund`,n)).data)}},zv=l.discriminatedUnion("type",[l.object({id:l.string(),type:l.literal("payment.updated"),mode:Ei,transaction:_t}),l.object({id:l.string(),type:l.literal("subscription.updated"),mode:Ei,subscription:_e})]);async function Ev(r,e,n,i,t=Date.now()){if(!/^(?:hpay|happ)_[a-f0-9]{64}$/.test(n))throw new Error("Invalid application payment credential.");let o=/^t=(\d+),v1=([a-f0-9]{64})$/.exec(e),a=o?.[1],s=o?.[2];if(!a||!s||Math.abs(t-Number(a)*1e3)>3e5||r.length>262144)throw new Error("Invalid or expired payment signature.");let c=new TextEncoder,u=await crypto.subtle.importKey("raw",c.encode(n),{name:"HMAC",hash:"SHA-256"},!1,["verify"]),d=Uint8Array.from(s.match(/../g)??[],h=>Number.parseInt(h,16));if(!await crypto.subtle.verify("HMAC",u,d,c.encode(`${a}.${r}`)))throw new Error("Invalid payment signature.");let m=zv.parse(JSON.parse(r));if(m.mode!==i)throw new Error("Payment event mode does not match this application.");return m}var fr=class{constructor(e,n){this.client=e;this.appCredential=n}async verifyEvent(e,n){if(!this.appCredential)throw new Error("Initialize the server app client with PHPSandbox.app() to verify payment events.");return Ev(e,n,this.appCredential.token,this.appCredential.mode)}async checkout(e){return _t.parse((await this.client.post("/platform/payments/runtime/checkouts",e)).data)}async transaction(e){return _t.parse((await this.client.get(`/platform/payments/runtime/transactions/${encodeURIComponent(e)}`)).data)}async subscribe(e){return _e.parse((await this.client.post("/platform/payments/runtime/subscriptions",e)).data)}async subscription(e){return _e.parse((await this.client.get(`/platform/payments/runtime/subscriptions/${encodeURIComponent(e)}`)).data)}async cancelSubscription(e){return _e.parse((await this.client.post(`/platform/payments/runtime/subscriptions/${encodeURIComponent(e)}/cancel`,{})).data)}async subscriptionPortal(e,n){return Hm.parse((await this.client.post(`/platform/payments/runtime/subscriptions/${encodeURIComponent(e)}/portal`,n)).data)}async prices(){return l.array(Ti).parse((await this.client.get("/platform/payments/runtime/prices")).data)}};function Xm(r){if(typeof window<"u"&&typeof document<"u")throw new Error("Application credentials must only be used on a trusted server.");let e=r.env??(typeof process>"u"?{}:process.env),n=r.mode??(e.NODE_ENV==="production"?"live":"test"),i=e[`PHPSANDBOX_APP_${n.toUpperCase()}_TOKEN`],t=e.PHPSANDBOX_APP_API_URL;if(!i||!/^happ_[a-f0-9]{64}$/.test(i)||!t)throw new Error(`Connect your app's ${n==="live"?"production":"development"} platform environment before using Customers or Payments.`);return{mode:n,token:i,url:t}}var Ui=class{constructor(e,n,i){this.mode=i;this.customers=new mr(e),this.payments=new fr(e,{token:n,mode:i})}};var Ym=l.object({user:l.object({id:l.string(),name:l.string()}).nullable(),organization:l.object({id:l.string(),name:l.string()}),permissions:l.array(l.string())});var Tv=["ActionNotFound","AuthenticationRequired","BadGateway","BadRequest","Conflict","FileAlreadyExists","FileIsDirectory","FileNotDirectory","FileNotFound","FilesystemUnavailable","InternalError","InvalidArgument","InvalidConfiguration","InvalidRequest","InvalidResponse","InvalidServiceCommand","MethodNotAllowed","NotebookInitializationFailed","NotebookUnavailable","NotFound","PayloadTooLarge","PermissionDenied","RateLimited","RequestFailed","RuntimeOperationFailed","ServiceNotFound","ServiceUnavailable","UnprocessableEntity","ValidationFailed","WorkspaceUnavailable"],E=class extends Error{constructor(e,n){super(e),this.name=new.target.name,this.cause=n}},C=class r extends E{constructor(e,n){super(e,n.cause),this.source=n.source,this.status=n.status,this.code=n.code,this.details=n.details}static is(e,n){return e instanceof r&&(n===void 0||e.code===n)}static isValidation(e){return r.is(e,"ValidationFailed")&&Ov(e.details)!==void 0}is(e){return this.code===e}},R=class r extends E{constructor(n,i,t,o){super(n,t);this.code=i;this.response=o}static is(n,i){return n instanceof r&&(i===void 0||n.code===i)}is(n){return this.code===n}};function je(r,e,n){let i=dl(e),t=Uv(i?.status),o=Qm(i?.code),a=Qm(i?.message);if(t===void 0||!Dv(o)||a===void 0)throw new R("PHPSandbox returned an invalid error response.","InvalidResponse",n??e);return new C(a,{source:r,status:t,code:o,details:i?.details,cause:n})}function Dv(r){return typeof r=="string"&&Tv.includes(r)}function Uv(r){return typeof r=="number"&&Number.isInteger(r)&&r>0?r:void 0}function Qm(r){return typeof r=="string"&&r.trim()!==""?r.trim():void 0}function dl(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)?r:void 0}function Rv(r){let e=dl(r);if(e===void 0)return;let n=Object.entries(e);if(n.every(([,i])=>Array.isArray(i)&&i.every(t=>typeof t=="string")))return Object.fromEntries(n)}function Ov(r){let e=dl(r),n=Rv(e?.errors);return n===void 0?void 0:{errors:n}}var St=class extends Error{constructor(n,i){super(n);this.time=i}},gr=class r extends R{constructor(n,i,t){super(n,"SendTimeout",t);this.time=i}static fromPromiseTimeoutError(n){return new r(n.message,n.time,n)}};var ef="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var j=(r=21)=>{let e="",n=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=ef[n[r]&63];return e};var tf=(t=>(t[t.Unknown=0]="Unknown",t[t.File=1]="File",t[t.Directory=2]="Directory",t[t.SymbolicLink=64]="SymbolicLink",t))(tf||{}),rf=(i=>(i[i.UPDATED=2]="UPDATED",i[i.ADDED=4]="ADDED",i[i.DELETED=8]="DELETED",i))(rf||{}),nf=(i=>(i[i.UPDATED=1]="UPDATED",i[i.ADDED=2]="ADDED",i[i.DELETED=3]="DELETED",i))(nf||{}),pl=class{constructor(e,n){this.disposable=e;this.onDispose=n;this.disposed=!1}dispose(){this.disposed||(this.disposed=!0,this.disposable.dispose(),this.onDispose())}},Ri=class{constructor(e,n=i=>e.onDidConnect(i)){this.okra=e;this.watches=new Map;this.registerReconnectHandler(n)}registerReconnectHandler(e){e!==null&&e(()=>{for(let{path:n,options:i}of this.watches.values())this.okra.invoke("fs.watch",{path:n,options:i}).catch(()=>{})})}async write(e,n,i={}){let t={overwrite:!0,create:!0,unlock:!1,atomic:!1,...i},o=typeof n=="string"?new TextEncoder().encode(n):n;if(this.okra.runtimeTransport==="rest"){let c=o instanceof Uint8Array?o:await Cv(o);await this.okra.invoke("fs.writeFile",{path:e,contents:c,options:t}).catch(u=>this.handleError(u));return}let a=j(),s=this.okra.invoke("fs.writeStream",{id:a,path:e,options:t});s.catch(()=>{});try{for await(let u of Av(o))if(!await this.okra.invoke("fs.writeChunk",{id:a,contents:u}))throw new Error(`File write stream ${a} is not available`);if(!await this.okra.invoke("fs.endWrite",{id:a}))throw new Error(`File write stream ${a} could not be completed`);await s}catch(c){throw await this.okra.invoke("fs.abortWrite",{id:a}).catch(()=>!1),await s.catch(()=>!1),c}}async read(e){try{let n=await this.okra.invoke("fs.readFile",{path:e});return n instanceof Uint8Array?n:new TextEncoder().encode(n)}catch(n){this.handleError(n)}}async readText(e){return new TextDecoder().decode(await this.read(e))}async readLines(e,n){try{let i=await this.okra.invoke("fs.readFile",{path:e,lineRange:{lineStart:n.start,lineEnd:n.end}});if(typeof i=="string"||i instanceof Uint8Array)throw new Error(`Unexpected ranged file response for ${e}`);return{start:i.lineStart,end:i.lineEnd,content:i.content,...i.error===null?{}:{warning:i.error}}}catch(i){this.handleError(i)}}readStream(e){if(this.okra.runtimeTransport==="rest")return new ReadableStream({start:async o=>{try{o.enqueue(await this.read(e)),o.close()}catch(a){o.error(a)}}});let n=j(),i=null,t=!1;return new ReadableStream({start:o=>{i=this.okra.listen(`fs.read.${n}`,a=>{o.enqueue(a.data)}),this.okra.invoke("fs.readStream",{id:n,path:e}).then(()=>{t||(t=!0,i?.dispose(),o.close())}).catch(a=>{t||(t=!0,i?.dispose(),o.error(a))})},cancel:async()=>{t||(t=!0,i?.dispose(),await this.okra.invoke("fs.cancelRead",{id:n}).catch(()=>!1))}})}follow(e,n={}){if(this.okra.runtimeTransport==="rest")return new ReadableStream({start(u){u.error(new E("Following files requires the realtime transport."))}});let i=j(),t=null,o=null,a=!1,s=!1,c=async()=>{s||(s=!0,t?.dispose(),t=null,o&&n.signal&&n.signal.removeEventListener("abort",o),o=null,a&&await this.okra.invoke("fs.cancelFollow",{id:i}).catch(()=>!1))};return new ReadableStream({start:u=>{if(t=this.okra.listen(`fs.follow.${i}`,d=>{s||u.enqueue(d.data)}),n.signal){if(o=()=>{c().finally(()=>u.error(n.signal?.reason??new Error("Aborted")))},n.signal.aborted){o();return}n.signal.addEventListener("abort",o,{once:!0})}a=!0,this.okra.invoke("fs.follow",{id:i,path:e,lines:n.lines??10}).then(()=>{s||(s=!0,t?.dispose(),o&&n.signal&&n.signal.removeEventListener("abort",o),o=null,u.close())}).catch(d=>{s||(s=!0,t?.dispose(),o&&n.signal&&n.signal.removeEventListener("abort",o),o=null,u.error(d))})},cancel:c})}find(e,n={useIgnoreFiles:!1,followSymlinks:!1,useGlobalIgnoreFiles:!1,useParentIgnoreFiles:!1}){return this.okra.invoke("fs.find",{query:e,options:{includes:[],excludes:["**/storage","**/vendor","**/node_modules","**/.git","**/.svn","**/.hg","**/CVS","**/.DS_Store","**/Thumbs.db","**/*.crswap"],useIgnoreFiles:!1,followSymlinks:!1,useGlobalIgnoreFiles:!1,useParentIgnoreFiles:!1,...n}})}search(e,n,i){e.id||(e.id=j());let t={maxResults:5,afterContext:2,beforeContext:2,includes:[],excludes:["**/.git","**/.svn","**/.hg","**/CVS","**/.DS_Store","**/Thumbs.db","**/*.crswap","**/node_modules","**/vendor","**/bower_components","**/*.code-search"],useIgnoreFiles:!0,followSymlinks:!0,useGlobalIgnoreFiles:!0,useParentIgnoreFiles:!0,encoding:"utf-8",previewOptions:{matchLines:5,charsPerLine:1e3}},o=e.id,a=async c=>{c===!1&&s.dispose(),i&&await Promise.resolve(i(c))===!1&&s.dispose()},s=this.okra.listen(`fs.text.search.${o}`,a);return this.okra.invoke("fs.textSearch",{query:e,options:{...t,...n}}).finally(()=>s.dispose())}tail(e,n={}){return this.okra.invoke("fs.tail",{path:e,lines:n.lines??10}).then(({content:i})=>i).catch(i=>this.handleError(i))}stat(e){return this.okra.invoke("fs.stat",{path:e}).catch(n=>this.handleError(n))}move(e,n,i={}){return this.okra.invoke("fs.rename",{from:e,to:n,options:{overwrite:!1,...i}}).catch(t=>this.handleError(t))}remove(e,n={}){return this.okra.invoke("fs.delete",{path:e,options:{recursive:!1,useTrash:!1,atomic:!1,...n}}).catch(i=>this.handleError(i))}copy(e,n,i={}){return this.okra.invoke("fs.copy",{source:e,destination:n,options:{overwrite:!1,...i}}).catch(t=>this.handleError(t))}list(e,n={}){return this.okra.invoke("fs.readDirectory",{path:e,include:n.include??[],exclude:n.exclude??[]}).catch(i=>this.handleError(i))}createDirectory(e){return this.okra.invoke("fs.createDirectory",{path:e}).catch(n=>this.handleError(n))}watch(e,n,i){let t=this.okra.listen(`fs.watch.${e}`,i),o={dispose:()=>{t.dispose(),this.okra.invoke("fs.unwatch",{path:e}).catch(()=>{})}},a=new pl(o,()=>{this.watches.get(e)?.onDidChange===i&&this.watches.delete(e)});return this.watches.set(e,{options:n,path:e,onDidChange:i}),this.okra.invoke("fs.watch",{path:e,options:n}).then(()=>a).catch(s=>{throw a.dispose(),s})}exists(e){return this.stat(e).then(()=>!0).catch(()=>!1)}download(e={}){return this.okra.stream("fs.download",{include:e.include,exclude:e.exclude},{abortSignal:e.signal})}tree(e="/"){return this.okra.invoke("fs.tree",{path:e})}handleError(e){throw e}};async function*Av(r){if(r instanceof Uint8Array){yield r;return}yield*r}async function Cv(r){let e=[],n=0;for await(let o of r)e.push(o),n+=o.byteLength;let i=new Uint8Array(n),t=0;for(let o of e)i.set(o,t),t+=o.byteLength;return i}var of=(r,e)=>{let n;return Promise.race([r,new Promise((i,t)=>n=setTimeout(t,e,new St("Timeout before promise can resolve",e)))]).finally(()=>clearTimeout(n))},Oi=r=>{let e=null;return()=>e||(e=r())};var jv=8,Nv=/[\x00-\x1f\x7f]/,hr=class{constructor(e){this.okra=e}list(){return this.okra.invoke("terminal.list")}async create(e={}){let n=e.id??j(),i=this.processHandle(n,e.abortSignal),t=typeof e.command=="string"&&e.args?.length?[e.command,...e.args]:e.command,{abortSignal:o,args:a,...s}=e;try{let c=await this.okra.invoke("terminal.create",{...s,id:n,kind:e.kind??"bash",size:e.size??[80,24],command:t},{abortSignal:o});return{...i.process,...c}}catch(c){throw i.dispose(),c}}async attach(e,n){let i=this.processHandle(e,n?.abortSignal);try{let t=await this.okra.invoke("terminal.attach",{id:e,replayHistory:n?.replayHistory},{abortSignal:n?.abortSignal});return t?{...i.process,...t}:(i.dispose(),!1)}catch(t){throw i.dispose(),t}}processHandle(e,n){let i=new Set,t,o=()=>{t&&(n?.removeEventListener("abort",t),t=void 0);for(let F of i)F.dispose();i.clear()},a="",s,c=()=>{if(s&&(clearTimeout(s),s=void 0),a==="")return;let F=a;a="",this.okra.send("terminal.input",{id:e,input:F})},u=()=>{s||(s=setTimeout(c,jv))},d=F=>{let N=typeof F=="string"?F:new TextDecoder().decode(F);if(a+=N,Nv.test(N)){c();return}u()},m=()=>{c(),o()},h=new WritableStream({write:d,close:m,abort:m}),g=null,k=new ReadableStream({start:F=>{g=F,i.add(this.okra.listen(`terminal.output.${e}`,N=>{g?.enqueue(N.output)}))},cancel:()=>{g=null,m()}}),w=new Promise(F=>{i.add(this.okra.listen(`terminal.close.${e}`,N=>{if(g)try{g.close()}catch{}m(),F(N.exitCode)}))}),P=Oi(()=>(m(),this.okra.invoke("terminal.close",{id:e}))),Tt=F=>this.okra.invoke("terminal.resize",{id:e,width:F.cols,height:F.rows});return n&&!n.aborted&&(t=()=>{P()},n.addEventListener("abort",t,{once:!0})),{process:{wait:()=>w,input:h,output:k,kill:P,resize:Tt},dispose:m}}};var vr=class{constructor(e){this.okra=e}message(e,n){return this.okra.invoke("lsp.message",{id:e,message:n})}listen(e,n,i){return this.okra.listen(`${n}.${e}`,t=>i(t))}onClose(e,n){return this.listen(e,"lsp.closed",i=>n(i.code,i.reason))}onError(e,n){return this.listen(e,"lsp.error",i=>n(i.message))}onClientDisconnect(e){return this.okra.onDidDisconnect(()=>e(1e3,"OKRA DISCONNECTED"))}onResponse(e,n){return this.listen(e,"lsp.response",i=>n(JSON.stringify(i)))}close(e){return this.okra.invoke("lsp.close",{id:e})}start(e){return this.okra.invoke("lsp.start",{id:e})}connection(e){return Ai.create(e,this)}whenSocketConnected(){return this.okra.connected()}},Ai=class r{constructor(e,n){this.id=e;this.lsp=n}send(e){return this.lsp.message(this.id,e)}onMessage(e){return this.lsp.onResponse(this.id,e)}onError(e){return this.lsp.onError(this.id,e)}onClose(e){return this.lsp.onClose(this.id,e)}dispose(){return this.lsp.close(this.id)}start(){return this.lsp.start(this.id)}onClientDisconnect(e){return this.lsp.onClientDisconnect(e)}whenSocketConnected(){return this.lsp.whenSocketConnected()}static create(e,n){return new r(e,n)}};function Lv(r,e=[],n){let i=Array.isArray(e)?e:[],t=Array.isArray(e)?n:e;return{command:Array.isArray(r)?r:i.length>0?[r,...i]:r,opts:{tty:!1,...t}}}var de=class{constructor(){this.controller=null;this.closed=!1;this.stream=new ReadableStream({start:e=>{this.controller=e},cancel:()=>{this.closed=!0,this.controller=null}})}enqueue(e){this.closed||this.controller?.enqueue(e)}close(){this.closed||(this.closed=!0,this.controller?.close(),this.controller=null)}fail(e){this.closed||(this.closed=!0,this.controller?.error(e),this.controller=null)}},ml=class{constructor(e,n,i,t){this.id=e;this.okra=n;let o=new de,a=new de,s=new de;this.output=o.stream,this.stdout=a.stream,this.stderr=s.stream,this.stdin=new WritableStream({write:async k=>{let w=typeof k=="string"?k:new TextDecoder().decode(k);if(!await this.okra.invoke("shell.input",{id:this.id,input:w}))throw new Error(`Process ${this.id} is not accepting input`)}});let c=new TextEncoder,u=this.okra.listen(`shell.output.${this.id}`,k=>{let w=c.encode(k.output),P=k.source??"output";o.enqueue({source:P,data:w}),P==="stderr"?s.enqueue(w):a.enqueue(w)}),d=()=>{u?.dispose(),u=null,o.close(),a.close(),s.close()},m=k=>{u?.dispose(),u=null,o.fail(k),a.fail(k),s.fail(k)},{abortSignal:h,...g}=t;this.completion=this.okra.invoke("shell.exec",{command:i,opts:{...g,id:this.id}},{abortSignal:h}).then(k=>(d(),k)).catch(k=>{throw m(k),k})}wait(){return this.completion}async kill(){await this.okra.invoke("shell.kill",{id:this.id})}},br=class{constructor(e){this.okra=e}run(e,n=[],i){let t=Lv(e,n,i),o=t.opts?.id??j();return new ml(o,this.okra,t.command,{...t.opts,id:o})}};var fl=class{constructor(e,n){this.client=e;this.notebookId=n}async set(e){return(await this.client.put(`/notebook/${this.notebookId}/composer/credentials`,e)).data}async remove(e,n){let i=new URLSearchParams({type:e});n&&i.set("url",n),await this.client.delete(`/notebook/${this.notebookId}/composer/credentials?${i.toString()}`)}},gl=class{constructor(e,n,i,t,o){this.id=e;this.okra=n;let a=new de,s=new de,c=new de;this.output=a.stream,this.stdout=s.stream,this.stderr=c.stream;let u=new TextEncoder,d=this.okra.listen(`composer.output.${this.id}`,g=>{let k=u.encode(g.output),w=g.source??"output";a.enqueue({source:w,data:k}),w==="stderr"?c.enqueue(k):s.enqueue(k)}),m=()=>{d?.dispose(),d=null,a.close(),s.close(),c.close()},h=g=>{d?.dispose(),d=null,a.fail(g),s.fail(g),c.fail(g)};this.completion=this.okra.invoke("composer.invoke",{id:e,command:i,args:t,options:o}).then(g=>(m(),g)).catch(g=>{throw h(g),g})}wait(){return this.completion}async kill(){await this.okra.invoke("composer.kill",{id:this.id})}},yr=class{constructor(e,n){this.okra=e;this.credentials=new fl(n,e.data.id)}run(e,n={},i={}){return new gl(j(),this.okra,e,n,i)}packages(){return this.okra.invoke("composer.packages")}};var Ci=class{constructor(e){this.okra=e;this.references=new Map;this.synchronization=Promise.resolve();e.runtimeTransport==="realtime"&&e.onDidConnect(()=>{this.references.size>0&&this.synchronize()})}async acquire(e){this.references.set(e,(this.references.get(e)??0)+1);try{await this.synchronize()}catch(i){throw this.removeReference(e),i}let n=!1;return async()=>{n||(n=!0,this.removeReference(e),await this.synchronize())}}removeReference(e){let n=this.references.get(e)??0;n<=1?this.references.delete(e):this.references.set(e,n-1)}synchronize(){return this.synchronization=this.synchronization.catch(()=>{}).then(async()=>{let e=Array.from(this.references.keys());e.length===0?await this.okra.invoke("container.stop-telemetry"):await this.okra.invoke("container.stream-telemetry",{features:e})}),this.synchronization}};function It(r,e,n,i,t,o={}){let a=null,s=null,c=!1,u=null,d=async()=>{c||(c=!0,a?.dispose(),a=null,u&&o.signal&&o.signal.removeEventListener("abort",u),u=null,await s?.(),s=null)};return new ReadableStream({start(m){if(a=r.listen(i,h=>{c||m.enqueue(t(h))}),o.signal){if(u=()=>{d().finally(()=>m.error(o.signal?.reason??new Error("Aborted")))},o.signal.aborted){u();return}o.signal.addEventListener("abort",u,{once:!0})}e.acquire(n).then(async h=>{if(c){await h();return}s=h}).catch(h=>{c||(c=!0,a?.dispose(),u&&o.signal&&o.signal.removeEventListener("abort",u),u=null,m.error(h))})},cancel:d})}var xr=class{constructor(e,n){this.okra=e;this.telemetry=n}follow(e={}){return It(this.okra,this.telemetry,"logs","notebook.log",n=>({timestamp:new Date().toISOString(),source:"runtime",message:n}),e)}};var kr=class{constructor(e,n){this.okra=e;this.telemetry=n}current(){return this.okra.invoke("container.stats")}watch(e={}){return It(this.okra,this.telemetry,"stats","container.stats",n=>n,e)}};var $r=class{constructor(e,n){this.okra=e;this.telemetry=n}list(){return this.okra.invoke("container.opened-ports")}resolve(e){return this.okra.invoke("container.resolve-port",{port:e})}watch(e={}){return It(this.okra,this.telemetry,"ports","container.ports",n=>n,e)}};var hl=class{constructor(e){this.metrics=e}current(){return this.metrics.current()}watch(e={}){return this.metrics.watch(e)}},vl=class{constructor(e){this.logs=e}follow(e={}){return this.logs.follow(e)}},bl=class{constructor(e){this.ports=e}list(){return this.ports.list()}resolve(e){return this.ports.resolve(e)}watch(e={}){return this.ports.watch(e)}},wr=class{constructor(e){this.notebook=e;let n=new Ci(e);this.metrics=new hl(new kr(e,n)),this.logs=new vl(new xr(e,n)),this.ports=new bl(new $r(e,n))}setPhpVersion(e){return this.notebook.invoke("container.set-php",{version:e})}};var _r=class{constructor(e){this.okra=e}eval(e,n="",i={prependWith:"",appendWith:""}){return this.okra.invoke("repl.eval",{code:e,args:n,repl:i})}write(e){return this.okra.invoke("repl.write",{input:e})}stop(){return this.okra.invoke("repl.stop")}resize(e,n){return this.okra.invoke("repl.resize",{cols:e,rows:n})}listen(e,n){return this.okra.listen(e,n)}onOutput(e){return this.okra.listen("repl.output",e)}};var af=["redis"],Zv=["start","nginx",...af],Sr=class{constructor(e){this.okra=e}list(){return this.okra.invoke("service.list")}run(e,n){return this.okra.invoke("service.run",{name:e,command:n})}stop(e){return this.okra.invoke("service.stop",{name:e})}logs(e,n={}){return n.follow?this.followLogs(e,n):this.okra.invoke("service.logs",{name:e,tail:n.tail}).then(i=>{if(!("output"in i))throw new Error(`Unexpected service.logs response for ${e}`);return i.output})}followLogs(e,n){let i=n.id||j(),t=new Set,o=null,a=!1,s=()=>{for(let m of t)m.dispose();t.clear()},c=()=>{if(!a&&(a=!0,s(),o))try{o.close()}catch{}},u=m=>{a||(a=!0,s(),o&&o.error(m))},d=Oi(()=>(c(),this.okra.invoke("service.stop-logs",{id:i})));return new ReadableStream({start:m=>{o=m,t.add(this.okra.listen(`service.log.${i}`,h=>{o?.enqueue(h.output)})),this.okra.invoke("service.logs",{name:e,tail:n.tail,follow:!0,id:i}).catch(h=>{u(h)})},cancel:()=>d().then(()=>{})})}};var Ir=class{constructor(e){this.okra=e}get(){return this.okra.invoke("config.get")}update(e){return this.okra.invoke("config.update",{config:e})}setPorts(e){return this.okra.invoke("config.set-ports",{ports:e})}};function sf(r){let e=r.length,n=0,i=0;for(;i<e;){let t=r.charCodeAt(i++);if((t&4294967168)===0){n++;continue}else if((t&4294965248)===0)n+=2;else{if(t>=55296&&t<=56319&&i<e){let o=r.charCodeAt(i);(o&64512)===56320&&(++i,t=((t&1023)<<10)+(o&1023)+65536)}(t&4294901760)===0?n+=3:n+=4}}return n}function Fv(r,e,n){let i=r.length,t=n,o=0;for(;o<i;){let a=r.charCodeAt(o++);if((a&4294967168)===0){e[t++]=a;continue}else if((a&4294965248)===0)e[t++]=a>>6&31|192;else{if(a>=55296&&a<=56319&&o<i){let s=r.charCodeAt(o);(s&64512)===56320&&(++o,a=((a&1023)<<10)+(s&1023)+65536)}(a&4294901760)===0?(e[t++]=a>>12&15|224,e[t++]=a>>6&63|128):(e[t++]=a>>18&7|240,e[t++]=a>>12&63|128,e[t++]=a>>6&63|128)}e[t++]=a&63|128}}var Mv=new TextEncoder,Bv=50;function Gv(r,e,n){Mv.encodeInto(r,e.subarray(n))}function cf(r,e,n){r.length>Bv?Gv(r,e,n):Fv(r,e,n)}var Wv=4096;function yl(r,e,n){let i=e,t=i+n,o=[],a="";for(;i<t;){let s=r[i++];if((s&128)===0)o.push(s);else if((s&224)===192){let c=r[i++]&63;o.push((s&31)<<6|c)}else if((s&240)===224){let c=r[i++]&63,u=r[i++]&63;o.push((s&31)<<12|c<<6|u)}else if((s&248)===240){let c=r[i++]&63,u=r[i++]&63,d=r[i++]&63,m=(s&7)<<18|c<<12|u<<6|d;m>65535&&(m-=65536,o.push(m>>>10&1023|55296),m=56320|m&1023),o.push(m)}else o.push(s);o.length>=Wv&&(a+=String.fromCharCode(...o),o.length=0)}return o.length>0&&(a+=String.fromCharCode(...o)),a}var Vv=new TextDecoder,Jv=200;function Kv(r,e,n){let i=r.subarray(e,e+n);return Vv.decode(i)}function uf(r,e,n){return n>Jv?Kv(r,e,n):yl(r,e,n)}var Ne=class{constructor(e,n){this.type=e,this.data=n}};var H=class r extends Error{constructor(e){super(e);let n=Object.create(r.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:r.name})}};function lf(r,e,n){let i=n/4294967296,t=n;r.setUint32(e,i),r.setUint32(e+4,t)}function ji(r,e,n){let i=Math.floor(n/4294967296),t=n;r.setUint32(e,i),r.setUint32(e+4,t)}function Ni(r,e){let n=r.getInt32(e),i=r.getUint32(e+4);return n*4294967296+i}function df(r,e){let n=r.getUint32(e),i=r.getUint32(e+4);return n*4294967296+i}var qv=-1,Hv=4294967296-1,Xv=17179869184-1;function Yv({sec:r,nsec:e}){if(r>=0&&e>=0&&r<=Xv)if(e===0&&r<=Hv){let n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,r),n}else{let n=r/4294967296,i=r&4294967295,t=new Uint8Array(8),o=new DataView(t.buffer);return o.setUint32(0,e<<2|n&3),o.setUint32(4,i),t}else{let n=new Uint8Array(12),i=new DataView(n.buffer);return i.setUint32(0,e),ji(i,4,r),n}}function Qv(r){let e=r.getTime(),n=Math.floor(e/1e3),i=(e-n*1e3)*1e6,t=Math.floor(i/1e9);return{sec:n+t,nsec:i-t*1e9}}function eb(r){if(r instanceof Date){let e=Qv(r);return Yv(e)}else return null}function tb(r){let e=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(r.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{let n=e.getUint32(0),i=e.getUint32(4),t=(n&3)*4294967296+i,o=n>>>2;return{sec:t,nsec:o}}case 12:{let n=Ni(e,4),i=e.getUint32(0);return{sec:n,nsec:i}}default:throw new H(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${r.length}`)}}function rb(r){let e=tb(r);return new Date(e.sec*1e3+e.nsec/1e6)}var pf={type:qv,encode:eb,decode:rb};var Se=class{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(pf)}register({type:e,encode:n,decode:i}){if(e>=0)this.encoders[e]=n,this.decoders[e]=i;else{let t=-1-e;this.builtInEncoders[t]=n,this.builtInDecoders[t]=i}}tryToEncode(e,n){for(let i=0;i<this.builtInEncoders.length;i++){let t=this.builtInEncoders[i];if(t!=null){let o=t(e,n);if(o!=null){let a=-1-i;return new Ne(a,o)}}}for(let i=0;i<this.encoders.length;i++){let t=this.encoders[i];if(t!=null){let o=t(e,n);if(o!=null){let a=i;return new Ne(a,o)}}}return e instanceof Ne?e:null}decode(e,n,i){let t=n<0?this.builtInDecoders[-1-n]:this.decoders[n];return t?t(e,n,i):new Ne(n,e)}};Se.defaultCodec=new Se;function nb(r){return r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer}function Pr(r){return r instanceof Uint8Array?r:ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):nb(r)?new Uint8Array(r):Uint8Array.from(r)}var ib=100,ob=2048,Li=class r{constructor(e){this.entered=!1,this.extensionCodec=e?.extensionCodec??Se.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??ib,this.initialBufferSize=e?.initialBufferSize??ob,this.sortKeys=e?.sortKeys??!1,this.forceFloat32=e?.forceFloat32??!1,this.ignoreUndefined=e?.ignoreUndefined??!1,this.forceIntegerToFloat=e?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new r({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,n){if(n>this.maxDepth)throw new Error(`Too deep objects in depth ${n}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,n)}ensureBufferSizeToWrite(e){let n=this.pos+e;this.view.byteLength<n&&this.resizeBuffer(n*2)}resizeBuffer(e){let n=new ArrayBuffer(e),i=new Uint8Array(n),t=new DataView(n);i.set(this.bytes),this.view=t,this.bytes=i}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){let i=sf(e);this.ensureBufferSizeToWrite(5+i),this.writeStringHeader(i),cf(e,this.bytes,this.pos),this.pos+=i}encodeObject(e,n){let i=this.extensionCodec.tryToEncode(e,this.context);if(i!=null)this.encodeExtension(i);else if(Array.isArray(e))this.encodeArray(e,n);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,n);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){let n=e.byteLength;if(n<256)this.writeU8(196),this.writeU8(n);else if(n<65536)this.writeU8(197),this.writeU16(n);else if(n<4294967296)this.writeU8(198),this.writeU32(n);else throw new Error(`Too large binary: ${n}`);let i=Pr(e);this.writeU8a(i)}encodeArray(e,n){let i=e.length;if(i<16)this.writeU8(144+i);else if(i<65536)this.writeU8(220),this.writeU16(i);else if(i<4294967296)this.writeU8(221),this.writeU32(i);else throw new Error(`Too large array: ${i}`);for(let t of e)this.doEncode(t,n+1)}countWithoutUndefined(e,n){let i=0;for(let t of n)e[t]!==void 0&&i++;return i}encodeMap(e,n){let i=Object.keys(e);this.sortKeys&&i.sort();let t=this.ignoreUndefined?this.countWithoutUndefined(e,i):i.length;if(t<16)this.writeU8(128+t);else if(t<65536)this.writeU8(222),this.writeU16(t);else if(t<4294967296)this.writeU8(223),this.writeU32(t);else throw new Error(`Too large map object: ${t}`);for(let o of i){let a=e[o];this.ignoreUndefined&&a===void 0||(this.encodeString(o),this.doEncode(a,n+1))}}encodeExtension(e){if(typeof e.data=="function"){let i=e.data(this.pos+6),t=i.length;if(t>=4294967296)throw new Error(`Too large extension object: ${t}`);this.writeU8(201),this.writeU32(t),this.writeI8(e.type),this.writeU8a(i);return}let n=e.data.length;if(n===1)this.writeU8(212);else if(n===2)this.writeU8(213);else if(n===4)this.writeU8(214);else if(n===8)this.writeU8(215);else if(n===16)this.writeU8(216);else if(n<256)this.writeU8(199),this.writeU8(n);else if(n<65536)this.writeU8(200),this.writeU16(n);else if(n<4294967296)this.writeU8(201),this.writeU32(n);else throw new Error(`Too large extension object: ${n}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){let n=e.length;this.ensureBufferSizeToWrite(n),this.bytes.set(e,this.pos),this.pos+=n}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),lf(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),ji(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}};function xl(r,e){return new Li(e).encodeSharedRef(r)}function Zi(r){return`${r<0?"-":""}0x${Math.abs(r).toString(16).padStart(2,"0")}`}var ab=16,sb=16,Fi=class{constructor(e=ab,n=sb){this.hit=0,this.miss=0,this.maxKeyLength=e,this.maxLengthPerKey=n,this.caches=[];for(let i=0;i<this.maxKeyLength;i++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,n,i){let t=this.caches[i-1];e:for(let o of t){let a=o.bytes;for(let s=0;s<i;s++)if(a[s]!==e[n+s])continue e;return o.str}return null}store(e,n){let i=this.caches[e.length-1],t={bytes:e,str:n};i.length>=this.maxLengthPerKey?i[Math.random()*i.length|0]=t:i.push(t)}decode(e,n,i){let t=this.find(e,n,i);if(t!=null)return this.hit++,t;this.miss++;let o=yl(e,n,i),a=Uint8Array.prototype.slice.call(e,n,n+i);return this.store(a,o),o}};var kl="array",Tr="map_key",ff="map_value",cb=r=>{if(typeof r=="string"||typeof r=="number")return r;throw new H("The type of key must be string or number but "+typeof r)},$l=class{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){let n=this.getUninitializedStateFromPool();n.type=kl,n.position=0,n.size=e,n.array=new Array(e)}pushMapState(e){let n=this.getUninitializedStateFromPool();n.type=Tr,n.readCount=0,n.size=e,n.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===kl){let i=e;i.size=0,i.array=void 0,i.position=0,i.type=void 0}if(e.type===Tr||e.type===ff){let i=e;i.size=0,i.map=void 0,i.readCount=0,i.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},Er=-1,wl=new DataView(new ArrayBuffer(0)),ub=new Uint8Array(wl.buffer);try{wl.getInt8(0)}catch(r){if(!(r instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var mf=new RangeError("Insufficient data"),lb=new Fi,Mi=class r{constructor(e){this.totalPos=0,this.pos=0,this.view=wl,this.bytes=ub,this.headByte=Er,this.stack=new $l,this.entered=!1,this.extensionCodec=e?.extensionCodec??Se.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??4294967295,this.maxBinLength=e?.maxBinLength??4294967295,this.maxArrayLength=e?.maxArrayLength??4294967295,this.maxMapLength=e?.maxMapLength??4294967295,this.maxExtLength=e?.maxExtLength??4294967295,this.keyDecoder=e?.keyDecoder!==void 0?e.keyDecoder:lb,this.mapKeyConverter=e?.mapKeyConverter??cb}clone(){return new r({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=Er,this.stack.reset()}setBuffer(e){let n=Pr(e);this.bytes=n,this.view=new DataView(n.buffer,n.byteOffset,n.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===Er&&!this.hasRemaining(1))this.setBuffer(e);else{let n=this.bytes.subarray(this.pos),i=Pr(e),t=new Uint8Array(n.length+i.length);t.set(n),t.set(i,n.length),this.setBuffer(t)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){let{view:n,pos:i}=this;return new RangeError(`Extra ${n.byteLength-i} of ${n.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);let n=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return n}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let n=!1,i;for await(let s of e){if(n)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(s);try{i=this.doDecodeSync(),n=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(n){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return i}let{headByte:t,pos:o,totalPos:a}=this;throw new RangeError(`Insufficient data in parsing ${Zi(t)} at ${a} (${o} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,n){if(this.entered){yield*this.clone().decodeMultiAsync(e,n);return}try{this.entered=!0;let i=n,t=-1;for await(let o of e){if(n&&t===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(o),i&&(t=this.readArraySize(),i=!1,this.complete());try{for(;yield this.doDecodeSync(),--t!==0;);}catch(a){if(!(a instanceof RangeError))throw a}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){let e=this.readHeadByte(),n;if(e>=224)n=e-256;else if(e<192)if(e<128)n=e;else if(e<144){let t=e-128;if(t!==0){this.pushMapState(t),this.complete();continue e}else n={}}else if(e<160){let t=e-144;if(t!==0){this.pushArrayState(t),this.complete();continue e}else n=[]}else{let t=e-160;n=this.decodeString(t,0)}else if(e===192)n=null;else if(e===194)n=!1;else if(e===195)n=!0;else if(e===202)n=this.readF32();else if(e===203)n=this.readF64();else if(e===204)n=this.readU8();else if(e===205)n=this.readU16();else if(e===206)n=this.readU32();else if(e===207)this.useBigInt64?n=this.readU64AsBigInt():n=this.readU64();else if(e===208)n=this.readI8();else if(e===209)n=this.readI16();else if(e===210)n=this.readI32();else if(e===211)this.useBigInt64?n=this.readI64AsBigInt():n=this.readI64();else if(e===217){let t=this.lookU8();n=this.decodeString(t,1)}else if(e===218){let t=this.lookU16();n=this.decodeString(t,2)}else if(e===219){let t=this.lookU32();n=this.decodeString(t,4)}else if(e===220){let t=this.readU16();if(t!==0){this.pushArrayState(t),this.complete();continue e}else n=[]}else if(e===221){let t=this.readU32();if(t!==0){this.pushArrayState(t),this.complete();continue e}else n=[]}else if(e===222){let t=this.readU16();if(t!==0){this.pushMapState(t),this.complete();continue e}else n={}}else if(e===223){let t=this.readU32();if(t!==0){this.pushMapState(t),this.complete();continue e}else n={}}else if(e===196){let t=this.lookU8();n=this.decodeBinary(t,1)}else if(e===197){let t=this.lookU16();n=this.decodeBinary(t,2)}else if(e===198){let t=this.lookU32();n=this.decodeBinary(t,4)}else if(e===212)n=this.decodeExtension(1,0);else if(e===213)n=this.decodeExtension(2,0);else if(e===214)n=this.decodeExtension(4,0);else if(e===215)n=this.decodeExtension(8,0);else if(e===216)n=this.decodeExtension(16,0);else if(e===199){let t=this.lookU8();n=this.decodeExtension(t,1)}else if(e===200){let t=this.lookU16();n=this.decodeExtension(t,2)}else if(e===201){let t=this.lookU32();n=this.decodeExtension(t,4)}else throw new H(`Unrecognized type byte: ${Zi(e)}`);this.complete();let i=this.stack;for(;i.length>0;){let t=i.top();if(t.type===kl)if(t.array[t.position]=n,t.position++,t.position===t.size)n=t.array,i.release(t);else continue e;else if(t.type===Tr){if(n==="__proto__")throw new H("The key __proto__ is not allowed");t.key=this.mapKeyConverter(n),t.type=ff;continue e}else if(t.map[t.key]=n,t.readCount++,t.readCount===t.size)n=t.map,i.release(t);else{t.key=null,t.type=Tr;continue e}}return n}}readHeadByte(){return this.headByte===Er&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=Er}readArraySize(){let e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new H(`Unrecognized array type byte: ${Zi(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new H(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new H(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,n){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,n):this.decodeBinary(e,n)}decodeUtf8String(e,n){if(e>this.maxStrLength)throw new H(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+n+e)throw mf;let i=this.pos+n,t;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?t=this.keyDecoder.decode(this.bytes,i,e):t=uf(this.bytes,i,e),this.pos+=n+e,t}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===Tr:!1}decodeBinary(e,n){if(e>this.maxBinLength)throw new H(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+n))throw mf;let i=this.pos+n,t=this.bytes.subarray(i,i+e);return this.pos+=n+e,t}decodeExtension(e,n){if(e>this.maxExtLength)throw new H(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);let i=this.view.getInt8(this.pos+n),t=this.decodeBinary(e,n+1);return this.extensionCodec.decode(t,i,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){let e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){let e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){let e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){let e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){let e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){let e=df(this.view,this.pos);return this.pos+=8,e}readI64(){let e=Ni(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){let e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){let e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){let e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){let e=this.view.getFloat64(this.pos);return this.pos+=8,e}};function _l(r,e){return new Mi(e).decode(r)}var Bi=class{constructor(e){this.error=e}},db=r=>new Promise(e=>{setTimeout(e,r)}),pb=(r,e)=>{let n=e.randomize?Math.random()+1:1,i=Math.max(e.minTimeout,1)*Math.pow(e.factor,r-1);return Math.round(Math.min(n*i,e.maxTimeout))};async function gf(r,e={}){let n={retries:e.retries??10,minTimeout:e.minTimeout??1e3,maxTimeout:e.maxTimeout??1/0,factor:e.factor??2,randomize:e.randomize??!0},i=o=>{throw new Bi(o??new Error("Aborted"))},t;for(let o=1;o<=n.retries+1;o++)try{return await r(i,o)}catch(a){if(a instanceof Bi)throw a.error;if(t=a,o>n.retries)throw a;await e.onRetry?.(a,o),await db(pb(o,n))}throw t}var Pl={};ne(Pl,{default:()=>Il});var Sl=function(r,e){return Sl=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var t in i)i.hasOwnProperty(t)&&(n[t]=i[t])},Sl(r,e)};function hf(r,e){Sl(r,e);function n(){this.constructor=r}r.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}function mb(r){var e=typeof Symbol=="function"&&r[Symbol.iterator],n=0;return e?e.call(r):{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}}}function fb(r,e){var n=typeof Symbol=="function"&&r[Symbol.iterator];if(!n)return r;var i=n.call(r),t,o=[],a;try{for(;(e===void 0||e-- >0)&&!(t=i.next()).done;)o.push(t.value)}catch(s){a={error:s}}finally{try{t&&!t.done&&(n=i.return)&&n.call(i)}finally{if(a)throw a.error}}return o}function gb(){for(var r=[],e=0;e<arguments.length;e++)r=r.concat(fb(arguments[e]));return r}var vf=(function(){function r(e,n){this.target=n,this.type=e}return r})(),hb=(function(r){hf(e,r);function e(n,i){var t=r.call(this,"error",i)||this;return t.message=n.message,t.error=n,t}return e})(vf),vb=(function(r){hf(e,r);function e(n,i,t){n===void 0&&(n=1e3),i===void 0&&(i="");var o=r.call(this,"close",t)||this;return o.wasClean=!0,o.code=n,o.reason=i,o}return e})(vf);var bb=function(){if(typeof WebSocket<"u")return WebSocket},yb=function(r){return typeof r<"u"&&!!r&&r.CLOSING===2},Le={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0,startClosed:!1,debug:!1},xb=(function(){function r(e,n,i){var t=this;i===void 0&&(i={}),this._listeners={error:[],message:[],open:[],close:[]},this._retryCount=-1,this._shouldReconnect=!0,this._connectLock=!1,this._binaryType="blob",this._closeCalled=!1,this._messageQueue=[],this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this._handleOpen=function(o){t._debug("open event");var a=t._options.minUptime,s=a===void 0?Le.minUptime:a;clearTimeout(t._connectTimeout),t._uptimeTimeout=setTimeout(function(){return t._acceptOpen()},s),t._ws.binaryType=t._binaryType,t._messageQueue.forEach(function(c){return t._ws.send(c)}),t._messageQueue=[],t.onopen&&t.onopen(o),t._listeners.open.forEach(function(c){return t._callEventListener(o,c)})},this._handleMessage=function(o){t._debug("message event"),t.onmessage&&t.onmessage(o),t._listeners.message.forEach(function(a){return t._callEventListener(o,a)})},this._handleError=function(o){t._debug("error event",o.message),t._disconnect(void 0,o.message==="TIMEOUT"?"timeout":void 0),t.onerror&&t.onerror(o),t._debug("exec error listeners"),t._listeners.error.forEach(function(a){return t._callEventListener(o,a)}),t._connect()},this._handleClose=function(o){t._debug("close event"),t._clearTimeouts(),t._shouldReconnect&&t._connect(),t.onclose&&t.onclose(o),t._listeners.close.forEach(function(a){return t._callEventListener(o,a)})},this._url=e,this._protocols=n,this._options=i,this._options.startClosed&&(this._shouldReconnect=!1),this._connect()}return Object.defineProperty(r,"CONNECTING",{get:function(){return 0},enumerable:!0,configurable:!0}),Object.defineProperty(r,"OPEN",{get:function(){return 1},enumerable:!0,configurable:!0}),Object.defineProperty(r,"CLOSING",{get:function(){return 2},enumerable:!0,configurable:!0}),Object.defineProperty(r,"CLOSED",{get:function(){return 3},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"CONNECTING",{get:function(){return r.CONNECTING},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"OPEN",{get:function(){return r.OPEN},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"CLOSING",{get:function(){return r.CLOSING},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"CLOSED",{get:function(){return r.CLOSED},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"binaryType",{get:function(){return this._ws?this._ws.binaryType:this._binaryType},set:function(e){this._binaryType=e,this._ws&&(this._ws.binaryType=e)},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"retryCount",{get:function(){return Math.max(this._retryCount,0)},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"bufferedAmount",{get:function(){var e=this._messageQueue.reduce(function(n,i){return typeof i=="string"?n+=i.length:i instanceof Blob?n+=i.size:n+=i.byteLength,n},0);return e+(this._ws?this._ws.bufferedAmount:0)},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"extensions",{get:function(){return this._ws?this._ws.extensions:""},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"protocol",{get:function(){return this._ws?this._ws.protocol:""},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"readyState",{get:function(){return this._ws?this._ws.readyState:this._options.startClosed?r.CLOSED:r.CONNECTING},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"url",{get:function(){return this._ws?this._ws.url:""},enumerable:!0,configurable:!0}),r.prototype.close=function(e,n){if(e===void 0&&(e=1e3),this._closeCalled=!0,this._shouldReconnect=!1,this._clearTimeouts(),!this._ws){this._debug("close enqueued: no ws instance");return}if(this._ws.readyState===this.CLOSED){this._debug("close: already closed");return}this._ws.close(e,n)},r.prototype.reconnect=function(e,n){this._shouldReconnect=!0,this._closeCalled=!1,this._retryCount=-1,!this._ws||this._ws.readyState===this.CLOSED?this._connect():(this._disconnect(e,n),this._connect())},r.prototype.send=function(e){if(this._ws&&this._ws.readyState===this.OPEN)this._debug("send",e),this._ws.send(e);else{var n=this._options.maxEnqueuedMessages,i=n===void 0?Le.maxEnqueuedMessages:n;this._messageQueue.length<i&&(this._debug("enqueue",e),this._messageQueue.push(e))}},r.prototype.addEventListener=function(e,n){this._listeners[e]&&this._listeners[e].push(n)},r.prototype.dispatchEvent=function(e){var n,i,t=this._listeners[e.type];if(t)try{for(var o=mb(t),a=o.next();!a.done;a=o.next()){var s=a.value;this._callEventListener(e,s)}}catch(c){n={error:c}}finally{try{a&&!a.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}return!0},r.prototype.removeEventListener=function(e,n){this._listeners[e]&&(this._listeners[e]=this._listeners[e].filter(function(i){return i!==n}))},r.prototype._debug=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];this._options.debug&&console.log.apply(console,gb(["RWS>"],e))},r.prototype._getNextDelay=function(){var e=this._options,n=e.reconnectionDelayGrowFactor,i=n===void 0?Le.reconnectionDelayGrowFactor:n,t=e.minReconnectionDelay,o=t===void 0?Le.minReconnectionDelay:t,a=e.maxReconnectionDelay,s=a===void 0?Le.maxReconnectionDelay:a,c=0;return this._retryCount>0&&(c=o*Math.pow(i,this._retryCount-1),c>s&&(c=s)),this._debug("next delay",c),c},r.prototype._wait=function(){var e=this;return new Promise(function(n){setTimeout(n,e._getNextDelay())})},r.prototype._getNextUrl=function(e){if(typeof e=="string")return Promise.resolve(e);if(typeof e=="function"){var n=e();if(typeof n=="string")return Promise.resolve(n);if(n.then)return n}throw Error("Invalid URL")},r.prototype._connect=function(){var e=this;if(!(this._connectLock||!this._shouldReconnect)){this._connectLock=!0;var n=this._options,i=n.maxRetries,t=i===void 0?Le.maxRetries:i,o=n.connectionTimeout,a=o===void 0?Le.connectionTimeout:o,s=n.WebSocket,c=s===void 0?bb():s;if(this._retryCount>=t){this._debug("max retries reached",this._retryCount,">=",t);return}if(this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),!yb(c))throw Error("No valid WebSocket class provided");this._wait().then(function(){return e._getNextUrl(e._url)}).then(function(u){e._closeCalled||(e._debug("connect",{url:u,protocols:e._protocols}),e._ws=e._protocols?new c(u,e._protocols):new c(u),e._ws.binaryType=e._binaryType,e._connectLock=!1,e._addListeners(),e._connectTimeout=setTimeout(function(){return e._handleTimeout()},a))})}},r.prototype._handleTimeout=function(){this._debug("timeout event"),this._handleError(new hb(Error("TIMEOUT"),this))},r.prototype._disconnect=function(e,n){if(e===void 0&&(e=1e3),this._clearTimeouts(),!!this._ws){this._removeListeners();try{this._ws.close(e,n),this._handleClose(new vb(e,n,this))}catch{}}},r.prototype._acceptOpen=function(){this._debug("accept open"),this._retryCount=0},r.prototype._callEventListener=function(e,n){"handleEvent"in n?n.handleEvent(e):n(e)},r.prototype._removeListeners=function(){this._ws&&(this._debug("removeListeners"),this._ws.removeEventListener("open",this._handleOpen),this._ws.removeEventListener("close",this._handleClose),this._ws.removeEventListener("message",this._handleMessage),this._ws.removeEventListener("error",this._handleError))},r.prototype._addListeners=function(){this._ws&&(this._debug("addListeners"),this._ws.addEventListener("open",this._handleOpen),this._ws.addEventListener("close",this._handleClose),this._ws.addEventListener("message",this._handleMessage),this._ws.addEventListener("error",this._handleError))},r.prototype._clearTimeouts=function(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)},r})(),Il=xb;var kb=r=>{if(typeof r=="number")return{0:"CONNECTING",1:"OPEN",2:"CLOSING",3:"CLOSED"}[r]??`STATE_${r}`},$b=r=>{try{let e=new URL(r);return`${e.origin}${e.pathname}`}catch{return r}},bf=r=>{if(r instanceof Error)return r.message?`${r.name}: ${r.message}`:r.name;if(typeof r=="string")return r;if(!r||typeof r!="object")return;let e=r,n=typeof e.message=="string"&&e.message?e.message:typeof e.reason=="string"&&e.reason?e.reason:void 0;if(!n)return;let i=typeof e.name=="string"&&e.name?e.name:void 0;return i?`${i}: ${n}`:n},Gi=r=>{if(r instanceof Error)return r.message?`${r.name}: ${r.message}`:r.name;if(typeof r=="string")return r;if(!r||typeof r!="object")return String(r);let e=r,n=[],i=bf(e);i&&n.push(i);let t=bf(e.error);t&&t!==i&&n.push(`error=${t}`),typeof e.type=="string"&&e.type&&n.push(`type=${e.type}`),typeof e.code=="number"&&n.push(`code=${e.code}`),typeof e.reason=="string"&&e.reason&&e.reason!==i&&n.push(`reason=${e.reason}`),typeof e.wasClean=="boolean"&&n.push(`wasClean=${e.wasClean}`);let o=e.target??e.currentTarget;if(o&&typeof o=="object"){typeof o.url=="string"&&o.url&&n.push(`url=${$b(o.url)}`);let a=kb(o.readyState);a&&n.push(`readyState=${a}`)}return n.length>0?n.join(" | "):"Unknown websocket event"};var Pt=null;typeof WebSocket<"u"?Pt=WebSocket:typeof MozWebSocket<"u"?Pt=MozWebSocket:typeof global<"u"?Pt=global.WebSocket||global.MozWebSocket:typeof window<"u"?Pt=window.WebSocket||window.MozWebSocket:typeof self<"u"&&(Pt=self.WebSocket||self.MozWebSocket);var yf=Pt;var Wi=class{constructor(){this.disposables=new Map}add(e,n){this.disposables.has(e)&&(console.warn(`Disposable with key "${e}" already exists. Disposing the old one.`),this.disposables.get(e)?.dispose()),typeof n=="function"&&(n=n()),this.disposables.set(e,n)}dispose(){this.disposables.forEach(e=>e.dispose()),this.disposables.clear()}};var wb=new Set(["url","action","event","responseEvent","errorEvent","hasData","code","attempt","maxRetries","timeout","errorCount","byteLength"]),_b=Il??Pl;var zl=class extends R{constructor(e="WebSocket connection timeout"){super(e,"ConnectionTimeout")}},zt=class extends R{constructor(n,i){super(n,"ConnectionFailed",i);this.originalError=i}},Ze=class extends R{constructor(n,i){super(n,"InvalidResponse",i);this.data=i}},Fe=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}},Ie,El,Tl,Vi=class{constructor(e,n,i={}){this.eventEmitter=n;this.options=i;Dt(this,Ie);this.clientId="";this.closed=!1;this.disposables=new Wi;this.connectPromise=null;this.terminalError=null;this.pingIntervalStarted=!1;this.incomingMessageChain=Promise.resolve();this.validateConfiguration(i),this.url=typeof e=="string"?new URL(e):null;let t=typeof e=="string"?new URL(e).toString():async()=>new URL(await e()).toString();this.PING_INTERVAL=i.pingInterval??3e4,this.CONNECT_WAIT_TIMEOUT=i.connectWaitTimeout??3e4,this.rws=new _b(t,[],{WebSocket:i.webSocket??globalThis.WebSocket??yf,connectionTimeout:i.connectionTimeout,maxReconnectionDelay:2e3,minReconnectionDelay:200,maxEnqueuedMessages:0,maxRetries:i.maxRetries??50,startClosed:!0}),this.log("debug","Transport initialized",{url:this.url===null?"dynamic":Ib(this.url),options:i}),this.registerWatchers()}validateConfiguration(e){if(e.pingInterval!==void 0&&(e.pingInterval<1e3||e.pingInterval>3e5))throw new Fe("pingInterval must be between 1000ms and 300000ms");if(e.connectionTimeout!==void 0&&(e.connectionTimeout<100||e.connectionTimeout>3e4))throw new Fe("connectionTimeout must be between 100ms and 30000ms");if(e.connectWaitTimeout!==void 0&&(e.connectWaitTimeout<1e3||e.connectWaitTimeout>3e5))throw new Fe("connectWaitTimeout must be between 1000ms and 300000ms");if(e.maxRetries!==void 0&&(e.maxRetries<0||e.maxRetries>100))throw new Fe("maxRetries must be between 0 and 100")}log(e,n,i){if(this.options.debug){let t=new Date().toISOString(),o=Sb(i),a=o?`
66
66
  ${JSON.stringify(o,null,2)}`:"";console[e](`[Transport ${t}] ${n}${a}`)}}connect(){return this.terminalError?Promise.reject(this.terminalError):pe(this,Ie,El).call(this)}id(){return this.clientId}registerWatchers(){let e=n=>{this.incomingMessageChain=this.incomingMessageChain.catch(()=>{}).then(()=>this.processIncomingMessage(n)).catch(i=>{this.log("error","Failed to process queued WebSocket frame",{error:i instanceof Error?i.message:String(i)}),this.eventEmitter.emit("transport.error",{type:"message_handle_error",error:i,rawMessage:n.data,timestamp:Date.now()})})};this.rws.addEventListener("message",e),this.disposables.add("message",{dispose:()=>{this.rws.removeEventListener("message",e)}})}async processIncomingMessage(e){let n;try{n=await this.toArrayBuffer(e.data)}catch(t){this.log("error","Unexpected WebSocket message type",{error:t instanceof Error?t.message:String(t),messageType:typeof e.data}),this.eventEmitter.emit("transport.error",{type:"message_type_error",error:t,rawMessage:e.data,timestamp:Date.now()});return}if(n.byteLength===0){this.log("warn","Ignoring empty WebSocket frame");return}let i;try{i=_l(n)}catch(t){this.log("error","Failed to decode WebSocket frame",{error:t instanceof Error?t.message:String(t),byteLength:n.byteLength}),this.eventEmitter.emit("transport.error",{type:"message_decode_error",error:t,rawMessage:n,timestamp:Date.now()});return}try{await this.handleRawMessage(i)}catch(t){this.log("error","Failed to process WebSocket frame",{error:t instanceof Error?t.message:String(t),byteLength:n.byteLength}),this.eventEmitter.emit("transport.error",{type:"message_handle_error",error:t,rawMessage:n,timestamp:Date.now()})}}async toArrayBuffer(e){if(e instanceof Blob)return e.arrayBuffer();if(e instanceof ArrayBuffer)return e;if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength).slice().buffer;throw new Error("Unexpected message type: "+typeof e)}async handleRawMessage(e){if(this.closed){this.log("debug","Ignoring message received after transport was closed");return}if(typeof e!="object"||e===null){this.log("debug","Received invalid message format",{ev:e});return}try{let{data:n,event:i,as:t}=e;if(!i||typeof i!="string")throw new Ze("Message missing event field",e);if(this.log("debug","Processing message",{event:i,hasData:!!n}),i==="App.Actions.GetClientId"){this.clientId=n.id,this.log("info","Client ID received",{clientId:this.clientId});return}if(i==="Events.BootError"){let o=n,a=new C(o?.message||"Notebook is no longer available",{source:"runtime",status:503,code:"NotebookUnavailable",details:o||{}});this.log("error","Boot error received",{data:n}),this.terminate(a,4e3,a.message);return}if(i==="response"){let{responseEvent:o,data:a}=n;if(!o)throw new Ze("Response message missing responseEvent",e);this.log("debug","Response message received",{responseEvent:o}),await this.handleMessage(o,a);return}if(i==="error"){let{errorEvent:o,data:a}=n;if(!o)throw new Ze("Error message missing errorEvent",e);this.log("debug","Error message received",{errorEvent:o,errorData:a}),await this.handleMessage(o,a);return}await this.handleMessage(i,n,t)}catch(n){n instanceof Ze?this.log("error","Invalid message format",{error:n.message,data:n.data}):this.log("error","Failed to parse message",{ev:e,error:n instanceof Error?n.message:String(n)}),this.eventEmitter.emit("transport.error",{type:"message_parse_error",error:n,rawMessage:e,timestamp:Date.now()})}}async handleMessage(e,n,i){if(e==="App.Actions.GetClientId"){this.clientId=n.id,this.eventEmitter.emit(e,this.clientId);return}e&&this.eventEmitter.emit(i||e,n)}listen(e,n,i){return this.eventEmitter.listen(e,n)}onDidBootError(e){return this.eventEmitter.listen("transport.boot_error",n=>{n&&typeof n=="object"&&"error"in n&&C.is(n.error,"NotebookUnavailable")&&e(n.error)})}removeListener(e,n){this.eventEmitter.removeListener(e,n)}listenOnce(e,n,i){return this.eventEmitter.once(e,n,i)}emit(e,...n){this.eventEmitter.emit(e,n.length>1?n:n[0])}get isConnected(){return this.status==="OPEN"}get isConnecting(){return this.status==="CONNECTING"}get isDisconnected(){return this.status==="CLOSED"}get isClosed(){return this.closed}getTerminalError(){return this.terminalError}get status(){return{0:"CONNECTING",1:"OPEN",2:"CLOSING",3:"CLOSED"}[this.rws.readyState]}async call(e,n={},i={}){if(this.terminalError)throw this.terminalError;let t=i.responseEvent||`${e}_${j()}_response`,o=`${t}_error`,a,s,c=()=>{a&&(this.rws.removeEventListener("close",a),this.rws.removeEventListener("error",a)),s&&(i.abortSignal?.removeEventListener("abort",s),s=void 0),this.eventEmitter.removeListener(t),this.eventEmitter.removeListener(o)},u=(h,g)=>{if(this.terminalError){g(this.terminalError);return}let k=new DOMException("Request aborted","AbortError");if(i.abortSignal?.aborted){g(k);return}if(i.abortSignal&&(s=()=>{g(k)},i.abortSignal.addEventListener("abort",s,{once:!0})),!this.isConnected||this.isClosed){g(new zt(`Connection is not open while sending ${e}. Current status: ${this.status}`));return}this.listenOnce(t,w=>{this.log("debug","Message response received",{action:e}),h(w)}),this.listenOnce(o,w=>{this.log("error","Message error received",{action:e,error:w}),g(je("runtime",w))}),a=w=>{if(w.code===1008&&(w.reason||"").includes("rate limit")){g(new C(w.reason||"Rate limit exceeded",{source:"runtime",status:429,code:"RateLimited",cause:w}));return}let P=Gi(w);g(this.terminalError||new zt(`Connection lost to the notebook during request: ${P}`,w))},this.rws.addEventListener("close",a),this.rws.addEventListener("error",a);try{this.rws.send(this.pack({action:e,data:n,errorEvent:o,responseEvent:t})),this.log("debug","Message sent",{action:e,data:n})}catch(w){this.log("error","Failed to send message",{action:e,error:w}),g(new zt(`Failed to send runtime action ${e}.`,w))}},d=async()=>{if(i.abortSignal?.aborted)throw new DOMException("Request aborted","AbortError");if(await pe(this,Ie,El).call(this),i.abortSignal?.aborted)throw new DOMException("Request aborted","AbortError");let h=new Promise(u).finally(c);return i.timeout?of(h,i.timeout).catch(g=>{throw g instanceof St?gr.fromPromiseTimeoutError(g):g}).finally(c):h},m=i.retries===!1?0:i.retries??0;return this.sendWithRetry(async()=>await d(),m)}send(e,n={}){if(this.terminalError)throw this.terminalError;if(!this.isConnected||this.isClosed)return this.log("debug","Connection not available, dropping one-way message",{action:e}),!1;try{return this.rws.send(this.pack({action:e,data:n})),this.log("debug","One-way message sent",{action:e,data:n}),!0}catch(i){return this.log("error","Failed to send one-way message",{action:e,error:i}),!1}}pack(e){return new Blob([xl(e)])}sendWithRetry(e,n){return gf(async(i,t)=>{try{return await e()}catch(o){if(o instanceof C||o instanceof Fe||o instanceof Ze||o instanceof DOMException){this.log("debug","Non-retryable error, bailing",{error:o.message,attempt:t}),i(o);return}throw o instanceof gr&&(this.reconnect(),this.log("warn","Send operation timed out, connection reset",{attempt:t,timeout:o.time})),this.log("debug","Retrying send operation",{attempt:t,error:o instanceof Error?o.message:String(o)}),o}},{retries:n,onRetry:(i,t)=>{this.log("warn","Send operation retry",{attempt:t,maxRetries:n,error:i instanceof Error?i.message:String(i)})},minTimeout:1e3,factor:2,maxTimeout:3e4,randomize:!0})}invoke(e,n={},i={}){return i.responseEvent||(i.responseEvent=`${e}_${j()}`),this.call("invoke",{action:e,data:n},i)}reconnect(){if(this.terminalError)throw this.terminalError;if(this.closed)throw new Error("Cannot reconnect a closed transport. The transport has been permanently closed.");this.log("info","Reconnecting transport"),this.connectPromise=null,this.rws.reconnect()}disconnect(){this.closed||this.close()}terminate(e,n=4e3,i=e.message){this.terminalError=e,C.is(e,"NotebookUnavailable")&&this.eventEmitter.emit("transport.boot_error",{error:e,timestamp:Date.now()}),this.close(n,i)}close(e,n){if(!this.closed){this.log("info","Closing transport connection",{code:e,reason:n}),this.connectPromise=null,this.disposables.dispose();try{this.rws.close(e,n)}catch(i){this.log("error","Error closing WebSocket",{error:i instanceof Error?i.message:String(i)})}this.eventEmitter.emit("transport.closed",{code:e,reason:n,timestamp:Date.now()}),this.eventEmitter.removeListener("*"),this.closed=!0,this.log("info","Transport connection closed successfully")}}onDidConnect(e){this.rws.addEventListener("open",e);let n={dispose:()=>{this.rws.removeEventListener("open",e)}};return this.disposables.add(`connect_${j()}`,n),n}onDidClose(e){this.rws.addEventListener("close",e);let n={dispose:()=>{this.rws.removeEventListener("close",e)}};return this.disposables.add(`close_${j()}`,n),n}};Ie=new WeakSet,El=function(){return this.terminalError?Promise.reject(this.terminalError):this.isConnected?Promise.resolve():this.connectPromise?this.connectPromise:(this.connectPromise=new Promise((e,n)=>{if(this.isConnected){e(),pe(this,Ie,Tl).call(this);return}let i,t=0,o=()=>{this.rws.removeEventListener("open",a),this.rws.removeEventListener("error",s),this.rws.removeEventListener("close",c),clearTimeout(i)},a=()=>{o(),this.connectPromise=null,e(),pe(this,Ie,Tl).call(this)},s=u=>{t+=1,this.log("warn","WebSocket emitted an error while connecting; waiting for reconnect/open",{errorCount:t,error:Gi(u)})},c=u=>{let d=Gi(u);if(u.code===1008||u.code===4e3){o(),this.connectPromise=null,n(new zt(`WebSocket connection failed: ${d}`,u));return}this.log("warn","WebSocket closed before opening; waiting for reconnect/open",{error:d})};this.rws.addEventListener("open",a),this.rws.addEventListener("error",s),this.rws.addEventListener("close",c),this.rws.readyState===3&&this.rws.reconnect(),i=setTimeout(()=>{o(),this.connectPromise=null,n(new zl(`WebSocket connection timeout after ${this.CONNECT_WAIT_TIMEOUT}ms`))},this.CONNECT_WAIT_TIMEOUT)}),this.connectPromise)},Tl=function(){this.pingIntervalStarted||this.closed||(this.pingIntervalStarted=!0,this.disposables.add("pingInterval",()=>{let e=setInterval(async()=>{try{this.log("debug","Sending periodic ping"),await this.invoke("ping"),this.log("debug","Ping successful")}catch(n){this.log("error","Ping failed",{error:n instanceof Error?n.message:String(n)})}},this.PING_INTERVAL);return{dispose:()=>{clearInterval(e),this.pingIntervalStarted=!1}}}))};function Sb(r){if(r===null||typeof r!="object")return null;let e=Object.entries(r).filter(([n,i])=>wb.has(n)&&["string","number","boolean"].includes(typeof i));return e.length>0?Object.fromEntries(e):null}function Ib(r){let e=new URL(r);return e.search="",e.hash="",e.toString()}function Ji(r){return{all:r=r||new Map,on:function(e,n){var i=r.get(e);i?i.push(n):r.set(e,[n])},off:function(e,n){var i=r.get(e);i&&(n?i.splice(i.indexOf(n)>>>0,1):r.set(e,[]))},emit:function(e,n){var i=r.get(e);i&&i.slice().map(function(t){t(n)}),(i=r.get("*"))&&i.slice().map(function(t){t(e,n)})}}}var Pb=typeof Ji=="function"?Ji:Ji.default;function zb(r){let e=Pb(r);return Object.assign(e,{once:(i,t)=>{let o=a=>{e.off(i,o),t(a)};return e.on(i,o),{dispose:()=>{e.off(i,o)}}}})}var Dr=class r{constructor(){this.emitter=zb()}listen(e,n){let i=()=>{this.removeListener(e,n)};return this.emitter.on(e,n),{dispose:i}}emit(e,...n){this.emitter.emit(e,n[0])}once(e,n){return this.emitter.once(e,n)}static make(){return new r}static refresh(){return new r}removeListener(e,n){if(e===void 0){this.emitter.all.clear();return}this.emitter.off(e,n)}static createInstance(){return new r}inspect(){return this.emitter.all}};var Rr=class{constructor(e,n){this.okra=e;this.client=n;this.targets=new Dl(e.data.id,n)}checkpoint(e,n,i="main",t=!1){return this.okra.invoke("git.checkpoint",{author:e,message:n,branch:i,allowEmpty:t})}checkout(e,n=!0){return this.okra.invoke("git.checkout",{branch:e,create:n})}log(e="main"){return this.okra.invoke("git.log",{ref:e})}diff(e){return this.okra.invoke("git.diff",this.normalizeRemoteInput(e))}merge(e){return this.okra.invoke("git.merge",this.normalizeRemoteInput(e))}conflicts(){return this.okra.invoke("git.conflicts",{})}abortMerge(){return this.okra.invoke("git.resolve",{action:"abort"})}continueMerge(e,n){return this.okra.invoke("git.resolve",{action:"continue",author:e,message:n})}review(){return this.okra.invoke("git.review",{})}stage(e={all:!0}){return this.okra.invoke("git.stage",e)}unstage(e={all:!0}){return this.okra.invoke("git.unstage",e)}revert(e){return this.okra.invoke("git.revert",e)}async credentials(){return(await this.client.post(`/notebook/${this.okra.data.id}/git/credentials`)).data}restore(e){return this.okra.invoke("git.restore",{ref:e})}status(){return this.okra.invoke("git.status",{})}normalizeRemoteInput(e){if(e.notebookId===void 0)return e;let n=e.notebookId.trim();if(!n)throw new Error("'notebookId' cannot be empty.");if(e.url?.trim())throw new Error("Pass either 'url' or 'notebookId', not both.");if(e.target?.trim())throw new Error("Pass either 'target' or 'notebookId', not both.");let{notebookId:i,...t}=e;return{...t,url:this.gitUrlForNotebook(n)}}gitUrlForNotebook(e){let n=new URL(this.okra.data.gitUrl);return n.username="",n.password="",n.pathname=`/${encodeURIComponent(e)}.git`,n.search="",n.hash="",n.toString()}},Dl=class{constructor(e,n){this.notebookId=e;this.client=n}async create(e){let n=await this.client.post(`/notebook/${this.notebookId}/git/targets`,xf({...e}));return new Ur(n.data,this.notebookId,this.client)}async list(){return(await this.client.get(`/notebook/${this.notebookId}/git/targets`)).data.map(n=>new Ur(n,this.notebookId,this.client))}async get(e){let n=await this.client.get(`/notebook/${this.notebookId}/git/targets/${encodeURIComponent(Eb(e))}`);return new Ur(n.data,this.notebookId,this.client)}},Ur=class r{constructor(e,n,i){this.data=e;this.notebookId=n;this.client=i}get id(){return this.data.id}async sync(e={}){let n=await this.client.post(`/notebook/${this.notebookId}/git/targets/${encodeURIComponent(this.id)}/sync`,xf({...e}));return new r(n.data,this.notebookId,this.client)}};function Eb(r){return typeof r=="string"?r:r.id}function xf(r){return Object.fromEntries(Object.entries(r).filter(([,e])=>e!==void 0))}var Bw=l.enum(["cloudflare-containers","ssh-server","laravel-cloud"]),Tb=l.enum(["pending","queued","building","deploying","healthy","failed","stopped","deleting","deleted","delete_failed"]),Gw=l.enum(["pending","queued","running","succeeded","failed","cancelled"]),Ww=l.enum(["created","ready","deleted"]),Vw=l.enum(["nano","small","medium","large","lite","basic","standard-1","standard-2"]),Jw=l.enum(["ENAM","WNAM","EEUR","WEUR","APAC","SAM","ME","OC","AFR"]),Kw=l.enum(["eu","fedramp"]),qw=l.enum(["none","password","email","external"]),Db=l.enum(["build","runtime"]),Ub=l.enum(["build","publish","runtime"]),Rb=l.preprocess(r=>Array.isArray(r)&&r.length===0?{}:r,l.record(l.string(),l.unknown())),kf=l.object({id:l.union([l.number(),l.string()]).optional(),sequence:l.number(),type:l.string(),payload:Rb,createdAt:l.string().nullable()}).passthrough(),Ul=l.object({sequence:l.number(),stream:Db,content:l.string(),createdAt:l.string().nullable()}).passthrough(),$f=l.object({name:l.string(),status:l.enum(["running","completed","failed"]).optional(),data:l.record(l.string(),l.unknown()).optional()}).strict(),wf=l.object({stream:Ub,content:l.string()}).strict(),Rl=l.object({success:l.boolean(),publicationId:l.string(),url:l.string().url(),buildId:l.string(),releaseId:l.string(),status:Tb}).strict(),Ob=$f.extend({type:l.literal("phase")}).strict(),Ab=wf.extend({type:l.literal("log")}).strict(),Cb=Rl.extend({type:l.literal("result")}).strict(),jb=l.discriminatedUnion("type",[Ob,Ab,Cb]),Nb=l.object({message:l.string().optional()}).passthrough(),_f=l.enum(["phase","log","done","result","error"]),Lb=l.object({event:l.literal("phase"),data:$f}).strict(),Zb=l.object({event:l.literal("log"),data:wf}).strict(),Fb=l.object({event:l.literal("done"),data:Rl}).strict(),Mb=l.object({event:l.literal("result"),data:Rl}).strict(),Bb=l.object({event:l.literal("error"),data:Nb}).strict(),Sf=l.discriminatedUnion("event",[Lb,Zb,Fb,Mb,Bb]).transform(r=>{if(r.event==="error")throw new Error(r.data.message??"Publish failed");let e=r.event==="done"?"result":r.event;return jb.parse({type:e,...r.data})});async function*Ol(r,e={}){if(r instanceof Response&&(!r.ok||!r.body))throw await r.body?.cancel().catch(()=>{}),new E(`Publishing stream is unavailable (HTTP ${r.status}).`);let i=(r instanceof Response?r.body:r).getReader(),t=new TextDecoder,o="",a="message",s=[],c=!1,u=!1;function d(){let h=a,g=s;if(a="message",s=[],!g.length||!_f.safeParse(h).success)return null;let k=g.join(`
67
- `),w;try{w=JSON.parse(k)}catch{w=k}let P=Sf.parse({event:h,data:w});return P.type==="result"&&(u=!0),P}function m(h){if(h==="")return d();if(h.startsWith(":"))return null;let g=h.indexOf(":"),k=g<0?h:h.slice(0,g),w=g<0?"":h.slice(g+1);return w.startsWith(" ")&&(w=w.slice(1)),k==="event"&&(a=w),k==="data"&&s.push(w),null}try{for(;;){let{done:h,value:g}=await i.read();o+=h?t.decode():t.decode(g,{stream:!0});let k;for(;(k=/\r\n|\r|\n/.exec(o))&&!(!h&&k[0]==="\r"&&k.index===o.length-1);){let w=m(o.slice(0,k.index));o=o.slice(k.index+k[0].length),w&&(yield w)}if(h){if(c=!0,o){let P=m(o);P&&(yield P)}let w=d();if(w&&(yield w),e.requireResult!==!1&&!u)throw new E("Publish stream ended without result");return}}}finally{c||await i.cancel().catch(()=>{}),i.releaseLock()}}function Gb(r,e={}){let n=r.getReader(),i=!1,t=!1,o,a;async function s(){i||(i=!0,e.signal?.removeEventListener("abort",a),n.releaseLock(),await e.onDispose?.())}function c(u){return o??(o=(async()=>{t=!0;try{await n.cancel(u)}finally{await s()}})())}return new Response(new ReadableStream({start(u){a=()=>{u.error(e.signal.reason),c(e.signal.reason).catch(()=>{})},e.signal?.aborted?a():e.signal?.addEventListener("abort",a,{once:!0})},async pull(u){try{let{done:d,value:m}=await n.read();if(t)return;d?(t=!0,await s(),u.close()):u.enqueue(m)}catch(d){if(t&&o)return;try{await c(d)}finally{u.error(d)}}},cancel:c},{highWaterMark:0}),{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform","X-Accel-Buffering":"no"}})}var Me=class{constructor(e,n){this.initial=e;this.client=n;this.streamAbort=new AbortController;this.started=!1;this.completed=!1;this.finalError=null;this.finalResult=null;this.resultPromise=null;this.resolveResult=null;this.rejectResult=null;this.bufferedEvents=[];this.subscribers=new Set}async*events(){this.start();let e=this.subscribe();try{for await(let n of e)yield n}finally{this.subscribers.delete(e),e.close()}}result(){if(this.start(),!this.resultPromise)throw new E("Publication stream could not start.");return this.resultPromise}async publication(){return await this.result(),this.initial.refresh()}start(){if(this.started)return this;let e=this.initial.data.eventStreamUrl;if(!e)throw new E(`Publication ${this.initial.data.id} has no eventStreamUrl for SSE streaming`);return this.started=!0,this.resultPromise=new Promise((n,i)=>{this.resolveResult=n,this.rejectResult=i}),this.resultPromise.catch(()=>{}),this.consumeStream(e),this}dispose(){if(this.completed)return;let e=new DOMException("Stopped observing publication; deployment continues.","AbortError");this.started||(this.started=!0,this.resultPromise=Promise.reject(e),this.resultPromise.catch(()=>{})),this.streamAbort.abort(e),this.fail(e)}subscribe(){let e=new Al;for(let n of this.bufferedEvents)e.push(n);return this.finalError?e.fail(this.finalError):this.completed?e.close():this.subscribers.add(e),e}async consumeStream(e){try{let n=await this.client.sse(e,this.streamAbort.signal);for await(let i of Ol(n))if(this.publish(i),i.type==="result"){let{type:t,...o}=i;this.finalResult=o,this.resolveResult?.(this.finalResult)}if(!this.finalResult)throw new E("Publish stream ended without result");this.closeSubscribers()}catch(n){this.fail(n instanceof Error?n:new E(String(n),n))}}publish(e){this.bufferedEvents.push(e);for(let n of this.subscribers)n.push(e)}closeSubscribers(){this.completed=!0;for(let e of this.subscribers)e.close();this.subscribers.clear()}fail(e){this.finalError=e,this.completed=!0,this.rejectResult?.(e);for(let n of this.subscribers)n.fail(e);this.subscribers.clear()}},Al=class{constructor(){this.values=[];this.pending=[];this.closed=!1;this.error=null}push(e){if(this.closed)return;let n=this.pending.shift();if(n){n.resolve({done:!1,value:e});return}this.values.push(e)}close(){if(!this.closed){this.closed=!0;for(let e of this.pending.splice(0))e.resolve({done:!0,value:void 0})}}fail(e){if(!this.closed){this.error=e,this.closed=!0;for(let n of this.pending.splice(0))n.reject(e)}}async*[Symbol.asyncIterator](){for(;;){let e=await this.next();if(e.done)return;yield e.value}}next(){let e=this.values.shift();return e?Promise.resolve({done:!1,value:e}):this.error?Promise.reject(this.error):this.closed?Promise.resolve({done:!0,value:void 0}):new Promise((n,i)=>{this.pending.push({resolve:n,reject:i})})}};var Be=class{constructor(e,n="/publication-resources"){this.client=e;this.path=n}async inspect(e){return(await this.client.post(`/publication-resources/${encodeURIComponent(e)}/inspect`,{})).data}async list(e={}){let n=new URLSearchParams;for(let[t,o]of Object.entries(e))o!==void 0&&n.set(t,String(o));let i=n.size>0?`?${n.toString()}`:"";return this.client.get(`${this.path}${i}`)}};var Or=class{constructor(e,n){this.client=e;this.publicationId=n}async list(){return(await this.client.get(this.path())).data}async create(e){return(await this.client.post(this.path(),{hostname:e})).data}async refresh(e){return(await this.client.post(`${this.path()}/${encodeURIComponent(e)}/refresh`)).data}async useAsApplicationUrl(e){return(await this.client.post(`${this.path()}/${encodeURIComponent(e)}/application-url`)).data}async delete(e){await this.client.delete(`${this.path()}/${encodeURIComponent(e)}`)}path(){return`/publications/${encodeURIComponent(this.publicationId)}/domains`}};var Ar=class{constructor(e){this.client=e;this.resources=new Be(e)}forProject(e){return new Cr(e,this.client)}async get(e){let n=await this.client.get(`/publications/${encodeURIComponent(e)}`);return new Ge(n.data,this.client)}},Ge=class r{constructor(e,n,i){this.data=e;this.client=n;this.notebookId=i;this.domains=new Or(n,e.id)}async reconcileLaravelCloudResource(e){let n=await this.client.post(`/publications/${encodeURIComponent(this.data.id)}/laravel-cloud/reconcile`,{resourceId:e});return new r(n.data,this.client,this.notebookId)}async configureLaravelCloud(e){let n=await this.client.put(`/publications/${encodeURIComponent(this.data.id)}/laravel-cloud/setup`,{setup:e});return new r(n.data,this.client,this.notebookId)}async refresh(){let e=await this.client.get(`/publications/${encodeURIComponent(this.data.id)}`);return new r(e.data,this.client,this.notebookId)}follow(){return new Me(this,this.client).start()}async stream(e){if(!this.data.eventStreamUrl)throw new E(`Publication ${this.data.id} has no eventStreamUrl for SSE streaming`);return this.client.sse(this.data.eventStreamUrl,e)}async destroy(e={}){let n=e.deleteResources?"?deleteResources=1":"";await this.client.delete(`/publications/${encodeURIComponent(this.data.id)}${n}`)}async wait(e={}){let n=e.intervalMs??1e3,i=e.timeoutMs??3e5,t=Date.now(),o=this;for(;!Wb(o.data.status);){if(Date.now()-t>i)throw new E(`Timed out waiting for publication ${this.data.id}`);await Vb(n),o=await o.refresh()}return o}async events(){return Cl(await this.client.stream(`/publications/${encodeURIComponent(this.data.id)}/events/stream`),kf)}buildLogs(e=this.data.latestBuild?.id??""){return e===""?Promise.reject(new E("Publication has no latest build id")):this.client.stream(`/publications/${encodeURIComponent(this.data.id)}/builds/${encodeURIComponent(e)}/logs/stream`).then(n=>Cl(n,Ul))}async logSnapshot(e,n=50){let i=new URLSearchParams({stream:e,limit:String(n)});return(await this.client.get(`/publications/${encodeURIComponent(this.data.id)}/logs?${i}`)).data}async logs(){return Cl(await this.client.stream(`/publications/${encodeURIComponent(this.data.id)}/logs/stream`),Ul)}async setProtection(e){let n=await this.client.put(`/publications/${encodeURIComponent(this.data.id)}/protection`,e);return new r(n.data,this.client,this.notebookId)}async protection(){return(await this.client.get(`/publications/${encodeURIComponent(this.data.id)}/protection`)).data}async createProtectionSession(){return(await this.client.post(`/publications/${encodeURIComponent(this.data.id)}/protection/session`)).data}async disableProtection(){let e=await this.client.delete(`/publications/${encodeURIComponent(this.data.id)}/protection`);if(!e.data)throw new R("Protection response has no publication data.","InvalidResponse");return new r(e.data,this.client,this.notebookId)}};function Wb(r){return["healthy","failed","stopped","deleted","delete_failed"].includes(r)}function Vb(r){return new Promise(e=>setTimeout(e,r))}function Cl(r,e){let n=new TextDecoder,i="";return r.pipeThrough(new TransformStream({transform(t,o){i+=n.decode(t,{stream:!0});let a=i.split(`
67
+ `),w;try{w=JSON.parse(k)}catch{w=k}let P=Sf.parse({event:h,data:w});return P.type==="result"&&(u=!0),P}function m(h){if(h==="")return d();if(h.startsWith(":"))return null;let g=h.indexOf(":"),k=g<0?h:h.slice(0,g),w=g<0?"":h.slice(g+1);return w.startsWith(" ")&&(w=w.slice(1)),k==="event"&&(a=w),k==="data"&&s.push(w),null}try{for(;;){let{done:h,value:g}=await i.read();o+=h?t.decode():t.decode(g,{stream:!0});let k;for(;(k=/\r\n|\r|\n/.exec(o))&&!(!h&&k[0]==="\r"&&k.index===o.length-1);){let w=m(o.slice(0,k.index));o=o.slice(k.index+k[0].length),w&&(yield w)}if(h){if(c=!0,o){let P=m(o);P&&(yield P)}let w=d();if(w&&(yield w),e.requireResult!==!1&&!u)throw new E("Publish stream ended without result");return}}}finally{c||await i.cancel().catch(()=>{}),i.releaseLock()}}function Gb(r,e={}){let n=r.getReader(),i=!1,t=!1,o,a;async function s(){i||(i=!0,e.signal?.removeEventListener("abort",a),n.releaseLock(),await e.onDispose?.())}function c(u){return o??(o=(async()=>{t=!0;try{await n.cancel(u)}finally{await s()}})())}return new Response(new ReadableStream({start(u){a=()=>{u.error(e.signal.reason),c(e.signal.reason).catch(()=>{})},e.signal?.aborted?a():e.signal?.addEventListener("abort",a,{once:!0})},async pull(u){try{let{done:d,value:m}=await n.read();if(t)return;d?(t=!0,await s(),u.close()):u.enqueue(m)}catch(d){if(t&&o)return;try{await c(d)}finally{u.error(d)}}},cancel:c},{highWaterMark:0}),{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform","X-Accel-Buffering":"no"}})}var Me=class{constructor(e,n){this.initial=e;this.client=n;this.streamAbort=new AbortController;this.started=!1;this.completed=!1;this.finalError=null;this.finalResult=null;this.resultPromise=null;this.resolveResult=null;this.rejectResult=null;this.bufferedEvents=[];this.subscribers=new Set}async*events(){this.start();let e=this.subscribe();try{for await(let n of e)yield n}finally{this.subscribers.delete(e),e.close()}}result(){if(this.start(),!this.resultPromise)throw new E("Publication stream could not start.");return this.resultPromise}async publication(){return await this.result(),this.initial.refresh()}start(){if(this.started)return this;let e=this.initial.data.eventStreamUrl;if(!e)throw new E(`Publication ${this.initial.data.id} has no eventStreamUrl for SSE streaming`);return this.started=!0,this.resultPromise=new Promise((n,i)=>{this.resolveResult=n,this.rejectResult=i}),this.resultPromise.catch(()=>{}),this.consumeStream(e),this}dispose(){if(this.completed)return;let e=new DOMException("Stopped observing publication; deployment continues.","AbortError");this.started||(this.started=!0,this.resultPromise=Promise.reject(e),this.resultPromise.catch(()=>{})),this.streamAbort.abort(e),this.fail(e)}subscribe(){let e=new Al;for(let n of this.bufferedEvents)e.push(n);return this.finalError?e.fail(this.finalError):this.completed?e.close():this.subscribers.add(e),e}async consumeStream(e){try{let n=await this.client.sse(e,this.streamAbort.signal);for await(let i of Ol(n))if(this.publish(i),i.type==="result"){let{type:t,...o}=i;this.finalResult=o,this.resolveResult?.(this.finalResult)}if(!this.finalResult)throw new E("Publish stream ended without result");this.closeSubscribers()}catch(n){this.fail(n instanceof Error?n:new E(String(n),n))}}publish(e){this.bufferedEvents.push(e);for(let n of this.subscribers)n.push(e)}closeSubscribers(){this.completed=!0;for(let e of this.subscribers)e.close();this.subscribers.clear()}fail(e){this.finalError=e,this.completed=!0,this.rejectResult?.(e);for(let n of this.subscribers)n.fail(e);this.subscribers.clear()}},Al=class{constructor(){this.values=[];this.pending=[];this.closed=!1;this.error=null}push(e){if(this.closed)return;let n=this.pending.shift();if(n){n.resolve({done:!1,value:e});return}this.values.push(e)}close(){if(!this.closed){this.closed=!0;for(let e of this.pending.splice(0))e.resolve({done:!0,value:void 0})}}fail(e){if(!this.closed){this.error=e,this.closed=!0;for(let n of this.pending.splice(0))n.reject(e)}}async*[Symbol.asyncIterator](){for(;;){let e=await this.next();if(e.done)return;yield e.value}}next(){let e=this.values.shift();return e?Promise.resolve({done:!1,value:e}):this.error?Promise.reject(this.error):this.closed?Promise.resolve({done:!0,value:void 0}):new Promise((n,i)=>{this.pending.push({resolve:n,reject:i})})}};var Be=class{constructor(e,n="/publication-resources"){this.client=e;this.path=n}async inspect(e){return(await this.client.post(`/publication-resources/${encodeURIComponent(e)}/inspect`,{})).data}async list(e={}){let n=new URLSearchParams;for(let[t,o]of Object.entries(e))o!==void 0&&n.set(t,String(o));let i=n.size>0?`?${n.toString()}`:"";return this.client.get(`${this.path}${i}`)}};var Or=class{constructor(e,n){this.client=e;this.publicationId=n}async list(){return(await this.client.get(this.path())).data}async create(e,n={}){return(await this.client.post(this.path(),{hostname:e,cloudflareStrategy:n.cloudflareStrategy,allowDowntime:n.allowDowntime})).data}async refresh(e){return(await this.client.post(`${this.path()}/${encodeURIComponent(e)}/refresh`)).data}async useAsApplicationUrl(e){return(await this.client.post(`${this.path()}/${encodeURIComponent(e)}/application-url`)).data}async delete(e){await this.client.delete(`${this.path()}/${encodeURIComponent(e)}`)}path(){return`/publications/${encodeURIComponent(this.publicationId)}/domains`}};var Ar=class{constructor(e){this.client=e;this.resources=new Be(e)}forProject(e){return new Cr(e,this.client)}async get(e){let n=await this.client.get(`/publications/${encodeURIComponent(e)}`);return new Ge(n.data,this.client)}},Ge=class r{constructor(e,n,i){this.data=e;this.client=n;this.notebookId=i;this.domains=new Or(n,e.id)}async reconcileLaravelCloudResource(e){let n=await this.client.post(`/publications/${encodeURIComponent(this.data.id)}/laravel-cloud/reconcile`,{resourceId:e});return new r(n.data,this.client,this.notebookId)}async configureLaravelCloud(e){let n=await this.client.put(`/publications/${encodeURIComponent(this.data.id)}/laravel-cloud/setup`,{setup:e});return new r(n.data,this.client,this.notebookId)}async refresh(){let e=await this.client.get(`/publications/${encodeURIComponent(this.data.id)}`);return new r(e.data,this.client,this.notebookId)}follow(){return new Me(this,this.client).start()}async stream(e){if(!this.data.eventStreamUrl)throw new E(`Publication ${this.data.id} has no eventStreamUrl for SSE streaming`);return this.client.sse(this.data.eventStreamUrl,e)}async destroy(e={}){let n=e.deleteResources?"?deleteResources=1":"";await this.client.delete(`/publications/${encodeURIComponent(this.data.id)}${n}`)}async wait(e={}){let n=e.intervalMs??1e3,i=e.timeoutMs??3e5,t=Date.now(),o=this;for(;!Wb(o.data.status);){if(Date.now()-t>i)throw new E(`Timed out waiting for publication ${this.data.id}`);await Vb(n),o=await o.refresh()}return o}async events(){return Cl(await this.client.stream(`/publications/${encodeURIComponent(this.data.id)}/events/stream`),kf)}buildLogs(e=this.data.latestBuild?.id??""){return e===""?Promise.reject(new E("Publication has no latest build id")):this.client.stream(`/publications/${encodeURIComponent(this.data.id)}/builds/${encodeURIComponent(e)}/logs/stream`).then(n=>Cl(n,Ul))}async logSnapshot(e,n=50){let i=new URLSearchParams({stream:e,limit:String(n)});return(await this.client.get(`/publications/${encodeURIComponent(this.data.id)}/logs?${i}`)).data}async logs(){return Cl(await this.client.stream(`/publications/${encodeURIComponent(this.data.id)}/logs/stream`),Ul)}async setProtection(e){let n=await this.client.put(`/publications/${encodeURIComponent(this.data.id)}/protection`,e);return new r(n.data,this.client,this.notebookId)}async protection(){return(await this.client.get(`/publications/${encodeURIComponent(this.data.id)}/protection`)).data}async createProtectionSession(){return(await this.client.post(`/publications/${encodeURIComponent(this.data.id)}/protection/session`)).data}async disableProtection(){let e=await this.client.delete(`/publications/${encodeURIComponent(this.data.id)}/protection`);if(!e.data)throw new R("Protection response has no publication data.","InvalidResponse");return new r(e.data,this.client,this.notebookId)}};function Wb(r){return["healthy","failed","stopped","deleted","delete_failed"].includes(r)}function Vb(r){return new Promise(e=>setTimeout(e,r))}function Cl(r,e){let n=new TextDecoder,i="";return r.pipeThrough(new TransformStream({transform(t,o){i+=n.decode(t,{stream:!0});let a=i.split(`
68
68
  `);i=a.pop()??"";for(let s of a){let c=s.trim();c!==""&&o.enqueue(e.parse(JSON.parse(c)))}},flush(t){i+=n.decode();let o=i.trim();o!==""&&t.enqueue(e.parse(JSON.parse(o)))}}))}var Cr=class{constructor(e,n){this.projectId=e;this.client=n;this.resources=new Be(n,`${this.path}/publication/resources`)}get path(){return`/projects/${encodeURIComponent(this.projectId)}`}async current(){try{let e=await this.client.get(`${this.path}/publication`);return new Ge(e.data,this.client)}catch(e){if(C.is(e)&&e.status===404)return null;throw e}}async readiness(){return(await this.client.get(`${this.path}/publication/readiness`)).data}async configuration(){return(await this.client.get(`${this.path}/publication/configuration`)).data}async updateConfiguration(e){return(await this.client.patch(`${this.path}/publication/configuration`,e)).data}async prepare(e){return(await this.client.post(`${this.path}/publication/plan`,e)).data}async publish(e){let n=(await this.client.post(`${this.path}/publication`,e)).data;return"confirmationRequired"in n||this.startApplicationRuns(n),n}async application(e){return(await this.client.get(`${this.path}/publication/application/${encodeURIComponent(e)}`)).data}async retryApplication(e){let n=(await this.client.post(`${this.path}/publication/application/${encodeURIComponent(e)}/retry`,{})).data;return this.startApplicationRuns(n),n}async destroyApplication(e,n={}){let i=n.deleteResources?"?deleteResources=1":"";await this.client.delete(`${this.path}/publication/application/${encodeURIComponent(e)}${i}`)}startApplicationRuns(e){for(let n of e.apps)(e.selectedAppIds??[]).includes(n.appId)&&["pending","queued","building","deploying"].includes(n.publication.status)&&new Me(new Ge(n.publication,this.client),this.client).start()}async catalog(e,n){let i=new URLSearchParams({provider:e});return n!==void 0&&i.set("serverId",n),(await this.client.get(`${this.path}/publication/catalog?${i}`)).data}};function Jb(r={},e=null){let n={...r},i={database:e?.databaseId,cache:e?.cacheId,storage:e?.storageId},t=["database","cache","storage"];for(let o of t){let a=i[o];r[o]?.mode==="create"&&a&&(n[o]={mode:"reuse",id:a})}return n}var Ki=class{constructor(e){this.client=e}async inspectInvitation(e,n){return(await this.client.post(`/platform/server-invitations/${encodeURIComponent(e)}/inspect`,{token:n})).data}async acceptInvitation(e,n){return(await this.client.post(`/platform/server-invitations/${encodeURIComponent(e)}/accept`,{token:n})).data}async declineInvitation(e,n){return(await this.client.post(`/platform/server-invitations/${encodeURIComponent(e)}/decline`,{token:n})).data}async list(e={}){let n=e.page===void 0?"":`?${new URLSearchParams({page:String(e.page)}).toString()}`;return this.client.get(`/servers${n}`)}async create(e){let n=await this.client.post("/servers",e);return new qi(n.data,this.client)}async get(e){let n=await this.client.get(`/servers/${e}`);return new qi(n.data,this.client)}},qi=class{constructor(e,n){this.data=e;this.client=n}async updateAgent(e){return(await this.client.post(`/servers/${encodeURIComponent(this.data.id)}/agent/updates`,e)).data}async installation(e={}){let n=e.managedUpdates?"?managedUpdates=1":"";return(await this.client.get(`/servers/${encodeURIComponent(this.data.id)}/installation${n}`)).data}async members(e={}){let n=e.page===void 0?"":`?${new URLSearchParams({page:String(e.page)}).toString()}`;return this.client.get(`/servers/${encodeURIComponent(this.data.id)}/members${n}`)}async share(e){if(e.email!==void 0)return(await this.client.post(`/platform/servers/${encodeURIComponent(this.data.id)}/invitations`,{email:e.email,requestId:e.requestId??crypto.randomUUID()})).data;let n={organizationId:e.organizationId,requestId:e.requestId};return(await this.client.post(`/servers/${encodeURIComponent(this.data.id)}/members`,n)).data}async revokeAccess(e){await this.client.delete(`/servers/${encodeURIComponent(this.data.id)}/members/${encodeURIComponent(String(e))}`)}async invitations(e={}){let n=e.page===void 0?"":`?${new URLSearchParams({page:String(e.page)}).toString()}`;return this.client.get(`/platform/servers/${encodeURIComponent(this.data.id)}/invitations${n}`)}async cancelInvitation(e){let n=await this.client.delete(`/platform/servers/${encodeURIComponent(this.data.id)}/invitations/${encodeURIComponent(e)}`);if(n.data===void 0)throw new E("Missing invitation cancellation response.");return n.data}async resendInvitation(e){return(await this.client.post(`/platform/servers/${encodeURIComponent(this.data.id)}/invitations/${encodeURIComponent(e)}/resend`,{})).data}refresh(){return this.client.servers.get(this.data.id)}async delete(){await this.client.delete(`/servers/${this.data.id}`)}async waitReady(e){let n=e?.timeout??3e5,i=e?.interval??3e3,t=Date.now()+n;for(;Date.now()<t;){let o=await this.refresh();if(o.data.status==="connected")return o;if(o.data.status==="failed")throw new Error(`Server provisioning failed: ${o.data.id}`);await new Promise(a=>setTimeout(a,i))}throw new Error(`Server did not become ready within ${n}ms`)}};function Et(r,e){return new Request(r,{...e,redirect:"manual"})}var If={"runtime.ready":{method:"GET",path:"/runtime"},"config.get":{method:"GET",path:"/runtime/config"},"config.update":{method:"PATCH",path:"/runtime/config"},"config.set-ports":{method:"PUT",path:"/runtime/config/ports"},"container.restart":{method:"POST",path:"/runtime/container/restart"},"container.stop":{method:"POST",path:"/runtime/container/stop"},"container.set-php":{method:"PUT",path:"/runtime/container/php"},"container.opened-ports":{method:"GET",path:"/runtime/container/ports"},"container.resolve-port":{method:"POST",path:"/runtime/container/ports/resolve"},"container.stats":{method:"GET",path:"/runtime/container/stats"},"terminal.list":{method:"GET",path:"/runtime/terminals"},"shell.exec":{method:"POST",path:"/runtime/executions"},"fs.readFile":{method:"GET",path:"/runtime/files/content"},"fs.writeFile":{method:"PUT",path:"/runtime/files/content"},"fs.download":{method:"POST",path:"/runtime/files/download"},"fs.createDirectory":{method:"PUT",path:"/runtime/directories"},"fs.readDirectory":{method:"POST",path:"/runtime/directories/read"},"fs.stat":{method:"POST",path:"/runtime/files/stat"},"fs.rename":{method:"POST",path:"/runtime/files/rename"},"fs.copy":{method:"POST",path:"/runtime/files/copy"},"fs.delete":{method:"DELETE",path:"/runtime/files"},"fs.tail":{method:"POST",path:"/runtime/files/tail"},"fs.find":{method:"POST",path:"/runtime/files/find"},"fs.textSearch":{method:"POST",path:"/runtime/files/search"},"fs.tree":{method:"POST",path:"/runtime/files/tree"},"service.list":{method:"GET",path:"/runtime/services"},"service.run":{method:"POST",path:"/runtime/services/run"},"service.stop":{method:"POST",path:"/runtime/services/stop"},"service.logs":{method:"POST",path:"/runtime/services/logs"},"composer.invoke":{method:"POST",path:"/runtime/composer/executions"},"composer.packages":{method:"GET",path:"/runtime/composer/packages"},"git.checkpoint":{method:"POST",path:"/runtime/git/checkpoints"},"git.checkout":{method:"POST",path:"/runtime/git/checkouts"},"git.log":{method:"POST",path:"/runtime/git/log"},"git.sync":{method:"POST",path:"/runtime/git/sync"},"git.diff":{method:"POST",path:"/runtime/git/diff"},"git.merge":{method:"POST",path:"/runtime/git/merge"},"git.conflicts":{method:"GET",path:"/runtime/git/conflicts"},"git.resolve":{method:"POST",path:"/runtime/git/conflicts/resolve"},"git.restore":{method:"POST",path:"/runtime/git/restore"},"git.status":{method:"GET",path:"/runtime/git/status"},"git.review":{method:"GET",path:"/runtime/git/review"},"git.stage":{method:"POST",path:"/runtime/git/stage"},"git.unstage":{method:"POST",path:"/runtime/git/unstage"},"git.revert":{method:"POST",path:"/runtime/git/revert"}},jr=class{constructor(e,n,i){this.fetch=n;this.refresh=i;this.refreshPromise=null;this.streams=new Set;this.notebookId=e.id,this.configure(e.runtimeUrl)}configure(e){let n=new URL(e),i=n.searchParams.get("ticket")??"";if(i==="")throw new E("The notebook connection does not contain a runtime ticket.");this.ticket=i,n.protocol==="wss:"?n.protocol="https:":n.protocol==="ws:"&&(n.protocol="http:"),n.pathname=`/api/v1/notebooks/${encodeURIComponent(this.notebookId)}`,n.searchParams.delete("ticket"),n.hash="",this.actionUrl=n}ready(){return this.invokeRaw("runtime.ready",{},{})}supports(e){return e in If}invoke(e,n={},i={}){return this.invokeRaw(e,n??{},i)}send(){throw new E("Fire-and-forget actions require the realtime transport.")}dispose(){for(let e of this.streams)e.abort(new DOMException("Notebook disposed","AbortError"))}stream(e,n,i={}){let t=new AbortController;this.streams.add(t);let o=Ef({...i,abortSignal:t.signal}),a=()=>t.abort(i.abortSignal?.reason),s,c=!1,u=()=>{},d=()=>{this.streams.delete(t),i.abortSignal?.removeEventListener("abort",a),o.signal.removeEventListener("abort",u),o.dispose()},m=async h=>{let g=s;s=void 0,g!==void 0&&(await g.cancel(h).catch(()=>{}),g.releaseLock())};return new ReadableStream({start:h=>{u=()=>{c||(c=!0,d(),h.error(o.signal.reason),m(o.signal.reason))},o.signal.addEventListener("abort",u,{once:!0}),i.abortSignal?.addEventListener("abort",a,{once:!0}),i.abortSignal?.aborted&&a()},pull:async h=>{try{if(s===void 0){let k=await this.streamResponse(e,n,o.signal);if(c){await k.body?.cancel();return}if(k.body===null)throw new R("PHPSandbox runtime returned an empty download.","InvalidResponse",k);s=k.body.getReader()}let g=await s.read();if(c)return;g.done?(c=!0,d(),s.releaseLock(),s=void 0,h.close()):h.enqueue(g.value)}catch(g){c||(c=!0,t.abort(g),d(),await m(g),h.error(g))}},cancel:async h=>{c=!0,t.abort(h),d(),await m(h)}},{highWaterMark:0})}async streamResponse(e,n,i){for(let t=0;t<2;t+=1){i.throwIfAborted();let o=await Pf(this.fetch,this.request(e,n,i));if(i.aborted&&(await o.body?.cancel(),i.throwIfAborted()),o.status===401&&t===0&&this.refresh!==void 0){await o.body?.cancel(),await this.refreshAuthorization();continue}if(!o.ok){let a=await zf(o);throw je("runtime",a.error,o)}if(!o.headers.get("content-type")?.toLowerCase().startsWith("application/zip"))throw await o.body?.cancel(),new R("PHPSandbox runtime returned an invalid download.","InvalidResponse",o);return o}throw new C("Notebook download could not be authorized.",{source:"runtime",status:401,code:"AuthenticationRequired"})}async invokeRaw(e,n,i){let t=Ef(i);try{for(let o=0;o<2;o+=1){let a=await Pf(this.fetch,this.request(e,n,t.signal));if(a.status===401&&o===0&&this.refresh!==void 0){await this.refreshAuthorization();continue}let s=await zf(a);if(!a.ok||s.error!==void 0)throw je("runtime",s.error,a);return s.data}throw new C(`Runtime action ${e} could not be authorized.`,{source:"runtime",status:401,code:"AuthenticationRequired"})}finally{t.dispose()}}request(e,n,i){let t=If[e];if(t===void 0)throw new E(`Runtime action ${e} requires the realtime transport.`);let o=new URL(this.actionUrl);o.pathname+=t.path;let a={Accept:e==="fs.download"?"application/zip":"application/json, application/octet-stream",Authorization:`Bearer ${this.ticket}`},s=Kb(e,n,o,a);return Et(o,{method:t.method,headers:a,body:t.method==="GET"?void 0:s,signal:i})}async refreshAuthorization(){this.refreshPromise===null&&(this.refreshPromise=this.refresh().then(e=>this.configure(e)));try{await this.refreshPromise}finally{this.refreshPromise=null}}};async function Pf(r,e){try{return await r(e)}catch(n){throw n instanceof DOMException&&n.name==="AbortError"?n:new R("Unable to reach the PHPSandbox runtime.","ConnectionFailed",n)}}async function zf(r){if(r.ok&&r.headers.get("content-type")?.toLowerCase().startsWith("application/octet-stream"))return{data:new Uint8Array(await r.arrayBuffer())};let e=await r.text();if(e===""){if(r.ok)throw new R("PHPSandbox runtime returned an empty response.","InvalidResponse",r);return{}}try{return JSON.parse(e)}catch(n){throw new R("PHPSandbox runtime returned an invalid JSON response.","InvalidResponse",n)}}function Kb(r,e,n,i){let t=Hi(e);if(r==="fs.readFile"){Xi(n,"path",t.path);let o=Hi(t.lineRange);(o.lineStart!==void 0||o.lineEnd!==void 0)&&(Xi(n,"lineStart",o.lineStart),Xi(n,"lineEnd",o.lineEnd));return}if(r==="fs.writeFile"){Xi(n,"path",t.path);let o=Hi(t.options);jl(n,"overwrite",o.overwrite),jl(n,"create",o.create),jl(n,"unlock",o.unlock);let a=Hi(o.atomic);if(typeof a.postfix=="string"&&a.postfix!==""&&n.searchParams.set("atomicPostfix",a.postfix),!ArrayBuffer.isView(t.contents))throw new TypeError("Runtime file contents must be binary data.");return i["Content-Type"]="application/octet-stream",Uint8Array.from(new Uint8Array(t.contents.buffer,t.contents.byteOffset,t.contents.byteLength)).buffer}return i["Content-Type"]="application/json",JSON.stringify(e)}function Hi(r){return r!==null&&typeof r=="object"?r:{}}function Xi(r,e,n){if(typeof n!="string"&&typeof n!="number"||String(n)==="")throw new TypeError(`Runtime file ${e} is required.`);r.searchParams.set(e,String(n))}function jl(r,e,n){r.searchParams.set(e,n===!0?"true":"false")}function Ef(r){if(r.timeout===void 0&&r.abortSignal===void 0)return{signal:new AbortController().signal,dispose:()=>{}};let e=new AbortController,n=()=>e.abort(r.abortSignal?.reason);r.abortSignal?.addEventListener("abort",n,{once:!0}),r.abortSignal?.aborted&&n();let i=r.timeout===void 0?void 0:setTimeout(()=>e.abort(),r.timeout);return{signal:e.signal,dispose:()=>{r.abortSignal?.removeEventListener("abort",n),i!==void 0&&clearTimeout(i)}}}var Yi=class{constructor(e,n){this.client=e;this.identifier=n}async configure(e){return(await this.client.put(this.path("/configuration"),e)).data}async configuration(){return(await this.client.get(this.path("/configuration"))).data}async submit(e,n={}){return(await this.client.post(this.path(),e,n)).data}async list(e={}){let n=new URLSearchParams;for(let[i,t]of Object.entries(e))t!==void 0&&n.set(i,String(t));return this.client.get(`${this.path()}${n.size===0?"":`?${n.toString()}`}`)}async get(e){return(await this.client.get(this.path(`/${encodeURIComponent(e)}`))).data}async update(e,n){return(await this.client.patch(this.path(`/${encodeURIComponent(e)}`),n)).data}path(e=""){return`/platform/projects/${encodeURIComponent(this.identifier)}/feedback${e}`}},Nr=class{constructor(e){this.client=e}forProject(e){return new Yi(this.client,e)}};var Qi=class{constructor(e){this.client=e}async link(e){let n=await this.client.post("/integrations",e);return new We(n.data,this.client)}async list(){return(await this.client.get("/integrations")).data.map(n=>new We(n,this.client))}async get(e){let n=await this.client.get(`/integrations/${encodeURIComponent(eo(e))}`);return new We(n.data,this.client)}},We=class r{constructor(e,n){this.data=e;this.client=n}get id(){return this.data.id}get provider(){return this.data.provider}get label(){return this.data.label}async update(e){let n=await this.client.patch(`/integrations/${encodeURIComponent(this.id)}`,e);return new r(n.data,this.client)}async unlink(){await this.client.delete(`/integrations/${encodeURIComponent(this.id)}`)}};function eo(r){return typeof r=="string"?r:r.id}var to=class{constructor(e,n){this.notebookId=e;this.client=n}async attach(e){let n=await this.client.post(this.path(),{...e,integration:eo(e.integration)});return new Lr(n.data,this.notebookId,this.client)}async list(){return(await this.client.get(this.path())).data.map(n=>new Lr(n,this.notebookId,this.client))}async get(e){let n=await this.client.get(this.bindingPath(e));return new Lr(n.data,this.notebookId,this.client)}path(){return`/notebook/${this.notebookId}/integrations`}bindingPath(e){return`${this.path()}/${encodeURIComponent(qb(e))}`}},Lr=class r{constructor(e,n,i){this.data=e;this.notebookId=n;this.client=i}get id(){return this.data.id}get integration(){return new We(this.data.integration,this.client)}get effects(){return this.data.effects}async update(e){let n=await this.client.patch(this.path(),{...e,integration:e.integration===void 0?void 0:eo(e.integration)});return new r(n.data,this.notebookId,this.client)}async detach(){await this.client.delete(this.path())}path(){return`/notebook/${this.notebookId}/integrations/${encodeURIComponent(this.id)}`}};function qb(r){return typeof r=="string"?r:r.id}function Hb(r){return Array.isArray(r)?r:Object.entries(r).map(([e,n])=>({name:e,...typeof n=="string"?{value:n}:n}))}var Ll=class{constructor(e){this.client=e}async list(e={}){return this.client.get(`/notebook${Df({page:e.page,per_page:e.perPage})}`)}async inspectImport(e){return(await this.client.post("/notebook/imports/inspect",e)).data}async create(e,n={}){let i=await this.client.post("/notebook",{template:e,...n});return new Fr(i.data,this.client)}async get(e){let n=await this.client.get(`/notebook/${e}`);return new Fr(n.data,this.client)}open(e){return new Fr(e,this.client)}};function Xb(r){let e=new URL(r),n=e.pathname.replace(/\/+$/,"");return e.pathname=n===""||n==="/"?"/v1/":`${n}/`,e.search="",e.hash="",e.toString()}var Zr=class{constructor(e,n="https://api.phpsandbox.io/v1",i={},t="realtime"){this.fetch=globalThis.fetch;this.publications=new Ar(this),this.notebook=new Ll(this),this.servers=new Ki(this),this.integrations=new Qi(this),this.payments=new Di(this),this.customers=new zi(this),this.feedback=new Nr(this),this.options={...i},this.runtimeTransportValue=t,this.baseUrl=Xb(n),i.fetch&&(this.fetch=i.fetch),this.headers={Accept:"application/json",Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}get runtimeTransport(){return this.runtimeTransportValue}get(e){return this.requireData(this.makeRequest("GET",e))}post(e,n,i={}){return this.requireData(this.makeRequest("POST",e,{body:n===void 0?void 0:JSON.stringify(n),headers:i.idempotencyKey===void 0?void 0:{"Idempotency-Key":i.idempotencyKey}}))}delete(e){return this.makeRequest("DELETE",e)}put(e,n){return this.requireData(this.makeRequest("PUT",e,{body:n===void 0?void 0:JSON.stringify(n)}))}patch(e,n){return this.requireData(this.makeRequest("PATCH",e,{body:n===void 0?void 0:JSON.stringify(n)}))}async stream(e){let n=await this.fetchResponse(Et(new URL(e.replace(/^\//,""),this.baseUrl),{method:"GET",headers:this.headers}));if(!n.ok)throw await Nl(n);if(!n.body)throw new R("PHPSandbox API response body is not readable.","InvalidResponse",n);return n.body}async sse(e,n){let i=await this.fetchResponse(Et(e,{method:"GET",headers:{...this.headers,Accept:"text/event-stream"},...n===void 0?{}:{signal:n}}));if(!i.ok)throw await Nl(i);if(!i.body)throw new R("PHPSandbox API SSE response body is not readable.","InvalidResponse",i);return i.body}async requireData(e){let n=await e;if(n.data===void 0)throw new R("PHPSandbox API returned no data for a data request.","InvalidResponse");return{...n,data:n.data}}async makeRequest(e,n,i){let t=new Headers(i?.headers);for(let[s,c]of Object.entries(this.headers))t.set(s,c);let o=await this.fetchResponse(Et(new URL(n.replace(/^\//,""),this.baseUrl),{method:e,...i,headers:t}));if(!o.ok)throw await Nl(o,n.startsWith("/platform/")?"platform":"core");if(o.status===204)return{data:void 0};let a=await o.text();if(a==="")throw new R("PHPSandbox API returned an empty response.","InvalidResponse",o);try{let s=JSON.parse(a);if(s===null||typeof s!="object"||Array.isArray(s)||!Object.prototype.hasOwnProperty.call(s,"data"))throw new R("PHPSandbox API returned an invalid success response.","InvalidResponse",o);return s}catch(s){throw R.is(s)?s:new R("PHPSandbox API returned an invalid JSON response.","InvalidResponse",s)}}async fetchResponse(e){try{return await this.fetch(e)}catch(n){throw n instanceof DOMException&&n.name==="AbortError"?n:new R("Unable to reach the PHPSandbox API.","ConnectionFailed",n)}}};async function Nl(r,e="core"){let n=await r.text();try{return je(e,Yb(n===""?void 0:JSON.parse(n)),r)}catch{return new R(`PHPSandbox API returned an invalid error response (HTTP ${r.status}).`,"InvalidResponse",r,{status:r.status,statusText:r.statusText,body:n})}}function Yb(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)?r.error:void 0}var Tf=class r{constructor(e){this.client=e;this.notebook=e.notebook,this.publications=e.publications,this.servers=e.servers,this.integrations=e.integrations,this.payments=e.payments,this.customers=e.customers,this.feedback=e.feedback}async whoami(){let{data:e}=await this.client.get("/auth/whoami"),n=Ym.safeParse(e);if(!n.success)throw new E("Invalid identity response.");return n.data}get runtimeTransport(){return this.client.runtimeTransport}static app(e={}){let{token:n,url:i,mode:t}=Xm(e);return new Ui(new Zr(n,i,{},"rest"),n,t)}static realtime(e,n="https://api.phpsandbox.io/v1",i={}){return new r(new Zr(e,n,i))}static rest(e,n="https://api.phpsandbox.io/v1",i={}){return new r(new Zr(e,n,i,"rest"))}},Q,Mr,Zl,Gl=class Gl{constructor(e,n){this.data=e;this.client=n;Dt(this,Mr);this.downloadInvoker=null;this.initialized=!1;Dt(this,Q,null);this.disposables=[];let i=n.options.runtimeUrlProvider;if(this.emitter=Dr.createInstance(),n.runtimeTransport==="rest")this.socket=null,this.restInvoker=new jr(e,n.options.fetch??globalThis.fetch,i===void 0?void 0:()=>i(e.id));else{this.restInvoker=null;let t=!0,o=i===void 0?e.runtimeUrl:async()=>t?(t=!1,e.runtimeUrl):i(e.id);this.socket=new Vi(o,this.emitter,{debug:n.options.debug,webSocket:n.options.webSocket}),this.watchConnection(),Ut(this,Q,pe(this,Mr,Zl).call(this))}this.files=new Ri(this,this.socket===null?null:t=>this.onDidConnect(t)),this.terminals=new hr(this),this.lsp=new vr(this),this.composer=new yr(this,n),this.runtime=new wr(this),this.repl=new _r(this),this.shell=new br(this),this.git=new Rr(this,n),this.services=new Sr(this),this.config=new Ir(this),this.secrets=new Fl(n,this.data.id),this.integrations=new to(this.data.id,n),this.preview=new Ml(n,this.data.id),this.mail=new Bl(n,this.data.id)}get runtimeTransport(){return this.client.runtimeTransport}async ready(){if(this.restInvoker!==null)return this.restInitialization();let e=this.realtimeSocket(),n=e.getTerminalError();if(n)throw n;return(async()=>(e.isConnected||await e.connect(),Pe(this,Q)))()}async update(e){let n=await this.client.put(`/notebook/${this.data.id}`,e);return Object.assign(this.data,n.data),this.data}async fork(e={}){let n=await this.client.post(`/notebook/${this.data.id}/fork`,e);return new Gl(n.data,this.client)}run(e,n=[],i){return Array.isArray(n)?this.shell.run(e,n,i):this.shell.run(e,n)}exec(e,n=[],i){return Array.isArray(n)?this.run(e,n,i).wait():this.run(e,n).wait()}async destroy(){await this.client.delete(`/notebook/${this.data.id}`),this.socket?.terminate(new C("Notebook has been deleted.",{source:"runtime",status:503,code:"NotebookUnavailable",details:{id:this.data.id}}))}restart(){return this.invoke("container.restart")}stop(){return this.invoke("container.stop")}invoke(e,n={},i={}){return this.restInvoker!==null?(this.restInvoker.supports(String(e))&&this.restInitialization(),this.restInvoker.invoke(e,n||{},i)):this.realtimeSocket().invoke(e,n||{},i)}send(e,n={}){return this.restInvoker!==null?this.restInvoker.send():this.realtimeSocket().send(e,n||{})}stream(e,n={},i={}){let t=this.client.options.runtimeUrlProvider;return this.downloadInvoker??(this.downloadInvoker=this.restInvoker??new jr(this.data,this.client.options.fetch??globalThis.fetch,t===void 0?void 0:()=>t(this.data.id))),this.downloadInvoker.stream(e,n,i)}listen(e,n){let i=this.emitter.listen(e,n);return this.disposables.push(i),i}dispose(){this.downloadInvoker?.dispose(),this.disposables.forEach(e=>e.dispose()),this.socket!==null&&!this.socket.isClosed&&this.socket.disconnect()}connected(){return this.waitForSocketConnection({rejectOnClose:!0})}waitForSocketConnection(e){let n=this.realtimeSocket(),i=n.getTerminalError();return i?Promise.reject(i):n.isConnected?Promise.resolve(this):new Promise((t,o)=>{let a=[],s=!1,c=()=>{for(let d of a)d.dispose();a.length=0},u=d=>{s||(s=!0,c(),d())};try{a.push(n.onDidConnect(()=>u(()=>t(this)))),e.rejectOnClose&&a.push(n.onDidClose(()=>u(()=>o(new Error("Connection closed"))))),a.push(n.onDidBootError(d=>u(()=>o(d))))}catch(d){u(()=>o(d))}})}watchConnection(){let e=this.realtimeSocket();e.onDidConnect(()=>{e.emit("okra.connected")}),e.onDidClose(()=>{e.emit("okra.disconnected"),this.initialized=!1}),e.onDidBootError(n=>{e.emit("okra.boot_error",n),e.emit("okra.disconnected"),this.initialized=!1})}onDidConnect(e){let n=this.realtimeSocket();n.removeListener("okra.connected",e);let i=n.listen("okra.connected",e);return this.disposables.push(i),i}onDidDisconnect(e){let n=this.realtimeSocket().listen("okra.disconnected",e);return this.disposables.push(n),n}onDidBootError(e){let n=this.realtimeSocket().listen("okra.boot_error",i=>{C.is(i,"NotebookUnavailable")&&e(i)});return this.disposables.push(n),n}restInitialization(){if(this.restInvoker===null)throw new E("This operation requires the REST transport.");return Pe(this,Q)===null&&(Ut(this,Q,this.restInvoker.ready().then(e=>(this.initialized=e,this.emitter.emit("notebook.initialized",e),e))),Pe(this,Q).catch(()=>{})),Pe(this,Q)}onDidInitialize(e){return this.listen("notebook.initialized",e)}async reconnect(){let e=this.realtimeSocket(),n=this.waitForSocketConnection({rejectOnClose:!1});return e.reconnect(),this.initialized=!1,await n,Ut(this,Q,pe(this,Mr,Zl).call(this)),this.ready().then(()=>this)}realtimeSocket(){if(this.socket===null)throw new E("This operation requires the realtime transport.");return this.socket}};Q=new WeakMap,Mr=new WeakSet,Zl=function(){return Ut(this,Q,new Promise((e,n)=>{let i=this.onDidInitialize(o=>{if(t.dispose(),i.dispose(),this.initialized=o,o.type==="error"){n(new C(o.message,{source:"runtime",status:503,code:"NotebookInitializationFailed",details:o.data}));return}e(o)}),t=this.onDidBootError(o=>{i.dispose(),t.dispose(),n(o)})})),Pe(this,Q).catch(()=>{}),Pe(this,Q)};var Fr=Gl,Fl=class{constructor(e,n){this.client=e;this.notebookId=n}async list(e){let n=new URLSearchParams;e?.environment&&n.set("environment",e.environment);let i=n.toString();return(await this.client.get(`/notebook/${this.notebookId}/secrets${i?`?${i}`:""}`)).data}async set(e,n){let i=typeof n=="string"?{name:e,value:n}:{name:e,...n};return(await this.client.put(`/notebook/${this.notebookId}/secrets`,i)).data}async setMany(e){return(await this.client.put(`/notebook/${this.notebookId}/secrets`,{secrets:Hb(e)})).data}async delete(e,n){let i=new URLSearchParams;n?.environment&&i.set("environment",n.environment);let t=i.toString();await this.client.delete(`/notebook/${this.notebookId}/secrets/${encodeURIComponent(e)}${t?`?${t}`:""}`)}},Ml=class{constructor(e,n){this.client=e;this.notebookId=n}async get(e){let n=e===void 0?"":`?${new URLSearchParams({url:e}).toString()}`;return(await this.client.get(`/notebook/${this.notebookId}/preview${n}`)).data}async configure(e){if(e.mode==="public"){await this.client.delete(`/notebook/${this.notebookId}/preview`);return}await this.client.put(`/notebook/${this.notebookId}/preview`,e)}async createSession(e){return(await this.client.post(`/notebook/${this.notebookId}/preview/session`,e)).data}async createHandoff(e){return(await this.client.post(`/notebook/${this.notebookId}/preview/handoff`,e)).data}},Bl=class{constructor(e,n){this.client=e;this.notebookId=n}async status(){return(await this.client.get(`/notebook/${this.notebookId}/mail`)).data}async capture(e){return(await this.client.post(`/notebook/${this.notebookId}/mails`,e)).data}async enable(){return(await this.client.put(`/notebook/${this.notebookId}/mail`)).data}async disable(){await this.client.delete(`/notebook/${this.notebookId}/mail`)}async list(e={}){return this.client.get(`/notebook/${this.notebookId}/mails${Df(e)}`)}async get(e){return(await this.client.get(`/notebook/${this.notebookId}/mails/${encodeURIComponent(e)}`)).data}async delete(e){await this.client.delete(`/notebook/${this.notebookId}/mails/${encodeURIComponent(e)}`)}};function Df(r){let e=new URLSearchParams;for(let[i,t]of Object.entries(r))(typeof t=="string"||typeof t=="number"||typeof t=="boolean")&&e.set(i,String(t));let n=e.toString();return n===""?"":`?${n}`}export{Ui as AppRuntime,mr as CustomerRuntime,zi as CustomersApi,Yk as DEFAULT_PAYMENT_CALLBACK_PATH,Yi as Feedback,Nr as FeedbackApi,rf as FileChangeFilter,nf as FileChangeType,tf as FileType,Ai as LspConnection,Fr as NotebookInstance,Tf as PHPSandbox,E as PHPSandboxError,fr as PaymentRuntime,Di as PaymentsApi,cl as ProjectCustomers,ll as ProjectPayments,Cr as ProjectPublication,Ar as PublicationApi,Or as PublicationDomains,Ge as PublicationInstance,Be as PublicationResources,Me as PublicationRun,C as RemoteError,R as TransportError,Gb as createPublicationStreamResponse,Km as customerModeSchema,pr as customerSchema,Jb as laravelCloudSetupForRepublish,af as notebookBuiltinServices,Zv as notebookKnownServices,Sv as paymentApplicationsSchema,Ei as paymentModeSchema,Ol as readPublicationStream,Ev as verifyPaymentEvent};
69
69
  /*! Bundled license information:
70
70
 
@@ -20006,8 +20006,12 @@ ${JSON.stringify(metadata, null, 2)}` : "";
20006
20006
  async list() {
20007
20007
  return (await this.client.get(this.path())).data;
20008
20008
  }
20009
- async create(hostname3) {
20010
- return (await this.client.post(this.path(), { hostname: hostname3 })).data;
20009
+ async create(hostname3, options = {}) {
20010
+ return (await this.client.post(this.path(), {
20011
+ hostname: hostname3,
20012
+ cloudflareStrategy: options.cloudflareStrategy,
20013
+ allowDowntime: options.allowDowntime
20014
+ })).data;
20011
20015
  }
20012
20016
  async refresh(id) {
20013
20017
  return (await this.client.post(`${this.path()}/${encodeURIComponent(id)}/refresh`)).data;
@@ -64,7 +64,7 @@
64
64
 
65
65
  Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let a of r.seen.entries()){let s=a[1];if(e===a[0]){o(a);continue}if(r.external){let u=r.external.registry.get(a[0])?.id;if(e!==a[0]&&u){o(a);continue}}if(r.metadataRegistry.get(a[0])?.id){o(a);continue}if(s.cycle){o(a);continue}if(s.count>1&&r.reused==="ref"){o(a);continue}}}function $e(r,e){let n=r.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let i=s=>{let c=r.seen.get(s);if(c.ref===null)return;let u=c.def??c.schema,d={...u},m=c.ref;if(c.ref=null,m){i(m);let g=r.seen.get(m),k=g.schema;if(k.$ref&&(r.target==="draft-07"||r.target==="draft-04"||r.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(k)):Object.assign(u,k),Object.assign(u,d),s._zod.parent===m)for(let P in u)P==="$ref"||P==="allOf"||P in d||delete u[P];if(k.$ref&&g.def)for(let P in u)P==="$ref"||P==="allOf"||P in g.def&&JSON.stringify(u[P])===JSON.stringify(g.def[P])&&delete u[P]}let h=s._zod.parent;if(h&&h!==m){i(h);let g=r.seen.get(h);if(g?.schema.$ref&&(u.$ref=g.schema.$ref,g.def))for(let k in u)k==="$ref"||k==="allOf"||k in g.def&&JSON.stringify(u[k])===JSON.stringify(g.def[k])&&delete u[k]}r.override({zodSchema:s,jsonSchema:u,path:c.path??[]})};for(let s of[...r.seen.entries()].reverse())i(s[0]);let t={};if(r.target==="draft-2020-12"?t.$schema="https://json-schema.org/draft/2020-12/schema":r.target==="draft-07"?t.$schema="http://json-schema.org/draft-07/schema#":r.target==="draft-04"?t.$schema="http://json-schema.org/draft-04/schema#":r.target,r.external?.uri){let s=r.external.registry.get(e)?.id;if(!s)throw new Error("Schema is missing an `id` property");t.$id=r.external.uri(s)}Object.assign(t,n.def??n.schema);let o=r.metadataRegistry.get(e)?.id;o!==void 0&&t.id===o&&delete t.id;let a=r.external?.defs??{};for(let s of r.seen.entries()){let c=s[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,a[c.defId]=c.def)}r.external||Object.keys(a).length>0&&(r.target==="draft-2020-12"?t.$defs=a:t.definitions=a);try{let s=JSON.parse(JSON.stringify(t));return Object.defineProperty(s,"~standard",{value:{...e["~standard"],jsonSchema:{input:ft(e,"input",r.processors),output:ft(e,"output",r.processors)}},enumerable:!1,writable:!1}),s}catch{throw new Error("Error converting schema to JSON.")}}function V(r,e){let n=e??{seen:new Set};if(n.seen.has(r))return!1;n.seen.add(r);let i=r._zod.def;if(i.type==="transform")return!0;if(i.type==="array")return V(i.element,n);if(i.type==="set")return V(i.valueType,n);if(i.type==="lazy")return V(i.getter(),n);if(i.type==="promise"||i.type==="optional"||i.type==="nonoptional"||i.type==="nullable"||i.type==="readonly"||i.type==="default"||i.type==="prefault")return V(i.innerType,n);if(i.type==="intersection")return V(i.left,n)||V(i.right,n);if(i.type==="record"||i.type==="map")return V(i.keyType,n)||V(i.valueType,n);if(i.type==="pipe")return r._zod.traits.has("$ZodCodec")?!0:V(i.in,n)||V(i.out,n);if(i.type==="object"){for(let t in i.shape)if(V(i.shape[t],n))return!0;return!1}if(i.type==="union"){for(let t of i.options)if(V(t,n))return!0;return!1}if(i.type==="tuple"){for(let t of i.items)if(V(t,n))return!0;return!!(i.rest&&V(i.rest,n))}return!1}var hc=(r,e={})=>n=>{let i=xe({...n,processors:e});return z(r,i),ke(i,r),$e(i,r)},ft=(r,e,n={})=>i=>{let{libraryOptions:t,target:o}=i??{},a=xe({...t??{},target:o,io:e,processors:n});return z(r,a),ke(a,r),$e(a,r)};var bv={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},vc=(r,e,n,i)=>{let t=n;t.type="string";let{minimum:o,maximum:a,format:s,patterns:c,contentEncoding:u}=r._zod.bag;if(typeof o=="number"&&(t.minLength=o),typeof a=="number"&&(t.maxLength=a),s&&(t.format=bv[s]??s,t.format===""&&delete t.format,s==="time"&&delete t.format),u&&(t.contentEncoding=u),c&&c.size>0){let d=[...c];d.length===1?t.pattern=d[0].source:d.length>1&&(t.allOf=[...d.map(m=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:m.source}))])}},bc=(r,e,n,i)=>{let t=n,{minimum:o,maximum:a,format:s,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:d}=r._zod.bag;typeof s=="string"&&s.includes("int")?t.type="integer":t.type="number";let m=typeof d=="number"&&d>=(o??Number.NEGATIVE_INFINITY),h=typeof u=="number"&&u<=(a??Number.POSITIVE_INFINITY),g=e.target==="draft-04"||e.target==="openapi-3.0";m?g?(t.minimum=d,t.exclusiveMinimum=!0):t.exclusiveMinimum=d:typeof o=="number"&&(t.minimum=o),h?g?(t.maximum=u,t.exclusiveMaximum=!0):t.exclusiveMaximum=u:typeof a=="number"&&(t.maximum=a),typeof c=="number"&&(t.multipleOf=c)},yc=(r,e,n,i)=>{n.type="boolean"},xc=(r,e,n,i)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},kc=(r,e,n,i)=>{if(e.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},$c=(r,e,n,i)=>{e.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},wc=(r,e,n,i)=>{if(e.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},_c=(r,e,n,i)=>{if(e.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},Sc=(r,e,n,i)=>{n.not={}},Ic=(r,e,n,i)=>{},Pc=(r,e,n,i)=>{},zc=(r,e,n,i)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},Ec=(r,e,n,i)=>{let t=r._zod.def,o=Mt(t.entries);o.every(a=>typeof a=="number")&&(n.type="number"),o.every(a=>typeof a=="string")&&(n.type="string"),n.enum=o},Tc=(r,e,n,i)=>{let t=r._zod.def,o=[];for(let a of t.values)if(a===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof a=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");o.push(Number(a))}else o.push(a);if(o.length!==0)if(o.length===1){let a=o[0];n.type=a===null?"null":typeof a,e.target==="draft-04"||e.target==="openapi-3.0"?n.enum=[a]:n.const=a}else o.every(a=>typeof a=="number")&&(n.type="number"),o.every(a=>typeof a=="string")&&(n.type="string"),o.every(a=>typeof a=="boolean")&&(n.type="boolean"),o.every(a=>a===null)&&(n.type="null"),n.enum=o},Dc=(r,e,n,i)=>{if(e.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},Uc=(r,e,n,i)=>{let t=n,o=r._zod.pattern;if(!o)throw new Error("Pattern not found in template literal");t.type="string",t.pattern=o.source},Rc=(r,e,n,i)=>{let t=n,o={type:"string",format:"binary",contentEncoding:"binary"},{minimum:a,maximum:s,mime:c}=r._zod.bag;a!==void 0&&(o.minLength=a),s!==void 0&&(o.maxLength=s),c?c.length===1?(o.contentMediaType=c[0],Object.assign(t,o)):(Object.assign(t,o),t.anyOf=c.map(u=>({contentMediaType:u}))):Object.assign(t,o)},Oc=(r,e,n,i)=>{n.type="boolean"},Ac=(r,e,n,i)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},Cc=(r,e,n,i)=>{if(e.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},jc=(r,e,n,i)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},Nc=(r,e,n,i)=>{if(e.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},Lc=(r,e,n,i)=>{if(e.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},Zc=(r,e,n,i)=>{let t=n,o=r._zod.def,{minimum:a,maximum:s}=r._zod.bag;typeof a=="number"&&(t.minItems=a),typeof s=="number"&&(t.maxItems=s),t.type="array",t.items=z(o.element,e,{...i,path:[...i.path,"items"]})},Fc=(r,e,n,i)=>{let t=n,o=r._zod.def;t.type="object",t.properties={};let a=o.shape;for(let u in a)t.properties[u]=z(a[u],e,{...i,path:[...i.path,"properties",u]});let s=new Set(Object.keys(a)),c=new Set([...s].filter(u=>{let d=o.shape[u]._zod;return e.io==="input"?d.optin===void 0:d.optout===void 0}));c.size>0&&(t.required=Array.from(c)),o.catchall?._zod.def.type==="never"?t.additionalProperties=!1:o.catchall?o.catchall&&(t.additionalProperties=z(o.catchall,e,{...i,path:[...i.path,"additionalProperties"]})):e.io==="output"&&(t.additionalProperties=!1)},Yn=(r,e,n,i)=>{let t=r._zod.def,o=t.inclusive===!1,a=t.options.map((s,c)=>z(s,e,{...i,path:[...i.path,o?"oneOf":"anyOf",c]}));o?n.oneOf=a:n.anyOf=a},Mc=(r,e,n,i)=>{let t=r._zod.def,o=z(t.left,e,{...i,path:[...i.path,"allOf",0]}),a=z(t.right,e,{...i,path:[...i.path,"allOf",1]}),s=u=>"allOf"in u&&Object.keys(u).length===1,c=[...s(o)?o.allOf:[o],...s(a)?a.allOf:[a]];n.allOf=c},Bc=(r,e,n,i)=>{let t=n,o=r._zod.def;t.type="array";let a=e.target==="draft-2020-12"?"prefixItems":"items",s=e.target==="draft-2020-12"||e.target==="openapi-3.0"?"items":"additionalItems",c=o.items.map((h,g)=>z(h,e,{...i,path:[...i.path,a,g]})),u=o.rest?z(o.rest,e,{...i,path:[...i.path,s,...e.target==="openapi-3.0"?[o.items.length]:[]]}):null;e.target==="draft-2020-12"?(t.prefixItems=c,u&&(t.items=u)):e.target==="openapi-3.0"?(t.items={anyOf:c},u&&t.items.anyOf.push(u),t.minItems=c.length,u||(t.maxItems=c.length)):(t.items=c,u&&(t.additionalItems=u));let{minimum:d,maximum:m}=r._zod.bag;typeof d=="number"&&(t.minItems=d),typeof m=="number"&&(t.maxItems=m)},Gc=(r,e,n,i)=>{let t=n,o=r._zod.def;t.type="object";let a=o.keyType,c=a._zod.bag?.patterns;if(o.mode==="loose"&&c&&c.size>0){let d=z(o.valueType,e,{...i,path:[...i.path,"patternProperties","*"]});t.patternProperties={};for(let m of c)t.patternProperties[m.source]=d}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(t.propertyNames=z(o.keyType,e,{...i,path:[...i.path,"propertyNames"]})),t.additionalProperties=z(o.valueType,e,{...i,path:[...i.path,"additionalProperties"]});let u=a._zod.values;if(u){let d=[...u].filter(m=>typeof m=="string"||typeof m=="number");d.length>0&&(t.required=d)}},Wc=(r,e,n,i)=>{let t=r._zod.def,o=z(t.innerType,e,i),a=e.seen.get(r);e.target==="openapi-3.0"?(a.ref=t.innerType,n.nullable=!0):n.anyOf=[o,{type:"null"}]},Vc=(r,e,n,i)=>{let t=r._zod.def;z(t.innerType,e,i);let o=e.seen.get(r);o.ref=t.innerType},Jc=(r,e,n,i)=>{let t=r._zod.def;z(t.innerType,e,i);let o=e.seen.get(r);o.ref=t.innerType,n.default=JSON.parse(JSON.stringify(t.defaultValue))},Kc=(r,e,n,i)=>{let t=r._zod.def;z(t.innerType,e,i);let o=e.seen.get(r);o.ref=t.innerType,e.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(t.defaultValue)))},qc=(r,e,n,i)=>{let t=r._zod.def;z(t.innerType,e,i);let o=e.seen.get(r);o.ref=t.innerType;let a;try{a=t.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=a},Hc=(r,e,n,i)=>{let t=r._zod.def,o=t.in._zod.traits.has("$ZodTransform"),a=e.io==="input"?o?t.out:t.in:t.out;z(a,e,i);let s=e.seen.get(r);s.ref=a},Xc=(r,e,n,i)=>{let t=r._zod.def;z(t.innerType,e,i);let o=e.seen.get(r);o.ref=t.innerType,n.readOnly=!0},Yc=(r,e,n,i)=>{let t=r._zod.def;z(t.innerType,e,i);let o=e.seen.get(r);o.ref=t.innerType},Qn=(r,e,n,i)=>{let t=r._zod.def;z(t.innerType,e,i);let o=e.seen.get(r);o.ref=t.innerType},Qc=(r,e,n,i)=>{let t=r._zod.innerType;z(t,e,i);let o=e.seen.get(r);o.ref=t},Xn={string:vc,number:bc,boolean:yc,bigint:xc,symbol:kc,null:$c,undefined:wc,void:_c,never:Sc,any:Ic,unknown:Pc,date:zc,enum:Ec,literal:Tc,nan:Dc,template_literal:Uc,file:Rc,success:Oc,custom:Ac,function:Cc,transform:jc,map:Nc,set:Lc,array:Zc,object:Fc,union:Yn,intersection:Mc,tuple:Bc,record:Gc,nullable:Wc,nonoptional:Vc,default:Jc,prefault:Kc,catch:qc,pipe:Hc,readonly:Xc,promise:Yc,optional:Qn,lazy:Qc};function ei(r,e){if("_idmap"in r){let i=r,t=xe({...e,processors:Xn}),o={};for(let c of i._idmap.entries()){let[u,d]=c;z(d,t)}let a={},s={registry:i,uri:e?.uri,defs:o};t.external=s;for(let c of i._idmap.entries()){let[u,d]=c;ke(t,d),a[u]=$e(t,d)}if(Object.keys(o).length>0){let c=t.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[c]:o}}return{schemas:a}}let n=xe({...e,processors:Xn});return z(r,n),ke(n,r),$e(n,r)}var ti=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(e){this.ctx.counter=e}get seen(){return this.ctx.seen}constructor(e){let n=e?.target??"draft-2020-12";n==="draft-4"&&(n="draft-04"),n==="draft-7"&&(n="draft-07"),this.ctx=xe({processors:Xn,target:n,...e?.metadata&&{metadata:e.metadata},...e?.unrepresentable&&{unrepresentable:e.unrepresentable},...e?.override&&{override:e.override},...e?.io&&{io:e.io}})}process(e,n={path:[],schemaPath:[]}){return z(e,this.ctx,n)}emit(e,n){n&&(n.cycles&&(this.ctx.cycles=n.cycles),n.reused&&(this.ctx.reused=n.reused),n.external&&(this.ctx.external=n.external)),ke(this.ctx,e);let i=$e(this.ctx,e),{"~standard":t,...o}=i;return o}};var Rp={};var ar={};te(ar,{ZodAny:()=>wu,ZodArray:()=>Pu,ZodBase64:()=>$i,ZodBase64URL:()=>wi,ZodBigInt:()=>$t,ZodBigIntFormat:()=>Ii,ZodBoolean:()=>kt,ZodCIDRv4:()=>xi,ZodCIDRv6:()=>ki,ZodCUID:()=>mi,ZodCUID2:()=>fi,ZodCatch:()=>qu,ZodCodec:()=>br,ZodCustom:()=>yr,ZodCustomStringFormat:()=>yt,ZodDate:()=>mr,ZodDefault:()=>Bu,ZodDiscriminatedUnion:()=>Eu,ZodE164:()=>_i,ZodEmail:()=>li,ZodEmoji:()=>di,ZodEnum:()=>vt,ZodExactOptional:()=>Zu,ZodFile:()=>Nu,ZodFunction:()=>ol,ZodGUID:()=>cr,ZodIPv4:()=>bi,ZodIPv6:()=>yi,ZodIntersection:()=>Tu,ZodJWT:()=>Si,ZodKSUID:()=>vi,ZodLazy:()=>rl,ZodLiteral:()=>ju,ZodMAC:()=>hu,ZodMap:()=>Au,ZodNaN:()=>Xu,ZodNanoID:()=>pi,ZodNever:()=>Su,ZodNonOptional:()=>Ui,ZodNull:()=>ku,ZodNullable:()=>Mu,ZodNumber:()=>xt,ZodNumberFormat:()=>Le,ZodObject:()=>gr,ZodOptional:()=>Di,ZodPipe:()=>vr,ZodPrefault:()=>Wu,ZodPreprocess:()=>Yu,ZodPromise:()=>il,ZodReadonly:()=>Qu,ZodRecord:()=>ht,ZodSet:()=>Cu,ZodString:()=>bt,ZodStringFormat:()=>D,ZodSuccess:()=>Ku,ZodSymbol:()=>yu,ZodTemplateLiteral:()=>tl,ZodTransform:()=>Lu,ZodTuple:()=>Uu,ZodType:()=>S,ZodULID:()=>gi,ZodURL:()=>pr,ZodUUID:()=>se,ZodUndefined:()=>xu,ZodUnion:()=>hr,ZodUnknown:()=>_u,ZodVoid:()=>Iu,ZodXID:()=>hi,ZodXor:()=>zu,_ZodString:()=>ui,_default:()=>Gu,_function:()=>Mm,any:()=>ym,array:()=>fr,base64:()=>rm,base64url:()=>nm,bigint:()=>fm,boolean:()=>bu,catch:()=>Hu,check:()=>Bm,cidrv4:()=>em,cidrv6:()=>tm,codec:()=>Nm,cuid:()=>Vp,cuid2:()=>Jp,custom:()=>Gm,date:()=>km,describe:()=>Wm,discriminatedUnion:()=>Pm,e164:()=>im,email:()=>Cp,emoji:()=>Gp,enum:()=>Ei,exactOptional:()=>Fu,file:()=>Om,float32:()=>lm,float64:()=>dm,function:()=>Mm,guid:()=>jp,hash:()=>um,hex:()=>cm,hostname:()=>sm,httpUrl:()=>Bp,instanceof:()=>Jm,int:()=>si,int32:()=>pm,int64:()=>gm,intersection:()=>Du,invertCodec:()=>Lm,ipv4:()=>Xp,ipv6:()=>Qp,json:()=>qm,jwt:()=>om,keyof:()=>$m,ksuid:()=>Hp,lazy:()=>nl,literal:()=>Rm,looseObject:()=>Sm,looseRecord:()=>Em,mac:()=>Yp,map:()=>Tm,meta:()=>Vm,nan:()=>jm,nanoid:()=>Wp,nativeEnum:()=>Um,never:()=>Pi,nonoptional:()=>Ju,null:()=>$u,nullable:()=>lr,nullish:()=>Am,number:()=>vu,object:()=>wm,optional:()=>ur,partialRecord:()=>zm,pipe:()=>ci,prefault:()=>Vu,preprocess:()=>Hm,promise:()=>Fm,readonly:()=>el,record:()=>Ou,refine:()=>al,set:()=>Dm,strictObject:()=>_m,string:()=>sr,stringFormat:()=>am,stringbool:()=>Km,success:()=>Cm,superRefine:()=>sl,symbol:()=>vm,templateLiteral:()=>Zm,transform:()=>Ti,tuple:()=>Ru,uint32:()=>mm,uint64:()=>hm,ulid:()=>Kp,undefined:()=>bm,union:()=>zi,unknown:()=>Ne,url:()=>Mp,uuid:()=>Np,uuidv4:()=>Lp,uuidv6:()=>Zp,uuidv7:()=>Fp,void:()=>xm,xid:()=>qp,xor:()=>Im});var ri={};te(ri,{endsWith:()=>at,gt:()=>oe,gte:()=>W,includes:()=>it,length:()=>je,lowercase:()=>rt,lt:()=>ie,lte:()=>Y,maxLength:()=>Ce,maxSize:()=>ye,mime:()=>st,minLength:()=>ue,minSize:()=>ae,multipleOf:()=>be,negative:()=>Jn,nonnegative:()=>qn,nonpositive:()=>Kn,normalize:()=>ct,overwrite:()=>ne,positive:()=>Vn,property:()=>Hn,regex:()=>tt,size:()=>Ae,slugify:()=>pt,startsWith:()=>ot,toLowerCase:()=>lt,toUpperCase:()=>dt,trim:()=>ut,uppercase:()=>nt});var gt={};te(gt,{ZodISODate:()=>ii,ZodISODateTime:()=>ni,ZodISODuration:()=>ai,ZodISOTime:()=>oi,date:()=>tu,datetime:()=>eu,duration:()=>nu,time:()=>ru});var ni=p("ZodISODateTime",(r,e)=>{Da.init(r,e),D.init(r,e)});function eu(r){return As(ni,r)}var ii=p("ZodISODate",(r,e)=>{Ua.init(r,e),D.init(r,e)});function tu(r){return Cs(ii,r)}var oi=p("ZodISOTime",(r,e)=>{Ra.init(r,e),D.init(r,e)});function ru(r){return js(oi,r)}var ai=p("ZodISODuration",(r,e)=>{Oa.init(r,e),D.init(r,e)});function nu(r){return Ns(ai,r)}var Op=(r,e)=>{Jt.init(r,e),r.name="ZodError",Object.defineProperties(r,{format:{value:n=>qt(r,n)},flatten:{value:n=>Kt(r,n)},addIssue:{value:n=>{r.issues.push(n),r.message=JSON.stringify(r.issues,Ve,2)}},addIssues:{value:n=>{r.issues.push(...n),r.message=JSON.stringify(r.issues,Ve,2)}},isEmpty:{get(){return r.issues.length===0}}})},xv=p("ZodError",Op),q=p("ZodError",Op,{Parent:Error});var iu=qe(q),ou=He(q),au=Xe(q),su=Ye(q),cu=Qr(q),uu=en(q),lu=tn(q),du=rn(q),pu=nn(q),mu=on(q),fu=an(q),gu=sn(q);var Ap=new WeakMap;function dr(r,e,n){let i=Object.getPrototypeOf(r),t=Ap.get(i);if(t||(t=new Set,Ap.set(i,t)),!t.has(e)){t.add(e);for(let o in n){let a=n[o];Object.defineProperty(i,o,{configurable:!0,enumerable:!1,get(){let s=a.bind(this);return Object.defineProperty(this,o,{configurable:!0,writable:!0,enumerable:!0,value:s}),s},set(s){Object.defineProperty(this,o,{configurable:!0,writable:!0,enumerable:!0,value:s})}})}}}var S=p("ZodType",(r,e)=>(_.init(r,e),Object.assign(r["~standard"],{jsonSchema:{input:ft(r,"input"),output:ft(r,"output")}}),r.toJSONSchema=hc(r,{}),r.def=e,r.type=e.type,Object.defineProperty(r,"_def",{value:e}),r.parse=(n,i)=>iu(r,n,i,{callee:r.parse}),r.safeParse=(n,i)=>au(r,n,i),r.parseAsync=async(n,i)=>ou(r,n,i,{callee:r.parseAsync}),r.safeParseAsync=async(n,i)=>su(r,n,i),r.spa=r.safeParseAsync,r.encode=(n,i)=>cu(r,n,i),r.decode=(n,i)=>uu(r,n,i),r.encodeAsync=async(n,i)=>lu(r,n,i),r.decodeAsync=async(n,i)=>du(r,n,i),r.safeEncode=(n,i)=>pu(r,n,i),r.safeDecode=(n,i)=>mu(r,n,i),r.safeEncodeAsync=async(n,i)=>fu(r,n,i),r.safeDecodeAsync=async(n,i)=>gu(r,n,i),dr(r,"ZodType",{check(...n){let i=this.def;return this.clone(y.mergeDefs(i,{checks:[...i.checks??[],...n.map(t=>typeof t=="function"?{_zod:{check:t,def:{check:"custom"},onattach:[]}}:t)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,i){return B(this,n,i)},brand(){return this},register(n,i){return n.add(this,i),this},refine(n,i){return this.check(al(n,i))},superRefine(n,i){return this.check(sl(n,i))},overwrite(n){return this.check(ne(n))},optional(){return ur(this)},exactOptional(){return Fu(this)},nullable(){return lr(this)},nullish(){return ur(lr(this))},nonoptional(n){return Ju(this,n)},array(){return fr(this)},or(n){return zi([this,n])},and(n){return Du(this,n)},transform(n){return ci(this,Ti(n))},default(n){return Gu(this,n)},prefault(n){return Vu(this,n)},catch(n){return Hu(this,n)},pipe(n){return ci(this,n)},readonly(){return el(this)},describe(n){let i=this.clone();return Z.add(i,{description:n}),i},meta(...n){if(n.length===0)return Z.get(this);let i=this.clone();return Z.add(i,n[0]),i},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(r,"description",{get(){return Z.get(r)?.description},configurable:!0}),r)),ui=p("_ZodString",(r,e)=>{Oe.init(r,e),S.init(r,e),r._zod.processJSONSchema=(i,t,o)=>vc(r,i,t,o);let n=r._zod.bag;r.format=n.format??null,r.minLength=n.minimum??null,r.maxLength=n.maximum??null,dr(r,"_ZodString",{regex(...i){return this.check(tt(...i))},includes(...i){return this.check(it(...i))},startsWith(...i){return this.check(ot(...i))},endsWith(...i){return this.check(at(...i))},min(...i){return this.check(ue(...i))},max(...i){return this.check(Ce(...i))},length(...i){return this.check(je(...i))},nonempty(...i){return this.check(ue(1,...i))},lowercase(i){return this.check(rt(i))},uppercase(i){return this.check(nt(i))},trim(){return this.check(ut())},normalize(...i){return this.check(ct(...i))},toLowerCase(){return this.check(lt())},toUpperCase(){return this.check(dt())},slugify(){return this.check(pt())}})}),bt=p("ZodString",(r,e)=>{Oe.init(r,e),ui.init(r,e),r.email=n=>r.check(In(li,n)),r.url=n=>r.check(or(pr,n)),r.jwt=n=>r.check(Wn(Si,n)),r.emoji=n=>r.check(Dn(di,n)),r.guid=n=>r.check(ir(cr,n)),r.uuid=n=>r.check(Pn(se,n)),r.uuidv4=n=>r.check(zn(se,n)),r.uuidv6=n=>r.check(En(se,n)),r.uuidv7=n=>r.check(Tn(se,n)),r.nanoid=n=>r.check(Un(pi,n)),r.guid=n=>r.check(ir(cr,n)),r.cuid=n=>r.check(Rn(mi,n)),r.cuid2=n=>r.check(On(fi,n)),r.ulid=n=>r.check(An(gi,n)),r.base64=n=>r.check(Mn($i,n)),r.base64url=n=>r.check(Bn(wi,n)),r.xid=n=>r.check(Cn(hi,n)),r.ksuid=n=>r.check(jn(vi,n)),r.ipv4=n=>r.check(Nn(bi,n)),r.ipv6=n=>r.check(Ln(yi,n)),r.cidrv4=n=>r.check(Zn(xi,n)),r.cidrv6=n=>r.check(Fn(ki,n)),r.e164=n=>r.check(Gn(_i,n)),r.datetime=n=>r.check(eu(n)),r.date=n=>r.check(tu(n)),r.time=n=>r.check(ru(n)),r.duration=n=>r.check(nu(n))});function sr(r){return Ds(bt,r)}var D=p("ZodStringFormat",(r,e)=>{T.init(r,e),ui.init(r,e)}),li=p("ZodEmail",(r,e)=>{$a.init(r,e),D.init(r,e)});function Cp(r){return In(li,r)}var cr=p("ZodGUID",(r,e)=>{xa.init(r,e),D.init(r,e)});function jp(r){return ir(cr,r)}var se=p("ZodUUID",(r,e)=>{ka.init(r,e),D.init(r,e)});function Np(r){return Pn(se,r)}function Lp(r){return zn(se,r)}function Zp(r){return En(se,r)}function Fp(r){return Tn(se,r)}var pr=p("ZodURL",(r,e)=>{wa.init(r,e),D.init(r,e)});function Mp(r){return or(pr,r)}function Bp(r){return or(pr,{protocol:X.httpProtocol,hostname:X.domain,...y.normalizeParams(r)})}var di=p("ZodEmoji",(r,e)=>{_a.init(r,e),D.init(r,e)});function Gp(r){return Dn(di,r)}var pi=p("ZodNanoID",(r,e)=>{Sa.init(r,e),D.init(r,e)});function Wp(r){return Un(pi,r)}var mi=p("ZodCUID",(r,e)=>{Ia.init(r,e),D.init(r,e)});function Vp(r){return Rn(mi,r)}var fi=p("ZodCUID2",(r,e)=>{Pa.init(r,e),D.init(r,e)});function Jp(r){return On(fi,r)}var gi=p("ZodULID",(r,e)=>{za.init(r,e),D.init(r,e)});function Kp(r){return An(gi,r)}var hi=p("ZodXID",(r,e)=>{Ea.init(r,e),D.init(r,e)});function qp(r){return Cn(hi,r)}var vi=p("ZodKSUID",(r,e)=>{Ta.init(r,e),D.init(r,e)});function Hp(r){return jn(vi,r)}var bi=p("ZodIPv4",(r,e)=>{Aa.init(r,e),D.init(r,e)});function Xp(r){return Nn(bi,r)}var hu=p("ZodMAC",(r,e)=>{ja.init(r,e),D.init(r,e)});function Yp(r){return Rs(hu,r)}var yi=p("ZodIPv6",(r,e)=>{Ca.init(r,e),D.init(r,e)});function Qp(r){return Ln(yi,r)}var xi=p("ZodCIDRv4",(r,e)=>{Na.init(r,e),D.init(r,e)});function em(r){return Zn(xi,r)}var ki=p("ZodCIDRv6",(r,e)=>{La.init(r,e),D.init(r,e)});function tm(r){return Fn(ki,r)}var $i=p("ZodBase64",(r,e)=>{Fa.init(r,e),D.init(r,e)});function rm(r){return Mn($i,r)}var wi=p("ZodBase64URL",(r,e)=>{Ma.init(r,e),D.init(r,e)});function nm(r){return Bn(wi,r)}var _i=p("ZodE164",(r,e)=>{Ba.init(r,e),D.init(r,e)});function im(r){return Gn(_i,r)}var Si=p("ZodJWT",(r,e)=>{Ga.init(r,e),D.init(r,e)});function om(r){return Wn(Si,r)}var yt=p("ZodCustomStringFormat",(r,e)=>{Wa.init(r,e),D.init(r,e)});function am(r,e,n={}){return mt(yt,r,e,n)}function sm(r){return mt(yt,"hostname",X.hostname,r)}function cm(r){return mt(yt,"hex",X.hex,r)}function um(r,e){let n=e?.enc??"hex",i=`${r}_${n}`,t=X[i];if(!t)throw new Error(`Unrecognized hash format: ${i}`);return mt(yt,i,t,e)}var xt=p("ZodNumber",(r,e)=>{hn.init(r,e),S.init(r,e),r._zod.processJSONSchema=(i,t,o)=>bc(r,i,t,o),dr(r,"ZodNumber",{gt(i,t){return this.check(oe(i,t))},gte(i,t){return this.check(W(i,t))},min(i,t){return this.check(W(i,t))},lt(i,t){return this.check(ie(i,t))},lte(i,t){return this.check(Y(i,t))},max(i,t){return this.check(Y(i,t))},int(i){return this.check(si(i))},safe(i){return this.check(si(i))},positive(i){return this.check(oe(0,i))},nonnegative(i){return this.check(W(0,i))},negative(i){return this.check(ie(0,i))},nonpositive(i){return this.check(Y(0,i))},multipleOf(i,t){return this.check(be(i,t))},step(i,t){return this.check(be(i,t))},finite(){return this}});let n=r._zod.bag;r.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,r.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,r.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),r.isFinite=!0,r.format=n.format??null});function vu(r){return Ls(xt,r)}var Le=p("ZodNumberFormat",(r,e)=>{Va.init(r,e),xt.init(r,e)});function si(r){return Fs(Le,r)}function lm(r){return Ms(Le,r)}function dm(r){return Bs(Le,r)}function pm(r){return Gs(Le,r)}function mm(r){return Ws(Le,r)}var kt=p("ZodBoolean",(r,e)=>{Qt.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>yc(r,n,i,t)});function bu(r){return Vs(kt,r)}var $t=p("ZodBigInt",(r,e)=>{vn.init(r,e),S.init(r,e),r._zod.processJSONSchema=(i,t,o)=>xc(r,i,t,o),r.gte=(i,t)=>r.check(W(i,t)),r.min=(i,t)=>r.check(W(i,t)),r.gt=(i,t)=>r.check(oe(i,t)),r.gte=(i,t)=>r.check(W(i,t)),r.min=(i,t)=>r.check(W(i,t)),r.lt=(i,t)=>r.check(ie(i,t)),r.lte=(i,t)=>r.check(Y(i,t)),r.max=(i,t)=>r.check(Y(i,t)),r.positive=i=>r.check(oe(BigInt(0),i)),r.negative=i=>r.check(ie(BigInt(0),i)),r.nonpositive=i=>r.check(Y(BigInt(0),i)),r.nonnegative=i=>r.check(W(BigInt(0),i)),r.multipleOf=(i,t)=>r.check(be(i,t));let n=r._zod.bag;r.minValue=n.minimum??null,r.maxValue=n.maximum??null,r.format=n.format??null});function fm(r){return Ks($t,r)}var Ii=p("ZodBigIntFormat",(r,e)=>{Ja.init(r,e),$t.init(r,e)});function gm(r){return Hs(Ii,r)}function hm(r){return Xs(Ii,r)}var yu=p("ZodSymbol",(r,e)=>{Ka.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>kc(r,n,i,t)});function vm(r){return Ys(yu,r)}var xu=p("ZodUndefined",(r,e)=>{qa.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>wc(r,n,i,t)});function bm(r){return Qs(xu,r)}var ku=p("ZodNull",(r,e)=>{Ha.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>$c(r,n,i,t)});function $u(r){return ec(ku,r)}var wu=p("ZodAny",(r,e)=>{Xa.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Ic(r,n,i,t)});function ym(){return tc(wu)}var _u=p("ZodUnknown",(r,e)=>{Ya.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Pc(r,n,i,t)});function Ne(){return rc(_u)}var Su=p("ZodNever",(r,e)=>{Qa.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Sc(r,n,i,t)});function Pi(r){return nc(Su,r)}var Iu=p("ZodVoid",(r,e)=>{es.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>_c(r,n,i,t)});function xm(r){return ic(Iu,r)}var mr=p("ZodDate",(r,e)=>{ts.init(r,e),S.init(r,e),r._zod.processJSONSchema=(i,t,o)=>zc(r,i,t,o),r.min=(i,t)=>r.check(W(i,t)),r.max=(i,t)=>r.check(Y(i,t));let n=r._zod.bag;r.minDate=n.minimum?new Date(n.minimum):null,r.maxDate=n.maximum?new Date(n.maximum):null});function km(r){return oc(mr,r)}var Pu=p("ZodArray",(r,e)=>{rs.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Zc(r,n,i,t),r.element=e.element,dr(r,"ZodArray",{min(n,i){return this.check(ue(n,i))},nonempty(n){return this.check(ue(1,n))},max(n,i){return this.check(Ce(n,i))},length(n,i){return this.check(je(n,i))},unwrap(){return this.element}})});function fr(r,e){return cc(Pu,r,e)}function $m(r){let e=r._zod.def.shape;return Ei(Object.keys(e))}var gr=p("ZodObject",(r,e)=>{ns.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Fc(r,n,i,t),y.defineLazy(r,"shape",()=>e.shape),dr(r,"ZodObject",{keyof(){return Ei(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:Ne()})},loose(){return this.clone({...this._zod.def,catchall:Ne()})},strict(){return this.clone({...this._zod.def,catchall:Pi()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return y.extend(this,n)},safeExtend(n){return y.safeExtend(this,n)},merge(n){return y.merge(this,n)},pick(n){return y.pick(this,n)},omit(n){return y.omit(this,n)},partial(...n){return y.partial(Di,this,n[0])},required(...n){return y.required(Ui,this,n[0])}})});function wm(r,e){let n={type:"object",shape:r??{},...y.normalizeParams(e)};return new gr(n)}function _m(r,e){return new gr({type:"object",shape:r,catchall:Pi(),...y.normalizeParams(e)})}function Sm(r,e){return new gr({type:"object",shape:r,catchall:Ne(),...y.normalizeParams(e)})}var hr=p("ZodUnion",(r,e)=>{er.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Yn(r,n,i,t),r.options=e.options});function zi(r,e){return new hr({type:"union",options:r,...y.normalizeParams(e)})}var zu=p("ZodXor",(r,e)=>{hr.init(r,e),is.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Yn(r,n,i,t),r.options=e.options});function Im(r,e){return new zu({type:"union",options:r,inclusive:!1,...y.normalizeParams(e)})}var Eu=p("ZodDiscriminatedUnion",(r,e)=>{hr.init(r,e),os.init(r,e)});function Pm(r,e,n){return new Eu({type:"union",options:e,discriminator:r,...y.normalizeParams(n)})}var Tu=p("ZodIntersection",(r,e)=>{as.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Mc(r,n,i,t)});function Du(r,e){return new Tu({type:"intersection",left:r,right:e})}var Uu=p("ZodTuple",(r,e)=>{bn.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Bc(r,n,i,t),r.rest=n=>r.clone({...r._zod.def,rest:n})});function Ru(r,e,n){let i=e instanceof _,t=i?n:e,o=i?e:null;return new Uu({type:"tuple",items:r,rest:o,...y.normalizeParams(t)})}var ht=p("ZodRecord",(r,e)=>{ss.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Gc(r,n,i,t),r.keyType=e.keyType,r.valueType=e.valueType});function Ou(r,e,n){return!e||!e._zod?new ht({type:"record",keyType:sr(),valueType:r,...y.normalizeParams(e)}):new ht({type:"record",keyType:r,valueType:e,...y.normalizeParams(n)})}function zm(r,e,n){let i=B(r);return i._zod.values=void 0,new ht({type:"record",keyType:i,valueType:e,...y.normalizeParams(n)})}function Em(r,e,n){return new ht({type:"record",keyType:r,valueType:e,mode:"loose",...y.normalizeParams(n)})}var Au=p("ZodMap",(r,e)=>{cs.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Nc(r,n,i,t),r.keyType=e.keyType,r.valueType=e.valueType,r.min=(...n)=>r.check(ae(...n)),r.nonempty=n=>r.check(ae(1,n)),r.max=(...n)=>r.check(ye(...n)),r.size=(...n)=>r.check(Ae(...n))});function Tm(r,e,n){return new Au({type:"map",keyType:r,valueType:e,...y.normalizeParams(n)})}var Cu=p("ZodSet",(r,e)=>{us.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Lc(r,n,i,t),r.min=(...n)=>r.check(ae(...n)),r.nonempty=n=>r.check(ae(1,n)),r.max=(...n)=>r.check(ye(...n)),r.size=(...n)=>r.check(Ae(...n))});function Dm(r,e){return new Cu({type:"set",valueType:r,...y.normalizeParams(e)})}var vt=p("ZodEnum",(r,e)=>{ls.init(r,e),S.init(r,e),r._zod.processJSONSchema=(i,t,o)=>Ec(r,i,t,o),r.enum=e.entries,r.options=Object.values(e.entries);let n=new Set(Object.keys(e.entries));r.extract=(i,t)=>{let o={};for(let a of i)if(n.has(a))o[a]=e.entries[a];else throw new Error(`Key ${a} not found in enum`);return new vt({...e,checks:[],...y.normalizeParams(t),entries:o})},r.exclude=(i,t)=>{let o={...e.entries};for(let a of i)if(n.has(a))delete o[a];else throw new Error(`Key ${a} not found in enum`);return new vt({...e,checks:[],...y.normalizeParams(t),entries:o})}});function Ei(r,e){let n=Array.isArray(r)?Object.fromEntries(r.map(i=>[i,i])):r;return new vt({type:"enum",entries:n,...y.normalizeParams(e)})}function Um(r,e){return new vt({type:"enum",entries:r,...y.normalizeParams(e)})}var ju=p("ZodLiteral",(r,e)=>{ds.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Tc(r,n,i,t),r.values=new Set(e.values),Object.defineProperty(r,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function Rm(r,e){return new ju({type:"literal",values:Array.isArray(r)?r:[r],...y.normalizeParams(e)})}var Nu=p("ZodFile",(r,e)=>{ps.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Rc(r,n,i,t),r.min=(n,i)=>r.check(ae(n,i)),r.max=(n,i)=>r.check(ye(n,i)),r.mime=(n,i)=>r.check(st(Array.isArray(n)?n:[n],i))});function Om(r){return uc(Nu,r)}var Lu=p("ZodTransform",(r,e)=>{ms.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>jc(r,n,i,t),r._zod.parse=(n,i)=>{if(i.direction==="backward")throw new me(r.constructor.name);n.addIssue=o=>{if(typeof o=="string")n.issues.push(y.issue(o,n.value,e));else{let a=o;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=n.value),a.inst??(a.inst=r),n.issues.push(y.issue(a))}};let t=e.transform(n.value,n);return t instanceof Promise?t.then(o=>(n.value=o,n.fallback=!0,n)):(n.value=t,n.fallback=!0,n)}});function Ti(r){return new Lu({type:"transform",transform:r})}var Di=p("ZodOptional",(r,e)=>{yn.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Qn(r,n,i,t),r.unwrap=()=>r._zod.def.innerType});function ur(r){return new Di({type:"optional",innerType:r})}var Zu=p("ZodExactOptional",(r,e)=>{fs.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Qn(r,n,i,t),r.unwrap=()=>r._zod.def.innerType});function Fu(r){return new Zu({type:"optional",innerType:r})}var Mu=p("ZodNullable",(r,e)=>{gs.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Wc(r,n,i,t),r.unwrap=()=>r._zod.def.innerType});function lr(r){return new Mu({type:"nullable",innerType:r})}function Am(r){return ur(lr(r))}var Bu=p("ZodDefault",(r,e)=>{hs.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Jc(r,n,i,t),r.unwrap=()=>r._zod.def.innerType,r.removeDefault=r.unwrap});function Gu(r,e){return new Bu({type:"default",innerType:r,get defaultValue(){return typeof e=="function"?e():y.shallowClone(e)}})}var Wu=p("ZodPrefault",(r,e)=>{vs.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Kc(r,n,i,t),r.unwrap=()=>r._zod.def.innerType});function Vu(r,e){return new Wu({type:"prefault",innerType:r,get defaultValue(){return typeof e=="function"?e():y.shallowClone(e)}})}var Ui=p("ZodNonOptional",(r,e)=>{bs.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Vc(r,n,i,t),r.unwrap=()=>r._zod.def.innerType});function Ju(r,e){return new Ui({type:"nonoptional",innerType:r,...y.normalizeParams(e)})}var Ku=p("ZodSuccess",(r,e)=>{ys.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Oc(r,n,i,t),r.unwrap=()=>r._zod.def.innerType});function Cm(r){return new Ku({type:"success",innerType:r})}var qu=p("ZodCatch",(r,e)=>{xs.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>qc(r,n,i,t),r.unwrap=()=>r._zod.def.innerType,r.removeCatch=r.unwrap});function Hu(r,e){return new qu({type:"catch",innerType:r,catchValue:typeof e=="function"?e:()=>e})}var Xu=p("ZodNaN",(r,e)=>{ks.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Dc(r,n,i,t)});function jm(r){return sc(Xu,r)}var vr=p("ZodPipe",(r,e)=>{xn.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Hc(r,n,i,t),r.in=e.in,r.out=e.out});function ci(r,e){return new vr({type:"pipe",in:r,out:e})}var br=p("ZodCodec",(r,e)=>{vr.init(r,e),tr.init(r,e)});function Nm(r,e,n){return new br({type:"pipe",in:r,out:e,transform:n.decode,reverseTransform:n.encode})}function Lm(r){let e=r._zod.def;return new br({type:"pipe",in:e.out,out:e.in,transform:e.reverseTransform,reverseTransform:e.transform})}var Yu=p("ZodPreprocess",(r,e)=>{vr.init(r,e),$s.init(r,e)}),Qu=p("ZodReadonly",(r,e)=>{ws.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Xc(r,n,i,t),r.unwrap=()=>r._zod.def.innerType});function el(r){return new Qu({type:"readonly",innerType:r})}var tl=p("ZodTemplateLiteral",(r,e)=>{_s.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Uc(r,n,i,t)});function Zm(r,e){return new tl({type:"template_literal",parts:r,...y.normalizeParams(e)})}var rl=p("ZodLazy",(r,e)=>{Ps.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Qc(r,n,i,t),r.unwrap=()=>r._zod.def.getter()});function nl(r){return new rl({type:"lazy",getter:r})}var il=p("ZodPromise",(r,e)=>{Is.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Yc(r,n,i,t),r.unwrap=()=>r._zod.def.innerType});function Fm(r){return new il({type:"promise",innerType:r})}var ol=p("ZodFunction",(r,e)=>{Ss.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Cc(r,n,i,t)});function Mm(r){return new ol({type:"function",input:Array.isArray(r?.input)?Ru(r?.input):r?.input??fr(Ne()),output:r?.output??Ne()})}var yr=p("ZodCustom",(r,e)=>{zs.init(r,e),S.init(r,e),r._zod.processJSONSchema=(n,i,t)=>Ac(r,n,i,t)});function Bm(r){let e=new R({check:"custom"});return e._zod.check=r,e}function Gm(r,e){return lc(yr,r??(()=>!0),e)}function al(r,e={}){return dc(yr,r,e)}function sl(r,e){return pc(r,e)}var Wm=mc,Vm=fc;function Jm(r,e={}){let n=new yr({type:"custom",check:"custom",fn:i=>i instanceof r,abort:!0,...y.normalizeParams(e)});return n._zod.bag.Class=r,n._zod.check=i=>{i.value instanceof r||i.issues.push({code:"invalid_type",expected:r.name,input:i.value,inst:n,path:[...n._zod.def.path??[]]})},n}var Km=(...r)=>gc({Codec:br,Boolean:kt,String:bt},...r);function qm(r){let e=nl(()=>zi([sr(r),vu(),bu(),$u(),fr(e),Ou(sr(),e)]));return e}function Hm(r,e){return new Yu({type:"pipe",in:Ti(r),out:e})}var $v={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function wv(r){A({customError:r})}function _v(){return A().customError}var cl;cl||(cl={});var $={...ar,...ri,iso:gt},Sv=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function Iv(r,e){let n=r.$schema;return n==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":n==="http://json-schema.org/draft-07/schema#"?"draft-7":n==="http://json-schema.org/draft-04/schema#"?"draft-4":e??"draft-2020-12"}function Pv(r,e){if(!r.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let n=r.slice(1).split("/").filter(Boolean);if(n.length===0)return e.rootSchema;let i=e.version==="draft-2020-12"?"$defs":"definitions";if(n[0]===i){let t=n[1];if(!t||!e.defs[t])throw new Error(`Reference not found: ${r}`);return e.defs[t]}throw new Error(`Reference not found: ${r}`)}function Xm(r,e){if(r.not!==void 0){if(typeof r.not=="object"&&Object.keys(r.not).length===0)return $.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(r.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(r.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(r.if!==void 0||r.then!==void 0||r.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(r.dependentSchemas!==void 0||r.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(r.$ref){let t=r.$ref;if(e.refs.has(t))return e.refs.get(t);if(e.processing.has(t))return $.lazy(()=>{if(!e.refs.has(t))throw new Error(`Circular reference not resolved: ${t}`);return e.refs.get(t)});e.processing.add(t);let o=Pv(t,e),a=M(o,e);return e.refs.set(t,a),e.processing.delete(t),a}if(r.enum!==void 0){let t=r.enum;if(e.version==="openapi-3.0"&&r.nullable===!0&&t.length===1&&t[0]===null)return $.null();if(t.length===0)return $.never();if(t.length===1)return $.literal(t[0]);if(t.every(a=>typeof a=="string"))return $.enum(t);let o=t.map(a=>$.literal(a));return o.length<2?o[0]:$.union([o[0],o[1],...o.slice(2)])}if(r.const!==void 0)return $.literal(r.const);let n=r.type;if(Array.isArray(n)){let t=n.map(o=>{let a={...r,type:o};return Xm(a,e)});return t.length===0?$.never():t.length===1?t[0]:$.union(t)}if(!n)return $.any();let i;switch(n){case"string":{let t=$.string();if(r.format){let o=r.format;o==="email"?t=t.check($.email()):o==="uri"||o==="uri-reference"?t=t.check($.url()):o==="uuid"||o==="guid"?t=t.check($.uuid()):o==="date-time"?t=t.check($.iso.datetime()):o==="date"?t=t.check($.iso.date()):o==="time"?t=t.check($.iso.time()):o==="duration"?t=t.check($.iso.duration()):o==="ipv4"?t=t.check($.ipv4()):o==="ipv6"?t=t.check($.ipv6()):o==="mac"?t=t.check($.mac()):o==="cidr"?t=t.check($.cidrv4()):o==="cidr-v6"?t=t.check($.cidrv6()):o==="base64"?t=t.check($.base64()):o==="base64url"?t=t.check($.base64url()):o==="e164"?t=t.check($.e164()):o==="jwt"?t=t.check($.jwt()):o==="emoji"?t=t.check($.emoji()):o==="nanoid"?t=t.check($.nanoid()):o==="cuid"?t=t.check($.cuid()):o==="cuid2"?t=t.check($.cuid2()):o==="ulid"?t=t.check($.ulid()):o==="xid"?t=t.check($.xid()):o==="ksuid"&&(t=t.check($.ksuid()))}typeof r.minLength=="number"&&(t=t.min(r.minLength)),typeof r.maxLength=="number"&&(t=t.max(r.maxLength)),r.pattern&&(t=t.regex(new RegExp(r.pattern))),i=t;break}case"number":case"integer":{let t=n==="integer"?$.number().int():$.number();typeof r.minimum=="number"&&(t=t.min(r.minimum)),typeof r.maximum=="number"&&(t=t.max(r.maximum)),typeof r.exclusiveMinimum=="number"?t=t.gt(r.exclusiveMinimum):r.exclusiveMinimum===!0&&typeof r.minimum=="number"&&(t=t.gt(r.minimum)),typeof r.exclusiveMaximum=="number"?t=t.lt(r.exclusiveMaximum):r.exclusiveMaximum===!0&&typeof r.maximum=="number"&&(t=t.lt(r.maximum)),typeof r.multipleOf=="number"&&(t=t.multipleOf(r.multipleOf)),i=t;break}case"boolean":{i=$.boolean();break}case"null":{i=$.null();break}case"object":{let t={},o=r.properties||{},a=new Set(r.required||[]);for(let[c,u]of Object.entries(o)){let d=M(u,e);t[c]=a.has(c)?d:d.optional()}if(r.propertyNames){let c=M(r.propertyNames,e),u=r.additionalProperties&&typeof r.additionalProperties=="object"?M(r.additionalProperties,e):$.any();if(Object.keys(t).length===0){i=$.record(c,u);break}let d=$.object(t).passthrough(),m=$.looseRecord(c,u);i=$.intersection(d,m);break}if(r.patternProperties){let c=r.patternProperties,u=Object.keys(c),d=[];for(let h of u){let g=M(c[h],e),k=$.string().regex(new RegExp(h));d.push($.looseRecord(k,g))}let m=[];if(Object.keys(t).length>0&&m.push($.object(t).passthrough()),m.push(...d),m.length===0)i=$.object({}).passthrough();else if(m.length===1)i=m[0];else{let h=$.intersection(m[0],m[1]);for(let g=2;g<m.length;g++)h=$.intersection(h,m[g]);i=h}break}let s=$.object(t);r.additionalProperties===!1?i=s.strict():typeof r.additionalProperties=="object"?i=s.catchall(M(r.additionalProperties,e)):i=s.passthrough();break}case"array":{let t=r.prefixItems,o=r.items;if(t&&Array.isArray(t)){let a=t.map(c=>M(c,e)),s=o&&typeof o=="object"&&!Array.isArray(o)?M(o,e):void 0;s?i=$.tuple(a).rest(s):i=$.tuple(a),typeof r.minItems=="number"&&(i=i.check($.minLength(r.minItems))),typeof r.maxItems=="number"&&(i=i.check($.maxLength(r.maxItems)))}else if(Array.isArray(o)){let a=o.map(c=>M(c,e)),s=r.additionalItems&&typeof r.additionalItems=="object"?M(r.additionalItems,e):void 0;s?i=$.tuple(a).rest(s):i=$.tuple(a),typeof r.minItems=="number"&&(i=i.check($.minLength(r.minItems))),typeof r.maxItems=="number"&&(i=i.check($.maxLength(r.maxItems)))}else if(o!==void 0){let a=M(o,e),s=$.array(a);typeof r.minItems=="number"&&(s=s.min(r.minItems)),typeof r.maxItems=="number"&&(s=s.max(r.maxItems)),i=s}else i=$.array($.any());break}default:throw new Error(`Unsupported type: ${n}`)}return i}function M(r,e){if(typeof r=="boolean")return r?$.any():$.never();let n=Xm(r,e),i=r.type||r.enum!==void 0||r.const!==void 0;if(r.anyOf&&Array.isArray(r.anyOf)){let s=r.anyOf.map(u=>M(u,e)),c=$.union(s);n=i?$.intersection(n,c):c}if(r.oneOf&&Array.isArray(r.oneOf)){let s=r.oneOf.map(u=>M(u,e)),c=$.xor(s);n=i?$.intersection(n,c):c}if(r.allOf&&Array.isArray(r.allOf))if(r.allOf.length===0)n=i?n:$.any();else{let s=i?n:M(r.allOf[0],e),c=i?0:1;for(let u=c;u<r.allOf.length;u++)s=$.intersection(s,M(r.allOf[u],e));n=s}r.nullable===!0&&e.version==="openapi-3.0"&&(n=$.nullable(n)),r.readOnly===!0&&(n=$.readonly(n)),r.default!==void 0&&(n=n.default(r.default));let t={},o=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let s of o)s in r&&(t[s]=r[s]);let a=["contentEncoding","contentMediaType","contentSchema"];for(let s of a)s in r&&(t[s]=r[s]);for(let s of Object.keys(r))Sv.has(s)||(t[s]=r[s]);return Object.keys(t).length>0&&e.registry.add(n,t),r.description&&(n=n.describe(r.description)),n}function Ym(r,e){if(typeof r=="boolean")return r?$.any():$.never();let n;try{n=JSON.parse(JSON.stringify(r))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let i=Iv(n,e?.defaultTarget),t=n.$defs||n.definitions||{},o={version:i,defs:t,refs:new Map,processing:new Set,rootSchema:n,registry:e?.registry??Z};return M(n,o)}var ul={};te(ul,{bigint:()=>Dv,boolean:()=>Tv,date:()=>Uv,number:()=>Ev,string:()=>zv});function zv(r){return Us(bt,r)}function Ev(r){return Zs(xt,r)}function Tv(r){return Js(kt,r)}function Dv(r){return qs($t,r)}function Uv(r){return ac(mr,r)}A(kn());var Ri=l.string().trim().min(1).max(100),ll=l.object({funnel:l.object({title:l.string().trim().min(1).max(100),stages:l.array(l.discriminatedUnion("measure",[l.object({id:l.string().regex(/^[a-zA-Z0-9_-]+$/).max(50),label:l.string().trim().min(1).max(100),measure:l.literal("event"),event:Ri}),l.object({id:l.string().regex(/^[a-zA-Z0-9_-]+$/).max(50),label:l.string().trim().min(1).max(100),measure:l.literal("first_payment")}),l.object({id:l.string().regex(/^[a-zA-Z0-9_-]+$/).max(50),label:l.string().trim().min(1).max(100),measure:l.literal("event_after_payment"),event:Ri})])).max(12)}).nullable(),followUp:l.object({label:l.string().trim().min(1).max(100),triggerEvent:Ri,prerequisiteEvent:Ri.nullable(),stopOnPayment:l.boolean()}).nullable()}),pl=l.enum(["test","live"]),wt=l.object({id:l.string(),externalId:l.string(),email:l.string(),name:l.string().nullable(),source:l.string().nullable(),marketingSubscribed:l.boolean(),communicationBasis:l.enum(["unknown","legacy_account","explicit_opt_in","unsubscribed"]).optional(),legacyPolicy:l.string().nullable().optional(),joinedAt:l.string().nullable().optional(),importedAt:l.string().nullable().optional(),lastActiveAt:l.string().nullable().optional(),billingStatus:l.enum(["unknown","free","paid"]).optional(),suppressionReason:l.string().nullable(),activatedAt:l.string().nullable(),createdAt:l.string().nullable()}),we=l.object({id:l.string(),mode:pl,enabled:l.boolean(),senderName:l.string().nullable(),senderEmail:l.string().nullable(),replyTo:l.string().nullable(),senderVerified:l.boolean(),domainRecords:l.string().nullable(),configuration:ll.optional(),emailTemplate:l.string().nullable().optional(),provisionedAt:l.string().nullable().optional(),lastRequestAt:l.string().nullable().optional(),processedAt:l.string().nullable().optional()}),Qm=l.object({enabled:l.boolean(),subject:l.string(),body:l.string(),delayMinutes:l.number(),activationEvent:l.string()}),tf=Qm.extend({kind:l.enum(["welcome","setup","purchase","credit_limit"]),version:l.number().int().optional(),startsAt:l.string().nullable().optional(),draft:Qm.nullable().optional()}),dl=l.object({id:l.string(),customerId:l.string().nullable(),recipient:l.string(),subject:l.string(),body:l.string(),status:l.string(),error:l.string().nullable(),dueAt:l.string().nullable().optional(),attemptedAt:l.string().nullable().optional(),receivedAt:l.string().nullable().optional(),journeyKind:l.enum(["welcome","setup","purchase","credit_limit"]).nullable().optional(),journeyVersion:l.number().int().nullable().optional(),category:l.enum(["marketing","service"]).optional(),from:l.string().nullable().optional(),replyTo:l.string().nullable().optional(),renderedText:l.string().nullable().optional(),renderedHtml:l.string().nullable().optional(),unsubscribeUrl:l.string().nullable().optional(),createdAt:l.string().nullable()}),Rv=l.object({funnel:l.object({title:l.string(),stages:l.array(l.object({id:l.string(),label:l.string(),count:l.number()}))}).nullable().optional(),space:we.nullable(),customers:l.array(wt),journeys:l.array(tf),messages:l.array(dl),total:l.number(),messageTotal:l.number().optional(),events:l.array(l.string()).optional()}),ef=l.object({id:l.string(),externalId:l.string(),name:l.string(),ownerCustomerId:l.string(),firstPaidAt:l.string().nullable(),activatedAt:l.string().nullable()}),_t=class{constructor(e){this.client=e}async configure(e){let n=ll.parse(e);return ll.parse((await this.client.put("/platform/customers/runtime/configuration",{...n,...e.emailTemplate!==void 0?{emailTemplate:e.emailTemplate}:{}})).data)}async context(){return l.object({id:l.string(),projectId:l.string(),notebookId:l.string(),mode:pl}).parse((await this.client.get("/platform/customers/runtime/context")).data)}async pendingFollowUps(){return l.array(l.object({messageId:l.string(),organizationExternalId:l.string(),actorExternalId:l.string()})).parse((await this.client.get("/platform/customers/runtime/follow-ups")).data)}async resolveFollowUp(e,n){return dl.parse((await this.client.post(`/platform/customers/runtime/follow-ups/${encodeURIComponent(e)}/resolve`,{resolution:n})).data)}async organization(e){return ef.parse((await this.client.put("/platform/customers/runtime/organizations",e)).data)}async confirmPayment(e,n){return ef.parse((await this.client.post(`/platform/customers/runtime/organizations/${encodeURIComponent(e)}/payments`,n)).data)}async identify(e){return wt.parse((await this.client.post("/platform/customers/runtime/identify",e)).data)}async linkIdentity(e,n){return wt.parse((await this.client.post(`/platform/customers/runtime/${encodeURIComponent(e)}/identities`,{externalId:n})).data)}async get(e){return wt.parse((await this.client.get(`/platform/customers/runtime/${encodeURIComponent(e)}`)).data)}async event(e,n){return l.object({id:l.string(),name:l.string()}).parse((await this.client.post(`/platform/customers/runtime/${encodeURIComponent(e)}/events`,n)).data)}async preferences(e,n){return wt.parse((await this.client.put(`/platform/customers/runtime/${encodeURIComponent(e)}/preferences`,n)).data)}async send(e,n){return dl.parse((await this.client.post(`/platform/customers/runtime/${encodeURIComponent(e)}/messages`,n)).data)}},xr=class{constructor(e){this.client=e;this.runtime=new _t(e)}forProject(e){return new Oi(e,this.client)}},Oi=class{constructor(e,n){this.projectId=e;this.client=n}async list(e="test",n={}){return Rv.parse((await this.client.get(`${this.path(e)}?${new URLSearchParams(Object.entries(n).map(([i,t])=>[i,String(t)])).toString()}`)).data)}async connect(e="test"){return we.parse((await this.client.put(this.path(e),{})).data)}async provision(e="test"){return we.parse((await this.client.post(`${this.path(e)}/provision`,{})).data)}async disable(e="test"){return we.parse((await this.client.post(`${this.path(e)}/disable`,{})).data)}async resume(e="test"){return we.parse((await this.client.post(`${this.path(e)}/resume`,{})).data)}async rotate(e="test"){return we.parse((await this.client.post(`${this.path(e)}/rotate`,{})).data)}async sender(e,n="test"){return we.parse((await this.client.put(`${this.path(n)}/sender`,e)).data)}async verifySender(e="test"){return we.parse((await this.client.post(`${this.path(e)}/sender/verify`,{})).data)}async journey(e,n,i="test"){return tf.parse((await this.client.put(`${this.path(i)}/journeys/${e}`,n)).data)}path(e){return`/platform/projects/${encodeURIComponent(this.projectId)}/customers/${e}`}};var Ov="/api/phpsandbox-payments/events",kr=l.enum(["test","live"]),ml=l.object({id:l.string(),mode:kr,chargesEnabled:l.boolean(),payoutsEnabled:l.boolean(),detailsSubmitted:l.boolean(),requirements:l.array(l.string()),disabledReason:l.string().nullable()}),Av=l.object({subscribed:l.boolean(),liveAllowed:l.boolean(),testConfigured:l.boolean(),liveConfigured:l.boolean(),feeBasisPoints:l.number().int().min(0).max(1e4).nullable(),canRead:l.boolean(),canManage:l.boolean(),canRefund:l.boolean(),recoveryEndsAt:l.string().nullable().default(null)}),rf=l.object({notebookId:l.string(),applications:l.array(l.object({id:l.string(),url:l.string().nullable(),healthy:l.boolean(),passwordProtected:l.boolean(),deployedAt:l.string().datetime().nullable()}))}),St=l.object({target:l.enum(["preview","publication"]).optional(),id:l.string(),projectId:l.string(),applicationId:l.string().nullable(),mode:kr,revision:l.number().int(),accountId:l.string(),enabled:l.boolean(),callbackUrl:l.string().nullable(),originUrl:l.string().nullable(),runtimeConfigured:l.boolean()}),Ai=l.object({billingInterval:l.enum(["month","year"]).nullable().default(null),id:l.string(),name:l.string(),amount:l.number().int(),currency:l.string(),bindingId:l.string()}),It=l.object({subscriptionId:l.string().nullable().default(null),periodStart:l.string().datetime({offset:!0}).nullable().default(null),periodEnd:l.string().datetime({offset:!0}).nullable().default(null),id:l.string(),bindingId:l.string(),orderId:l.string(),priceId:l.string(),amount:l.number().int(),currency:l.string(),feeAmount:l.number().int(),revision:l.number().int(),refundedAmount:l.number().int(),status:l.enum(["pending","paid","failed","refunded","partially_refunded"]),checkoutUrl:l.string().nullable(),deliveredAt:l.string().nullable()}),_e=l.object({id:l.string(),bindingId:l.string(),priceId:l.string(),orderId:l.string(),status:l.enum(["pending","incomplete","incomplete_expired","trialing","active","past_due","canceled","unpaid","paused"]),billingInterval:l.enum(["month","year"]),paidThrough:l.string().datetime({offset:!0}).nullable(),cancelAtPeriodEnd:l.boolean(),checkoutUrl:l.string().nullable(),revision:l.number().int()}),nf=l.object({url:l.string().url()}),Cv=It.extend({refund:l.object({id:l.string(),amount:l.number().int().positive(),status:l.enum(["pending","succeeded","failed","canceled","requires_action"])})}),jv=l.object({revision:l.number().int(),reviewId:l.string(),expiresAt:l.string(),blockers:l.array(l.string()),binding:St,account:ml,feeBasisPoints:l.number().int().nullable(),prices:l.array(Ai)}),$r=class{constructor(e){this.client=e;this.runtime=new Pt(e)}forProject(e){return new Ci(e,this.client)}async applications(e){return rf.parse((await this.client.get(`/platform/payments/projects/${encodeURIComponent(e)}/applications`)).data)}async access(){return Av.parse((await this.client.get("/platform/payments/access")).data)}async accounts(){return l.array(ml).parse((await this.client.get("/platform/payments/accounts")).data)}async createAccount(e,n){return ml.parse((await this.client.put(`/platform/payments/accounts/${e}`,{country:n})).data)}async onboarding(e){return l.object({url:l.string().url(),expiresAt:l.string()}).parse((await this.client.post(`/platform/payments/accounts/${e}/onboarding`,{})).data)}},Ci=class{constructor(e,n){this.projectId=e;this.client=n}path(e){return`/platform/payments/projects/${encodeURIComponent(this.projectId)}/${e}`}async get(e="test"){return St.nullable().parse((await this.client.get(this.path(e))).data)}async configure(e,n="test"){return St.parse((await this.client.put(this.path(n),e)).data)}async provision(e="test"){return St.parse((await this.client.post(`${this.path(e)}/provision`,{})).data)}async prices(e="test"){return l.array(Ai).parse((await this.client.get(`${this.path(e)}/prices`)).data)}async createPrice(e,n="test"){return Ai.parse((await this.client.post(`${this.path(n)}/prices`,e)).data)}async prepareActivation(e="test"){return jv.parse((await this.client.post(`${this.path(e)}/activation`,{})).data)}async activate(e,n="test"){return St.parse((await this.client.post(`${this.path(n)}/activate`,{reviewId:e})).data)}async disable(e="test"){return St.parse((await this.client.post(`${this.path(e)}/disable`,{})).data)}async checkout(e,n="test"){return It.parse((await this.client.post(`${this.path(n)}/checkouts`,e)).data)}async subscribe(e,n="test"){return _e.parse((await this.client.post(`${this.path(n)}/subscriptions`,e)).data)}async subscriptions(e="test"){return l.array(_e).parse((await this.client.get(`${this.path(e)}/subscriptions`)).data)}async subscription(e,n="test"){return _e.parse((await this.client.get(`${this.path(n)}/subscriptions/${encodeURIComponent(e)}`)).data)}async cancelSubscription(e,n="test"){return _e.parse((await this.client.post(`${this.path(n)}/subscriptions/${encodeURIComponent(e)}/cancel`,{})).data)}async subscriptionPortal(e,n,i="test"){return nf.parse((await this.client.post(`${this.path(i)}/subscriptions/${encodeURIComponent(e)}/portal`,n)).data)}async transactions(e="test"){return l.array(It).parse((await this.client.get(`${this.path(e)}/transactions`)).data)}async refund(e,n,i="test"){return Cv.parse((await this.client.post(`${this.path(i)}/transactions/${encodeURIComponent(e)}/refund`,n)).data)}},Nv=l.discriminatedUnion("type",[l.object({id:l.string(),type:l.literal("payment.updated"),mode:kr,transaction:It}),l.object({id:l.string(),type:l.literal("subscription.updated"),mode:kr,subscription:_e})]);async function of(r,e,n,i,t=Date.now()){if(!/^(?:hpay|happ)_[a-f0-9]{64}$/.test(n))throw new Error("Invalid application payment credential.");let o=/^t=(\d+),v1=([a-f0-9]{64})$/.exec(e),a=o?.[1],s=o?.[2];if(!a||!s||Math.abs(t-Number(a)*1e3)>3e5||r.length>262144)throw new Error("Invalid or expired payment signature.");let c=new TextEncoder,u=await crypto.subtle.importKey("raw",c.encode(n),{name:"HMAC",hash:"SHA-256"},!1,["verify"]),d=Uint8Array.from(s.match(/../g)??[],h=>Number.parseInt(h,16));if(!await crypto.subtle.verify("HMAC",u,d,c.encode(`${a}.${r}`)))throw new Error("Invalid payment signature.");let m=Nv.parse(JSON.parse(r));if(m.mode!==i)throw new Error("Payment event mode does not match this application.");return m}var Pt=class{constructor(e,n){this.client=e;this.appCredential=n}async verifyEvent(e,n){if(!this.appCredential)throw new Error("Initialize the server app client with PHPSandbox.app() to verify payment events.");return of(e,n,this.appCredential.token,this.appCredential.mode)}async checkout(e){return It.parse((await this.client.post("/platform/payments/runtime/checkouts",e)).data)}async transaction(e){return It.parse((await this.client.get(`/platform/payments/runtime/transactions/${encodeURIComponent(e)}`)).data)}async subscribe(e){return _e.parse((await this.client.post("/platform/payments/runtime/subscriptions",e)).data)}async subscription(e){return _e.parse((await this.client.get(`/platform/payments/runtime/subscriptions/${encodeURIComponent(e)}`)).data)}async cancelSubscription(e){return _e.parse((await this.client.post(`/platform/payments/runtime/subscriptions/${encodeURIComponent(e)}/cancel`,{})).data)}async subscriptionPortal(e,n){return nf.parse((await this.client.post(`/platform/payments/runtime/subscriptions/${encodeURIComponent(e)}/portal`,n)).data)}async prices(){return l.array(Ai).parse((await this.client.get("/platform/payments/runtime/prices")).data)}};function af(r){if(typeof window<"u"&&typeof document<"u")throw new Error("Application credentials must only be used on a trusted server.");let e=r.env??(typeof process>"u"?{}:process.env),n=r.mode??(e.NODE_ENV==="production"?"live":"test"),i=e[`PHPSANDBOX_APP_${n.toUpperCase()}_TOKEN`],t=e.PHPSANDBOX_APP_API_URL;if(!i||!/^happ_[a-f0-9]{64}$/.test(i)||!t)throw new Error(`Connect your app's ${n==="live"?"production":"development"} platform environment before using Customers or Payments.`);return{mode:n,token:i,url:t}}var wr=class{constructor(e,n,i){this.mode=i;this.customers=new _t(e),this.payments=new Pt(e,{token:n,mode:i})}};var sf=l.object({user:l.object({id:l.string(),name:l.string()}).nullable(),organization:l.object({id:l.string(),name:l.string()}),permissions:l.array(l.string())});var Lv=["ActionNotFound","AuthenticationRequired","BadGateway","BadRequest","Conflict","FileAlreadyExists","FileIsDirectory","FileNotDirectory","FileNotFound","FilesystemUnavailable","InternalError","InvalidArgument","InvalidConfiguration","InvalidRequest","InvalidResponse","InvalidServiceCommand","MethodNotAllowed","NotebookInitializationFailed","NotebookUnavailable","NotFound","PayloadTooLarge","PermissionDenied","RateLimited","RequestFailed","RuntimeOperationFailed","ServiceNotFound","ServiceUnavailable","UnprocessableEntity","ValidationFailed","WorkspaceUnavailable"],E=class extends Error{constructor(e,n){super(e),this.name=new.target.name,this.cause=n}},C=class r extends E{constructor(e,n){super(e,n.cause),this.source=n.source,this.status=n.status,this.code=n.code,this.details=n.details}static is(e,n){return e instanceof r&&(n===void 0||e.code===n)}static isValidation(e){return r.is(e,"ValidationFailed")&&Bv(e.details)!==void 0}is(e){return this.code===e}},U=class r extends E{constructor(n,i,t,o){super(n,t);this.code=i;this.response=o}static is(n,i){return n instanceof r&&(i===void 0||n.code===i)}is(n){return this.code===n}};function Ze(r,e,n){let i=fl(e),t=Fv(i?.status),o=cf(i?.code),a=cf(i?.message);if(t===void 0||!Zv(o)||a===void 0)throw new U("PHPSandbox returned an invalid error response.","InvalidResponse",n??e);return new C(a,{source:r,status:t,code:o,details:i?.details,cause:n})}function Zv(r){return typeof r=="string"&&Lv.includes(r)}function Fv(r){return typeof r=="number"&&Number.isInteger(r)&&r>0?r:void 0}function cf(r){return typeof r=="string"&&r.trim()!==""?r.trim():void 0}function fl(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)?r:void 0}function Mv(r){let e=fl(r);if(e===void 0)return;let n=Object.entries(e);if(n.every(([,i])=>Array.isArray(i)&&i.every(t=>typeof t=="string")))return Object.fromEntries(n)}function Bv(r){let e=fl(r),n=Mv(e?.errors);return n===void 0?void 0:{errors:n}}var zt=class extends Error{constructor(n,i){super(n);this.time=i}},_r=class r extends U{constructor(n,i,t){super(n,"SendTimeout",t);this.time=i}static fromPromiseTimeoutError(n){return new r(n.message,n.time,n)}};var uf="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var j=(r=21)=>{let e="",n=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=uf[n[r]&63];return e};var hl=(t=>(t[t.Unknown=0]="Unknown",t[t.File=1]="File",t[t.Directory=2]="Directory",t[t.SymbolicLink=64]="SymbolicLink",t))(hl||{}),vl=(i=>(i[i.UPDATED=2]="UPDATED",i[i.ADDED=4]="ADDED",i[i.DELETED=8]="DELETED",i))(vl||{}),bl=(i=>(i[i.UPDATED=1]="UPDATED",i[i.ADDED=2]="ADDED",i[i.DELETED=3]="DELETED",i))(bl||{}),gl=class{constructor(e,n){this.disposable=e;this.onDispose=n;this.disposed=!1}dispose(){this.disposed||(this.disposed=!0,this.disposable.dispose(),this.onDispose())}},ji=class{constructor(e,n=i=>e.onDidConnect(i)){this.okra=e;this.watches=new Map;this.registerReconnectHandler(n)}registerReconnectHandler(e){e!==null&&e(()=>{for(let{path:n,options:i}of this.watches.values())this.okra.invoke("fs.watch",{path:n,options:i}).catch(()=>{})})}async write(e,n,i={}){let t={overwrite:!0,create:!0,unlock:!1,atomic:!1,...i},o=typeof n=="string"?new TextEncoder().encode(n):n;if(this.okra.runtimeTransport==="rest"){let c=o instanceof Uint8Array?o:await Wv(o);await this.okra.invoke("fs.writeFile",{path:e,contents:c,options:t}).catch(u=>this.handleError(u));return}let a=j(),s=this.okra.invoke("fs.writeStream",{id:a,path:e,options:t});s.catch(()=>{});try{for await(let u of Gv(o))if(!await this.okra.invoke("fs.writeChunk",{id:a,contents:u}))throw new Error(`File write stream ${a} is not available`);if(!await this.okra.invoke("fs.endWrite",{id:a}))throw new Error(`File write stream ${a} could not be completed`);await s}catch(c){throw await this.okra.invoke("fs.abortWrite",{id:a}).catch(()=>!1),await s.catch(()=>!1),c}}async read(e){try{let n=await this.okra.invoke("fs.readFile",{path:e});return n instanceof Uint8Array?n:new TextEncoder().encode(n)}catch(n){this.handleError(n)}}async readText(e){return new TextDecoder().decode(await this.read(e))}async readLines(e,n){try{let i=await this.okra.invoke("fs.readFile",{path:e,lineRange:{lineStart:n.start,lineEnd:n.end}});if(typeof i=="string"||i instanceof Uint8Array)throw new Error(`Unexpected ranged file response for ${e}`);return{start:i.lineStart,end:i.lineEnd,content:i.content,...i.error===null?{}:{warning:i.error}}}catch(i){this.handleError(i)}}readStream(e){if(this.okra.runtimeTransport==="rest")return new ReadableStream({start:async o=>{try{o.enqueue(await this.read(e)),o.close()}catch(a){o.error(a)}}});let n=j(),i=null,t=!1;return new ReadableStream({start:o=>{i=this.okra.listen(`fs.read.${n}`,a=>{o.enqueue(a.data)}),this.okra.invoke("fs.readStream",{id:n,path:e}).then(()=>{t||(t=!0,i?.dispose(),o.close())}).catch(a=>{t||(t=!0,i?.dispose(),o.error(a))})},cancel:async()=>{t||(t=!0,i?.dispose(),await this.okra.invoke("fs.cancelRead",{id:n}).catch(()=>!1))}})}follow(e,n={}){if(this.okra.runtimeTransport==="rest")return new ReadableStream({start(u){u.error(new E("Following files requires the realtime transport."))}});let i=j(),t=null,o=null,a=!1,s=!1,c=async()=>{s||(s=!0,t?.dispose(),t=null,o&&n.signal&&n.signal.removeEventListener("abort",o),o=null,a&&await this.okra.invoke("fs.cancelFollow",{id:i}).catch(()=>!1))};return new ReadableStream({start:u=>{if(t=this.okra.listen(`fs.follow.${i}`,d=>{s||u.enqueue(d.data)}),n.signal){if(o=()=>{c().finally(()=>u.error(n.signal?.reason??new Error("Aborted")))},n.signal.aborted){o();return}n.signal.addEventListener("abort",o,{once:!0})}a=!0,this.okra.invoke("fs.follow",{id:i,path:e,lines:n.lines??10}).then(()=>{s||(s=!0,t?.dispose(),o&&n.signal&&n.signal.removeEventListener("abort",o),o=null,u.close())}).catch(d=>{s||(s=!0,t?.dispose(),o&&n.signal&&n.signal.removeEventListener("abort",o),o=null,u.error(d))})},cancel:c})}find(e,n={useIgnoreFiles:!1,followSymlinks:!1,useGlobalIgnoreFiles:!1,useParentIgnoreFiles:!1}){return this.okra.invoke("fs.find",{query:e,options:{includes:[],excludes:["**/storage","**/vendor","**/node_modules","**/.git","**/.svn","**/.hg","**/CVS","**/.DS_Store","**/Thumbs.db","**/*.crswap"],useIgnoreFiles:!1,followSymlinks:!1,useGlobalIgnoreFiles:!1,useParentIgnoreFiles:!1,...n}})}search(e,n,i){e.id||(e.id=j());let t={maxResults:5,afterContext:2,beforeContext:2,includes:[],excludes:["**/.git","**/.svn","**/.hg","**/CVS","**/.DS_Store","**/Thumbs.db","**/*.crswap","**/node_modules","**/vendor","**/bower_components","**/*.code-search"],useIgnoreFiles:!0,followSymlinks:!0,useGlobalIgnoreFiles:!0,useParentIgnoreFiles:!0,encoding:"utf-8",previewOptions:{matchLines:5,charsPerLine:1e3}},o=e.id,a=async c=>{c===!1&&s.dispose(),i&&await Promise.resolve(i(c))===!1&&s.dispose()},s=this.okra.listen(`fs.text.search.${o}`,a);return this.okra.invoke("fs.textSearch",{query:e,options:{...t,...n}}).finally(()=>s.dispose())}tail(e,n={}){return this.okra.invoke("fs.tail",{path:e,lines:n.lines??10}).then(({content:i})=>i).catch(i=>this.handleError(i))}stat(e){return this.okra.invoke("fs.stat",{path:e}).catch(n=>this.handleError(n))}move(e,n,i={}){return this.okra.invoke("fs.rename",{from:e,to:n,options:{overwrite:!1,...i}}).catch(t=>this.handleError(t))}remove(e,n={}){return this.okra.invoke("fs.delete",{path:e,options:{recursive:!1,useTrash:!1,atomic:!1,...n}}).catch(i=>this.handleError(i))}copy(e,n,i={}){return this.okra.invoke("fs.copy",{source:e,destination:n,options:{overwrite:!1,...i}}).catch(t=>this.handleError(t))}list(e,n={}){return this.okra.invoke("fs.readDirectory",{path:e,include:n.include??[],exclude:n.exclude??[]}).catch(i=>this.handleError(i))}createDirectory(e){return this.okra.invoke("fs.createDirectory",{path:e}).catch(n=>this.handleError(n))}watch(e,n,i){let t=this.okra.listen(`fs.watch.${e}`,i),o={dispose:()=>{t.dispose(),this.okra.invoke("fs.unwatch",{path:e}).catch(()=>{})}},a=new gl(o,()=>{this.watches.get(e)?.onDidChange===i&&this.watches.delete(e)});return this.watches.set(e,{options:n,path:e,onDidChange:i}),this.okra.invoke("fs.watch",{path:e,options:n}).then(()=>a).catch(s=>{throw a.dispose(),s})}exists(e){return this.stat(e).then(()=>!0).catch(()=>!1)}download(e={}){return this.okra.stream("fs.download",{include:e.include,exclude:e.exclude},{abortSignal:e.signal})}tree(e="/"){return this.okra.invoke("fs.tree",{path:e})}handleError(e){throw e}};async function*Gv(r){if(r instanceof Uint8Array){yield r;return}yield*r}async function Wv(r){let e=[],n=0;for await(let o of r)e.push(o),n+=o.byteLength;let i=new Uint8Array(n),t=0;for(let o of e)i.set(o,t),t+=o.byteLength;return i}var lf=(r,e)=>{let n;return Promise.race([r,new Promise((i,t)=>n=setTimeout(t,e,new zt("Timeout before promise can resolve",e)))]).finally(()=>clearTimeout(n))},Ni=r=>{let e=null;return()=>e||(e=r())};var Vv=8,Jv=/[\x00-\x1f\x7f]/,Sr=class{constructor(e){this.okra=e}list(){return this.okra.invoke("terminal.list")}async create(e={}){let n=e.id??j(),i=this.processHandle(n,e.abortSignal),t=typeof e.command=="string"&&e.args?.length?[e.command,...e.args]:e.command,{abortSignal:o,args:a,...s}=e;try{let c=await this.okra.invoke("terminal.create",{...s,id:n,kind:e.kind??"bash",size:e.size??[80,24],command:t},{abortSignal:o});return{...i.process,...c}}catch(c){throw i.dispose(),c}}async attach(e,n){let i=this.processHandle(e,n?.abortSignal);try{let t=await this.okra.invoke("terminal.attach",{id:e,replayHistory:n?.replayHistory},{abortSignal:n?.abortSignal});return t?{...i.process,...t}:(i.dispose(),!1)}catch(t){throw i.dispose(),t}}processHandle(e,n){let i=new Set,t,o=()=>{t&&(n?.removeEventListener("abort",t),t=void 0);for(let F of i)F.dispose();i.clear()},a="",s,c=()=>{if(s&&(clearTimeout(s),s=void 0),a==="")return;let F=a;a="",this.okra.send("terminal.input",{id:e,input:F})},u=()=>{s||(s=setTimeout(c,Vv))},d=F=>{let N=typeof F=="string"?F:new TextDecoder().decode(F);if(a+=N,Jv.test(N)){c();return}u()},m=()=>{c(),o()},h=new WritableStream({write:d,close:m,abort:m}),g=null,k=new ReadableStream({start:F=>{g=F,i.add(this.okra.listen(`terminal.output.${e}`,N=>{g?.enqueue(N.output)}))},cancel:()=>{g=null,m()}}),w=new Promise(F=>{i.add(this.okra.listen(`terminal.close.${e}`,N=>{if(g)try{g.close()}catch{}m(),F(N.exitCode)}))}),P=Ni(()=>(m(),this.okra.invoke("terminal.close",{id:e}))),Nt=F=>this.okra.invoke("terminal.resize",{id:e,width:F.cols,height:F.rows});return n&&!n.aborted&&(t=()=>{P()},n.addEventListener("abort",t,{once:!0})),{process:{wait:()=>w,input:h,output:k,kill:P,resize:Nt},dispose:m}}};var Ir=class{constructor(e){this.okra=e}message(e,n){return this.okra.invoke("lsp.message",{id:e,message:n})}listen(e,n,i){return this.okra.listen(`${n}.${e}`,t=>i(t))}onClose(e,n){return this.listen(e,"lsp.closed",i=>n(i.code,i.reason))}onError(e,n){return this.listen(e,"lsp.error",i=>n(i.message))}onClientDisconnect(e){return this.okra.onDidDisconnect(()=>e(1e3,"OKRA DISCONNECTED"))}onResponse(e,n){return this.listen(e,"lsp.response",i=>n(JSON.stringify(i)))}close(e){return this.okra.invoke("lsp.close",{id:e})}start(e){return this.okra.invoke("lsp.start",{id:e})}connection(e){return Pr.create(e,this)}whenSocketConnected(){return this.okra.connected()}},Pr=class r{constructor(e,n){this.id=e;this.lsp=n}send(e){return this.lsp.message(this.id,e)}onMessage(e){return this.lsp.onResponse(this.id,e)}onError(e){return this.lsp.onError(this.id,e)}onClose(e){return this.lsp.onClose(this.id,e)}dispose(){return this.lsp.close(this.id)}start(){return this.lsp.start(this.id)}onClientDisconnect(e){return this.lsp.onClientDisconnect(e)}whenSocketConnected(){return this.lsp.whenSocketConnected()}static create(e,n){return new r(e,n)}};function Kv(r,e=[],n){let i=Array.isArray(e)?e:[],t=Array.isArray(e)?n:e;return{command:Array.isArray(r)?r:i.length>0?[r,...i]:r,opts:{tty:!1,...t}}}var de=class{constructor(){this.controller=null;this.closed=!1;this.stream=new ReadableStream({start:e=>{this.controller=e},cancel:()=>{this.closed=!0,this.controller=null}})}enqueue(e){this.closed||this.controller?.enqueue(e)}close(){this.closed||(this.closed=!0,this.controller?.close(),this.controller=null)}fail(e){this.closed||(this.closed=!0,this.controller?.error(e),this.controller=null)}},yl=class{constructor(e,n,i,t){this.id=e;this.okra=n;let o=new de,a=new de,s=new de;this.output=o.stream,this.stdout=a.stream,this.stderr=s.stream,this.stdin=new WritableStream({write:async k=>{let w=typeof k=="string"?k:new TextDecoder().decode(k);if(!await this.okra.invoke("shell.input",{id:this.id,input:w}))throw new Error(`Process ${this.id} is not accepting input`)}});let c=new TextEncoder,u=this.okra.listen(`shell.output.${this.id}`,k=>{let w=c.encode(k.output),P=k.source??"output";o.enqueue({source:P,data:w}),P==="stderr"?s.enqueue(w):a.enqueue(w)}),d=()=>{u?.dispose(),u=null,o.close(),a.close(),s.close()},m=k=>{u?.dispose(),u=null,o.fail(k),a.fail(k),s.fail(k)},{abortSignal:h,...g}=t;this.completion=this.okra.invoke("shell.exec",{command:i,opts:{...g,id:this.id}},{abortSignal:h}).then(k=>(d(),k)).catch(k=>{throw m(k),k})}wait(){return this.completion}async kill(){await this.okra.invoke("shell.kill",{id:this.id})}},zr=class{constructor(e){this.okra=e}run(e,n=[],i){let t=Kv(e,n,i),o=t.opts?.id??j();return new yl(o,this.okra,t.command,{...t.opts,id:o})}};var xl=class{constructor(e,n){this.client=e;this.notebookId=n}async set(e){return(await this.client.put(`/notebook/${this.notebookId}/composer/credentials`,e)).data}async remove(e,n){let i=new URLSearchParams({type:e});n&&i.set("url",n),await this.client.delete(`/notebook/${this.notebookId}/composer/credentials?${i.toString()}`)}},kl=class{constructor(e,n,i,t,o){this.id=e;this.okra=n;let a=new de,s=new de,c=new de;this.output=a.stream,this.stdout=s.stream,this.stderr=c.stream;let u=new TextEncoder,d=this.okra.listen(`composer.output.${this.id}`,g=>{let k=u.encode(g.output),w=g.source??"output";a.enqueue({source:w,data:k}),w==="stderr"?c.enqueue(k):s.enqueue(k)}),m=()=>{d?.dispose(),d=null,a.close(),s.close(),c.close()},h=g=>{d?.dispose(),d=null,a.fail(g),s.fail(g),c.fail(g)};this.completion=this.okra.invoke("composer.invoke",{id:e,command:i,args:t,options:o}).then(g=>(m(),g)).catch(g=>{throw h(g),g})}wait(){return this.completion}async kill(){await this.okra.invoke("composer.kill",{id:this.id})}},Er=class{constructor(e,n){this.okra=e;this.credentials=new xl(n,e.data.id)}run(e,n={},i={}){return new kl(j(),this.okra,e,n,i)}packages(){return this.okra.invoke("composer.packages")}};var Li=class{constructor(e){this.okra=e;this.references=new Map;this.synchronization=Promise.resolve();e.runtimeTransport==="realtime"&&e.onDidConnect(()=>{this.references.size>0&&this.synchronize()})}async acquire(e){this.references.set(e,(this.references.get(e)??0)+1);try{await this.synchronize()}catch(i){throw this.removeReference(e),i}let n=!1;return async()=>{n||(n=!0,this.removeReference(e),await this.synchronize())}}removeReference(e){let n=this.references.get(e)??0;n<=1?this.references.delete(e):this.references.set(e,n-1)}synchronize(){return this.synchronization=this.synchronization.catch(()=>{}).then(async()=>{let e=Array.from(this.references.keys());e.length===0?await this.okra.invoke("container.stop-telemetry"):await this.okra.invoke("container.stream-telemetry",{features:e})}),this.synchronization}};function Et(r,e,n,i,t,o={}){let a=null,s=null,c=!1,u=null,d=async()=>{c||(c=!0,a?.dispose(),a=null,u&&o.signal&&o.signal.removeEventListener("abort",u),u=null,await s?.(),s=null)};return new ReadableStream({start(m){if(a=r.listen(i,h=>{c||m.enqueue(t(h))}),o.signal){if(u=()=>{d().finally(()=>m.error(o.signal?.reason??new Error("Aborted")))},o.signal.aborted){u();return}o.signal.addEventListener("abort",u,{once:!0})}e.acquire(n).then(async h=>{if(c){await h();return}s=h}).catch(h=>{c||(c=!0,a?.dispose(),u&&o.signal&&o.signal.removeEventListener("abort",u),u=null,m.error(h))})},cancel:d})}var Tr=class{constructor(e,n){this.okra=e;this.telemetry=n}follow(e={}){return Et(this.okra,this.telemetry,"logs","notebook.log",n=>({timestamp:new Date().toISOString(),source:"runtime",message:n}),e)}};var Dr=class{constructor(e,n){this.okra=e;this.telemetry=n}current(){return this.okra.invoke("container.stats")}watch(e={}){return Et(this.okra,this.telemetry,"stats","container.stats",n=>n,e)}};var Ur=class{constructor(e,n){this.okra=e;this.telemetry=n}list(){return this.okra.invoke("container.opened-ports")}resolve(e){return this.okra.invoke("container.resolve-port",{port:e})}watch(e={}){return Et(this.okra,this.telemetry,"ports","container.ports",n=>n,e)}};var $l=class{constructor(e){this.metrics=e}current(){return this.metrics.current()}watch(e={}){return this.metrics.watch(e)}},wl=class{constructor(e){this.logs=e}follow(e={}){return this.logs.follow(e)}},_l=class{constructor(e){this.ports=e}list(){return this.ports.list()}resolve(e){return this.ports.resolve(e)}watch(e={}){return this.ports.watch(e)}},Rr=class{constructor(e){this.notebook=e;let n=new Li(e);this.metrics=new $l(new Dr(e,n)),this.logs=new wl(new Tr(e,n)),this.ports=new _l(new Ur(e,n))}setPhpVersion(e){return this.notebook.invoke("container.set-php",{version:e})}};var Or=class{constructor(e){this.okra=e}eval(e,n="",i={prependWith:"",appendWith:""}){return this.okra.invoke("repl.eval",{code:e,args:n,repl:i})}write(e){return this.okra.invoke("repl.write",{input:e})}stop(){return this.okra.invoke("repl.stop")}resize(e,n){return this.okra.invoke("repl.resize",{cols:e,rows:n})}listen(e,n){return this.okra.listen(e,n)}onOutput(e){return this.okra.listen("repl.output",e)}};var Sl=["redis"],df=["start","nginx",...Sl],Ar=class{constructor(e){this.okra=e}list(){return this.okra.invoke("service.list")}run(e,n){return this.okra.invoke("service.run",{name:e,command:n})}stop(e){return this.okra.invoke("service.stop",{name:e})}logs(e,n={}){return n.follow?this.followLogs(e,n):this.okra.invoke("service.logs",{name:e,tail:n.tail}).then(i=>{if(!("output"in i))throw new Error(`Unexpected service.logs response for ${e}`);return i.output})}followLogs(e,n){let i=n.id||j(),t=new Set,o=null,a=!1,s=()=>{for(let m of t)m.dispose();t.clear()},c=()=>{if(!a&&(a=!0,s(),o))try{o.close()}catch{}},u=m=>{a||(a=!0,s(),o&&o.error(m))},d=Ni(()=>(c(),this.okra.invoke("service.stop-logs",{id:i})));return new ReadableStream({start:m=>{o=m,t.add(this.okra.listen(`service.log.${i}`,h=>{o?.enqueue(h.output)})),this.okra.invoke("service.logs",{name:e,tail:n.tail,follow:!0,id:i}).catch(h=>{u(h)})},cancel:()=>d().then(()=>{})})}};var Cr=class{constructor(e){this.okra=e}get(){return this.okra.invoke("config.get")}update(e){return this.okra.invoke("config.update",{config:e})}setPorts(e){return this.okra.invoke("config.set-ports",{ports:e})}};function pf(r){let e=r.length,n=0,i=0;for(;i<e;){let t=r.charCodeAt(i++);if((t&4294967168)===0){n++;continue}else if((t&4294965248)===0)n+=2;else{if(t>=55296&&t<=56319&&i<e){let o=r.charCodeAt(i);(o&64512)===56320&&(++i,t=((t&1023)<<10)+(o&1023)+65536)}(t&4294901760)===0?n+=3:n+=4}}return n}function qv(r,e,n){let i=r.length,t=n,o=0;for(;o<i;){let a=r.charCodeAt(o++);if((a&4294967168)===0){e[t++]=a;continue}else if((a&4294965248)===0)e[t++]=a>>6&31|192;else{if(a>=55296&&a<=56319&&o<i){let s=r.charCodeAt(o);(s&64512)===56320&&(++o,a=((a&1023)<<10)+(s&1023)+65536)}(a&4294901760)===0?(e[t++]=a>>12&15|224,e[t++]=a>>6&63|128):(e[t++]=a>>18&7|240,e[t++]=a>>12&63|128,e[t++]=a>>6&63|128)}e[t++]=a&63|128}}var Hv=new TextEncoder,Xv=50;function Yv(r,e,n){Hv.encodeInto(r,e.subarray(n))}function mf(r,e,n){r.length>Xv?Yv(r,e,n):qv(r,e,n)}var Qv=4096;function Il(r,e,n){let i=e,t=i+n,o=[],a="";for(;i<t;){let s=r[i++];if((s&128)===0)o.push(s);else if((s&224)===192){let c=r[i++]&63;o.push((s&31)<<6|c)}else if((s&240)===224){let c=r[i++]&63,u=r[i++]&63;o.push((s&31)<<12|c<<6|u)}else if((s&248)===240){let c=r[i++]&63,u=r[i++]&63,d=r[i++]&63,m=(s&7)<<18|c<<12|u<<6|d;m>65535&&(m-=65536,o.push(m>>>10&1023|55296),m=56320|m&1023),o.push(m)}else o.push(s);o.length>=Qv&&(a+=String.fromCharCode(...o),o.length=0)}return o.length>0&&(a+=String.fromCharCode(...o)),a}var eb=new TextDecoder,tb=200;function rb(r,e,n){let i=r.subarray(e,e+n);return eb.decode(i)}function ff(r,e,n){return n>tb?rb(r,e,n):Il(r,e,n)}var Fe=class{constructor(e,n){this.type=e,this.data=n}};var H=class r extends Error{constructor(e){super(e);let n=Object.create(r.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:r.name})}};function gf(r,e,n){let i=n/4294967296,t=n;r.setUint32(e,i),r.setUint32(e+4,t)}function Zi(r,e,n){let i=Math.floor(n/4294967296),t=n;r.setUint32(e,i),r.setUint32(e+4,t)}function Fi(r,e){let n=r.getInt32(e),i=r.getUint32(e+4);return n*4294967296+i}function hf(r,e){let n=r.getUint32(e),i=r.getUint32(e+4);return n*4294967296+i}var nb=-1,ib=4294967296-1,ob=17179869184-1;function ab({sec:r,nsec:e}){if(r>=0&&e>=0&&r<=ob)if(e===0&&r<=ib){let n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,r),n}else{let n=r/4294967296,i=r&4294967295,t=new Uint8Array(8),o=new DataView(t.buffer);return o.setUint32(0,e<<2|n&3),o.setUint32(4,i),t}else{let n=new Uint8Array(12),i=new DataView(n.buffer);return i.setUint32(0,e),Zi(i,4,r),n}}function sb(r){let e=r.getTime(),n=Math.floor(e/1e3),i=(e-n*1e3)*1e6,t=Math.floor(i/1e9);return{sec:n+t,nsec:i-t*1e9}}function cb(r){if(r instanceof Date){let e=sb(r);return ab(e)}else return null}function ub(r){let e=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(r.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{let n=e.getUint32(0),i=e.getUint32(4),t=(n&3)*4294967296+i,o=n>>>2;return{sec:t,nsec:o}}case 12:{let n=Fi(e,4),i=e.getUint32(0);return{sec:n,nsec:i}}default:throw new H(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${r.length}`)}}function lb(r){let e=ub(r);return new Date(e.sec*1e3+e.nsec/1e6)}var vf={type:nb,encode:cb,decode:lb};var Se=class{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(vf)}register({type:e,encode:n,decode:i}){if(e>=0)this.encoders[e]=n,this.decoders[e]=i;else{let t=-1-e;this.builtInEncoders[t]=n,this.builtInDecoders[t]=i}}tryToEncode(e,n){for(let i=0;i<this.builtInEncoders.length;i++){let t=this.builtInEncoders[i];if(t!=null){let o=t(e,n);if(o!=null){let a=-1-i;return new Fe(a,o)}}}for(let i=0;i<this.encoders.length;i++){let t=this.encoders[i];if(t!=null){let o=t(e,n);if(o!=null){let a=i;return new Fe(a,o)}}}return e instanceof Fe?e:null}decode(e,n,i){let t=n<0?this.builtInDecoders[-1-n]:this.decoders[n];return t?t(e,n,i):new Fe(n,e)}};Se.defaultCodec=new Se;function db(r){return r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer}function jr(r){return r instanceof Uint8Array?r:ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):db(r)?new Uint8Array(r):Uint8Array.from(r)}var pb=100,mb=2048,Mi=class r{constructor(e){this.entered=!1,this.extensionCodec=e?.extensionCodec??Se.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??pb,this.initialBufferSize=e?.initialBufferSize??mb,this.sortKeys=e?.sortKeys??!1,this.forceFloat32=e?.forceFloat32??!1,this.ignoreUndefined=e?.ignoreUndefined??!1,this.forceIntegerToFloat=e?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new r({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,n){if(n>this.maxDepth)throw new Error(`Too deep objects in depth ${n}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,n)}ensureBufferSizeToWrite(e){let n=this.pos+e;this.view.byteLength<n&&this.resizeBuffer(n*2)}resizeBuffer(e){let n=new ArrayBuffer(e),i=new Uint8Array(n),t=new DataView(n);i.set(this.bytes),this.view=t,this.bytes=i}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){let i=pf(e);this.ensureBufferSizeToWrite(5+i),this.writeStringHeader(i),mf(e,this.bytes,this.pos),this.pos+=i}encodeObject(e,n){let i=this.extensionCodec.tryToEncode(e,this.context);if(i!=null)this.encodeExtension(i);else if(Array.isArray(e))this.encodeArray(e,n);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,n);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){let n=e.byteLength;if(n<256)this.writeU8(196),this.writeU8(n);else if(n<65536)this.writeU8(197),this.writeU16(n);else if(n<4294967296)this.writeU8(198),this.writeU32(n);else throw new Error(`Too large binary: ${n}`);let i=jr(e);this.writeU8a(i)}encodeArray(e,n){let i=e.length;if(i<16)this.writeU8(144+i);else if(i<65536)this.writeU8(220),this.writeU16(i);else if(i<4294967296)this.writeU8(221),this.writeU32(i);else throw new Error(`Too large array: ${i}`);for(let t of e)this.doEncode(t,n+1)}countWithoutUndefined(e,n){let i=0;for(let t of n)e[t]!==void 0&&i++;return i}encodeMap(e,n){let i=Object.keys(e);this.sortKeys&&i.sort();let t=this.ignoreUndefined?this.countWithoutUndefined(e,i):i.length;if(t<16)this.writeU8(128+t);else if(t<65536)this.writeU8(222),this.writeU16(t);else if(t<4294967296)this.writeU8(223),this.writeU32(t);else throw new Error(`Too large map object: ${t}`);for(let o of i){let a=e[o];this.ignoreUndefined&&a===void 0||(this.encodeString(o),this.doEncode(a,n+1))}}encodeExtension(e){if(typeof e.data=="function"){let i=e.data(this.pos+6),t=i.length;if(t>=4294967296)throw new Error(`Too large extension object: ${t}`);this.writeU8(201),this.writeU32(t),this.writeI8(e.type),this.writeU8a(i);return}let n=e.data.length;if(n===1)this.writeU8(212);else if(n===2)this.writeU8(213);else if(n===4)this.writeU8(214);else if(n===8)this.writeU8(215);else if(n===16)this.writeU8(216);else if(n<256)this.writeU8(199),this.writeU8(n);else if(n<65536)this.writeU8(200),this.writeU16(n);else if(n<4294967296)this.writeU8(201),this.writeU32(n);else throw new Error(`Too large extension object: ${n}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){let n=e.length;this.ensureBufferSizeToWrite(n),this.bytes.set(e,this.pos),this.pos+=n}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),gf(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),Zi(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}};function Pl(r,e){return new Mi(e).encodeSharedRef(r)}function Bi(r){return`${r<0?"-":""}0x${Math.abs(r).toString(16).padStart(2,"0")}`}var fb=16,gb=16,Gi=class{constructor(e=fb,n=gb){this.hit=0,this.miss=0,this.maxKeyLength=e,this.maxLengthPerKey=n,this.caches=[];for(let i=0;i<this.maxKeyLength;i++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,n,i){let t=this.caches[i-1];e:for(let o of t){let a=o.bytes;for(let s=0;s<i;s++)if(a[s]!==e[n+s])continue e;return o.str}return null}store(e,n){let i=this.caches[e.length-1],t={bytes:e,str:n};i.length>=this.maxLengthPerKey?i[Math.random()*i.length|0]=t:i.push(t)}decode(e,n,i){let t=this.find(e,n,i);if(t!=null)return this.hit++,t;this.miss++;let o=Il(e,n,i),a=Uint8Array.prototype.slice.call(e,n,n+i);return this.store(a,o),o}};var zl="array",Zr="map_key",yf="map_value",hb=r=>{if(typeof r=="string"||typeof r=="number")return r;throw new H("The type of key must be string or number but "+typeof r)},El=class{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){let n=this.getUninitializedStateFromPool();n.type=zl,n.position=0,n.size=e,n.array=new Array(e)}pushMapState(e){let n=this.getUninitializedStateFromPool();n.type=Zr,n.readCount=0,n.size=e,n.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===zl){let i=e;i.size=0,i.array=void 0,i.position=0,i.type=void 0}if(e.type===Zr||e.type===yf){let i=e;i.size=0,i.map=void 0,i.readCount=0,i.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},Lr=-1,Tl=new DataView(new ArrayBuffer(0)),vb=new Uint8Array(Tl.buffer);try{Tl.getInt8(0)}catch(r){if(!(r instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var bf=new RangeError("Insufficient data"),bb=new Gi,Wi=class r{constructor(e){this.totalPos=0,this.pos=0,this.view=Tl,this.bytes=vb,this.headByte=Lr,this.stack=new El,this.entered=!1,this.extensionCodec=e?.extensionCodec??Se.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??4294967295,this.maxBinLength=e?.maxBinLength??4294967295,this.maxArrayLength=e?.maxArrayLength??4294967295,this.maxMapLength=e?.maxMapLength??4294967295,this.maxExtLength=e?.maxExtLength??4294967295,this.keyDecoder=e?.keyDecoder!==void 0?e.keyDecoder:bb,this.mapKeyConverter=e?.mapKeyConverter??hb}clone(){return new r({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=Lr,this.stack.reset()}setBuffer(e){let n=jr(e);this.bytes=n,this.view=new DataView(n.buffer,n.byteOffset,n.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===Lr&&!this.hasRemaining(1))this.setBuffer(e);else{let n=this.bytes.subarray(this.pos),i=jr(e),t=new Uint8Array(n.length+i.length);t.set(n),t.set(i,n.length),this.setBuffer(t)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){let{view:n,pos:i}=this;return new RangeError(`Extra ${n.byteLength-i} of ${n.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);let n=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return n}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let n=!1,i;for await(let s of e){if(n)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(s);try{i=this.doDecodeSync(),n=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(n){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return i}let{headByte:t,pos:o,totalPos:a}=this;throw new RangeError(`Insufficient data in parsing ${Bi(t)} at ${a} (${o} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,n){if(this.entered){yield*this.clone().decodeMultiAsync(e,n);return}try{this.entered=!0;let i=n,t=-1;for await(let o of e){if(n&&t===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(o),i&&(t=this.readArraySize(),i=!1,this.complete());try{for(;yield this.doDecodeSync(),--t!==0;);}catch(a){if(!(a instanceof RangeError))throw a}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){let e=this.readHeadByte(),n;if(e>=224)n=e-256;else if(e<192)if(e<128)n=e;else if(e<144){let t=e-128;if(t!==0){this.pushMapState(t),this.complete();continue e}else n={}}else if(e<160){let t=e-144;if(t!==0){this.pushArrayState(t),this.complete();continue e}else n=[]}else{let t=e-160;n=this.decodeString(t,0)}else if(e===192)n=null;else if(e===194)n=!1;else if(e===195)n=!0;else if(e===202)n=this.readF32();else if(e===203)n=this.readF64();else if(e===204)n=this.readU8();else if(e===205)n=this.readU16();else if(e===206)n=this.readU32();else if(e===207)this.useBigInt64?n=this.readU64AsBigInt():n=this.readU64();else if(e===208)n=this.readI8();else if(e===209)n=this.readI16();else if(e===210)n=this.readI32();else if(e===211)this.useBigInt64?n=this.readI64AsBigInt():n=this.readI64();else if(e===217){let t=this.lookU8();n=this.decodeString(t,1)}else if(e===218){let t=this.lookU16();n=this.decodeString(t,2)}else if(e===219){let t=this.lookU32();n=this.decodeString(t,4)}else if(e===220){let t=this.readU16();if(t!==0){this.pushArrayState(t),this.complete();continue e}else n=[]}else if(e===221){let t=this.readU32();if(t!==0){this.pushArrayState(t),this.complete();continue e}else n=[]}else if(e===222){let t=this.readU16();if(t!==0){this.pushMapState(t),this.complete();continue e}else n={}}else if(e===223){let t=this.readU32();if(t!==0){this.pushMapState(t),this.complete();continue e}else n={}}else if(e===196){let t=this.lookU8();n=this.decodeBinary(t,1)}else if(e===197){let t=this.lookU16();n=this.decodeBinary(t,2)}else if(e===198){let t=this.lookU32();n=this.decodeBinary(t,4)}else if(e===212)n=this.decodeExtension(1,0);else if(e===213)n=this.decodeExtension(2,0);else if(e===214)n=this.decodeExtension(4,0);else if(e===215)n=this.decodeExtension(8,0);else if(e===216)n=this.decodeExtension(16,0);else if(e===199){let t=this.lookU8();n=this.decodeExtension(t,1)}else if(e===200){let t=this.lookU16();n=this.decodeExtension(t,2)}else if(e===201){let t=this.lookU32();n=this.decodeExtension(t,4)}else throw new H(`Unrecognized type byte: ${Bi(e)}`);this.complete();let i=this.stack;for(;i.length>0;){let t=i.top();if(t.type===zl)if(t.array[t.position]=n,t.position++,t.position===t.size)n=t.array,i.release(t);else continue e;else if(t.type===Zr){if(n==="__proto__")throw new H("The key __proto__ is not allowed");t.key=this.mapKeyConverter(n),t.type=yf;continue e}else if(t.map[t.key]=n,t.readCount++,t.readCount===t.size)n=t.map,i.release(t);else{t.key=null,t.type=Zr;continue e}}return n}}readHeadByte(){return this.headByte===Lr&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=Lr}readArraySize(){let e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new H(`Unrecognized array type byte: ${Bi(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new H(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new H(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,n){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,n):this.decodeBinary(e,n)}decodeUtf8String(e,n){if(e>this.maxStrLength)throw new H(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+n+e)throw bf;let i=this.pos+n,t;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?t=this.keyDecoder.decode(this.bytes,i,e):t=ff(this.bytes,i,e),this.pos+=n+e,t}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===Zr:!1}decodeBinary(e,n){if(e>this.maxBinLength)throw new H(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+n))throw bf;let i=this.pos+n,t=this.bytes.subarray(i,i+e);return this.pos+=n+e,t}decodeExtension(e,n){if(e>this.maxExtLength)throw new H(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);let i=this.view.getInt8(this.pos+n),t=this.decodeBinary(e,n+1);return this.extensionCodec.decode(t,i,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){let e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){let e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){let e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){let e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){let e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){let e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){let e=hf(this.view,this.pos);return this.pos+=8,e}readI64(){let e=Fi(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){let e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){let e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){let e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){let e=this.view.getFloat64(this.pos);return this.pos+=8,e}};function Dl(r,e){return new Wi(e).decode(r)}var Vi=class{constructor(e){this.error=e}},yb=r=>new Promise(e=>{setTimeout(e,r)}),xb=(r,e)=>{let n=e.randomize?Math.random()+1:1,i=Math.max(e.minTimeout,1)*Math.pow(e.factor,r-1);return Math.round(Math.min(n*i,e.maxTimeout))};async function xf(r,e={}){let n={retries:e.retries??10,minTimeout:e.minTimeout??1e3,maxTimeout:e.maxTimeout??1/0,factor:e.factor??2,randomize:e.randomize??!0},i=o=>{throw new Vi(o??new Error("Aborted"))},t;for(let o=1;o<=n.retries+1;o++)try{return await r(i,o)}catch(a){if(a instanceof Vi)throw a.error;if(t=a,o>n.retries)throw a;await e.onRetry?.(a,o),await yb(xb(o,n))}throw t}var Ol={};te(Ol,{default:()=>Rl});var Ul=function(r,e){return Ul=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var t in i)i.hasOwnProperty(t)&&(n[t]=i[t])},Ul(r,e)};function kf(r,e){Ul(r,e);function n(){this.constructor=r}r.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}function kb(r){var e=typeof Symbol=="function"&&r[Symbol.iterator],n=0;return e?e.call(r):{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}}}function $b(r,e){var n=typeof Symbol=="function"&&r[Symbol.iterator];if(!n)return r;var i=n.call(r),t,o=[],a;try{for(;(e===void 0||e-- >0)&&!(t=i.next()).done;)o.push(t.value)}catch(s){a={error:s}}finally{try{t&&!t.done&&(n=i.return)&&n.call(i)}finally{if(a)throw a.error}}return o}function wb(){for(var r=[],e=0;e<arguments.length;e++)r=r.concat($b(arguments[e]));return r}var $f=(function(){function r(e,n){this.target=n,this.type=e}return r})(),_b=(function(r){kf(e,r);function e(n,i){var t=r.call(this,"error",i)||this;return t.message=n.message,t.error=n,t}return e})($f),Sb=(function(r){kf(e,r);function e(n,i,t){n===void 0&&(n=1e3),i===void 0&&(i="");var o=r.call(this,"close",t)||this;return o.wasClean=!0,o.code=n,o.reason=i,o}return e})($f);var Ib=function(){if(typeof WebSocket<"u")return WebSocket},Pb=function(r){return typeof r<"u"&&!!r&&r.CLOSING===2},Me={maxReconnectionDelay:1e4,minReconnectionDelay:1e3+Math.random()*4e3,minUptime:5e3,reconnectionDelayGrowFactor:1.3,connectionTimeout:4e3,maxRetries:1/0,maxEnqueuedMessages:1/0,startClosed:!1,debug:!1},zb=(function(){function r(e,n,i){var t=this;i===void 0&&(i={}),this._listeners={error:[],message:[],open:[],close:[]},this._retryCount=-1,this._shouldReconnect=!0,this._connectLock=!1,this._binaryType="blob",this._closeCalled=!1,this._messageQueue=[],this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this._handleOpen=function(o){t._debug("open event");var a=t._options.minUptime,s=a===void 0?Me.minUptime:a;clearTimeout(t._connectTimeout),t._uptimeTimeout=setTimeout(function(){return t._acceptOpen()},s),t._ws.binaryType=t._binaryType,t._messageQueue.forEach(function(c){return t._ws.send(c)}),t._messageQueue=[],t.onopen&&t.onopen(o),t._listeners.open.forEach(function(c){return t._callEventListener(o,c)})},this._handleMessage=function(o){t._debug("message event"),t.onmessage&&t.onmessage(o),t._listeners.message.forEach(function(a){return t._callEventListener(o,a)})},this._handleError=function(o){t._debug("error event",o.message),t._disconnect(void 0,o.message==="TIMEOUT"?"timeout":void 0),t.onerror&&t.onerror(o),t._debug("exec error listeners"),t._listeners.error.forEach(function(a){return t._callEventListener(o,a)}),t._connect()},this._handleClose=function(o){t._debug("close event"),t._clearTimeouts(),t._shouldReconnect&&t._connect(),t.onclose&&t.onclose(o),t._listeners.close.forEach(function(a){return t._callEventListener(o,a)})},this._url=e,this._protocols=n,this._options=i,this._options.startClosed&&(this._shouldReconnect=!1),this._connect()}return Object.defineProperty(r,"CONNECTING",{get:function(){return 0},enumerable:!0,configurable:!0}),Object.defineProperty(r,"OPEN",{get:function(){return 1},enumerable:!0,configurable:!0}),Object.defineProperty(r,"CLOSING",{get:function(){return 2},enumerable:!0,configurable:!0}),Object.defineProperty(r,"CLOSED",{get:function(){return 3},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"CONNECTING",{get:function(){return r.CONNECTING},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"OPEN",{get:function(){return r.OPEN},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"CLOSING",{get:function(){return r.CLOSING},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"CLOSED",{get:function(){return r.CLOSED},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"binaryType",{get:function(){return this._ws?this._ws.binaryType:this._binaryType},set:function(e){this._binaryType=e,this._ws&&(this._ws.binaryType=e)},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"retryCount",{get:function(){return Math.max(this._retryCount,0)},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"bufferedAmount",{get:function(){var e=this._messageQueue.reduce(function(n,i){return typeof i=="string"?n+=i.length:i instanceof Blob?n+=i.size:n+=i.byteLength,n},0);return e+(this._ws?this._ws.bufferedAmount:0)},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"extensions",{get:function(){return this._ws?this._ws.extensions:""},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"protocol",{get:function(){return this._ws?this._ws.protocol:""},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"readyState",{get:function(){return this._ws?this._ws.readyState:this._options.startClosed?r.CLOSED:r.CONNECTING},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"url",{get:function(){return this._ws?this._ws.url:""},enumerable:!0,configurable:!0}),r.prototype.close=function(e,n){if(e===void 0&&(e=1e3),this._closeCalled=!0,this._shouldReconnect=!1,this._clearTimeouts(),!this._ws){this._debug("close enqueued: no ws instance");return}if(this._ws.readyState===this.CLOSED){this._debug("close: already closed");return}this._ws.close(e,n)},r.prototype.reconnect=function(e,n){this._shouldReconnect=!0,this._closeCalled=!1,this._retryCount=-1,!this._ws||this._ws.readyState===this.CLOSED?this._connect():(this._disconnect(e,n),this._connect())},r.prototype.send=function(e){if(this._ws&&this._ws.readyState===this.OPEN)this._debug("send",e),this._ws.send(e);else{var n=this._options.maxEnqueuedMessages,i=n===void 0?Me.maxEnqueuedMessages:n;this._messageQueue.length<i&&(this._debug("enqueue",e),this._messageQueue.push(e))}},r.prototype.addEventListener=function(e,n){this._listeners[e]&&this._listeners[e].push(n)},r.prototype.dispatchEvent=function(e){var n,i,t=this._listeners[e.type];if(t)try{for(var o=kb(t),a=o.next();!a.done;a=o.next()){var s=a.value;this._callEventListener(e,s)}}catch(c){n={error:c}}finally{try{a&&!a.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}return!0},r.prototype.removeEventListener=function(e,n){this._listeners[e]&&(this._listeners[e]=this._listeners[e].filter(function(i){return i!==n}))},r.prototype._debug=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];this._options.debug&&console.log.apply(console,wb(["RWS>"],e))},r.prototype._getNextDelay=function(){var e=this._options,n=e.reconnectionDelayGrowFactor,i=n===void 0?Me.reconnectionDelayGrowFactor:n,t=e.minReconnectionDelay,o=t===void 0?Me.minReconnectionDelay:t,a=e.maxReconnectionDelay,s=a===void 0?Me.maxReconnectionDelay:a,c=0;return this._retryCount>0&&(c=o*Math.pow(i,this._retryCount-1),c>s&&(c=s)),this._debug("next delay",c),c},r.prototype._wait=function(){var e=this;return new Promise(function(n){setTimeout(n,e._getNextDelay())})},r.prototype._getNextUrl=function(e){if(typeof e=="string")return Promise.resolve(e);if(typeof e=="function"){var n=e();if(typeof n=="string")return Promise.resolve(n);if(n.then)return n}throw Error("Invalid URL")},r.prototype._connect=function(){var e=this;if(!(this._connectLock||!this._shouldReconnect)){this._connectLock=!0;var n=this._options,i=n.maxRetries,t=i===void 0?Me.maxRetries:i,o=n.connectionTimeout,a=o===void 0?Me.connectionTimeout:o,s=n.WebSocket,c=s===void 0?Ib():s;if(this._retryCount>=t){this._debug("max retries reached",this._retryCount,">=",t);return}if(this._retryCount++,this._debug("connect",this._retryCount),this._removeListeners(),!Pb(c))throw Error("No valid WebSocket class provided");this._wait().then(function(){return e._getNextUrl(e._url)}).then(function(u){e._closeCalled||(e._debug("connect",{url:u,protocols:e._protocols}),e._ws=e._protocols?new c(u,e._protocols):new c(u),e._ws.binaryType=e._binaryType,e._connectLock=!1,e._addListeners(),e._connectTimeout=setTimeout(function(){return e._handleTimeout()},a))})}},r.prototype._handleTimeout=function(){this._debug("timeout event"),this._handleError(new _b(Error("TIMEOUT"),this))},r.prototype._disconnect=function(e,n){if(e===void 0&&(e=1e3),this._clearTimeouts(),!!this._ws){this._removeListeners();try{this._ws.close(e,n),this._handleClose(new Sb(e,n,this))}catch{}}},r.prototype._acceptOpen=function(){this._debug("accept open"),this._retryCount=0},r.prototype._callEventListener=function(e,n){"handleEvent"in n?n.handleEvent(e):n(e)},r.prototype._removeListeners=function(){this._ws&&(this._debug("removeListeners"),this._ws.removeEventListener("open",this._handleOpen),this._ws.removeEventListener("close",this._handleClose),this._ws.removeEventListener("message",this._handleMessage),this._ws.removeEventListener("error",this._handleError))},r.prototype._addListeners=function(){this._ws&&(this._debug("addListeners"),this._ws.addEventListener("open",this._handleOpen),this._ws.addEventListener("close",this._handleClose),this._ws.addEventListener("message",this._handleMessage),this._ws.addEventListener("error",this._handleError))},r.prototype._clearTimeouts=function(){clearTimeout(this._connectTimeout),clearTimeout(this._uptimeTimeout)},r})(),Rl=zb;var Eb=r=>{if(typeof r=="number")return{0:"CONNECTING",1:"OPEN",2:"CLOSING",3:"CLOSED"}[r]??`STATE_${r}`},Tb=r=>{try{let e=new URL(r);return`${e.origin}${e.pathname}`}catch{return r}},wf=r=>{if(r instanceof Error)return r.message?`${r.name}: ${r.message}`:r.name;if(typeof r=="string")return r;if(!r||typeof r!="object")return;let e=r,n=typeof e.message=="string"&&e.message?e.message:typeof e.reason=="string"&&e.reason?e.reason:void 0;if(!n)return;let i=typeof e.name=="string"&&e.name?e.name:void 0;return i?`${i}: ${n}`:n},Ji=r=>{if(r instanceof Error)return r.message?`${r.name}: ${r.message}`:r.name;if(typeof r=="string")return r;if(!r||typeof r!="object")return String(r);let e=r,n=[],i=wf(e);i&&n.push(i);let t=wf(e.error);t&&t!==i&&n.push(`error=${t}`),typeof e.type=="string"&&e.type&&n.push(`type=${e.type}`),typeof e.code=="number"&&n.push(`code=${e.code}`),typeof e.reason=="string"&&e.reason&&e.reason!==i&&n.push(`reason=${e.reason}`),typeof e.wasClean=="boolean"&&n.push(`wasClean=${e.wasClean}`);let o=e.target??e.currentTarget;if(o&&typeof o=="object"){typeof o.url=="string"&&o.url&&n.push(`url=${Tb(o.url)}`);let a=Eb(o.readyState);a&&n.push(`readyState=${a}`)}return n.length>0?n.join(" | "):"Unknown websocket event"};var Tt=null;typeof WebSocket<"u"?Tt=WebSocket:typeof MozWebSocket<"u"?Tt=MozWebSocket:typeof global<"u"?Tt=global.WebSocket||global.MozWebSocket:typeof window<"u"?Tt=window.WebSocket||window.MozWebSocket:typeof self<"u"&&(Tt=self.WebSocket||self.MozWebSocket);var _f=Tt;var Ki=class{constructor(){this.disposables=new Map}add(e,n){this.disposables.has(e)&&(console.warn(`Disposable with key "${e}" already exists. Disposing the old one.`),this.disposables.get(e)?.dispose()),typeof n=="function"&&(n=n()),this.disposables.set(e,n)}dispose(){this.disposables.forEach(e=>e.dispose()),this.disposables.clear()}};var Db=new Set(["url","action","event","responseEvent","errorEvent","hasData","code","attempt","maxRetries","timeout","errorCount","byteLength"]),Ub=Rl??Ol;var Al=class extends U{constructor(e="WebSocket connection timeout"){super(e,"ConnectionTimeout")}},Dt=class extends U{constructor(n,i){super(n,"ConnectionFailed",i);this.originalError=i}},Be=class extends U{constructor(n,i){super(n,"InvalidResponse",i);this.data=i}},Ge=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}},Ie,Cl,jl,qi=class{constructor(e,n,i={}){this.eventEmitter=n;this.options=i;Lt(this,Ie);this.clientId="";this.closed=!1;this.disposables=new Ki;this.connectPromise=null;this.terminalError=null;this.pingIntervalStarted=!1;this.incomingMessageChain=Promise.resolve();this.validateConfiguration(i),this.url=typeof e=="string"?new URL(e):null;let t=typeof e=="string"?new URL(e).toString():async()=>new URL(await e()).toString();this.PING_INTERVAL=i.pingInterval??3e4,this.CONNECT_WAIT_TIMEOUT=i.connectWaitTimeout??3e4,this.rws=new Ub(t,[],{WebSocket:i.webSocket??globalThis.WebSocket??_f,connectionTimeout:i.connectionTimeout,maxReconnectionDelay:2e3,minReconnectionDelay:200,maxEnqueuedMessages:0,maxRetries:i.maxRetries??50,startClosed:!0}),this.log("debug","Transport initialized",{url:this.url===null?"dynamic":Ob(this.url),options:i}),this.registerWatchers()}validateConfiguration(e){if(e.pingInterval!==void 0&&(e.pingInterval<1e3||e.pingInterval>3e5))throw new Ge("pingInterval must be between 1000ms and 300000ms");if(e.connectionTimeout!==void 0&&(e.connectionTimeout<100||e.connectionTimeout>3e4))throw new Ge("connectionTimeout must be between 100ms and 30000ms");if(e.connectWaitTimeout!==void 0&&(e.connectWaitTimeout<1e3||e.connectWaitTimeout>3e5))throw new Ge("connectWaitTimeout must be between 1000ms and 300000ms");if(e.maxRetries!==void 0&&(e.maxRetries<0||e.maxRetries>100))throw new Ge("maxRetries must be between 0 and 100")}log(e,n,i){if(this.options.debug){let t=new Date().toISOString(),o=Rb(i),a=o?`
66
66
  ${JSON.stringify(o,null,2)}`:"";console[e](`[Transport ${t}] ${n}${a}`)}}connect(){return this.terminalError?Promise.reject(this.terminalError):pe(this,Ie,Cl).call(this)}id(){return this.clientId}registerWatchers(){let e=n=>{this.incomingMessageChain=this.incomingMessageChain.catch(()=>{}).then(()=>this.processIncomingMessage(n)).catch(i=>{this.log("error","Failed to process queued WebSocket frame",{error:i instanceof Error?i.message:String(i)}),this.eventEmitter.emit("transport.error",{type:"message_handle_error",error:i,rawMessage:n.data,timestamp:Date.now()})})};this.rws.addEventListener("message",e),this.disposables.add("message",{dispose:()=>{this.rws.removeEventListener("message",e)}})}async processIncomingMessage(e){let n;try{n=await this.toArrayBuffer(e.data)}catch(t){this.log("error","Unexpected WebSocket message type",{error:t instanceof Error?t.message:String(t),messageType:typeof e.data}),this.eventEmitter.emit("transport.error",{type:"message_type_error",error:t,rawMessage:e.data,timestamp:Date.now()});return}if(n.byteLength===0){this.log("warn","Ignoring empty WebSocket frame");return}let i;try{i=Dl(n)}catch(t){this.log("error","Failed to decode WebSocket frame",{error:t instanceof Error?t.message:String(t),byteLength:n.byteLength}),this.eventEmitter.emit("transport.error",{type:"message_decode_error",error:t,rawMessage:n,timestamp:Date.now()});return}try{await this.handleRawMessage(i)}catch(t){this.log("error","Failed to process WebSocket frame",{error:t instanceof Error?t.message:String(t),byteLength:n.byteLength}),this.eventEmitter.emit("transport.error",{type:"message_handle_error",error:t,rawMessage:n,timestamp:Date.now()})}}async toArrayBuffer(e){if(e instanceof Blob)return e.arrayBuffer();if(e instanceof ArrayBuffer)return e;if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength).slice().buffer;throw new Error("Unexpected message type: "+typeof e)}async handleRawMessage(e){if(this.closed){this.log("debug","Ignoring message received after transport was closed");return}if(typeof e!="object"||e===null){this.log("debug","Received invalid message format",{ev:e});return}try{let{data:n,event:i,as:t}=e;if(!i||typeof i!="string")throw new Be("Message missing event field",e);if(this.log("debug","Processing message",{event:i,hasData:!!n}),i==="App.Actions.GetClientId"){this.clientId=n.id,this.log("info","Client ID received",{clientId:this.clientId});return}if(i==="Events.BootError"){let o=n,a=new C(o?.message||"Notebook is no longer available",{source:"runtime",status:503,code:"NotebookUnavailable",details:o||{}});this.log("error","Boot error received",{data:n}),this.terminate(a,4e3,a.message);return}if(i==="response"){let{responseEvent:o,data:a}=n;if(!o)throw new Be("Response message missing responseEvent",e);this.log("debug","Response message received",{responseEvent:o}),await this.handleMessage(o,a);return}if(i==="error"){let{errorEvent:o,data:a}=n;if(!o)throw new Be("Error message missing errorEvent",e);this.log("debug","Error message received",{errorEvent:o,errorData:a}),await this.handleMessage(o,a);return}await this.handleMessage(i,n,t)}catch(n){n instanceof Be?this.log("error","Invalid message format",{error:n.message,data:n.data}):this.log("error","Failed to parse message",{ev:e,error:n instanceof Error?n.message:String(n)}),this.eventEmitter.emit("transport.error",{type:"message_parse_error",error:n,rawMessage:e,timestamp:Date.now()})}}async handleMessage(e,n,i){if(e==="App.Actions.GetClientId"){this.clientId=n.id,this.eventEmitter.emit(e,this.clientId);return}e&&this.eventEmitter.emit(i||e,n)}listen(e,n,i){return this.eventEmitter.listen(e,n)}onDidBootError(e){return this.eventEmitter.listen("transport.boot_error",n=>{n&&typeof n=="object"&&"error"in n&&C.is(n.error,"NotebookUnavailable")&&e(n.error)})}removeListener(e,n){this.eventEmitter.removeListener(e,n)}listenOnce(e,n,i){return this.eventEmitter.once(e,n,i)}emit(e,...n){this.eventEmitter.emit(e,n.length>1?n:n[0])}get isConnected(){return this.status==="OPEN"}get isConnecting(){return this.status==="CONNECTING"}get isDisconnected(){return this.status==="CLOSED"}get isClosed(){return this.closed}getTerminalError(){return this.terminalError}get status(){return{0:"CONNECTING",1:"OPEN",2:"CLOSING",3:"CLOSED"}[this.rws.readyState]}async call(e,n={},i={}){if(this.terminalError)throw this.terminalError;let t=i.responseEvent||`${e}_${j()}_response`,o=`${t}_error`,a,s,c=()=>{a&&(this.rws.removeEventListener("close",a),this.rws.removeEventListener("error",a)),s&&(i.abortSignal?.removeEventListener("abort",s),s=void 0),this.eventEmitter.removeListener(t),this.eventEmitter.removeListener(o)},u=(h,g)=>{if(this.terminalError){g(this.terminalError);return}let k=new DOMException("Request aborted","AbortError");if(i.abortSignal?.aborted){g(k);return}if(i.abortSignal&&(s=()=>{g(k)},i.abortSignal.addEventListener("abort",s,{once:!0})),!this.isConnected||this.isClosed){g(new Dt(`Connection is not open while sending ${e}. Current status: ${this.status}`));return}this.listenOnce(t,w=>{this.log("debug","Message response received",{action:e}),h(w)}),this.listenOnce(o,w=>{this.log("error","Message error received",{action:e,error:w}),g(Ze("runtime",w))}),a=w=>{if(w.code===1008&&(w.reason||"").includes("rate limit")){g(new C(w.reason||"Rate limit exceeded",{source:"runtime",status:429,code:"RateLimited",cause:w}));return}let P=Ji(w);g(this.terminalError||new Dt(`Connection lost to the notebook during request: ${P}`,w))},this.rws.addEventListener("close",a),this.rws.addEventListener("error",a);try{this.rws.send(this.pack({action:e,data:n,errorEvent:o,responseEvent:t})),this.log("debug","Message sent",{action:e,data:n})}catch(w){this.log("error","Failed to send message",{action:e,error:w}),g(new Dt(`Failed to send runtime action ${e}.`,w))}},d=async()=>{if(i.abortSignal?.aborted)throw new DOMException("Request aborted","AbortError");if(await pe(this,Ie,Cl).call(this),i.abortSignal?.aborted)throw new DOMException("Request aborted","AbortError");let h=new Promise(u).finally(c);return i.timeout?lf(h,i.timeout).catch(g=>{throw g instanceof zt?_r.fromPromiseTimeoutError(g):g}).finally(c):h},m=i.retries===!1?0:i.retries??0;return this.sendWithRetry(async()=>await d(),m)}send(e,n={}){if(this.terminalError)throw this.terminalError;if(!this.isConnected||this.isClosed)return this.log("debug","Connection not available, dropping one-way message",{action:e}),!1;try{return this.rws.send(this.pack({action:e,data:n})),this.log("debug","One-way message sent",{action:e,data:n}),!0}catch(i){return this.log("error","Failed to send one-way message",{action:e,error:i}),!1}}pack(e){return new Blob([Pl(e)])}sendWithRetry(e,n){return xf(async(i,t)=>{try{return await e()}catch(o){if(o instanceof C||o instanceof Ge||o instanceof Be||o instanceof DOMException){this.log("debug","Non-retryable error, bailing",{error:o.message,attempt:t}),i(o);return}throw o instanceof _r&&(this.reconnect(),this.log("warn","Send operation timed out, connection reset",{attempt:t,timeout:o.time})),this.log("debug","Retrying send operation",{attempt:t,error:o instanceof Error?o.message:String(o)}),o}},{retries:n,onRetry:(i,t)=>{this.log("warn","Send operation retry",{attempt:t,maxRetries:n,error:i instanceof Error?i.message:String(i)})},minTimeout:1e3,factor:2,maxTimeout:3e4,randomize:!0})}invoke(e,n={},i={}){return i.responseEvent||(i.responseEvent=`${e}_${j()}`),this.call("invoke",{action:e,data:n},i)}reconnect(){if(this.terminalError)throw this.terminalError;if(this.closed)throw new Error("Cannot reconnect a closed transport. The transport has been permanently closed.");this.log("info","Reconnecting transport"),this.connectPromise=null,this.rws.reconnect()}disconnect(){this.closed||this.close()}terminate(e,n=4e3,i=e.message){this.terminalError=e,C.is(e,"NotebookUnavailable")&&this.eventEmitter.emit("transport.boot_error",{error:e,timestamp:Date.now()}),this.close(n,i)}close(e,n){if(!this.closed){this.log("info","Closing transport connection",{code:e,reason:n}),this.connectPromise=null,this.disposables.dispose();try{this.rws.close(e,n)}catch(i){this.log("error","Error closing WebSocket",{error:i instanceof Error?i.message:String(i)})}this.eventEmitter.emit("transport.closed",{code:e,reason:n,timestamp:Date.now()}),this.eventEmitter.removeListener("*"),this.closed=!0,this.log("info","Transport connection closed successfully")}}onDidConnect(e){this.rws.addEventListener("open",e);let n={dispose:()=>{this.rws.removeEventListener("open",e)}};return this.disposables.add(`connect_${j()}`,n),n}onDidClose(e){this.rws.addEventListener("close",e);let n={dispose:()=>{this.rws.removeEventListener("close",e)}};return this.disposables.add(`close_${j()}`,n),n}};Ie=new WeakSet,Cl=function(){return this.terminalError?Promise.reject(this.terminalError):this.isConnected?Promise.resolve():this.connectPromise?this.connectPromise:(this.connectPromise=new Promise((e,n)=>{if(this.isConnected){e(),pe(this,Ie,jl).call(this);return}let i,t=0,o=()=>{this.rws.removeEventListener("open",a),this.rws.removeEventListener("error",s),this.rws.removeEventListener("close",c),clearTimeout(i)},a=()=>{o(),this.connectPromise=null,e(),pe(this,Ie,jl).call(this)},s=u=>{t+=1,this.log("warn","WebSocket emitted an error while connecting; waiting for reconnect/open",{errorCount:t,error:Ji(u)})},c=u=>{let d=Ji(u);if(u.code===1008||u.code===4e3){o(),this.connectPromise=null,n(new Dt(`WebSocket connection failed: ${d}`,u));return}this.log("warn","WebSocket closed before opening; waiting for reconnect/open",{error:d})};this.rws.addEventListener("open",a),this.rws.addEventListener("error",s),this.rws.addEventListener("close",c),this.rws.readyState===3&&this.rws.reconnect(),i=setTimeout(()=>{o(),this.connectPromise=null,n(new Al(`WebSocket connection timeout after ${this.CONNECT_WAIT_TIMEOUT}ms`))},this.CONNECT_WAIT_TIMEOUT)}),this.connectPromise)},jl=function(){this.pingIntervalStarted||this.closed||(this.pingIntervalStarted=!0,this.disposables.add("pingInterval",()=>{let e=setInterval(async()=>{try{this.log("debug","Sending periodic ping"),await this.invoke("ping"),this.log("debug","Ping successful")}catch(n){this.log("error","Ping failed",{error:n instanceof Error?n.message:String(n)})}},this.PING_INTERVAL);return{dispose:()=>{clearInterval(e),this.pingIntervalStarted=!1}}}))};function Rb(r){if(r===null||typeof r!="object")return null;let e=Object.entries(r).filter(([n,i])=>Db.has(n)&&["string","number","boolean"].includes(typeof i));return e.length>0?Object.fromEntries(e):null}function Ob(r){let e=new URL(r);return e.search="",e.hash="",e.toString()}function Hi(r){return{all:r=r||new Map,on:function(e,n){var i=r.get(e);i?i.push(n):r.set(e,[n])},off:function(e,n){var i=r.get(e);i&&(n?i.splice(i.indexOf(n)>>>0,1):r.set(e,[]))},emit:function(e,n){var i=r.get(e);i&&i.slice().map(function(t){t(n)}),(i=r.get("*"))&&i.slice().map(function(t){t(e,n)})}}}var Ab=typeof Hi=="function"?Hi:Hi.default;function Cb(r){let e=Ab(r);return Object.assign(e,{once:(i,t)=>{let o=a=>{e.off(i,o),t(a)};return e.on(i,o),{dispose:()=>{e.off(i,o)}}}})}var Fr=class r{constructor(){this.emitter=Cb()}listen(e,n){let i=()=>{this.removeListener(e,n)};return this.emitter.on(e,n),{dispose:i}}emit(e,...n){this.emitter.emit(e,n[0])}once(e,n){return this.emitter.once(e,n)}static make(){return new r}static refresh(){return new r}removeListener(e,n){if(e===void 0){this.emitter.all.clear();return}this.emitter.off(e,n)}static createInstance(){return new r}inspect(){return this.emitter.all}};var Br=class{constructor(e,n){this.okra=e;this.client=n;this.targets=new Nl(e.data.id,n)}checkpoint(e,n,i="main",t=!1){return this.okra.invoke("git.checkpoint",{author:e,message:n,branch:i,allowEmpty:t})}checkout(e,n=!0){return this.okra.invoke("git.checkout",{branch:e,create:n})}log(e="main"){return this.okra.invoke("git.log",{ref:e})}diff(e){return this.okra.invoke("git.diff",this.normalizeRemoteInput(e))}merge(e){return this.okra.invoke("git.merge",this.normalizeRemoteInput(e))}conflicts(){return this.okra.invoke("git.conflicts",{})}abortMerge(){return this.okra.invoke("git.resolve",{action:"abort"})}continueMerge(e,n){return this.okra.invoke("git.resolve",{action:"continue",author:e,message:n})}review(){return this.okra.invoke("git.review",{})}stage(e={all:!0}){return this.okra.invoke("git.stage",e)}unstage(e={all:!0}){return this.okra.invoke("git.unstage",e)}revert(e){return this.okra.invoke("git.revert",e)}async credentials(){return(await this.client.post(`/notebook/${this.okra.data.id}/git/credentials`)).data}restore(e){return this.okra.invoke("git.restore",{ref:e})}status(){return this.okra.invoke("git.status",{})}normalizeRemoteInput(e){if(e.notebookId===void 0)return e;let n=e.notebookId.trim();if(!n)throw new Error("'notebookId' cannot be empty.");if(e.url?.trim())throw new Error("Pass either 'url' or 'notebookId', not both.");if(e.target?.trim())throw new Error("Pass either 'target' or 'notebookId', not both.");let{notebookId:i,...t}=e;return{...t,url:this.gitUrlForNotebook(n)}}gitUrlForNotebook(e){let n=new URL(this.okra.data.gitUrl);return n.username="",n.password="",n.pathname=`/${encodeURIComponent(e)}.git`,n.search="",n.hash="",n.toString()}},Nl=class{constructor(e,n){this.notebookId=e;this.client=n}async create(e){let n=await this.client.post(`/notebook/${this.notebookId}/git/targets`,Sf({...e}));return new Mr(n.data,this.notebookId,this.client)}async list(){return(await this.client.get(`/notebook/${this.notebookId}/git/targets`)).data.map(n=>new Mr(n,this.notebookId,this.client))}async get(e){let n=await this.client.get(`/notebook/${this.notebookId}/git/targets/${encodeURIComponent(jb(e))}`);return new Mr(n.data,this.notebookId,this.client)}},Mr=class r{constructor(e,n,i){this.data=e;this.notebookId=n;this.client=i}get id(){return this.data.id}async sync(e={}){let n=await this.client.post(`/notebook/${this.notebookId}/git/targets/${encodeURIComponent(this.id)}/sync`,Sf({...e}));return new r(n.data,this.notebookId,this.client)}};function jb(r){return typeof r=="string"?r:r.id}function Sf(r){return Object.fromEntries(Object.entries(r).filter(([,e])=>e!==void 0))}var qw=l.enum(["cloudflare-containers","ssh-server","laravel-cloud"]),Nb=l.enum(["pending","queued","building","deploying","healthy","failed","stopped","deleting","deleted","delete_failed"]),Hw=l.enum(["pending","queued","running","succeeded","failed","cancelled"]),Xw=l.enum(["created","ready","deleted"]),Yw=l.enum(["nano","small","medium","large","lite","basic","standard-1","standard-2"]),Qw=l.enum(["ENAM","WNAM","EEUR","WEUR","APAC","SAM","ME","OC","AFR"]),e_=l.enum(["eu","fedramp"]),t_=l.enum(["none","password","email","external"]),Lb=l.enum(["build","runtime"]),Zb=l.enum(["build","publish","runtime"]),Fb=l.preprocess(r=>Array.isArray(r)&&r.length===0?{}:r,l.record(l.string(),l.unknown())),If=l.object({id:l.union([l.number(),l.string()]).optional(),sequence:l.number(),type:l.string(),payload:Fb,createdAt:l.string().nullable()}).passthrough(),Ll=l.object({sequence:l.number(),stream:Lb,content:l.string(),createdAt:l.string().nullable()}).passthrough(),Pf=l.object({name:l.string(),status:l.enum(["running","completed","failed"]).optional(),data:l.record(l.string(),l.unknown()).optional()}).strict(),zf=l.object({stream:Zb,content:l.string()}).strict(),Zl=l.object({success:l.boolean(),publicationId:l.string(),url:l.string().url(),buildId:l.string(),releaseId:l.string(),status:Nb}).strict(),Mb=Pf.extend({type:l.literal("phase")}).strict(),Bb=zf.extend({type:l.literal("log")}).strict(),Gb=Zl.extend({type:l.literal("result")}).strict(),Wb=l.discriminatedUnion("type",[Mb,Bb,Gb]),Vb=l.object({message:l.string().optional()}).passthrough(),Ef=l.enum(["phase","log","done","result","error"]),Jb=l.object({event:l.literal("phase"),data:Pf}).strict(),Kb=l.object({event:l.literal("log"),data:zf}).strict(),qb=l.object({event:l.literal("done"),data:Zl}).strict(),Hb=l.object({event:l.literal("result"),data:Zl}).strict(),Xb=l.object({event:l.literal("error"),data:Vb}).strict(),Tf=l.discriminatedUnion("event",[Jb,Kb,qb,Hb,Xb]).transform(r=>{if(r.event==="error")throw new Error(r.data.message??"Publish failed");let e=r.event==="done"?"result":r.event;return Wb.parse({type:e,...r.data})});async function*Xi(r,e={}){if(r instanceof Response&&(!r.ok||!r.body))throw await r.body?.cancel().catch(()=>{}),new E(`Publishing stream is unavailable (HTTP ${r.status}).`);let i=(r instanceof Response?r.body:r).getReader(),t=new TextDecoder,o="",a="message",s=[],c=!1,u=!1;function d(){let h=a,g=s;if(a="message",s=[],!g.length||!Ef.safeParse(h).success)return null;let k=g.join(`
67
- `),w;try{w=JSON.parse(k)}catch{w=k}let P=Tf.parse({event:h,data:w});return P.type==="result"&&(u=!0),P}function m(h){if(h==="")return d();if(h.startsWith(":"))return null;let g=h.indexOf(":"),k=g<0?h:h.slice(0,g),w=g<0?"":h.slice(g+1);return w.startsWith(" ")&&(w=w.slice(1)),k==="event"&&(a=w),k==="data"&&s.push(w),null}try{for(;;){let{done:h,value:g}=await i.read();o+=h?t.decode():t.decode(g,{stream:!0});let k;for(;(k=/\r\n|\r|\n/.exec(o))&&!(!h&&k[0]==="\r"&&k.index===o.length-1);){let w=m(o.slice(0,k.index));o=o.slice(k.index+k[0].length),w&&(yield w)}if(h){if(c=!0,o){let P=m(o);P&&(yield P)}let w=d();if(w&&(yield w),e.requireResult!==!1&&!u)throw new E("Publish stream ended without result");return}}}finally{c||await i.cancel().catch(()=>{}),i.releaseLock()}}function Df(r,e={}){let n=r.getReader(),i=!1,t=!1,o,a;async function s(){i||(i=!0,e.signal?.removeEventListener("abort",a),n.releaseLock(),await e.onDispose?.())}function c(u){return o??(o=(async()=>{t=!0;try{await n.cancel(u)}finally{await s()}})())}return new Response(new ReadableStream({start(u){a=()=>{u.error(e.signal.reason),c(e.signal.reason).catch(()=>{})},e.signal?.aborted?a():e.signal?.addEventListener("abort",a,{once:!0})},async pull(u){try{let{done:d,value:m}=await n.read();if(t)return;d?(t=!0,await s(),u.close()):u.enqueue(m)}catch(d){if(t&&o)return;try{await c(d)}finally{u.error(d)}}},cancel:c},{highWaterMark:0}),{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform","X-Accel-Buffering":"no"}})}var Pe=class{constructor(e,n){this.initial=e;this.client=n;this.streamAbort=new AbortController;this.started=!1;this.completed=!1;this.finalError=null;this.finalResult=null;this.resultPromise=null;this.resolveResult=null;this.rejectResult=null;this.bufferedEvents=[];this.subscribers=new Set}async*events(){this.start();let e=this.subscribe();try{for await(let n of e)yield n}finally{this.subscribers.delete(e),e.close()}}result(){if(this.start(),!this.resultPromise)throw new E("Publication stream could not start.");return this.resultPromise}async publication(){return await this.result(),this.initial.refresh()}start(){if(this.started)return this;let e=this.initial.data.eventStreamUrl;if(!e)throw new E(`Publication ${this.initial.data.id} has no eventStreamUrl for SSE streaming`);return this.started=!0,this.resultPromise=new Promise((n,i)=>{this.resolveResult=n,this.rejectResult=i}),this.resultPromise.catch(()=>{}),this.consumeStream(e),this}dispose(){if(this.completed)return;let e=new DOMException("Stopped observing publication; deployment continues.","AbortError");this.started||(this.started=!0,this.resultPromise=Promise.reject(e),this.resultPromise.catch(()=>{})),this.streamAbort.abort(e),this.fail(e)}subscribe(){let e=new Fl;for(let n of this.bufferedEvents)e.push(n);return this.finalError?e.fail(this.finalError):this.completed?e.close():this.subscribers.add(e),e}async consumeStream(e){try{let n=await this.client.sse(e,this.streamAbort.signal);for await(let i of Xi(n))if(this.publish(i),i.type==="result"){let{type:t,...o}=i;this.finalResult=o,this.resolveResult?.(this.finalResult)}if(!this.finalResult)throw new E("Publish stream ended without result");this.closeSubscribers()}catch(n){this.fail(n instanceof Error?n:new E(String(n),n))}}publish(e){this.bufferedEvents.push(e);for(let n of this.subscribers)n.push(e)}closeSubscribers(){this.completed=!0;for(let e of this.subscribers)e.close();this.subscribers.clear()}fail(e){this.finalError=e,this.completed=!0,this.rejectResult?.(e);for(let n of this.subscribers)n.fail(e);this.subscribers.clear()}},Fl=class{constructor(){this.values=[];this.pending=[];this.closed=!1;this.error=null}push(e){if(this.closed)return;let n=this.pending.shift();if(n){n.resolve({done:!1,value:e});return}this.values.push(e)}close(){if(!this.closed){this.closed=!0;for(let e of this.pending.splice(0))e.resolve({done:!0,value:void 0})}}fail(e){if(!this.closed){this.error=e,this.closed=!0;for(let n of this.pending.splice(0))n.reject(e)}}async*[Symbol.asyncIterator](){for(;;){let e=await this.next();if(e.done)return;yield e.value}}next(){let e=this.values.shift();return e?Promise.resolve({done:!1,value:e}):this.error?Promise.reject(this.error):this.closed?Promise.resolve({done:!0,value:void 0}):new Promise((n,i)=>{this.pending.push({resolve:n,reject:i})})}};var ze=class{constructor(e,n="/publication-resources"){this.client=e;this.path=n}async inspect(e){return(await this.client.post(`/publication-resources/${encodeURIComponent(e)}/inspect`,{})).data}async list(e={}){let n=new URLSearchParams;for(let[t,o]of Object.entries(e))o!==void 0&&n.set(t,String(o));let i=n.size>0?`?${n.toString()}`:"";return this.client.get(`${this.path}${i}`)}};var Ut=class{constructor(e,n){this.client=e;this.publicationId=n}async list(){return(await this.client.get(this.path())).data}async create(e){return(await this.client.post(this.path(),{hostname:e})).data}async refresh(e){return(await this.client.post(`${this.path()}/${encodeURIComponent(e)}/refresh`)).data}async useAsApplicationUrl(e){return(await this.client.post(`${this.path()}/${encodeURIComponent(e)}/application-url`)).data}async delete(e){await this.client.delete(`${this.path()}/${encodeURIComponent(e)}`)}path(){return`/publications/${encodeURIComponent(this.publicationId)}/domains`}};var Rt=class{constructor(e){this.client=e;this.resources=new ze(e)}forProject(e){return new Ot(e,this.client)}async get(e){let n=await this.client.get(`/publications/${encodeURIComponent(e)}`);return new Ee(n.data,this.client)}},Ee=class r{constructor(e,n,i){this.data=e;this.client=n;this.notebookId=i;this.domains=new Ut(n,e.id)}async reconcileLaravelCloudResource(e){let n=await this.client.post(`/publications/${encodeURIComponent(this.data.id)}/laravel-cloud/reconcile`,{resourceId:e});return new r(n.data,this.client,this.notebookId)}async configureLaravelCloud(e){let n=await this.client.put(`/publications/${encodeURIComponent(this.data.id)}/laravel-cloud/setup`,{setup:e});return new r(n.data,this.client,this.notebookId)}async refresh(){let e=await this.client.get(`/publications/${encodeURIComponent(this.data.id)}`);return new r(e.data,this.client,this.notebookId)}follow(){return new Pe(this,this.client).start()}async stream(e){if(!this.data.eventStreamUrl)throw new E(`Publication ${this.data.id} has no eventStreamUrl for SSE streaming`);return this.client.sse(this.data.eventStreamUrl,e)}async destroy(e={}){let n=e.deleteResources?"?deleteResources=1":"";await this.client.delete(`/publications/${encodeURIComponent(this.data.id)}${n}`)}async wait(e={}){let n=e.intervalMs??1e3,i=e.timeoutMs??3e5,t=Date.now(),o=this;for(;!Yb(o.data.status);){if(Date.now()-t>i)throw new E(`Timed out waiting for publication ${this.data.id}`);await Qb(n),o=await o.refresh()}return o}async events(){return Ml(await this.client.stream(`/publications/${encodeURIComponent(this.data.id)}/events/stream`),If)}buildLogs(e=this.data.latestBuild?.id??""){return e===""?Promise.reject(new E("Publication has no latest build id")):this.client.stream(`/publications/${encodeURIComponent(this.data.id)}/builds/${encodeURIComponent(e)}/logs/stream`).then(n=>Ml(n,Ll))}async logSnapshot(e,n=50){let i=new URLSearchParams({stream:e,limit:String(n)});return(await this.client.get(`/publications/${encodeURIComponent(this.data.id)}/logs?${i}`)).data}async logs(){return Ml(await this.client.stream(`/publications/${encodeURIComponent(this.data.id)}/logs/stream`),Ll)}async setProtection(e){let n=await this.client.put(`/publications/${encodeURIComponent(this.data.id)}/protection`,e);return new r(n.data,this.client,this.notebookId)}async protection(){return(await this.client.get(`/publications/${encodeURIComponent(this.data.id)}/protection`)).data}async createProtectionSession(){return(await this.client.post(`/publications/${encodeURIComponent(this.data.id)}/protection/session`)).data}async disableProtection(){let e=await this.client.delete(`/publications/${encodeURIComponent(this.data.id)}/protection`);if(!e.data)throw new U("Protection response has no publication data.","InvalidResponse");return new r(e.data,this.client,this.notebookId)}};function Yb(r){return["healthy","failed","stopped","deleted","delete_failed"].includes(r)}function Qb(r){return new Promise(e=>setTimeout(e,r))}function Ml(r,e){let n=new TextDecoder,i="";return r.pipeThrough(new TransformStream({transform(t,o){i+=n.decode(t,{stream:!0});let a=i.split(`
67
+ `),w;try{w=JSON.parse(k)}catch{w=k}let P=Tf.parse({event:h,data:w});return P.type==="result"&&(u=!0),P}function m(h){if(h==="")return d();if(h.startsWith(":"))return null;let g=h.indexOf(":"),k=g<0?h:h.slice(0,g),w=g<0?"":h.slice(g+1);return w.startsWith(" ")&&(w=w.slice(1)),k==="event"&&(a=w),k==="data"&&s.push(w),null}try{for(;;){let{done:h,value:g}=await i.read();o+=h?t.decode():t.decode(g,{stream:!0});let k;for(;(k=/\r\n|\r|\n/.exec(o))&&!(!h&&k[0]==="\r"&&k.index===o.length-1);){let w=m(o.slice(0,k.index));o=o.slice(k.index+k[0].length),w&&(yield w)}if(h){if(c=!0,o){let P=m(o);P&&(yield P)}let w=d();if(w&&(yield w),e.requireResult!==!1&&!u)throw new E("Publish stream ended without result");return}}}finally{c||await i.cancel().catch(()=>{}),i.releaseLock()}}function Df(r,e={}){let n=r.getReader(),i=!1,t=!1,o,a;async function s(){i||(i=!0,e.signal?.removeEventListener("abort",a),n.releaseLock(),await e.onDispose?.())}function c(u){return o??(o=(async()=>{t=!0;try{await n.cancel(u)}finally{await s()}})())}return new Response(new ReadableStream({start(u){a=()=>{u.error(e.signal.reason),c(e.signal.reason).catch(()=>{})},e.signal?.aborted?a():e.signal?.addEventListener("abort",a,{once:!0})},async pull(u){try{let{done:d,value:m}=await n.read();if(t)return;d?(t=!0,await s(),u.close()):u.enqueue(m)}catch(d){if(t&&o)return;try{await c(d)}finally{u.error(d)}}},cancel:c},{highWaterMark:0}),{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform","X-Accel-Buffering":"no"}})}var Pe=class{constructor(e,n){this.initial=e;this.client=n;this.streamAbort=new AbortController;this.started=!1;this.completed=!1;this.finalError=null;this.finalResult=null;this.resultPromise=null;this.resolveResult=null;this.rejectResult=null;this.bufferedEvents=[];this.subscribers=new Set}async*events(){this.start();let e=this.subscribe();try{for await(let n of e)yield n}finally{this.subscribers.delete(e),e.close()}}result(){if(this.start(),!this.resultPromise)throw new E("Publication stream could not start.");return this.resultPromise}async publication(){return await this.result(),this.initial.refresh()}start(){if(this.started)return this;let e=this.initial.data.eventStreamUrl;if(!e)throw new E(`Publication ${this.initial.data.id} has no eventStreamUrl for SSE streaming`);return this.started=!0,this.resultPromise=new Promise((n,i)=>{this.resolveResult=n,this.rejectResult=i}),this.resultPromise.catch(()=>{}),this.consumeStream(e),this}dispose(){if(this.completed)return;let e=new DOMException("Stopped observing publication; deployment continues.","AbortError");this.started||(this.started=!0,this.resultPromise=Promise.reject(e),this.resultPromise.catch(()=>{})),this.streamAbort.abort(e),this.fail(e)}subscribe(){let e=new Fl;for(let n of this.bufferedEvents)e.push(n);return this.finalError?e.fail(this.finalError):this.completed?e.close():this.subscribers.add(e),e}async consumeStream(e){try{let n=await this.client.sse(e,this.streamAbort.signal);for await(let i of Xi(n))if(this.publish(i),i.type==="result"){let{type:t,...o}=i;this.finalResult=o,this.resolveResult?.(this.finalResult)}if(!this.finalResult)throw new E("Publish stream ended without result");this.closeSubscribers()}catch(n){this.fail(n instanceof Error?n:new E(String(n),n))}}publish(e){this.bufferedEvents.push(e);for(let n of this.subscribers)n.push(e)}closeSubscribers(){this.completed=!0;for(let e of this.subscribers)e.close();this.subscribers.clear()}fail(e){this.finalError=e,this.completed=!0,this.rejectResult?.(e);for(let n of this.subscribers)n.fail(e);this.subscribers.clear()}},Fl=class{constructor(){this.values=[];this.pending=[];this.closed=!1;this.error=null}push(e){if(this.closed)return;let n=this.pending.shift();if(n){n.resolve({done:!1,value:e});return}this.values.push(e)}close(){if(!this.closed){this.closed=!0;for(let e of this.pending.splice(0))e.resolve({done:!0,value:void 0})}}fail(e){if(!this.closed){this.error=e,this.closed=!0;for(let n of this.pending.splice(0))n.reject(e)}}async*[Symbol.asyncIterator](){for(;;){let e=await this.next();if(e.done)return;yield e.value}}next(){let e=this.values.shift();return e?Promise.resolve({done:!1,value:e}):this.error?Promise.reject(this.error):this.closed?Promise.resolve({done:!0,value:void 0}):new Promise((n,i)=>{this.pending.push({resolve:n,reject:i})})}};var ze=class{constructor(e,n="/publication-resources"){this.client=e;this.path=n}async inspect(e){return(await this.client.post(`/publication-resources/${encodeURIComponent(e)}/inspect`,{})).data}async list(e={}){let n=new URLSearchParams;for(let[t,o]of Object.entries(e))o!==void 0&&n.set(t,String(o));let i=n.size>0?`?${n.toString()}`:"";return this.client.get(`${this.path}${i}`)}};var Ut=class{constructor(e,n){this.client=e;this.publicationId=n}async list(){return(await this.client.get(this.path())).data}async create(e,n={}){return(await this.client.post(this.path(),{hostname:e,cloudflareStrategy:n.cloudflareStrategy,allowDowntime:n.allowDowntime})).data}async refresh(e){return(await this.client.post(`${this.path()}/${encodeURIComponent(e)}/refresh`)).data}async useAsApplicationUrl(e){return(await this.client.post(`${this.path()}/${encodeURIComponent(e)}/application-url`)).data}async delete(e){await this.client.delete(`${this.path()}/${encodeURIComponent(e)}`)}path(){return`/publications/${encodeURIComponent(this.publicationId)}/domains`}};var Rt=class{constructor(e){this.client=e;this.resources=new ze(e)}forProject(e){return new Ot(e,this.client)}async get(e){let n=await this.client.get(`/publications/${encodeURIComponent(e)}`);return new Ee(n.data,this.client)}},Ee=class r{constructor(e,n,i){this.data=e;this.client=n;this.notebookId=i;this.domains=new Ut(n,e.id)}async reconcileLaravelCloudResource(e){let n=await this.client.post(`/publications/${encodeURIComponent(this.data.id)}/laravel-cloud/reconcile`,{resourceId:e});return new r(n.data,this.client,this.notebookId)}async configureLaravelCloud(e){let n=await this.client.put(`/publications/${encodeURIComponent(this.data.id)}/laravel-cloud/setup`,{setup:e});return new r(n.data,this.client,this.notebookId)}async refresh(){let e=await this.client.get(`/publications/${encodeURIComponent(this.data.id)}`);return new r(e.data,this.client,this.notebookId)}follow(){return new Pe(this,this.client).start()}async stream(e){if(!this.data.eventStreamUrl)throw new E(`Publication ${this.data.id} has no eventStreamUrl for SSE streaming`);return this.client.sse(this.data.eventStreamUrl,e)}async destroy(e={}){let n=e.deleteResources?"?deleteResources=1":"";await this.client.delete(`/publications/${encodeURIComponent(this.data.id)}${n}`)}async wait(e={}){let n=e.intervalMs??1e3,i=e.timeoutMs??3e5,t=Date.now(),o=this;for(;!Yb(o.data.status);){if(Date.now()-t>i)throw new E(`Timed out waiting for publication ${this.data.id}`);await Qb(n),o=await o.refresh()}return o}async events(){return Ml(await this.client.stream(`/publications/${encodeURIComponent(this.data.id)}/events/stream`),If)}buildLogs(e=this.data.latestBuild?.id??""){return e===""?Promise.reject(new E("Publication has no latest build id")):this.client.stream(`/publications/${encodeURIComponent(this.data.id)}/builds/${encodeURIComponent(e)}/logs/stream`).then(n=>Ml(n,Ll))}async logSnapshot(e,n=50){let i=new URLSearchParams({stream:e,limit:String(n)});return(await this.client.get(`/publications/${encodeURIComponent(this.data.id)}/logs?${i}`)).data}async logs(){return Ml(await this.client.stream(`/publications/${encodeURIComponent(this.data.id)}/logs/stream`),Ll)}async setProtection(e){let n=await this.client.put(`/publications/${encodeURIComponent(this.data.id)}/protection`,e);return new r(n.data,this.client,this.notebookId)}async protection(){return(await this.client.get(`/publications/${encodeURIComponent(this.data.id)}/protection`)).data}async createProtectionSession(){return(await this.client.post(`/publications/${encodeURIComponent(this.data.id)}/protection/session`)).data}async disableProtection(){let e=await this.client.delete(`/publications/${encodeURIComponent(this.data.id)}/protection`);if(!e.data)throw new U("Protection response has no publication data.","InvalidResponse");return new r(e.data,this.client,this.notebookId)}};function Yb(r){return["healthy","failed","stopped","deleted","delete_failed"].includes(r)}function Qb(r){return new Promise(e=>setTimeout(e,r))}function Ml(r,e){let n=new TextDecoder,i="";return r.pipeThrough(new TransformStream({transform(t,o){i+=n.decode(t,{stream:!0});let a=i.split(`
68
68
  `);i=a.pop()??"";for(let s of a){let c=s.trim();c!==""&&o.enqueue(e.parse(JSON.parse(c)))}},flush(t){i+=n.decode();let o=i.trim();o!==""&&t.enqueue(e.parse(JSON.parse(o)))}}))}var Ot=class{constructor(e,n){this.projectId=e;this.client=n;this.resources=new ze(n,`${this.path}/publication/resources`)}get path(){return`/projects/${encodeURIComponent(this.projectId)}`}async current(){try{let e=await this.client.get(`${this.path}/publication`);return new Ee(e.data,this.client)}catch(e){if(C.is(e)&&e.status===404)return null;throw e}}async readiness(){return(await this.client.get(`${this.path}/publication/readiness`)).data}async configuration(){return(await this.client.get(`${this.path}/publication/configuration`)).data}async updateConfiguration(e){return(await this.client.patch(`${this.path}/publication/configuration`,e)).data}async prepare(e){return(await this.client.post(`${this.path}/publication/plan`,e)).data}async publish(e){let n=(await this.client.post(`${this.path}/publication`,e)).data;return"confirmationRequired"in n||this.startApplicationRuns(n),n}async application(e){return(await this.client.get(`${this.path}/publication/application/${encodeURIComponent(e)}`)).data}async retryApplication(e){let n=(await this.client.post(`${this.path}/publication/application/${encodeURIComponent(e)}/retry`,{})).data;return this.startApplicationRuns(n),n}async destroyApplication(e,n={}){let i=n.deleteResources?"?deleteResources=1":"";await this.client.delete(`${this.path}/publication/application/${encodeURIComponent(e)}${i}`)}startApplicationRuns(e){for(let n of e.apps)(e.selectedAppIds??[]).includes(n.appId)&&["pending","queued","building","deploying"].includes(n.publication.status)&&new Pe(new Ee(n.publication,this.client),this.client).start()}async catalog(e,n){let i=new URLSearchParams({provider:e});return n!==void 0&&i.set("serverId",n),(await this.client.get(`${this.path}/publication/catalog?${i}`)).data}};function Uf(r={},e=null){let n={...r},i={database:e?.databaseId,cache:e?.cacheId,storage:e?.storageId},t=["database","cache","storage"];for(let o of t){let a=i[o];r[o]?.mode==="create"&&a&&(n[o]={mode:"reuse",id:a})}return n}var Yi=class{constructor(e){this.client=e}async inspectInvitation(e,n){return(await this.client.post(`/platform/server-invitations/${encodeURIComponent(e)}/inspect`,{token:n})).data}async acceptInvitation(e,n){return(await this.client.post(`/platform/server-invitations/${encodeURIComponent(e)}/accept`,{token:n})).data}async declineInvitation(e,n){return(await this.client.post(`/platform/server-invitations/${encodeURIComponent(e)}/decline`,{token:n})).data}async list(e={}){let n=e.page===void 0?"":`?${new URLSearchParams({page:String(e.page)}).toString()}`;return this.client.get(`/servers${n}`)}async create(e){let n=await this.client.post("/servers",e);return new Qi(n.data,this.client)}async get(e){let n=await this.client.get(`/servers/${e}`);return new Qi(n.data,this.client)}},Qi=class{constructor(e,n){this.data=e;this.client=n}async updateAgent(e){return(await this.client.post(`/servers/${encodeURIComponent(this.data.id)}/agent/updates`,e)).data}async installation(e={}){let n=e.managedUpdates?"?managedUpdates=1":"";return(await this.client.get(`/servers/${encodeURIComponent(this.data.id)}/installation${n}`)).data}async members(e={}){let n=e.page===void 0?"":`?${new URLSearchParams({page:String(e.page)}).toString()}`;return this.client.get(`/servers/${encodeURIComponent(this.data.id)}/members${n}`)}async share(e){if(e.email!==void 0)return(await this.client.post(`/platform/servers/${encodeURIComponent(this.data.id)}/invitations`,{email:e.email,requestId:e.requestId??crypto.randomUUID()})).data;let n={organizationId:e.organizationId,requestId:e.requestId};return(await this.client.post(`/servers/${encodeURIComponent(this.data.id)}/members`,n)).data}async revokeAccess(e){await this.client.delete(`/servers/${encodeURIComponent(this.data.id)}/members/${encodeURIComponent(String(e))}`)}async invitations(e={}){let n=e.page===void 0?"":`?${new URLSearchParams({page:String(e.page)}).toString()}`;return this.client.get(`/platform/servers/${encodeURIComponent(this.data.id)}/invitations${n}`)}async cancelInvitation(e){let n=await this.client.delete(`/platform/servers/${encodeURIComponent(this.data.id)}/invitations/${encodeURIComponent(e)}`);if(n.data===void 0)throw new E("Missing invitation cancellation response.");return n.data}async resendInvitation(e){return(await this.client.post(`/platform/servers/${encodeURIComponent(this.data.id)}/invitations/${encodeURIComponent(e)}/resend`,{})).data}refresh(){return this.client.servers.get(this.data.id)}async delete(){await this.client.delete(`/servers/${this.data.id}`)}async waitReady(e){let n=e?.timeout??3e5,i=e?.interval??3e3,t=Date.now()+n;for(;Date.now()<t;){let o=await this.refresh();if(o.data.status==="connected")return o;if(o.data.status==="failed")throw new Error(`Server provisioning failed: ${o.data.id}`);await new Promise(a=>setTimeout(a,i))}throw new Error(`Server did not become ready within ${n}ms`)}};function At(r,e){return new Request(r,{...e,redirect:"manual"})}var Rf={"runtime.ready":{method:"GET",path:"/runtime"},"config.get":{method:"GET",path:"/runtime/config"},"config.update":{method:"PATCH",path:"/runtime/config"},"config.set-ports":{method:"PUT",path:"/runtime/config/ports"},"container.restart":{method:"POST",path:"/runtime/container/restart"},"container.stop":{method:"POST",path:"/runtime/container/stop"},"container.set-php":{method:"PUT",path:"/runtime/container/php"},"container.opened-ports":{method:"GET",path:"/runtime/container/ports"},"container.resolve-port":{method:"POST",path:"/runtime/container/ports/resolve"},"container.stats":{method:"GET",path:"/runtime/container/stats"},"terminal.list":{method:"GET",path:"/runtime/terminals"},"shell.exec":{method:"POST",path:"/runtime/executions"},"fs.readFile":{method:"GET",path:"/runtime/files/content"},"fs.writeFile":{method:"PUT",path:"/runtime/files/content"},"fs.download":{method:"POST",path:"/runtime/files/download"},"fs.createDirectory":{method:"PUT",path:"/runtime/directories"},"fs.readDirectory":{method:"POST",path:"/runtime/directories/read"},"fs.stat":{method:"POST",path:"/runtime/files/stat"},"fs.rename":{method:"POST",path:"/runtime/files/rename"},"fs.copy":{method:"POST",path:"/runtime/files/copy"},"fs.delete":{method:"DELETE",path:"/runtime/files"},"fs.tail":{method:"POST",path:"/runtime/files/tail"},"fs.find":{method:"POST",path:"/runtime/files/find"},"fs.textSearch":{method:"POST",path:"/runtime/files/search"},"fs.tree":{method:"POST",path:"/runtime/files/tree"},"service.list":{method:"GET",path:"/runtime/services"},"service.run":{method:"POST",path:"/runtime/services/run"},"service.stop":{method:"POST",path:"/runtime/services/stop"},"service.logs":{method:"POST",path:"/runtime/services/logs"},"composer.invoke":{method:"POST",path:"/runtime/composer/executions"},"composer.packages":{method:"GET",path:"/runtime/composer/packages"},"git.checkpoint":{method:"POST",path:"/runtime/git/checkpoints"},"git.checkout":{method:"POST",path:"/runtime/git/checkouts"},"git.log":{method:"POST",path:"/runtime/git/log"},"git.sync":{method:"POST",path:"/runtime/git/sync"},"git.diff":{method:"POST",path:"/runtime/git/diff"},"git.merge":{method:"POST",path:"/runtime/git/merge"},"git.conflicts":{method:"GET",path:"/runtime/git/conflicts"},"git.resolve":{method:"POST",path:"/runtime/git/conflicts/resolve"},"git.restore":{method:"POST",path:"/runtime/git/restore"},"git.status":{method:"GET",path:"/runtime/git/status"},"git.review":{method:"GET",path:"/runtime/git/review"},"git.stage":{method:"POST",path:"/runtime/git/stage"},"git.unstage":{method:"POST",path:"/runtime/git/unstage"},"git.revert":{method:"POST",path:"/runtime/git/revert"}},Gr=class{constructor(e,n,i){this.fetch=n;this.refresh=i;this.refreshPromise=null;this.streams=new Set;this.notebookId=e.id,this.configure(e.runtimeUrl)}configure(e){let n=new URL(e),i=n.searchParams.get("ticket")??"";if(i==="")throw new E("The notebook connection does not contain a runtime ticket.");this.ticket=i,n.protocol==="wss:"?n.protocol="https:":n.protocol==="ws:"&&(n.protocol="http:"),n.pathname=`/api/v1/notebooks/${encodeURIComponent(this.notebookId)}`,n.searchParams.delete("ticket"),n.hash="",this.actionUrl=n}ready(){return this.invokeRaw("runtime.ready",{},{})}supports(e){return e in Rf}invoke(e,n={},i={}){return this.invokeRaw(e,n??{},i)}send(){throw new E("Fire-and-forget actions require the realtime transport.")}dispose(){for(let e of this.streams)e.abort(new DOMException("Notebook disposed","AbortError"))}stream(e,n,i={}){let t=new AbortController;this.streams.add(t);let o=Cf({...i,abortSignal:t.signal}),a=()=>t.abort(i.abortSignal?.reason),s,c=!1,u=()=>{},d=()=>{this.streams.delete(t),i.abortSignal?.removeEventListener("abort",a),o.signal.removeEventListener("abort",u),o.dispose()},m=async h=>{let g=s;s=void 0,g!==void 0&&(await g.cancel(h).catch(()=>{}),g.releaseLock())};return new ReadableStream({start:h=>{u=()=>{c||(c=!0,d(),h.error(o.signal.reason),m(o.signal.reason))},o.signal.addEventListener("abort",u,{once:!0}),i.abortSignal?.addEventListener("abort",a,{once:!0}),i.abortSignal?.aborted&&a()},pull:async h=>{try{if(s===void 0){let k=await this.streamResponse(e,n,o.signal);if(c){await k.body?.cancel();return}if(k.body===null)throw new U("PHPSandbox runtime returned an empty download.","InvalidResponse",k);s=k.body.getReader()}let g=await s.read();if(c)return;g.done?(c=!0,d(),s.releaseLock(),s=void 0,h.close()):h.enqueue(g.value)}catch(g){c||(c=!0,t.abort(g),d(),await m(g),h.error(g))}},cancel:async h=>{c=!0,t.abort(h),d(),await m(h)}},{highWaterMark:0})}async streamResponse(e,n,i){for(let t=0;t<2;t+=1){i.throwIfAborted();let o=await Of(this.fetch,this.request(e,n,i));if(i.aborted&&(await o.body?.cancel(),i.throwIfAborted()),o.status===401&&t===0&&this.refresh!==void 0){await o.body?.cancel(),await this.refreshAuthorization();continue}if(!o.ok){let a=await Af(o);throw Ze("runtime",a.error,o)}if(!o.headers.get("content-type")?.toLowerCase().startsWith("application/zip"))throw await o.body?.cancel(),new U("PHPSandbox runtime returned an invalid download.","InvalidResponse",o);return o}throw new C("Notebook download could not be authorized.",{source:"runtime",status:401,code:"AuthenticationRequired"})}async invokeRaw(e,n,i){let t=Cf(i);try{for(let o=0;o<2;o+=1){let a=await Of(this.fetch,this.request(e,n,t.signal));if(a.status===401&&o===0&&this.refresh!==void 0){await this.refreshAuthorization();continue}let s=await Af(a);if(!a.ok||s.error!==void 0)throw Ze("runtime",s.error,a);return s.data}throw new C(`Runtime action ${e} could not be authorized.`,{source:"runtime",status:401,code:"AuthenticationRequired"})}finally{t.dispose()}}request(e,n,i){let t=Rf[e];if(t===void 0)throw new E(`Runtime action ${e} requires the realtime transport.`);let o=new URL(this.actionUrl);o.pathname+=t.path;let a={Accept:e==="fs.download"?"application/zip":"application/json, application/octet-stream",Authorization:`Bearer ${this.ticket}`},s=ey(e,n,o,a);return At(o,{method:t.method,headers:a,body:t.method==="GET"?void 0:s,signal:i})}async refreshAuthorization(){this.refreshPromise===null&&(this.refreshPromise=this.refresh().then(e=>this.configure(e)));try{await this.refreshPromise}finally{this.refreshPromise=null}}};async function Of(r,e){try{return await r(e)}catch(n){throw n instanceof DOMException&&n.name==="AbortError"?n:new U("Unable to reach the PHPSandbox runtime.","ConnectionFailed",n)}}async function Af(r){if(r.ok&&r.headers.get("content-type")?.toLowerCase().startsWith("application/octet-stream"))return{data:new Uint8Array(await r.arrayBuffer())};let e=await r.text();if(e===""){if(r.ok)throw new U("PHPSandbox runtime returned an empty response.","InvalidResponse",r);return{}}try{return JSON.parse(e)}catch(n){throw new U("PHPSandbox runtime returned an invalid JSON response.","InvalidResponse",n)}}function ey(r,e,n,i){let t=eo(e);if(r==="fs.readFile"){to(n,"path",t.path);let o=eo(t.lineRange);(o.lineStart!==void 0||o.lineEnd!==void 0)&&(to(n,"lineStart",o.lineStart),to(n,"lineEnd",o.lineEnd));return}if(r==="fs.writeFile"){to(n,"path",t.path);let o=eo(t.options);Bl(n,"overwrite",o.overwrite),Bl(n,"create",o.create),Bl(n,"unlock",o.unlock);let a=eo(o.atomic);if(typeof a.postfix=="string"&&a.postfix!==""&&n.searchParams.set("atomicPostfix",a.postfix),!ArrayBuffer.isView(t.contents))throw new TypeError("Runtime file contents must be binary data.");return i["Content-Type"]="application/octet-stream",Uint8Array.from(new Uint8Array(t.contents.buffer,t.contents.byteOffset,t.contents.byteLength)).buffer}return i["Content-Type"]="application/json",JSON.stringify(e)}function eo(r){return r!==null&&typeof r=="object"?r:{}}function to(r,e,n){if(typeof n!="string"&&typeof n!="number"||String(n)==="")throw new TypeError(`Runtime file ${e} is required.`);r.searchParams.set(e,String(n))}function Bl(r,e,n){r.searchParams.set(e,n===!0?"true":"false")}function Cf(r){if(r.timeout===void 0&&r.abortSignal===void 0)return{signal:new AbortController().signal,dispose:()=>{}};let e=new AbortController,n=()=>e.abort(r.abortSignal?.reason);r.abortSignal?.addEventListener("abort",n,{once:!0}),r.abortSignal?.aborted&&n();let i=r.timeout===void 0?void 0:setTimeout(()=>e.abort(),r.timeout);return{signal:e.signal,dispose:()=>{r.abortSignal?.removeEventListener("abort",n),i!==void 0&&clearTimeout(i)}}}var Wr=class{constructor(e,n){this.client=e;this.identifier=n}async configure(e){return(await this.client.put(this.path("/configuration"),e)).data}async configuration(){return(await this.client.get(this.path("/configuration"))).data}async submit(e,n={}){return(await this.client.post(this.path(),e,n)).data}async list(e={}){let n=new URLSearchParams;for(let[i,t]of Object.entries(e))t!==void 0&&n.set(i,String(t));return this.client.get(`${this.path()}${n.size===0?"":`?${n.toString()}`}`)}async get(e){return(await this.client.get(this.path(`/${encodeURIComponent(e)}`))).data}async update(e,n){return(await this.client.patch(this.path(`/${encodeURIComponent(e)}`),n)).data}path(e=""){return`/platform/projects/${encodeURIComponent(this.identifier)}/feedback${e}`}},Ct=class{constructor(e){this.client=e}forProject(e){return new Wr(this.client,e)}};var ro=class{constructor(e){this.client=e}async link(e){let n=await this.client.post("/integrations",e);return new We(n.data,this.client)}async list(){return(await this.client.get("/integrations")).data.map(n=>new We(n,this.client))}async get(e){let n=await this.client.get(`/integrations/${encodeURIComponent(no(e))}`);return new We(n.data,this.client)}},We=class r{constructor(e,n){this.data=e;this.client=n}get id(){return this.data.id}get provider(){return this.data.provider}get label(){return this.data.label}async update(e){let n=await this.client.patch(`/integrations/${encodeURIComponent(this.id)}`,e);return new r(n.data,this.client)}async unlink(){await this.client.delete(`/integrations/${encodeURIComponent(this.id)}`)}};function no(r){return typeof r=="string"?r:r.id}var io=class{constructor(e,n){this.notebookId=e;this.client=n}async attach(e){let n=await this.client.post(this.path(),{...e,integration:no(e.integration)});return new Vr(n.data,this.notebookId,this.client)}async list(){return(await this.client.get(this.path())).data.map(n=>new Vr(n,this.notebookId,this.client))}async get(e){let n=await this.client.get(this.bindingPath(e));return new Vr(n.data,this.notebookId,this.client)}path(){return`/notebook/${this.notebookId}/integrations`}bindingPath(e){return`${this.path()}/${encodeURIComponent(ty(e))}`}},Vr=class r{constructor(e,n,i){this.data=e;this.notebookId=n;this.client=i}get id(){return this.data.id}get integration(){return new We(this.data.integration,this.client)}get effects(){return this.data.effects}async update(e){let n=await this.client.patch(this.path(),{...e,integration:e.integration===void 0?void 0:no(e.integration)});return new r(n.data,this.notebookId,this.client)}async detach(){await this.client.delete(this.path())}path(){return`/notebook/${this.notebookId}/integrations/${encodeURIComponent(this.id)}`}};function ty(r){return typeof r=="string"?r:r.id}function ry(r){return Array.isArray(r)?r:Object.entries(r).map(([e,n])=>({name:e,...typeof n=="string"?{value:n}:n}))}var Wl=class{constructor(e){this.client=e}async list(e={}){return this.client.get(`/notebook${jf({page:e.page,per_page:e.perPage})}`)}async inspectImport(e){return(await this.client.post("/notebook/imports/inspect",e)).data}async create(e,n={}){let i=await this.client.post("/notebook",{template:e,...n});return new jt(i.data,this.client)}async get(e){let n=await this.client.get(`/notebook/${e}`);return new jt(n.data,this.client)}open(e){return new jt(e,this.client)}};function ny(r){let e=new URL(r),n=e.pathname.replace(/\/+$/,"");return e.pathname=n===""||n==="/"?"/v1/":`${n}/`,e.search="",e.hash="",e.toString()}var Jr=class{constructor(e,n="https://api.phpsandbox.io/v1",i={},t="realtime"){this.fetch=globalThis.fetch;this.publications=new Rt(this),this.notebook=new Wl(this),this.servers=new Yi(this),this.integrations=new ro(this),this.payments=new $r(this),this.customers=new xr(this),this.feedback=new Ct(this),this.options={...i},this.runtimeTransportValue=t,this.baseUrl=ny(n),i.fetch&&(this.fetch=i.fetch),this.headers={Accept:"application/json",Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}get runtimeTransport(){return this.runtimeTransportValue}get(e){return this.requireData(this.makeRequest("GET",e))}post(e,n,i={}){return this.requireData(this.makeRequest("POST",e,{body:n===void 0?void 0:JSON.stringify(n),headers:i.idempotencyKey===void 0?void 0:{"Idempotency-Key":i.idempotencyKey}}))}delete(e){return this.makeRequest("DELETE",e)}put(e,n){return this.requireData(this.makeRequest("PUT",e,{body:n===void 0?void 0:JSON.stringify(n)}))}patch(e,n){return this.requireData(this.makeRequest("PATCH",e,{body:n===void 0?void 0:JSON.stringify(n)}))}async stream(e){let n=await this.fetchResponse(At(new URL(e.replace(/^\//,""),this.baseUrl),{method:"GET",headers:this.headers}));if(!n.ok)throw await Gl(n);if(!n.body)throw new U("PHPSandbox API response body is not readable.","InvalidResponse",n);return n.body}async sse(e,n){let i=await this.fetchResponse(At(e,{method:"GET",headers:{...this.headers,Accept:"text/event-stream"},...n===void 0?{}:{signal:n}}));if(!i.ok)throw await Gl(i);if(!i.body)throw new U("PHPSandbox API SSE response body is not readable.","InvalidResponse",i);return i.body}async requireData(e){let n=await e;if(n.data===void 0)throw new U("PHPSandbox API returned no data for a data request.","InvalidResponse");return{...n,data:n.data}}async makeRequest(e,n,i){let t=new Headers(i?.headers);for(let[s,c]of Object.entries(this.headers))t.set(s,c);let o=await this.fetchResponse(At(new URL(n.replace(/^\//,""),this.baseUrl),{method:e,...i,headers:t}));if(!o.ok)throw await Gl(o,n.startsWith("/platform/")?"platform":"core");if(o.status===204)return{data:void 0};let a=await o.text();if(a==="")throw new U("PHPSandbox API returned an empty response.","InvalidResponse",o);try{let s=JSON.parse(a);if(s===null||typeof s!="object"||Array.isArray(s)||!Object.prototype.hasOwnProperty.call(s,"data"))throw new U("PHPSandbox API returned an invalid success response.","InvalidResponse",o);return s}catch(s){throw U.is(s)?s:new U("PHPSandbox API returned an invalid JSON response.","InvalidResponse",s)}}async fetchResponse(e){try{return await this.fetch(e)}catch(n){throw n instanceof DOMException&&n.name==="AbortError"?n:new U("Unable to reach the PHPSandbox API.","ConnectionFailed",n)}}};async function Gl(r,e="core"){let n=await r.text();try{return Ze(e,iy(n===""?void 0:JSON.parse(n)),r)}catch{return new U(`PHPSandbox API returned an invalid error response (HTTP ${r.status}).`,"InvalidResponse",r,{status:r.status,statusText:r.statusText,body:n})}}function iy(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)?r.error:void 0}var Vl=class r{constructor(e){this.client=e;this.notebook=e.notebook,this.publications=e.publications,this.servers=e.servers,this.integrations=e.integrations,this.payments=e.payments,this.customers=e.customers,this.feedback=e.feedback}async whoami(){let{data:e}=await this.client.get("/auth/whoami"),n=sf.safeParse(e);if(!n.success)throw new E("Invalid identity response.");return n.data}get runtimeTransport(){return this.client.runtimeTransport}static app(e={}){let{token:n,url:i,mode:t}=af(e);return new wr(new Jr(n,i,{},"rest"),n,t)}static realtime(e,n="https://api.phpsandbox.io/v1",i={}){return new r(new Jr(e,n,i))}static rest(e,n="https://api.phpsandbox.io/v1",i={}){return new r(new Jr(e,n,i,"rest"))}},Q,Kr,Jl,Xl=class Xl{constructor(e,n){this.data=e;this.client=n;Lt(this,Kr);this.downloadInvoker=null;this.initialized=!1;Lt(this,Q,null);this.disposables=[];let i=n.options.runtimeUrlProvider;if(this.emitter=Fr.createInstance(),n.runtimeTransport==="rest")this.socket=null,this.restInvoker=new Gr(e,n.options.fetch??globalThis.fetch,i===void 0?void 0:()=>i(e.id));else{this.restInvoker=null;let t=!0,o=i===void 0?e.runtimeUrl:async()=>t?(t=!1,e.runtimeUrl):i(e.id);this.socket=new qi(o,this.emitter,{debug:n.options.debug,webSocket:n.options.webSocket}),this.watchConnection(),Zt(this,Q,pe(this,Kr,Jl).call(this))}this.files=new ji(this,this.socket===null?null:t=>this.onDidConnect(t)),this.terminals=new Sr(this),this.lsp=new Ir(this),this.composer=new Er(this,n),this.runtime=new Rr(this),this.repl=new Or(this),this.shell=new zr(this),this.git=new Br(this,n),this.services=new Ar(this),this.config=new Cr(this),this.secrets=new Kl(n,this.data.id),this.integrations=new io(this.data.id,n),this.preview=new ql(n,this.data.id),this.mail=new Hl(n,this.data.id)}get runtimeTransport(){return this.client.runtimeTransport}async ready(){if(this.restInvoker!==null)return this.restInitialization();let e=this.realtimeSocket(),n=e.getTerminalError();if(n)throw n;return(async()=>(e.isConnected||await e.connect(),Te(this,Q)))()}async update(e){let n=await this.client.put(`/notebook/${this.data.id}`,e);return Object.assign(this.data,n.data),this.data}async fork(e={}){let n=await this.client.post(`/notebook/${this.data.id}/fork`,e);return new Xl(n.data,this.client)}run(e,n=[],i){return Array.isArray(n)?this.shell.run(e,n,i):this.shell.run(e,n)}exec(e,n=[],i){return Array.isArray(n)?this.run(e,n,i).wait():this.run(e,n).wait()}async destroy(){await this.client.delete(`/notebook/${this.data.id}`),this.socket?.terminate(new C("Notebook has been deleted.",{source:"runtime",status:503,code:"NotebookUnavailable",details:{id:this.data.id}}))}restart(){return this.invoke("container.restart")}stop(){return this.invoke("container.stop")}invoke(e,n={},i={}){return this.restInvoker!==null?(this.restInvoker.supports(String(e))&&this.restInitialization(),this.restInvoker.invoke(e,n||{},i)):this.realtimeSocket().invoke(e,n||{},i)}send(e,n={}){return this.restInvoker!==null?this.restInvoker.send():this.realtimeSocket().send(e,n||{})}stream(e,n={},i={}){let t=this.client.options.runtimeUrlProvider;return this.downloadInvoker??(this.downloadInvoker=this.restInvoker??new Gr(this.data,this.client.options.fetch??globalThis.fetch,t===void 0?void 0:()=>t(this.data.id))),this.downloadInvoker.stream(e,n,i)}listen(e,n){let i=this.emitter.listen(e,n);return this.disposables.push(i),i}dispose(){this.downloadInvoker?.dispose(),this.disposables.forEach(e=>e.dispose()),this.socket!==null&&!this.socket.isClosed&&this.socket.disconnect()}connected(){return this.waitForSocketConnection({rejectOnClose:!0})}waitForSocketConnection(e){let n=this.realtimeSocket(),i=n.getTerminalError();return i?Promise.reject(i):n.isConnected?Promise.resolve(this):new Promise((t,o)=>{let a=[],s=!1,c=()=>{for(let d of a)d.dispose();a.length=0},u=d=>{s||(s=!0,c(),d())};try{a.push(n.onDidConnect(()=>u(()=>t(this)))),e.rejectOnClose&&a.push(n.onDidClose(()=>u(()=>o(new Error("Connection closed"))))),a.push(n.onDidBootError(d=>u(()=>o(d))))}catch(d){u(()=>o(d))}})}watchConnection(){let e=this.realtimeSocket();e.onDidConnect(()=>{e.emit("okra.connected")}),e.onDidClose(()=>{e.emit("okra.disconnected"),this.initialized=!1}),e.onDidBootError(n=>{e.emit("okra.boot_error",n),e.emit("okra.disconnected"),this.initialized=!1})}onDidConnect(e){let n=this.realtimeSocket();n.removeListener("okra.connected",e);let i=n.listen("okra.connected",e);return this.disposables.push(i),i}onDidDisconnect(e){let n=this.realtimeSocket().listen("okra.disconnected",e);return this.disposables.push(n),n}onDidBootError(e){let n=this.realtimeSocket().listen("okra.boot_error",i=>{C.is(i,"NotebookUnavailable")&&e(i)});return this.disposables.push(n),n}restInitialization(){if(this.restInvoker===null)throw new E("This operation requires the REST transport.");return Te(this,Q)===null&&(Zt(this,Q,this.restInvoker.ready().then(e=>(this.initialized=e,this.emitter.emit("notebook.initialized",e),e))),Te(this,Q).catch(()=>{})),Te(this,Q)}onDidInitialize(e){return this.listen("notebook.initialized",e)}async reconnect(){let e=this.realtimeSocket(),n=this.waitForSocketConnection({rejectOnClose:!1});return e.reconnect(),this.initialized=!1,await n,Zt(this,Q,pe(this,Kr,Jl).call(this)),this.ready().then(()=>this)}realtimeSocket(){if(this.socket===null)throw new E("This operation requires the realtime transport.");return this.socket}};Q=new WeakMap,Kr=new WeakSet,Jl=function(){return Zt(this,Q,new Promise((e,n)=>{let i=this.onDidInitialize(o=>{if(t.dispose(),i.dispose(),this.initialized=o,o.type==="error"){n(new C(o.message,{source:"runtime",status:503,code:"NotebookInitializationFailed",details:o.data}));return}e(o)}),t=this.onDidBootError(o=>{i.dispose(),t.dispose(),n(o)})})),Te(this,Q).catch(()=>{}),Te(this,Q)};var jt=Xl,Kl=class{constructor(e,n){this.client=e;this.notebookId=n}async list(e){let n=new URLSearchParams;e?.environment&&n.set("environment",e.environment);let i=n.toString();return(await this.client.get(`/notebook/${this.notebookId}/secrets${i?`?${i}`:""}`)).data}async set(e,n){let i=typeof n=="string"?{name:e,value:n}:{name:e,...n};return(await this.client.put(`/notebook/${this.notebookId}/secrets`,i)).data}async setMany(e){return(await this.client.put(`/notebook/${this.notebookId}/secrets`,{secrets:ry(e)})).data}async delete(e,n){let i=new URLSearchParams;n?.environment&&i.set("environment",n.environment);let t=i.toString();await this.client.delete(`/notebook/${this.notebookId}/secrets/${encodeURIComponent(e)}${t?`?${t}`:""}`)}},ql=class{constructor(e,n){this.client=e;this.notebookId=n}async get(e){let n=e===void 0?"":`?${new URLSearchParams({url:e}).toString()}`;return(await this.client.get(`/notebook/${this.notebookId}/preview${n}`)).data}async configure(e){if(e.mode==="public"){await this.client.delete(`/notebook/${this.notebookId}/preview`);return}await this.client.put(`/notebook/${this.notebookId}/preview`,e)}async createSession(e){return(await this.client.post(`/notebook/${this.notebookId}/preview/session`,e)).data}async createHandoff(e){return(await this.client.post(`/notebook/${this.notebookId}/preview/handoff`,e)).data}},Hl=class{constructor(e,n){this.client=e;this.notebookId=n}async status(){return(await this.client.get(`/notebook/${this.notebookId}/mail`)).data}async capture(e){return(await this.client.post(`/notebook/${this.notebookId}/mails`,e)).data}async enable(){return(await this.client.put(`/notebook/${this.notebookId}/mail`)).data}async disable(){await this.client.delete(`/notebook/${this.notebookId}/mail`)}async list(e={}){return this.client.get(`/notebook/${this.notebookId}/mails${jf(e)}`)}async get(e){return(await this.client.get(`/notebook/${this.notebookId}/mails/${encodeURIComponent(e)}`)).data}async delete(e){await this.client.delete(`/notebook/${this.notebookId}/mails/${encodeURIComponent(e)}`)}};function jf(r){let e=new URLSearchParams;for(let[i,t]of Object.entries(r))(typeof t=="string"||typeof t=="number"||typeof t=="boolean")&&e.set(i,String(t));let n=e.toString();return n===""?"":`?${n}`}return Bf(oy);})();
69
69
  /*! Bundled license information:
70
70
 
@@ -1,11 +1,11 @@
1
1
  import type { Client } from '../index.js';
2
- import type { PublicationDomainData } from './types.js';
2
+ import type { PublicationDomainCreateOptions, PublicationDomainData } from './types.js';
3
3
  export declare class PublicationDomains {
4
4
  private readonly client;
5
5
  private readonly publicationId;
6
6
  constructor(client: Client, publicationId: string);
7
7
  list(): Promise<PublicationDomainData[]>;
8
- create(hostname: string): Promise<PublicationDomainData>;
8
+ create(hostname: string, options?: PublicationDomainCreateOptions): Promise<PublicationDomainData>;
9
9
  refresh(id: string): Promise<PublicationDomainData>;
10
10
  /** Sets production APP_URL. Publish again to apply it to the running app. */
11
11
  useAsApplicationUrl(id: string): Promise<{
@@ -6,8 +6,12 @@ export class PublicationDomains {
6
6
  async list() {
7
7
  return (await this.client.get(this.path())).data;
8
8
  }
9
- async create(hostname) {
10
- return (await this.client.post(this.path(), { hostname })).data;
9
+ async create(hostname, options = {}) {
10
+ return (await this.client.post(this.path(), {
11
+ hostname,
12
+ cloudflareStrategy: options.cloudflareStrategy,
13
+ allowDowntime: options.allowDowntime,
14
+ })).data;
11
15
  }
12
16
  async refresh(id) {
13
17
  return (await this.client.post(`${this.path()}/${encodeURIComponent(id)}/refresh`)).data;
@@ -471,6 +471,13 @@ export interface PublicationDnsRecord {
471
471
  value: string;
472
472
  purpose?: 'ownership' | 'certificate' | 'traffic';
473
473
  }
474
+ /** Optional Laravel Cloud DNS and domain transfer settings. */
475
+ export interface PublicationDomainCreateOptions {
476
+ /** Use Cloudflare DNS only, Cloudflare's proxy, or another DNS provider. */
477
+ cloudflareStrategy?: 'none' | 'dns' | 'dns_proxy';
478
+ /** Allow routing before verification. Defaults to false for an uninterrupted transfer. */
479
+ allowDowntime?: boolean;
480
+ }
474
481
  export interface PublicationDomainData {
475
482
  id: string;
476
483
  publicationId: string | null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phpsandbox/sdk",
3
- "version": "0.6.0-canary.7",
3
+ "version": "0.6.0-canary.8",
4
4
  "description": "The TypeScript SDK for PHPSandbox cloud development environments",
5
5
  "keywords": [
6
6
  "cloud",